PageRenderTime 65ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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