mime.php 53 KB

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