9dd61e3f818b2a223875e0bfb621f5bc6c04ff64
6 * This contains the functions necessary to detect and decode MIME
9 * @copyright © 1999-2005 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @package squirrelmail
15 /** The typical includes... */
16 require_once(SM_PATH
. 'functions/imap.php');
17 require_once(SM_PATH
. 'functions/attachment_common.php');
18 /** add sqm_baseuri()*/
19 include_once(SM_PATH
. 'functions/display_messages.php');
21 /* -------------------------------------------------------------------------- */
23 /* -------------------------------------------------------------------------- */
26 * Get the MIME structure
28 * This function gets the structure of a message and stores it in the "message" class.
29 * It will return this object for use with all relevant header information and
30 * fully parsed into the standard "message" object format.
32 function mime_structure ($bodystructure, $flags=array()) {
34 /* Isolate the body structure and remove beginning and end parenthesis. */
35 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
36 $read = trim(substr ($read, 0, -1));
38 $msg = Message
::parseStructure($read,$i);
39 if (!is_object($msg)) {
40 include_once(SM_PATH
. 'functions/display_messages.php');
41 global $color, $mailbox;
42 /* removed urldecode because $_GET is auto urldecoded ??? */
43 displayPageHeader( $color, $mailbox );
44 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
45 $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
46 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
47 plain_error_message( $errormessage, $color );
48 echo '</body></html>';
52 foreach ($flags as $flag) {
53 $char = strtoupper($flag{1});
56 if (strtolower($flag) == '\\seen') {
61 if (strtolower($flag) == '\\answered') {
62 $msg->is_answered
= true;
66 if (strtolower($flag) == '\\deleted') {
67 $msg->is_deleted
= true;
71 if (strtolower($flag) == '\\flagged') {
72 $msg->is_flagged
= true;
76 if (strtolower($flag) == '$mdnsent') {
77 $msg->is_mdnsent
= true;
85 // listEntities($msg);
91 /* This starts the parsing of a particular structure. It is called recursively,
92 * so it can be passed different structures. It returns an object of type
94 * First, it checks to see if it is a multipart message. If it is, then it
95 * handles that as it sees is necessary. If it is just a regular entity,
96 * then it parses it and adds the necessary header information (by calling out
97 * to mime_get_elements()
100 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
101 /* Do a bit of error correction. If we couldn't find the entity id, just guess
102 * that it is the first one. That is usually the case anyway.
106 $cmd = "FETCH $id BODY[]";
108 $cmd = "FETCH $id BODY[$ent_id]";
111 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
113 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
115 $topline = trim(array_shift($data));
116 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
118 $wholemessage = implode('', $data);
119 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
120 $ret = substr($wholemessage, 0, $regs[1]);
121 /* There is some information in the content info header that could be important
122 * in order to parse html messages. Let's get them here.
124 // if ($ret{0} == '<') {
125 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
127 } else if (ereg('"([^"]*)"', $topline, $regs)) {
130 global $where, $what, $mailbox, $passed_id, $startMessage;
131 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
132 if (isset($where) && isset($what)) {
133 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
135 $par .= '&startMessage=' . $startMessage . '&show_more=0';
137 $par .= '&response=' . urlencode($response) .
138 '&message=' . urlencode($message) .
139 '&topline=' . urlencode($topline);
142 '<table width="80%"><tr>' .
143 '<tr><td colspan="2">' .
144 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
146 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
147 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
148 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
149 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
150 "</table><br /></tt></font><hr />";
152 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
154 $wholemessage = implode('', $data);
156 $ret = $wholemessage;
161 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
163 /* Don't kill the connection if the browser is over a dialup
164 * and it would take over 30 seconds to download it.
165 * Don't call set_time_limit in safe mode.
168 if (!ini_get('safe_mode')) {
171 /* in case of base64 encoded attachments, do not buffer them.
172 Instead, echo the decoded attachment directly to screen */
173 if (strtolower($encoding) == 'base64') {
175 $query = "FETCH $id BODY[]";
177 $query = "FETCH $id BODY[$ent_id]";
179 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
181 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
182 if (is_resource($rStream)) {
183 fputs($rStream,decodeBody($body,$encoding));
185 echo decodeBody($body, $encoding);
190 TODO, use the same method for quoted printable.
191 However, I assume that quoted printable attachments aren't that large
192 so the performancegain / memory usage drop will be minimal.
193 If we decide to add that then we need to adapt sqimap_fread because
194 we need to split te result on \n and fread doesn't stop at \n. That
195 means we also should provide $results from sqimap_fread (by ref) to
196 te function and set $no_return to false. The $filter function for
197 quoted printable should handle unsetting of $results.
200 TODO 2: find out how we write to the output stream php://stdout. fwrite
201 doesn't work because 'php://stdout isn't a stream.
207 /* -[ END MIME DECODING ]----------------------------------------------------------- */
209 /* This is here for debugging purposes. It will print out a list
210 * of all the entity IDs that are in the $message object.
212 function listEntities ($message) {
214 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
215 for ($i = 0; isset($message->entities
[$i]); $i++
) {
217 $msg = listEntities($message->entities
[$i]);
227 function getPriorityStr($priority) {
228 $priority_level = substr($priority,0,1);
230 switch($priority_level) {
231 /* Check for a higher then normal priority. */
234 $priority_string = _("High");
237 /* Check for a lower then normal priority. */
240 $priority_string = _("Low");
243 /* Check for a normal priority. */
246 $priority_level = '3';
247 $priority_string = _("Normal");
251 return $priority_string;
254 /* returns a $message object for a particular entity id */
255 function getEntity ($message, $ent_id) {
256 return $message->getEntity($ent_id);
260 * Extracted from strings.php 23/03/2002
263 function translateText(&$body, $wrap_at, $charset) {
264 global $where, $what; /* from searching */
265 global $color; /* color theme */
267 require_once(SM_PATH
. 'functions/url_parser.php');
269 $body_ary = explode("\n", $body);
270 for ($i=0; $i < count($body_ary); $i++
) {
271 $line = $body_ary[$i];
272 if (strlen($line) - 2 >= $wrap_at) {
273 sqWordWrap($line, $wrap_at, $charset);
275 $line = charset_decode($charset, $line);
276 $line = str_replace("\t", ' ', $line);
285 if ($line[$pos] == ' ') {
287 } else if (strpos($line, '>', $pos) === $pos) {
296 if (!isset($color[13])) {
297 $color[13] = '#800000';
299 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
301 if (!isset($color[14])) {
302 $color[14] = '#FF0000';
304 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
307 $body_ary[$i] = $line;
309 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
313 * This returns a parsed string called $body. That string can then
314 * be displayed as the actual message in the HTML. It contains
315 * everything needed, including HTML Tags, Attachments at the
318 * Since 1.2.0 function uses message_body hook.
319 * Till 1.3.0 function included output of formatAttachments().
321 * @param resource $imap_stream imap connection resource
322 * @param object $message squirrelmail message object
323 * @param array $color squirrelmail color theme array
324 * @param integer $wrap_at number of characters per line
325 * @param string $ent_num (since 1.3.0) message part id
326 * @param integer $id (since 1.3.0) message id
327 * @param string $mailbox (since 1.3.0) imap folder name
328 * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
329 * @return string html formated message text
331 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
332 /* This if statement checks for the entity to show as the
333 * primary message. To add more of them, just put them in the
334 * order that is their priority.
336 global $startMessage, $languages, $squirrelmail_language,
337 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id, $use_iframe,$iframe_height;
339 // workaround for not updated config.php
340 if (! isset($use_iframe)) $use_iframe = false;
342 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
343 $view_unsafe_images = false;
347 $urlmailbox = urlencode($mailbox);
348 $body_message = getEntity($message, $ent_num);
349 if (($body_message->header
->type0
== 'text') ||
350 ($body_message->header
->type0
== 'rfc822')) {
351 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
352 $body = decodeBody($body, $body_message->header
->encoding
);
354 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
355 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
356 if (mb_detect_encoding($body) != 'ASCII') {
357 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
360 $hookResults = do_hook("message_body", $body);
361 $body = $hookResults[1];
363 /* If there are other types that shouldn't be formatted, add
367 if ($body_message->header
->type1
== 'html') {
368 if ($show_html_default <> 1) {
369 $entity_conv = array(' ' => ' ',
378 $body = strtr($body, $entity_conv);
379 $body = strip_tags($body);
381 translateText($body, $wrap_at,
382 $body_message->header
->getParameter('charset'));
383 } elseif ($use_iframe && ! $clean) {
384 // $clean is used to remove iframe in printable view.
387 * If we don't add html message between iframe tags,
388 * we must detect unsafe images and modify $has_unsafe_images.
390 $html_body = magicHTML($body, $id, $message, $mailbox);
391 // Convert character set in order to display html mails in different character set
392 $html_body = charset_decode($body_message->header
->getParameter('charset'),$html_body,false,true);
394 // creating iframe url
395 $iframeurl=sqm_baseuri().'src/view_html.php?'
396 . 'mailbox=' . $urlmailbox
397 . '&passed_id=' . $id
398 . '&ent_id=' . $ent_num
399 . '&view_unsafe_images=' . (int) $view_unsafe_images;
401 // adding warning message
402 $body = html_tag('div',_("Viewing HTML formatted email"),'center');
405 * height can't be set to 100%, because it does not work as expected when
406 * iframe is inside the table. Browsers do not create full height objects
407 * even when iframe is not nested. Maybe there is some way to get full size
408 * with CSS. Tested in firefox 1.02 and opera 7.53
410 * width="100%" does not work as expected, when table width is not set (automatic)
412 * tokul: I think <iframe> are safer sandbox than <object>. Objects might
413 * need special handling for IE and IE6SP2.
415 $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
416 .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
418 // Message for browsers without iframe support
419 //$body.= _("Your browser does not support inline frames.
420 // You can view HTML formated message by following below link.");
421 //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
423 // if browser can't render iframe, it renders html message.
427 $body.="</iframe></div>\n";
429 // old way of html rendering
430 $body = magicHTML($body, $id, $message, $mailbox);
432 * convert character set. charset_decode does not remove html special chars
433 * applied by magicHTML functions and does not sanitize them second time if
434 * fourth argument is true.
436 $body = charset_decode($body_message->header
->getParameter('charset'),$body,false,true);
439 translateText($body, $wrap_at,
440 $body_message->header
->getParameter('charset'));
443 // if this is the clean display (i.e. printer friendly), stop here.
448 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
449 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
450 '&startMessage=' . $startMessage . '&show_more=0';
451 if (isset($passed_ent_id)) {
452 $link .= '&passed_ent_id='.$passed_ent_id;
454 $body .= '<center><small><a href="download.php?absolute_dl=true&' .
455 $link . '">' . _("Download this as a file") . '</a>';
456 if ($view_unsafe_images) {
457 $text = _("Hide Unsafe Images");
459 if (isset($has_unsafe_images) && $has_unsafe_images) {
460 $link .= '&view_unsafe_images=1';
461 $text = _("View Unsafe Images");
467 $body .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
469 $body .= '</small></center><br />' . "\n";
475 * Displays attachment links and information
477 * Since 1.3.0 function is not included in formatBody() call.
479 * Since 1.0.2 uses attachment $type0/$type1 hook.
480 * Since 1.2.5 uses attachment $type0/* hook.
481 * Since 1.5.0 uses attachments_bottom hook.
483 * @param object $message SquirrelMail message object
484 * @param array $exclude_id message parts that are not attachments.
485 * @param string $mailbox mailbox name
486 * @param integer $id message id
487 * @return string html formated attachment information.
489 function formatAttachments($message, $exclude_id, $mailbox, $id) {
490 global $where, $what, $startMessage, $color, $passed_ent_id;
492 $att_ar = $message->getAttachments($exclude_id);
494 if (!count($att_ar)) return '';
498 $urlMailbox = urlencode($mailbox);
500 foreach ($att_ar as $att) {
501 $ent = $att->entity_id
;
502 $header = $att->header
;
503 $type0 = strtolower($header->type0
);
504 $type1 = strtolower($header->type1
);
506 $links['download link']['text'] = _("Download");
507 $links['download link']['href'] = sqm_baseuri() .
508 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
509 if ($type0 =='message' && $type1 == 'rfc822') {
510 $default_page = sqm_baseuri() . 'src/read_body.php';
511 $rfc822_header = $att->rfc822_header
;
512 $filename = $rfc822_header->subject
;
513 if (trim( $filename ) == '') {
514 $filename = 'untitled-[' . $ent . ']' ;
516 $from_o = $rfc822_header->from
;
517 if (is_object($from_o)) {
518 $from_name = decodeHeader($from_o->getAddress(false));
520 $from_name = _("Unknown sender");
522 $description = $from_name;
524 $default_page = sqm_baseuri() . 'src/download.php';
525 $filename = $att->getFilename();
526 if ($header->description
) {
527 $description = decodeHeader($header->description
);
533 $display_filename = $filename;
534 if (isset($passed_ent_id)) {
535 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
537 $passed_ent_id_link = '';
539 $defaultlink = $default_page . "?startMessage=$startMessage"
540 . "&passed_id=$id&mailbox=$urlMailbox"
541 . '&ent_id='.$ent.$passed_ent_id_link;
542 if ($where && $what) {
543 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
546 /* This executes the attachment hook with a specific MIME-type.
547 * If that doesn't have results, it tries if there's a rule
548 * for a more generic type.
550 $hookresults = do_hook("attachment $type0/$type1", $links,
551 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
552 $display_filename, $where, $what);
553 if(count($hookresults[1]) <= 1) {
554 $hookresults = do_hook("attachment $type0/*", $links,
555 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
556 $display_filename, $where, $what);
559 $links = $hookresults[1];
560 $defaultlink = $hookresults[6];
562 $attachments .= '<tr><td>' .
563 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
564 '<td><small><b>' . show_readable_size($header->size
) .
565 '</b> </small></td>' .
566 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
568 $attachments .= '<b>' . $description . '</b>';
569 $attachments .= '</small></td><td><small> ';
572 foreach ($links as $val) {
576 $attachments .= ' | ';
578 $attachments .= '<a href="' . $val['href'] . '">'
579 . (isset($val['text']) && !empty($val['text']) ?
$val['text'] : '')
580 . (isset($val['extra']) && !empty($val['extra']) ?
$val['extra'] : '')
584 $attachments .= "</td></tr>\n";
586 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
587 if ($attachmentadd != '')
588 $attachments = $attachmentadd;
592 function sqimap_base64_decode(&$string) {
594 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
595 // fly decoding (to reduce memory usage) you have to check if the
596 // data has incomplete pairs
598 // Remove the noise in order to check if the 4 bytes pairs are complete
599 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
602 $iMod = strlen($string) %
4;
604 $sStringRem = substr($string,-$iMod);
605 // Check if $sStringRem contains padding characters
606 if (substr($sStringRem,-1) != '=') {
607 $string = substr($string,0,-$iMod);
612 $string = base64_decode($string);
617 * Decodes encoded message body
619 * This function decodes the body depending on the encoding type.
620 * Currently quoted-printable and base64 encodings are supported.
621 * decode_body hook was added to this function in 1.4.2/1.5.0
622 * @param string $body encoded message body
623 * @param string $encoding used encoding
624 * @return string decoded string
627 function decodeBody($body, $encoding) {
629 $body = str_replace("\r\n", "\n", $body);
630 $encoding = strtolower($encoding);
632 $encoding_handler = do_hook_function('decode_body', $encoding);
635 // plugins get first shot at decoding the body
637 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
638 $body = $encoding_handler('decode', $body);
640 } elseif ($encoding == 'quoted-printable' ||
641 $encoding == 'quoted_printable') {
643 * quoted_printable_decode() function is broken in older
644 * php versions. Text with \r\n decoding was fixed only
645 * in php 4.3.0. Minimal code requirement 4.0.4 +
646 * str_replace("\r\n", "\n", $body); call.
648 $body = quoted_printable_decode($body);
649 } elseif ($encoding == 'base64') {
650 $body = base64_decode($body);
653 // All other encodings are returned raw.
660 * This functions decode strings that is encoded according to
661 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
662 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
664 * @param string $string header string that has to be made readable
665 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
666 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
667 * @param boolean $decide decide if string can be utfencoded. defaults to false
668 * @return string decoded header string
670 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
671 global $languages, $squirrelmail_language,$default_charset;
672 if (is_array($string)) {
673 $string = implode("\n", $string);
676 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
677 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
678 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
679 // Do we need to return at this point?
686 $aString = explode(' ',$string);
688 foreach ($aString as $chunk) {
689 if ($encoded && $chunk === '') {
691 } elseif ($chunk === '') {
696 /* if encoded words are not separated by a linear-space-white we still catch them */
699 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
700 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
701 if ($iLastMatch !== $j) {
711 $ret .= htmlspecialchars($res[1]);
715 $encoding = ucfirst($res[3]);
717 /* decide about valid decoding */
718 if ($decide && is_conversion_safe($res[2])) {
720 $can_be_encoded=true;
722 $can_be_encoded=false;
727 $replace = base64_decode($res[4]);
729 if ($can_be_encoded) {
730 /* convert string to different charset,
731 * if functions asks for it (usually in compose)
733 $ret .= charset_convert($res[2],$replace,$default_charset);
735 // convert string to html codes in order to display it
736 $ret .= charset_decode($res[2],$replace);
740 $replace = htmlspecialchars($replace);
746 $replace = str_replace('_', ' ', $res[4]);
747 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
750 if ($can_be_encoded) {
751 /* convert string to different charset,
752 * if functions asks for it (usually in compose)
754 $replace = charset_convert($res[2], $replace,$default_charset);
756 // convert string to html codes in order to display it
757 $replace = charset_decode($res[2], $replace);
761 $replace = htmlspecialchars($replace);
780 if (!$encoded && $htmlsave) {
781 $ret .= htmlspecialchars($chunk);
787 /* remove the first added space */
790 $ret = substr($ret,5);
792 $ret = substr($ret,1);
802 * Function uses XTRA_CODE _encodeheader function, if such function exists.
804 * Function uses Q encoding by default and encodes a string according to RFC
805 * 1522 for use in headers if it contains 8-bit characters or anything that
806 * looks like it should be encoded.
808 * Function switches to B encoding and encodeHeaderBase64() function, if
809 * string is 8bit and multibyte character set supported by mbstring extension
810 * is used. It can cause E_USER_NOTICE errors, if interface is used with
811 * multibyte character set unsupported by mbstring extension.
813 * @param string $string header string, that has to be encoded
814 * @return string quoted-printable encoded string
815 * @todo make $mb_charsets system wide constant
817 function encodeHeader ($string) {
818 global $default_charset, $languages, $squirrelmail_language;
820 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
821 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
822 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
825 // Use B encoding for multibyte charsets
826 $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
827 if (in_array($default_charset,$mb_charsets) &&
828 in_array($default_charset,sq_mb_list_encodings()) &&
829 sq_is8bit($string)) {
830 return encodeHeaderBase64($string,$default_charset);
831 } elseif (in_array($default_charset,$mb_charsets) &&
832 sq_is8bit($string) &&
833 ! in_array($default_charset,sq_mb_list_encodings())) {
834 // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
835 // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
838 // Encode only if the string contains 8-bit characters or =?
839 $j = strlen($string);
840 $max_l = 75 - strlen($default_charset) - 7;
843 $iEncStart = $enc_init = false;
844 $cur_l = $iOffset = 0;
845 for($i = 0; $i < $j; ++
$i) {
854 if ($iEncStart === false) {
858 if ($cur_l > ($max_l-2)) {
859 /* if there is an stringpart that doesn't need encoding, add it */
860 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
861 $aRet[] = "=?$default_charset?Q?$ret?=";
867 $ret .= sprintf("=%02X",ord($string{$i}));
872 if ($iEncStart !== false) {
873 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
874 $aRet[] = "=?$default_charset?Q?$ret?=";
882 if ($iEncStart !== false) {
884 if ($cur_l > $max_l) {
885 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
886 $aRet[] = "=?$default_charset?Q?$ret?=";
897 $k = ord($string{$i});
899 if ($iEncStart === false) {
900 // do not start encoding in the middle of a string, also take the rest of the word.
901 $sLeadString = substr($string,0,$i);
902 $aLeadString = explode(' ',$sLeadString);
903 $sToBeEncoded = array_pop($aLeadString);
904 $iEncStart = $i - strlen($sToBeEncoded);
905 $ret .= $sToBeEncoded;
906 $cur_l +
= strlen($sToBeEncoded);
909 /* first we add the encoded string that reached it's max size */
910 if ($cur_l > ($max_l-2)) {
911 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
912 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
919 $ret .= sprintf("=%02X", $k);
921 if ($iEncStart !== false) {
923 if ($cur_l > $max_l) {
924 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
925 $aRet[] = "=?$default_charset?Q?$ret?=";
940 if ($iEncStart !== false) {
941 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
942 $aRet[] = "=?$default_charset?Q?$ret?=";
944 $aRet[] = substr($string,$iOffset);
946 $string = implode('',$aRet);
952 * Encodes string according to rfc2047 B encoding header formating rules
954 * It is recommended way to encode headers with character sets that store
955 * symbols in more than one byte.
957 * Function requires mbstring support. If required mbstring functions are missing,
958 * function returns false and sets E_USER_WARNING level error message.
960 * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
961 * that mbstring functions will generate E_WARNING errors, if unsupported
962 * character set is used. mb_encode_mimeheader function provided by php
963 * mbstring extension is not used in order to get better control of header
966 * Used php code functions - function_exists(), trigger_error(), strlen()
967 * (is used with charset names and base64 strings). Used php mbstring
968 * functions - mb_strlen and mb_substr.
970 * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
971 * encoding), rfc 2822 (header folding)
973 * @param string $string header string that must be encoded
974 * @param string $charset character set. Must be supported by mbstring extension.
975 * Use sq_mb_list_encodings() to detect supported charsets.
976 * @return string string encoded according to rfc2047 B encoding formating rules
978 * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
979 * @todo Do we want to control max length of header?
980 * @todo Do we want to control EOL (end-of-line) marker?
981 * @todo Do we want to translate error message?
983 function encodeHeaderBase64($string,$charset) {
985 * Check mbstring function requirements.
987 if (! function_exists('mb_strlen') ||
988 ! function_exists('mb_substr')) {
989 // set E_USER_WARNING
990 trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING
);
995 // initial return array
999 * header length = 75 symbols max (same as in encodeHeader)
1000 * remove $charset length
1001 * remove =? ? ?= (5 chars)
1002 * remove 2 more chars (\r\n ?)
1004 $iMaxLength = 75 - strlen($charset) - 7;
1006 // set first character position
1009 // loop through all characters. count characters and not bytes.
1010 for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++
) {
1011 // encode string from starting character to current character.
1012 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1014 // Check encoded string length
1015 if(strlen($encoded_string)>$iMaxLength) {
1016 // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
1017 $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
1019 // set new starting character
1020 $iStartCharNum = $iCharNum-1;
1022 // encode last char (in case it is last character in string)
1023 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1024 } // if string is shorter than max length - add next character
1027 // add last encoded string to array
1028 $aRet[] = $encoded_string;
1030 // set initial return string
1033 // loop through encoded strings
1034 foreach($aRet as $string) {
1035 // TODO: Do we want to control EOL (end-of-line) marker
1036 if ($sRet!='') $sRet.= " ";
1038 // add header tags and encoded string to return string
1039 $sRet.= '=?'.$charset.'?B?'.$string.'?=';
1045 /* This function trys to locate the entity_id of a specific mime element */
1046 function find_ent_id($id, $message) {
1047 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
1048 if ($message->entities
[$i]->header
->type0
== 'multipart') {
1049 $ret = find_ent_id($id, $message->entities
[$i]);
1051 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
1052 // if (sq_check_save_extension($message->entities[$i])) {
1053 return $message->entities
[$i]->entity_id
;
1055 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
1057 * This is part of a fix for Outlook Express 6.x generating
1058 * cid URLs without creating content-id headers
1061 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
1062 return $message->entities
[$i]->entity_id
;
1070 function sq_check_save_extension($message) {
1071 $filename = $message->getFilename();
1072 $ext = substr($filename, strrpos($filename,'.')+
1);
1073 $save_extensions = array('jpg','jpeg','gif','png','bmp');
1074 return in_array($ext, $save_extensions);
1079 ** HTMLFILTER ROUTINES
1083 * This function checks attribute values for entity-encoded values
1084 * and returns them translated into 8-bit strings so we can run
1087 * @param $attvalue A string to run entity check against.
1088 * @return Nothing, modifies a reference value.
1090 function sq_defang(&$attvalue){
1093 * Skip this if there aren't ampersands or backslashes.
1095 if (strpos($attvalue, '&') === false
1096 && strpos($attvalue, '\\') === false){
1102 $m = $m ||
sq_deent($attvalue, '/\�*(\d+);*/s');
1103 $m = $m ||
sq_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true);
1104 $m = $m ||
sq_deent($attvalue, '/\\\\(\d+)/s', true);
1105 } while ($m == true);
1106 $attvalue = stripslashes($attvalue);
1110 * Kill any tabs, newlines, or carriage returns. Our friends the
1111 * makers of the browser with 95% market value decided that it'd
1112 * be funny to make "java[tab]script" be just as good as "javascript".
1114 * @param attvalue The attribute value before extraneous spaces removed.
1115 * @return attvalue Nothing, modifies a reference value.
1117 function sq_unspace(&$attvalue){
1119 if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
1120 $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
1121 Array('', '', '', '', ''), $attvalue);
1126 * This function returns the final tag out of the tag name, an array
1127 * of attributes, and the type of the tag. This function is called by
1128 * sq_sanitize internally.
1130 * @param $tagname the name of the tag.
1131 * @param $attary the array of attributes and their values
1132 * @param $tagtype The type of the tag (see in comments).
1133 * @return a string with the final tag representation.
1135 function sq_tagprint($tagname, $attary, $tagtype){
1136 $me = 'sq_tagprint';
1139 $fulltag = '</' . $tagname . '>';
1141 $fulltag = '<' . $tagname;
1142 if (is_array($attary) && sizeof($attary)){
1144 while (list($attname, $attvalue) = each($attary)){
1145 array_push($atts, "$attname=$attvalue");
1147 $fulltag .= ' ' . join(" ", $atts);
1158 * A small helper function to use with array_walk. Modifies a by-ref
1159 * value and makes it lowercase.
1161 * @param $val a value passed by-ref.
1162 * @return void since it modifies a by-ref value.
1164 function sq_casenormalize(&$val){
1165 $val = strtolower($val);
1169 * This function skips any whitespace from the current position within
1170 * a string and to the next non-whitespace value.
1172 * @param $body the string
1173 * @param $offset the offset within the string where we should start
1174 * looking for the next non-whitespace character.
1175 * @return the location within the $body where the next
1176 * non-whitespace char is located.
1178 function sq_skipspace($body, $offset){
1179 $me = 'sq_skipspace';
1180 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1181 if (sizeof($matches{1})){
1182 $count = strlen($matches{1});
1189 * This function looks for the next character within a string. It's
1190 * really just a glorified "strpos", except it catches if failures
1193 * @param $body The string to look for needle in.
1194 * @param $offset Start looking from this position.
1195 * @param $needle The character/string to look for.
1196 * @return location of the next occurance of the needle, or
1197 * strlen($body) if needle wasn't found.
1199 function sq_findnxstr($body, $offset, $needle){
1200 $me = 'sq_findnxstr';
1201 $pos = strpos($body, $needle, $offset);
1202 if ($pos === FALSE){
1203 $pos = strlen($body);
1209 * This function takes a PCRE-style regexp and tries to match it
1210 * within the string.
1212 * @param $body The string to look for needle in.
1213 * @param $offset Start looking from here.
1214 * @param $reg A PCRE-style regex to match.
1215 * @return Returns a false if no matches found, or an array
1216 * with the following members:
1217 * - integer with the location of the match within $body
1218 * - string with whatever content between offset and the match
1219 * - string with whatever it is we matched
1221 function sq_findnxreg($body, $offset, $reg){
1222 $me = 'sq_findnxreg';
1225 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1226 if (!isset($matches{0}) ||
!$matches{0}){
1229 $retarr{0} = $offset +
strlen($matches{1});
1230 $retarr{1} = $matches{1};
1231 $retarr{2} = $matches{2};
1237 * This function looks for the next tag.
1239 * @param $body String where to look for the next tag.
1240 * @param $offset Start looking from here.
1241 * @return false if no more tags exist in the body, or
1242 * an array with the following members:
1243 * - string with the name of the tag
1244 * - array with attributes and their values
1245 * - integer with tag type (1, 2, or 3)
1246 * - integer where the tag starts (starting "<")
1247 * - integer where the tag ends (ending ">")
1248 * first three members will be false, if the tag is invalid.
1250 function sq_getnxtag($body, $offset){
1251 $me = 'sq_getnxtag';
1252 if ($offset > strlen($body)){
1255 $lt = sq_findnxstr($body, $offset, "<");
1256 if ($lt == strlen($body)){
1261 * blah blah <tag attribute="value">
1264 $pos = sq_skipspace($body, $lt+
1);
1265 if ($pos >= strlen($body)){
1266 return Array(false, false, false, $lt, strlen($body));
1269 * There are 3 kinds of tags:
1270 * 1. Opening tag, e.g.:
1272 * 2. Closing tag, e.g.:
1274 * 3. XHTML-style content-less tag, e.g.:
1275 * <img src="blah" />
1278 switch (substr($body, $pos, 1)){
1285 * A comment or an SGML declaration.
1287 if (substr($body, $pos+
1, 2) == "--"){
1288 $gt = strpos($body, "-->", $pos);
1290 $gt = strlen($body);
1294 return Array(false, false, false, $lt, $gt);
1296 $gt = sq_findnxstr($body, $pos, ">");
1297 return Array(false, false, false, $lt, $gt);
1302 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1312 * Look for next [\W-_], which will indicate the end of the tag name.
1314 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1315 if ($regary == false){
1316 return Array(false, false, false, $lt, strlen($body));
1318 list($pos, $tagname, $match) = $regary;
1319 $tagname = strtolower($tagname);
1322 * $match can be either of these:
1323 * '>' indicating the end of the tag entirely.
1324 * '\s' indicating the end of the tag name.
1325 * '/' indicating that this is type-3 xhtml tag.
1327 * Whatever else we find there indicates an invalid tag.
1332 * This is an xhtml-style tag with a closing / at the
1333 * end, like so: <img src="blah" />. Check if it's followed
1334 * by the closing bracket. If not, then this tag is invalid
1336 if (substr($body, $pos, 2) == "/>"){
1340 $gt = sq_findnxstr($body, $pos, ">");
1341 $retary = Array(false, false, false, $lt, $gt);
1345 return Array($tagname, false, $tagtype, $lt, $pos);
1349 * Check if it's whitespace
1351 if (!preg_match('/\s/', $match)){
1353 * This is an invalid tag! Look for the next closing ">".
1355 $gt = sq_findnxstr($body, $lt, ">");
1356 return Array(false, false, false, $lt, $gt);
1362 * At this point we're here:
1363 * <tagname attribute='blah'>
1366 * At this point we loop in order to find all attributes.
1372 while ($pos <= strlen($body)){
1373 $pos = sq_skipspace($body, $pos);
1374 if ($pos == strlen($body)){
1378 return Array(false, false, false, $lt, $pos);
1381 * See if we arrived at a ">" or "/>", which means that we reached
1382 * the end of the tag.
1385 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1389 $pos +
= strlen($matches{1});
1390 if ($matches{2} == "/>"){
1394 return Array($tagname, $attary, $tagtype, $lt, $pos);
1398 * There are several types of attributes, with optional
1399 * [:space:] between members.
1401 * attrname[:space:]=[:space:]'CDATA'
1403 * attrname[:space:]=[:space:]"CDATA"
1405 * attr[:space:]=[:space:]CDATA
1409 * We leave types 1 and 2 the same, type 3 we check for
1410 * '"' and convert to """ if needed, then wrap in
1411 * double quotes. Type 4 we convert into:
1414 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1415 if ($regary == false){
1417 * Looks like body ended before the end of tag.
1419 return Array(false, false, false, $lt, strlen($body));
1421 list($pos, $attname, $match) = $regary;
1422 $attname = strtolower($attname);
1424 * We arrived at the end of attribute name. Several things possible
1426 * '>' means the end of the tag and this is attribute type 4
1427 * '/' if followed by '>' means the same thing as above
1428 * '\s' means a lot of things -- look what it's followed by.
1429 * anything else means the attribute is invalid.
1434 * This is an xhtml-style tag with a closing / at the
1435 * end, like so: <img src="blah" />. Check if it's followed
1436 * by the closing bracket. If not, then this tag is invalid
1438 if (substr($body, $pos, 2) == "/>"){
1442 $gt = sq_findnxstr($body, $pos, ">");
1443 $retary = Array(false, false, false, $lt, $gt);
1447 $attary{$attname} = '"yes"';
1448 return Array($tagname, $attary, $tagtype, $lt, $pos);
1452 * Skip whitespace and see what we arrive at.
1454 $pos = sq_skipspace($body, $pos);
1455 $char = substr($body, $pos, 1);
1457 * Two things are valid here:
1458 * '=' means this is attribute type 1 2 or 3.
1459 * \w means this was attribute type 4.
1460 * anything else we ignore and re-loop. End of tag and
1461 * invalid stuff will be caught by our checks at the beginning
1466 $pos = sq_skipspace($body, $pos);
1468 * Here are 3 possibilities:
1469 * "'" attribute type 1
1470 * '"' attribute type 2
1471 * everything else is the content of tag type 3
1473 $quot = substr($body, $pos, 1);
1475 $regary = sq_findnxreg($body, $pos+
1, "\'");
1476 if ($regary == false){
1477 return Array(false, false, false, $lt, strlen($body));
1479 list($pos, $attval, $match) = $regary;
1481 $attary{$attname} = "'" . $attval . "'";
1482 } else if ($quot == '"'){
1483 $regary = sq_findnxreg($body, $pos+
1, '\"');
1484 if ($regary == false){
1485 return Array(false, false, false, $lt, strlen($body));
1487 list($pos, $attval, $match) = $regary;
1489 $attary{$attname} = '"' . $attval . '"';
1492 * These are hateful. Look for \s, or >.
1494 $regary = sq_findnxreg($body, $pos, "[\s>]");
1495 if ($regary == false){
1496 return Array(false, false, false, $lt, strlen($body));
1498 list($pos, $attval, $match) = $regary;
1500 * If it's ">" it will be caught at the top.
1502 $attval = preg_replace("/\"/s", """, $attval);
1503 $attary{$attname} = '"' . $attval . '"';
1505 } else if (preg_match("|[\w/>]|", $char)) {
1507 * That was attribute type 4.
1509 $attary{$attname} = '"yes"';
1512 * An illegal character. Find next '>' and return.
1514 $gt = sq_findnxstr($body, $pos, ">");
1515 return Array(false, false, false, $lt, $gt);
1521 * The fact that we got here indicates that the tag end was never
1522 * found. Return invalid tag indication so it gets stripped.
1524 return Array(false, false, false, $lt, strlen($body));
1528 * Translates entities into literal values so they can be checked.
1530 * @param $attvalue the by-ref value to check.
1531 * @param $regex the regular expression to check against.
1532 * @param $hex whether the entites are hexadecimal.
1533 * @return True or False depending on whether there were matches.
1535 function sq_deent(&$attvalue, $regex, $hex=false){
1538 preg_match_all($regex, $attvalue, $matches);
1539 if (is_array($matches) && sizeof($matches[0]) > 0){
1541 for ($i = 0; $i < sizeof($matches[0]); $i++
){
1542 $numval = $matches[1][$i];
1544 $numval = hexdec($numval);
1546 $repl{$matches[0][$i]} = chr($numval);
1548 $attvalue = strtr($attvalue, $repl);
1556 * This function runs various checks against the attributes.
1558 * @param $tagname String with the name of the tag.
1559 * @param $attary Array with all tag attributes.
1560 * @param $rm_attnames See description for sq_sanitize
1561 * @param $bad_attvals See description for sq_sanitize
1562 * @param $add_attr_to_tag See description for sq_sanitize
1563 * @param $message message object
1564 * @param $id message id
1565 * @return Array with modified attributes.
1567 function sq_fixatts($tagname,
1577 while (list($attname, $attvalue) = each($attary)){
1579 * See if this attribute should be removed.
1581 foreach ($rm_attnames as $matchtag=>$matchattrs){
1582 if (preg_match($matchtag, $tagname)){
1583 foreach ($matchattrs as $matchattr){
1584 if (preg_match($matchattr, $attname)){
1585 unset($attary{$attname});
1592 * Remove any backslashes, entities, and extraneous whitespace.
1594 sq_defang($attvalue);
1595 sq_unspace($attvalue);
1598 * Now let's run checks on the attvalues.
1599 * I don't expect anyone to comprehend this. If you do,
1600 * get in touch with me so I can drive to where you live and
1601 * shake your hand personally. :)
1603 foreach ($bad_attvals as $matchtag=>$matchattrs){
1604 if (preg_match($matchtag, $tagname)){
1605 foreach ($matchattrs as $matchattr=>$valary){
1606 if (preg_match($matchattr, $attname)){
1608 * There are two arrays in valary.
1610 * Second one is replacements
1612 list($valmatch, $valrepl) = $valary;
1614 preg_replace($valmatch, $valrepl, $attvalue);
1615 if ($newvalue != $attvalue){
1616 $attary{$attname} = $newvalue;
1624 * Replace empty src tags with the blank image. src is only used
1625 * for frames, images, and image inputs. Doing a replace should
1626 * not affect them working as should be, however it will stop
1627 * IE from being kicked off when src for img tags are not set
1629 if (($attname == 'src') && ($attvalue == '""')) {
1630 $attary{$attname} = '"' . SM_PATH
. 'images/blank.png"';
1634 * Turn cid: urls into http-friendly ones.
1636 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1637 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1641 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1642 * One day MS might actually make it match something useful, for now, falling
1643 * back to using cid2http, so we can grab the blank.png.
1645 if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
1646 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1651 * See if we need to append any attributes to this tag.
1653 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1654 if (preg_match($matchtag, $tagname)){
1655 $attary = array_merge($attary, $addattary);
1662 * This function edits the style definition to make them friendly and
1663 * usable in SquirrelMail.
1665 * @param $message the message object
1666 * @param $id the message id
1667 * @param $content a string with whatever is between <style> and </style>
1668 * @param $mailbox the message mailbox
1669 * @return a string with edited content.
1671 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1672 global $view_unsafe_images;
1673 $me = 'sq_fixstyle';
1674 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1676 return array(FALSE, strlen($body));
1678 $newpos = $ret[0] +
strlen($ret[2]);
1681 * First look for general BODY style declaration, which would be
1683 * body {background: blah-blah}
1684 * and change it to .bodyclass so we can just assign it to a <div>
1686 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1687 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1689 * Fix url('blah') declarations.
1691 // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1692 // "url(\\1$secremoveimg\\2)", $content);
1694 $content = str_replace("\0", "", $content);
1696 // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
1697 while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
1698 $sProto = strtolower($matches[1]);
1701 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1706 if (!$view_unsafe_images){
1708 $sExpr = "/url\s*\(\s*[\'\"]?\s*$sProto*:.*[\'\"]?\s*\)/si";
1709 $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
1712 $content = preg_replace('/url/i',"u\0r\0l",$content);
1716 * Fix urls that refer to cid:
1719 $cidurl = 'cid:'. $matches[2];
1720 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1721 // escape parentheses that can modify the regular expression
1722 $cidurl = str_replace(array('(',')'),array('\\(','\\)'),$cidurl);
1723 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1724 "u\0r\0l($httpurl)", $content);
1728 * replace url with protocol other then the white list
1729 * http,https and cid by an empty string.
1731 $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
1737 $content = str_replace("\0", "", $content);
1739 * Remove any backslashes, entities, and extraneous whitespace.
1741 $contentTemp = $content;
1742 sq_defang($contentTemp);
1743 sq_unspace($contentTemp);
1746 * Fix stupid css declarations which lead to vulnerabilities
1749 $match = Array('/expression/i',
1752 '/include-source/i');
1753 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1754 $contentNew = preg_replace($match, $replace, $contentTemp);
1755 if ($contentNew !== $contentTemp) {
1756 // insecure css declarations are used. From now on we don't care
1757 // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
1758 $content = $contentNew;
1760 return array($content, $newpos);
1765 * This function converts cid: url's into the ones that can be viewed in
1768 * @param $message the message object
1769 * @param $id the message id
1770 * @param $cidurl the cid: url.
1771 * @param $mailbox the message mailbox
1772 * @return a string with a http-friendly url
1774 function sq_cid2http($message, $id, $cidurl, $mailbox){
1776 * Get rid of quotes.
1778 $quotchar = substr($cidurl, 0, 1);
1779 if ($quotchar == '"' ||
$quotchar == "'"){
1780 $cidurl = str_replace($quotchar, "", $cidurl);
1784 $cidurl = substr(trim($cidurl), 4);
1786 $match_str = '/\{.*?\}\//';
1788 $cidurl = preg_replace($match_str, $str_rep, $cidurl);
1790 $linkurl = find_ent_id($cidurl, $message);
1791 /* in case of non-save cid links $httpurl should be replaced by a sort of
1792 unsave link image */
1796 * This is part of a fix for Outlook Express 6.x generating
1797 * cid URLs without creating content-id headers. These images are
1798 * not part of the multipart/related html mail. The html contains
1799 * <img src="cid:{some_id}/image_filename.ext"> references to
1800 * attached images with as goal to render them inline although
1801 * the attachment disposition property is not inline.
1804 if (empty($linkurl)) {
1805 if (preg_match('/{.*}\//', $cidurl)) {
1806 $cidurl = preg_replace('/{.*}\//','', $cidurl);
1807 if (!empty($cidurl)) {
1808 $linkurl = find_ent_id($cidurl, $message);
1813 if (!empty($linkurl)) {
1814 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1815 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1816 '&ent_id=' . $linkurl . $quotchar;
1819 * If we couldn't generate a proper img url, drop in a blank image
1820 * instead of sending back empty, otherwise it causes unusual behaviour
1822 $httpurl = $quotchar . SM_PATH
. 'images/blank.png' . $quotchar;
1829 * This function changes the <body> tag into a <div> tag since we
1830 * can't really have a body-within-body.
1832 * @param $attary an array of attributes and values of <body>
1833 * @param $mailbox mailbox we're currently reading (for cid2http)
1834 * @param $message current message (for cid2http)
1835 * @param $id current message id (for cid2http)
1836 * @return a modified array of attributes to be set for <div>
1838 function sq_body2div($attary, $mailbox, $message, $id){
1839 $me = 'sq_body2div';
1840 $divattary = Array('class' => "'bodyclass'");
1842 $has_bgc_stl = $has_txt_stl = false;
1844 if (is_array($attary) && sizeof($attary) > 0){
1845 foreach ($attary as $attname=>$attvalue){
1846 $quotchar = substr($attvalue, 0, 1);
1847 $attvalue = str_replace($quotchar, "", $attvalue);
1850 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1851 $styledef .= "background-image: url('$attvalue'); ";
1854 $has_bgc_stl = true;
1855 $styledef .= "background-color: $attvalue; ";
1858 $has_txt_stl = true;
1859 $styledef .= "color: $attvalue; ";
1863 // Outlook defines a white bgcolor and no text color. This can lead to
1864 // white text on a white bg with certain themes.
1865 if ($has_bgc_stl && !$has_txt_stl) {
1866 $styledef .= "color: $text; ";
1868 if (strlen($styledef) > 0){
1869 $divattary{"style"} = "\"$styledef\"";
1876 * This is the main function and the one you should actually be calling.
1877 * There are several variables you should be aware of an which need
1878 * special description.
1880 * Since the description is quite lengthy, see it here:
1881 * http://linux.duke.edu/projects/mini/htmlfilter/
1883 * @param $body the string with HTML you wish to filter
1884 * @param $tag_list see description above
1885 * @param $rm_tags_with_content see description above
1886 * @param $self_closing_tags see description above
1887 * @param $force_tag_closing see description above
1888 * @param $rm_attnames see description above
1889 * @param $bad_attvals see description above
1890 * @param $add_attr_to_tag see description above
1891 * @param $message message object
1892 * @param $id message id
1893 * @return sanitized html safe to show on your pages.
1895 function sq_sanitize($body,
1897 $rm_tags_with_content,
1907 $me = 'sq_sanitize';
1908 $rm_tags = array_shift($tag_list);
1910 * Normalize rm_tags and rm_tags_with_content.
1912 @array_walk
($tag_list, 'sq_casenormalize');
1913 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1914 @array_walk
($self_closing_tags, 'sq_casenormalize');
1916 * See if tag_list is of tags to remove or tags to allow.
1917 * false means remove these tags
1918 * true means allow these tags
1921 $open_tags = Array();
1922 $trusted = "\n<!-- begin sanitized html -->\n";
1923 $skip_content = false;
1925 * Take care of netscape's stupid javascript entities like
1928 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1930 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1931 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1932 $free_content = substr($body, $curpos, $lt-$curpos);
1934 * Take care of <style>
1936 if ($tagname == "style" && $tagtype == 1){
1937 list($free_content, $curpos) =
1938 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1939 if ($free_content != FALSE){
1940 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1941 $trusted .= $free_content;
1942 $trusted .= sq_tagprint($tagname, false, 2);
1946 if ($skip_content == false){
1947 $trusted .= $free_content;
1949 if ($tagname != FALSE){
1951 if ($skip_content == $tagname){
1953 * Got to the end of tag we needed to remove.
1956 $skip_content = false;
1958 if ($skip_content == false){
1959 if ($tagname == "body"){
1962 if (isset($open_tags{$tagname}) &&
1963 $open_tags{$tagname} > 0){
1964 $open_tags{$tagname}--;
1972 * $rm_tags_with_content
1974 if ($skip_content == false){
1976 * See if this is a self-closing type and change
1977 * tagtype appropriately.
1980 && in_array($tagname, $self_closing_tags)){
1984 * See if we should skip this tag and any content
1987 if ($tagtype == 1 &&
1988 in_array($tagname, $rm_tags_with_content)){
1989 $skip_content = $tagname;
1991 if (($rm_tags == false
1992 && in_array($tagname, $tag_list)) ||
1993 ($rm_tags == true &&
1994 !in_array($tagname, $tag_list))){
1998 * Convert body into div.
2000 if ($tagname == "body"){
2002 $attary = sq_body2div($attary, $mailbox,
2006 if (isset($open_tags{$tagname})){
2007 $open_tags{$tagname}++
;
2009 $open_tags{$tagname}=1;
2013 * This is where we run other checks.
2015 if (is_array($attary) && sizeof($attary) > 0){
2016 $attary = sq_fixatts($tagname,
2030 if ($tagname != false && $skip_content == false){
2031 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2036 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
2037 if ($force_tag_closing == true){
2038 foreach ($open_tags as $tagname=>$opentimes){
2039 while ($opentimes > 0){
2040 $trusted .= '</' . $tagname . '>';
2046 $trusted .= "<!-- end sanitized html -->\n";
2051 * This is a wrapper function to call html sanitizing routines.
2053 * @param $body the body of the message
2054 * @param $id the id of the message
2058 * @param boolean $take_mailto_links When TRUE, converts mailto: links
2059 * into internal SM compose links
2060 * (optional; default = TRUE)
2061 * @return a string with html safe to display in the browser.
2063 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
2065 require_once(SM_PATH
. 'functions/url_parser.php'); // for $MailTo_PReg_Match
2067 global $attachment_common_show_images, $view_unsafe_images,
2070 * Don't display attached images in HTML mode.
2072 $attachment_common_show_images = false;
2087 $rm_tags_with_content = Array(
2097 $self_closing_tags = Array(
2105 $force_tag_closing = true;
2107 $rm_attnames = Array(
2118 $secremoveimg = "../images/" . _("sec_remove_eng.png");
2119 $bad_attvals = Array(
2122 "/^src|background/i" =>
2125 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2126 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2127 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2130 "\\1$secremoveimg\\2",
2131 "\\1$secremoveimg\\2",
2132 "\\1$secremoveimg\\2",
2135 "/^href|action/i" =>
2138 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2139 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2140 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2154 "/include-source/i",
2155 "/position\s*:\s*absolute/i",
2156 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2157 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2158 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2159 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2175 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2176 $view_unsafe_images = false;
2178 if (!$view_unsafe_images){
2180 * Remove any references to http/https if view_unsafe_images set
2183 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2184 '/^([\'\"])\s*https*:.*([\'\"])/si');
2185 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2186 "\\1$secremoveimg\\1");
2187 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2188 '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
2189 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2190 "url(\\1$secremoveimg\\1)");
2193 $add_attr_to_tag = Array(
2195 Array('target'=>'"_blank"',
2196 'title'=>'"'._("This external link will open in a new window").'"'
2199 $trusted = sq_sanitize($body,
2201 $rm_tags_with_content,
2211 if (preg_match("|$secremoveimg|i", $trusted)){
2212 $has_unsafe_images = true;
2215 // we want to parse mailto's in HTML output, change to SM compose links
2216 // this is a modified version of code from url_parser.php... but Marc is
2217 // right: we need a better filtering implementation; adding this randomly
2218 // here is not a great solution
2220 if ($take_mailto_links) {
2221 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2222 global $MailTo_PReg_Match;
2223 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
2224 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2225 foreach ($regs[0] as $i => $mailto_before) {
2226 $mailto_params = $regs[10][$i];
2227 // get rid of any tailing quote since we have to add send_to to the end
2229 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2230 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2231 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2232 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2234 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2235 $to = 'to=' . $regs[1][$i];
2236 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2237 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2239 if ($mailto_params) //already some params, append to them
2240 $mailto_params .= '&' . $to;
2242 $mailto_params .= '?' . $to;
2246 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2248 // we'll already have target=_blank, no need to allow comp_in_new
2249 // here (which would be a lot more work anyway)
2251 global $compose_new_win;
2252 $temp_comp_in_new = $compose_new_win;
2253 $compose_new_win = 0;
2254 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2255 $compose_new_win = $temp_comp_in_new;
2257 // remove <a href=" and anything after the next quote (we only
2258 // need the uri, not the link HTML) in compose uri
2260 $comp_uri = substr($comp_uri, 9);
2261 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2262 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2271 * function SendDownloadHeaders - send file to the browser
2273 * Original Source: SM core src/download.php
2274 * moved here to make it available to other code, and separate
2275 * front end from back end functionality.
2277 * @param string $type0 first half of mime type
2278 * @param string $type1 second half of mime type
2279 * @param string $filename filename to tell the browser for downloaded file
2280 * @param boolean $force whether to force the download dialog to pop
2281 * @param optional integer $filesize send the Content-Header and length to the browser
2284 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2285 global $languages, $squirrelmail_language;
2286 $isIE = $isIE6plus = false;
2288 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2290 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2291 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2295 if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
2296 ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
2300 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2301 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2303 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2305 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2308 // A Pox on Microsoft and it's Internet Explorer!
2310 // IE has lots of bugs with file downloads.
2311 // It also has problems with SSL. Both of these cause problems
2312 // for us in this function.
2314 // See this article on Cache Control headers and SSL
2315 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2317 // The best thing you can do for IE is to upgrade to the latest
2319 //set all the Cache Control Headers for IE
2321 $filename=rawurlencode($filename);
2322 header ("Pragma: public");
2323 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2324 header ("Cache-Control: post-check=0, pre-check=0", false);
2325 header ("Cache-Control: private");
2327 //set the inline header for IE, we'll add the attachment header later if we need it
2328 header ("Content-Disposition: inline; filename=$filename");
2332 // Try to show in browser window
2333 header ("Content-Disposition: inline; filename=\"$filename\"");
2334 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2336 // Try to pop up the "save as" box
2338 // IE makes this hard. It pops up 2 save boxes, or none.
2339 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2340 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2341 // But, according to Microsoft, it is "RFC compliant but doesn't
2342 // take into account some deviations that allowed within the
2343 // specification." Doesn't that mean RFC non-compliant?
2344 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2346 // all browsers need the application/octet-stream header for this
2347 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2349 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2350 // Do not have quotes around filename, but that applied to
2351 // "attachment"... does it apply to inline too?
2352 header ("Content-Disposition: attachment; filename=\"$filename\"");
2354 if ($isIE && !$isIE6plus) {
2355 // This combination seems to work mostly. IE 5.5 SP 1 has
2356 // known issues (see the Microsoft Knowledge Base)
2358 // This works for most types, but doesn't work with Word files
2359 header ("Content-Type: application/download; name=\"$filename\"");
2361 // These are spares, just in case. :-)
2362 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2363 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2364 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2366 // another application/octet-stream forces download for Netscape
2367 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2371 //send the content-length header if the calling function provides it
2372 if ($filesize > 0) {
2373 header("Content-Length: $filesize");
2376 } // end fn SendDownloadHeaders