PageRenderTime 35ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/webmail-release-1_4_22/functions/mime.php

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