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

/tags/rel-1_4_17/functions/mime.php

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