6 * Copyright (c) 1999-2004 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains the functions necessary to detect and decode MIME
13 * @package squirrelmail
16 /** The typical includes... */
17 require_once(SM_PATH
. 'functions/imap.php');
18 require_once(SM_PATH
. 'functions/attachment_common.php');
20 /* -------------------------------------------------------------------------- */
22 /* -------------------------------------------------------------------------- */
25 * Get the MIME structure
27 * This function gets the structure of a message and stores it in the "message" class.
28 * It will return this object for use with all relevant header information and
29 * fully parsed into the standard "message" object format.
31 function mime_structure ($bodystructure, $flags=array()) {
33 /* Isolate the body structure and remove beginning and end parenthesis. */
34 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
35 $read = trim(substr ($read, 0, -1));
37 $msg = Message
::parseStructure($read,$i);
38 if (!is_object($msg)) {
39 include_once(SM_PATH
. 'functions/display_messages.php');
40 global $color, $mailbox;
41 /* removed urldecode because $_GET is auto urldecoded ??? */
42 displayPageHeader( $color, $mailbox );
43 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
44 $errormessage .= '<br />'._("the provided bodystructure by your imap-server").':<br /><br />';
45 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
46 plain_error_message( $errormessage, $color );
47 echo '</body></html>';
51 foreach ($flags as $flag) {
52 $char = strtoupper($flag{1});
55 if (strtolower($flag) == '\\seen') {
60 if (strtolower($flag) == '\\answered') {
61 $msg->is_answered
= true;
65 if (strtolower($flag) == '\\deleted') {
66 $msg->is_deleted
= true;
70 if (strtolower($flag) == '\\flagged') {
71 $msg->is_flagged
= true;
75 if (strtolower($flag) == '$mdnsent') {
76 $msg->is_mdnsent
= true;
84 // listEntities($msg);
90 /* This starts the parsing of a particular structure. It is called recursively,
91 * so it can be passed different structures. It returns an object of type
93 * First, it checks to see if it is a multipart message. If it is, then it
94 * handles that as it sees is necessary. If it is just a regular entity,
95 * then it parses it and adds the necessary header information (by calling out
96 * to mime_get_elements()
99 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
100 /* Do a bit of error correction. If we couldn't find the entity id, just guess
101 * that it is the first one. That is usually the case anyway.
105 $cmd = "FETCH $id BODY[]";
107 $cmd = "FETCH $id BODY[$ent_id]";
110 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
112 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
114 $topline = trim(array_shift($data));
115 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
117 $wholemessage = implode('', $data);
118 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
119 $ret = substr($wholemessage, 0, $regs[1]);
120 /* There is some information in the content info header that could be important
121 * in order to parse html messages. Let's get them here.
123 // if ($ret{0} == '<') {
124 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
126 } else if (ereg('"([^"]*)"', $topline, $regs)) {
129 global $where, $what, $mailbox, $passed_id, $startMessage;
130 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
131 if (isset($where) && isset($what)) {
132 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
134 $par .= '&startMessage=' . $startMessage . '&show_more=0';
136 $par .= '&response=' . urlencode($response) .
137 '&message=' . urlencode($message) .
138 '&topline=' . urlencode($topline);
141 '<table width="80%"><tr>' .
142 '<tr><td colspan="2">' .
143 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
145 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
146 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
147 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
148 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
149 "</table><br /></tt></font><hr />";
151 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
153 $wholemessage = implode('', $data);
155 $ret = $wholemessage;
160 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
162 /* Don't kill the connection if the browser is over a dialup
163 * and it would take over 30 seconds to download it.
164 * Don't call set_time_limit in safe mode.
167 if (!ini_get('safe_mode')) {
170 /* in case of base64 encoded attachments, do not buffer them.
171 Instead, echo the decoded attachment directly to screen */
172 if (strtolower($encoding) == 'base64') {
174 $query = "FETCH $id BODY[]";
176 $query = "FETCH $id BODY[$ent_id]";
178 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode','php://stdout',true);
180 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
181 echo decodeBody($body, $encoding);
185 TODO, use the same method for quoted printable.
186 However, I assume that quoted printable attachments aren't that large
187 so the performancegain / memory usage drop will be minimal.
188 If we decide to add that then we need to adapt sqimap_fread because
189 we need to split te result on \n and fread doesn't stop at \n. That
190 means we also should provide $results from sqimap_fread (by ref) to
191 te function and set $no_return to false. The $filter function for
192 quoted printable should handle unsetting of $results.
195 TODO 2: find out how we write to the output stream php://stdout. fwrite
196 doesn't work because 'php://stdout isn't a stream.
201 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
204 $read = fgets ($imap_stream,8192);
207 // This could be bad -- if the section has sqimap_session_id() . ' OK'
208 // or similar, it will kill the download.
209 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
210 if (trim($read) == ')==') {
212 $read = fgets ($imap_stream,4096);
213 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
216 echo decodeBody($read1, $encoding) .
217 decodeBody($read, $encoding);
220 echo decodeBody($read, $encoding);
222 $read = fgets ($imap_stream,4096);
229 /* -[ END MIME DECODING ]----------------------------------------------------------- */
231 /* This is here for debugging purposes. It will print out a list
232 * of all the entity IDs that are in the $message object.
234 function listEntities ($message) {
236 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
237 for ($i = 0; isset($message->entities
[$i]); $i++
) {
239 $msg = listEntities($message->entities
[$i]);
249 function getPriorityStr($priority) {
250 $priority_level = substr($priority,0,1);
252 switch($priority_level) {
253 /* Check for a higher then normal priority. */
256 $priority_string = _("High");
259 /* Check for a lower then normal priority. */
262 $priority_string = _("Low");
265 /* Check for a normal priority. */
268 $priority_level = '3';
269 $priority_string = _("Normal");
273 return $priority_string;
276 /* returns a $message object for a particular entity id */
277 function getEntity ($message, $ent_id) {
278 return $message->getEntity($ent_id);
282 * Extracted from strings.php 23/03/2002
285 function translateText(&$body, $wrap_at, $charset) {
286 global $where, $what; /* from searching */
287 global $color; /* color theme */
289 require_once(SM_PATH
. 'functions/url_parser.php');
291 $body_ary = explode("\n", $body);
292 for ($i=0; $i < count($body_ary); $i++
) {
293 $line = $body_ary[$i];
294 if (strlen($line) - 2 >= $wrap_at) {
295 sqWordWrap($line, $wrap_at);
297 $line = charset_decode($charset, $line);
298 $line = str_replace("\t", ' ', $line);
307 if ($line[$pos] == ' ') {
309 } else if (strpos($line, '>', $pos) === $pos) {
318 if (!isset($color[13])) {
319 $color[13] = '#800000';
321 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
323 if (!isset($color[14])) {
324 $color[14] = '#FF0000';
326 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
329 $body_ary[$i] = $line;
331 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
334 /* This returns a parsed string called $body. That string can then
335 * be displayed as the actual message in the HTML. It contains
336 * everything needed, including HTML Tags, Attachments at the
339 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
340 /* This if statement checks for the entity to show as the
341 * primary message. To add more of them, just put them in the
342 * order that is their priority.
344 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
345 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
346 global $languages, $squirrelmail_language;
348 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
349 $view_unsafe_images = false;
353 $urlmailbox = urlencode($mailbox);
354 $body_message = getEntity($message, $ent_num);
355 if (($body_message->header
->type0
== 'text') ||
356 ($body_message->header
->type0
== 'rfc822')) {
357 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
358 $body = decodeBody($body, $body_message->header
->encoding
);
360 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
361 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
362 if (mb_detect_encoding($body) != 'ASCII') {
363 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
366 $hookResults = do_hook("message_body", $body);
367 $body = $hookResults[1];
369 /* If there are other types that shouldn't be formatted, add
373 if ($body_message->header
->type1
== 'html') {
374 if ($show_html_default <> 1) {
375 $entity_conv = array(' ' => ' ',
384 $body = strtr($body, $entity_conv);
385 $body = strip_tags($body);
387 translateText($body, $wrap_at,
388 $body_message->header
->getParameter('charset'));
390 $body = magicHTML($body, $id, $message, $mailbox);
393 translateText($body, $wrap_at,
394 $body_message->header
->getParameter('charset'));
396 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
397 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
398 '&startMessage=' . $startMessage . '&show_more=0';
399 if (isset($passed_ent_id)) {
400 $link .= '&passed_ent_id='.$passed_ent_id;
402 $body .= '<center><small><a href="download.php?absolute_dl=true&' .
403 $link . '">' . _("Download this as a file") . '</a>';
404 if ($view_unsafe_images) {
405 $text = _("Hide Unsafe Images");
407 if (isset($has_unsafe_images) && $has_unsafe_images) {
408 $link .= '&view_unsafe_images=1';
409 $text = _("View Unsafe Images");
415 $body .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
417 $body .= '</small></center><br />' . "\n";
423 function formatAttachments($message, $exclude_id, $mailbox, $id) {
424 global $where, $what, $startMessage, $color;
425 static $ShownHTML = 0;
427 $att_ar = $message->getAttachments($exclude_id);
429 if (!count($att_ar)) return '';
433 $urlMailbox = urlencode($mailbox);
435 foreach ($att_ar as $att) {
436 $ent = $att->entity_id
;
437 $header = $att->header
;
438 $type0 = strtolower($header->type0
);
439 $type1 = strtolower($header->type1
);
441 $links['download link']['text'] = _("Download");
442 $links['download link']['href'] = SM_PATH
.
443 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
445 if ($type0 =='message' && $type1 == 'rfc822') {
446 $default_page = SM_PATH
. 'src/read_body.php';
447 $rfc822_header = $att->rfc822_header
;
448 $filename = $rfc822_header->subject
;
449 if (trim( $filename ) == '') {
450 $filename = 'untitled-[' . $ent . ']' ;
452 $from_o = $rfc822_header->from
;
453 if (is_object($from_o)) {
454 $from_name = decodeHeader($from_o->getAddress(false));
456 $from_name = _("Unknown sender");
458 $description = $from_name;
460 $default_page = SM_PATH
. 'src/download.php';
461 if (is_object($header->disposition
)) {
462 $filename = $header->disposition
->getProperty('filename');
463 if (trim($filename) == '') {
464 $name = decodeHeader($header->disposition
->getProperty('name'));
465 if (trim($name) == '') {
466 $name = $header->getParameter('name');
467 if(trim($name) == '') {
468 if (trim( $header->id
) == '') {
469 $filename = 'untitled-[' . $ent . ']' ;
471 $filename = 'cid: ' . $header->id
;
481 $filename = $header->getParameter('name');
482 if (!trim($filename)) {
483 if (trim( $header->id
) == '') {
484 $filename = 'untitled-[' . $ent . ']' ;
486 $filename = 'cid: ' . $header->id
;
490 if ($header->description
) {
491 $description = decodeHeader($header->description
);
497 $display_filename = $filename;
498 if (isset($passed_ent_id)) {
499 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
501 $passed_ent_id_link = '';
503 $defaultlink = $default_page . "?startMessage=$startMessage"
504 . "&passed_id=$id&mailbox=$urlMailbox"
505 . '&ent_id='.$ent.$passed_ent_id_link;
506 if ($where && $what) {
507 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
510 /* This executes the attachment hook with a specific MIME-type.
511 * If that doesn't have results, it tries if there's a rule
512 * for a more generic type.
514 $hookresults = do_hook("attachment $type0/$type1", $links,
515 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
516 $display_filename, $where, $what);
517 if(count($hookresults[1]) <= 1) {
518 $hookresults = do_hook("attachment $type0/*", $links,
519 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
520 $display_filename, $where, $what);
523 $links = $hookresults[1];
524 $defaultlink = $hookresults[6];
526 $attachments .= '<tr><td>' .
527 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
528 '<td><small><b>' . show_readable_size($header->size
) .
529 '</b> </small></td>' .
530 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
532 $attachments .= '<b>' . $description . '</b>';
533 $attachments .= '</small></td><td><small> ';
536 foreach ($links as $val) {
540 $attachments .= ' | ';
542 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
545 $attachments .= "</td></tr>\n";
547 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
548 if ($attachmentadd != '')
549 $attachments = $attachmentadd;
553 function sqimap_base64_decode(&$string) {
555 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
556 // fly decoding (to reduce memory usage) you have to check if the
557 // data has incomplete pairs
559 // Remove the noise in order to check if the 4 bytes pairs are complete
560 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
563 $iMod = strlen($string) %
4;
565 $sStringRem = substr($string,-$iMod);
566 // Check if $sStringRem contains padding characters
567 if (substr($sStringRem,-1) != '=') {
568 $string = substr($string,0,-$iMod);
573 $string = base64_decode($string);
578 /* This function decodes the body depending on the encoding type. */
579 function decodeBody($body, $encoding) {
580 global $show_html_default;
582 $body = str_replace("\r\n", "\n", $body);
583 $encoding = strtolower($encoding);
585 $encoding_handler = do_hook_function('decode_body', $encoding);
588 // plugins get first shot at decoding the body
590 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
591 $body = $encoding_handler('decode', $body);
593 } else if ($encoding == 'quoted-printable' ||
594 $encoding == 'quoted_printable') {
595 $body = quoted_printable_decode($body);
597 while (ereg("=\n", $body)) {
598 $body = ereg_replace ("=\n", '', $body);
601 } else if ($encoding == 'base64') {
602 $body = base64_decode($body);
605 // All other encodings are returned raw.
612 * This functions decode strings that is encoded according to
613 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
614 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
616 * @param string $string header string that has to be made readable
617 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
618 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
619 * @param boolean $decide decide if string can be utfencoded. defaults to false
620 * @return string decoded header string
622 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
623 global $languages, $squirrelmail_language,$default_charset;
624 if (is_array($string)) {
625 $string = implode("\n", $string);
628 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
629 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
630 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
631 // Do we need to return at this point?
638 $aString = explode(' ',$string);
640 foreach ($aString as $chunk) {
641 if ($encoded && $chunk === '') {
643 } elseif ($chunk === '') {
648 /* if encoded words are not separated by a linear-space-white we still catch them */
651 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
652 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
653 if ($iLastMatch !== $j) {
663 $ret .= htmlspecialchars($res[1]);
667 $encoding = ucfirst($res[3]);
669 /* decide about valid decoding */
670 if ($decide && is_conversion_safe($res[2])) {
672 $can_be_encoded=true;
674 $can_be_encoded=false;
679 $replace = base64_decode($res[4]);
680 if ($can_be_encoded) {
681 /* convert string to different charset,
682 * if functions asks for it (usually in compose)
684 $ret .= charset_convert($res[2],$replace,$default_charset);
686 // convert string to html codes in order to display it
687 $ret .= charset_decode($res[2],$replace);
691 $replace = str_replace('_', ' ', $res[4]);
692 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
695 if ($can_be_encoded) {
696 /* convert string to different charset,
697 * if functions asks for it (usually in compose)
699 $replace = charset_convert($res[2], $replace,$default_charset);
701 // convert string to html codes in order to display it
702 $replace = charset_decode($res[2], $replace);
706 $replace = htmlspecialchars($replace);
725 if (!$encoded && $htmlsave) {
726 $ret .= htmlspecialchars($chunk);
732 /* remove the first added space */
735 $ret = substr($ret,5);
737 $ret = substr($ret,1);
745 * Encodes header as quoted-printable
747 * Encode a string according to RFC 1522 for use in headers if it
748 * contains 8-bit characters or anything that looks like it should
751 * @param string $string header string, that has to be encoded
752 * @return string quoted-printable encoded string
754 function encodeHeader ($string) {
755 global $default_charset, $languages, $squirrelmail_language;
757 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
758 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
759 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
762 // Encode only if the string contains 8-bit characters or =?
763 $j = strlen($string);
764 $max_l = 75 - strlen($default_charset) - 7;
767 $iEncStart = $enc_init = false;
768 $cur_l = $iOffset = 0;
769 for($i = 0; $i < $j; ++
$i) {
778 if ($iEncStart === false) {
782 if ($cur_l > ($max_l-2)) {
783 /* if there is an stringpart that doesn't need encoding, add it */
784 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
785 $aRet[] = "=?$default_charset?Q?$ret?=";
791 $ret .= sprintf("=%02X",ord($string{$i}));
796 if ($iEncStart !== false) {
797 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
798 $aRet[] = "=?$default_charset?Q?$ret?=";
806 if ($iEncStart !== false) {
808 if ($cur_l > $max_l) {
809 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
810 $aRet[] = "=?$default_charset?Q?$ret?=";
821 $k = ord($string{$i});
823 if ($iEncStart === false) {
824 // do not start encoding in the middle of a string, also take the rest of the word.
825 $sLeadString = substr($string,0,$i);
826 $aLeadString = explode(' ',$sLeadString);
827 $sToBeEncoded = array_pop($aLeadString);
828 $iEncStart = $i - strlen($sToBeEncoded);
829 $ret .= $sToBeEncoded;
830 $cur_l +
= strlen($sToBeEncoded);
833 /* first we add the encoded string that reached it's max size */
834 if ($cur_l > ($max_l-2)) {
835 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
836 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
843 $ret .= sprintf("=%02X", $k);
845 if ($iEncStart !== false) {
847 if ($cur_l > $max_l) {
848 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
849 $aRet[] = "=?$default_charset?Q?$ret?=";
864 if ($iEncStart !== false) {
865 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
866 $aRet[] = "=?$default_charset?Q?$ret?=";
868 $aRet[] = substr($string,$iOffset);
870 $string = implode('',$aRet);
875 /* This function trys to locate the entity_id of a specific mime element */
876 function find_ent_id($id, $message) {
877 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
878 if ($message->entities
[$i]->header
->type0
== 'multipart') {
879 $ret = find_ent_id($id, $message->entities
[$i]);
881 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
882 // if (sq_check_save_extension($message->entities[$i])) {
883 return $message->entities
[$i]->entity_id
;
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);
900 ** HTMLFILTER ROUTINES
904 * This function is more or less a wrapper around stripslashes. Apparently
905 * Explorer is stupid enough to just remove the backslashes and then
906 * execute the content of the attribute as if nothing happened.
909 * @param attvalue The value of the attribute
910 * @return attvalue The value of the attribute stripslashed.
912 function sq_unbackslash($attvalue){
914 * Remove any backslashes. See if there are any first.
917 if (strstr($attvalue, '\\') !== false){
918 $attvalue = stripslashes($attvalue);
924 * Kill any tabs, newlines, or carriage returns. Our friends the
925 * makers of the browser with 95% market value decided that it'd
926 * be funny to make "java[tab]script" be just as good as "javascript".
928 * @param attvalue The attribute value before extraneous spaces removed.
929 * @return attvalue The attribute value after extraneous spaces removed.
931 function sq_unspace($attvalue){
932 if (strcspn($attvalue, "\t\r\n") != strlen($attvalue)){
933 $attvalue = str_replace(Array("\t", "\r", "\n"), Array('', '', ''),
940 * This function returns the final tag out of the tag name, an array
941 * of attributes, and the type of the tag. This function is called by
942 * sq_sanitize internally.
944 * @param $tagname the name of the tag.
945 * @param $attary the array of attributes and their values
946 * @param $tagtype The type of the tag (see in comments).
947 * @return a string with the final tag representation.
949 function sq_tagprint($tagname, $attary, $tagtype){
953 $fulltag = '</' . $tagname . '>';
955 $fulltag = '<' . $tagname;
956 if (is_array($attary) && sizeof($attary)){
958 while (list($attname, $attvalue) = each($attary)){
959 array_push($atts, "$attname=$attvalue");
961 $fulltag .= ' ' . join(" ", $atts);
972 * A small helper function to use with array_walk. Modifies a by-ref
973 * value and makes it lowercase.
975 * @param $val a value passed by-ref.
976 * @return void since it modifies a by-ref value.
978 function sq_casenormalize(&$val){
979 $val = strtolower($val);
983 * This function skips any whitespace from the current position within
984 * a string and to the next non-whitespace value.
986 * @param $body the string
987 * @param $offset the offset within the string where we should start
988 * looking for the next non-whitespace character.
989 * @return the location within the $body where the next
990 * non-whitespace char is located.
992 function sq_skipspace($body, $offset){
993 $me = 'sq_skipspace';
994 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
995 if (sizeof($matches{1})){
996 $count = strlen($matches{1});
1003 * This function looks for the next character within a string. It's
1004 * really just a glorified "strpos", except it catches if failures
1007 * @param $body The string to look for needle in.
1008 * @param $offset Start looking from this position.
1009 * @param $needle The character/string to look for.
1010 * @return location of the next occurance of the needle, or
1011 * strlen($body) if needle wasn't found.
1013 function sq_findnxstr($body, $offset, $needle){
1014 $me = 'sq_findnxstr';
1015 $pos = strpos($body, $needle, $offset);
1016 if ($pos === FALSE){
1017 $pos = strlen($body);
1023 * This function takes a PCRE-style regexp and tries to match it
1024 * within the string.
1026 * @param $body The string to look for needle in.
1027 * @param $offset Start looking from here.
1028 * @param $reg A PCRE-style regex to match.
1029 * @return Returns a false if no matches found, or an array
1030 * with the following members:
1031 * - integer with the location of the match within $body
1032 * - string with whatever content between offset and the match
1033 * - string with whatever it is we matched
1035 function sq_findnxreg($body, $offset, $reg){
1036 $me = 'sq_findnxreg';
1039 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1040 if (!isset($matches{0}) ||
!$matches{0}){
1043 $retarr{0} = $offset +
strlen($matches{1});
1044 $retarr{1} = $matches{1};
1045 $retarr{2} = $matches{2};
1051 * This function looks for the next tag.
1053 * @param $body String where to look for the next tag.
1054 * @param $offset Start looking from here.
1055 * @return false if no more tags exist in the body, or
1056 * an array with the following members:
1057 * - string with the name of the tag
1058 * - array with attributes and their values
1059 * - integer with tag type (1, 2, or 3)
1060 * - integer where the tag starts (starting "<")
1061 * - integer where the tag ends (ending ">")
1062 * first three members will be false, if the tag is invalid.
1064 function sq_getnxtag($body, $offset){
1065 $me = 'sq_getnxtag';
1066 if ($offset > strlen($body)){
1069 $lt = sq_findnxstr($body, $offset, "<");
1070 if ($lt == strlen($body)){
1075 * blah blah <tag attribute="value">
1078 $pos = sq_skipspace($body, $lt+
1);
1079 if ($pos >= strlen($body)){
1080 return Array(false, false, false, $lt, strlen($body));
1083 * There are 3 kinds of tags:
1084 * 1. Opening tag, e.g.:
1086 * 2. Closing tag, e.g.:
1088 * 3. XHTML-style content-less tag, e.g.:
1089 * <img src="blah" />
1092 switch (substr($body, $pos, 1)){
1099 * A comment or an SGML declaration.
1101 if (substr($body, $pos+
1, 2) == "--"){
1102 $gt = strpos($body, "-->", $pos);
1104 $gt = strlen($body);
1108 return Array(false, false, false, $lt, $gt);
1110 $gt = sq_findnxstr($body, $pos, ">");
1111 return Array(false, false, false, $lt, $gt);
1116 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1126 * Look for next [\W-_], which will indicate the end of the tag name.
1128 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1129 if ($regary == false){
1130 return Array(false, false, false, $lt, strlen($body));
1132 list($pos, $tagname, $match) = $regary;
1133 $tagname = strtolower($tagname);
1136 * $match can be either of these:
1137 * '>' indicating the end of the tag entirely.
1138 * '\s' indicating the end of the tag name.
1139 * '/' indicating that this is type-3 xhtml tag.
1141 * Whatever else we find there indicates an invalid tag.
1146 * This is an xhtml-style tag with a closing / at the
1147 * end, like so: <img src="blah" />. Check if it's followed
1148 * by the closing bracket. If not, then this tag is invalid
1150 if (substr($body, $pos, 2) == "/>"){
1154 $gt = sq_findnxstr($body, $pos, ">");
1155 $retary = Array(false, false, false, $lt, $gt);
1159 return Array($tagname, false, $tagtype, $lt, $pos);
1163 * Check if it's whitespace
1165 if (!preg_match('/\s/', $match)){
1167 * This is an invalid tag! Look for the next closing ">".
1169 $gt = sq_findnxstr($body, $lt, ">");
1170 return Array(false, false, false, $lt, $gt);
1176 * At this point we're here:
1177 * <tagname attribute='blah'>
1180 * At this point we loop in order to find all attributes.
1186 while ($pos <= strlen($body)){
1187 $pos = sq_skipspace($body, $pos);
1188 if ($pos == strlen($body)){
1192 return Array(false, false, false, $lt, $pos);
1195 * See if we arrived at a ">" or "/>", which means that we reached
1196 * the end of the tag.
1199 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1203 $pos +
= strlen($matches{1});
1204 if ($matches{2} == "/>"){
1208 return Array($tagname, $attary, $tagtype, $lt, $pos);
1212 * There are several types of attributes, with optional
1213 * [:space:] between members.
1215 * attrname[:space:]=[:space:]'CDATA'
1217 * attrname[:space:]=[:space:]"CDATA"
1219 * attr[:space:]=[:space:]CDATA
1223 * We leave types 1 and 2 the same, type 3 we check for
1224 * '"' and convert to """ if needed, then wrap in
1225 * double quotes. Type 4 we convert into:
1228 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1229 if ($regary == false){
1231 * Looks like body ended before the end of tag.
1233 return Array(false, false, false, $lt, strlen($body));
1235 list($pos, $attname, $match) = $regary;
1236 $attname = strtolower($attname);
1238 * We arrived at the end of attribute name. Several things possible
1240 * '>' means the end of the tag and this is attribute type 4
1241 * '/' if followed by '>' means the same thing as above
1242 * '\s' means a lot of things -- look what it's followed by.
1243 * anything else means the attribute is invalid.
1248 * This is an xhtml-style tag with a closing / at the
1249 * end, like so: <img src="blah" />. Check if it's followed
1250 * by the closing bracket. If not, then this tag is invalid
1252 if (substr($body, $pos, 2) == "/>"){
1256 $gt = sq_findnxstr($body, $pos, ">");
1257 $retary = Array(false, false, false, $lt, $gt);
1261 $attary{$attname} = '"yes"';
1262 return Array($tagname, $attary, $tagtype, $lt, $pos);
1266 * Skip whitespace and see what we arrive at.
1268 $pos = sq_skipspace($body, $pos);
1269 $char = substr($body, $pos, 1);
1271 * Two things are valid here:
1272 * '=' means this is attribute type 1 2 or 3.
1273 * \w means this was attribute type 4.
1274 * anything else we ignore and re-loop. End of tag and
1275 * invalid stuff will be caught by our checks at the beginning
1280 $pos = sq_skipspace($body, $pos);
1282 * Here are 3 possibilities:
1283 * "'" attribute type 1
1284 * '"' attribute type 2
1285 * everything else is the content of tag type 3
1287 $quot = substr($body, $pos, 1);
1289 $regary = sq_findnxreg($body, $pos+
1, "\'");
1290 if ($regary == false){
1291 return Array(false, false, false, $lt, strlen($body));
1293 list($pos, $attval, $match) = $regary;
1295 $attary{$attname} = "'" . $attval . "'";
1296 } else if ($quot == '"'){
1297 $regary = sq_findnxreg($body, $pos+
1, '\"');
1298 if ($regary == false){
1299 return Array(false, false, false, $lt, strlen($body));
1301 list($pos, $attval, $match) = $regary;
1303 $attary{$attname} = '"' . $attval . '"';
1306 * These are hateful. Look for \s, or >.
1308 $regary = sq_findnxreg($body, $pos, "[\s>]");
1309 if ($regary == false){
1310 return Array(false, false, false, $lt, strlen($body));
1312 list($pos, $attval, $match) = $regary;
1314 * If it's ">" it will be caught at the top.
1316 $attval = preg_replace("/\"/s", """, $attval);
1317 $attary{$attname} = '"' . $attval . '"';
1319 } else if (preg_match("|[\w/>]|", $char)) {
1321 * That was attribute type 4.
1323 $attary{$attname} = '"yes"';
1326 * An illegal character. Find next '>' and return.
1328 $gt = sq_findnxstr($body, $pos, ">");
1329 return Array(false, false, false, $lt, $gt);
1335 * The fact that we got here indicates that the tag end was never
1336 * found. Return invalid tag indication so it gets stripped.
1338 return Array(false, false, false, $lt, strlen($body));
1342 * This function checks attribute values for entity-encoded values
1343 * and returns them translated into 8-bit strings so we can run
1346 * @param $attvalue A string to run entity check against.
1347 * @return Translated value.
1350 function sq_deent($attvalue){
1353 * See if we have to run the checks first. All entities must start
1356 if (strpos($attvalue, '&') === false){
1360 * Check named entities first.
1362 $trans = get_html_translation_table(HTML_ENTITIES
);
1364 * Leave " in, as it can mess us up.
1366 $trans = array_flip($trans);
1367 unset($trans{'"'});
1368 while (list($ent, $val) = each($trans)){
1369 $attvalue = preg_replace('/' . $ent . '*/si', $val, $attvalue);
1372 * Now translate numbered entities from 1 to 255 if needed.
1374 if (strpos($attvalue, '#') !== false){
1375 $omit = Array(34, 39);
1376 for ($asc = 256; $asc >= 0; $asc--){
1377 if (!in_array($asc, $omit)){
1379 $octrule = '/\�*' . $asc . ';*/si';
1380 $hexrule = '/\�*' . dechex($asc) . ';*/si';
1381 $attvalue = preg_replace($octrule, $chr, $attvalue);
1382 $attvalue = preg_replace($hexrule, $chr, $attvalue);
1390 * This function runs various checks against the attributes.
1392 * @param $tagname String with the name of the tag.
1393 * @param $attary Array with all tag attributes.
1394 * @param $rm_attnames See description for sq_sanitize
1395 * @param $bad_attvals See description for sq_sanitize
1396 * @param $add_attr_to_tag See description for sq_sanitize
1397 * @param $message message object
1398 * @param $id message id
1399 * @return Array with modified attributes.
1401 function sq_fixatts($tagname,
1411 while (list($attname, $attvalue) = each($attary)){
1413 * See if this attribute should be removed.
1415 foreach ($rm_attnames as $matchtag=>$matchattrs){
1416 if (preg_match($matchtag, $tagname)){
1417 foreach ($matchattrs as $matchattr){
1418 if (preg_match($matchattr, $attname)){
1419 unset($attary{$attname});
1426 * Remove any backslashes, entities, and extraneous whitespace.
1428 $attvalue = sq_unbackslash($attvalue);
1429 $attvalue = sq_deent($attvalue);
1430 $attvalue = sq_unspace($attvalue);
1433 * Remove \r \n \t \0 " " "\\"
1435 $attvalue = str_replace(Array("\r", "\n", "\t", "\0", " ", "\\"),
1436 Array('', '','','','',''), $attvalue);
1439 * Now let's run checks on the attvalues.
1440 * I don't expect anyone to comprehend this. If you do,
1441 * get in touch with me so I can drive to where you live and
1442 * shake your hand personally. :)
1444 foreach ($bad_attvals as $matchtag=>$matchattrs){
1445 if (preg_match($matchtag, $tagname)){
1446 foreach ($matchattrs as $matchattr=>$valary){
1447 if (preg_match($matchattr, $attname)){
1449 * There are two arrays in valary.
1451 * Second one is replacements
1453 list($valmatch, $valrepl) = $valary;
1455 preg_replace($valmatch, $valrepl, $attvalue);
1456 if ($newvalue != $attvalue){
1457 $attary{$attname} = $newvalue;
1464 * Turn cid: urls into http-friendly ones.
1466 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1467 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1471 * See if we need to append any attributes to this tag.
1473 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1474 if (preg_match($matchtag, $tagname)){
1475 $attary = array_merge($attary, $addattary);
1482 * This function edits the style definition to make them friendly and
1483 * usable in squirrelmail.
1485 * @param $message the message object
1486 * @param $id the message id
1487 * @param $content a string with whatever is between <style> and </style>
1488 * @param $mailbox the message mailbox
1489 * @return a string with edited content.
1491 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1492 global $view_unsafe_images;
1493 $me = 'sq_fixstyle';
1494 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1496 return array(FALSE, strlen($body));
1498 $newpos = $ret[0] +
strlen($ret[2]);
1501 * First look for general BODY style declaration, which would be
1503 * body {background: blah-blah}
1504 * and change it to .bodyclass so we can just assign it to a <div>
1506 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1507 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1509 * Fix url('blah') declarations.
1511 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1512 "url(\\1$secremoveimg\\2)", $content);
1514 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1517 if (!$view_unsafe_images){
1518 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1519 "url(\\1$secremoveimg\\2)", $content);
1523 * Fix urls that refer to cid:
1525 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1526 $content, $matches)){
1527 $cidurl = $matches{1};
1528 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1529 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1530 "url($httpurl)", $content);
1534 * Fix stupid css declarations which lead to vulnerabilities
1537 $match = Array('/expression/i',
1540 '/include-source/i');
1541 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1542 $content = preg_replace($match, $replace, $content);
1543 return array($content, $newpos);
1547 * This function converts cid: url's into the ones that can be viewed in
1550 * @param $message the message object
1551 * @param $id the message id
1552 * @param $cidurl the cid: url.
1553 * @param $mailbox the message mailbox
1554 * @return a string with a http-friendly url
1556 function sq_cid2http($message, $id, $cidurl, $mailbox){
1558 * Get rid of quotes.
1560 $quotchar = substr($cidurl, 0, 1);
1561 if ($quotchar == '"' ||
$quotchar == "'"){
1562 $cidurl = str_replace($quotchar, "", $cidurl);
1566 $cidurl = substr(trim($cidurl), 4);
1567 $linkurl = find_ent_id($cidurl, $message);
1568 /* in case of non-save cid links $httpurl should be replaced by a sort of
1569 unsave link image */
1572 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1573 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1574 '&ent_id=' . $linkurl . $quotchar;
1580 * This function changes the <body> tag into a <div> tag since we
1581 * can't really have a body-within-body.
1583 * @param $attary an array of attributes and values of <body>
1584 * @param $mailbox mailbox we're currently reading (for cid2http)
1585 * @param $message current message (for cid2http)
1586 * @param $id current message id (for cid2http)
1587 * @return a modified array of attributes to be set for <div>
1589 function sq_body2div($attary, $mailbox, $message, $id){
1590 $me = 'sq_body2div';
1591 $divattary = Array('class' => "'bodyclass'");
1592 $bgcolor = '#ffffff';
1594 $has_bgc_stl = $has_txt_stl = false;
1596 if (is_array($attary) && sizeof($attary) > 0){
1597 foreach ($attary as $attname=>$attvalue){
1598 $quotchar = substr($attvalue, 0, 1);
1599 $attvalue = str_replace($quotchar, "", $attvalue);
1602 $attvalue = sq_cid2http($message, $id,
1603 $attvalue, $mailbox);
1604 $styledef .= "background-image: url('$attvalue'); ";
1607 $has_bgc_stl = true;
1608 $styledef .= "background-color: $attvalue; ";
1611 $has_txt_stl = true;
1612 $styledef .= "color: $attvalue; ";
1616 // Outlook defines a white bgcolor and no text color. This can lead to
1617 // white text on a white bg with certain themes.
1618 if ($has_bgc_stl && !$has_txt_stl) {
1619 $styledef .= "color: $text; ";
1621 if (strlen($styledef) > 0){
1622 $divattary{"style"} = "\"$styledef\"";
1629 * This is the main function and the one you should actually be calling.
1630 * There are several variables you should be aware of an which need
1631 * special description.
1633 * Since the description is quite lengthy, see it here:
1634 * http://linux.duke.edu/projects/mini/htmlfilter/
1636 * @param $body the string with HTML you wish to filter
1637 * @param $tag_list see description above
1638 * @param $rm_tags_with_content see description above
1639 * @param $self_closing_tags see description above
1640 * @param $force_tag_closing see description above
1641 * @param $rm_attnames see description above
1642 * @param $bad_attvals see description above
1643 * @param $add_attr_to_tag see description above
1644 * @param $message message object
1645 * @param $id message id
1646 * @return sanitized html safe to show on your pages.
1648 function sq_sanitize($body,
1650 $rm_tags_with_content,
1660 $me = 'sq_sanitize';
1661 $rm_tags = array_shift($tag_list);
1663 * Normalize rm_tags and rm_tags_with_content.
1665 @array_walk
($tag_list, 'sq_casenormalize');
1666 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1667 @array_walk
($self_closing_tags, 'sq_casenormalize');
1669 * See if tag_list is of tags to remove or tags to allow.
1670 * false means remove these tags
1671 * true means allow these tags
1674 $open_tags = Array();
1675 $trusted = "\n<!-- begin sanitized html -->\n";
1676 $skip_content = false;
1678 * Take care of netscape's stupid javascript entities like
1681 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1683 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1684 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1685 $free_content = substr($body, $curpos, $lt-$curpos);
1687 * Take care of <style>
1689 if ($tagname == "style" && $tagtype == 1){
1690 list($free_content, $curpos) =
1691 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1692 if ($free_content != FALSE){
1693 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1694 $trusted .= $free_content;
1695 $trusted .= sq_tagprint($tagname, false, 2);
1699 if ($skip_content == false){
1700 $trusted .= $free_content;
1702 if ($tagname != FALSE){
1704 if ($skip_content == $tagname){
1706 * Got to the end of tag we needed to remove.
1709 $skip_content = false;
1711 if ($skip_content == false){
1712 if ($tagname == "body"){
1715 if (isset($open_tags{$tagname}) &&
1716 $open_tags{$tagname} > 0){
1717 $open_tags{$tagname}--;
1725 * $rm_tags_with_content
1727 if ($skip_content == false){
1729 * See if this is a self-closing type and change
1730 * tagtype appropriately.
1733 && in_array($tagname, $self_closing_tags)){
1737 * See if we should skip this tag and any content
1740 if ($tagtype == 1 &&
1741 in_array($tagname, $rm_tags_with_content)){
1742 $skip_content = $tagname;
1744 if (($rm_tags == false
1745 && in_array($tagname, $tag_list)) ||
1746 ($rm_tags == true &&
1747 !in_array($tagname, $tag_list))){
1751 * Convert body into div.
1753 if ($tagname == "body"){
1755 $attary = sq_body2div($attary, $mailbox,
1759 if (isset($open_tags{$tagname})){
1760 $open_tags{$tagname}++
;
1762 $open_tags{$tagname}=1;
1766 * This is where we run other checks.
1768 if (is_array($attary) && sizeof($attary) > 0){
1769 $attary = sq_fixatts($tagname,
1783 if ($tagname != false && $skip_content == false){
1784 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1789 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1790 if ($force_tag_closing == true){
1791 foreach ($open_tags as $tagname=>$opentimes){
1792 while ($opentimes > 0){
1793 $trusted .= '</' . $tagname . '>';
1799 $trusted .= "<!-- end sanitized html -->\n";
1804 * This is a wrapper function to call html sanitizing routines.
1806 * @param $body the body of the message
1807 * @param $id the id of the message
1808 * @return a string with html safe to display in the browser.
1810 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1811 global $attachment_common_show_images, $view_unsafe_images,
1814 * Don't display attached images in HTML mode.
1816 $attachment_common_show_images = false;
1831 $rm_tags_with_content = Array(
1840 $self_closing_tags = Array(
1847 $force_tag_closing = true;
1849 $rm_attnames = Array(
1860 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1861 $bad_attvals = Array(
1864 "/^src|background/i" =>
1867 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1868 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1869 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1872 "\\1$secremoveimg\\2",
1873 "\\1$secremoveimg\\2",
1874 "\\1$secremoveimg\\2",
1875 "\\1$secremoveimg\\2"
1878 "/^href|action/i" =>
1881 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1882 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1883 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1898 "/include-source/i",
1899 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1900 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1901 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
1902 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
1918 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1919 $view_unsafe_images = false;
1921 if (!$view_unsafe_images){
1923 * Remove any references to http/https if view_unsafe_images set
1926 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1927 '/^([\'\"])\s*https*:.*([\'\"])/si');
1928 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1929 "\\1$secremoveimg\\1");
1930 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1931 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1932 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1933 "url(\\1$secremoveimg\\1)");
1936 $add_attr_to_tag = Array(
1938 Array('target'=>'"_new"',
1939 'title'=>'"'._("This external link will open in a new window").'"'
1942 $trusted = sq_sanitize($body,
1944 $rm_tags_with_content,
1954 if (preg_match("|$secremoveimg|i", $trusted)){
1955 $has_unsafe_images = true;
1961 * function SendDownloadHeaders - send file to the browser
1963 * Original Source: SM core src/download.php
1964 * moved here to make it available to other code, and separate
1965 * front end from back end functionality.
1967 * @param string $type0 first half of mime type
1968 * @param string $type1 second half of mime type
1969 * @param string $filename filename to tell the browser for downloaded file
1970 * @param boolean $force whether to force the download dialog to pop
1971 * @param optional integer $filesize send the Content-Header and length to the browser
1974 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
1975 global $languages, $squirrelmail_language;
1978 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
1980 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
1981 strstr($HTTP_USER_AGENT, 'Opera') === false) {
1985 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
1986 strstr($HTTP_USER_AGENT, 'Opera') === false) {
1990 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1991 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
1993 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
1995 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
1998 // A Pox on Microsoft and it's Internet Explorer!
2000 // IE has lots of bugs with file downloads.
2001 // It also has problems with SSL. Both of these cause problems
2002 // for us in this function.
2004 // See this article on Cache Control headers and SSL
2005 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2007 // The best thing you can do for IE is to upgrade to the latest
2009 //set all the Cache Control Headers for IE
2011 $filename=urlencode($filename);
2012 header ("Pragma: public");
2013 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); # HTTP/1.1
2014 header ("Cache-Control: post-check=0, pre-check=0", false);
2015 header ("Cache-control: private");
2017 //set the inline header for IE, we'll add the attachment header later if we need it
2018 header ("Content-Disposition: inline; filename=$filename");
2022 // Try to show in browser window
2023 header ("Content-Disposition: inline; filename=\"$filename\"");
2024 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2026 // Try to pop up the "save as" box
2028 // IE makes this hard. It pops up 2 save boxes, or none.
2029 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2030 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2031 // But, according to Microsoft, it is "RFC compliant but doesn't
2032 // take into account some deviations that allowed within the
2033 // specification." Doesn't that mean RFC non-compliant?
2034 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2036 // all browsers need the application/octet-stream header for this
2037 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2039 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2040 // Do not have quotes around filename, but that applied to
2041 // "attachment"... does it apply to inline too?
2042 header ("Content-Disposition: attachment; filename=\"$filename\"");
2044 if ($isIE && !$isIE6) {
2045 // This combination seems to work mostly. IE 5.5 SP 1 has
2046 // known issues (see the Microsoft Knowledge Base)
2048 // This works for most types, but doesn't work with Word files
2049 header ("Content-Type: application/download; name=\"$filename\"");
2051 // These are spares, just in case. :-)
2052 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2053 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2054 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2056 // another application/octet-stream forces download for Netscape
2057 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2061 //send the content-length header if the calling function provides it
2062 if ($filesize > 0) {
2063 header("Content-Length: $filesize");
2066 } // end fn SendDownloadHeaders