mime.php 54 KB

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