PageRenderTime 63ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

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