PageRenderTime 141ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 1ms

/tags/rel-1_5_1/squirrelmail/functions/mime.php

#
PHP | 2390 lines | 1392 code | 166 blank | 832 comment | 337 complexity | 29c9622efa4f8a1b9f4e3b42b0a07f8f MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /**
  3. * mime.php
  4. *
  5. * This contains the functions necessary to detect and decode MIME
  6. * messages.
  7. *
  8. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: mime.php 10703 2006-02-11 11:13:05Z stekkel $
  11. * @package squirrelmail
  12. */
  13. /** The typical includes... */
  14. require_once(SM_PATH . 'functions/imap.php');
  15. require_once(SM_PATH . 'functions/attachment_common.php');
  16. /** add sqm_baseuri()*/
  17. include_once(SM_PATH . 'functions/display_messages.php');
  18. /* -------------------------------------------------------------------------- */
  19. /* MIME DECODING */
  20. /* -------------------------------------------------------------------------- */
  21. /**
  22. * Get the MIME structure
  23. *
  24. * This function gets the structure of a message and stores it in the "message" class.
  25. * It will return this object for use with all relevant header information and
  26. * fully parsed into the standard "message" object format.
  27. */
  28. function mime_structure ($bodystructure, $flags=array()) {
  29. /* Isolate the body structure and remove beginning and end parenthesis. */
  30. $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
  31. $read = trim(substr ($read, 0, -1));
  32. $i = 0;
  33. $msg = Message::parseStructure($read,$i);
  34. if (!is_object($msg)) {
  35. include_once(SM_PATH . 'functions/display_messages.php');
  36. global $color, $mailbox;
  37. /* removed urldecode because $_GET is auto urldecoded ??? */
  38. displayPageHeader( $color, $mailbox );
  39. $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
  40. $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
  41. $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
  42. plain_error_message( $errormessage, $color );
  43. echo '</body></html>';
  44. exit;
  45. }
  46. if (count($flags)) {
  47. foreach ($flags as $flag) {
  48. $char = strtoupper($flag{1});
  49. switch ($char) {
  50. case 'S':
  51. if (strtolower($flag) == '\\seen') {
  52. $msg->is_seen = true;
  53. }
  54. break;
  55. case 'A':
  56. if (strtolower($flag) == '\\answered') {
  57. $msg->is_answered = true;
  58. }
  59. break;
  60. case 'D':
  61. if (strtolower($flag) == '\\deleted') {
  62. $msg->is_deleted = true;
  63. }
  64. break;
  65. case 'F':
  66. if (strtolower($flag) == '\\flagged') {
  67. $msg->is_flagged = true;
  68. }
  69. break;
  70. case 'M':
  71. if (strtolower($flag) == '$mdnsent') {
  72. $msg->is_mdnsent = true;
  73. }
  74. break;
  75. default:
  76. break;
  77. }
  78. }
  79. }
  80. // listEntities($msg);
  81. return $msg;
  82. }
  83. /* This starts the parsing of a particular structure. It is called recursively,
  84. * so it can be passed different structures. It returns an object of type
  85. * $message.
  86. * First, it checks to see if it is a multipart message. If it is, then it
  87. * handles that as it sees is necessary. If it is just a regular entity,
  88. * then it parses it and adds the necessary header information (by calling out
  89. * to mime_get_elements()
  90. */
  91. function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
  92. /* Do a bit of error correction. If we couldn't find the entity id, just guess
  93. * that it is the first one. That is usually the case anyway.
  94. */
  95. if (!$ent_id) {
  96. $cmd = "FETCH $id BODY[]";
  97. } else {
  98. $cmd = "FETCH $id BODY[$ent_id]";
  99. }
  100. if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
  101. $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
  102. do {
  103. $topline = trim(array_shift($data));
  104. } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
  105. $wholemessage = implode('', $data);
  106. if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
  107. $ret = substr($wholemessage, 0, $regs[1]);
  108. /* There is some information in the content info header that could be important
  109. * in order to parse html messages. Let's get them here.
  110. */
  111. // if ($ret{0} == '<') {
  112. // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
  113. // }
  114. } else if (ereg('"([^"]*)"', $topline, $regs)) {
  115. $ret = $regs[1];
  116. } else {
  117. global $where, $what, $mailbox, $passed_id, $startMessage;
  118. $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
  119. if (isset($where) && isset($what)) {
  120. $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
  121. } else {
  122. $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  123. }
  124. $par .= '&amp;response=' . urlencode($response) .
  125. '&amp;message=' . urlencode($message) .
  126. '&amp;topline=' . urlencode($topline);
  127. echo '<tt><br />' .
  128. '<table width="80%"><tr>' .
  129. '<tr><td colspan="2">' .
  130. _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
  131. '</td></tr>' .
  132. '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
  133. '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
  134. '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
  135. '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
  136. "</table><br /></tt></font><hr />";
  137. $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
  138. array_shift($data);
  139. $wholemessage = implode('', $data);
  140. $ret = $wholemessage;
  141. }
  142. return $ret;
  143. }
  144. function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
  145. /* Don't kill the connection if the browser is over a dialup
  146. * and it would take over 30 seconds to download it.
  147. * Don't call set_time_limit in safe mode.
  148. */
  149. if (!ini_get('safe_mode')) {
  150. set_time_limit(0);
  151. }
  152. /* in case of base64 encoded attachments, do not buffer them.
  153. Instead, echo the decoded attachment directly to screen */
  154. if (strtolower($encoding) == 'base64') {
  155. if (!$ent_id) {
  156. $query = "FETCH $id BODY[]";
  157. } else {
  158. $query = "FETCH $id BODY[$ent_id]";
  159. }
  160. sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
  161. } else {
  162. $body = mime_fetch_body ($imap_stream, $id, $ent_id);
  163. if (is_resource($rStream)) {
  164. fputs($rStream,decodeBody($body,$encoding));
  165. } else {
  166. echo decodeBody($body, $encoding);
  167. }
  168. }
  169. /*
  170. TODO, use the same method for quoted printable.
  171. However, I assume that quoted printable attachments aren't that large
  172. so the performancegain / memory usage drop will be minimal.
  173. If we decide to add that then we need to adapt sqimap_fread because
  174. we need to split te result on \n and fread doesn't stop at \n. That
  175. means we also should provide $results from sqimap_fread (by ref) to
  176. te function and set $no_return to false. The $filter function for
  177. quoted printable should handle unsetting of $results.
  178. */
  179. /*
  180. TODO 2: find out how we write to the output stream php://stdout. fwrite
  181. doesn't work because 'php://stdout isn't a stream.
  182. */
  183. return;
  184. }
  185. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  186. /* This is here for debugging purposes. It will print out a list
  187. * of all the entity IDs that are in the $message object.
  188. */
  189. function listEntities ($message) {
  190. if ($message) {
  191. echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
  192. for ($i = 0; isset($message->entities[$i]); $i++) {
  193. echo "$i : ";
  194. $msg = listEntities($message->entities[$i]);
  195. if ($msg) {
  196. echo "return: ";
  197. return $msg;
  198. }
  199. }
  200. }
  201. }
  202. function getPriorityStr($priority) {
  203. $priority_level = substr($priority,0,1);
  204. switch($priority_level) {
  205. /* Check for a higher then normal priority. */
  206. case '1':
  207. case '2':
  208. $priority_string = _("High");
  209. break;
  210. /* Check for a lower then normal priority. */
  211. case '4':
  212. case '5':
  213. $priority_string = _("Low");
  214. break;
  215. /* Check for a normal priority. */
  216. case '3':
  217. default:
  218. $priority_level = '3';
  219. $priority_string = _("Normal");
  220. break;
  221. }
  222. return $priority_string;
  223. }
  224. /* returns a $message object for a particular entity id */
  225. function getEntity ($message, $ent_id) {
  226. return $message->getEntity($ent_id);
  227. }
  228. /* translateText
  229. * Extracted from strings.php 23/03/2002
  230. */
  231. function translateText(&$body, $wrap_at, $charset) {
  232. global $where, $what; /* from searching */
  233. global $color; /* color theme */
  234. require_once(SM_PATH . 'functions/url_parser.php');
  235. $body_ary = explode("\n", $body);
  236. for ($i=0; $i < count($body_ary); $i++) {
  237. $line = $body_ary[$i];
  238. if (strlen($line) - 2 >= $wrap_at) {
  239. sqWordWrap($line, $wrap_at, $charset);
  240. }
  241. $line = charset_decode($charset, $line);
  242. $line = str_replace("\t", ' ', $line);
  243. parseUrl ($line);
  244. $quotes = 0;
  245. $pos = 0;
  246. $j = strlen($line);
  247. while ($pos < $j) {
  248. if ($line[$pos] == ' ') {
  249. $pos++;
  250. } else if (strpos($line, '&gt;', $pos) === $pos) {
  251. $pos += 4;
  252. $quotes++;
  253. } else {
  254. break;
  255. }
  256. }
  257. if ($quotes % 2) {
  258. if (!isset($color[13])) {
  259. $color[13] = '#800000';
  260. }
  261. $line = '<font color="' . $color[13] . '">' . $line . '</font>';
  262. } elseif ($quotes) {
  263. if (!isset($color[14])) {
  264. $color[14] = '#FF0000';
  265. }
  266. $line = '<font color="' . $color[14] . '">' . $line . '</font>';
  267. }
  268. $body_ary[$i] = $line;
  269. }
  270. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  271. }
  272. /**
  273. * This returns a parsed string called $body. That string can then
  274. * be displayed as the actual message in the HTML. It contains
  275. * everything needed, including HTML Tags, Attachments at the
  276. * bottom, etc.
  277. *
  278. * Since 1.2.0 function uses message_body hook.
  279. * Till 1.3.0 function included output of formatAttachments().
  280. *
  281. * @param resource $imap_stream imap connection resource
  282. * @param object $message squirrelmail message object
  283. * @param array $color squirrelmail color theme array
  284. * @param integer $wrap_at number of characters per line
  285. * @param string $ent_num (since 1.3.0) message part id
  286. * @param integer $id (since 1.3.0) message id
  287. * @param string $mailbox (since 1.3.0) imap folder name
  288. * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
  289. * @return string html formated message text
  290. */
  291. function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
  292. /* This if statement checks for the entity to show as the
  293. * primary message. To add more of them, just put them in the
  294. * order that is their priority.
  295. */
  296. global $startMessage, $languages, $squirrelmail_language,
  297. $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
  298. $use_iframe, $iframe_height, $download_and_unsafe_link;
  299. // workaround for not updated config.php
  300. if (! isset($use_iframe)) $use_iframe = false;
  301. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  302. $view_unsafe_images = false;
  303. }
  304. $body = '';
  305. $urlmailbox = urlencode($mailbox);
  306. $body_message = getEntity($message, $ent_num);
  307. if (($body_message->header->type0 == 'text') ||
  308. ($body_message->header->type0 == 'rfc822')) {
  309. $body = mime_fetch_body ($imap_stream, $id, $ent_num);
  310. $body = decodeBody($body, $body_message->header->encoding);
  311. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  312. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
  313. if (mb_detect_encoding($body) != 'ASCII') {
  314. $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
  315. }
  316. }
  317. $hookResults = do_hook("message_body", $body);
  318. $body = $hookResults[1];
  319. /* If there are other types that shouldn't be formatted, add
  320. * them here.
  321. */
  322. if ($body_message->header->type1 == 'html') {
  323. if ($show_html_default <> 1) {
  324. $entity_conv = array('&nbsp;' => ' ',
  325. '<p>' => "\n",
  326. '<P>' => "\n",
  327. '<br>' => "\n",
  328. '<BR>' => "\n",
  329. '<br />' => "\n",
  330. '<BR />' => "\n",
  331. '&gt;' => '>',
  332. '&lt;' => '<');
  333. $body = strtr($body, $entity_conv);
  334. $body = strip_tags($body);
  335. $body = trim($body);
  336. translateText($body, $wrap_at,
  337. $body_message->header->getParameter('charset'));
  338. } elseif ($use_iframe && ! $clean) {
  339. // $clean is used to remove iframe in printable view.
  340. /**
  341. * If we don't add html message between iframe tags,
  342. * we must detect unsafe images and modify $has_unsafe_images.
  343. */
  344. $html_body = magicHTML($body, $id, $message, $mailbox);
  345. // Convert character set in order to display html mails in different character set
  346. $html_body = charset_decode($body_message->header->getParameter('charset'),$html_body,false,true);
  347. // creating iframe url
  348. $iframeurl=sqm_baseuri().'src/view_html.php?'
  349. . 'mailbox=' . $urlmailbox
  350. . '&amp;passed_id=' . $id
  351. . '&amp;ent_id=' . $ent_num
  352. . '&amp;view_unsafe_images=' . (int) $view_unsafe_images;
  353. // adding warning message
  354. $body = html_tag('div',_("Viewing HTML formatted email"),'center');
  355. /**
  356. * height can't be set to 100%, because it does not work as expected when
  357. * iframe is inside the table. Browsers do not create full height objects
  358. * even when iframe is not nested. Maybe there is some way to get full size
  359. * with CSS. Tested in firefox 1.02 and opera 7.53
  360. *
  361. * width="100%" does not work as expected, when table width is not set (automatic)
  362. *
  363. * tokul: I think <iframe> are safer sandbox than <object>. Objects might
  364. * need special handling for IE and IE6SP2.
  365. */
  366. $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
  367. .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
  368. // Message for browsers without iframe support
  369. //$body.= _("Your browser does not support inline frames.
  370. // You can view HTML formated message by following below link.");
  371. //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
  372. // if browser can't render iframe, it renders html message.
  373. $body.= $html_body;
  374. // close iframe
  375. $body.="</iframe></div>\n";
  376. } else {
  377. // old way of html rendering
  378. $body = magicHTML($body, $id, $message, $mailbox);
  379. /**
  380. * convert character set. charset_decode does not remove html special chars
  381. * applied by magicHTML functions and does not sanitize them second time if
  382. * fourth argument is true.
  383. */
  384. $body = charset_decode($body_message->header->getParameter('charset'),$body,false,true);
  385. }
  386. } else {
  387. translateText($body, $wrap_at,
  388. $body_message->header->getParameter('charset'));
  389. }
  390. // if this is the clean display (i.e. printer friendly), stop here.
  391. if ( $clean ) {
  392. return $body;
  393. }
  394. $download_and_unsafe_link = '';
  395. $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
  396. '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
  397. '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
  398. if (isset($passed_ent_id)) {
  399. $link .= '&amp;passed_ent_id='.$passed_ent_id;
  400. }
  401. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="download.php?absolute_dl=true&amp;' .
  402. $link . '">' . _("Download this as a file") . '</a>';
  403. if ($view_unsafe_images) {
  404. $text = _("Hide Unsafe Images");
  405. } else {
  406. if (isset($has_unsafe_images) && $has_unsafe_images) {
  407. $link .= '&amp;view_unsafe_images=1';
  408. $text = _("View Unsafe Images");
  409. } else {
  410. $text = '';
  411. }
  412. }
  413. if($text != '') {
  414. $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
  415. }
  416. }
  417. return $body;
  418. }
  419. /**
  420. * Displays attachment links and information
  421. *
  422. * Since 1.3.0 function is not included in formatBody() call.
  423. *
  424. * Since 1.0.2 uses attachment $type0/$type1 hook.
  425. * Since 1.2.5 uses attachment $type0/* hook.
  426. * Since 1.5.0 uses attachments_bottom hook.
  427. *
  428. * @param object $message SquirrelMail message object
  429. * @param array $exclude_id message parts that are not attachments.
  430. * @param string $mailbox mailbox name
  431. * @param integer $id message id
  432. * @return string html formated attachment information.
  433. */
  434. function formatAttachments($message, $exclude_id, $mailbox, $id) {
  435. global $where, $what, $startMessage, $color, $passed_ent_id;
  436. $att_ar = $message->getAttachments($exclude_id);
  437. if (!count($att_ar)) return '';
  438. $attachments = '';
  439. $urlMailbox = urlencode($mailbox);
  440. foreach ($att_ar as $att) {
  441. $ent = $att->entity_id;
  442. $header = $att->header;
  443. $type0 = strtolower($header->type0);
  444. $type1 = strtolower($header->type1);
  445. $name = '';
  446. $links['download link']['text'] = _("Download");
  447. $links['download link']['href'] = sqm_baseuri() .
  448. "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  449. if ($type0 =='message' && $type1 == 'rfc822') {
  450. $default_page = sqm_baseuri() . 'src/read_body.php';
  451. $rfc822_header = $att->rfc822_header;
  452. $filename = $rfc822_header->subject;
  453. if (trim( $filename ) == '') {
  454. $filename = 'untitled-[' . $ent . ']' ;
  455. }
  456. $from_o = $rfc822_header->from;
  457. if (is_object($from_o)) {
  458. $from_name = decodeHeader($from_o->getAddress(false));
  459. } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
  460. // something weird happens when a digest message is opened and you return to the digest
  461. // now the from object is part of an array. Probably the parseHeader call overwrites the info
  462. // retrieved from the bodystructure in a different way. We need to fix this later.
  463. // possible starting point, do not fetch header we already have and inspect how
  464. // the rfc822_header object behaves.
  465. $from_name = decodeHeader($from_o[0]->getAddress(false));
  466. } else {
  467. $from_name = _("Unknown sender");
  468. }
  469. $description = $from_name;
  470. } else {
  471. $default_page = sqm_baseuri() . 'src/download.php';
  472. $filename = $att->getFilename();
  473. if ($header->description) {
  474. $description = decodeHeader($header->description);
  475. } else {
  476. $description = '';
  477. }
  478. }
  479. $display_filename = $filename;
  480. if (isset($passed_ent_id)) {
  481. $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
  482. } else {
  483. $passed_ent_id_link = '';
  484. }
  485. $defaultlink = $default_page . "?startMessage=$startMessage"
  486. . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  487. . '&amp;ent_id='.$ent.$passed_ent_id_link;
  488. if ($where && $what) {
  489. $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
  490. }
  491. /* This executes the attachment hook with a specific MIME-type.
  492. * If that doesn't have results, it tries if there's a rule
  493. * for a more generic type.
  494. */
  495. $hookresults = do_hook("attachment $type0/$type1", $links,
  496. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  497. $display_filename, $where, $what);
  498. if(count($hookresults[1]) <= 1) {
  499. $hookresults = do_hook("attachment $type0/*", $links,
  500. $startMessage, $id, $urlMailbox, $ent, $defaultlink,
  501. $display_filename, $where, $what);
  502. }
  503. $links = $hookresults[1];
  504. $defaultlink = $hookresults[6];
  505. $attachments .= '<tr><td>' .
  506. '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  507. '<td><small><b>' . show_readable_size($header->size) .
  508. '</b>&nbsp;&nbsp;</small></td>' .
  509. '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  510. '<td><small>';
  511. $attachments .= '<b>' . $description . '</b>';
  512. $attachments .= '</small></td><td><small>&nbsp;';
  513. $skipspaces = 1;
  514. foreach ($links as $val) {
  515. if ($skipspaces) {
  516. $skipspaces = 0;
  517. } else {
  518. $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  519. }
  520. $attachments .= '<a href="' . $val['href'] . '">'
  521. . (isset($val['text']) && !empty($val['text']) ? $val['text'] : '')
  522. . (isset($val['extra']) && !empty($val['extra']) ? $val['extra'] : '')
  523. . '</a>';
  524. }
  525. unset($links);
  526. $attachments .= "</td></tr>\n";
  527. }
  528. $attachmentadd = do_hook_function('attachments_bottom',$attachments);
  529. if ($attachmentadd != '')
  530. $attachments = $attachmentadd;
  531. return $attachments;
  532. }
  533. function sqimap_base64_decode(&$string) {
  534. // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  535. // fly decoding (to reduce memory usage) you have to check if the
  536. // data has incomplete pairs
  537. // Remove the noise in order to check if the 4 bytes pairs are complete
  538. $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
  539. $sStringRem = '';
  540. $iMod = strlen($string) % 4;
  541. if ($iMod) {
  542. $sStringRem = substr($string,-$iMod);
  543. // Check if $sStringRem contains padding characters
  544. if (substr($sStringRem,-1) != '=') {
  545. $string = substr($string,0,-$iMod);
  546. } else {
  547. $sStringRem = '';
  548. }
  549. }
  550. $string = base64_decode($string);
  551. return $sStringRem;
  552. }
  553. /**
  554. * Decodes encoded message body
  555. *
  556. * This function decodes the body depending on the encoding type.
  557. * Currently quoted-printable and base64 encodings are supported.
  558. * decode_body hook was added to this function in 1.4.2/1.5.0
  559. * @param string $body encoded message body
  560. * @param string $encoding used encoding
  561. * @return string decoded string
  562. * @since 1.0
  563. */
  564. function decodeBody($body, $encoding) {
  565. $body = str_replace("\r\n", "\n", $body);
  566. $encoding = strtolower($encoding);
  567. $encoding_handler = do_hook_function('decode_body', $encoding);
  568. // plugins get first shot at decoding the body
  569. //
  570. if (!empty($encoding_handler) && function_exists($encoding_handler)) {
  571. $body = $encoding_handler('decode', $body);
  572. } elseif ($encoding == 'quoted-printable' ||
  573. $encoding == 'quoted_printable') {
  574. /**
  575. * quoted_printable_decode() function is broken in older
  576. * php versions. Text with \r\n decoding was fixed only
  577. * in php 4.3.0. Minimal code requirement 4.0.4 +
  578. * str_replace("\r\n", "\n", $body); call.
  579. */
  580. $body = quoted_printable_decode($body);
  581. } elseif ($encoding == 'base64') {
  582. $body = base64_decode($body);
  583. }
  584. // All other encodings are returned raw.
  585. return $body;
  586. }
  587. /**
  588. * Decodes headers
  589. *
  590. * This functions decode strings that is encoded according to
  591. * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  592. * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
  593. *
  594. * @param string $string header string that has to be made readable
  595. * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
  596. * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
  597. * @param boolean $decide decide if string can be utfencoded. defaults to false
  598. * @return string decoded header string
  599. */
  600. function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
  601. global $languages, $squirrelmail_language,$default_charset;
  602. if (is_array($string)) {
  603. $string = implode("\n", $string);
  604. }
  605. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  606. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
  607. $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
  608. // Do we need to return at this point?
  609. // return $string;
  610. }
  611. $i = 0;
  612. $iLastMatch = -2;
  613. $encoded = true;
  614. $aString = explode(' ',$string);
  615. $ret = '';
  616. foreach ($aString as $chunk) {
  617. if ($encoded && $chunk === '') {
  618. continue;
  619. } elseif ($chunk === '') {
  620. $ret .= ' ';
  621. continue;
  622. }
  623. $encoded = false;
  624. /* if encoded words are not separated by a linear-space-white we still catch them */
  625. $j = $i-1;
  626. while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  627. /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  628. if ($iLastMatch !== $j) {
  629. if ($htmlsave) {
  630. $ret .= '&#32;';
  631. } else {
  632. $ret .= ' ';
  633. }
  634. }
  635. $iLastMatch = $i;
  636. $j = $i;
  637. if ($htmlsave) {
  638. $ret .= htmlspecialchars($res[1]);
  639. } else {
  640. $ret .= $res[1];
  641. }
  642. $encoding = ucfirst($res[3]);
  643. /* decide about valid decoding */
  644. if ($decide && is_conversion_safe($res[2])) {
  645. $utfencode=true;
  646. $can_be_encoded=true;
  647. } else {
  648. $can_be_encoded=false;
  649. }
  650. switch ($encoding)
  651. {
  652. case 'B':
  653. $replace = base64_decode($res[4]);
  654. if ($utfencode) {
  655. if ($can_be_encoded) {
  656. /* convert string to different charset,
  657. * if functions asks for it (usually in compose)
  658. */
  659. $ret .= charset_convert($res[2],$replace,$default_charset);
  660. } else {
  661. // convert string to html codes in order to display it
  662. $ret .= charset_decode($res[2],$replace);
  663. }
  664. } else {
  665. if ($htmlsave) {
  666. $replace = htmlspecialchars($replace);
  667. }
  668. $ret.= $replace;
  669. }
  670. break;
  671. case 'Q':
  672. $replace = str_replace('_', ' ', $res[4]);
  673. $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
  674. $replace);
  675. if ($utfencode) {
  676. if ($can_be_encoded) {
  677. /* convert string to different charset,
  678. * if functions asks for it (usually in compose)
  679. */
  680. $replace = charset_convert($res[2], $replace,$default_charset);
  681. } else {
  682. // convert string to html codes in order to display it
  683. $replace = charset_decode($res[2], $replace);
  684. }
  685. } else {
  686. if ($htmlsave) {
  687. $replace = htmlspecialchars($replace);
  688. }
  689. }
  690. $ret .= $replace;
  691. break;
  692. default:
  693. break;
  694. }
  695. $chunk = $res[5];
  696. $encoded = true;
  697. }
  698. if (!$encoded) {
  699. if ($htmlsave) {
  700. $ret .= '&#32;';
  701. } else {
  702. $ret .= ' ';
  703. }
  704. }
  705. if (!$encoded && $htmlsave) {
  706. $ret .= htmlspecialchars($chunk);
  707. } else {
  708. $ret .= $chunk;
  709. }
  710. ++$i;
  711. }
  712. /* remove the first added space */
  713. if ($ret) {
  714. if ($htmlsave) {
  715. $ret = substr($ret,5);
  716. } else {
  717. $ret = substr($ret,1);
  718. }
  719. }
  720. return $ret;
  721. }
  722. /**
  723. * Encodes header
  724. *
  725. * Function uses XTRA_CODE _encodeheader function, if such function exists.
  726. *
  727. * Function uses Q encoding by default and encodes a string according to RFC
  728. * 1522 for use in headers if it contains 8-bit characters or anything that
  729. * looks like it should be encoded.
  730. *
  731. * Function switches to B encoding and encodeHeaderBase64() function, if
  732. * string is 8bit and multibyte character set supported by mbstring extension
  733. * is used. It can cause E_USER_NOTICE errors, if interface is used with
  734. * multibyte character set unsupported by mbstring extension.
  735. *
  736. * @param string $string header string, that has to be encoded
  737. * @return string quoted-printable encoded string
  738. * @todo make $mb_charsets system wide constant
  739. */
  740. function encodeHeader ($string) {
  741. global $default_charset, $languages, $squirrelmail_language;
  742. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  743. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
  744. return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
  745. }
  746. // Use B encoding for multibyte charsets
  747. $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
  748. if (in_array($default_charset,$mb_charsets) &&
  749. in_array($default_charset,sq_mb_list_encodings()) &&
  750. sq_is8bit($string)) {
  751. return encodeHeaderBase64($string,$default_charset);
  752. } elseif (in_array($default_charset,$mb_charsets) &&
  753. sq_is8bit($string) &&
  754. ! in_array($default_charset,sq_mb_list_encodings())) {
  755. // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  756. // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  757. }
  758. // Encode only if the string contains 8-bit characters or =?
  759. $j = strlen($string);
  760. $max_l = 75 - strlen($default_charset) - 7;
  761. $aRet = array();
  762. $ret = '';
  763. $iEncStart = $enc_init = false;
  764. $cur_l = $iOffset = 0;
  765. for($i = 0; $i < $j; ++$i) {
  766. switch($string{$i})
  767. {
  768. case '=':
  769. case '<':
  770. case '>':
  771. case ',':
  772. case '?':
  773. case '_':
  774. if ($iEncStart === false) {
  775. $iEncStart = $i;
  776. }
  777. $cur_l+=3;
  778. if ($cur_l > ($max_l-2)) {
  779. /* if there is an stringpart that doesn't need encoding, add it */
  780. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  781. $aRet[] = "=?$default_charset?Q?$ret?=";
  782. $iOffset = $i;
  783. $cur_l = 0;
  784. $ret = '';
  785. $iEncStart = false;
  786. } else {
  787. $ret .= sprintf("=%02X",ord($string{$i}));
  788. }
  789. break;
  790. case '(':
  791. case ')':
  792. if ($iEncStart !== false) {
  793. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  794. $aRet[] = "=?$default_charset?Q?$ret?=";
  795. $iOffset = $i;
  796. $cur_l = 0;
  797. $ret = '';
  798. $iEncStart = false;
  799. }
  800. break;
  801. case ' ':
  802. if ($iEncStart !== false) {
  803. $cur_l++;
  804. if ($cur_l > $max_l) {
  805. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  806. $aRet[] = "=?$default_charset?Q?$ret?=";
  807. $iOffset = $i;
  808. $cur_l = 0;
  809. $ret = '';
  810. $iEncStart = false;
  811. } else {
  812. $ret .= '_';
  813. }
  814. }
  815. break;
  816. default:
  817. $k = ord($string{$i});
  818. if ($k > 126) {
  819. if ($iEncStart === false) {
  820. // do not start encoding in the middle of a string, also take the rest of the word.
  821. $sLeadString = substr($string,0,$i);
  822. $aLeadString = explode(' ',$sLeadString);
  823. $sToBeEncoded = array_pop($aLeadString);
  824. $iEncStart = $i - strlen($sToBeEncoded);
  825. $ret .= $sToBeEncoded;
  826. $cur_l += strlen($sToBeEncoded);
  827. }
  828. $cur_l += 3;
  829. /* first we add the encoded string that reached it's max size */
  830. if ($cur_l > ($max_l-2)) {
  831. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  832. $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
  833. $cur_l = 3;
  834. $ret = '';
  835. $iOffset = $i;
  836. $iEncStart = $i;
  837. }
  838. $enc_init = true;
  839. $ret .= sprintf("=%02X", $k);
  840. } else {
  841. if ($iEncStart !== false) {
  842. $cur_l++;
  843. if ($cur_l > $max_l) {
  844. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  845. $aRet[] = "=?$default_charset?Q?$ret?=";
  846. $iEncStart = false;
  847. $iOffset = $i;
  848. $cur_l = 0;
  849. $ret = '';
  850. } else {
  851. $ret .= $string{$i};
  852. }
  853. }
  854. }
  855. break;
  856. }
  857. }
  858. if ($enc_init) {
  859. if ($iEncStart !== false) {
  860. $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
  861. $aRet[] = "=?$default_charset?Q?$ret?=";
  862. } else {
  863. $aRet[] = substr($string,$iOffset);
  864. }
  865. $string = implode('',$aRet);
  866. }
  867. return $string;
  868. }
  869. /**
  870. * Encodes string according to rfc2047 B encoding header formating rules
  871. *
  872. * It is recommended way to encode headers with character sets that store
  873. * symbols in more than one byte.
  874. *
  875. * Function requires mbstring support. If required mbstring functions are missing,
  876. * function returns false and sets E_USER_WARNING level error message.
  877. *
  878. * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  879. * that mbstring functions will generate E_WARNING errors, if unsupported
  880. * character set is used. mb_encode_mimeheader function provided by php
  881. * mbstring extension is not used in order to get better control of header
  882. * encoding.
  883. *
  884. * Used php code functions - function_exists(), trigger_error(), strlen()
  885. * (is used with charset names and base64 strings). Used php mbstring
  886. * functions - mb_strlen and mb_substr.
  887. *
  888. * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  889. * encoding), rfc 2822 (header folding)
  890. *
  891. * @param string $string header string that must be encoded
  892. * @param string $charset character set. Must be supported by mbstring extension.
  893. * Use sq_mb_list_encodings() to detect supported charsets.
  894. * @return string string encoded according to rfc2047 B encoding formating rules
  895. * @since 1.5.1
  896. * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
  897. * @todo Do we want to control max length of header?
  898. * @todo Do we want to control EOL (end-of-line) marker?
  899. * @todo Do we want to translate error message?
  900. */
  901. function encodeHeaderBase64($string,$charset) {
  902. /**
  903. * Check mbstring function requirements.
  904. */
  905. if (! function_exists('mb_strlen') ||
  906. ! function_exists('mb_substr')) {
  907. // set E_USER_WARNING
  908. trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  909. // return false
  910. return false;
  911. }
  912. // initial return array
  913. $aRet = array();
  914. /**
  915. * header length = 75 symbols max (same as in encodeHeader)
  916. * remove $charset length
  917. * remove =? ? ?= (5 chars)
  918. * remove 2 more chars (\r\n ?)
  919. */
  920. $iMaxLength = 75 - strlen($charset) - 7;
  921. // set first character position
  922. $iStartCharNum = 0;
  923. // loop through all characters. count characters and not bytes.
  924. for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
  925. // encode string from starting character to current character.
  926. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  927. // Check encoded string length
  928. if(strlen($encoded_string)>$iMaxLength) {
  929. // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  930. $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  931. // set new starting character
  932. $iStartCharNum = $iCharNum-1;
  933. // encode last char (in case it is last character in string)
  934. $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  935. } // if string is shorter than max length - add next character
  936. }
  937. // add last encoded string to array
  938. $aRet[] = $encoded_string;
  939. // set initial return string
  940. $sRet = '';
  941. // loop through encoded strings
  942. foreach($aRet as $string) {
  943. // TODO: Do we want to control EOL (end-of-line) marker
  944. if ($sRet!='') $sRet.= " ";
  945. // add header tags and encoded string to return string
  946. $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  947. }
  948. return $sRet;
  949. }
  950. /* This function trys to locate the entity_id of a specific mime element */
  951. function find_ent_id($id, $message) {
  952. for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
  953. if ($message->entities[$i]->header->type0 == 'multipart') {
  954. $ret = find_ent_id($id, $message->entities[$i]);
  955. } else {
  956. if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
  957. // if (sq_check_save_extension($message->entities[$i])) {
  958. return $message->entities[$i]->entity_id;
  959. // }
  960. } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  961. /**
  962. * This is part of a fix for Outlook Express 6.x generating
  963. * cid URLs without creating content-id headers
  964. * @@JA - 20050207
  965. */
  966. if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
  967. return $message->entities[$i]->entity_id;
  968. }
  969. }
  970. }
  971. }
  972. return $ret;
  973. }
  974. function sq_check_save_extension($message) {
  975. $filename = $message->getFilename();
  976. $ext = substr($filename, strrpos($filename,'.')+1);
  977. $save_extensions = array('jpg','jpeg','gif','png','bmp');
  978. return in_array($ext, $save_extensions);
  979. }
  980. /**
  981. ** HTMLFILTER ROUTINES
  982. */
  983. /**
  984. * This function checks attribute values for entity-encoded values
  985. * and returns them translated into 8-bit strings so we can run
  986. * checks on them.
  987. *
  988. * @param $attvalue A string to run entity check against.
  989. * @return Nothing, modifies a reference value.
  990. */
  991. function sq_defang(&$attvalue){
  992. $me = 'sq_defang';
  993. /**
  994. * Skip this if there aren't ampersands or backslashes.
  995. */
  996. if (strpos($attvalue, '&') === false
  997. && strpos($attvalue, '\\') === false){
  998. return;
  999. }
  1000. $m = false;
  1001. do {
  1002. $m = false;
  1003. $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
  1004. $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
  1005. $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
  1006. } while ($m == true);
  1007. $attvalue = stripslashes($attvalue);
  1008. }
  1009. /**
  1010. * Kill any tabs, newlines, or carriage returns. Our friends the
  1011. * makers of the browser with 95% market value decided that it'd
  1012. * be funny to make "java[tab]script" be just as good as "javascript".
  1013. *
  1014. * @param attvalue The attribute value before extraneous spaces removed.
  1015. * @return attvalue Nothing, modifies a reference value.
  1016. */
  1017. function sq_unspace(&$attvalue){
  1018. $me = 'sq_unspace';
  1019. if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
  1020. $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
  1021. Array('', '', '', '', ''), $attvalue);
  1022. }
  1023. }
  1024. /**
  1025. * This function returns the final tag out of the tag name, an array
  1026. * of attributes, and the type of the tag. This function is called by
  1027. * sq_sanitize internally.
  1028. *
  1029. * @param $tagname the name of the tag.
  1030. * @param $attary the array of attributes and their values
  1031. * @param $tagtype The type of the tag (see in comments).
  1032. * @return a string with the final tag representation.
  1033. */
  1034. function sq_tagprint($tagname, $attary, $tagtype){
  1035. $me = 'sq_tagprint';
  1036. if ($tagtype == 2){
  1037. $fulltag = '</' . $tagname . '>';
  1038. } else {
  1039. $fulltag = '<' . $tagname;
  1040. if (is_array($attary) && sizeof($attary)){
  1041. $atts = Array();
  1042. while (list($attname, $attvalue) = each($attary)){
  1043. array_push($atts, "$attname=$attvalue");
  1044. }
  1045. $fulltag .= ' ' . join(" ", $atts);
  1046. }
  1047. if ($tagtype == 3){
  1048. $fulltag .= ' /';
  1049. }
  1050. $fulltag .= '>';
  1051. }
  1052. return $fulltag;
  1053. }
  1054. /**
  1055. * A small helper function to use with array_walk. Modifies a by-ref
  1056. * value and makes it lowercase.
  1057. *
  1058. * @param $val a value passed by-ref.
  1059. * @return void since it modifies a by-ref value.
  1060. */
  1061. function sq_casenormalize(&$val){
  1062. $val = strtolower($val);
  1063. }
  1064. /**
  1065. * This function skips any whitespace from the current position within
  1066. * a string and to the next non-whitespace value.
  1067. *
  1068. * @param $body the string
  1069. * @param $offset the offset within the string where we should start
  1070. * looking for the next non-whitespace character.
  1071. * @return the location within the $body where the next
  1072. * non-whitespace char is located.
  1073. */
  1074. function sq_skipspace($body, $offset){
  1075. $me = 'sq_skipspace';
  1076. preg_match('/^(\s*)/s', substr($body, $offset), $matches);
  1077. if (sizeof($matches{1})){
  1078. $count = strlen($matches{1});
  1079. $offset += $count;
  1080. }
  1081. return $offset;
  1082. }
  1083. /**
  1084. * This function looks for the next character within a string. It's
  1085. * really just a glorified "strpos", except it catches if failures
  1086. * nicely.
  1087. *
  1088. * @param $body The string to look for needle in.
  1089. * @param $offset Start looking from this position.
  1090. * @param $needle The character/string to look for.
  1091. * @return location of the next occurance of the needle, or
  1092. * strlen($body) if needle wasn't found.
  1093. */
  1094. function sq_findnxstr($body, $offset, $needle){
  1095. $me = 'sq_findnxstr';
  1096. $pos = strpos($body, $needle, $offset);
  1097. if ($pos === FALSE){
  1098. $pos = strlen($body);
  1099. }
  1100. return $pos;
  1101. }
  1102. /**
  1103. * This function takes a PCRE-style regexp and tries to match it
  1104. * within the string.
  1105. *
  1106. * @param $body The string to look for needle in.
  1107. * @param $offset Start looking from here.
  1108. * @param $reg A PCRE-style regex to match.
  1109. * @return Returns a false if no matches found, or an array
  1110. * with the following members:
  1111. * - integer with the location of the match within $body
  1112. * - string with whatever content between offset and the match
  1113. * - string with whatever it is we matched
  1114. */
  1115. function sq_findnxreg($body, $offset, $reg){
  1116. $me = 'sq_findnxreg';
  1117. $matches = Array();
  1118. $retarr = Array();
  1119. preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
  1120. if (!isset($matches{0}) || !$matches{0}){
  1121. $retarr = false;
  1122. } else {
  1123. $retarr{0} = $offset + strlen($matches{1});
  1124. $retarr{1} = $matches{1};
  1125. $retarr{2} = $matches{2};
  1126. }
  1127. return $retarr;
  1128. }
  1129. /**
  1130. * This function looks for the next tag.
  1131. *
  1132. * @param $body String where to look for the next tag.
  1133. * @param $offset Start looking from here.
  1134. * @return false if no more tags exist in the body, or
  1135. * an array with the following members:
  1136. * - string with the name of the tag
  1137. * - array with attributes and their values
  1138. * - integer with tag type (1, 2, or 3)
  1139. * - integer where the tag starts (starting "<")
  1140. * - integer where the tag ends (ending ">")
  1141. * first three members will be false, if the tag is invalid.
  1142. */
  1143. function sq_getnxtag($body, $offset){
  1144. $me = 'sq_getnxtag';
  1145. if ($offset > strlen($body)){
  1146. return false;
  1147. }
  1148. $lt = sq_findnxstr($body, $offset, "<");
  1149. if ($lt == strlen($body)){
  1150. return false;
  1151. }
  1152. /**
  1153. * We are here:
  1154. * blah blah <tag attribute="value">
  1155. * \---------^
  1156. */
  1157. $pos = sq_skipspace($body, $lt+1);
  1158. if ($pos >= strlen($body)){
  1159. return Array(false, false, false, $lt, strlen($body));
  1160. }
  1161. /**
  1162. * There are 3 kinds of tags:
  1163. * 1. Opening tag, e.g.:
  1164. * <a href="blah">
  1165. * 2. Closing tag, e.g.:
  1166. * </a>
  1167. * 3. XHTML-style content-less tag, e.g.:
  1168. * <img src="blah" />
  1169. */
  1170. $tagtype = false;
  1171. switch (substr($body, $pos, 1)){
  1172. case '/':
  1173. $tagtype = 2;
  1174. $pos++;
  1175. break;
  1176. case '!':
  1177. /**
  1178. * A comment or an SGML declaration.
  1179. */
  1180. if (substr($body, $pos+1, 2) == "--"){
  1181. $gt = strpos($body, "-->", $pos);
  1182. if ($gt === false){
  1183. $gt = strlen($body);
  1184. } else {
  1185. $gt += 2;
  1186. }
  1187. return Array(false, false, false, $lt, $gt);
  1188. } else {
  1189. $gt = sq_findnxstr($body, $pos, ">");
  1190. return Array(false, false, false, $lt, $gt);
  1191. }
  1192. break;
  1193. default:
  1194. /**
  1195. * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1196. * later.
  1197. */
  1198. $tagtype = 1;
  1199. break;
  1200. }
  1201. $tag_start = $pos;
  1202. $tagname = '';
  1203. /**
  1204. * Look for next [\W-_], which will indicate the end of the tag name.
  1205. */
  1206. $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
  1207. if ($regary == false){
  1208. return Array(false, false, false, $lt, strlen($body));
  1209. }
  1210. list($pos, $tagname, $match) = $regary;
  1211. $tagname = strtolower($tagname);
  1212. /**
  1213. * $match can be either of these:
  1214. * '>' indicating the end of the tag entirely.
  1215. * '\s' indicating the end of the tag name.
  1216. * '/' indicating that this is type-3 xhtml tag.
  1217. *
  1218. * Whatever else we find there indicates an invalid tag.
  1219. */
  1220. switch ($match){
  1221. case '/':
  1222. /**
  1223. * This is an xhtml-style tag with a closing / at the
  1224. * end, like so: <img src="blah" />. Check if it's followed
  1225. * by the closing bracket. If not, then this tag is invalid
  1226. */
  1227. if (substr($body, $pos, 2) == "/>"){
  1228. $pos++;
  1229. $tagtype = 3;
  1230. } else {
  1231. $gt = sq_findnxstr($body, $pos, ">");
  1232. $retary = Array(false, false, false, $lt, $gt);
  1233. return $retary;
  1234. }
  1235. case '>':
  1236. return Array($tagname, false, $tagtype, $lt, $pos);
  1237. break;
  1238. default:
  1239. /**
  1240. * Check if it's whitespace
  1241. */
  1242. if (!preg_match('/\s/', $match)){
  1243. /**
  1244. * This is an invalid tag! Look for the next closing ">".
  1245. */
  1246. $gt = sq_findnxstr($body, $lt, ">");
  1247. return Array(false, false, false, $lt, $gt);
  1248. }
  1249. break;
  1250. }
  1251. /**
  1252. * At this point we're here:
  1253. * <tagname attribute='blah'>
  1254. * \-------^
  1255. *
  1256. * At this point we loop in order to find all attributes.
  1257. */
  1258. $attname = '';
  1259. $atttype = false;
  1260. $attary = Array();
  1261. while ($pos <= strlen($body)){
  1262. $pos = sq_skipspace($body, $pos);
  1263. if ($pos == strlen($body)){
  1264. /**
  1265. * Non-closed tag.
  1266. */
  1267. return Array(false, false, false, $lt, $pos);
  1268. }
  1269. /**
  1270. * See if we arrived at a ">" or "/>", which means that we reached
  1271. * the end of the tag.
  1272. */
  1273. $matches = Array();
  1274. if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
  1275. /**
  1276. * Yep. So we did.
  1277. */
  1278. $pos += strlen($matches{1});
  1279. if ($matches{2} == "/>"){
  1280. $tagtype = 3;
  1281. $pos++;
  1282. }
  1283. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1284. }
  1285. /**
  1286. * There are several types of attributes, with optional
  1287. * [:space:] between members.
  1288. * Type 1:
  1289. * attrname[:space:]=[:space:]'CDATA'
  1290. * Type 2:
  1291. * attrname[:space:]=[:space:]"CDATA"
  1292. * Type 3:
  1293. * attr[:space:]=[:space:]CDATA
  1294. * Type 4:
  1295. * attrname
  1296. *
  1297. * We leave types 1 and 2 the same, type 3 we check for
  1298. * '"' and convert to "&quot" if needed, then wrap in
  1299. * double quotes. Type 4 we convert into:
  1300. * attrname="yes".
  1301. */
  1302. $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
  1303. if ($regary == false){
  1304. /**
  1305. * Looks like body ended before the end of tag.
  1306. */
  1307. return Array(false, false, false, $lt, strlen($body));
  1308. }
  1309. list($pos, $attname, $match) = $regary;
  1310. $attname = strtolower($attname);
  1311. /**
  1312. * We arrived at the end of attribute name. Several things possible
  1313. * here:
  1314. * '>' means the end of the tag and this is attribute type 4
  1315. * '/' if followed by '>' means the same thing as above
  1316. * '\s' means a lot of things -- look what it's followed by.
  1317. * anything else means the attribute is invalid.
  1318. */
  1319. switch($match){
  1320. case '/':
  1321. /**
  1322. * This is an xhtml-style tag with a closing / at the
  1323. * end, like so: <img src="blah" />. Check if it's followed
  1324. * by the closing bracket. If not, then this tag is invalid
  1325. */
  1326. if (substr($body, $pos, 2) == "/>"){
  1327. $pos++;
  1328. $tagtype = 3;
  1329. } else {
  1330. $gt = sq_findnxstr($body, $pos, ">");
  1331. $retary = Array(false, false, false, $lt, $gt);
  1332. return $retary;
  1333. }
  1334. case '>':
  1335. $attary{$attname} = '"yes"';
  1336. return Array($tagname, $attary, $tagtype, $lt, $pos);
  1337. break;
  1338. default:
  1339. /**
  1340. * Skip whitespace and see what we arrive at.
  1341. */
  1342. $pos = sq_skipspace($body, $pos);
  1343. $char = substr($body, $pos, 1);
  1344. /**
  1345. * Two things are valid here:
  1346. * '=' means this is attribute type 1 2 or 3.
  1347. * \w means this was attribute type 4.
  1348. * anything else we ignore and re-loop. End of tag and
  1349. * invalid stuff will be caught by our checks at the beginning
  1350. * of the loop.
  1351. */
  1352. if ($char == "="){
  1353. $pos++;
  1354. $pos = sq_skipspace($body, $pos);
  1355. /**
  1356. * Here are 3 possibilities:
  1357. * "'" attribute type 1
  1358. * '"' attribute type 2
  1359. * everything else is the content of tag type 3
  1360. */
  1361. $quot = substr($body, $pos, 1);
  1362. if ($quot == "'"){
  1363. $regary = sq_findnxreg($body, $pos+1, "\'");
  1364. if ($regary == false){
  1365. return Array(false, false, false, $lt, strlen($body));
  1366. }
  1367. list($pos, $attval, $match) = $regary;
  1368. $pos++;
  1369. $attary{$attname} = "'" . $attval . "'";
  1370. } else if ($quot == '"'){
  1371. $regary = sq_findnxreg($body, $pos+1, '\"');
  1372. if ($regary == false){
  1373. return Array(false, false, false, $lt, strlen($body));
  1374. }
  1375. list($pos, $attval, $match) = $regary;
  1376. $pos++;
  1377. $attary{$attname} = '"' . $attval . '"';
  1378. } else {
  1379. /**
  1380. * These are hateful. Look for \s, or >.
  1381. */
  1382. $regary = sq_findnxreg($body, $pos, "[\s>]");
  1383. if ($regary == false){
  1384. return Array(false, false, false, $lt, strlen($body));
  1385. }
  1386. list($pos, $attval, $match) = $regary;
  1387. /**
  1388. * If it's ">" it will be caught at the top.
  1389. */
  1390. $attval = preg_replace("/\"/s", "&quot;", $attval);
  1391. $attary{$attname} = '"' . $attval . '"';
  1392. }
  1393. } else if (preg_match("|[\w/>]|", $char)) {
  1394. /**
  1395. * That was attribute type 4.
  1396. */
  1397. $attary{$attname} = '"yes"';
  1398. } else {
  1399. /**
  1400. * An illegal character. Find next '>' and return.
  1401. */
  1402. $gt = sq_findnxstr($body, $pos, ">");
  1403. return Array(false, false, false, $lt, $gt);
  1404. }
  1405. break;
  1406. }
  1407. }
  1408. /**
  1409. * The fact that we got here indicates that the tag end was never
  1410. * found. Return invalid tag indication so it gets stripped.
  1411. */
  1412. return Array(false, false, false, $lt, strlen($body));
  1413. }
  1414. /**
  1415. * Translates entities into literal values so they can be checked.
  1416. *
  1417. * @param $attvalue the by-ref value to check.
  1418. * @param $regex the regular expression to check against.
  1419. * @param $hex whether the entites are hexadecimal.
  1420. * @return True or False depending on whether there were matches.
  1421. */
  1422. function sq_deent(&$attvalue, $regex, $hex=false){
  1423. $me = 'sq_deent';
  1424. $ret_match = false;
  1425. preg_match_all($regex, $attvalue, $matches);
  1426. if (is_array($matches) && sizeof($matches[0]) > 0){
  1427. $repl = Array();
  1428. for ($i = 0; $i < sizeof($matches[0]); $i++){
  1429. $numval = $matches[1][$i];
  1430. if ($hex){
  1431. $numval = hexdec($numval);
  1432. }
  1433. $repl{$matches[0][$i]} = chr($numval);
  1434. }
  1435. $attvalue = strtr($attvalue, $repl);
  1436. return true;
  1437. } else {
  1438. return false;
  1439. }
  1440. }
  1441. /**
  1442. * This function runs various checks against the attributes.
  1443. *
  1444. * @param $tagname String with the name of the tag.
  1445. * @param $attary Array with all tag attributes.
  1446. * @param $rm_attnames See description for sq_sanitize
  1447. * @param $bad_attvals See description for sq_sanitize
  1448. * @param $add_attr_to_tag See description for sq_sanitize
  1449. * @param $message message object
  1450. * @param $id message id
  1451. * @return Array with modified attributes.
  1452. */
  1453. function sq_fixatts($tagname,
  1454. $attary,
  1455. $rm_attnames,
  1456. $bad_attvals,
  1457. $add_attr_to_tag,
  1458. $message,
  1459. $id,
  1460. $mailbox
  1461. ){
  1462. $me = 'sq_fixatts';
  1463. while (list($attname, $attvalue) = each($attary)){
  1464. /**
  1465. * See if this attribute should be removed.
  1466. */
  1467. foreach ($rm_attnames as $matchtag=>$matchattrs){
  1468. if (preg_match($matchtag, $tagname)){
  1469. foreach ($matchattrs as $matchattr){
  1470. if (preg_match($matchattr, $attname)){
  1471. unset($attary{$attname});
  1472. continue;
  1473. }
  1474. }
  1475. }
  1476. }
  1477. /**
  1478. * Remove any backslashes, entities, and extraneous whitespace.
  1479. */
  1480. sq_defang($attvalue);
  1481. sq_unspace($attvalue);
  1482. /**
  1483. * Now let's run checks on the attvalues.
  1484. * I don't expect anyone to comprehend this. If you do,
  1485. * get in touch with me so I can drive to where you live and
  1486. * shake your hand personally. :)
  1487. */
  1488. foreach ($bad_attvals as $matchtag=>$matchattrs){
  1489. if (preg_match($matchtag, $tagname)){
  1490. foreach ($matchattrs as $matchattr=>$valary){
  1491. if (preg_match($matchattr, $attname)){
  1492. /**
  1493. * There are two arrays in valary.
  1494. * First is matches.
  1495. * Second one is replacements
  1496. */
  1497. list($valmatch, $valrepl) = $valary;
  1498. $newvalue =
  1499. preg_replace($valmatch, $valrepl, $attvalue);
  1500. if ($newvalue != $attvalue){
  1501. $attary{$attname} = $newvalue;
  1502. }
  1503. }
  1504. }
  1505. }
  1506. }
  1507. /**
  1508. * Replace empty src tags with the blank image. src is only used
  1509. * for frames, images, and image inputs. Doing a replace should
  1510. * not affect them working as should be, however it will stop
  1511. * IE from being kicked off when src for img tags are not set
  1512. */
  1513. if (($attname == 'src') && ($attvalue == '""')) {
  1514. $attary{$attname} = '"' . SM_PATH . 'images/blank.png"';
  1515. }
  1516. /**
  1517. * Turn cid: urls into http-friendly ones.
  1518. */
  1519. if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
  1520. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1521. }
  1522. /**
  1523. * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
  1524. * One day MS might actually make it match something useful, for now, falling
  1525. * back to using cid2http, so we can grab the blank.png.
  1526. */
  1527. if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
  1528. $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
  1529. }
  1530. }
  1531. /**
  1532. * See if we need to append any attributes to this tag.
  1533. */
  1534. foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1535. if (preg_match($matchtag, $tagname)){
  1536. $attary = array_merge($attary, $addattary);
  1537. }
  1538. }
  1539. return $attary;
  1540. }
  1541. /**
  1542. * This function edits the style definition to make them friendly and
  1543. * usable in SquirrelMail.
  1544. *
  1545. * @param $message the message object
  1546. * @param $id the message id
  1547. * @param $content a string with whatever is between <style> and </style>
  1548. * @param $mailbox the message mailbox
  1549. * @return a string with edited content.
  1550. */
  1551. function sq_fixstyle($body, $pos, $message, $id, $mailbox){
  1552. global $view_unsafe_images;
  1553. $me = 'sq_fixstyle';
  1554. $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
  1555. if ($ret == FALSE){
  1556. return array(FALSE, strlen($body));
  1557. }
  1558. $newpos = $ret[0] + strlen($ret[2]);
  1559. $content = $ret[1];
  1560. /**
  1561. * First look for general BODY style declaration, which would be
  1562. * like so:
  1563. * body {background: blah-blah}
  1564. * and change it to .bodyclass so we can just assign it to a <div>
  1565. */
  1566. $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
  1567. $secremoveimg = '../images/' . _("sec_remove_eng.png");
  1568. /**
  1569. * Fix url('blah') declarations.
  1570. */
  1571. // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
  1572. // "url(\\1$secremoveimg\\2)", $content);
  1573. // remove NUL
  1574. $content = str_replace("\0", "", $content);
  1575. // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
  1576. while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
  1577. $sProto = strtolower($matches[1]);
  1578. switch ($sProto) {
  1579. /**
  1580. * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1581. * is false.
  1582. */
  1583. case 'https':
  1584. case 'http':
  1585. if (!$view_unsafe_images){
  1586. $sExpr = "/url\s*\(\s*[\'\"]?\s*$sProto*:.*[\'\"]?\s*\)/si";
  1587. $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
  1588. } else {
  1589. $content = preg_replace('/url/i',"u\0r\0l",$content);
  1590. }
  1591. break;
  1592. /**
  1593. * Fix urls that refer to cid:
  1594. */
  1595. case 'cid':
  1596. $cidurl = 'cid:'. $matches[2];
  1597. $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
  1598. // escape parentheses that can modify the regular expression
  1599. $cidurl = str_replace(array('(',')'),array('\\(','\\)'),$cidurl);
  1600. $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
  1601. "u\0r\0l($httpurl)", $content);
  1602. break;
  1603. default:
  1604. /**
  1605. * replace url with protocol other then the white list
  1606. * http,https and cid by an empty string.
  1607. */
  1608. $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
  1609. "", $content);
  1610. break;
  1611. }
  1612. }
  1613. // remove NUL
  1614. $content = str_replace("\0", "", $content);
  1615. /**
  1616. * Remove any backslashes, entities, and extraneous whitespace.
  1617. */
  1618. $contentTemp = $content;
  1619. sq_defang($contentTemp);
  1620. sq_unspace($contentTemp);
  1621. /**
  1622. * Fix stupid css declarations which lead to vulnerabilities
  1623. * in IE.
  1624. */
  1625. $match = Array('/\/\*.*\*\//',
  1626. '/expression/i',
  1627. '/behaviou*r/i',
  1628. '/binding/i',
  1629. '/include-source/i');
  1630. $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy');
  1631. $contentNew = preg_replace($match, $replace, $contentTemp);
  1632. if ($contentNew !== $contentTemp) {
  1633. // insecure css declarations are used. From now on we don't care
  1634. // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
  1635. $content = $contentNew;
  1636. }
  1637. return array($content, $newpos);
  1638. }
  1639. /**
  1640. * This function converts cid: url's into the ones that can be viewed in
  1641. * the browser.
  1642. *
  1643. * @param $message the message object
  1644. * @param $id the message id
  1645. * @param $cidurl the cid: url.
  1646. * @param $mailbox the message mailbox
  1647. * @return a string with a http-friendly url
  1648. */
  1649. function sq_cid2http($message, $id, $cidurl, $mailbox){
  1650. /**
  1651. * Get rid of quotes.
  1652. */
  1653. $quotchar = substr($cidurl, 0, 1);
  1654. if ($quotchar == '"' || $quotchar == "'"){
  1655. $cidurl = str_replace($quotchar, "", $cidurl);
  1656. } else {
  1657. $quotchar = '';
  1658. }
  1659. $cidurl = substr(trim($cidurl), 4);
  1660. $match_str = '/\{.*?\}\//';
  1661. $str_rep = '';
  1662. $cidurl = preg_replace($match_str, $str_rep, $cidurl);
  1663. $linkurl = find_ent_id($cidurl, $message);
  1664. /* in case of non-save cid links $httpurl should be replaced by a sort of
  1665. unsave link image */
  1666. $httpurl = '';
  1667. /**
  1668. * This is part of a fix for Outlook Express 6.x generating
  1669. * cid URLs without creating content-id headers. These images are
  1670. * not part of the multipart/related html mail. The html contains
  1671. * <img src="cid:{some_id}/image_filename.ext"> references to
  1672. * attached images with as goal to render them inline although
  1673. * the attachment disposition property is not inline.
  1674. */
  1675. if (empty($linkurl)) {
  1676. if (preg_match('/{.*}\//', $cidurl)) {
  1677. $cidurl = preg_replace('/{.*}\//','', $cidurl);
  1678. if (!empty($cidurl)) {
  1679. $linkurl = find_ent_id($cidurl, $message);
  1680. }
  1681. }
  1682. }
  1683. if (!empty($linkurl)) {
  1684. $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
  1685. "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
  1686. '&amp;ent_id=' . $linkurl . $quotchar;
  1687. } else {
  1688. /**
  1689. * If we couldn't generate a proper img url, drop in a blank image
  1690. * instead of sending back empty, otherwise it causes unusual behaviour
  1691. */
  1692. $httpurl = $quotchar . SM_PATH . 'images/blank.png' . $quotchar;
  1693. }
  1694. return $httpurl;
  1695. }
  1696. /**
  1697. * This function changes the <body> tag into a <div> tag since we
  1698. * can't really have a body-within-body.
  1699. *
  1700. * @param $attary an array of attributes and values of <body>
  1701. * @param $mailbox mailbox we're currently reading (for cid2http)
  1702. * @param $message current message (for cid2http)
  1703. * @param $id current message id (for cid2http)
  1704. * @return a modified array of attributes to be set for <div>
  1705. */
  1706. function sq_body2div($attary, $mailbox, $message, $id){
  1707. $me = 'sq_body2div';
  1708. $divattary = Array('class' => "'bodyclass'");
  1709. $text = '#000000';
  1710. $has_bgc_stl = $has_txt_stl = false;
  1711. $styledef = '';
  1712. if (is_array($attary) && sizeof($attary) > 0){
  1713. foreach ($attary as $attname=>$attvalue){
  1714. $quotchar = substr($attvalue, 0, 1);
  1715. $attvalue = str_replace($quotchar, "", $attvalue);
  1716. switch ($attname){
  1717. case 'background':
  1718. $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
  1719. $styledef .= "background-image: url('$attvalue'); ";
  1720. break;
  1721. case 'bgcolor':
  1722. $has_bgc_stl = true;
  1723. $styledef .= "background-color: $attvalue; ";
  1724. break;
  1725. case 'text':
  1726. $has_txt_stl = true;
  1727. $styledef .= "color: $attvalue; ";
  1728. break;
  1729. }
  1730. }
  1731. // Outlook defines a white bgcolor and no text color. This can lead to
  1732. // white text on a white bg with certain themes.
  1733. if ($has_bgc_stl && !$has_txt_stl) {
  1734. $styledef .= "color: $text; ";
  1735. }
  1736. if (strlen($styledef) > 0){
  1737. $divattary{"style"} = "\"$styledef\"";
  1738. }
  1739. }
  1740. return $divattary;
  1741. }
  1742. /**
  1743. * This is the main function and the one you should actually be calling.
  1744. * There are several variables you should be aware of an which need
  1745. * special description.
  1746. *
  1747. * Since the description is quite lengthy, see it here:
  1748. * http://linux.duke.edu/projects/mini/htmlfilter/
  1749. *
  1750. * @param $body the string with HTML you wish to filter
  1751. * @param $tag_list see description above
  1752. * @param $rm_tags_with_content see description above
  1753. * @param $self_closing_tags see description above
  1754. * @param $force_tag_closing see description above
  1755. * @param $rm_attnames see description above
  1756. * @param $bad_attvals see description above
  1757. * @param $add_attr_to_tag see description above
  1758. * @param $message message object
  1759. * @param $id message id
  1760. * @return sanitized html safe to show on your pages.
  1761. */
  1762. function sq_sanitize($body,
  1763. $tag_list,
  1764. $rm_tags_with_content,
  1765. $self_closing_tags,
  1766. $force_tag_closing,
  1767. $rm_attnames,
  1768. $bad_attvals,
  1769. $add_attr_to_tag,
  1770. $message,
  1771. $id,
  1772. $mailbox
  1773. ){
  1774. $me = 'sq_sanitize';
  1775. $rm_tags = array_shift($tag_list);
  1776. /**
  1777. * Normalize rm_tags and rm_tags_with_content.
  1778. */
  1779. @array_walk($tag_list, 'sq_casenormalize');
  1780. @array_walk($rm_tags_with_content, 'sq_casenormalize');
  1781. @array_walk($self_closing_tags, 'sq_casenormalize');
  1782. /**
  1783. * See if tag_list is of tags to remove or tags to allow.
  1784. * false means remove these tags
  1785. * true means allow these tags
  1786. */
  1787. $curpos = 0;
  1788. $open_tags = Array();
  1789. $trusted = "\n<!-- begin sanitized html -->\n";
  1790. $skip_content = false;
  1791. /**
  1792. * Take care of netscape's stupid javascript entities like
  1793. * &{alert('boo')};
  1794. */
  1795. $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
  1796. while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
  1797. list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
  1798. $free_content = substr($body, $curpos, $lt-$curpos);
  1799. /**
  1800. * Take care of <style>
  1801. */
  1802. if ($tagname == "style" && $tagtype == 1){
  1803. list($free_content, $curpos) =
  1804. sq_fixstyle($body, $gt+1, $message, $id, $mailbox);
  1805. if ($free_content != FALSE){
  1806. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1807. $trusted .= $free_content;
  1808. $trusted .= sq_tagprint($tagname, false, 2);
  1809. }
  1810. continue;
  1811. }
  1812. if ($skip_content == false){
  1813. $trusted .= $free_content;
  1814. }
  1815. if ($tagname != FALSE){
  1816. if ($tagtype == 2){
  1817. if ($skip_content == $tagname){
  1818. /**
  1819. * Got to the end of tag we needed to remove.
  1820. */
  1821. $tagname = false;
  1822. $skip_content = false;
  1823. } else {
  1824. if ($skip_content == false){
  1825. if ($tagname == "body"){
  1826. $tagname = "div";
  1827. }
  1828. if (isset($open_tags{$tagname}) &&
  1829. $open_tags{$tagname} > 0){
  1830. $open_tags{$tagname}--;
  1831. } else {
  1832. $tagname = false;
  1833. }
  1834. }
  1835. }
  1836. } else {
  1837. /**
  1838. * $rm_tags_with_content
  1839. */
  1840. if ($skip_content == false){
  1841. /**
  1842. * See if this is a self-closing type and change
  1843. * tagtype appropriately.
  1844. */
  1845. if ($tagtype == 1
  1846. && in_array($tagname, $self_closing_tags)){
  1847. $tagtype = 3;
  1848. }
  1849. /**
  1850. * See if we should skip this tag and any content
  1851. * inside it.
  1852. */
  1853. if ($tagtype == 1 &&
  1854. in_array($tagname, $rm_tags_with_content)){
  1855. $skip_content = $tagname;
  1856. } else {
  1857. if (($rm_tags == false
  1858. && in_array($tagname, $tag_list)) ||
  1859. ($rm_tags == true &&
  1860. !in_array($tagname, $tag_list))){
  1861. $tagname = false;
  1862. } else {
  1863. /**
  1864. * Convert body into div.
  1865. */
  1866. if ($tagname == "body"){
  1867. $tagname = "div";
  1868. $attary = sq_body2div($attary, $mailbox,
  1869. $message, $id);
  1870. }
  1871. if ($tagtype == 1){
  1872. if (isset($open_tags{$tagname})){
  1873. $open_tags{$tagname}++;
  1874. } else {
  1875. $open_tags{$tagname}=1;
  1876. }
  1877. }
  1878. /**
  1879. * This is where we run other checks.
  1880. */
  1881. if (is_array($attary) && sizeof($attary) > 0){
  1882. $attary = sq_fixatts($tagname,
  1883. $attary,
  1884. $rm_attnames,
  1885. $bad_attvals,
  1886. $add_attr_to_tag,
  1887. $message,
  1888. $id,
  1889. $mailbox
  1890. );
  1891. }
  1892. }
  1893. }
  1894. }
  1895. }
  1896. if ($tagname != false && $skip_content == false){
  1897. $trusted .= sq_tagprint($tagname, $attary, $tagtype);
  1898. }
  1899. }
  1900. $curpos = $gt+1;
  1901. }
  1902. $trusted .= substr($body, $curpos, strlen($body)-$curpos);
  1903. if ($force_tag_closing == true){
  1904. foreach ($open_tags as $tagname=>$opentimes){
  1905. while ($opentimes > 0){
  1906. $trusted .= '</' . $tagname . '>';
  1907. $opentimes--;
  1908. }
  1909. }
  1910. $trusted .= "\n";
  1911. }
  1912. $trusted .= "<!-- end sanitized html -->\n";
  1913. return $trusted;
  1914. }
  1915. /**
  1916. * This is a wrapper function to call html sanitizing routines.
  1917. *
  1918. * @param $body the body of the message
  1919. * @param $id the id of the message
  1920. * @param $message
  1921. * @param $mailbox
  1922. * @param boolean $take_mailto_links When TRUE, converts mailto: links
  1923. * into internal SM compose links
  1924. * (optional; default = TRUE)
  1925. * @return a string with html safe to display in the browser.
  1926. */
  1927. function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
  1928. require_once(SM_PATH . 'functions/url_parser.php'); // for $MailTo_PReg_Match
  1929. global $attachment_common_show_images, $view_unsafe_images,
  1930. $has_unsafe_images;
  1931. /**
  1932. * Don't display attached images in HTML mode.
  1933. */
  1934. $attachment_common_show_images = false;
  1935. $tag_list = Array(
  1936. false,
  1937. "object",
  1938. "meta",
  1939. "html",
  1940. "head",
  1941. "base",
  1942. "link",
  1943. "frame",
  1944. "iframe",
  1945. "plaintext",
  1946. "marquee"
  1947. );
  1948. $rm_tags_with_content = Array(
  1949. "script",
  1950. "applet",
  1951. "embed",
  1952. "title",
  1953. "frameset",
  1954. "xmp",
  1955. "xml"
  1956. );
  1957. $self_closing_tags = Array(
  1958. "img",
  1959. "br",
  1960. "hr",
  1961. "input",
  1962. "outbind"
  1963. );
  1964. $force_tag_closing = true;
  1965. $rm_attnames = Array(
  1966. "/.*/" =>
  1967. Array(
  1968. "/target/i",
  1969. "/^on.*/i",
  1970. "/^dynsrc/i",
  1971. "/^data.*/i",
  1972. "/^lowsrc.*/i"
  1973. )
  1974. );
  1975. $secremoveimg = "../images/" . _("sec_remove_eng.png");
  1976. $bad_attvals = Array(
  1977. "/.*/" =>
  1978. Array(
  1979. "/^src|background/i" =>
  1980. Array(
  1981. Array(
  1982. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1983. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1984. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1985. ),
  1986. Array(
  1987. "\\1$secremoveimg\\2",
  1988. "\\1$secremoveimg\\2",
  1989. "\\1$secremoveimg\\2",
  1990. )
  1991. ),
  1992. "/^href|action/i" =>
  1993. Array(
  1994. Array(
  1995. "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  1996. "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  1997. "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  1998. ),
  1999. Array(
  2000. "\\1#\\1",
  2001. "\\1#\\1",
  2002. "\\1#\\1"
  2003. )
  2004. ),
  2005. "/^style/i" =>
  2006. Array(
  2007. Array(
  2008. "/\/\*.*\*\//",
  2009. "/expression/i",
  2010. "/binding/i",
  2011. "/behaviou*r/i",
  2012. "/include-source/i",
  2013. "/position\s*:\s*absolute/i",
  2014. "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  2015. "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  2016. "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
  2017. "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
  2018. ),
  2019. Array(
  2020. "",
  2021. "idiocy",
  2022. "idiocy",
  2023. "idiocy",
  2024. "idiocy",
  2025. "",
  2026. "url(\\1#\\1)",
  2027. "url(\\1#\\1)",
  2028. "url(\\1#\\1)",
  2029. "\\1:url(\\2#\\3)"
  2030. )
  2031. )
  2032. )
  2033. );
  2034. if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
  2035. $view_unsafe_images = false;
  2036. }
  2037. if (!$view_unsafe_images){
  2038. /**
  2039. * Remove any references to http/https if view_unsafe_images set
  2040. * to false.
  2041. */
  2042. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  2043. '/^([\'\"])\s*https*:.*([\'\"])/si');
  2044. array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  2045. "\\1$secremoveimg\\1");
  2046. array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  2047. '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
  2048. array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  2049. "url(\\1$secremoveimg\\1)");
  2050. }
  2051. $add_attr_to_tag = Array(
  2052. "/^a$/i" =>
  2053. Array('target'=>'"_blank"',
  2054. 'title'=>'"'._("This external link will open in a new window").'"'
  2055. )
  2056. );
  2057. $trusted = sq_sanitize($body,
  2058. $tag_list,
  2059. $rm_tags_with_content,
  2060. $self_closing_tags,
  2061. $force_tag_closing,
  2062. $rm_attnames,
  2063. $bad_attvals,
  2064. $add_attr_to_tag,
  2065. $message,
  2066. $id,
  2067. $mailbox
  2068. );
  2069. if (preg_match("|$secremoveimg|i", $trusted)){
  2070. $has_unsafe_images = true;
  2071. }
  2072. // we want to parse mailto's in HTML output, change to SM compose links
  2073. // this is a modified version of code from url_parser.php... but Marc is
  2074. // right: we need a better filtering implementation; adding this randomly
  2075. // here is not a great solution
  2076. //
  2077. if ($take_mailto_links) {
  2078. // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
  2079. global $MailTo_PReg_Match;
  2080. $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
  2081. if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
  2082. foreach ($regs[0] as $i => $mailto_before) {
  2083. $mailto_params = $regs[10][$i];
  2084. // get rid of any tailing quote since we have to add send_to to the end
  2085. //
  2086. if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
  2087. $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
  2088. if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
  2089. $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
  2090. if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
  2091. $to = 'to=' . $regs[1][$i];
  2092. if (strpos($mailto_params, 'to=') > -1) //already a 'to='
  2093. $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
  2094. else {
  2095. if ($mailto_params) //already some params, append to them
  2096. $mailto_params .= '&amp;' . $to;
  2097. else
  2098. $mailto_params .= '?' . $to;
  2099. }
  2100. }
  2101. $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
  2102. // we'll already have target=_blank, no need to allow comp_in_new
  2103. // here (which would be a lot more work anyway)
  2104. //
  2105. global $compose_new_win;
  2106. $temp_comp_in_new = $compose_new_win;
  2107. $compose_new_win = 0;
  2108. $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
  2109. $compose_new_win = $temp_comp_in_new;
  2110. // remove <a href=" and anything after the next quote (we only
  2111. // need the uri, not the link HTML) in compose uri
  2112. //
  2113. $comp_uri = substr($comp_uri, 9);
  2114. $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
  2115. $trusted = str_replace($mailto_before, $comp_uri, $trusted);
  2116. }
  2117. }
  2118. }
  2119. return $trusted;
  2120. }
  2121. /**
  2122. * function SendDownloadHeaders - send file to the browser
  2123. *
  2124. * Original Source: SM core src/download.php
  2125. * moved here to make it available to other code, and separate
  2126. * front end from back end functionality.
  2127. *
  2128. * @param string $type0 first half of mime type
  2129. * @param string $type1 second half of mime type
  2130. * @param string $filename filename to tell the browser for downloaded file
  2131. * @param boolean $force whether to force the download dialog to pop
  2132. * @param optional integer $filesize send the Content-Header and length to the browser
  2133. * @return void
  2134. */
  2135. function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
  2136. global $languages, $squirrelmail_language;
  2137. $isIE = $isIE6plus = false;
  2138. sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
  2139. if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
  2140. strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2141. $isIE = true;
  2142. }
  2143. if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
  2144. ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
  2145. $isIE6plus = true;
  2146. }
  2147. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  2148. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
  2149. $filename =
  2150. call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
  2151. } else {
  2152. $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace('&nbsp;', ' ', $filename));
  2153. }
  2154. // A Pox on Microsoft and it's Internet Explorer!
  2155. //
  2156. // IE has lots of bugs with file downloads.
  2157. // It also has problems with SSL. Both of these cause problems
  2158. // for us in this function.
  2159. //
  2160. // See this article on Cache Control headers and SSL
  2161. // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
  2162. //
  2163. // The best thing you can do for IE is to upgrade to the latest
  2164. // version
  2165. //set all the Cache Control Headers for IE
  2166. if ($isIE) {
  2167. $filename=rawurlencode($filename);
  2168. header ("Pragma: public");
  2169. header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
  2170. header ("Cache-Control: post-check=0, pre-check=0", false);
  2171. header ("Cache-Control: private");
  2172. //set the inline header for IE, we'll add the attachment header later if we need it
  2173. header ("Content-Disposition: inline; filename=$filename");
  2174. }
  2175. if (!$force) {
  2176. // Try to show in browser window
  2177. header ("Content-Disposition: inline; filename=\"$filename\"");
  2178. header ("Content-Type: $type0/$type1; name=\"$filename\"");
  2179. } else {
  2180. // Try to pop up the "save as" box
  2181. // IE makes this hard. It pops up 2 save boxes, or none.
  2182. // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
  2183. // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
  2184. // But, according to Microsoft, it is "RFC compliant but doesn't
  2185. // take into account some deviations that allowed within the
  2186. // specification." Doesn't that mean RFC non-compliant?
  2187. // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
  2188. // all browsers need the application/octet-stream header for this
  2189. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2190. // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
  2191. // Do not have quotes around filename, but that applied to
  2192. // "attachment"... does it apply to inline too?
  2193. header ("Content-Disposition: attachment; filename=\"$filename\"");
  2194. if ($isIE && !$isIE6plus) {
  2195. // This combination seems to work mostly. IE 5.5 SP 1 has
  2196. // known issues (see the Microsoft Knowledge Base)
  2197. // This works for most types, but doesn't work with Word files
  2198. header ("Content-Type: application/download; name=\"$filename\"");
  2199. // These are spares, just in case. :-)
  2200. //header("Content-Type: $type0/$type1; name=\"$filename\"");
  2201. //header("Content-Type: application/x-msdownload; name=\"$filename\"");
  2202. //header("Content-Type: application/octet-stream; name=\"$filename\"");
  2203. } else {
  2204. // another application/octet-stream forces download for Netscape
  2205. header ("Content-Type: application/octet-stream; name=\"$filename\"");
  2206. }
  2207. }
  2208. //send the content-length header if the calling function provides it
  2209. if ($filesize > 0) {
  2210. header("Content-Length: $filesize");
  2211. }
  2212. } // end fn SendDownloadHeaders
  2213. ?>