a7e6cbf30ecaa4e68037fac0de4b0ea8c9b6dc37
6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains the functions necessary to detect and decode MIME
13 * @package squirrelmail
16 /** The typical includes... */
17 require_once(SM_PATH
. 'functions/imap.php');
18 require_once(SM_PATH
. 'functions/attachment_common.php');
19 /** add sqm_baseuri()*/
20 include_once(SM_PATH
. 'functions/display_messages.php');
22 /* -------------------------------------------------------------------------- */
24 /* -------------------------------------------------------------------------- */
27 * Get the MIME structure
29 * This function gets the structure of a message and stores it in the "message" class.
30 * It will return this object for use with all relevant header information and
31 * fully parsed into the standard "message" object format.
33 function mime_structure ($bodystructure, $flags=array()) {
35 /* Isolate the body structure and remove beginning and end parenthesis. */
36 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
37 $read = trim(substr ($read, 0, -1));
39 $msg = Message
::parseStructure($read,$i);
40 if (!is_object($msg)) {
41 include_once(SM_PATH
. 'functions/display_messages.php');
42 global $color, $mailbox;
43 /* removed urldecode because $_GET is auto urldecoded ??? */
44 displayPageHeader( $color, $mailbox );
45 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
46 $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
47 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
48 plain_error_message( $errormessage, $color );
49 echo '</body></html>';
53 foreach ($flags as $flag) {
54 $char = strtoupper($flag{1});
57 if (strtolower($flag) == '\\seen') {
62 if (strtolower($flag) == '\\answered') {
63 $msg->is_answered
= true;
67 if (strtolower($flag) == '\\deleted') {
68 $msg->is_deleted
= true;
72 if (strtolower($flag) == '\\flagged') {
73 $msg->is_flagged
= true;
77 if (strtolower($flag) == '$mdnsent') {
78 $msg->is_mdnsent
= true;
86 // listEntities($msg);
92 /* This starts the parsing of a particular structure. It is called recursively,
93 * so it can be passed different structures. It returns an object of type
95 * First, it checks to see if it is a multipart message. If it is, then it
96 * handles that as it sees is necessary. If it is just a regular entity,
97 * then it parses it and adds the necessary header information (by calling out
98 * to mime_get_elements()
101 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
102 /* Do a bit of error correction. If we couldn't find the entity id, just guess
103 * that it is the first one. That is usually the case anyway.
107 $cmd = "FETCH $id BODY[]";
109 $cmd = "FETCH $id BODY[$ent_id]";
112 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
114 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
116 $topline = trim(array_shift($data));
117 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
119 $wholemessage = implode('', $data);
120 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
121 $ret = substr($wholemessage, 0, $regs[1]);
122 /* There is some information in the content info header that could be important
123 * in order to parse html messages. Let's get them here.
125 // if ($ret{0} == '<') {
126 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
128 } else if (ereg('"([^"]*)"', $topline, $regs)) {
131 global $where, $what, $mailbox, $passed_id, $startMessage;
132 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
133 if (isset($where) && isset($what)) {
134 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
136 $par .= '&startMessage=' . $startMessage . '&show_more=0';
138 $par .= '&response=' . urlencode($response) .
139 '&message=' . urlencode($message) .
140 '&topline=' . urlencode($topline);
143 '<table width="80%"><tr>' .
144 '<tr><td colspan="2">' .
145 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
147 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
148 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
149 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
150 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
151 "</table><br /></tt></font><hr />";
153 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
155 $wholemessage = implode('', $data);
157 $ret = $wholemessage;
162 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
164 /* Don't kill the connection if the browser is over a dialup
165 * and it would take over 30 seconds to download it.
166 * Don't call set_time_limit in safe mode.
169 if (!ini_get('safe_mode')) {
172 /* in case of base64 encoded attachments, do not buffer them.
173 Instead, echo the decoded attachment directly to screen */
174 if (strtolower($encoding) == 'base64') {
176 $query = "FETCH $id BODY[]";
178 $query = "FETCH $id BODY[$ent_id]";
180 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
182 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
183 if (is_resource($rStream)) {
184 fputs($rStream,decodeBody($body,$encoding));
186 echo decodeBody($body, $encoding);
191 TODO, use the same method for quoted printable.
192 However, I assume that quoted printable attachments aren't that large
193 so the performancegain / memory usage drop will be minimal.
194 If we decide to add that then we need to adapt sqimap_fread because
195 we need to split te result on \n and fread doesn't stop at \n. That
196 means we also should provide $results from sqimap_fread (by ref) to
197 te function and set $no_return to false. The $filter function for
198 quoted printable should handle unsetting of $results.
201 TODO 2: find out how we write to the output stream php://stdout. fwrite
202 doesn't work because 'php://stdout isn't a stream.
208 /* -[ END MIME DECODING ]----------------------------------------------------------- */
210 /* This is here for debugging purposes. It will print out a list
211 * of all the entity IDs that are in the $message object.
213 function listEntities ($message) {
215 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
216 for ($i = 0; isset($message->entities
[$i]); $i++
) {
218 $msg = listEntities($message->entities
[$i]);
228 function getPriorityStr($priority) {
229 $priority_level = substr($priority,0,1);
231 switch($priority_level) {
232 /* Check for a higher then normal priority. */
235 $priority_string = _("High");
238 /* Check for a lower then normal priority. */
241 $priority_string = _("Low");
244 /* Check for a normal priority. */
247 $priority_level = '3';
248 $priority_string = _("Normal");
252 return $priority_string;
255 /* returns a $message object for a particular entity id */
256 function getEntity ($message, $ent_id) {
257 return $message->getEntity($ent_id);
261 * Extracted from strings.php 23/03/2002
264 function translateText(&$body, $wrap_at, $charset) {
265 global $where, $what; /* from searching */
266 global $color; /* color theme */
268 require_once(SM_PATH
. 'functions/url_parser.php');
270 $body_ary = explode("\n", $body);
271 for ($i=0; $i < count($body_ary); $i++
) {
272 $line = $body_ary[$i];
273 if (strlen($line) - 2 >= $wrap_at) {
274 sqWordWrap($line, $wrap_at, $charset);
276 $line = charset_decode($charset, $line);
277 $line = str_replace("\t", ' ', $line);
286 if ($line[$pos] == ' ') {
288 } else if (strpos($line, '>', $pos) === $pos) {
297 if (!isset($color[13])) {
298 $color[13] = '#800000';
300 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
302 if (!isset($color[14])) {
303 $color[14] = '#FF0000';
305 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
308 $body_ary[$i] = $line;
310 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
314 * This returns a parsed string called $body. That string can then
315 * be displayed as the actual message in the HTML. It contains
316 * everything needed, including HTML Tags, Attachments at the
319 * Since 1.2.0 function uses message_body hook.
320 * Till 1.3.0 function included output of formatAttachments().
322 * @param resource $imap_stream imap connection resource
323 * @param object $message squirrelmail message object
324 * @param array $color squirrelmail color theme array
325 * @param integer $wrap_at number of characters per line
326 * @param string $ent_num (since 1.3.0) message part id
327 * @param integer $id (since 1.3.0) message id
328 * @param string $mailbox (since 1.3.0) imap folder name
329 * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
330 * @return string html formated message text
332 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
333 /* This if statement checks for the entity to show as the
334 * primary message. To add more of them, just put them in the
335 * order that is their priority.
337 global $startMessage, $languages, $squirrelmail_language,
338 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id, $use_iframe,$iframe_height;
340 // workaround for not updated config.php
341 if (! isset($use_iframe)) $use_iframe = false;
343 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
344 $view_unsafe_images = false;
348 $urlmailbox = urlencode($mailbox);
349 $body_message = getEntity($message, $ent_num);
350 if (($body_message->header
->type0
== 'text') ||
351 ($body_message->header
->type0
== 'rfc822')) {
352 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
353 $body = decodeBody($body, $body_message->header
->encoding
);
355 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
356 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
357 if (mb_detect_encoding($body) != 'ASCII') {
358 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
361 $hookResults = do_hook("message_body", $body);
362 $body = $hookResults[1];
364 /* If there are other types that shouldn't be formatted, add
368 if ($body_message->header
->type1
== 'html') {
369 if ($show_html_default <> 1) {
370 $entity_conv = array(' ' => ' ',
379 $body = strtr($body, $entity_conv);
380 $body = strip_tags($body);
382 translateText($body, $wrap_at,
383 $body_message->header
->getParameter('charset'));
384 } elseif ($use_iframe && ! $clean) {
385 // $clean is used to remove iframe in printable view.
388 * If we don't add html message between iframe tags,
389 * we must detect unsafe images and modify $has_unsafe_images.
391 $html_body = magicHTML($body, $id, $message, $mailbox);
393 // creating iframe url
394 $iframeurl=sqm_baseuri().'src/view_html.php?'
395 . 'mailbox=' . $urlmailbox
396 . '&passed_id=' . $id
397 . '&ent_id=' . $ent_num
398 . '&view_unsafe_images=' . (int) $view_unsafe_images;
400 // adding warning message
401 $body = html_tag('div',_("Viewing HTML formatted email"),'center');
404 * height can't be set to 100%, because it does not work as expected when
405 * iframe is inside the table. Browsers do not create full height objects
406 * even when iframe is not nested. Maybe there is some way to get full size
407 * with CSS. Tested in firefox 1.02 and opera 7.53
409 * width="100%" does not work as expected, when table width is not set (automatic)
411 * tokul: I think <iframe> are safer sandbox than <object>. Objects might
412 * need special handling for IE and IE6SP2.
414 $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
415 .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
417 // Message for browsers without iframe support
418 //$body.= _("Your browser does not support inline frames.
419 // You can view HTML formated message by following below link.");
420 //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
422 // if browser can't render iframe, it renders html message.
426 $body.="</iframe></div>\n";
428 // old way of html rendering
429 $body = magicHTML($body, $id, $message, $mailbox);
432 translateText($body, $wrap_at,
433 $body_message->header
->getParameter('charset'));
436 // if this is the clean display (i.e. printer friendly), stop here.
441 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
442 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
443 '&startMessage=' . $startMessage . '&show_more=0';
444 if (isset($passed_ent_id)) {
445 $link .= '&passed_ent_id='.$passed_ent_id;
447 $body .= '<center><small><a href="download.php?absolute_dl=true&' .
448 $link . '">' . _("Download this as a file") . '</a>';
449 if ($view_unsafe_images) {
450 $text = _("Hide Unsafe Images");
452 if (isset($has_unsafe_images) && $has_unsafe_images) {
453 $link .= '&view_unsafe_images=1';
454 $text = _("View Unsafe Images");
460 $body .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
462 $body .= '</small></center><br />' . "\n";
468 * Displays attachment links and information
470 * Since 1.3.0 function is not included in formatBody() call.
472 * Since 1.0.2 uses attachment $type0/$type1 hook.
473 * Since 1.2.5 uses attachment $type0/* hook.
474 * Since 1.5.0 uses attachments_bottom hook.
476 * @param object $message SquirrelMail message object
477 * @param array $exclude_id message parts that are not attachments.
478 * @param string $mailbox mailbox name
479 * @param integer $id message id
480 * @return string html formated attachment information.
482 function formatAttachments($message, $exclude_id, $mailbox, $id) {
483 global $where, $what, $startMessage, $color, $passed_ent_id;
485 $att_ar = $message->getAttachments($exclude_id);
487 if (!count($att_ar)) return '';
491 $urlMailbox = urlencode($mailbox);
493 foreach ($att_ar as $att) {
494 $ent = $att->entity_id
;
495 $header = $att->header
;
496 $type0 = strtolower($header->type0
);
497 $type1 = strtolower($header->type1
);
499 $links['download link']['text'] = _("Download");
500 $links['download link']['href'] = sqm_baseuri() .
501 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
502 if ($type0 =='message' && $type1 == 'rfc822') {
503 $default_page = sqm_baseuri() . 'src/read_body.php';
504 $rfc822_header = $att->rfc822_header
;
505 $filename = $rfc822_header->subject
;
506 if (trim( $filename ) == '') {
507 $filename = 'untitled-[' . $ent . ']' ;
509 $from_o = $rfc822_header->from
;
510 if (is_object($from_o)) {
511 $from_name = decodeHeader($from_o->getAddress(false));
513 $from_name = _("Unknown sender");
515 $description = $from_name;
517 $default_page = sqm_baseuri() . 'src/download.php';
518 $filename = $att->getFilename();
519 if ($header->description
) {
520 $description = decodeHeader($header->description
);
526 $display_filename = $filename;
527 if (isset($passed_ent_id)) {
528 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
530 $passed_ent_id_link = '';
532 $defaultlink = $default_page . "?startMessage=$startMessage"
533 . "&passed_id=$id&mailbox=$urlMailbox"
534 . '&ent_id='.$ent.$passed_ent_id_link;
535 if ($where && $what) {
536 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
539 /* This executes the attachment hook with a specific MIME-type.
540 * If that doesn't have results, it tries if there's a rule
541 * for a more generic type.
543 $hookresults = do_hook("attachment $type0/$type1", $links,
544 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
545 $display_filename, $where, $what);
546 if(count($hookresults[1]) <= 1) {
547 $hookresults = do_hook("attachment $type0/*", $links,
548 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
549 $display_filename, $where, $what);
552 $links = $hookresults[1];
553 $defaultlink = $hookresults[6];
555 $attachments .= '<tr><td>' .
556 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
557 '<td><small><b>' . show_readable_size($header->size
) .
558 '</b> </small></td>' .
559 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
561 $attachments .= '<b>' . $description . '</b>';
562 $attachments .= '</small></td><td><small> ';
565 foreach ($links as $val) {
569 $attachments .= ' | ';
571 $attachments .= '<a href="' . $val['href'] . '">'
572 . (isset($val['text']) && !empty($val['text']) ?
$val['text'] : '')
573 . (isset($val['extra']) && !empty($val['extra']) ?
$val['extra'] : '')
577 $attachments .= "</td></tr>\n";
579 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
580 if ($attachmentadd != '')
581 $attachments = $attachmentadd;
585 function sqimap_base64_decode(&$string) {
587 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
588 // fly decoding (to reduce memory usage) you have to check if the
589 // data has incomplete pairs
591 // Remove the noise in order to check if the 4 bytes pairs are complete
592 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
595 $iMod = strlen($string) %
4;
597 $sStringRem = substr($string,-$iMod);
598 // Check if $sStringRem contains padding characters
599 if (substr($sStringRem,-1) != '=') {
600 $string = substr($string,0,-$iMod);
605 $string = base64_decode($string);
610 /* This function decodes the body depending on the encoding type. */
611 function decodeBody($body, $encoding) {
612 global $show_html_default;
614 $body = str_replace("\r\n", "\n", $body);
615 $encoding = strtolower($encoding);
617 $encoding_handler = do_hook_function('decode_body', $encoding);
620 // plugins get first shot at decoding the body
622 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
623 $body = $encoding_handler('decode', $body);
625 } else if ($encoding == 'quoted-printable' ||
626 $encoding == 'quoted_printable') {
627 $body = quoted_printable_decode($body);
629 while (ereg("=\n", $body)) {
630 $body = ereg_replace ("=\n", '', $body);
633 } else if ($encoding == 'base64') {
634 $body = base64_decode($body);
637 // All other encodings are returned raw.
644 * This functions decode strings that is encoded according to
645 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
646 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
648 * @param string $string header string that has to be made readable
649 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
650 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
651 * @param boolean $decide decide if string can be utfencoded. defaults to false
652 * @return string decoded header string
654 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
655 global $languages, $squirrelmail_language,$default_charset;
656 if (is_array($string)) {
657 $string = implode("\n", $string);
660 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
661 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
662 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
663 // Do we need to return at this point?
670 $aString = explode(' ',$string);
672 foreach ($aString as $chunk) {
673 if ($encoded && $chunk === '') {
675 } elseif ($chunk === '') {
680 /* if encoded words are not separated by a linear-space-white we still catch them */
683 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
684 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
685 if ($iLastMatch !== $j) {
695 $ret .= htmlspecialchars($res[1]);
699 $encoding = ucfirst($res[3]);
701 /* decide about valid decoding */
702 if ($decide && is_conversion_safe($res[2])) {
704 $can_be_encoded=true;
706 $can_be_encoded=false;
711 $replace = base64_decode($res[4]);
713 if ($can_be_encoded) {
714 /* convert string to different charset,
715 * if functions asks for it (usually in compose)
717 $ret .= charset_convert($res[2],$replace,$default_charset);
719 // convert string to html codes in order to display it
720 $ret .= charset_decode($res[2],$replace);
724 $replace = htmlspecialchars($replace);
730 $replace = str_replace('_', ' ', $res[4]);
731 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
734 if ($can_be_encoded) {
735 /* convert string to different charset,
736 * if functions asks for it (usually in compose)
738 $replace = charset_convert($res[2], $replace,$default_charset);
740 // convert string to html codes in order to display it
741 $replace = charset_decode($res[2], $replace);
745 $replace = htmlspecialchars($replace);
764 if (!$encoded && $htmlsave) {
765 $ret .= htmlspecialchars($chunk);
771 /* remove the first added space */
774 $ret = substr($ret,5);
776 $ret = substr($ret,1);
786 * Function uses XTRA_CODE _encodeheader function, if such function exists.
788 * Function uses Q encoding by default and encodes a string according to RFC
789 * 1522 for use in headers if it contains 8-bit characters or anything that
790 * looks like it should be encoded.
792 * Function switches to B encoding and encodeHeaderBase64() function, if
793 * string is 8bit and multibyte character set supported by mbstring extension
794 * is used. It can cause E_USER_NOTICE errors, if interface is used with
795 * multibyte character set unsupported by mbstring extension.
797 * @param string $string header string, that has to be encoded
798 * @return string quoted-printable encoded string
799 * @todo make $mb_charsets system wide constant
801 function encodeHeader ($string) {
802 global $default_charset, $languages, $squirrelmail_language;
804 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
805 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
806 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
809 // Use B encoding for multibyte charsets
810 $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
811 if (in_array($default_charset,$mb_charsets) &&
812 in_array($default_charset,sq_mb_list_encodings()) &&
813 sq_is8bit($string)) {
814 return encodeHeaderBase64($string,$default_charset);
815 } elseif (in_array($default_charset,$mb_charsets) &&
816 sq_is8bit($string) &&
817 ! in_array($default_charset,sq_mb_list_encodings())) {
818 // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
819 // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
822 // Encode only if the string contains 8-bit characters or =?
823 $j = strlen($string);
824 $max_l = 75 - strlen($default_charset) - 7;
827 $iEncStart = $enc_init = false;
828 $cur_l = $iOffset = 0;
829 for($i = 0; $i < $j; ++
$i) {
838 if ($iEncStart === false) {
842 if ($cur_l > ($max_l-2)) {
843 /* if there is an stringpart that doesn't need encoding, add it */
844 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
845 $aRet[] = "=?$default_charset?Q?$ret?=";
851 $ret .= sprintf("=%02X",ord($string{$i}));
856 if ($iEncStart !== false) {
857 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
858 $aRet[] = "=?$default_charset?Q?$ret?=";
866 if ($iEncStart !== false) {
868 if ($cur_l > $max_l) {
869 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
870 $aRet[] = "=?$default_charset?Q?$ret?=";
881 $k = ord($string{$i});
883 if ($iEncStart === false) {
884 // do not start encoding in the middle of a string, also take the rest of the word.
885 $sLeadString = substr($string,0,$i);
886 $aLeadString = explode(' ',$sLeadString);
887 $sToBeEncoded = array_pop($aLeadString);
888 $iEncStart = $i - strlen($sToBeEncoded);
889 $ret .= $sToBeEncoded;
890 $cur_l +
= strlen($sToBeEncoded);
893 /* first we add the encoded string that reached it's max size */
894 if ($cur_l > ($max_l-2)) {
895 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
896 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
903 $ret .= sprintf("=%02X", $k);
905 if ($iEncStart !== false) {
907 if ($cur_l > $max_l) {
908 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
909 $aRet[] = "=?$default_charset?Q?$ret?=";
924 if ($iEncStart !== false) {
925 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
926 $aRet[] = "=?$default_charset?Q?$ret?=";
928 $aRet[] = substr($string,$iOffset);
930 $string = implode('',$aRet);
936 * Encodes string according to rfc2047 B encoding header formating rules
938 * It is recommended way to encode headers with character sets that store
939 * symbols in more than one byte.
941 * Function requires mbstring support. If required mbstring functions are missing,
942 * function returns false and sets E_USER_WARNING level error message.
944 * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
945 * that mbstring functions will generate E_WARNING errors, if unsupported
946 * character set is used. mb_encode_mimeheader function provided by php
947 * mbstring extension is not used in order to get better control of header
950 * Used php code functions - function_exists(), trigger_error(), strlen()
951 * (is used with charset names and base64 strings). Used php mbstring
952 * functions - mb_strlen and mb_substr.
954 * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
955 * encoding), rfc 2822 (header folding)
957 * @param string $string header string that must be encoded
958 * @param string $charset character set. Must be supported by mbstring extension.
959 * Use sq_mb_list_encodings() to detect supported charsets.
960 * @return string string encoded according to rfc2047 B encoding formating rules
962 * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
963 * @todo Do we want to control max length of header?
964 * @todo Do we want to control EOL (end-of-line) marker?
965 * @todo Do we want to translate error message?
967 function encodeHeaderBase64($string,$charset) {
969 * Check mbstring function requirements.
971 if (! function_exists('mb_strlen') ||
972 ! function_exists('mb_substr')) {
973 // set E_USER_WARNING
974 trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING
);
979 // initial return array
983 * header length = 75 symbols max (same as in encodeHeader)
984 * remove $charset length
985 * remove =? ? ?= (5 chars)
986 * remove 2 more chars (\r\n ?)
988 $iMaxLength = 75 - strlen($charset) - 7;
990 // set first character position
993 // loop through all characters. count characters and not bytes.
994 for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++
) {
995 // encode string from starting character to current character.
996 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
998 // Check encoded string length
999 if(strlen($encoded_string)>$iMaxLength) {
1000 // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
1001 $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
1003 // set new starting character
1004 $iStartCharNum = $iCharNum-1;
1006 // encode last char (in case it is last character in string)
1007 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1008 } // if string is shorter than max length - add next character
1011 // add last encoded string to array
1012 $aRet[] = $encoded_string;
1014 // set initial return string
1017 // loop through encoded strings
1018 foreach($aRet as $string) {
1019 // TODO: Do we want to control EOL (end-of-line) marker
1020 if ($sRet!='') $sRet.= " ";
1022 // add header tags and encoded string to return string
1023 $sRet.= '=?'.$charset.'?B?'.$string.'?=';
1029 /* This function trys to locate the entity_id of a specific mime element */
1030 function find_ent_id($id, $message) {
1031 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
1032 if ($message->entities
[$i]->header
->type0
== 'multipart') {
1033 $ret = find_ent_id($id, $message->entities
[$i]);
1035 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
1036 // if (sq_check_save_extension($message->entities[$i])) {
1037 return $message->entities
[$i]->entity_id
;
1039 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
1041 * This is part of a fix for Outlook Express 6.x generating
1042 * cid URLs without creating content-id headers
1045 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
1046 return $message->entities
[$i]->entity_id
;
1054 function sq_check_save_extension($message) {
1055 $filename = $message->getFilename();
1056 $ext = substr($filename, strrpos($filename,'.')+
1);
1057 $save_extensions = array('jpg','jpeg','gif','png','bmp');
1058 return in_array($ext, $save_extensions);
1063 ** HTMLFILTER ROUTINES
1067 * This function checks attribute values for entity-encoded values
1068 * and returns them translated into 8-bit strings so we can run
1071 * @param $attvalue A string to run entity check against.
1072 * @return Nothing, modifies a reference value.
1074 function sq_defang(&$attvalue){
1077 * Skip this if there aren't ampersands or backslashes.
1079 if (strpos($attvalue, '&') === false
1080 && strpos($attvalue, '\\') === false){
1086 $m = $m ||
sq_deent($attvalue, '/\�*(\d+);*/s');
1087 $m = $m ||
sq_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true);
1088 $m = $m ||
sq_deent($attvalue, '/\\\\(\d+)/s', true);
1089 } while ($m == true);
1090 $attvalue = stripslashes($attvalue);
1094 * Kill any tabs, newlines, or carriage returns. Our friends the
1095 * makers of the browser with 95% market value decided that it'd
1096 * be funny to make "java[tab]script" be just as good as "javascript".
1098 * @param attvalue The attribute value before extraneous spaces removed.
1099 * @return attvalue Nothing, modifies a reference value.
1101 function sq_unspace(&$attvalue){
1103 if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
1104 $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
1105 Array('', '', '', '', ''), $attvalue);
1110 * This function returns the final tag out of the tag name, an array
1111 * of attributes, and the type of the tag. This function is called by
1112 * sq_sanitize internally.
1114 * @param $tagname the name of the tag.
1115 * @param $attary the array of attributes and their values
1116 * @param $tagtype The type of the tag (see in comments).
1117 * @return a string with the final tag representation.
1119 function sq_tagprint($tagname, $attary, $tagtype){
1120 $me = 'sq_tagprint';
1123 $fulltag = '</' . $tagname . '>';
1125 $fulltag = '<' . $tagname;
1126 if (is_array($attary) && sizeof($attary)){
1128 while (list($attname, $attvalue) = each($attary)){
1129 array_push($atts, "$attname=$attvalue");
1131 $fulltag .= ' ' . join(" ", $atts);
1142 * A small helper function to use with array_walk. Modifies a by-ref
1143 * value and makes it lowercase.
1145 * @param $val a value passed by-ref.
1146 * @return void since it modifies a by-ref value.
1148 function sq_casenormalize(&$val){
1149 $val = strtolower($val);
1153 * This function skips any whitespace from the current position within
1154 * a string and to the next non-whitespace value.
1156 * @param $body the string
1157 * @param $offset the offset within the string where we should start
1158 * looking for the next non-whitespace character.
1159 * @return the location within the $body where the next
1160 * non-whitespace char is located.
1162 function sq_skipspace($body, $offset){
1163 $me = 'sq_skipspace';
1164 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1165 if (sizeof($matches{1})){
1166 $count = strlen($matches{1});
1173 * This function looks for the next character within a string. It's
1174 * really just a glorified "strpos", except it catches if failures
1177 * @param $body The string to look for needle in.
1178 * @param $offset Start looking from this position.
1179 * @param $needle The character/string to look for.
1180 * @return location of the next occurance of the needle, or
1181 * strlen($body) if needle wasn't found.
1183 function sq_findnxstr($body, $offset, $needle){
1184 $me = 'sq_findnxstr';
1185 $pos = strpos($body, $needle, $offset);
1186 if ($pos === FALSE){
1187 $pos = strlen($body);
1193 * This function takes a PCRE-style regexp and tries to match it
1194 * within the string.
1196 * @param $body The string to look for needle in.
1197 * @param $offset Start looking from here.
1198 * @param $reg A PCRE-style regex to match.
1199 * @return Returns a false if no matches found, or an array
1200 * with the following members:
1201 * - integer with the location of the match within $body
1202 * - string with whatever content between offset and the match
1203 * - string with whatever it is we matched
1205 function sq_findnxreg($body, $offset, $reg){
1206 $me = 'sq_findnxreg';
1209 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1210 if (!isset($matches{0}) ||
!$matches{0}){
1213 $retarr{0} = $offset +
strlen($matches{1});
1214 $retarr{1} = $matches{1};
1215 $retarr{2} = $matches{2};
1221 * This function looks for the next tag.
1223 * @param $body String where to look for the next tag.
1224 * @param $offset Start looking from here.
1225 * @return false if no more tags exist in the body, or
1226 * an array with the following members:
1227 * - string with the name of the tag
1228 * - array with attributes and their values
1229 * - integer with tag type (1, 2, or 3)
1230 * - integer where the tag starts (starting "<")
1231 * - integer where the tag ends (ending ">")
1232 * first three members will be false, if the tag is invalid.
1234 function sq_getnxtag($body, $offset){
1235 $me = 'sq_getnxtag';
1236 if ($offset > strlen($body)){
1239 $lt = sq_findnxstr($body, $offset, "<");
1240 if ($lt == strlen($body)){
1245 * blah blah <tag attribute="value">
1248 $pos = sq_skipspace($body, $lt+
1);
1249 if ($pos >= strlen($body)){
1250 return Array(false, false, false, $lt, strlen($body));
1253 * There are 3 kinds of tags:
1254 * 1. Opening tag, e.g.:
1256 * 2. Closing tag, e.g.:
1258 * 3. XHTML-style content-less tag, e.g.:
1259 * <img src="blah" />
1262 switch (substr($body, $pos, 1)){
1269 * A comment or an SGML declaration.
1271 if (substr($body, $pos+
1, 2) == "--"){
1272 $gt = strpos($body, "-->", $pos);
1274 $gt = strlen($body);
1278 return Array(false, false, false, $lt, $gt);
1280 $gt = sq_findnxstr($body, $pos, ">");
1281 return Array(false, false, false, $lt, $gt);
1286 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1296 * Look for next [\W-_], which will indicate the end of the tag name.
1298 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1299 if ($regary == false){
1300 return Array(false, false, false, $lt, strlen($body));
1302 list($pos, $tagname, $match) = $regary;
1303 $tagname = strtolower($tagname);
1306 * $match can be either of these:
1307 * '>' indicating the end of the tag entirely.
1308 * '\s' indicating the end of the tag name.
1309 * '/' indicating that this is type-3 xhtml tag.
1311 * Whatever else we find there indicates an invalid tag.
1316 * This is an xhtml-style tag with a closing / at the
1317 * end, like so: <img src="blah" />. Check if it's followed
1318 * by the closing bracket. If not, then this tag is invalid
1320 if (substr($body, $pos, 2) == "/>"){
1324 $gt = sq_findnxstr($body, $pos, ">");
1325 $retary = Array(false, false, false, $lt, $gt);
1329 return Array($tagname, false, $tagtype, $lt, $pos);
1333 * Check if it's whitespace
1335 if (!preg_match('/\s/', $match)){
1337 * This is an invalid tag! Look for the next closing ">".
1339 $gt = sq_findnxstr($body, $lt, ">");
1340 return Array(false, false, false, $lt, $gt);
1346 * At this point we're here:
1347 * <tagname attribute='blah'>
1350 * At this point we loop in order to find all attributes.
1356 while ($pos <= strlen($body)){
1357 $pos = sq_skipspace($body, $pos);
1358 if ($pos == strlen($body)){
1362 return Array(false, false, false, $lt, $pos);
1365 * See if we arrived at a ">" or "/>", which means that we reached
1366 * the end of the tag.
1369 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1373 $pos +
= strlen($matches{1});
1374 if ($matches{2} == "/>"){
1378 return Array($tagname, $attary, $tagtype, $lt, $pos);
1382 * There are several types of attributes, with optional
1383 * [:space:] between members.
1385 * attrname[:space:]=[:space:]'CDATA'
1387 * attrname[:space:]=[:space:]"CDATA"
1389 * attr[:space:]=[:space:]CDATA
1393 * We leave types 1 and 2 the same, type 3 we check for
1394 * '"' and convert to """ if needed, then wrap in
1395 * double quotes. Type 4 we convert into:
1398 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1399 if ($regary == false){
1401 * Looks like body ended before the end of tag.
1403 return Array(false, false, false, $lt, strlen($body));
1405 list($pos, $attname, $match) = $regary;
1406 $attname = strtolower($attname);
1408 * We arrived at the end of attribute name. Several things possible
1410 * '>' means the end of the tag and this is attribute type 4
1411 * '/' if followed by '>' means the same thing as above
1412 * '\s' means a lot of things -- look what it's followed by.
1413 * anything else means the attribute is invalid.
1418 * This is an xhtml-style tag with a closing / at the
1419 * end, like so: <img src="blah" />. Check if it's followed
1420 * by the closing bracket. If not, then this tag is invalid
1422 if (substr($body, $pos, 2) == "/>"){
1426 $gt = sq_findnxstr($body, $pos, ">");
1427 $retary = Array(false, false, false, $lt, $gt);
1431 $attary{$attname} = '"yes"';
1432 return Array($tagname, $attary, $tagtype, $lt, $pos);
1436 * Skip whitespace and see what we arrive at.
1438 $pos = sq_skipspace($body, $pos);
1439 $char = substr($body, $pos, 1);
1441 * Two things are valid here:
1442 * '=' means this is attribute type 1 2 or 3.
1443 * \w means this was attribute type 4.
1444 * anything else we ignore and re-loop. End of tag and
1445 * invalid stuff will be caught by our checks at the beginning
1450 $pos = sq_skipspace($body, $pos);
1452 * Here are 3 possibilities:
1453 * "'" attribute type 1
1454 * '"' attribute type 2
1455 * everything else is the content of tag type 3
1457 $quot = substr($body, $pos, 1);
1459 $regary = sq_findnxreg($body, $pos+
1, "\'");
1460 if ($regary == false){
1461 return Array(false, false, false, $lt, strlen($body));
1463 list($pos, $attval, $match) = $regary;
1465 $attary{$attname} = "'" . $attval . "'";
1466 } else if ($quot == '"'){
1467 $regary = sq_findnxreg($body, $pos+
1, '\"');
1468 if ($regary == false){
1469 return Array(false, false, false, $lt, strlen($body));
1471 list($pos, $attval, $match) = $regary;
1473 $attary{$attname} = '"' . $attval . '"';
1476 * These are hateful. Look for \s, or >.
1478 $regary = sq_findnxreg($body, $pos, "[\s>]");
1479 if ($regary == false){
1480 return Array(false, false, false, $lt, strlen($body));
1482 list($pos, $attval, $match) = $regary;
1484 * If it's ">" it will be caught at the top.
1486 $attval = preg_replace("/\"/s", """, $attval);
1487 $attary{$attname} = '"' . $attval . '"';
1489 } else if (preg_match("|[\w/>]|", $char)) {
1491 * That was attribute type 4.
1493 $attary{$attname} = '"yes"';
1496 * An illegal character. Find next '>' and return.
1498 $gt = sq_findnxstr($body, $pos, ">");
1499 return Array(false, false, false, $lt, $gt);
1505 * The fact that we got here indicates that the tag end was never
1506 * found. Return invalid tag indication so it gets stripped.
1508 return Array(false, false, false, $lt, strlen($body));
1512 * Translates entities into literal values so they can be checked.
1514 * @param $attvalue the by-ref value to check.
1515 * @param $regex the regular expression to check against.
1516 * @param $hex whether the entites are hexadecimal.
1517 * @return True or False depending on whether there were matches.
1519 function sq_deent(&$attvalue, $regex, $hex=false){
1522 preg_match_all($regex, $attvalue, $matches);
1523 if (is_array($matches) && sizeof($matches[0]) > 0){
1525 for ($i = 0; $i < sizeof($matches[0]); $i++
){
1526 $numval = $matches[1][$i];
1528 $numval = hexdec($numval);
1530 $repl{$matches[0][$i]} = chr($numval);
1532 $attvalue = strtr($attvalue, $repl);
1540 * This function runs various checks against the attributes.
1542 * @param $tagname String with the name of the tag.
1543 * @param $attary Array with all tag attributes.
1544 * @param $rm_attnames See description for sq_sanitize
1545 * @param $bad_attvals See description for sq_sanitize
1546 * @param $add_attr_to_tag See description for sq_sanitize
1547 * @param $message message object
1548 * @param $id message id
1549 * @return Array with modified attributes.
1551 function sq_fixatts($tagname,
1561 while (list($attname, $attvalue) = each($attary)){
1563 * See if this attribute should be removed.
1565 foreach ($rm_attnames as $matchtag=>$matchattrs){
1566 if (preg_match($matchtag, $tagname)){
1567 foreach ($matchattrs as $matchattr){
1568 if (preg_match($matchattr, $attname)){
1569 unset($attary{$attname});
1576 * Remove any backslashes, entities, and extraneous whitespace.
1578 sq_defang($attvalue);
1579 sq_unspace($attvalue);
1582 * Now let's run checks on the attvalues.
1583 * I don't expect anyone to comprehend this. If you do,
1584 * get in touch with me so I can drive to where you live and
1585 * shake your hand personally. :)
1587 foreach ($bad_attvals as $matchtag=>$matchattrs){
1588 if (preg_match($matchtag, $tagname)){
1589 foreach ($matchattrs as $matchattr=>$valary){
1590 if (preg_match($matchattr, $attname)){
1592 * There are two arrays in valary.
1594 * Second one is replacements
1596 list($valmatch, $valrepl) = $valary;
1598 preg_replace($valmatch, $valrepl, $attvalue);
1599 if ($newvalue != $attvalue){
1600 $attary{$attname} = $newvalue;
1608 * Replace empty src tags with the blank image. src is only used
1609 * for frames, images, and image inputs. Doing a replace should
1610 * not affect them working as should be, however it will stop
1611 * IE from being kicked off when src for img tags are not set
1613 if (($attname == 'src') && ($attvalue == '""')) {
1614 $attary{$attname} = '"' . SM_PATH
. 'images/blank.png"';
1618 * Turn cid: urls into http-friendly ones.
1620 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1621 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1625 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1626 * One day MS might actually make it match something useful, for now, falling
1627 * back to using cid2http, so we can grab the blank.png.
1629 if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
1630 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1635 * See if we need to append any attributes to this tag.
1637 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1638 if (preg_match($matchtag, $tagname)){
1639 $attary = array_merge($attary, $addattary);
1646 * This function edits the style definition to make them friendly and
1647 * usable in SquirrelMail.
1649 * @param $message the message object
1650 * @param $id the message id
1651 * @param $content a string with whatever is between <style> and </style>
1652 * @param $mailbox the message mailbox
1653 * @return a string with edited content.
1655 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1656 global $view_unsafe_images;
1657 $me = 'sq_fixstyle';
1658 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1660 return array(FALSE, strlen($body));
1662 $newpos = $ret[0] +
strlen($ret[2]);
1665 * First look for general BODY style declaration, which would be
1667 * body {background: blah-blah}
1668 * and change it to .bodyclass so we can just assign it to a <div>
1670 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1671 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1673 * Fix url('blah') declarations.
1675 // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1676 // "url(\\1$secremoveimg\\2)", $content);
1678 $content = str_replace("\0", "", $content);
1679 // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
1680 while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
1681 $sProto = strtolower($matches[1]);
1684 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1689 if (!$view_unsafe_images){
1690 $sExpr = "/url\s*\(\s*([\'\"])\s*$sProto*:.*?([\'\"])\s*\)/si";
1691 $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
1695 * Fix urls that refer to cid:
1698 $cidurl = 'cid:'. $matches[2];
1699 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1700 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1701 "u\0r\0l($httpurl)", $content);
1705 * replace url with protocol other then the white list
1706 * http,https and cid by an empty string.
1708 $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
1715 $content = str_replace("\0", "", $content);
1718 * Remove any backslashes, entities, and extraneous whitespace.
1720 $contentTemp = $content;
1721 sq_defang($contentTemp);
1722 sq_unspace($contentTemp);
1725 * Fix stupid css declarations which lead to vulnerabilities
1728 $match = Array('/expression/i',
1731 '/include-source/i');
1732 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1733 $contentNew = preg_replace($match, $replace, $contentTemp);
1734 if ($contentNew !== $contentTemp) {
1735 // insecure css declarations are used. From now on we don't care
1736 // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
1737 $content = $contentNew;
1739 return array($content, $newpos);
1744 * This function converts cid: url's into the ones that can be viewed in
1747 * @param $message the message object
1748 * @param $id the message id
1749 * @param $cidurl the cid: url.
1750 * @param $mailbox the message mailbox
1751 * @return a string with a http-friendly url
1753 function sq_cid2http($message, $id, $cidurl, $mailbox){
1755 * Get rid of quotes.
1757 $quotchar = substr($cidurl, 0, 1);
1758 if ($quotchar == '"' ||
$quotchar == "'"){
1759 $cidurl = str_replace($quotchar, "", $cidurl);
1763 $cidurl = substr(trim($cidurl), 4);
1765 $match_str = '/\{.*?\}\//';
1767 $cidurl = preg_replace($match_str, $str_rep, $cidurl);
1769 $linkurl = find_ent_id($cidurl, $message);
1770 /* in case of non-save cid links $httpurl should be replaced by a sort of
1771 unsave link image */
1775 * This is part of a fix for Outlook Express 6.x generating
1776 * cid URLs without creating content-id headers. These images are
1777 * not part of the multipart/related html mail. The html contains
1778 * <img src="cid:{some_id}/image_filename.ext"> references to
1779 * attached images with as goal to render them inline although
1780 * the attachment disposition property is not inline.
1783 if (empty($linkurl)) {
1784 if (preg_match('/{.*}\//', $cidurl)) {
1785 $cidurl = preg_replace('/{.*}\//','', $cidurl);
1786 if (!empty($cidurl)) {
1787 $linkurl = find_ent_id($cidurl, $message);
1792 if (!empty($linkurl)) {
1793 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1794 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1795 '&ent_id=' . $linkurl . $quotchar;
1798 * If we couldn't generate a proper img url, drop in a blank image
1799 * instead of sending back empty, otherwise it causes unusual behaviour
1801 $httpurl = $quotchar . SM_PATH
. 'images/blank.png' . $quotchar;
1808 * This function changes the <body> tag into a <div> tag since we
1809 * can't really have a body-within-body.
1811 * @param $attary an array of attributes and values of <body>
1812 * @param $mailbox mailbox we're currently reading (for cid2http)
1813 * @param $message current message (for cid2http)
1814 * @param $id current message id (for cid2http)
1815 * @return a modified array of attributes to be set for <div>
1817 function sq_body2div($attary, $mailbox, $message, $id){
1818 $me = 'sq_body2div';
1819 $divattary = Array('class' => "'bodyclass'");
1821 $has_bgc_stl = $has_txt_stl = false;
1823 if (is_array($attary) && sizeof($attary) > 0){
1824 foreach ($attary as $attname=>$attvalue){
1825 $quotchar = substr($attvalue, 0, 1);
1826 $attvalue = str_replace($quotchar, "", $attvalue);
1829 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1830 $styledef .= "background-image: url('$attvalue'); ";
1833 $has_bgc_stl = true;
1834 $styledef .= "background-color: $attvalue; ";
1837 $has_txt_stl = true;
1838 $styledef .= "color: $attvalue; ";
1842 // Outlook defines a white bgcolor and no text color. This can lead to
1843 // white text on a white bg with certain themes.
1844 if ($has_bgc_stl && !$has_txt_stl) {
1845 $styledef .= "color: $text; ";
1847 if (strlen($styledef) > 0){
1848 $divattary{"style"} = "\"$styledef\"";
1855 * This is the main function and the one you should actually be calling.
1856 * There are several variables you should be aware of an which need
1857 * special description.
1859 * Since the description is quite lengthy, see it here:
1860 * http://linux.duke.edu/projects/mini/htmlfilter/
1862 * @param $body the string with HTML you wish to filter
1863 * @param $tag_list see description above
1864 * @param $rm_tags_with_content see description above
1865 * @param $self_closing_tags see description above
1866 * @param $force_tag_closing see description above
1867 * @param $rm_attnames see description above
1868 * @param $bad_attvals see description above
1869 * @param $add_attr_to_tag see description above
1870 * @param $message message object
1871 * @param $id message id
1872 * @return sanitized html safe to show on your pages.
1874 function sq_sanitize($body,
1876 $rm_tags_with_content,
1886 $me = 'sq_sanitize';
1887 $rm_tags = array_shift($tag_list);
1889 * Normalize rm_tags and rm_tags_with_content.
1891 @array_walk
($tag_list, 'sq_casenormalize');
1892 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1893 @array_walk
($self_closing_tags, 'sq_casenormalize');
1895 * See if tag_list is of tags to remove or tags to allow.
1896 * false means remove these tags
1897 * true means allow these tags
1900 $open_tags = Array();
1901 $trusted = "\n<!-- begin sanitized html -->\n";
1902 $skip_content = false;
1904 * Take care of netscape's stupid javascript entities like
1907 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1909 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1910 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1911 $free_content = substr($body, $curpos, $lt-$curpos);
1913 * Take care of <style>
1915 if ($tagname == "style" && $tagtype == 1){
1916 list($free_content, $curpos) =
1917 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1918 if ($free_content != FALSE){
1919 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1920 $trusted .= $free_content;
1921 $trusted .= sq_tagprint($tagname, false, 2);
1925 if ($skip_content == false){
1926 $trusted .= $free_content;
1928 if ($tagname != FALSE){
1930 if ($skip_content == $tagname){
1932 * Got to the end of tag we needed to remove.
1935 $skip_content = false;
1937 if ($skip_content == false){
1938 if ($tagname == "body"){
1941 if (isset($open_tags{$tagname}) &&
1942 $open_tags{$tagname} > 0){
1943 $open_tags{$tagname}--;
1951 * $rm_tags_with_content
1953 if ($skip_content == false){
1955 * See if this is a self-closing type and change
1956 * tagtype appropriately.
1959 && in_array($tagname, $self_closing_tags)){
1963 * See if we should skip this tag and any content
1966 if ($tagtype == 1 &&
1967 in_array($tagname, $rm_tags_with_content)){
1968 $skip_content = $tagname;
1970 if (($rm_tags == false
1971 && in_array($tagname, $tag_list)) ||
1972 ($rm_tags == true &&
1973 !in_array($tagname, $tag_list))){
1977 * Convert body into div.
1979 if ($tagname == "body"){
1981 $attary = sq_body2div($attary, $mailbox,
1985 if (isset($open_tags{$tagname})){
1986 $open_tags{$tagname}++
;
1988 $open_tags{$tagname}=1;
1992 * This is where we run other checks.
1994 if (is_array($attary) && sizeof($attary) > 0){
1995 $attary = sq_fixatts($tagname,
2009 if ($tagname != false && $skip_content == false){
2010 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2015 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
2016 if ($force_tag_closing == true){
2017 foreach ($open_tags as $tagname=>$opentimes){
2018 while ($opentimes > 0){
2019 $trusted .= '</' . $tagname . '>';
2025 $trusted .= "<!-- end sanitized html -->\n";
2030 * This is a wrapper function to call html sanitizing routines.
2032 * @param $body the body of the message
2033 * @param $id the id of the message
2037 * @param boolean $take_mailto_links When TRUE, converts mailto: links
2038 * into internal SM compose links
2039 * (optional; default = TRUE)
2040 * @return a string with html safe to display in the browser.
2042 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
2044 require_once(SM_PATH
. 'functions/url_parser.php'); // for $MailTo_PReg_Match
2046 global $attachment_common_show_images, $view_unsafe_images,
2049 * Don't display attached images in HTML mode.
2051 $attachment_common_show_images = false;
2066 $rm_tags_with_content = Array(
2076 $self_closing_tags = Array(
2084 $force_tag_closing = true;
2086 $rm_attnames = Array(
2097 $secremoveimg = "../images/" . _("sec_remove_eng.png");
2098 $bad_attvals = Array(
2101 "/^src|background/i" =>
2104 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2105 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2106 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2109 "\\1$secremoveimg\\2",
2110 "\\1$secremoveimg\\2",
2111 "\\1$secremoveimg\\2",
2114 "/^href|action/i" =>
2117 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2118 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2119 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2133 "/include-source/i",
2134 "/position\s*:\s*absolute/i",
2135 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2136 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2137 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2138 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2154 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2155 $view_unsafe_images = false;
2157 if (!$view_unsafe_images){
2159 * Remove any references to http/https if view_unsafe_images set
2162 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2163 '/^([\'\"])\s*https*:.*([\'\"])/si');
2164 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2165 "\\1$secremoveimg\\1");
2166 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2167 '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
2168 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2169 "url(\\1$secremoveimg\\1)");
2172 $add_attr_to_tag = Array(
2174 Array('target'=>'"_blank"',
2175 'title'=>'"'._("This external link will open in a new window").'"'
2178 $trusted = sq_sanitize($body,
2180 $rm_tags_with_content,
2190 if (preg_match("|$secremoveimg|i", $trusted)){
2191 $has_unsafe_images = true;
2194 // we want to parse mailto's in HTML output, change to SM compose links
2195 // this is a modified version of code from url_parser.php... but Marc is
2196 // right: we need a better filtering implementation; adding this randomly
2197 // here is not a great solution
2199 if ($take_mailto_links) {
2200 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2201 global $MailTo_PReg_Match;
2202 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
2203 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2204 foreach ($regs[0] as $i => $mailto_before) {
2205 $mailto_params = $regs[10][$i];
2206 // get rid of any tailing quote since we have to add send_to to the end
2208 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2209 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2210 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2211 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2213 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2214 $to = 'to=' . $regs[1][$i];
2215 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2216 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2218 if ($mailto_params) //already some params, append to them
2219 $mailto_params .= '&' . $to;
2221 $mailto_params .= '?' . $to;
2225 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2227 // we'll already have target=_blank, no need to allow comp_in_new
2228 // here (which would be a lot more work anyway)
2230 global $compose_new_win;
2231 $temp_comp_in_new = $compose_new_win;
2232 $compose_new_win = 0;
2233 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2234 $compose_new_win = $temp_comp_in_new;
2236 // remove <a href=" and anything after the next quote (we only
2237 // need the uri, not the link HTML) in compose uri
2239 $comp_uri = substr($comp_uri, 9);
2240 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2241 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2250 * function SendDownloadHeaders - send file to the browser
2252 * Original Source: SM core src/download.php
2253 * moved here to make it available to other code, and separate
2254 * front end from back end functionality.
2256 * @param string $type0 first half of mime type
2257 * @param string $type1 second half of mime type
2258 * @param string $filename filename to tell the browser for downloaded file
2259 * @param boolean $force whether to force the download dialog to pop
2260 * @param optional integer $filesize send the Content-Header and length to the browser
2263 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2264 global $languages, $squirrelmail_language;
2267 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2269 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2270 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2274 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
2275 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2279 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2280 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2282 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2284 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2287 // A Pox on Microsoft and it's Internet Explorer!
2289 // IE has lots of bugs with file downloads.
2290 // It also has problems with SSL. Both of these cause problems
2291 // for us in this function.
2293 // See this article on Cache Control headers and SSL
2294 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2296 // The best thing you can do for IE is to upgrade to the latest
2298 //set all the Cache Control Headers for IE
2300 $filename=rawurlencode($filename);
2301 header ("Pragma: public");
2302 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2303 header ("Cache-Control: post-check=0, pre-check=0", false);
2304 header ("Cache-Control: private");
2306 //set the inline header for IE, we'll add the attachment header later if we need it
2307 header ("Content-Disposition: inline; filename=$filename");
2311 // Try to show in browser window
2312 header ("Content-Disposition: inline; filename=\"$filename\"");
2313 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2315 // Try to pop up the "save as" box
2317 // IE makes this hard. It pops up 2 save boxes, or none.
2318 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2319 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2320 // But, according to Microsoft, it is "RFC compliant but doesn't
2321 // take into account some deviations that allowed within the
2322 // specification." Doesn't that mean RFC non-compliant?
2323 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2325 // all browsers need the application/octet-stream header for this
2326 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2328 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2329 // Do not have quotes around filename, but that applied to
2330 // "attachment"... does it apply to inline too?
2331 header ("Content-Disposition: attachment; filename=\"$filename\"");
2333 if ($isIE && !$isIE6) {
2334 // This combination seems to work mostly. IE 5.5 SP 1 has
2335 // known issues (see the Microsoft Knowledge Base)
2337 // This works for most types, but doesn't work with Word files
2338 header ("Content-Type: application/download; name=\"$filename\"");
2340 // These are spares, just in case. :-)
2341 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2342 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2343 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2345 // another application/octet-stream forces download for Netscape
2346 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2350 //send the content-length header if the calling function provides it
2351 if ($filesize > 0) {
2352 header("Content-Length: $filesize");
2355 } // end fn SendDownloadHeaders