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 provided bodystructure 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) {
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','php://stdout',true);
182 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
183 echo decodeBody($body, $encoding);
187 TODO, use the same method for quoted printable.
188 However, I assume that quoted printable attachments aren't that large
189 so the performancegain / memory usage drop will be minimal.
190 If we decide to add that then we need to adapt sqimap_fread because
191 we need to split te result on \n and fread doesn't stop at \n. That
192 means we also should provide $results from sqimap_fread (by ref) to
193 te function and set $no_return to false. The $filter function for
194 quoted printable should handle unsetting of $results.
197 TODO 2: find out how we write to the output stream php://stdout. fwrite
198 doesn't work because 'php://stdout isn't a stream.
203 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
206 $read = fgets ($imap_stream,8192);
209 // This could be bad -- if the section has sqimap_session_id() . ' OK'
210 // or similar, it will kill the download.
211 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
212 if (trim($read) == ')==') {
214 $read = fgets ($imap_stream,4096);
215 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
218 echo decodeBody($read1, $encoding) .
219 decodeBody($read, $encoding);
222 echo decodeBody($read, $encoding);
224 $read = fgets ($imap_stream,4096);
231 /* -[ END MIME DECODING ]----------------------------------------------------------- */
233 /* This is here for debugging purposes. It will print out a list
234 * of all the entity IDs that are in the $message object.
236 function listEntities ($message) {
238 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
239 for ($i = 0; isset($message->entities
[$i]); $i++
) {
241 $msg = listEntities($message->entities
[$i]);
251 function getPriorityStr($priority) {
252 $priority_level = substr($priority,0,1);
254 switch($priority_level) {
255 /* Check for a higher then normal priority. */
258 $priority_string = _("High");
261 /* Check for a lower then normal priority. */
264 $priority_string = _("Low");
267 /* Check for a normal priority. */
270 $priority_level = '3';
271 $priority_string = _("Normal");
275 return $priority_string;
278 /* returns a $message object for a particular entity id */
279 function getEntity ($message, $ent_id) {
280 return $message->getEntity($ent_id);
284 * Extracted from strings.php 23/03/2002
287 function translateText(&$body, $wrap_at, $charset) {
288 global $where, $what; /* from searching */
289 global $color; /* color theme */
291 require_once(SM_PATH
. 'functions/url_parser.php');
293 $body_ary = explode("\n", $body);
294 for ($i=0; $i < count($body_ary); $i++
) {
295 $line = $body_ary[$i];
296 if (strlen($line) - 2 >= $wrap_at) {
297 sqWordWrap($line, $wrap_at, $charset);
299 $line = charset_decode($charset, $line);
300 $line = str_replace("\t", ' ', $line);
309 if ($line[$pos] == ' ') {
311 } else if (strpos($line, '>', $pos) === $pos) {
320 if (!isset($color[13])) {
321 $color[13] = '#800000';
323 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
325 if (!isset($color[14])) {
326 $color[14] = '#FF0000';
328 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
331 $body_ary[$i] = $line;
333 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
337 * This returns a parsed string called $body. That string can then
338 * be displayed as the actual message in the HTML. It contains
339 * everything needed, including HTML Tags, Attachments at the
342 * Since 1.2.0 function uses message_body hook.
343 * Till 1.3.0 function included output of formatAttachments().
345 * @param resource $imap_stream imap connection resource
346 * @param object $message squirrelmail message object
347 * @param array $color squirrelmail color theme array
348 * @param integer $wrap_at number of characters per line
349 * @param string $ent_num (since 1.3.0) message part id
350 * @param integer $id (since 1.3.0) message id
351 * @param string $mailbox (since 1.3.0) imap folder name
352 * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
353 * @return string html formated message text
355 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
356 /* This if statement checks for the entity to show as the
357 * primary message. To add more of them, just put them in the
358 * order that is their priority.
360 global $startMessage, $languages, $squirrelmail_language,
361 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id, $use_iframe,$iframe_height;
363 // workaround for not updated config.php
364 if (! isset($use_iframe)) $use_iframe = false;
366 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
367 $view_unsafe_images = false;
371 $urlmailbox = urlencode($mailbox);
372 $body_message = getEntity($message, $ent_num);
373 if (($body_message->header
->type0
== 'text') ||
374 ($body_message->header
->type0
== 'rfc822')) {
375 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
376 $body = decodeBody($body, $body_message->header
->encoding
);
378 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
379 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
380 if (mb_detect_encoding($body) != 'ASCII') {
381 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
384 $hookResults = do_hook("message_body", $body);
385 $body = $hookResults[1];
387 /* If there are other types that shouldn't be formatted, add
391 if ($body_message->header
->type1
== 'html') {
392 if ($show_html_default <> 1) {
393 $entity_conv = array(' ' => ' ',
402 $body = strtr($body, $entity_conv);
403 $body = strip_tags($body);
405 translateText($body, $wrap_at,
406 $body_message->header
->getParameter('charset'));
407 } elseif ($use_iframe && ! $clean) {
408 // $clean is used to remove iframe in printable view.
410 // creating iframe url
411 $iframeurl=sqm_baseuri().'src/view_html.php?'
412 . 'mailbox=' . $urlmailbox
413 . '&passed_id=' . $id
414 . '&ent_id=' . $ent_num
415 . '&view_unsafe_images=' . (int) $view_unsafe_images;
417 // adding warning message
418 $body = html_tag('div',_("Viewing HTML formatted email"),'center');
421 * height can't be set to 100%, because it does not work as expected when
422 * iframe is inside the table. Browsers do not create full height objects
423 * even when iframe is not nested. Maybe there is some way to get full size
424 * with CSS. Tested in firefox 1.02 and opera 7.53
426 * width="100%" does not work as expected, when table width is not set (automatic)
428 * tokul: I think <iframe> are safer sandbox than <object>. Objects might
429 * need special handling for IE and IE6SP2.
431 $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
432 .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
434 // Message for browsers without iframe support
435 $body.= _("Your browser does not support inline frames. You can view HTML formated message by following below link.");
436 $body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
439 $body.="</iframe></div>\n";
441 // old way of html rendering
442 $body = magicHTML($body, $id, $message, $mailbox);
445 translateText($body, $wrap_at,
446 $body_message->header
->getParameter('charset'));
449 // if this is the clean display (i.e. printer friendly), stop here.
454 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
455 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
456 '&startMessage=' . $startMessage . '&show_more=0';
457 if (isset($passed_ent_id)) {
458 $link .= '&passed_ent_id='.$passed_ent_id;
460 $body .= '<center><small><a href="download.php?absolute_dl=true&' .
461 $link . '">' . _("Download this as a file") . '</a>';
462 if ($view_unsafe_images) {
463 $text = _("Hide Unsafe Images");
465 if (isset($has_unsafe_images) && $has_unsafe_images) {
466 $link .= '&view_unsafe_images=1';
467 $text = _("View Unsafe Images");
473 $body .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
475 $body .= '</small></center><br />' . "\n";
481 * Displays attachment links and information
483 * Since 1.3.0 function is not included in formatBody() call.
485 * Since 1.0.2 uses attachment $type0/$type1 hook.
486 * Since 1.2.5 uses attachment $type0/* hook.
487 * Since 1.5.0 uses attachments_bottom hook.
489 * @param object $message SquirrelMail message object
490 * @param array $exclude_id message parts that are not attachments.
491 * @param string $mailbox mailbox name
492 * @param integer $id message id
493 * @return string html formated attachment information.
495 function formatAttachments($message, $exclude_id, $mailbox, $id) {
496 global $where, $what, $startMessage, $color, $passed_ent_id;
498 $att_ar = $message->getAttachments($exclude_id);
500 if (!count($att_ar)) return '';
504 $urlMailbox = urlencode($mailbox);
506 foreach ($att_ar as $att) {
507 $ent = $att->entity_id
;
508 $header = $att->header
;
509 $type0 = strtolower($header->type0
);
510 $type1 = strtolower($header->type1
);
512 $links['download link']['text'] = _("Download");
513 $links['download link']['href'] = sqm_baseuri() .
514 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
515 if ($type0 =='message' && $type1 == 'rfc822') {
516 $default_page = sqm_baseuri() . 'src/read_body.php';
517 $rfc822_header = $att->rfc822_header
;
518 $filename = $rfc822_header->subject
;
519 if (trim( $filename ) == '') {
520 $filename = 'untitled-[' . $ent . ']' ;
522 $from_o = $rfc822_header->from
;
523 if (is_object($from_o)) {
524 $from_name = decodeHeader($from_o->getAddress(false));
526 $from_name = _("Unknown sender");
528 $description = $from_name;
530 $default_page = sqm_baseuri() . 'src/download.php';
531 $filename = $att->getFilename();
532 if ($header->description
) {
533 $description = decodeHeader($header->description
);
539 $display_filename = $filename;
540 if (isset($passed_ent_id)) {
541 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
543 $passed_ent_id_link = '';
545 $defaultlink = $default_page . "?startMessage=$startMessage"
546 . "&passed_id=$id&mailbox=$urlMailbox"
547 . '&ent_id='.$ent.$passed_ent_id_link;
548 if ($where && $what) {
549 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
552 /* This executes the attachment hook with a specific MIME-type.
553 * If that doesn't have results, it tries if there's a rule
554 * for a more generic type.
556 $hookresults = do_hook("attachment $type0/$type1", $links,
557 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
558 $display_filename, $where, $what);
559 if(count($hookresults[1]) <= 1) {
560 $hookresults = do_hook("attachment $type0/*", $links,
561 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
562 $display_filename, $where, $what);
565 $links = $hookresults[1];
566 $defaultlink = $hookresults[6];
568 $attachments .= '<tr><td>' .
569 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
570 '<td><small><b>' . show_readable_size($header->size
) .
571 '</b> </small></td>' .
572 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
574 $attachments .= '<b>' . $description . '</b>';
575 $attachments .= '</small></td><td><small> ';
578 foreach ($links as $val) {
582 $attachments .= ' | ';
584 $attachments .= '<a href="' . $val['href'] . '">'
585 . (isset($val['text']) && !empty($val['text']) ?
$val['text'] : '')
586 . (isset($val['extra']) && !empty($val['extra']) ?
$val['extra'] : '')
590 $attachments .= "</td></tr>\n";
592 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
593 if ($attachmentadd != '')
594 $attachments = $attachmentadd;
598 function sqimap_base64_decode(&$string) {
600 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
601 // fly decoding (to reduce memory usage) you have to check if the
602 // data has incomplete pairs
604 // Remove the noise in order to check if the 4 bytes pairs are complete
605 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
608 $iMod = strlen($string) %
4;
610 $sStringRem = substr($string,-$iMod);
611 // Check if $sStringRem contains padding characters
612 if (substr($sStringRem,-1) != '=') {
613 $string = substr($string,0,-$iMod);
618 $string = base64_decode($string);
623 /* This function decodes the body depending on the encoding type. */
624 function decodeBody($body, $encoding) {
625 global $show_html_default;
627 $body = str_replace("\r\n", "\n", $body);
628 $encoding = strtolower($encoding);
630 $encoding_handler = do_hook_function('decode_body', $encoding);
633 // plugins get first shot at decoding the body
635 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
636 $body = $encoding_handler('decode', $body);
638 } else if ($encoding == 'quoted-printable' ||
639 $encoding == 'quoted_printable') {
640 $body = quoted_printable_decode($body);
642 while (ereg("=\n", $body)) {
643 $body = ereg_replace ("=\n", '', $body);
646 } else if ($encoding == 'base64') {
647 $body = base64_decode($body);
650 // All other encodings are returned raw.
657 * This functions decode strings that is encoded according to
658 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
659 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
661 * @param string $string header string that has to be made readable
662 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
663 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
664 * @param boolean $decide decide if string can be utfencoded. defaults to false
665 * @return string decoded header string
667 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
668 global $languages, $squirrelmail_language,$default_charset;
669 if (is_array($string)) {
670 $string = implode("\n", $string);
673 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
674 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
675 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
676 // Do we need to return at this point?
683 $aString = explode(' ',$string);
685 foreach ($aString as $chunk) {
686 if ($encoded && $chunk === '') {
688 } elseif ($chunk === '') {
693 /* if encoded words are not separated by a linear-space-white we still catch them */
696 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
697 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
698 if ($iLastMatch !== $j) {
708 $ret .= htmlspecialchars($res[1]);
712 $encoding = ucfirst($res[3]);
714 /* decide about valid decoding */
715 if ($decide && is_conversion_safe($res[2])) {
717 $can_be_encoded=true;
719 $can_be_encoded=false;
724 $replace = base64_decode($res[4]);
726 if ($can_be_encoded) {
727 /* convert string to different charset,
728 * if functions asks for it (usually in compose)
730 $ret .= charset_convert($res[2],$replace,$default_charset);
732 // convert string to html codes in order to display it
733 $ret .= charset_decode($res[2],$replace);
737 $replace = htmlspecialchars($replace);
743 $replace = str_replace('_', ' ', $res[4]);
744 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
747 if ($can_be_encoded) {
748 /* convert string to different charset,
749 * if functions asks for it (usually in compose)
751 $replace = charset_convert($res[2], $replace,$default_charset);
753 // convert string to html codes in order to display it
754 $replace = charset_decode($res[2], $replace);
758 $replace = htmlspecialchars($replace);
777 if (!$encoded && $htmlsave) {
778 $ret .= htmlspecialchars($chunk);
784 /* remove the first added space */
787 $ret = substr($ret,5);
789 $ret = substr($ret,1);
797 * Encodes header as quoted-printable
799 * Encode a string according to RFC 1522 for use in headers if it
800 * contains 8-bit characters or anything that looks like it should
803 * @param string $string header string, that has to be encoded
804 * @return string quoted-printable encoded string
806 function encodeHeader ($string) {
807 global $default_charset, $languages, $squirrelmail_language;
809 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
810 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
811 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
814 // Encode only if the string contains 8-bit characters or =?
815 $j = strlen($string);
816 $max_l = 75 - strlen($default_charset) - 7;
819 $iEncStart = $enc_init = false;
820 $cur_l = $iOffset = 0;
821 for($i = 0; $i < $j; ++
$i) {
830 if ($iEncStart === false) {
834 if ($cur_l > ($max_l-2)) {
835 /* if there is an stringpart that doesn't need encoding, add it */
836 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
837 $aRet[] = "=?$default_charset?Q?$ret?=";
843 $ret .= sprintf("=%02X",ord($string{$i}));
848 if ($iEncStart !== false) {
849 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
850 $aRet[] = "=?$default_charset?Q?$ret?=";
858 if ($iEncStart !== false) {
860 if ($cur_l > $max_l) {
861 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
862 $aRet[] = "=?$default_charset?Q?$ret?=";
873 $k = ord($string{$i});
875 if ($iEncStart === false) {
876 // do not start encoding in the middle of a string, also take the rest of the word.
877 $sLeadString = substr($string,0,$i);
878 $aLeadString = explode(' ',$sLeadString);
879 $sToBeEncoded = array_pop($aLeadString);
880 $iEncStart = $i - strlen($sToBeEncoded);
881 $ret .= $sToBeEncoded;
882 $cur_l +
= strlen($sToBeEncoded);
885 /* first we add the encoded string that reached it's max size */
886 if ($cur_l > ($max_l-2)) {
887 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
888 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
895 $ret .= sprintf("=%02X", $k);
897 if ($iEncStart !== false) {
899 if ($cur_l > $max_l) {
900 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
901 $aRet[] = "=?$default_charset?Q?$ret?=";
916 if ($iEncStart !== false) {
917 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
918 $aRet[] = "=?$default_charset?Q?$ret?=";
920 $aRet[] = substr($string,$iOffset);
922 $string = implode('',$aRet);
927 /* This function trys to locate the entity_id of a specific mime element */
928 function find_ent_id($id, $message) {
929 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
930 if ($message->entities
[$i]->header
->type0
== 'multipart') {
931 $ret = find_ent_id($id, $message->entities
[$i]);
933 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
934 // if (sq_check_save_extension($message->entities[$i])) {
935 return $message->entities
[$i]->entity_id
;
937 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
939 * This is part of a fix for Outlook Express 6.x generating
940 * cid URLs without creating content-id headers
943 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
944 return $message->entities
[$i]->entity_id
;
952 function sq_check_save_extension($message) {
953 $filename = $message->getFilename();
954 $ext = substr($filename, strrpos($filename,'.')+
1);
955 $save_extensions = array('jpg','jpeg','gif','png','bmp');
956 return in_array($ext, $save_extensions);
961 ** HTMLFILTER ROUTINES
965 * This function is more or less a wrapper around stripslashes. Apparently
966 * Explorer is stupid enough to just remove the backslashes and then
967 * execute the content of the attribute as if nothing happened.
970 * @param attvalue The value of the attribute
971 * @return attvalue The value of the attribute stripslashed.
973 function sq_unbackslash($attvalue){
975 * Remove any backslashes. See if there are any first.
978 if (strstr($attvalue, '\\') !== false){
979 $attvalue = stripslashes($attvalue);
985 * Kill any tabs, newlines, or carriage returns. Our friends the
986 * makers of the browser with 95% market value decided that it'd
987 * be funny to make "java[tab]script" be just as good as "javascript".
989 * @param attvalue The attribute value before extraneous spaces removed.
990 * @return attvalue The attribute value after extraneous spaces removed.
992 function sq_unspace($attvalue){
993 if (strcspn($attvalue, "\t\r\n") != strlen($attvalue)){
994 $attvalue = str_replace(Array("\t", "\r", "\n"), Array('', '', ''),
1001 * This function returns the final tag out of the tag name, an array
1002 * of attributes, and the type of the tag. This function is called by
1003 * sq_sanitize internally.
1005 * @param $tagname the name of the tag.
1006 * @param $attary the array of attributes and their values
1007 * @param $tagtype The type of the tag (see in comments).
1008 * @return a string with the final tag representation.
1010 function sq_tagprint($tagname, $attary, $tagtype){
1011 $me = 'sq_tagprint';
1014 $fulltag = '</' . $tagname . '>';
1016 $fulltag = '<' . $tagname;
1017 if (is_array($attary) && sizeof($attary)){
1019 while (list($attname, $attvalue) = each($attary)){
1020 array_push($atts, "$attname=$attvalue");
1022 $fulltag .= ' ' . join(" ", $atts);
1033 * A small helper function to use with array_walk. Modifies a by-ref
1034 * value and makes it lowercase.
1036 * @param $val a value passed by-ref.
1037 * @return void since it modifies a by-ref value.
1039 function sq_casenormalize(&$val){
1040 $val = strtolower($val);
1044 * This function skips any whitespace from the current position within
1045 * a string and to the next non-whitespace value.
1047 * @param $body the string
1048 * @param $offset the offset within the string where we should start
1049 * looking for the next non-whitespace character.
1050 * @return the location within the $body where the next
1051 * non-whitespace char is located.
1053 function sq_skipspace($body, $offset){
1054 $me = 'sq_skipspace';
1055 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1056 if (sizeof($matches{1})){
1057 $count = strlen($matches{1});
1064 * This function looks for the next character within a string. It's
1065 * really just a glorified "strpos", except it catches if failures
1068 * @param $body The string to look for needle in.
1069 * @param $offset Start looking from this position.
1070 * @param $needle The character/string to look for.
1071 * @return location of the next occurance of the needle, or
1072 * strlen($body) if needle wasn't found.
1074 function sq_findnxstr($body, $offset, $needle){
1075 $me = 'sq_findnxstr';
1076 $pos = strpos($body, $needle, $offset);
1077 if ($pos === FALSE){
1078 $pos = strlen($body);
1084 * This function takes a PCRE-style regexp and tries to match it
1085 * within the string.
1087 * @param $body The string to look for needle in.
1088 * @param $offset Start looking from here.
1089 * @param $reg A PCRE-style regex to match.
1090 * @return Returns a false if no matches found, or an array
1091 * with the following members:
1092 * - integer with the location of the match within $body
1093 * - string with whatever content between offset and the match
1094 * - string with whatever it is we matched
1096 function sq_findnxreg($body, $offset, $reg){
1097 $me = 'sq_findnxreg';
1100 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1101 if (!isset($matches{0}) ||
!$matches{0}){
1104 $retarr{0} = $offset +
strlen($matches{1});
1105 $retarr{1} = $matches{1};
1106 $retarr{2} = $matches{2};
1112 * This function looks for the next tag.
1114 * @param $body String where to look for the next tag.
1115 * @param $offset Start looking from here.
1116 * @return false if no more tags exist in the body, or
1117 * an array with the following members:
1118 * - string with the name of the tag
1119 * - array with attributes and their values
1120 * - integer with tag type (1, 2, or 3)
1121 * - integer where the tag starts (starting "<")
1122 * - integer where the tag ends (ending ">")
1123 * first three members will be false, if the tag is invalid.
1125 function sq_getnxtag($body, $offset){
1126 $me = 'sq_getnxtag';
1127 if ($offset > strlen($body)){
1130 $lt = sq_findnxstr($body, $offset, "<");
1131 if ($lt == strlen($body)){
1136 * blah blah <tag attribute="value">
1139 $pos = sq_skipspace($body, $lt+
1);
1140 if ($pos >= strlen($body)){
1141 return Array(false, false, false, $lt, strlen($body));
1144 * There are 3 kinds of tags:
1145 * 1. Opening tag, e.g.:
1147 * 2. Closing tag, e.g.:
1149 * 3. XHTML-style content-less tag, e.g.:
1150 * <img src="blah" />
1153 switch (substr($body, $pos, 1)){
1160 * A comment or an SGML declaration.
1162 if (substr($body, $pos+
1, 2) == "--"){
1163 $gt = strpos($body, "-->", $pos);
1165 $gt = strlen($body);
1169 return Array(false, false, false, $lt, $gt);
1171 $gt = sq_findnxstr($body, $pos, ">");
1172 return Array(false, false, false, $lt, $gt);
1177 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1186 * Look for next [\W-_], which will indicate the end of the tag name.
1188 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1189 if ($regary == false){
1190 return Array(false, false, false, $lt, strlen($body));
1192 list($pos, $tagname, $match) = $regary;
1193 $tagname = strtolower($tagname);
1196 * $match can be either of these:
1197 * '>' indicating the end of the tag entirely.
1198 * '\s' indicating the end of the tag name.
1199 * '/' indicating that this is type-3 xhtml tag.
1201 * Whatever else we find there indicates an invalid tag.
1206 * This is an xhtml-style tag with a closing / at the
1207 * end, like so: <img src="blah" />. Check if it's followed
1208 * by the closing bracket. If not, then this tag is invalid
1210 if (substr($body, $pos, 2) == "/>"){
1214 $gt = sq_findnxstr($body, $pos, ">");
1215 $retary = Array(false, false, false, $lt, $gt);
1219 return Array($tagname, false, $tagtype, $lt, $pos);
1223 * Check if it's whitespace
1225 if (!preg_match('/\s/', $match)){
1227 * This is an invalid tag! Look for the next closing ">".
1229 $gt = sq_findnxstr($body, $lt, ">");
1230 return Array(false, false, false, $lt, $gt);
1236 * At this point we're here:
1237 * <tagname attribute='blah'>
1240 * At this point we loop in order to find all attributes.
1245 while ($pos <= strlen($body)){
1246 $pos = sq_skipspace($body, $pos);
1247 if ($pos == strlen($body)){
1251 return Array(false, false, false, $lt, $pos);
1254 * See if we arrived at a ">" or "/>", which means that we reached
1255 * the end of the tag.
1258 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1262 $pos +
= strlen($matches{1});
1263 if ($matches{2} == "/>"){
1267 return Array($tagname, $attary, $tagtype, $lt, $pos);
1271 * There are several types of attributes, with optional
1272 * [:space:] between members.
1274 * attrname[:space:]=[:space:]'CDATA'
1276 * attrname[:space:]=[:space:]"CDATA"
1278 * attr[:space:]=[:space:]CDATA
1282 * We leave types 1 and 2 the same, type 3 we check for
1283 * '"' and convert to """ if needed, then wrap in
1284 * double quotes. Type 4 we convert into:
1287 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1288 if ($regary == false){
1290 * Looks like body ended before the end of tag.
1292 return Array(false, false, false, $lt, strlen($body));
1294 list($pos, $attname, $match) = $regary;
1295 $attname = strtolower($attname);
1297 * We arrived at the end of attribute name. Several things possible
1299 * '>' means the end of the tag and this is attribute type 4
1300 * '/' if followed by '>' means the same thing as above
1301 * '\s' means a lot of things -- look what it's followed by.
1302 * anything else means the attribute is invalid.
1307 * This is an xhtml-style tag with a closing / at the
1308 * end, like so: <img src="blah" />. Check if it's followed
1309 * by the closing bracket. If not, then this tag is invalid
1311 if (substr($body, $pos, 2) == "/>"){
1315 $gt = sq_findnxstr($body, $pos, ">");
1316 $retary = Array(false, false, false, $lt, $gt);
1320 $attary{$attname} = '"yes"';
1321 return Array($tagname, $attary, $tagtype, $lt, $pos);
1325 * Skip whitespace and see what we arrive at.
1327 $pos = sq_skipspace($body, $pos);
1328 $char = substr($body, $pos, 1);
1330 * Two things are valid here:
1331 * '=' means this is attribute type 1 2 or 3.
1332 * \w means this was attribute type 4.
1333 * anything else we ignore and re-loop. End of tag and
1334 * invalid stuff will be caught by our checks at the beginning
1339 $pos = sq_skipspace($body, $pos);
1341 * Here are 3 possibilities:
1342 * "'" attribute type 1
1343 * '"' attribute type 2
1344 * everything else is the content of tag type 3
1346 $quot = substr($body, $pos, 1);
1348 $regary = sq_findnxreg($body, $pos+
1, "\'");
1349 if ($regary == false){
1350 return Array(false, false, false, $lt, strlen($body));
1352 list($pos, $attval, $match) = $regary;
1354 $attary{$attname} = "'" . $attval . "'";
1355 } else if ($quot == '"'){
1356 $regary = sq_findnxreg($body, $pos+
1, '\"');
1357 if ($regary == false){
1358 return Array(false, false, false, $lt, strlen($body));
1360 list($pos, $attval, $match) = $regary;
1362 $attary{$attname} = '"' . $attval . '"';
1365 * These are hateful. Look for \s, or >.
1367 $regary = sq_findnxreg($body, $pos, "[\s>]");
1368 if ($regary == false){
1369 return Array(false, false, false, $lt, strlen($body));
1371 list($pos, $attval, $match) = $regary;
1373 * If it's ">" it will be caught at the top.
1375 $attval = preg_replace("/\"/s", """, $attval);
1376 $attary{$attname} = '"' . $attval . '"';
1378 } else if (preg_match("|[\w/>]|", $char)) {
1380 * That was attribute type 4.
1382 $attary{$attname} = '"yes"';
1385 * An illegal character. Find next '>' and return.
1387 $gt = sq_findnxstr($body, $pos, ">");
1388 return Array(false, false, false, $lt, $gt);
1394 * The fact that we got here indicates that the tag end was never
1395 * found. Return invalid tag indication so it gets stripped.
1397 return Array(false, false, false, $lt, strlen($body));
1401 * This function checks attribute values for entity-encoded values
1402 * and returns them translated into 8-bit strings so we can run
1405 * @param $attvalue A string to run entity check against.
1406 * @return Translated value.
1409 function sq_deent($attvalue){
1412 * See if we have to run the checks first. All entities must start
1415 if (strpos($attvalue, '&') === false){
1419 * Check named entities first.
1421 $trans = get_html_translation_table(HTML_ENTITIES
);
1423 * Leave " in, as it can mess us up.
1425 $trans = array_flip($trans);
1426 unset($trans{'"'});
1427 while (list($ent, $val) = each($trans)){
1428 $attvalue = preg_replace('/' . $ent . '*/si', $val, $attvalue);
1431 * Now translate numbered entities from 1 to 255 if needed.
1433 if (strpos($attvalue, '#') !== false){
1434 $omit = Array(34, 39);
1435 for ($asc = 256; $asc >= 0; $asc--){
1436 if (!in_array($asc, $omit)){
1438 $octrule = '/\�*' . $asc . ';*/si';
1439 $hexrule = '/\�*' . dechex($asc) . ';*/si';
1440 $attvalue = preg_replace($octrule, $chr, $attvalue);
1441 $attvalue = preg_replace($hexrule, $chr, $attvalue);
1449 * This function runs various checks against the attributes.
1451 * @param $tagname String with the name of the tag.
1452 * @param $attary Array with all tag attributes.
1453 * @param $rm_attnames See description for sq_sanitize
1454 * @param $bad_attvals See description for sq_sanitize
1455 * @param $add_attr_to_tag See description for sq_sanitize
1456 * @param $message message object
1457 * @param $id message id
1458 * @return Array with modified attributes.
1460 function sq_fixatts($tagname,
1470 while (list($attname, $attvalue) = each($attary)){
1472 * See if this attribute should be removed.
1474 foreach ($rm_attnames as $matchtag=>$matchattrs){
1475 if (preg_match($matchtag, $tagname)){
1476 foreach ($matchattrs as $matchattr){
1477 if (preg_match($matchattr, $attname)){
1478 unset($attary{$attname});
1485 * Remove any backslashes, entities, and extraneous whitespace.
1487 $attvalue = sq_unbackslash($attvalue);
1488 $attvalue = sq_deent($attvalue);
1489 $attvalue = sq_unspace($attvalue);
1492 * Remove \r \n \t \0 " " "\\"
1494 $attvalue = str_replace(Array("\r", "\n", "\t", "\0", " ", "\\"),
1495 Array('', '','','','',''), $attvalue);
1498 * Now let's run checks on the attvalues.
1499 * I don't expect anyone to comprehend this. If you do,
1500 * get in touch with me so I can drive to where you live and
1501 * shake your hand personally. :)
1503 foreach ($bad_attvals as $matchtag=>$matchattrs){
1504 if (preg_match($matchtag, $tagname)){
1505 foreach ($matchattrs as $matchattr=>$valary){
1506 if (preg_match($matchattr, $attname)){
1508 * There are two arrays in valary.
1510 * Second one is replacements
1512 list($valmatch, $valrepl) = $valary;
1514 preg_replace($valmatch, $valrepl, $attvalue);
1515 if ($newvalue != $attvalue){
1516 $attary{$attname} = $newvalue;
1525 * Replace empty src tags with the blank image. src is only used
1526 * for frames, images, and image inputs. Doing a replace should
1527 * not affect them working as should be, however it will stop
1528 * IE from being kicked off when src for img tags are not set
1530 if (($attname == 'src') && ($attvalue == '""')) {
1531 $attary{$attname} = '"' . SM_PATH
. 'images/blank.png"';
1535 * Turn cid: urls into http-friendly ones.
1537 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1538 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1542 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1543 * One day MS might actually make it match something useful, for now, falling
1544 * back to using cid2http, so we can grab the blank.png.
1546 if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
1547 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1552 * See if we need to append any attributes to this tag.
1554 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1555 if (preg_match($matchtag, $tagname)){
1556 $attary = array_merge($attary, $addattary);
1563 * This function edits the style definition to make them friendly and
1564 * usable in SquirrelMail.
1566 * @param $message the message object
1567 * @param $id the message id
1568 * @param $content a string with whatever is between <style> and </style>
1569 * @param $mailbox the message mailbox
1570 * @return a string with edited content.
1572 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1573 global $view_unsafe_images;
1574 $me = 'sq_fixstyle';
1575 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1577 return array(FALSE, strlen($body));
1579 $newpos = $ret[0] +
strlen($ret[2]);
1582 * First look for general BODY style declaration, which would be
1584 * body {background: blah-blah}
1585 * and change it to .bodyclass so we can just assign it to a <div>
1587 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1588 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1590 * Fix url('blah') declarations.
1592 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1593 "url(\\1$secremoveimg\\2)", $content);
1595 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1598 if (!$view_unsafe_images){
1599 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1600 "url(\\1$secremoveimg\\2)", $content);
1604 * Fix urls that refer to cid:
1606 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1607 $content, $matches)){
1608 $cidurl = $matches{1};
1609 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1610 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1611 "url($httpurl)", $content);
1615 * Fix stupid css declarations which lead to vulnerabilities
1618 $match = Array('/expression/i',
1621 '/include-source/i');
1622 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1623 $content = preg_replace($match, $replace, $content);
1624 return array($content, $newpos);
1628 * This function converts cid: url's into the ones that can be viewed in
1631 * @param $message the message object
1632 * @param $id the message id
1633 * @param $cidurl the cid: url.
1634 * @param $mailbox the message mailbox
1635 * @return a string with a http-friendly url
1637 function sq_cid2http($message, $id, $cidurl, $mailbox){
1639 * Get rid of quotes.
1641 $quotchar = substr($cidurl, 0, 1);
1642 if ($quotchar == '"' ||
$quotchar == "'"){
1643 $cidurl = str_replace($quotchar, "", $cidurl);
1647 $cidurl = substr(trim($cidurl), 4);
1648 $linkurl = find_ent_id($cidurl, $message);
1649 /* in case of non-save cid links $httpurl should be replaced by a sort of
1650 unsave link image */
1654 * This is part of a fix for Outlook Express 6.x generating
1655 * cid URLs without creating content-id headers. These images are
1656 * not part of the multipart/related html mail. The html contains
1657 * <img src="cid:{some_id}/image_filename.ext"> references to
1658 * attached images with as goal to render them inline although
1659 * the attachment disposition property is not inline.
1662 if (empty($linkurl)) {
1663 if (preg_match('/{.*}\//', $cidurl)) {
1664 $cidurl = preg_replace('/{.*}\//','', $cidurl);
1665 if (!empty($cidurl)) {
1666 $linkurl = find_ent_id($cidurl, $message);
1671 if (!empty($linkurl)) {
1672 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1673 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1674 '&ent_id=' . $linkurl . $quotchar;
1677 * If we couldn't generate a proper img url, drop in a blank image
1678 * instead of sending back empty, otherwise it causes unusual behaviour
1680 $httpurl = $quotchar . SM_PATH
. 'images/blank.png';
1687 * This function changes the <body> tag into a <div> tag since we
1688 * can't really have a body-within-body.
1690 * @param $attary an array of attributes and values of <body>
1691 * @param $mailbox mailbox we're currently reading (for cid2http)
1692 * @param $message current message (for cid2http)
1693 * @param $id current message id (for cid2http)
1694 * @return a modified array of attributes to be set for <div>
1696 function sq_body2div($attary, $mailbox, $message, $id){
1697 $me = 'sq_body2div';
1698 $divattary = Array('class' => "'bodyclass'");
1700 $has_bgc_stl = $has_txt_stl = false;
1702 if (is_array($attary) && sizeof($attary) > 0){
1703 foreach ($attary as $attname=>$attvalue){
1704 $quotchar = substr($attvalue, 0, 1);
1705 $attvalue = str_replace($quotchar, "", $attvalue);
1708 $attvalue = sq_cid2http($message, $id,
1709 $attvalue, $mailbox);
1710 $styledef .= "background-image: url('$attvalue'); ";
1713 $has_bgc_stl = true;
1714 $styledef .= "background-color: $attvalue; ";
1717 $has_txt_stl = true;
1718 $styledef .= "color: $attvalue; ";
1722 // Outlook defines a white bgcolor and no text color. This can lead to
1723 // white text on a white bg with certain themes.
1724 if ($has_bgc_stl && !$has_txt_stl) {
1725 $styledef .= "color: $text; ";
1727 if (strlen($styledef) > 0){
1728 $divattary{"style"} = "\"$styledef\"";
1735 * This is the main function and the one you should actually be calling.
1736 * There are several variables you should be aware of an which need
1737 * special description.
1739 * Since the description is quite lengthy, see it here:
1740 * http://linux.duke.edu/projects/mini/htmlfilter/
1742 * @param $body the string with HTML you wish to filter
1743 * @param $tag_list see description above
1744 * @param $rm_tags_with_content see description above
1745 * @param $self_closing_tags see description above
1746 * @param $force_tag_closing see description above
1747 * @param $rm_attnames see description above
1748 * @param $bad_attvals see description above
1749 * @param $add_attr_to_tag see description above
1750 * @param $message message object
1751 * @param $id message id
1752 * @return sanitized html safe to show on your pages.
1754 function sq_sanitize($body,
1756 $rm_tags_with_content,
1766 $me = 'sq_sanitize';
1767 $rm_tags = array_shift($tag_list);
1769 * Normalize rm_tags and rm_tags_with_content.
1771 @array_walk
($tag_list, 'sq_casenormalize');
1772 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1773 @array_walk
($self_closing_tags, 'sq_casenormalize');
1775 * See if tag_list is of tags to remove or tags to allow.
1776 * false means remove these tags
1777 * true means allow these tags
1780 $open_tags = Array();
1781 $trusted = "\n<!-- begin sanitized html -->\n";
1782 $skip_content = false;
1784 * Take care of netscape's stupid javascript entities like
1787 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1789 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1790 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1791 $free_content = substr($body, $curpos, $lt-$curpos);
1793 * Take care of <style>
1795 if ($tagname == "style" && $tagtype == 1){
1796 list($free_content, $curpos) =
1797 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1798 if ($free_content != FALSE){
1799 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1800 $trusted .= $free_content;
1801 $trusted .= sq_tagprint($tagname, false, 2);
1805 if ($skip_content == false){
1806 $trusted .= $free_content;
1808 if ($tagname != FALSE){
1810 if ($skip_content == $tagname){
1812 * Got to the end of tag we needed to remove.
1815 $skip_content = false;
1817 if ($skip_content == false){
1818 if ($tagname == "body"){
1821 if (isset($open_tags{$tagname}) &&
1822 $open_tags{$tagname} > 0){
1823 $open_tags{$tagname}--;
1831 * $rm_tags_with_content
1833 if ($skip_content == false){
1835 * See if this is a self-closing type and change
1836 * tagtype appropriately.
1839 && in_array($tagname, $self_closing_tags)){
1843 * See if we should skip this tag and any content
1846 if ($tagtype == 1 &&
1847 in_array($tagname, $rm_tags_with_content)){
1848 $skip_content = $tagname;
1850 if (($rm_tags == false
1851 && in_array($tagname, $tag_list)) ||
1852 ($rm_tags == true &&
1853 !in_array($tagname, $tag_list))){
1857 * Convert body into div.
1859 if ($tagname == "body"){
1861 $attary = sq_body2div($attary, $mailbox,
1865 if (isset($open_tags{$tagname})){
1866 $open_tags{$tagname}++
;
1868 $open_tags{$tagname}=1;
1872 * This is where we run other checks.
1874 if (is_array($attary) && sizeof($attary) > 0){
1875 $attary = sq_fixatts($tagname,
1889 if ($tagname != false && $skip_content == false){
1890 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1895 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1896 if ($force_tag_closing == true){
1897 foreach ($open_tags as $tagname=>$opentimes){
1898 while ($opentimes > 0){
1899 $trusted .= '</' . $tagname . '>';
1905 $trusted .= "<!-- end sanitized html -->\n";
1910 * This is a wrapper function to call html sanitizing routines.
1912 * @param $body the body of the message
1913 * @param $id the id of the message
1916 * @param boolean $take_mailto_links When TRUE, converts mailto: links
1917 * into internal SM compose links
1918 * (optional; default = TRUE)
1919 * @return a string with html safe to display in the browser.
1921 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links = true) {
1923 require_once(SM_PATH
. 'functions/url_parser.php'); // for $MailTo_PReg_Match
1925 global $attachment_common_show_images, $view_unsafe_images,
1929 * Don't display attached images in HTML mode.
1931 $attachment_common_show_images = false;
1946 $rm_tags_with_content = Array(
1955 $self_closing_tags = Array(
1963 $force_tag_closing = true;
1965 $rm_attnames = Array(
1976 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1977 $bad_attvals = Array(
1980 "/^src|background/i" =>
1983 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1984 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1985 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1988 "\\1$secremoveimg\\2",
1989 "\\1$secremoveimg\\2",
1990 "\\1$secremoveimg\\2",
1991 "\\1$secremoveimg\\2"
1994 "/^href|action/i" =>
1997 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1998 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1999 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2014 "/include-source/i",
2015 "/position\s*:\s*absolute/i",
2016 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2017 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2018 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2019 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2036 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2037 $view_unsafe_images = false;
2039 if (!$view_unsafe_images){
2041 * Remove any references to http/https if view_unsafe_images set
2044 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2045 '/^([\'\"])\s*https*:.*([\'\"])/si');
2046 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2047 "\\1$secremoveimg\\1");
2048 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2049 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
2050 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2051 "url(\\1$secremoveimg\\1)");
2054 $add_attr_to_tag = Array(
2056 Array('target'=>'"_blank"',
2057 'title'=>'"'._("This external link will open in a new window").'"'
2060 $trusted = sq_sanitize($body,
2062 $rm_tags_with_content,
2072 if (preg_match("|$secremoveimg|i", $trusted)){
2073 $has_unsafe_images = true;
2077 // we want to parse mailto's in HTML output, change to SM compose links
2078 // this is a modified version of code from url_parser.php... but Marc is
2079 // right: we need a better filtering implementation; adding this randomly
2080 // here is not a great solution
2082 if ($take_mailto_links) {
2083 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2084 global $MailTo_PReg_Match;
2085 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
2086 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2087 foreach ($regs[0] as $i => $mailto_before) {
2088 $mailto_params = $regs[10][$i];
2090 // get rid of any tailing quote since we have to add send_to to the end
2092 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2093 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2094 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2095 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2097 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2098 $to = 'to=' . $regs[1][$i];
2099 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2100 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2102 if ($mailto_params) //already some params, append to them
2103 $mailto_params .= '&' . $to;
2105 $mailto_params .= '?' . $to;
2109 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2111 // we'll already have target=_blank, no need to allow comp_in_new
2112 // here (which would be a lot more work anyway)
2114 global $compose_new_win;
2115 $temp_comp_in_new = $compose_new_win;
2116 $compose_new_win = 0;
2117 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2118 $compose_new_win = $temp_comp_in_new;
2120 // remove <a href=" and anything after the next quote (we only
2121 // need the uri, not the link HTML) in compose uri
2123 $comp_uri = substr($comp_uri, 9);
2124 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2125 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2134 * function SendDownloadHeaders - send file to the browser
2136 * Original Source: SM core src/download.php
2137 * moved here to make it available to other code, and separate
2138 * front end from back end functionality.
2140 * @param string $type0 first half of mime type
2141 * @param string $type1 second half of mime type
2142 * @param string $filename filename to tell the browser for downloaded file
2143 * @param boolean $force whether to force the download dialog to pop
2144 * @param optional integer $filesize send the Content-Header and length to the browser
2147 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2148 global $languages, $squirrelmail_language;
2151 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2153 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2154 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2158 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
2159 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2163 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2164 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2166 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2168 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2171 // A Pox on Microsoft and it's Internet Explorer!
2173 // IE has lots of bugs with file downloads.
2174 // It also has problems with SSL. Both of these cause problems
2175 // for us in this function.
2177 // See this article on Cache Control headers and SSL
2178 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2180 // The best thing you can do for IE is to upgrade to the latest
2182 //set all the Cache Control Headers for IE
2184 $filename=rawurlencode($filename);
2185 header ("Pragma: public");
2186 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); # HTTP/1.1
2187 header ("Cache-Control: post-check=0, pre-check=0", false);
2188 header ("Cache-control: private");
2190 //set the inline header for IE, we'll add the attachment header later if we need it
2191 header ("Content-Disposition: inline; filename=$filename");
2195 // Try to show in browser window
2196 header ("Content-Disposition: inline; filename=\"$filename\"");
2197 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2199 // Try to pop up the "save as" box
2201 // IE makes this hard. It pops up 2 save boxes, or none.
2202 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2203 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2204 // But, according to Microsoft, it is "RFC compliant but doesn't
2205 // take into account some deviations that allowed within the
2206 // specification." Doesn't that mean RFC non-compliant?
2207 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2209 // all browsers need the application/octet-stream header for this
2210 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2212 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2213 // Do not have quotes around filename, but that applied to
2214 // "attachment"... does it apply to inline too?
2215 header ("Content-Disposition: attachment; filename=\"$filename\"");
2217 if ($isIE && !$isIE6) {
2218 // This combination seems to work mostly. IE 5.5 SP 1 has
2219 // known issues (see the Microsoft Knowledge Base)
2221 // This works for most types, but doesn't work with Word files
2222 header ("Content-Type: application/download; name=\"$filename\"");
2224 // These are spares, just in case. :-)
2225 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2226 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2227 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2229 // another application/octet-stream forces download for Netscape
2230 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2234 //send the content-length header if the calling function provides it
2235 if ($filesize > 0) {
2236 header("Content-Length: $filesize");
2239 } // end fn SendDownloadHeaders