6 * Copyright (c) 1999-2005 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');
19 /** add sqm_baseuri()*/
20 include_once(SM_PATH
. 'functions/display_messages.php');
22 /* -------------------------------------------------------------------------- */
24 /* -------------------------------------------------------------------------- */
27 * Get the MIME structure
29 * This function gets the structure of a message and stores it in the "message" class.
30 * It will return this object for use with all relevant header information and
31 * fully parsed into the standard "message" object format.
33 function mime_structure ($bodystructure, $flags=array()) {
35 /* Isolate the body structure and remove beginning and end parenthesis. */
36 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
37 $read = trim(substr ($read, 0, -1));
39 $msg = Message
::parseStructure($read,$i);
40 if (!is_object($msg)) {
41 include_once(SM_PATH
. 'functions/display_messages.php');
42 global $color, $mailbox;
43 /* removed urldecode because $_GET is auto urldecoded ??? */
44 displayPageHeader( $color, $mailbox );
45 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
46 $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
47 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
48 plain_error_message( $errormessage, $color );
49 echo '</body></html>';
53 foreach ($flags as $flag) {
54 $char = strtoupper($flag{1});
57 if (strtolower($flag) == '\\seen') {
62 if (strtolower($flag) == '\\answered') {
63 $msg->is_answered
= true;
67 if (strtolower($flag) == '\\deleted') {
68 $msg->is_deleted
= true;
72 if (strtolower($flag) == '\\flagged') {
73 $msg->is_flagged
= true;
77 if (strtolower($flag) == '$mdnsent') {
78 $msg->is_mdnsent
= true;
86 // listEntities($msg);
92 /* This starts the parsing of a particular structure. It is called recursively,
93 * so it can be passed different structures. It returns an object of type
95 * First, it checks to see if it is a multipart message. If it is, then it
96 * handles that as it sees is necessary. If it is just a regular entity,
97 * then it parses it and adds the necessary header information (by calling out
98 * to mime_get_elements()
101 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
102 /* Do a bit of error correction. If we couldn't find the entity id, just guess
103 * that it is the first one. That is usually the case anyway.
107 $cmd = "FETCH $id BODY[]";
109 $cmd = "FETCH $id BODY[$ent_id]";
112 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
114 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
116 $topline = trim(array_shift($data));
117 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
119 $wholemessage = implode('', $data);
120 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
121 $ret = substr($wholemessage, 0, $regs[1]);
122 /* There is some information in the content info header that could be important
123 * in order to parse html messages. Let's get them here.
125 // if ($ret{0} == '<') {
126 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
128 } else if (ereg('"([^"]*)"', $topline, $regs)) {
131 global $where, $what, $mailbox, $passed_id, $startMessage;
132 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
133 if (isset($where) && isset($what)) {
134 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
136 $par .= '&startMessage=' . $startMessage . '&show_more=0';
138 $par .= '&response=' . urlencode($response) .
139 '&message=' . urlencode($message) .
140 '&topline=' . urlencode($topline);
143 '<table width="80%"><tr>' .
144 '<tr><td colspan="2">' .
145 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
147 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
148 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
149 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
150 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
151 "</table><br /></tt></font><hr />";
153 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
155 $wholemessage = implode('', $data);
157 $ret = $wholemessage;
162 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
164 /* Don't kill the connection if the browser is over a dialup
165 * and it would take over 30 seconds to download it.
166 * Don't call set_time_limit in safe mode.
169 if (!ini_get('safe_mode')) {
172 /* in case of base64 encoded attachments, do not buffer them.
173 Instead, echo the decoded attachment directly to screen */
174 if (strtolower($encoding) == 'base64') {
176 $query = "FETCH $id BODY[]";
178 $query = "FETCH $id BODY[$ent_id]";
180 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
182 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
183 if (is_resource($rStream)) {
184 fputs($rStream,decodeBody($body,$encoding));
186 echo decodeBody($body, $encoding);
191 TODO, use the same method for quoted printable.
192 However, I assume that quoted printable attachments aren't that large
193 so the performancegain / memory usage drop will be minimal.
194 If we decide to add that then we need to adapt sqimap_fread because
195 we need to split te result on \n and fread doesn't stop at \n. That
196 means we also should provide $results from sqimap_fread (by ref) to
197 te function and set $no_return to false. The $filter function for
198 quoted printable should handle unsetting of $results.
201 TODO 2: find out how we write to the output stream php://stdout. fwrite
202 doesn't work because 'php://stdout isn't a stream.
208 /* -[ END MIME DECODING ]----------------------------------------------------------- */
210 /* This is here for debugging purposes. It will print out a list
211 * of all the entity IDs that are in the $message object.
213 function listEntities ($message) {
215 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
216 for ($i = 0; isset($message->entities
[$i]); $i++
) {
218 $msg = listEntities($message->entities
[$i]);
228 function getPriorityStr($priority) {
229 $priority_level = substr($priority,0,1);
231 switch($priority_level) {
232 /* Check for a higher then normal priority. */
235 $priority_string = _("High");
238 /* Check for a lower then normal priority. */
241 $priority_string = _("Low");
244 /* Check for a normal priority. */
247 $priority_level = '3';
248 $priority_string = _("Normal");
252 return $priority_string;
255 /* returns a $message object for a particular entity id */
256 function getEntity ($message, $ent_id) {
257 return $message->getEntity($ent_id);
261 * Extracted from strings.php 23/03/2002
264 function translateText(&$body, $wrap_at, $charset) {
265 global $where, $what; /* from searching */
266 global $color; /* color theme */
268 require_once(SM_PATH
. 'functions/url_parser.php');
270 $body_ary = explode("\n", $body);
271 for ($i=0; $i < count($body_ary); $i++
) {
272 $line = $body_ary[$i];
273 if (strlen($line) - 2 >= $wrap_at) {
274 sqWordWrap($line, $wrap_at, $charset);
276 $line = charset_decode($charset, $line);
277 $line = str_replace("\t", ' ', $line);
286 if ($line[$pos] == ' ') {
288 } else if (strpos($line, '>', $pos) === $pos) {
297 if (!isset($color[13])) {
298 $color[13] = '#800000';
300 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
302 if (!isset($color[14])) {
303 $color[14] = '#FF0000';
305 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
308 $body_ary[$i] = $line;
310 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
314 * This returns a parsed string called $body. That string can then
315 * be displayed as the actual message in the HTML. It contains
316 * everything needed, including HTML Tags, Attachments at the
319 * Since 1.2.0 function uses message_body hook.
320 * Till 1.3.0 function included output of formatAttachments().
322 * @param resource $imap_stream imap connection resource
323 * @param object $message squirrelmail message object
324 * @param array $color squirrelmail color theme array
325 * @param integer $wrap_at number of characters per line
326 * @param string $ent_num (since 1.3.0) message part id
327 * @param integer $id (since 1.3.0) message id
328 * @param string $mailbox (since 1.3.0) imap folder name
329 * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
330 * @return string html formated message text
332 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
333 /* This if statement checks for the entity to show as the
334 * primary message. To add more of them, just put them in the
335 * order that is their priority.
337 global $startMessage, $languages, $squirrelmail_language,
338 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id, $use_iframe,$iframe_height;
340 // workaround for not updated config.php
341 if (! isset($use_iframe)) $use_iframe = false;
343 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
344 $view_unsafe_images = false;
348 $urlmailbox = urlencode($mailbox);
349 $body_message = getEntity($message, $ent_num);
350 if (($body_message->header
->type0
== 'text') ||
351 ($body_message->header
->type0
== 'rfc822')) {
352 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
353 $body = decodeBody($body, $body_message->header
->encoding
);
355 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
356 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
357 if (mb_detect_encoding($body) != 'ASCII') {
358 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
361 $hookResults = do_hook("message_body", $body);
362 $body = $hookResults[1];
364 /* If there are other types that shouldn't be formatted, add
368 if ($body_message->header
->type1
== 'html') {
369 if ($show_html_default <> 1) {
370 $entity_conv = array(' ' => ' ',
379 $body = strtr($body, $entity_conv);
380 $body = strip_tags($body);
382 translateText($body, $wrap_at,
383 $body_message->header
->getParameter('charset'));
384 } elseif ($use_iframe && ! $clean) {
385 // $clean is used to remove iframe in printable view.
388 * If we don't add html message between iframe tags,
389 * we must detect unsafe images and modify $has_unsafe_images.
391 $html_body = magicHTML($body, $id, $message, $mailbox);
393 // creating iframe url
394 $iframeurl=sqm_baseuri().'src/view_html.php?'
395 . 'mailbox=' . $urlmailbox
396 . '&passed_id=' . $id
397 . '&ent_id=' . $ent_num
398 . '&view_unsafe_images=' . (int) $view_unsafe_images;
400 // adding warning message
401 $body = html_tag('div',_("Viewing HTML formatted email"),'center');
404 * height can't be set to 100%, because it does not work as expected when
405 * iframe is inside the table. Browsers do not create full height objects
406 * even when iframe is not nested. Maybe there is some way to get full size
407 * with CSS. Tested in firefox 1.02 and opera 7.53
409 * width="100%" does not work as expected, when table width is not set (automatic)
411 * tokul: I think <iframe> are safer sandbox than <object>. Objects might
412 * need special handling for IE and IE6SP2.
414 $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
415 .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
417 // Message for browsers without iframe support
418 //$body.= _("Your browser does not support inline frames.
419 // You can view HTML formated message by following below link.");
420 //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
422 // if browser can't render iframe, it renders html message.
426 $body.="</iframe></div>\n";
428 // old way of html rendering
429 $body = magicHTML($body, $id, $message, $mailbox);
432 translateText($body, $wrap_at,
433 $body_message->header
->getParameter('charset'));
436 // if this is the clean display (i.e. printer friendly), stop here.
441 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
442 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
443 '&startMessage=' . $startMessage . '&show_more=0';
444 if (isset($passed_ent_id)) {
445 $link .= '&passed_ent_id='.$passed_ent_id;
447 $body .= '<center><small><a href="download.php?absolute_dl=true&' .
448 $link . '">' . _("Download this as a file") . '</a>';
449 if ($view_unsafe_images) {
450 $text = _("Hide Unsafe Images");
452 if (isset($has_unsafe_images) && $has_unsafe_images) {
453 $link .= '&view_unsafe_images=1';
454 $text = _("View Unsafe Images");
460 $body .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
462 $body .= '</small></center><br />' . "\n";
468 * Displays attachment links and information
470 * Since 1.3.0 function is not included in formatBody() call.
472 * Since 1.0.2 uses attachment $type0/$type1 hook.
473 * Since 1.2.5 uses attachment $type0/* hook.
474 * Since 1.5.0 uses attachments_bottom hook.
476 * @param object $message SquirrelMail message object
477 * @param array $exclude_id message parts that are not attachments.
478 * @param string $mailbox mailbox name
479 * @param integer $id message id
480 * @return string html formated attachment information.
482 function formatAttachments($message, $exclude_id, $mailbox, $id) {
483 global $where, $what, $startMessage, $color, $passed_ent_id;
485 $att_ar = $message->getAttachments($exclude_id);
487 if (!count($att_ar)) return '';
491 $urlMailbox = urlencode($mailbox);
493 foreach ($att_ar as $att) {
494 $ent = $att->entity_id
;
495 $header = $att->header
;
496 $type0 = strtolower($header->type0
);
497 $type1 = strtolower($header->type1
);
499 $links['download link']['text'] = _("Download");
500 $links['download link']['href'] = sqm_baseuri() .
501 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
502 if ($type0 =='message' && $type1 == 'rfc822') {
503 $default_page = sqm_baseuri() . 'src/read_body.php';
504 $rfc822_header = $att->rfc822_header
;
505 $filename = $rfc822_header->subject
;
506 if (trim( $filename ) == '') {
507 $filename = 'untitled-[' . $ent . ']' ;
509 $from_o = $rfc822_header->from
;
510 if (is_object($from_o)) {
511 $from_name = decodeHeader($from_o->getAddress(false));
513 $from_name = _("Unknown sender");
515 $description = $from_name;
517 $default_page = sqm_baseuri() . 'src/download.php';
518 $filename = $att->getFilename();
519 if ($header->description
) {
520 $description = decodeHeader($header->description
);
526 $display_filename = $filename;
527 if (isset($passed_ent_id)) {
528 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
530 $passed_ent_id_link = '';
532 $defaultlink = $default_page . "?startMessage=$startMessage"
533 . "&passed_id=$id&mailbox=$urlMailbox"
534 . '&ent_id='.$ent.$passed_ent_id_link;
535 if ($where && $what) {
536 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
539 /* This executes the attachment hook with a specific MIME-type.
540 * If that doesn't have results, it tries if there's a rule
541 * for a more generic type.
543 $hookresults = do_hook("attachment $type0/$type1", $links,
544 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
545 $display_filename, $where, $what);
546 if(count($hookresults[1]) <= 1) {
547 $hookresults = do_hook("attachment $type0/*", $links,
548 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
549 $display_filename, $where, $what);
552 $links = $hookresults[1];
553 $defaultlink = $hookresults[6];
555 $attachments .= '<tr><td>' .
556 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
557 '<td><small><b>' . show_readable_size($header->size
) .
558 '</b> </small></td>' .
559 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
561 $attachments .= '<b>' . $description . '</b>';
562 $attachments .= '</small></td><td><small> ';
565 foreach ($links as $val) {
569 $attachments .= ' | ';
571 $attachments .= '<a href="' . $val['href'] . '">'
572 . (isset($val['text']) && !empty($val['text']) ?
$val['text'] : '')
573 . (isset($val['extra']) && !empty($val['extra']) ?
$val['extra'] : '')
577 $attachments .= "</td></tr>\n";
579 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
580 if ($attachmentadd != '')
581 $attachments = $attachmentadd;
585 function sqimap_base64_decode(&$string) {
587 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
588 // fly decoding (to reduce memory usage) you have to check if the
589 // data has incomplete pairs
591 // Remove the noise in order to check if the 4 bytes pairs are complete
592 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
595 $iMod = strlen($string) %
4;
597 $sStringRem = substr($string,-$iMod);
598 // Check if $sStringRem contains padding characters
599 if (substr($sStringRem,-1) != '=') {
600 $string = substr($string,0,-$iMod);
605 $string = base64_decode($string);
610 /* This function decodes the body depending on the encoding type. */
611 function decodeBody($body, $encoding) {
612 global $show_html_default;
614 $body = str_replace("\r\n", "\n", $body);
615 $encoding = strtolower($encoding);
617 $encoding_handler = do_hook_function('decode_body', $encoding);
620 // plugins get first shot at decoding the body
622 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
623 $body = $encoding_handler('decode', $body);
625 } else if ($encoding == 'quoted-printable' ||
626 $encoding == 'quoted_printable') {
627 $body = quoted_printable_decode($body);
629 while (ereg("=\n", $body)) {
630 $body = ereg_replace ("=\n", '', $body);
633 } else if ($encoding == 'base64') {
634 $body = base64_decode($body);
637 // All other encodings are returned raw.
644 * This functions decode strings that is encoded according to
645 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
646 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
648 * @param string $string header string that has to be made readable
649 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
650 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
651 * @param boolean $decide decide if string can be utfencoded. defaults to false
652 * @return string decoded header string
654 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
655 global $languages, $squirrelmail_language,$default_charset;
656 if (is_array($string)) {
657 $string = implode("\n", $string);
660 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
661 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
662 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
663 // Do we need to return at this point?
670 $aString = explode(' ',$string);
672 foreach ($aString as $chunk) {
673 if ($encoded && $chunk === '') {
675 } elseif ($chunk === '') {
680 /* if encoded words are not separated by a linear-space-white we still catch them */
683 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
684 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
685 if ($iLastMatch !== $j) {
695 $ret .= htmlspecialchars($res[1]);
699 $encoding = ucfirst($res[3]);
701 /* decide about valid decoding */
702 if ($decide && is_conversion_safe($res[2])) {
704 $can_be_encoded=true;
706 $can_be_encoded=false;
711 $replace = base64_decode($res[4]);
713 if ($can_be_encoded) {
714 /* convert string to different charset,
715 * if functions asks for it (usually in compose)
717 $ret .= charset_convert($res[2],$replace,$default_charset);
719 // convert string to html codes in order to display it
720 $ret .= charset_decode($res[2],$replace);
724 $replace = htmlspecialchars($replace);
730 $replace = str_replace('_', ' ', $res[4]);
731 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
734 if ($can_be_encoded) {
735 /* convert string to different charset,
736 * if functions asks for it (usually in compose)
738 $replace = charset_convert($res[2], $replace,$default_charset);
740 // convert string to html codes in order to display it
741 $replace = charset_decode($res[2], $replace);
745 $replace = htmlspecialchars($replace);
764 if (!$encoded && $htmlsave) {
765 $ret .= htmlspecialchars($chunk);
771 /* remove the first added space */
774 $ret = substr($ret,5);
776 $ret = substr($ret,1);
784 * Encodes header as quoted-printable
786 * Encode a string according to RFC 1522 for use in headers if it
787 * contains 8-bit characters or anything that looks like it should
790 * @param string $string header string, that has to be encoded
791 * @return string quoted-printable encoded string
793 function encodeHeader ($string) {
794 global $default_charset, $languages, $squirrelmail_language;
796 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
797 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
798 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
801 // Encode only if the string contains 8-bit characters or =?
802 $j = strlen($string);
803 $max_l = 75 - strlen($default_charset) - 7;
806 $iEncStart = $enc_init = false;
807 $cur_l = $iOffset = 0;
808 for($i = 0; $i < $j; ++
$i) {
817 if ($iEncStart === false) {
821 if ($cur_l > ($max_l-2)) {
822 /* if there is an stringpart that doesn't need encoding, add it */
823 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
824 $aRet[] = "=?$default_charset?Q?$ret?=";
830 $ret .= sprintf("=%02X",ord($string{$i}));
835 if ($iEncStart !== false) {
836 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
837 $aRet[] = "=?$default_charset?Q?$ret?=";
845 if ($iEncStart !== false) {
847 if ($cur_l > $max_l) {
848 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
849 $aRet[] = "=?$default_charset?Q?$ret?=";
860 $k = ord($string{$i});
862 if ($iEncStart === false) {
863 // do not start encoding in the middle of a string, also take the rest of the word.
864 $sLeadString = substr($string,0,$i);
865 $aLeadString = explode(' ',$sLeadString);
866 $sToBeEncoded = array_pop($aLeadString);
867 $iEncStart = $i - strlen($sToBeEncoded);
868 $ret .= $sToBeEncoded;
869 $cur_l +
= strlen($sToBeEncoded);
872 /* first we add the encoded string that reached it's max size */
873 if ($cur_l > ($max_l-2)) {
874 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
875 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
882 $ret .= sprintf("=%02X", $k);
884 if ($iEncStart !== false) {
886 if ($cur_l > $max_l) {
887 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
888 $aRet[] = "=?$default_charset?Q?$ret?=";
903 if ($iEncStart !== false) {
904 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
905 $aRet[] = "=?$default_charset?Q?$ret?=";
907 $aRet[] = substr($string,$iOffset);
909 $string = implode('',$aRet);
914 /* This function trys to locate the entity_id of a specific mime element */
915 function find_ent_id($id, $message) {
916 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
917 if ($message->entities
[$i]->header
->type0
== 'multipart') {
918 $ret = find_ent_id($id, $message->entities
[$i]);
920 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
921 // if (sq_check_save_extension($message->entities[$i])) {
922 return $message->entities
[$i]->entity_id
;
924 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
926 * This is part of a fix for Outlook Express 6.x generating
927 * cid URLs without creating content-id headers
930 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
931 return $message->entities
[$i]->entity_id
;
939 function sq_check_save_extension($message) {
940 $filename = $message->getFilename();
941 $ext = substr($filename, strrpos($filename,'.')+
1);
942 $save_extensions = array('jpg','jpeg','gif','png','bmp');
943 return in_array($ext, $save_extensions);
948 ** HTMLFILTER ROUTINES
952 * This function checks attribute values for entity-encoded values
953 * and returns them translated into 8-bit strings so we can run
956 * @param $attvalue A string to run entity check against.
957 * @return Nothing, modifies a reference value.
959 function sq_defang(&$attvalue){
962 * Skip this if there aren't ampersands or backslashes.
964 if (strpos($attvalue, '&') === false
965 && strpos($attvalue, '\\') === false){
971 $m = $m ||
sq_deent($attvalue, '/\�*(\d+);*/s');
972 $m = $m ||
sq_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true);
973 $m = $m ||
sq_deent($attvalue, '/\\\\(\d+)/s', true);
974 } while ($m == true);
975 $attvalue = stripslashes($attvalue);
979 * Kill any tabs, newlines, or carriage returns. Our friends the
980 * makers of the browser with 95% market value decided that it'd
981 * be funny to make "java[tab]script" be just as good as "javascript".
983 * @param attvalue The attribute value before extraneous spaces removed.
984 * @return attvalue Nothing, modifies a reference value.
986 function sq_unspace(&$attvalue){
988 if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
989 $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
990 Array('', '', '', '', ''), $attvalue);
995 * This function returns the final tag out of the tag name, an array
996 * of attributes, and the type of the tag. This function is called by
997 * sq_sanitize internally.
999 * @param $tagname the name of the tag.
1000 * @param $attary the array of attributes and their values
1001 * @param $tagtype The type of the tag (see in comments).
1002 * @return a string with the final tag representation.
1004 function sq_tagprint($tagname, $attary, $tagtype){
1005 $me = 'sq_tagprint';
1008 $fulltag = '</' . $tagname . '>';
1010 $fulltag = '<' . $tagname;
1011 if (is_array($attary) && sizeof($attary)){
1013 while (list($attname, $attvalue) = each($attary)){
1014 array_push($atts, "$attname=$attvalue");
1016 $fulltag .= ' ' . join(" ", $atts);
1027 * A small helper function to use with array_walk. Modifies a by-ref
1028 * value and makes it lowercase.
1030 * @param $val a value passed by-ref.
1031 * @return void since it modifies a by-ref value.
1033 function sq_casenormalize(&$val){
1034 $val = strtolower($val);
1038 * This function skips any whitespace from the current position within
1039 * a string and to the next non-whitespace value.
1041 * @param $body the string
1042 * @param $offset the offset within the string where we should start
1043 * looking for the next non-whitespace character.
1044 * @return the location within the $body where the next
1045 * non-whitespace char is located.
1047 function sq_skipspace($body, $offset){
1048 $me = 'sq_skipspace';
1049 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1050 if (sizeof($matches{1})){
1051 $count = strlen($matches{1});
1058 * This function looks for the next character within a string. It's
1059 * really just a glorified "strpos", except it catches if failures
1062 * @param $body The string to look for needle in.
1063 * @param $offset Start looking from this position.
1064 * @param $needle The character/string to look for.
1065 * @return location of the next occurance of the needle, or
1066 * strlen($body) if needle wasn't found.
1068 function sq_findnxstr($body, $offset, $needle){
1069 $me = 'sq_findnxstr';
1070 $pos = strpos($body, $needle, $offset);
1071 if ($pos === FALSE){
1072 $pos = strlen($body);
1078 * This function takes a PCRE-style regexp and tries to match it
1079 * within the string.
1081 * @param $body The string to look for needle in.
1082 * @param $offset Start looking from here.
1083 * @param $reg A PCRE-style regex to match.
1084 * @return Returns a false if no matches found, or an array
1085 * with the following members:
1086 * - integer with the location of the match within $body
1087 * - string with whatever content between offset and the match
1088 * - string with whatever it is we matched
1090 function sq_findnxreg($body, $offset, $reg){
1091 $me = 'sq_findnxreg';
1094 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1095 if (!isset($matches{0}) ||
!$matches{0}){
1098 $retarr{0} = $offset +
strlen($matches{1});
1099 $retarr{1} = $matches{1};
1100 $retarr{2} = $matches{2};
1106 * This function looks for the next tag.
1108 * @param $body String where to look for the next tag.
1109 * @param $offset Start looking from here.
1110 * @return false if no more tags exist in the body, or
1111 * an array with the following members:
1112 * - string with the name of the tag
1113 * - array with attributes and their values
1114 * - integer with tag type (1, 2, or 3)
1115 * - integer where the tag starts (starting "<")
1116 * - integer where the tag ends (ending ">")
1117 * first three members will be false, if the tag is invalid.
1119 function sq_getnxtag($body, $offset){
1120 $me = 'sq_getnxtag';
1121 if ($offset > strlen($body)){
1124 $lt = sq_findnxstr($body, $offset, "<");
1125 if ($lt == strlen($body)){
1130 * blah blah <tag attribute="value">
1133 $pos = sq_skipspace($body, $lt+
1);
1134 if ($pos >= strlen($body)){
1135 return Array(false, false, false, $lt, strlen($body));
1138 * There are 3 kinds of tags:
1139 * 1. Opening tag, e.g.:
1141 * 2. Closing tag, e.g.:
1143 * 3. XHTML-style content-less tag, e.g.:
1144 * <img src="blah" />
1147 switch (substr($body, $pos, 1)){
1154 * A comment or an SGML declaration.
1156 if (substr($body, $pos+
1, 2) == "--"){
1157 $gt = strpos($body, "-->", $pos);
1159 $gt = strlen($body);
1163 return Array(false, false, false, $lt, $gt);
1165 $gt = sq_findnxstr($body, $pos, ">");
1166 return Array(false, false, false, $lt, $gt);
1171 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1181 * Look for next [\W-_], which will indicate the end of the tag name.
1183 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1184 if ($regary == false){
1185 return Array(false, false, false, $lt, strlen($body));
1187 list($pos, $tagname, $match) = $regary;
1188 $tagname = strtolower($tagname);
1191 * $match can be either of these:
1192 * '>' indicating the end of the tag entirely.
1193 * '\s' indicating the end of the tag name.
1194 * '/' indicating that this is type-3 xhtml tag.
1196 * Whatever else we find there indicates an invalid tag.
1201 * This is an xhtml-style tag with a closing / at the
1202 * end, like so: <img src="blah" />. Check if it's followed
1203 * by the closing bracket. If not, then this tag is invalid
1205 if (substr($body, $pos, 2) == "/>"){
1209 $gt = sq_findnxstr($body, $pos, ">");
1210 $retary = Array(false, false, false, $lt, $gt);
1214 return Array($tagname, false, $tagtype, $lt, $pos);
1218 * Check if it's whitespace
1220 if (!preg_match('/\s/', $match)){
1222 * This is an invalid tag! Look for the next closing ">".
1224 $gt = sq_findnxstr($body, $lt, ">");
1225 return Array(false, false, false, $lt, $gt);
1231 * At this point we're here:
1232 * <tagname attribute='blah'>
1235 * At this point we loop in order to find all attributes.
1241 while ($pos <= strlen($body)){
1242 $pos = sq_skipspace($body, $pos);
1243 if ($pos == strlen($body)){
1247 return Array(false, false, false, $lt, $pos);
1250 * See if we arrived at a ">" or "/>", which means that we reached
1251 * the end of the tag.
1254 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1258 $pos +
= strlen($matches{1});
1259 if ($matches{2} == "/>"){
1263 return Array($tagname, $attary, $tagtype, $lt, $pos);
1267 * There are several types of attributes, with optional
1268 * [:space:] between members.
1270 * attrname[:space:]=[:space:]'CDATA'
1272 * attrname[:space:]=[:space:]"CDATA"
1274 * attr[:space:]=[:space:]CDATA
1278 * We leave types 1 and 2 the same, type 3 we check for
1279 * '"' and convert to """ if needed, then wrap in
1280 * double quotes. Type 4 we convert into:
1283 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1284 if ($regary == false){
1286 * Looks like body ended before the end of tag.
1288 return Array(false, false, false, $lt, strlen($body));
1290 list($pos, $attname, $match) = $regary;
1291 $attname = strtolower($attname);
1293 * We arrived at the end of attribute name. Several things possible
1295 * '>' means the end of the tag and this is attribute type 4
1296 * '/' if followed by '>' means the same thing as above
1297 * '\s' means a lot of things -- look what it's followed by.
1298 * anything else means the attribute is invalid.
1303 * This is an xhtml-style tag with a closing / at the
1304 * end, like so: <img src="blah" />. Check if it's followed
1305 * by the closing bracket. If not, then this tag is invalid
1307 if (substr($body, $pos, 2) == "/>"){
1311 $gt = sq_findnxstr($body, $pos, ">");
1312 $retary = Array(false, false, false, $lt, $gt);
1316 $attary{$attname} = '"yes"';
1317 return Array($tagname, $attary, $tagtype, $lt, $pos);
1321 * Skip whitespace and see what we arrive at.
1323 $pos = sq_skipspace($body, $pos);
1324 $char = substr($body, $pos, 1);
1326 * Two things are valid here:
1327 * '=' means this is attribute type 1 2 or 3.
1328 * \w means this was attribute type 4.
1329 * anything else we ignore and re-loop. End of tag and
1330 * invalid stuff will be caught by our checks at the beginning
1335 $pos = sq_skipspace($body, $pos);
1337 * Here are 3 possibilities:
1338 * "'" attribute type 1
1339 * '"' attribute type 2
1340 * everything else is the content of tag type 3
1342 $quot = substr($body, $pos, 1);
1344 $regary = sq_findnxreg($body, $pos+
1, "\'");
1345 if ($regary == false){
1346 return Array(false, false, false, $lt, strlen($body));
1348 list($pos, $attval, $match) = $regary;
1350 $attary{$attname} = "'" . $attval . "'";
1351 } else if ($quot == '"'){
1352 $regary = sq_findnxreg($body, $pos+
1, '\"');
1353 if ($regary == false){
1354 return Array(false, false, false, $lt, strlen($body));
1356 list($pos, $attval, $match) = $regary;
1358 $attary{$attname} = '"' . $attval . '"';
1361 * These are hateful. Look for \s, or >.
1363 $regary = sq_findnxreg($body, $pos, "[\s>]");
1364 if ($regary == false){
1365 return Array(false, false, false, $lt, strlen($body));
1367 list($pos, $attval, $match) = $regary;
1369 * If it's ">" it will be caught at the top.
1371 $attval = preg_replace("/\"/s", """, $attval);
1372 $attary{$attname} = '"' . $attval . '"';
1374 } else if (preg_match("|[\w/>]|", $char)) {
1376 * That was attribute type 4.
1378 $attary{$attname} = '"yes"';
1381 * An illegal character. Find next '>' and return.
1383 $gt = sq_findnxstr($body, $pos, ">");
1384 return Array(false, false, false, $lt, $gt);
1390 * The fact that we got here indicates that the tag end was never
1391 * found. Return invalid tag indication so it gets stripped.
1393 return Array(false, false, false, $lt, strlen($body));
1397 * Translates entities into literal values so they can be checked.
1399 * @param $attvalue the by-ref value to check.
1400 * @param $regex the regular expression to check against.
1401 * @param $hex whether the entites are hexadecimal.
1402 * @return True or False depending on whether there were matches.
1404 function sq_deent(&$attvalue, $regex, $hex=false){
1407 preg_match_all($regex, $attvalue, $matches);
1408 if (is_array($matches) && sizeof($matches[0]) > 0){
1410 for ($i = 0; $i < sizeof($matches[0]); $i++
){
1411 $numval = $matches[1][$i];
1413 $numval = hexdec($numval);
1415 $repl{$matches[0][$i]} = chr($numval);
1417 $attvalue = strtr($attvalue, $repl);
1425 * This function runs various checks against the attributes.
1427 * @param $tagname String with the name of the tag.
1428 * @param $attary Array with all tag attributes.
1429 * @param $rm_attnames See description for sq_sanitize
1430 * @param $bad_attvals See description for sq_sanitize
1431 * @param $add_attr_to_tag See description for sq_sanitize
1432 * @param $message message object
1433 * @param $id message id
1434 * @return Array with modified attributes.
1436 function sq_fixatts($tagname,
1446 while (list($attname, $attvalue) = each($attary)){
1448 * See if this attribute should be removed.
1450 foreach ($rm_attnames as $matchtag=>$matchattrs){
1451 if (preg_match($matchtag, $tagname)){
1452 foreach ($matchattrs as $matchattr){
1453 if (preg_match($matchattr, $attname)){
1454 unset($attary{$attname});
1461 * Remove any backslashes, entities, and extraneous whitespace.
1463 sq_defang($attvalue);
1464 sq_unspace($attvalue);
1467 * Now let's run checks on the attvalues.
1468 * I don't expect anyone to comprehend this. If you do,
1469 * get in touch with me so I can drive to where you live and
1470 * shake your hand personally. :)
1472 foreach ($bad_attvals as $matchtag=>$matchattrs){
1473 if (preg_match($matchtag, $tagname)){
1474 foreach ($matchattrs as $matchattr=>$valary){
1475 if (preg_match($matchattr, $attname)){
1477 * There are two arrays in valary.
1479 * Second one is replacements
1481 list($valmatch, $valrepl) = $valary;
1483 preg_replace($valmatch, $valrepl, $attvalue);
1484 if ($newvalue != $attvalue){
1485 $attary{$attname} = $newvalue;
1493 * Replace empty src tags with the blank image. src is only used
1494 * for frames, images, and image inputs. Doing a replace should
1495 * not affect them working as should be, however it will stop
1496 * IE from being kicked off when src for img tags are not set
1498 if (($attname == 'src') && ($attvalue == '""')) {
1499 $attary{$attname} = '"' . SM_PATH
. 'images/blank.png"';
1503 * Turn cid: urls into http-friendly ones.
1505 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1506 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1510 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1511 * One day MS might actually make it match something useful, for now, falling
1512 * back to using cid2http, so we can grab the blank.png.
1514 if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
1515 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1520 * See if we need to append any attributes to this tag.
1522 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1523 if (preg_match($matchtag, $tagname)){
1524 $attary = array_merge($attary, $addattary);
1531 * This function edits the style definition to make them friendly and
1532 * usable in SquirrelMail.
1534 * @param $message the message object
1535 * @param $id the message id
1536 * @param $content a string with whatever is between <style> and </style>
1537 * @param $mailbox the message mailbox
1538 * @return a string with edited content.
1540 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1541 global $view_unsafe_images;
1542 $me = 'sq_fixstyle';
1543 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1545 return array(FALSE, strlen($body));
1547 $newpos = $ret[0] +
strlen($ret[2]);
1550 * First look for general BODY style declaration, which would be
1552 * body {background: blah-blah}
1553 * and change it to .bodyclass so we can just assign it to a <div>
1555 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1556 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1558 * Fix url('blah') declarations.
1560 // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1561 // "url(\\1$secremoveimg\\2)", $content);
1563 $content = str_replace("\0", "", $content);
1564 // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
1565 while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
1566 $sProto = strtolower($matches[1]);
1569 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1574 if (!$view_unsafe_images){
1575 $sExpr = "/url\s*\(\s*([\'\"])\s*$sProto*:.*?([\'\"])\s*\)/si";
1576 $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
1580 * Fix urls that refer to cid:
1583 $cidurl = 'cid:'. $matches[2];
1584 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1585 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1586 "u\0r\0l($httpurl)", $content);
1590 * replace url with protocol other then the white list
1591 * http,https and cid by an empty string.
1593 $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
1600 $content = str_replace("\0", "", $content);
1603 * Remove any backslashes, entities, and extraneous whitespace.
1605 $contentTemp = $content;
1606 sq_defang($contentTemp);
1607 sq_unspace($contentTemp);
1610 * Fix stupid css declarations which lead to vulnerabilities
1613 $match = Array('/expression/i',
1616 '/include-source/i');
1617 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1618 $contentNew = preg_replace($match, $replace, $contentTemp);
1619 if ($contentNew !== $contentTemp) {
1620 // insecure css declarations are used. From now on we don't care
1621 // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
1622 $content = $contentNew;
1624 return array($content, $newpos);
1629 * This function converts cid: url's into the ones that can be viewed in
1632 * @param $message the message object
1633 * @param $id the message id
1634 * @param $cidurl the cid: url.
1635 * @param $mailbox the message mailbox
1636 * @return a string with a http-friendly url
1638 function sq_cid2http($message, $id, $cidurl, $mailbox){
1640 * Get rid of quotes.
1642 $quotchar = substr($cidurl, 0, 1);
1643 if ($quotchar == '"' ||
$quotchar == "'"){
1644 $cidurl = str_replace($quotchar, "", $cidurl);
1648 $cidurl = substr(trim($cidurl), 4);
1650 $match_str = '/\{.*?\}\//';
1652 $cidurl = preg_replace($match_str, $str_rep, $cidurl);
1654 $linkurl = find_ent_id($cidurl, $message);
1655 /* in case of non-save cid links $httpurl should be replaced by a sort of
1656 unsave link image */
1660 * This is part of a fix for Outlook Express 6.x generating
1661 * cid URLs without creating content-id headers. These images are
1662 * not part of the multipart/related html mail. The html contains
1663 * <img src="cid:{some_id}/image_filename.ext"> references to
1664 * attached images with as goal to render them inline although
1665 * the attachment disposition property is not inline.
1668 if (empty($linkurl)) {
1669 if (preg_match('/{.*}\//', $cidurl)) {
1670 $cidurl = preg_replace('/{.*}\//','', $cidurl);
1671 if (!empty($cidurl)) {
1672 $linkurl = find_ent_id($cidurl, $message);
1677 if (!empty($linkurl)) {
1678 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1679 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1680 '&ent_id=' . $linkurl . $quotchar;
1683 * If we couldn't generate a proper img url, drop in a blank image
1684 * instead of sending back empty, otherwise it causes unusual behaviour
1686 $httpurl = $quotchar . SM_PATH
. 'images/blank.png' . $quotchar;
1693 * This function changes the <body> tag into a <div> tag since we
1694 * can't really have a body-within-body.
1696 * @param $attary an array of attributes and values of <body>
1697 * @param $mailbox mailbox we're currently reading (for cid2http)
1698 * @param $message current message (for cid2http)
1699 * @param $id current message id (for cid2http)
1700 * @return a modified array of attributes to be set for <div>
1702 function sq_body2div($attary, $mailbox, $message, $id){
1703 $me = 'sq_body2div';
1704 $divattary = Array('class' => "'bodyclass'");
1706 $has_bgc_stl = $has_txt_stl = false;
1708 if (is_array($attary) && sizeof($attary) > 0){
1709 foreach ($attary as $attname=>$attvalue){
1710 $quotchar = substr($attvalue, 0, 1);
1711 $attvalue = str_replace($quotchar, "", $attvalue);
1714 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1715 $styledef .= "background-image: url('$attvalue'); ";
1718 $has_bgc_stl = true;
1719 $styledef .= "background-color: $attvalue; ";
1722 $has_txt_stl = true;
1723 $styledef .= "color: $attvalue; ";
1727 // Outlook defines a white bgcolor and no text color. This can lead to
1728 // white text on a white bg with certain themes.
1729 if ($has_bgc_stl && !$has_txt_stl) {
1730 $styledef .= "color: $text; ";
1732 if (strlen($styledef) > 0){
1733 $divattary{"style"} = "\"$styledef\"";
1740 * This is the main function and the one you should actually be calling.
1741 * There are several variables you should be aware of an which need
1742 * special description.
1744 * Since the description is quite lengthy, see it here:
1745 * http://linux.duke.edu/projects/mini/htmlfilter/
1747 * @param $body the string with HTML you wish to filter
1748 * @param $tag_list see description above
1749 * @param $rm_tags_with_content see description above
1750 * @param $self_closing_tags see description above
1751 * @param $force_tag_closing see description above
1752 * @param $rm_attnames see description above
1753 * @param $bad_attvals see description above
1754 * @param $add_attr_to_tag see description above
1755 * @param $message message object
1756 * @param $id message id
1757 * @return sanitized html safe to show on your pages.
1759 function sq_sanitize($body,
1761 $rm_tags_with_content,
1771 $me = 'sq_sanitize';
1772 $rm_tags = array_shift($tag_list);
1774 * Normalize rm_tags and rm_tags_with_content.
1776 @array_walk
($tag_list, 'sq_casenormalize');
1777 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1778 @array_walk
($self_closing_tags, 'sq_casenormalize');
1780 * See if tag_list is of tags to remove or tags to allow.
1781 * false means remove these tags
1782 * true means allow these tags
1785 $open_tags = Array();
1786 $trusted = "\n<!-- begin sanitized html -->\n";
1787 $skip_content = false;
1789 * Take care of netscape's stupid javascript entities like
1792 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1794 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1795 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1796 $free_content = substr($body, $curpos, $lt-$curpos);
1798 * Take care of <style>
1800 if ($tagname == "style" && $tagtype == 1){
1801 list($free_content, $curpos) =
1802 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1803 if ($free_content != FALSE){
1804 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1805 $trusted .= $free_content;
1806 $trusted .= sq_tagprint($tagname, false, 2);
1810 if ($skip_content == false){
1811 $trusted .= $free_content;
1813 if ($tagname != FALSE){
1815 if ($skip_content == $tagname){
1817 * Got to the end of tag we needed to remove.
1820 $skip_content = false;
1822 if ($skip_content == false){
1823 if ($tagname == "body"){
1826 if (isset($open_tags{$tagname}) &&
1827 $open_tags{$tagname} > 0){
1828 $open_tags{$tagname}--;
1836 * $rm_tags_with_content
1838 if ($skip_content == false){
1840 * See if this is a self-closing type and change
1841 * tagtype appropriately.
1844 && in_array($tagname, $self_closing_tags)){
1848 * See if we should skip this tag and any content
1851 if ($tagtype == 1 &&
1852 in_array($tagname, $rm_tags_with_content)){
1853 $skip_content = $tagname;
1855 if (($rm_tags == false
1856 && in_array($tagname, $tag_list)) ||
1857 ($rm_tags == true &&
1858 !in_array($tagname, $tag_list))){
1862 * Convert body into div.
1864 if ($tagname == "body"){
1866 $attary = sq_body2div($attary, $mailbox,
1870 if (isset($open_tags{$tagname})){
1871 $open_tags{$tagname}++
;
1873 $open_tags{$tagname}=1;
1877 * This is where we run other checks.
1879 if (is_array($attary) && sizeof($attary) > 0){
1880 $attary = sq_fixatts($tagname,
1894 if ($tagname != false && $skip_content == false){
1895 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1900 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1901 if ($force_tag_closing == true){
1902 foreach ($open_tags as $tagname=>$opentimes){
1903 while ($opentimes > 0){
1904 $trusted .= '</' . $tagname . '>';
1910 $trusted .= "<!-- end sanitized html -->\n";
1915 * This is a wrapper function to call html sanitizing routines.
1917 * @param $body the body of the message
1918 * @param $id the id of the message
1922 * @param boolean $take_mailto_links When TRUE, converts mailto: links
1923 * into internal SM compose links
1924 * (optional; default = TRUE)
1925 * @return a string with html safe to display in the browser.
1927 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
1929 require_once(SM_PATH
. 'functions/url_parser.php'); // for $MailTo_PReg_Match
1931 global $attachment_common_show_images, $view_unsafe_images,
1934 * Don't display attached images in HTML mode.
1936 $attachment_common_show_images = false;
1951 $rm_tags_with_content = Array(
1961 $self_closing_tags = Array(
1969 $force_tag_closing = true;
1971 $rm_attnames = Array(
1982 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1983 $bad_attvals = Array(
1986 "/^src|background/i" =>
1989 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1990 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1991 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1994 "\\1$secremoveimg\\2",
1995 "\\1$secremoveimg\\2",
1996 "\\1$secremoveimg\\2",
1997 "\\1$secremoveimg\\2"
2000 "/^href|action/i" =>
2003 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2004 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2005 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2020 "/include-source/i",
2021 "/position\s*:\s*absolute/i",
2022 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2023 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2024 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2025 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2043 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2044 $view_unsafe_images = false;
2046 if (!$view_unsafe_images){
2048 * Remove any references to http/https if view_unsafe_images set
2051 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2052 '/^([\'\"])\s*https*:.*([\'\"])/si');
2053 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2054 "\\1$secremoveimg\\1");
2055 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2056 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
2057 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2058 "url(\\1$secremoveimg\\1)");
2061 $add_attr_to_tag = Array(
2063 Array('target'=>'"_blank"',
2064 'title'=>'"'._("This external link will open in a new window").'"'
2067 $trusted = sq_sanitize($body,
2069 $rm_tags_with_content,
2079 if (preg_match("|$secremoveimg|i", $trusted)){
2080 $has_unsafe_images = true;
2083 // we want to parse mailto's in HTML output, change to SM compose links
2084 // this is a modified version of code from url_parser.php... but Marc is
2085 // right: we need a better filtering implementation; adding this randomly
2086 // here is not a great solution
2088 if ($take_mailto_links) {
2089 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2090 global $MailTo_PReg_Match;
2091 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
2092 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2093 foreach ($regs[0] as $i => $mailto_before) {
2094 $mailto_params = $regs[10][$i];
2095 // get rid of any tailing quote since we have to add send_to to the end
2097 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2098 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2099 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2100 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2102 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2103 $to = 'to=' . $regs[1][$i];
2104 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2105 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2107 if ($mailto_params) //already some params, append to them
2108 $mailto_params .= '&' . $to;
2110 $mailto_params .= '?' . $to;
2114 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2116 // we'll already have target=_blank, no need to allow comp_in_new
2117 // here (which would be a lot more work anyway)
2119 global $compose_new_win;
2120 $temp_comp_in_new = $compose_new_win;
2121 $compose_new_win = 0;
2122 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2123 $compose_new_win = $temp_comp_in_new;
2125 // remove <a href=" and anything after the next quote (we only
2126 // need the uri, not the link HTML) in compose uri
2128 $comp_uri = substr($comp_uri, 9);
2129 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2130 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2139 * function SendDownloadHeaders - send file to the browser
2141 * Original Source: SM core src/download.php
2142 * moved here to make it available to other code, and separate
2143 * front end from back end functionality.
2145 * @param string $type0 first half of mime type
2146 * @param string $type1 second half of mime type
2147 * @param string $filename filename to tell the browser for downloaded file
2148 * @param boolean $force whether to force the download dialog to pop
2149 * @param optional integer $filesize send the Content-Header and length to the browser
2152 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2153 global $languages, $squirrelmail_language;
2156 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2158 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2159 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2163 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
2164 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2168 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2169 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2171 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2173 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2176 // A Pox on Microsoft and it's Internet Explorer!
2178 // IE has lots of bugs with file downloads.
2179 // It also has problems with SSL. Both of these cause problems
2180 // for us in this function.
2182 // See this article on Cache Control headers and SSL
2183 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2185 // The best thing you can do for IE is to upgrade to the latest
2187 //set all the Cache Control Headers for IE
2189 $filename=rawurlencode($filename);
2190 header ("Pragma: public");
2191 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2192 header ("Cache-Control: post-check=0, pre-check=0", false);
2193 header ("Cache-Control: private");
2195 //set the inline header for IE, we'll add the attachment header later if we need it
2196 header ("Content-Disposition: inline; filename=$filename");
2200 // Try to show in browser window
2201 header ("Content-Disposition: inline; filename=\"$filename\"");
2202 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2204 // Try to pop up the "save as" box
2206 // IE makes this hard. It pops up 2 save boxes, or none.
2207 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2208 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2209 // But, according to Microsoft, it is "RFC compliant but doesn't
2210 // take into account some deviations that allowed within the
2211 // specification." Doesn't that mean RFC non-compliant?
2212 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2214 // all browsers need the application/octet-stream header for this
2215 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2217 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2218 // Do not have quotes around filename, but that applied to
2219 // "attachment"... does it apply to inline too?
2220 header ("Content-Disposition: attachment; filename=\"$filename\"");
2222 if ($isIE && !$isIE6) {
2223 // This combination seems to work mostly. IE 5.5 SP 1 has
2224 // known issues (see the Microsoft Knowledge Base)
2226 // This works for most types, but doesn't work with Word files
2227 header ("Content-Type: application/download; name=\"$filename\"");
2229 // These are spares, just in case. :-)
2230 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2231 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2232 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2234 // another application/octet-stream forces download for Netscape
2235 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2239 //send the content-length header if the calling function provides it
2240 if ($filesize > 0) {
2241 header("Content-Length: $filesize");
2244 } // end fn SendDownloadHeaders