PageRenderTime 64ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

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