mime.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * Copyright (c) 1999-2003 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This contains the functions necessary to detect and decode MIME
  9. * messages.
  10. *
  11. * $Id$
  12. */
  13. require_once(SM_PATH . 'functions/imap.php');
  14. require_once(SM_PATH . 'functions/attachment_common.php');
  15. /* --------------------------------------------------------------------------------- */
  16. /* MIME DECODING */
  17. /* --------------------------------------------------------------------------------- */
  18. /* This function gets the structure of a message and stores it in the "message" class.
  19. * It will return this object for use with all relevant header information and
  20. * fully parsed into the standard "message" object format.
  21. */
  22. function mime_structure ($bodystructure, $flags=array()) {
  23. /* Isolate the body structure and remove beginning and end parenthesis. */
  24. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  25. $read = trim(substr ($read, 0, -1));
  26. $i = 0;
  27. $msg = Message::parseStructure($read,$i);
  28. if (!is_object($msg)) {
  29. include_once(SM_PATH . 'functions/display_messages.php');
  30. global $color, $mailbox;
  31. /* removed urldecode because $_GET is auto urldecoded ??? */
  32. displayPageHeader( $color, $mailbox );
  33. echo "<BODY TEXT=\"$color[8]\" BGCOLOR=\"$color[4]\" LINK=\"$color[7]\" VLINK=\"$color[7]\" ALINK=\"$color[7]\">\n\n" .
  34. '<CENTER>';
  35. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  36. $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
  37. $errormessage .= '<table><tr><td>' . htmlspecialchars($read) . '</td></tr></table>';
  38. plain_error_message( $errormessage, $color );
  39. echo '</body></html>';
  40. exit;
  41. }
  42. if (count($flags)) {
  43. foreach ($flags as $flag) {
  44. $char = strtoupper($flag{1});
  45. switch ($char) {
  46. case 'S':
  47. if (strtolower($flag) == '\\seen') {
  48. $msg->is_seen = true;
  49. }
  50. break;
  51. case 'A':
  52. if (strtolower($flag) == '\\answered') {
  53. $msg->is_answered = true;
  54. }
  55. break;
  56. case 'D':
  57. if (strtolower($flag) == '\\deleted') {
  58. $msg->is_deleted = true;
  59. }
  60. break;
  61. case 'F':
  62. if (strtolower($flag) == '\\flagged') {
  63. $msg->is_flagged = true;
  64. }
  65. break;
  66. case 'M':
  67. if (strtolower($flag) == '$mdnsent') {
  68. $msg->is_mdnsent = true;
  69. }
  70. break;
  71. default:
  72. break;
  73. }
  74. }
  75. }
  76. // listEntities($msg);
  77. return $msg;
  78. }
  79. /* This starts the parsing of a particular structure. It is called recursively,
  80. * so it can be passed different structures. It returns an object of type
  81. * $message.
  82. * First, it checks to see if it is a multipart message. If it is, then it
  83. * handles that as it sees is necessary. If it is just a regular entity,
  84. * then it parses it and adds the necessary header information (by calling out
  85. * to mime_get_elements()
  86. */
  87. function mime_fetch_body($imap_stream, $id, $ent_id=1) {
  88. global $uid_support;
  89. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  90. * that it is the first one. That is usually the case anyway.
  91. */
  92. if (!$ent_id) {
  93. $cmd = "FETCH $id BODY[]";
  94. } else {
  95. $cmd = "FETCH $id BODY[$ent_id]";
  96. }
  97. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
  98. do {
  99. $topline = trim(array_shift($data));
  100. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  101. $wholemessage = implode('', $data);
  102. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  103. $ret = substr($wholemessage, 0, $regs[1]);
  104. /* There is some information in the content info header that could be important
  105. * in order to parse html messages. Let's get them here.
  106. */
  107. // if ($ret{0} == '<') {
  108. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
  109. // }
  110. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  111. $ret = $regs[1];
  112. } else {
  113. global $where, $what, $mailbox, $passed_id, $startMessage;
  114. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  115. if (isset($where) && isset($what)) {
  116. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  117. } else {
  118. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  119. }
  120. $par .= '&amp;response=' . urlencode($response) .
  121. '&amp;message=' . urlencode($message) .
  122. '&amp;topline=' . urlencode($topline);
  123. echo '<tt><br>' .
  124. '<table width="80%"><tr>' .
  125. '<tr><td colspan=2>' .
  126. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  127. '</td></tr>' .
  128. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  129. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  130. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  131. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  132. "</table><BR></tt></font><hr>";
  133. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
  134. array_shift($data);
  135. $wholemessage = implode('', $data);
  136. $ret = $wholemessage;
  137. }
  138. return $ret;
  139. }
  140. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
  141. global $uid_support;
  142. $sid = sqimap_session_id($uid_support);
  143. /* Don't kill the connection if the browser is over a dialup
  144. * and it would take over 30 seconds to download it.
  145. * Don´t call set_time_limit in safe mode.
  146. */
  147. if (!ini_get('safe_mode')) {
  148. set_time_limit(0);
  149. }
  150. if ($uid_support) {
  151. $sid_s = substr($sid,0,strpos($sid, ' '));
  152. } else {
  153. $sid_s = $sid;
  154. }
  155. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  156. echo decodeBody($body, $encoding);
  157. return;
  158. /*
  159. fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
  160. $cnt = 0;
  161. $continue = true;
  162. $read = fgets ($imap_stream,8192);
  163. // This could be bad -- if the section has sqimap_session_id() . ' OK'
  164. // or similar, it will kill the download.
  165. while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
  166. if (trim($read) == ')==') {
  167. $read1 = $read;
  168. $read = fgets ($imap_stream,4096);
  169. if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
  170. return;
  171. } else {
  172. echo decodeBody($read1, $encoding) .
  173. decodeBody($read, $encoding);
  174. }
  175. } else if ($cnt) {
  176. echo decodeBody($read, $encoding);
  177. }
  178. $read = fgets ($imap_stream,4096);
  179. $cnt++;
  180. // break;
  181. }
  182. */
  183. }
  184. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  185. /* This is here for debugging purposes. It will print out a list
  186. * of all the entity IDs that are in the $message object.
  187. */
  188. function listEntities ($message) {
  189. if ($message) {
  190. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
  191. for ($i = 0; isset($message->entities[$i]); $i++) {
  192. echo "$i : ";
  193. $msg = listEntities($message->entities[$i]);
  194. if ($msg) {
  195. echo "return: ";
  196. return $msg;
  197. }
  198. }
  199. }
  200. }
  201. function getPriorityStr($priority) {
  202. $priority_level = substr($priority,0,1);
  203. switch($priority_level) {
  204. /* Check for a higher then normal priority. */
  205. case '1':
  206. case '2':
  207. $priority_string = _("High");
  208. break;
  209. /* Check for a lower then normal priority. */
  210. case '4':
  211. case '5':
  212. $priority_string = _("Low");
  213. break;
  214. /* Check for a normal priority. */
  215. case '3':
  216. default:
  217. $priority_level = '3';
  218. $priority_string = _("Normal");
  219. break;
  220. }
  221. return $priority_string;
  222. }
  223. /* returns a $message object for a particular entity id */
  224. function getEntity ($message, $ent_id) {
  225. return $message->getEntity($ent_id);
  226. }
  227. /* translateText
  228. * Extracted from strings.php 23/03/2002
  229. */
  230. function translateText(&$body, $wrap_at, $charset) {
  231. global $where, $what; /* from searching */
  232. global $color; /* color theme */
  233. require_once(SM_PATH . 'functions/url_parser.php');
  234. $body_ary = explode("\n", $body);
  235. for ($i=0; $i < count($body_ary); $i++) {
  236. $line = $body_ary[$i];
  237. if (strlen($line) - 2 >= $wrap_at) {
  238. sqWordWrap($line, $wrap_at);
  239. }
  240. $line = charset_decode($charset, $line);
  241. $line = str_replace("\t", ' ', $line);
  242. parseUrl ($line);
  243. $quotes = 0;
  244. $pos = 0;
  245. $j = strlen($line);
  246. while ($pos < $j) {
  247. if ($line[$pos] == ' ') {
  248. $pos++;
  249. } else if (strpos($line, '&gt;', $pos) === $pos) {
  250. $pos += 4;
  251. $quotes++;
  252. } else {
  253. break;
  254. }
  255. }
  256. if ($quotes % 2) {
  257. if (!isset($color[13])) {
  258. $color[13] = '#800000';
  259. }
  260. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  261. } elseif ($quotes) {
  262. if (!isset($color[14])) {
  263. $color[14] = '#FF0000';
  264. }
  265. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  266. }
  267. $body_ary[$i] = $line;
  268. }
  269. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  270. }
  271. /* This returns a parsed string called $body. That string can then
  272. * be displayed as the actual message in the HTML. It contains
  273. * everything needed, including HTML Tags, Attachments at the
  274. * bottom, etc.
  275. */
  276. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
  277. /* This if statement checks for the entity to show as the
  278. * primary message. To add more of them, just put them in the
  279. * order that is their priority.
  280. */
  281. global $startMessage, $username, $key, $imapServerAddress, $imapPort,
  282. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
  283. global $languages, $squirrelmail_language;
  284. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  285. $view_unsafe_images = false;
  286. }
  287. $body = '';
  288. $urlmailbox = urlencode($mailbox);
  289. $body_message = getEntity($message, $ent_num);
  290. if (($body_message->header->type0 == 'text') ||
  291. ($body_message->header->type0 == 'rfc822')) {
  292. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  293. $body = decodeBody($body, $body_message->header->encoding);
  294. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  295. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  296. if (mb_detect_encoding($body) != 'ASCII') {
  297. $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
  298. }
  299. }
  300. $hookResults = do_hook("message_body", $body);
  301. $body = $hookResults[1];
  302. /* If there are other types that shouldn't be formatted, add
  303. * them here.
  304. */
  305. if ($body_message->header->type1 == 'html') {
  306. if ($show_html_default <> 1) {
  307. $entity_conv = array('&nbsp;' => ' ',
  308. '<p>' => "\n",
  309. '<br>' => "\n",
  310. '<P>' => "\n",
  311. '<BR>' => "\n",
  312. '&gt;' => '>',
  313. '&lt;' => '<');
  314. $body = strtr($body, $entity_conv);
  315. $body = strip_tags($body);
  316. $body = trim($body);
  317. translateText($body, $wrap_at,
  318. $body_message->header->getParameter('charset'));
  319. } else {
  320. $body = magicHTML($body, $id, $message, $mailbox);
  321. }
  322. } else {
  323. translateText($body, $wrap_at,
  324. $body_message->header->getParameter('charset'));
  325. }
  326. $link = 'read_body.php?passed_id=' . $id . '&amp;ent_id='.$ent_num.
  327. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  328. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  329. if (isset($passed_ent_id)) {
  330. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  331. }
  332. if ($view_unsafe_images) {
  333. $text = _("Hide Unsafe Images");
  334. } else {
  335. if (isset($has_unsafe_images) && $has_unsafe_images) {
  336. $link .= '&amp;view_unsafe_images=1';
  337. $text = _("View Unsafe Images");
  338. } else {
  339. $text = '';
  340. }
  341. }
  342. $body .= '<center><small><a href="'.$link.'">'.$text.
  343. '</a></small></center><br>' . "\n";
  344. }
  345. return $body;
  346. }
  347. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  348. global $where, $what, $startMessage, $color;
  349. static $ShownHTML = 0;
  350. $att_ar = $message->getAttachments($exclude_id);
  351. if (!count($att_ar)) return '';
  352. $attachments = '';
  353. $urlMailbox = urlencode($mailbox);
  354. foreach ($att_ar as $att) {
  355. $ent = $att->entity_id;
  356. $header = $att->header;
  357. $type0 = strtolower($header->type0);
  358. $type1 = strtolower($header->type1);
  359. $name = '';
  360. $links['download link']['text'] = _("download");
  361. $links['download link']['href'] =
  362. "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  363. $ImageURL = '';
  364. if ($type0 =='message' && $type1 == 'rfc822') {
  365. $default_page = '../src/read_body.php';
  366. $rfc822_header = $att->rfc822_header;
  367. $filename = $rfc822_header->subject;
  368. if (trim( $filename ) == '') {
  369. $filename = 'untitled-[' . $ent . ']' ;
  370. }
  371. $from_o = $rfc822_header->from;
  372. if (is_object($from_o)) {
  373. $from_name = $from_o->getAddress(false);
  374. } else {
  375. $from_name = _("Unknown sender");
  376. }
  377. $from_name = decodeHeader(($from_name));
  378. $description = $from_name;
  379. } else {
  380. $default_page = '../src/download.php';
  381. if (is_object($header->disposition)) {
  382. $filename = $header->disposition->getProperty('filename');
  383. if (trim($filename) == '') {
  384. $name = decodeHeader($header->disposition->getProperty('name'));
  385. if (trim($name) == '') {
  386. $name = $header->getParameter('name');
  387. if(trim($name) == '') {
  388. if (trim( $header->id ) == '') {
  389. $filename = 'untitled-[' . $ent . ']' ;
  390. } else {
  391. $filename = 'cid: ' . $header->id;
  392. }
  393. } else {
  394. $filename = $name;
  395. }
  396. } else {
  397. $filename = $name;
  398. }
  399. }
  400. } else {
  401. $filename = $header->getParameter('name');
  402. if (!trim($filename)) {
  403. if (trim( $header->id ) == '') {
  404. $filename = 'untitled-[' . $ent . ']' ;
  405. } else {
  406. $filename = 'cid: ' . $header->id;
  407. }
  408. }
  409. }
  410. if ($header->description) {
  411. $description = decodeHeader($header->description);
  412. } else {
  413. $description = '';
  414. }
  415. }
  416. $display_filename = $filename;
  417. if (isset($passed_ent_id)) {
  418. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  419. } else {
  420. $passed_ent_id_link = '';
  421. }
  422. $defaultlink = $default_page . "?startMessage=$startMessage"
  423. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  424. . '&amp;ent_id='.$ent.$passed_ent_id_link.'&amp;absolute_dl=true';
  425. if ($where && $what) {
  426. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  427. }
  428. /* This executes the attachment hook with a specific MIME-type.
  429. * If that doesn't have results, it tries if there's a rule
  430. * for a more generic type.
  431. */
  432. $hookresults = do_hook("attachment $type0/$type1", $links,
  433. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  434. $display_filename, $where, $what);
  435. if(count($hookresults[1]) <= 1) {
  436. $hookresults = do_hook("attachment $type0/*", $links,
  437. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  438. $display_filename, $where, $what);
  439. }
  440. $links = $hookresults[1];
  441. $defaultlink = $hookresults[6];
  442. $attachments .= '<TR><TD>' .
  443. '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A>&nbsp;</TD>' .
  444. '<TD><SMALL><b>' . show_readable_size($header->size) .
  445. '</b>&nbsp;&nbsp;</small></TD>' .
  446. "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
  447. '<TD><SMALL>';
  448. $attachments .= '<b>' . $description . '</b>';
  449. $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
  450. $skipspaces = 1;
  451. foreach ($links as $val) {
  452. if ($skipspaces) {
  453. $skipspaces = 0;
  454. } else {
  455. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  456. }
  457. $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
  458. }
  459. unset($links);
  460. $attachments .= "</TD></TR>\n";
  461. }
  462. return $attachments;
  463. }
  464. /* This function decodes the body depending on the encoding type. */
  465. function decodeBody($body, $encoding) {
  466. global $show_html_default;
  467. $body = str_replace("\r\n", "\n", $body);
  468. $encoding = strtolower($encoding);
  469. if ($encoding == 'quoted-printable' ||
  470. $encoding == 'quoted_printable') {
  471. $body = quoted_printable_decode($body);
  472. while (ereg("=\n", $body)) {
  473. $body = ereg_replace ("=\n", '', $body);
  474. }
  475. } else if ($encoding == 'base64') {
  476. $body = base64_decode($body);
  477. }
  478. // All other encodings are returned raw.
  479. return $body;
  480. }
  481. /*
  482. * This functions decode strings that is encoded according to
  483. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  484. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  485. */
  486. function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
  487. global $languages, $squirrelmail_language;
  488. if (is_array($string)) {
  489. $string = implode("\n", $string);
  490. }
  491. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  492. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  493. $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
  494. // Do we need to return at this point?
  495. // return $string;
  496. }
  497. $i = 0;
  498. $aString = explode(' ',$string);
  499. foreach ($aString as $chunk) {
  500. $encoded = false;
  501. $aString[$i] = '';
  502. while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  503. $aString[$i] .= $res[1];
  504. //echo "$chunk match ". $res[5] . "<br>";
  505. $encoding = ucfirst($res[3]);
  506. switch ($encoding)
  507. {
  508. case 'B':
  509. $replace = base64_decode($res[4]);
  510. $aString[$i] .= charset_decode($res[2],$replace);
  511. break;
  512. case 'Q':
  513. $replace = str_replace('_', ' ', $res[4]);
  514. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  515. $replace);
  516. /* Only encode into entities by default. Some places
  517. * don't need the encoding, like the compose form.
  518. */
  519. if ($utfencode) {
  520. $replace = charset_decode($res[2], $replace);
  521. } else {
  522. if ($htmlsave) {
  523. $replace = htmlspecialchars($replace);
  524. }
  525. }
  526. $aString[$i] .= $replace;
  527. break;
  528. default:
  529. break;
  530. }
  531. $chunk = $res[5];
  532. $encoded = true;
  533. }
  534. if (!$encoded && $htmlsave) {
  535. $aString[$i] = htmlspecialchars($chunk);
  536. } else {
  537. $aString[$i] .= $chunk;
  538. }
  539. ++$i;
  540. }
  541. return implode (' ',$aString);
  542. }
  543. /*
  544. * Encode a string according to RFC 1522 for use in headers if it
  545. * contains 8-bit characters or anything that looks like it should
  546. * be encoded.
  547. */
  548. function encodeHeader ($string) {
  549. global $default_charset, $languages, $squirrelmail_language;
  550. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  551. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  552. return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
  553. }
  554. if (strtolower($default_charset) == 'iso-8859-1') {
  555. $string = str_replace("\240",' ',$string);
  556. }
  557. // Encode only if the string contains 8-bit characters or =?
  558. $j = strlen($string);
  559. $max_l = 75 - strlen($default_charset) - 7;
  560. $aRet = array();
  561. $ret = '';
  562. $iEncStart = $enc_init = false;
  563. $cur_l = $iOffset = 0;
  564. for($i = 0; $i < $j; ++$i) {
  565. switch($string{$i})
  566. {
  567. case '=':
  568. case '<':
  569. case '>':
  570. case ',':
  571. case '?':
  572. case '_':
  573. if ($iEncStart === false) {
  574. $iEncStart = $i;
  575. }
  576. $cur_l+=3;
  577. if ($cur_l > ($max_l-2)) {
  578. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  579. $aRet[] = "=?$default_charset?Q?$ret?=";
  580. $iOffset = $i;
  581. $cur_l = 0;
  582. $ret = '';
  583. $iEncStart = false;
  584. } else {
  585. $ret .= sprintf("=%02X",ord($string{$i}));
  586. }
  587. break;
  588. case '(':
  589. case ')':
  590. if ($iEncStart !== false) {
  591. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  592. $aRet[] = "=?$default_charset?Q?$ret?=";
  593. $iOffset = $i;
  594. $cur_l = 0;
  595. $ret = '';
  596. $iEncStart = false;
  597. }
  598. break;
  599. case ' ':
  600. if ($iEncStart !== false) {
  601. $cur_l++;
  602. if ($cur_l > $max_l) {
  603. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  604. $aRet[] = "=?$default_charset?Q?$ret?=";
  605. $iOffset = $i;
  606. $cur_l = 0;
  607. $ret = '';
  608. $iEncStart = false;
  609. } else {
  610. $ret .= '_';
  611. }
  612. }
  613. break;
  614. default:
  615. $k = ord($string{$i});
  616. if ($k > 126) {
  617. if ($iEncStart === false) {
  618. $iEncStart = $i;
  619. }
  620. $cur_l += 3;
  621. if ($cur_l > ($max_l-2)) {
  622. if ($iEncStart !== false) {
  623. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  624. $aRet[] = "=?$default_charset?Q?$ret?=";
  625. } else {
  626. $aRet[] = substr($string,$iOffset,$i-$iOffset);
  627. }
  628. $cur_l = 3;
  629. $ret = '';
  630. $iOffset = $i;
  631. }
  632. $enc_init = true;
  633. $ret .= sprintf("=%02X", $k);
  634. } else {
  635. if ($iEncStart !== false) {
  636. $cur_l++;
  637. if ($cur_l > $max_l) {
  638. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  639. $aRet[] = "=?$default_charset?Q?$ret?=";
  640. $iEncStart = false;
  641. $iOffset = $i;
  642. $cur_l = 0;
  643. $ret = '';
  644. } else {
  645. $ret .= $string{$i};
  646. }
  647. }
  648. }
  649. break;
  650. }
  651. }
  652. if ($enc_init) {
  653. if ($iEncStart !== false) {
  654. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  655. $aRet[] = "=?$default_charset?Q?$ret?=";
  656. } else {
  657. $aRet[] = substr($string,$iOffset);
  658. }
  659. $string = implode('',$aRet);
  660. }
  661. return $string;
  662. }
  663. /* This function trys to locate the entity_id of a specific mime element */
  664. function find_ent_id($id, $message) {
  665. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  666. if ($message->entities[$i]->header->type0 == 'multipart') {
  667. $ret = find_ent_id($id, $message->entities[$i]);
  668. } else {
  669. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  670. // if (sq_check_save_extension($message->entities[$i])) {
  671. return $message->entities[$i]->entity_id;
  672. // }
  673. }
  674. }
  675. }
  676. return $ret;
  677. }
  678. function sq_check_save_extension($message) {
  679. $filename = $message->getFilename();
  680. $ext = substr($filename, strrpos($filename,'.')+1);
  681. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  682. return in_array($ext, $save_extensions);
  683. }
  684. /**
  685. ** HTMLFILTER ROUTINES
  686. */
  687. /**
  688. * This function returns the final tag out of the tag name, an array
  689. * of attributes, and the type of the tag. This function is called by
  690. * sq_sanitize internally.
  691. *
  692. * @param $tagname the name of the tag.
  693. * @param $attary the array of attributes and their values
  694. * @param $tagtype The type of the tag (see in comments).
  695. * @return a string with the final tag representation.
  696. */
  697. function sq_tagprint($tagname, $attary, $tagtype){
  698. $me = 'sq_tagprint';
  699. if ($tagtype == 2){
  700. $fulltag = '</' . $tagname . '>';
  701. } else {
  702. $fulltag = '<' . $tagname;
  703. if (is_array($attary) && sizeof($attary)){
  704. $atts = Array();
  705. while (list($attname, $attvalue) = each($attary)){
  706. array_push($atts, "$attname=$attvalue");
  707. }
  708. $fulltag .= ' ' . join(" ", $atts);
  709. }
  710. if ($tagtype == 3){
  711. $fulltag .= ' /';
  712. }
  713. $fulltag .= '>';
  714. }
  715. return $fulltag;
  716. }
  717. /**
  718. * A small helper function to use with array_walk. Modifies a by-ref
  719. * value and makes it lowercase.
  720. *
  721. * @param $val a value passed by-ref.
  722. * @return void since it modifies a by-ref value.
  723. */
  724. function sq_casenormalize(&$val){
  725. $val = strtolower($val);
  726. }
  727. /**
  728. * This function skips any whitespace from the current position within
  729. * a string and to the next non-whitespace value.
  730. *
  731. * @param $body the string
  732. * @param $offset the offset within the string where we should start
  733. * looking for the next non-whitespace character.
  734. * @return the location within the $body where the next
  735. * non-whitespace char is located.
  736. */
  737. function sq_skipspace($body, $offset){
  738. $me = 'sq_skipspace';
  739. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  740. if (sizeof($matches{1})){
  741. $count = strlen($matches{1});
  742. $offset += $count;
  743. }
  744. return $offset;
  745. }
  746. /**
  747. * This function looks for the next character within a string. It's
  748. * really just a glorified "strpos", except it catches if failures
  749. * nicely.
  750. *
  751. * @param $body The string to look for needle in.
  752. * @param $offset Start looking from this position.
  753. * @param $needle The character/string to look for.
  754. * @return location of the next occurance of the needle, or
  755. * strlen($body) if needle wasn't found.
  756. */
  757. function sq_findnxstr($body, $offset, $needle){
  758. $me = 'sq_findnxstr';
  759. $pos = strpos($body, $needle, $offset);
  760. if ($pos === FALSE){
  761. $pos = strlen($body);
  762. }
  763. return $pos;
  764. }
  765. /**
  766. * This function takes a PCRE-style regexp and tries to match it
  767. * within the string.
  768. *
  769. * @param $body The string to look for needle in.
  770. * @param $offset Start looking from here.
  771. * @param $reg A PCRE-style regex to match.
  772. * @return Returns a false if no matches found, or an array
  773. * with the following members:
  774. * - integer with the location of the match within $body
  775. * - string with whatever content between offset and the match
  776. * - string with whatever it is we matched
  777. */
  778. function sq_findnxreg($body, $offset, $reg){
  779. $me = 'sq_findnxreg';
  780. $matches = Array();
  781. $retarr = Array();
  782. preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
  783. if (!$matches{0}){
  784. $retarr = false;
  785. } else {
  786. $retarr{0} = $offset + strlen($matches{1});
  787. $retarr{1} = $matches{1};
  788. $retarr{2} = $matches{2};
  789. }
  790. return $retarr;
  791. }
  792. /**
  793. * This function looks for the next tag.
  794. *
  795. * @param $body String where to look for the next tag.
  796. * @param $offset Start looking from here.
  797. * @return false if no more tags exist in the body, or
  798. * an array with the following members:
  799. * - string with the name of the tag
  800. * - array with attributes and their values
  801. * - integer with tag type (1, 2, or 3)
  802. * - integer where the tag starts (starting "<")
  803. * - integer where the tag ends (ending ">")
  804. * first three members will be false, if the tag is invalid.
  805. */
  806. function sq_getnxtag($body, $offset){
  807. $me = 'sq_getnxtag';
  808. if ($offset > strlen($body)){
  809. return false;
  810. }
  811. $lt = sq_findnxstr($body, $offset, "<");
  812. if ($lt == strlen($body)){
  813. return false;
  814. }
  815. /**
  816. * We are here:
  817. * blah blah <tag attribute="value">
  818. * \---------^
  819. */
  820. $pos = sq_skipspace($body, $lt+1);
  821. if ($pos >= strlen($body)){
  822. return Array(false, false, false, $lt, strlen($body));
  823. }
  824. /**
  825. * There are 3 kinds of tags:
  826. * 1. Opening tag, e.g.:
  827. * <a href="blah">
  828. * 2. Closing tag, e.g.:
  829. * </a>
  830. * 3. XHTML-style content-less tag, e.g.:
  831. * <img src="blah"/>
  832. */
  833. $tagtype = false;
  834. switch (substr($body, $pos, 1)){
  835. case '/':
  836. $tagtype = 2;
  837. $pos++;
  838. break;
  839. case '!':
  840. /**
  841. * A comment or an SGML declaration.
  842. */
  843. if (substr($body, $pos+1, 2) == "--"){
  844. $gt = strpos($body, "-->", $pos);
  845. if ($gt === false){
  846. $gt = strlen($body);
  847. } else {
  848. $gt += 2;
  849. }
  850. return Array(false, false, false, $lt, $gt);
  851. } else {
  852. $gt = sq_findnxstr($body, $pos, ">");
  853. return Array(false, false, false, $lt, $gt);
  854. }
  855. break;
  856. default:
  857. /**
  858. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  859. * later.
  860. */
  861. $tagtype = 1;
  862. break;
  863. }
  864. $tag_start = $pos;
  865. $tagname = '';
  866. /**
  867. * Look for next [\W-_], which will indicate the end of the tag name.
  868. */
  869. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  870. if ($regary == false){
  871. return Array(false, false, false, $lt, strlen($body));
  872. }
  873. list($pos, $tagname, $match) = $regary;
  874. $tagname = strtolower($tagname);
  875. /**
  876. * $match can be either of these:
  877. * '>' indicating the end of the tag entirely.
  878. * '\s' indicating the end of the tag name.
  879. * '/' indicating that this is type-3 xhtml tag.
  880. *
  881. * Whatever else we find there indicates an invalid tag.
  882. */
  883. switch ($match){
  884. case '/':
  885. /**
  886. * This is an xhtml-style tag with a closing / at the
  887. * end, like so: <img src="blah"/>. Check if it's followed
  888. * by the closing bracket. If not, then this tag is invalid
  889. */
  890. if (substr($body, $pos, 2) == "/>"){
  891. $pos++;
  892. $tagtype = 3;
  893. } else {
  894. $gt = sq_findnxstr($body, $pos, ">");
  895. $retary = Array(false, false, false, $lt, $gt);
  896. return $retary;
  897. }
  898. case '>':
  899. return Array($tagname, false, $tagtype, $lt, $pos);
  900. break;
  901. default:
  902. /**
  903. * Check if it's whitespace
  904. */
  905. if (!preg_match('/\s/', $match)){
  906. /**
  907. * This is an invalid tag! Look for the next closing ">".
  908. */
  909. $gt = sq_findnxstr($body, $offset, ">");
  910. return Array(false, false, false, $lt, $gt);
  911. }
  912. break;
  913. }
  914. /**
  915. * At this point we're here:
  916. * <tagname attribute='blah'>
  917. * \-------^
  918. *
  919. * At this point we loop in order to find all attributes.
  920. */
  921. $attname = '';
  922. $atttype = false;
  923. $attary = Array();
  924. while ($pos <= strlen($body)){
  925. $pos = sq_skipspace($body, $pos);
  926. if ($pos == strlen($body)){
  927. /**
  928. * Non-closed tag.
  929. */
  930. return Array(false, false, false, $lt, $pos);
  931. }
  932. /**
  933. * See if we arrived at a ">" or "/>", which means that we reached
  934. * the end of the tag.
  935. */
  936. $matches = Array();
  937. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  938. /**
  939. * Yep. So we did.
  940. */
  941. $pos += strlen($matches{1});
  942. if ($matches{2} == "/>"){
  943. $tagtype = 3;
  944. $pos++;
  945. }
  946. return Array($tagname, $attary, $tagtype, $lt, $pos);
  947. }
  948. /**
  949. * There are several types of attributes, with optional
  950. * [:space:] between members.
  951. * Type 1:
  952. * attrname[:space:]=[:space:]'CDATA'
  953. * Type 2:
  954. * attrname[:space:]=[:space:]"CDATA"
  955. * Type 3:
  956. * attr[:space:]=[:space:]CDATA
  957. * Type 4:
  958. * attrname
  959. *
  960. * We leave types 1 and 2 the same, type 3 we check for
  961. * '"' and convert to "&quot" if needed, then wrap in
  962. * double quotes. Type 4 we convert into:
  963. * attrname="yes".
  964. */
  965. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  966. if ($regary == false){
  967. /**
  968. * Looks like body ended before the end of tag.
  969. */
  970. return Array(false, false, false, $lt, strlen($body));
  971. }
  972. list($pos, $attname, $match) = $regary;
  973. $attname = strtolower($attname);
  974. /**
  975. * We arrived at the end of attribute name. Several things possible
  976. * here:
  977. * '>' means the end of the tag and this is attribute type 4
  978. * '/' if followed by '>' means the same thing as above
  979. * '\s' means a lot of things -- look what it's followed by.
  980. * anything else means the attribute is invalid.
  981. */
  982. switch($match){
  983. case '/':
  984. /**
  985. * This is an xhtml-style tag with a closing / at the
  986. * end, like so: <img src="blah"/>. Check if it's followed
  987. * by the closing bracket. If not, then this tag is invalid
  988. */
  989. if (substr($body, $pos, 2) == "/>"){
  990. $pos++;
  991. $tagtype = 3;
  992. } else {
  993. $gt = sq_findnxstr($body, $pos, ">");
  994. $retary = Array(false, false, false, $lt, $gt);
  995. return $retary;
  996. }
  997. case '>':
  998. $attary{$attname} = '"yes"';
  999. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1000. break;
  1001. default:
  1002. /**
  1003. * Skip whitespace and see what we arrive at.
  1004. */
  1005. $pos = sq_skipspace($body, $pos);
  1006. $char = substr($body, $pos, 1);
  1007. /**
  1008. * Two things are valid here:
  1009. * '=' means this is attribute type 1 2 or 3.
  1010. * \w means this was attribute type 4.
  1011. * anything else we ignore and re-loop. End of tag and
  1012. * invalid stuff will be caught by our checks at the beginning
  1013. * of the loop.
  1014. */
  1015. if ($char == "="){
  1016. $pos++;
  1017. $pos = sq_skipspace($body, $pos);
  1018. /**
  1019. * Here are 3 possibilities:
  1020. * "'" attribute type 1
  1021. * '"' attribute type 2
  1022. * everything else is the content of tag type 3
  1023. */
  1024. $quot = substr($body, $pos, 1);
  1025. if ($quot == "'"){
  1026. $regary = sq_findnxreg($body, $pos+1, "\'");
  1027. if ($regary == false){
  1028. return Array(false, false, false, $lt, strlen($body));
  1029. }
  1030. list($pos, $attval, $match) = $regary;
  1031. $pos++;
  1032. $attary{$attname} = "'" . $attval . "'";
  1033. } else if ($quot == '"'){
  1034. $regary = sq_findnxreg($body, $pos+1, '\"');
  1035. if ($regary == false){
  1036. return Array(false, false, false, $lt, strlen($body));
  1037. }
  1038. list($pos, $attval, $match) = $regary;
  1039. $pos++;
  1040. $attary{$attname} = '"' . $attval . '"';
  1041. } else {
  1042. /**
  1043. * These are hateful. Look for \s, or >.
  1044. */
  1045. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1046. if ($regary == false){
  1047. return Array(false, false, false, $lt, strlen($body));
  1048. }
  1049. list($pos, $attval, $match) = $regary;
  1050. /**
  1051. * If it's ">" it will be caught at the top.
  1052. */
  1053. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1054. $attary{$attname} = '"' . $attval . '"';
  1055. }
  1056. } else if (preg_match("|[\w/>]|", $char)) {
  1057. /**
  1058. * That was attribute type 4.
  1059. */
  1060. $attary{$attname} = '"yes"';
  1061. } else {
  1062. /**
  1063. * An illegal character. Find next '>' and return.
  1064. */
  1065. $gt = sq_findnxstr($body, $pos, ">");
  1066. return Array(false, false, false, $lt, $gt);
  1067. }
  1068. break;
  1069. }
  1070. }
  1071. /**
  1072. * The fact that we got here indicates that the tag end was never
  1073. * found. Return invalid tag indication so it gets stripped.
  1074. */
  1075. return Array(false, false, false, $lt, strlen($body));
  1076. }
  1077. /**
  1078. * This function checks attribute values for entity-encoded values
  1079. * and returns them translated into 8-bit strings so we can run
  1080. * checks on them.
  1081. *
  1082. * @param $attvalue A string to run entity check against.
  1083. * @return Translated value.
  1084. */
  1085. function sq_deent($attvalue){
  1086. $me = 'sq_deent';
  1087. /**
  1088. * See if we have to run the checks first. All entities must start
  1089. * with "&".
  1090. */
  1091. if (strpos($attvalue, "&") === false){
  1092. return $attvalue;
  1093. }
  1094. /**
  1095. * Check named entities first.
  1096. */
  1097. $trans = get_html_translation_table(HTML_ENTITIES);
  1098. /**
  1099. * Leave &quot; in, as it can mess us up.
  1100. */
  1101. $trans = array_flip($trans);
  1102. unset($trans{"&quot;"});
  1103. while (list($ent, $val) = each($trans)){
  1104. $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
  1105. }
  1106. /**
  1107. * Now translate numbered entities from 1 to 255 if needed.
  1108. */
  1109. if (strpos($attvalue, "#") !== false){
  1110. $omit = Array(34, 39);
  1111. for ($asc=1; $asc<256; $asc++){
  1112. if (!in_array($asc, $omit)){
  1113. $chr = chr($asc);
  1114. $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
  1115. $attvalue);
  1116. $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
  1117. "$chr\\1", $attvalue);
  1118. }
  1119. }
  1120. }
  1121. return $attvalue;
  1122. }
  1123. /**
  1124. * This function runs various checks against the attributes.
  1125. *
  1126. * @param $tagname String with the name of the tag.
  1127. * @param $attary Array with all tag attributes.
  1128. * @param $rm_attnames See description for sq_sanitize
  1129. * @param $bad_attvals See description for sq_sanitize
  1130. * @param $add_attr_to_tag See description for sq_sanitize
  1131. * @param $message message object
  1132. * @param $id message id
  1133. * @return Array with modified attributes.
  1134. */
  1135. function sq_fixatts($tagname,
  1136. $attary,
  1137. $rm_attnames,
  1138. $bad_attvals,
  1139. $add_attr_to_tag,
  1140. $message,
  1141. $id,
  1142. $mailbox
  1143. ){
  1144. $me = 'sq_fixatts';
  1145. while (list($attname, $attvalue) = each($attary)){
  1146. /**
  1147. * See if this attribute should be removed.
  1148. */
  1149. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1150. if (preg_match($matchtag, $tagname)){
  1151. foreach ($matchattrs as $matchattr){
  1152. if (preg_match($matchattr, $attname)){
  1153. unset($attary{$attname});
  1154. continue;
  1155. }
  1156. }
  1157. }
  1158. }
  1159. /**
  1160. * Remove any entities.
  1161. */
  1162. $attvalue = sq_deent($attvalue);
  1163. /**
  1164. * Now let's run checks on the attvalues.
  1165. * I don't expect anyone to comprehend this. If you do,
  1166. * get in touch with me so I can drive to where you live and
  1167. * shake your hand personally. :)
  1168. */
  1169. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1170. if (preg_match($matchtag, $tagname)){
  1171. foreach ($matchattrs as $matchattr=>$valary){
  1172. if (preg_match($matchattr, $attname)){
  1173. /**
  1174. * There are two arrays in valary.
  1175. * First is matches.
  1176. * Second one is replacements
  1177. */
  1178. list($valmatch, $valrepl) = $valary;
  1179. $newvalue =
  1180. preg_replace($valmatch, $valrepl, $attvalue);
  1181. if ($newvalue != $attvalue){
  1182. $attary{$attname} = $newvalue;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Turn cid: urls into http-friendly ones.
  1190. */
  1191. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1192. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1193. }
  1194. }
  1195. /**
  1196. * See if we need to append any attributes to this tag.
  1197. */
  1198. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1199. if (preg_match($matchtag, $tagname)){
  1200. $attary = array_merge($attary, $addattary);
  1201. }
  1202. }
  1203. return $attary;
  1204. }
  1205. /**
  1206. * This function edits the style definition to make them friendly and
  1207. * usable in squirrelmail.
  1208. *
  1209. * @param $message the message object
  1210. * @param $id the message id
  1211. * @param $content a string with whatever is between <style> and </style>
  1212. * @return a string with edited content.
  1213. */
  1214. function sq_fixstyle($message, $id, $content){
  1215. global $view_unsafe_images;
  1216. $me = 'sq_fixstyle';
  1217. /**
  1218. * First look for general BODY style declaration, which would be
  1219. * like so:
  1220. * body {background: blah-blah}
  1221. * and change it to .bodyclass so we can just assign it to a <div>
  1222. */
  1223. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1224. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1225. /**
  1226. * Fix url('blah') declarations.
  1227. */
  1228. $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
  1229. "url(\\1$secremoveimg\\2)", $content);
  1230. /**
  1231. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1232. * is false.
  1233. */
  1234. if (!$view_unsafe_images){
  1235. $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
  1236. "url(\\1$secremoveimg\\2)", $content);
  1237. }
  1238. /**
  1239. * Fix urls that refer to cid:
  1240. */
  1241. while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
  1242. $matches)){
  1243. $cidurl = $matches{1};
  1244. $httpurl = sq_cid2http($message, $id, $cidurl);
  1245. $content = preg_replace("|url\($cidurl\)|si",
  1246. "url($httpurl)", $content);
  1247. }
  1248. /**
  1249. * Fix stupid css declarations which lead to vulnerabilities
  1250. * in IE.
  1251. */
  1252. $match = Array('/expression/i',
  1253. '/behaviou*r/i',
  1254. '/binding/i');
  1255. $replace = Array('idiocy', 'idiocy', 'idiocy');
  1256. $content = preg_replace($match, $replace, $content);
  1257. return $content;
  1258. }
  1259. /**
  1260. * This function converts cid: url's into the ones that can be viewed in
  1261. * the browser.
  1262. *
  1263. * @param $message the message object
  1264. * @param $id the message id
  1265. * @param $cidurl the cid: url.
  1266. * @return a string with a http-friendly url
  1267. */
  1268. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1269. /**
  1270. * Get rid of quotes.
  1271. */
  1272. $quotchar = substr($cidurl, 0, 1);
  1273. $cidurl = str_replace($quotchar, "", $cidurl);
  1274. $cidurl = substr(trim($cidurl), 4);
  1275. $linkurl = find_ent_id($cidurl, $message);
  1276. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1277. unsave link image */
  1278. $httpurl = '';
  1279. if ($linkurl) {
  1280. $httpurl = $quotchar . '../src/download.php?absolute_dl=true&amp;' .
  1281. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1282. '&amp;ent_id=' . $linkurl . $quotchar;
  1283. }
  1284. return $httpurl;
  1285. }
  1286. /**
  1287. * This function changes the <body> tag into a <div> tag since we
  1288. * can't really have a body-within-body.
  1289. *
  1290. * @param $attary an array of attributes and values of <body>
  1291. * @return a modified array of attributes to be set for <div>
  1292. */
  1293. function sq_body2div($attary){
  1294. $me = 'sq_body2div';
  1295. $divattary = Array('class' => "'bodyclass'");
  1296. $bgcolor = '#ffffff';
  1297. $text = '#000000';
  1298. $styledef = '';
  1299. if (is_array($attary) && sizeof($attary) > 0){
  1300. foreach ($attary as $attname=>$attvalue){
  1301. $quotchar = substr($attvalue, 0, 1);
  1302. $attvalue = str_replace($quotchar, "", $attvalue);
  1303. switch ($attname){
  1304. case 'background':
  1305. $styledef .= "background-image: url('$attvalue'); ";
  1306. break;
  1307. case 'bgcolor':
  1308. $styledef .= "background-color: $attvalue; ";
  1309. break;
  1310. case 'text':
  1311. $styledef .= "color: $attvalue; ";
  1312. break;
  1313. }
  1314. }
  1315. if (strlen($styledef) > 0){
  1316. $divattary{"style"} = "\"$styledef\"";
  1317. }
  1318. }
  1319. return $divattary;
  1320. }
  1321. /**
  1322. * This is the main function and the one you should actually be calling.
  1323. * There are several variables you should be aware of an which need
  1324. * special description.
  1325. *
  1326. * Since the description is quite lengthy, see it here:
  1327. * http://www.mricon.com/html/phpfilter.html
  1328. *
  1329. * @param $body the string with HTML you wish to filter
  1330. * @param $tag_list see description above
  1331. * @param $rm_tags_with_content see description above
  1332. * @param $self_closing_tags see description above
  1333. * @param $force_tag_closing see description above
  1334. * @param $rm_attnames see description above
  1335. * @param $bad_attvals see description above
  1336. * @param $add_attr_to_tag see description above
  1337. * @param $message message object
  1338. * @param $id message id
  1339. * @return sanitized html safe to show on your pages.
  1340. */
  1341. function sq_sanitize($body,
  1342. $tag_list,
  1343. $rm_tags_with_content,
  1344. $self_closing_tags,
  1345. $force_tag_closing,
  1346. $rm_attnames,
  1347. $bad_attvals,
  1348. $add_attr_to_tag,
  1349. $message,
  1350. $id,
  1351. $mailbox
  1352. ){
  1353. $me = 'sq_sanitize';
  1354. /**
  1355. * Normalize rm_tags and rm_tags_with_content.
  1356. */
  1357. @array_walk($rm_tags, 'sq_casenormalize');
  1358. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1359. @array_walk($self_closing_tags, 'sq_casenormalize');
  1360. /**
  1361. * See if tag_list is of tags to remove or tags to allow.
  1362. * false means remove these tags
  1363. * true means allow these tags
  1364. */
  1365. $rm_tags = array_shift($tag_list);
  1366. $curpos = 0;
  1367. $open_tags = Array();
  1368. $trusted = "<!-- begin sanitized html -->\n";
  1369. $skip_content = false;
  1370. /**
  1371. * Take care of netscape's stupid javascript entities like
  1372. * &{alert('boo')};
  1373. */
  1374. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1375. while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
  1376. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1377. $free_content = substr($body, $curpos, $lt-$curpos);
  1378. /**
  1379. * Take care of <style>
  1380. */
  1381. if ($tagname == "style" && $tagtype == 2){
  1382. /**
  1383. * This is a closing </style>. Edit the
  1384. * content before we apply it.
  1385. */
  1386. $free_content = sq_fixstyle($message, $id, $free_content);
  1387. }
  1388. if ($skip_content == false){
  1389. $trusted .= $free_content;
  1390. }
  1391. if ($tagname != FALSE){
  1392. if ($tagtype == 2){
  1393. if ($skip_content == $tagname){
  1394. /**
  1395. * Got to the end of tag we needed to remove.
  1396. */
  1397. $tagname = false;
  1398. $skip_content = false;
  1399. } else {
  1400. if ($skip_content == false){
  1401. if ($tagname == "body"){
  1402. $tagname = "div";
  1403. } else {
  1404. if (isset($open_tags{$tagname}) &&
  1405. $open_tags{$tagname} > 0){
  1406. $open_tags{$tagname}--;
  1407. } else {
  1408. $tagname = false;
  1409. }
  1410. }
  1411. }
  1412. }
  1413. } else {
  1414. /**
  1415. * $rm_tags_with_content
  1416. */
  1417. if ($skip_content == false){
  1418. /**
  1419. * See if this is a self-closing type and change
  1420. * tagtype appropriately.
  1421. */
  1422. if ($tagtype == 1
  1423. && in_array($tagname, $self_closing_tags)){
  1424. $tagtype=3;
  1425. }
  1426. /**
  1427. * See if we should skip this tag and any content
  1428. * inside it.
  1429. */
  1430. if ($tagtype == 1 &&
  1431. in_array($tagname, $rm_tags_with_content)){
  1432. $skip_content = $tagname;
  1433. } else {
  1434. if (($rm_tags == false
  1435. && in_array($tagname, $tag_list)) ||
  1436. ($rm_tags == true &&
  1437. !in_array($tagname, $tag_list))){
  1438. $tagname = false;
  1439. } else {
  1440. if ($tagtype == 1){
  1441. if (isset($open_tags{$tagname})){
  1442. $open_tags{$tagname}++;
  1443. } else {
  1444. $open_tags{$tagname}=1;
  1445. }
  1446. }
  1447. /**
  1448. * This is where we run other checks.
  1449. */
  1450. if (is_array($attary) && sizeof($attary) > 0){
  1451. $attary = sq_fixatts($tagname,
  1452. $attary,
  1453. $rm_attnames,
  1454. $bad_attvals,
  1455. $add_attr_to_tag,
  1456. $message,
  1457. $id,
  1458. $mailbox
  1459. );
  1460. }
  1461. /**
  1462. * Convert body into div.
  1463. */
  1464. if ($tagname == "body"){
  1465. $tagname = "div";
  1466. $attary = sq_body2div($attary, $message, $id);
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. if ($tagname != false && $skip_content == false){
  1473. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1474. }
  1475. }
  1476. $curpos = $gt+1;
  1477. }
  1478. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1479. if ($force_tag_closing == true){
  1480. foreach ($open_tags as $tagname=>$opentimes){
  1481. while ($opentimes > 0){
  1482. $trusted .= '</' . $tagname . '>';
  1483. $opentimes--;
  1484. }
  1485. }
  1486. $trusted .= "\n";
  1487. }
  1488. $trusted .= "<!-- end sanitized html -->\n";
  1489. return $trusted;
  1490. }
  1491. /**
  1492. * This is a wrapper function to call html sanitizing routines.
  1493. *
  1494. * @param $body the body of the message
  1495. * @param $id the id of the message
  1496. * @return a string with html safe to display in the browser.
  1497. */
  1498. function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
  1499. global $attachment_common_show_images, $view_unsafe_images,
  1500. $has_unsafe_images;
  1501. /**
  1502. * Don't display attached images in HTML mode.
  1503. */
  1504. $attachment_common_show_images = false;
  1505. $tag_list = Array(
  1506. false,
  1507. "object",
  1508. "meta",
  1509. "html",
  1510. "head",
  1511. "base",
  1512. "link",
  1513. "frame",
  1514. "iframe"
  1515. );
  1516. $rm_tags_with_content = Array(
  1517. "script",
  1518. "applet",
  1519. "embed",
  1520. "title"
  1521. );
  1522. $self_closing_tags = Array(
  1523. "img",
  1524. "br",
  1525. "hr",
  1526. "input"
  1527. );
  1528. $force_tag_closing = false;
  1529. $rm_attnames = Array(
  1530. "/.*/" =>
  1531. Array(
  1532. "/target/i",
  1533. "/^on.*/i",
  1534. "/^dynsrc/i",
  1535. "/^data.*/i",
  1536. "/^lowsrc.*/i"
  1537. )
  1538. );
  1539. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1540. $bad_attvals = Array(
  1541. "/.*/" =>
  1542. Array(
  1543. "/^src|background/i" =>
  1544. Array(
  1545. Array(
  1546. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1547. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1548. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1549. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1550. ),
  1551. Array(
  1552. "\\1$secremoveimg\\2",
  1553. "\\1$secremoveimg\\2",
  1554. "\\1$secremoveimg\\2",
  1555. "\\1$secremoveimg\\2"
  1556. )
  1557. ),
  1558. "/^href|action/i" =>
  1559. Array(
  1560. Array(
  1561. "|^([\'\"])\s*\.\./.*([\'\"])|si",
  1562. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1563. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1564. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1565. ),
  1566. Array(
  1567. "\\1#\\2",
  1568. "\\1#\\2",
  1569. "\\1#\\2",
  1570. "\\1#\\2"
  1571. )
  1572. ),
  1573. "/^style/i" =>
  1574. Array(
  1575. Array(
  1576. "/expression/i",
  1577. "/binding/i",
  1578. "/behaviou*r/i",
  1579. "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
  1580. "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
  1581. "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
  1582. "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
  1583. ),
  1584. Array(
  1585. "idiocy",
  1586. "idiocy",
  1587. "idiocy",
  1588. "url(\\1#\\2)",
  1589. "url(\\1#\\2)",
  1590. "url(\\1#\\2)",
  1591. "url(\\1#\\2)"
  1592. )
  1593. )
  1594. )
  1595. );
  1596. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  1597. $view_unsafe_images = false;
  1598. }
  1599. if (!$view_unsafe_images){
  1600. /**
  1601. * Remove any references to http/https if view_unsafe_images set
  1602. * to false.
  1603. */
  1604. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  1605. '/^([\'\"])\s*https*:.*([\'\"])/si');
  1606. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  1607. "\\1$secremoveimg\\2");
  1608. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  1609. '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
  1610. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  1611. "url(\\1$secremoveimg\\2)");
  1612. }
  1613. $add_attr_to_tag = Array(
  1614. "/^a$/i" => Array('target'=>'"_new"')
  1615. );
  1616. $trusted = sq_sanitize($body,
  1617. $tag_list,
  1618. $rm_tags_with_content,
  1619. $self_closing_tags,
  1620. $force_tag_closing,
  1621. $rm_attnames,
  1622. $bad_attvals,
  1623. $add_attr_to_tag,
  1624. $message,
  1625. $id,
  1626. $mailbox
  1627. );
  1628. if (preg_match("|$secremoveimg|i", $trusted)){
  1629. $has_unsafe_images = true;
  1630. }
  1631. return $trusted;
  1632. }
  1633. ?>