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