6 * This contains the functions necessary to detect and decode MIME
9 * @copyright © 1999-2006 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,
338 $use_iframe, $iframe_height, $download_and_unsafe_link;
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);
392 // Convert character set in order to display html mails in different character set
393 $html_body = charset_decode($body_message->header
->getParameter('charset'),$html_body,false,true);
395 // creating iframe url
396 $iframeurl=sqm_baseuri().'src/view_html.php?'
397 . 'mailbox=' . $urlmailbox
398 . '&passed_id=' . $id
399 . '&ent_id=' . $ent_num
400 . '&view_unsafe_images=' . (int) $view_unsafe_images;
402 // adding warning message
403 $body = html_tag('div',_("Viewing HTML formatted email"),'center');
406 * height can't be set to 100%, because it does not work as expected when
407 * iframe is inside the table. Browsers do not create full height objects
408 * even when iframe is not nested. Maybe there is some way to get full size
409 * with CSS. Tested in firefox 1.02 and opera 7.53
411 * width="100%" does not work as expected, when table width is not set (automatic)
413 * tokul: I think <iframe> are safer sandbox than <object>. Objects might
414 * need special handling for IE and IE6SP2.
416 $body.= "<div><iframe name=\"message_frame\" width=\"100%\" height=\"$iframe_height\" src=\"$iframeurl\""
417 .' frameborder="1" marginwidth="0" marginheight="0" scrolling="auto">' . "\n";
419 // Message for browsers without iframe support
420 //$body.= _("Your browser does not support inline frames.
421 // You can view HTML formated message by following below link.");
422 //$body.= "<br /><a href=\"$iframeurl\">"._("View HTML Message")."</a>";
424 // if browser can't render iframe, it renders html message.
428 $body.="</iframe></div>\n";
430 // old way of html rendering
431 $body = magicHTML($body, $id, $message, $mailbox);
433 * convert character set. charset_decode does not remove html special chars
434 * applied by magicHTML functions and does not sanitize them second time if
435 * fourth argument is true.
437 $body = charset_decode($body_message->header
->getParameter('charset'),$body,false,true);
440 translateText($body, $wrap_at,
441 $body_message->header
->getParameter('charset'));
444 // if this is the clean display (i.e. printer friendly), stop here.
449 $download_and_unsafe_link = '';
451 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
452 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
453 '&startMessage=' . $startMessage . '&show_more=0';
454 if (isset($passed_ent_id)) {
455 $link .= '&passed_ent_id='.$passed_ent_id;
457 $download_and_unsafe_link .= ' | <a href="download.php?absolute_dl=true&' .
458 $link . '">' . _("Download this as a file") . '</a>';
459 if ($view_unsafe_images) {
460 $text = _("Hide Unsafe Images");
462 if (isset($has_unsafe_images) && $has_unsafe_images) {
463 $link .= '&view_unsafe_images=1';
464 $text = _("View Unsafe Images");
470 $download_and_unsafe_link .= ' | <a href="read_body.php?' . $link . '">' . $text . '</a>';
477 * Displays attachment links and information
479 * Since 1.3.0 function is not included in formatBody() call.
481 * Since 1.0.2 uses attachment $type0/$type1 hook.
482 * Since 1.2.5 uses attachment $type0/* hook.
483 * Since 1.5.0 uses attachments_bottom hook.
485 * @param object $message SquirrelMail message object
486 * @param array $exclude_id message parts that are not attachments.
487 * @param string $mailbox mailbox name
488 * @param integer $id message id
489 * @return string html formated attachment information.
491 function formatAttachments($message, $exclude_id, $mailbox, $id) {
492 global $where, $what, $startMessage, $color, $passed_ent_id;
494 $att_ar = $message->getAttachments($exclude_id);
496 if (!count($att_ar)) return '';
500 $urlMailbox = urlencode($mailbox);
502 foreach ($att_ar as $att) {
503 $ent = $att->entity_id
;
504 $header = $att->header
;
505 $type0 = strtolower($header->type0
);
506 $type1 = strtolower($header->type1
);
508 $links['download link']['text'] = _("Download");
509 $links['download link']['href'] = sqm_baseuri() .
510 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
511 if ($type0 =='message' && $type1 == 'rfc822') {
512 $default_page = sqm_baseuri() . 'src/read_body.php';
513 $rfc822_header = $att->rfc822_header
;
514 $filename = $rfc822_header->subject
;
515 if (trim( $filename ) == '') {
516 $filename = 'untitled-[' . $ent . ']' ;
518 $from_o = $rfc822_header->from
;
519 if (is_object($from_o)) {
520 $from_name = decodeHeader($from_o->getAddress(false));
522 $from_name = _("Unknown sender");
524 $description = $from_name;
526 $default_page = sqm_baseuri() . 'src/download.php';
527 $filename = $att->getFilename();
528 if ($header->description
) {
529 $description = decodeHeader($header->description
);
535 $display_filename = $filename;
536 if (isset($passed_ent_id)) {
537 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
539 $passed_ent_id_link = '';
541 $defaultlink = $default_page . "?startMessage=$startMessage"
542 . "&passed_id=$id&mailbox=$urlMailbox"
543 . '&ent_id='.$ent.$passed_ent_id_link;
544 if ($where && $what) {
545 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
548 /* This executes the attachment hook with a specific MIME-type.
549 * If that doesn't have results, it tries if there's a rule
550 * for a more generic type.
552 $hookresults = do_hook("attachment $type0/$type1", $links,
553 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
554 $display_filename, $where, $what);
555 if(count($hookresults[1]) <= 1) {
556 $hookresults = do_hook("attachment $type0/*", $links,
557 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
558 $display_filename, $where, $what);
561 $links = $hookresults[1];
562 $defaultlink = $hookresults[6];
564 $attachments .= '<tr><td>' .
565 '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a> </td>' .
566 '<td><small><b>' . show_readable_size($header->size
) .
567 '</b> </small></td>' .
568 '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ] </small></td>' .
570 $attachments .= '<b>' . $description . '</b>';
571 $attachments .= '</small></td><td><small> ';
574 foreach ($links as $val) {
578 $attachments .= ' | ';
580 $attachments .= '<a href="' . $val['href'] . '">'
581 . (isset($val['text']) && !empty($val['text']) ?
$val['text'] : '')
582 . (isset($val['extra']) && !empty($val['extra']) ?
$val['extra'] : '')
586 $attachments .= "</td></tr>\n";
588 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
589 if ($attachmentadd != '')
590 $attachments = $attachmentadd;
594 function sqimap_base64_decode(&$string) {
596 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
597 // fly decoding (to reduce memory usage) you have to check if the
598 // data has incomplete pairs
600 // Remove the noise in order to check if the 4 bytes pairs are complete
601 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
604 $iMod = strlen($string) %
4;
606 $sStringRem = substr($string,-$iMod);
607 // Check if $sStringRem contains padding characters
608 if (substr($sStringRem,-1) != '=') {
609 $string = substr($string,0,-$iMod);
614 $string = base64_decode($string);
619 * Decodes encoded message body
621 * This function decodes the body depending on the encoding type.
622 * Currently quoted-printable and base64 encodings are supported.
623 * decode_body hook was added to this function in 1.4.2/1.5.0
624 * @param string $body encoded message body
625 * @param string $encoding used encoding
626 * @return string decoded string
629 function decodeBody($body, $encoding) {
631 $body = str_replace("\r\n", "\n", $body);
632 $encoding = strtolower($encoding);
634 $encoding_handler = do_hook_function('decode_body', $encoding);
637 // plugins get first shot at decoding the body
639 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
640 $body = $encoding_handler('decode', $body);
642 } elseif ($encoding == 'quoted-printable' ||
643 $encoding == 'quoted_printable') {
645 * quoted_printable_decode() function is broken in older
646 * php versions. Text with \r\n decoding was fixed only
647 * in php 4.3.0. Minimal code requirement 4.0.4 +
648 * str_replace("\r\n", "\n", $body); call.
650 $body = quoted_printable_decode($body);
651 } elseif ($encoding == 'base64') {
652 $body = base64_decode($body);
655 // All other encodings are returned raw.
662 * This functions decode strings that is encoded according to
663 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
664 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
666 * @param string $string header string that has to be made readable
667 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
668 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
669 * @param boolean $decide decide if string can be utfencoded. defaults to false
670 * @return string decoded header string
672 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
673 global $languages, $squirrelmail_language,$default_charset;
674 if (is_array($string)) {
675 $string = implode("\n", $string);
678 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
679 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
680 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
681 // Do we need to return at this point?
688 $aString = explode(' ',$string);
690 foreach ($aString as $chunk) {
691 if ($encoded && $chunk === '') {
693 } elseif ($chunk === '') {
698 /* if encoded words are not separated by a linear-space-white we still catch them */
701 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
702 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
703 if ($iLastMatch !== $j) {
713 $ret .= htmlspecialchars($res[1]);
717 $encoding = ucfirst($res[3]);
719 /* decide about valid decoding */
720 if ($decide && is_conversion_safe($res[2])) {
722 $can_be_encoded=true;
724 $can_be_encoded=false;
729 $replace = base64_decode($res[4]);
731 if ($can_be_encoded) {
732 /* convert string to different charset,
733 * if functions asks for it (usually in compose)
735 $ret .= charset_convert($res[2],$replace,$default_charset);
737 // convert string to html codes in order to display it
738 $ret .= charset_decode($res[2],$replace);
742 $replace = htmlspecialchars($replace);
748 $replace = str_replace('_', ' ', $res[4]);
749 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
752 if ($can_be_encoded) {
753 /* convert string to different charset,
754 * if functions asks for it (usually in compose)
756 $replace = charset_convert($res[2], $replace,$default_charset);
758 // convert string to html codes in order to display it
759 $replace = charset_decode($res[2], $replace);
763 $replace = htmlspecialchars($replace);
782 if (!$encoded && $htmlsave) {
783 $ret .= htmlspecialchars($chunk);
789 /* remove the first added space */
792 $ret = substr($ret,5);
794 $ret = substr($ret,1);
804 * Function uses XTRA_CODE _encodeheader function, if such function exists.
806 * Function uses Q encoding by default and encodes a string according to RFC
807 * 1522 for use in headers if it contains 8-bit characters or anything that
808 * looks like it should be encoded.
810 * Function switches to B encoding and encodeHeaderBase64() function, if
811 * string is 8bit and multibyte character set supported by mbstring extension
812 * is used. It can cause E_USER_NOTICE errors, if interface is used with
813 * multibyte character set unsupported by mbstring extension.
815 * @param string $string header string, that has to be encoded
816 * @return string quoted-printable encoded string
817 * @todo make $mb_charsets system wide constant
819 function encodeHeader ($string) {
820 global $default_charset, $languages, $squirrelmail_language;
822 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
823 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
824 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
827 // Use B encoding for multibyte charsets
828 $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
829 if (in_array($default_charset,$mb_charsets) &&
830 in_array($default_charset,sq_mb_list_encodings()) &&
831 sq_is8bit($string)) {
832 return encodeHeaderBase64($string,$default_charset);
833 } elseif (in_array($default_charset,$mb_charsets) &&
834 sq_is8bit($string) &&
835 ! in_array($default_charset,sq_mb_list_encodings())) {
836 // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
837 // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
840 // Encode only if the string contains 8-bit characters or =?
841 $j = strlen($string);
842 $max_l = 75 - strlen($default_charset) - 7;
845 $iEncStart = $enc_init = false;
846 $cur_l = $iOffset = 0;
847 for($i = 0; $i < $j; ++
$i) {
856 if ($iEncStart === false) {
860 if ($cur_l > ($max_l-2)) {
861 /* if there is an stringpart that doesn't need encoding, add it */
862 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
863 $aRet[] = "=?$default_charset?Q?$ret?=";
869 $ret .= sprintf("=%02X",ord($string{$i}));
874 if ($iEncStart !== false) {
875 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
876 $aRet[] = "=?$default_charset?Q?$ret?=";
884 if ($iEncStart !== false) {
886 if ($cur_l > $max_l) {
887 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
888 $aRet[] = "=?$default_charset?Q?$ret?=";
899 $k = ord($string{$i});
901 if ($iEncStart === false) {
902 // do not start encoding in the middle of a string, also take the rest of the word.
903 $sLeadString = substr($string,0,$i);
904 $aLeadString = explode(' ',$sLeadString);
905 $sToBeEncoded = array_pop($aLeadString);
906 $iEncStart = $i - strlen($sToBeEncoded);
907 $ret .= $sToBeEncoded;
908 $cur_l +
= strlen($sToBeEncoded);
911 /* first we add the encoded string that reached it's max size */
912 if ($cur_l > ($max_l-2)) {
913 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
914 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
921 $ret .= sprintf("=%02X", $k);
923 if ($iEncStart !== false) {
925 if ($cur_l > $max_l) {
926 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
927 $aRet[] = "=?$default_charset?Q?$ret?=";
942 if ($iEncStart !== false) {
943 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
944 $aRet[] = "=?$default_charset?Q?$ret?=";
946 $aRet[] = substr($string,$iOffset);
948 $string = implode('',$aRet);
954 * Encodes string according to rfc2047 B encoding header formating rules
956 * It is recommended way to encode headers with character sets that store
957 * symbols in more than one byte.
959 * Function requires mbstring support. If required mbstring functions are missing,
960 * function returns false and sets E_USER_WARNING level error message.
962 * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
963 * that mbstring functions will generate E_WARNING errors, if unsupported
964 * character set is used. mb_encode_mimeheader function provided by php
965 * mbstring extension is not used in order to get better control of header
968 * Used php code functions - function_exists(), trigger_error(), strlen()
969 * (is used with charset names and base64 strings). Used php mbstring
970 * functions - mb_strlen and mb_substr.
972 * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
973 * encoding), rfc 2822 (header folding)
975 * @param string $string header string that must be encoded
976 * @param string $charset character set. Must be supported by mbstring extension.
977 * Use sq_mb_list_encodings() to detect supported charsets.
978 * @return string string encoded according to rfc2047 B encoding formating rules
980 * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
981 * @todo Do we want to control max length of header?
982 * @todo Do we want to control EOL (end-of-line) marker?
983 * @todo Do we want to translate error message?
985 function encodeHeaderBase64($string,$charset) {
987 * Check mbstring function requirements.
989 if (! function_exists('mb_strlen') ||
990 ! function_exists('mb_substr')) {
991 // set E_USER_WARNING
992 trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING
);
997 // initial return array
1001 * header length = 75 symbols max (same as in encodeHeader)
1002 * remove $charset length
1003 * remove =? ? ?= (5 chars)
1004 * remove 2 more chars (\r\n ?)
1006 $iMaxLength = 75 - strlen($charset) - 7;
1008 // set first character position
1011 // loop through all characters. count characters and not bytes.
1012 for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++
) {
1013 // encode string from starting character to current character.
1014 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1016 // Check encoded string length
1017 if(strlen($encoded_string)>$iMaxLength) {
1018 // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
1019 $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
1021 // set new starting character
1022 $iStartCharNum = $iCharNum-1;
1024 // encode last char (in case it is last character in string)
1025 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1026 } // if string is shorter than max length - add next character
1029 // add last encoded string to array
1030 $aRet[] = $encoded_string;
1032 // set initial return string
1035 // loop through encoded strings
1036 foreach($aRet as $string) {
1037 // TODO: Do we want to control EOL (end-of-line) marker
1038 if ($sRet!='') $sRet.= " ";
1040 // add header tags and encoded string to return string
1041 $sRet.= '=?'.$charset.'?B?'.$string.'?=';
1047 /* This function trys to locate the entity_id of a specific mime element */
1048 function find_ent_id($id, $message) {
1049 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
1050 if ($message->entities
[$i]->header
->type0
== 'multipart') {
1051 $ret = find_ent_id($id, $message->entities
[$i]);
1053 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
1054 // if (sq_check_save_extension($message->entities[$i])) {
1055 return $message->entities
[$i]->entity_id
;
1057 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
1059 * This is part of a fix for Outlook Express 6.x generating
1060 * cid URLs without creating content-id headers
1063 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
1064 return $message->entities
[$i]->entity_id
;
1072 function sq_check_save_extension($message) {
1073 $filename = $message->getFilename();
1074 $ext = substr($filename, strrpos($filename,'.')+
1);
1075 $save_extensions = array('jpg','jpeg','gif','png','bmp');
1076 return in_array($ext, $save_extensions);
1081 ** HTMLFILTER ROUTINES
1085 * This function checks attribute values for entity-encoded values
1086 * and returns them translated into 8-bit strings so we can run
1089 * @param $attvalue A string to run entity check against.
1090 * @return Nothing, modifies a reference value.
1092 function sq_defang(&$attvalue){
1095 * Skip this if there aren't ampersands or backslashes.
1097 if (strpos($attvalue, '&') === false
1098 && strpos($attvalue, '\\') === false){
1104 $m = $m ||
sq_deent($attvalue, '/\�*(\d+);*/s');
1105 $m = $m ||
sq_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true);
1106 $m = $m ||
sq_deent($attvalue, '/\\\\(\d+)/s', true);
1107 } while ($m == true);
1108 $attvalue = stripslashes($attvalue);
1112 * Kill any tabs, newlines, or carriage returns. Our friends the
1113 * makers of the browser with 95% market value decided that it'd
1114 * be funny to make "java[tab]script" be just as good as "javascript".
1116 * @param attvalue The attribute value before extraneous spaces removed.
1117 * @return attvalue Nothing, modifies a reference value.
1119 function sq_unspace(&$attvalue){
1121 if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
1122 $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
1123 Array('', '', '', '', ''), $attvalue);
1128 * This function returns the final tag out of the tag name, an array
1129 * of attributes, and the type of the tag. This function is called by
1130 * sq_sanitize internally.
1132 * @param $tagname the name of the tag.
1133 * @param $attary the array of attributes and their values
1134 * @param $tagtype The type of the tag (see in comments).
1135 * @return a string with the final tag representation.
1137 function sq_tagprint($tagname, $attary, $tagtype){
1138 $me = 'sq_tagprint';
1141 $fulltag = '</' . $tagname . '>';
1143 $fulltag = '<' . $tagname;
1144 if (is_array($attary) && sizeof($attary)){
1146 while (list($attname, $attvalue) = each($attary)){
1147 array_push($atts, "$attname=$attvalue");
1149 $fulltag .= ' ' . join(" ", $atts);
1160 * A small helper function to use with array_walk. Modifies a by-ref
1161 * value and makes it lowercase.
1163 * @param $val a value passed by-ref.
1164 * @return void since it modifies a by-ref value.
1166 function sq_casenormalize(&$val){
1167 $val = strtolower($val);
1171 * This function skips any whitespace from the current position within
1172 * a string and to the next non-whitespace value.
1174 * @param $body the string
1175 * @param $offset the offset within the string where we should start
1176 * looking for the next non-whitespace character.
1177 * @return the location within the $body where the next
1178 * non-whitespace char is located.
1180 function sq_skipspace($body, $offset){
1181 $me = 'sq_skipspace';
1182 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1183 if (sizeof($matches{1})){
1184 $count = strlen($matches{1});
1191 * This function looks for the next character within a string. It's
1192 * really just a glorified "strpos", except it catches if failures
1195 * @param $body The string to look for needle in.
1196 * @param $offset Start looking from this position.
1197 * @param $needle The character/string to look for.
1198 * @return location of the next occurance of the needle, or
1199 * strlen($body) if needle wasn't found.
1201 function sq_findnxstr($body, $offset, $needle){
1202 $me = 'sq_findnxstr';
1203 $pos = strpos($body, $needle, $offset);
1204 if ($pos === FALSE){
1205 $pos = strlen($body);
1211 * This function takes a PCRE-style regexp and tries to match it
1212 * within the string.
1214 * @param $body The string to look for needle in.
1215 * @param $offset Start looking from here.
1216 * @param $reg A PCRE-style regex to match.
1217 * @return Returns a false if no matches found, or an array
1218 * with the following members:
1219 * - integer with the location of the match within $body
1220 * - string with whatever content between offset and the match
1221 * - string with whatever it is we matched
1223 function sq_findnxreg($body, $offset, $reg){
1224 $me = 'sq_findnxreg';
1227 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1228 if (!isset($matches{0}) ||
!$matches{0}){
1231 $retarr{0} = $offset +
strlen($matches{1});
1232 $retarr{1} = $matches{1};
1233 $retarr{2} = $matches{2};
1239 * This function looks for the next tag.
1241 * @param $body String where to look for the next tag.
1242 * @param $offset Start looking from here.
1243 * @return false if no more tags exist in the body, or
1244 * an array with the following members:
1245 * - string with the name of the tag
1246 * - array with attributes and their values
1247 * - integer with tag type (1, 2, or 3)
1248 * - integer where the tag starts (starting "<")
1249 * - integer where the tag ends (ending ">")
1250 * first three members will be false, if the tag is invalid.
1252 function sq_getnxtag($body, $offset){
1253 $me = 'sq_getnxtag';
1254 if ($offset > strlen($body)){
1257 $lt = sq_findnxstr($body, $offset, "<");
1258 if ($lt == strlen($body)){
1263 * blah blah <tag attribute="value">
1266 $pos = sq_skipspace($body, $lt+
1);
1267 if ($pos >= strlen($body)){
1268 return Array(false, false, false, $lt, strlen($body));
1271 * There are 3 kinds of tags:
1272 * 1. Opening tag, e.g.:
1274 * 2. Closing tag, e.g.:
1276 * 3. XHTML-style content-less tag, e.g.:
1277 * <img src="blah" />
1280 switch (substr($body, $pos, 1)){
1287 * A comment or an SGML declaration.
1289 if (substr($body, $pos+
1, 2) == "--"){
1290 $gt = strpos($body, "-->", $pos);
1292 $gt = strlen($body);
1296 return Array(false, false, false, $lt, $gt);
1298 $gt = sq_findnxstr($body, $pos, ">");
1299 return Array(false, false, false, $lt, $gt);
1304 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1314 * Look for next [\W-_], which will indicate the end of the tag name.
1316 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1317 if ($regary == false){
1318 return Array(false, false, false, $lt, strlen($body));
1320 list($pos, $tagname, $match) = $regary;
1321 $tagname = strtolower($tagname);
1324 * $match can be either of these:
1325 * '>' indicating the end of the tag entirely.
1326 * '\s' indicating the end of the tag name.
1327 * '/' indicating that this is type-3 xhtml tag.
1329 * Whatever else we find there indicates an invalid tag.
1334 * This is an xhtml-style tag with a closing / at the
1335 * end, like so: <img src="blah" />. Check if it's followed
1336 * by the closing bracket. If not, then this tag is invalid
1338 if (substr($body, $pos, 2) == "/>"){
1342 $gt = sq_findnxstr($body, $pos, ">");
1343 $retary = Array(false, false, false, $lt, $gt);
1347 return Array($tagname, false, $tagtype, $lt, $pos);
1351 * Check if it's whitespace
1353 if (!preg_match('/\s/', $match)){
1355 * This is an invalid tag! Look for the next closing ">".
1357 $gt = sq_findnxstr($body, $lt, ">");
1358 return Array(false, false, false, $lt, $gt);
1364 * At this point we're here:
1365 * <tagname attribute='blah'>
1368 * At this point we loop in order to find all attributes.
1374 while ($pos <= strlen($body)){
1375 $pos = sq_skipspace($body, $pos);
1376 if ($pos == strlen($body)){
1380 return Array(false, false, false, $lt, $pos);
1383 * See if we arrived at a ">" or "/>", which means that we reached
1384 * the end of the tag.
1387 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1391 $pos +
= strlen($matches{1});
1392 if ($matches{2} == "/>"){
1396 return Array($tagname, $attary, $tagtype, $lt, $pos);
1400 * There are several types of attributes, with optional
1401 * [:space:] between members.
1403 * attrname[:space:]=[:space:]'CDATA'
1405 * attrname[:space:]=[:space:]"CDATA"
1407 * attr[:space:]=[:space:]CDATA
1411 * We leave types 1 and 2 the same, type 3 we check for
1412 * '"' and convert to """ if needed, then wrap in
1413 * double quotes. Type 4 we convert into:
1416 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1417 if ($regary == false){
1419 * Looks like body ended before the end of tag.
1421 return Array(false, false, false, $lt, strlen($body));
1423 list($pos, $attname, $match) = $regary;
1424 $attname = strtolower($attname);
1426 * We arrived at the end of attribute name. Several things possible
1428 * '>' means the end of the tag and this is attribute type 4
1429 * '/' if followed by '>' means the same thing as above
1430 * '\s' means a lot of things -- look what it's followed by.
1431 * anything else means the attribute is invalid.
1436 * This is an xhtml-style tag with a closing / at the
1437 * end, like so: <img src="blah" />. Check if it's followed
1438 * by the closing bracket. If not, then this tag is invalid
1440 if (substr($body, $pos, 2) == "/>"){
1444 $gt = sq_findnxstr($body, $pos, ">");
1445 $retary = Array(false, false, false, $lt, $gt);
1449 $attary{$attname} = '"yes"';
1450 return Array($tagname, $attary, $tagtype, $lt, $pos);
1454 * Skip whitespace and see what we arrive at.
1456 $pos = sq_skipspace($body, $pos);
1457 $char = substr($body, $pos, 1);
1459 * Two things are valid here:
1460 * '=' means this is attribute type 1 2 or 3.
1461 * \w means this was attribute type 4.
1462 * anything else we ignore and re-loop. End of tag and
1463 * invalid stuff will be caught by our checks at the beginning
1468 $pos = sq_skipspace($body, $pos);
1470 * Here are 3 possibilities:
1471 * "'" attribute type 1
1472 * '"' attribute type 2
1473 * everything else is the content of tag type 3
1475 $quot = substr($body, $pos, 1);
1477 $regary = sq_findnxreg($body, $pos+
1, "\'");
1478 if ($regary == false){
1479 return Array(false, false, false, $lt, strlen($body));
1481 list($pos, $attval, $match) = $regary;
1483 $attary{$attname} = "'" . $attval . "'";
1484 } else if ($quot == '"'){
1485 $regary = sq_findnxreg($body, $pos+
1, '\"');
1486 if ($regary == false){
1487 return Array(false, false, false, $lt, strlen($body));
1489 list($pos, $attval, $match) = $regary;
1491 $attary{$attname} = '"' . $attval . '"';
1494 * These are hateful. Look for \s, or >.
1496 $regary = sq_findnxreg($body, $pos, "[\s>]");
1497 if ($regary == false){
1498 return Array(false, false, false, $lt, strlen($body));
1500 list($pos, $attval, $match) = $regary;
1502 * If it's ">" it will be caught at the top.
1504 $attval = preg_replace("/\"/s", """, $attval);
1505 $attary{$attname} = '"' . $attval . '"';
1507 } else if (preg_match("|[\w/>]|", $char)) {
1509 * That was attribute type 4.
1511 $attary{$attname} = '"yes"';
1514 * An illegal character. Find next '>' and return.
1516 $gt = sq_findnxstr($body, $pos, ">");
1517 return Array(false, false, false, $lt, $gt);
1523 * The fact that we got here indicates that the tag end was never
1524 * found. Return invalid tag indication so it gets stripped.
1526 return Array(false, false, false, $lt, strlen($body));
1530 * Translates entities into literal values so they can be checked.
1532 * @param $attvalue the by-ref value to check.
1533 * @param $regex the regular expression to check against.
1534 * @param $hex whether the entites are hexadecimal.
1535 * @return True or False depending on whether there were matches.
1537 function sq_deent(&$attvalue, $regex, $hex=false){
1540 preg_match_all($regex, $attvalue, $matches);
1541 if (is_array($matches) && sizeof($matches[0]) > 0){
1543 for ($i = 0; $i < sizeof($matches[0]); $i++
){
1544 $numval = $matches[1][$i];
1546 $numval = hexdec($numval);
1548 $repl{$matches[0][$i]} = chr($numval);
1550 $attvalue = strtr($attvalue, $repl);
1558 * This function runs various checks against the attributes.
1560 * @param $tagname String with the name of the tag.
1561 * @param $attary Array with all tag attributes.
1562 * @param $rm_attnames See description for sq_sanitize
1563 * @param $bad_attvals See description for sq_sanitize
1564 * @param $add_attr_to_tag See description for sq_sanitize
1565 * @param $message message object
1566 * @param $id message id
1567 * @return Array with modified attributes.
1569 function sq_fixatts($tagname,
1579 while (list($attname, $attvalue) = each($attary)){
1581 * See if this attribute should be removed.
1583 foreach ($rm_attnames as $matchtag=>$matchattrs){
1584 if (preg_match($matchtag, $tagname)){
1585 foreach ($matchattrs as $matchattr){
1586 if (preg_match($matchattr, $attname)){
1587 unset($attary{$attname});
1594 * Remove any backslashes, entities, and extraneous whitespace.
1596 sq_defang($attvalue);
1597 sq_unspace($attvalue);
1600 * Now let's run checks on the attvalues.
1601 * I don't expect anyone to comprehend this. If you do,
1602 * get in touch with me so I can drive to where you live and
1603 * shake your hand personally. :)
1605 foreach ($bad_attvals as $matchtag=>$matchattrs){
1606 if (preg_match($matchtag, $tagname)){
1607 foreach ($matchattrs as $matchattr=>$valary){
1608 if (preg_match($matchattr, $attname)){
1610 * There are two arrays in valary.
1612 * Second one is replacements
1614 list($valmatch, $valrepl) = $valary;
1616 preg_replace($valmatch, $valrepl, $attvalue);
1617 if ($newvalue != $attvalue){
1618 $attary{$attname} = $newvalue;
1626 * Replace empty src tags with the blank image. src is only used
1627 * for frames, images, and image inputs. Doing a replace should
1628 * not affect them working as should be, however it will stop
1629 * IE from being kicked off when src for img tags are not set
1631 if (($attname == 'src') && ($attvalue == '""')) {
1632 $attary{$attname} = '"' . SM_PATH
. 'images/blank.png"';
1636 * Turn cid: urls into http-friendly ones.
1638 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1639 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1643 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1644 * One day MS might actually make it match something useful, for now, falling
1645 * back to using cid2http, so we can grab the blank.png.
1647 if (preg_match("/^[\'\"]\s*outbind:\/\//si", $attvalue)) {
1648 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1653 * See if we need to append any attributes to this tag.
1655 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1656 if (preg_match($matchtag, $tagname)){
1657 $attary = array_merge($attary, $addattary);
1664 * This function edits the style definition to make them friendly and
1665 * usable in SquirrelMail.
1667 * @param $message the message object
1668 * @param $id the message id
1669 * @param $content a string with whatever is between <style> and </style>
1670 * @param $mailbox the message mailbox
1671 * @return a string with edited content.
1673 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1674 global $view_unsafe_images;
1675 $me = 'sq_fixstyle';
1676 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1678 return array(FALSE, strlen($body));
1680 $newpos = $ret[0] +
strlen($ret[2]);
1683 * First look for general BODY style declaration, which would be
1685 * body {background: blah-blah}
1686 * and change it to .bodyclass so we can just assign it to a <div>
1688 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1689 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1691 * Fix url('blah') declarations.
1693 // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1694 // "url(\\1$secremoveimg\\2)", $content);
1696 $content = str_replace("\0", "", $content);
1698 // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
1699 while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si", $content, $matches)) {
1700 $sProto = strtolower($matches[1]);
1703 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1708 if (!$view_unsafe_images){
1710 $sExpr = "/url\s*\(\s*[\'\"]?\s*$sProto*:.*[\'\"]?\s*\)/si";
1711 $content = preg_replace($sExpr, "u\0r\0l(\\1$secremoveimg\\2)", $content);
1714 $content = preg_replace('/url/i',"u\0r\0l",$content);
1718 * Fix urls that refer to cid:
1721 $cidurl = 'cid:'. $matches[2];
1722 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
1723 // escape parentheses that can modify the regular expression
1724 $cidurl = str_replace(array('(',')'),array('\\(','\\)'),$cidurl);
1725 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1726 "u\0r\0l($httpurl)", $content);
1730 * replace url with protocol other then the white list
1731 * http,https and cid by an empty string.
1733 $content = preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
1739 $content = str_replace("\0", "", $content);
1741 * Remove any backslashes, entities, and extraneous whitespace.
1743 $contentTemp = $content;
1744 sq_defang($contentTemp);
1745 sq_unspace($contentTemp);
1748 * Fix stupid css declarations which lead to vulnerabilities
1751 $match = Array('/\/\*.*\*\//',
1755 '/include-source/i');
1756 $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy');
1757 $contentNew = preg_replace($match, $replace, $contentTemp);
1758 if ($contentNew !== $contentTemp) {
1759 // insecure css declarations are used. From now on we don't care
1760 // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
1761 $content = $contentNew;
1763 return array($content, $newpos);
1768 * This function converts cid: url's into the ones that can be viewed in
1771 * @param $message the message object
1772 * @param $id the message id
1773 * @param $cidurl the cid: url.
1774 * @param $mailbox the message mailbox
1775 * @return a string with a http-friendly url
1777 function sq_cid2http($message, $id, $cidurl, $mailbox){
1779 * Get rid of quotes.
1781 $quotchar = substr($cidurl, 0, 1);
1782 if ($quotchar == '"' ||
$quotchar == "'"){
1783 $cidurl = str_replace($quotchar, "", $cidurl);
1787 $cidurl = substr(trim($cidurl), 4);
1789 $match_str = '/\{.*?\}\//';
1791 $cidurl = preg_replace($match_str, $str_rep, $cidurl);
1793 $linkurl = find_ent_id($cidurl, $message);
1794 /* in case of non-save cid links $httpurl should be replaced by a sort of
1795 unsave link image */
1799 * This is part of a fix for Outlook Express 6.x generating
1800 * cid URLs without creating content-id headers. These images are
1801 * not part of the multipart/related html mail. The html contains
1802 * <img src="cid:{some_id}/image_filename.ext"> references to
1803 * attached images with as goal to render them inline although
1804 * the attachment disposition property is not inline.
1807 if (empty($linkurl)) {
1808 if (preg_match('/{.*}\//', $cidurl)) {
1809 $cidurl = preg_replace('/{.*}\//','', $cidurl);
1810 if (!empty($cidurl)) {
1811 $linkurl = find_ent_id($cidurl, $message);
1816 if (!empty($linkurl)) {
1817 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1818 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1819 '&ent_id=' . $linkurl . $quotchar;
1822 * If we couldn't generate a proper img url, drop in a blank image
1823 * instead of sending back empty, otherwise it causes unusual behaviour
1825 $httpurl = $quotchar . SM_PATH
. 'images/blank.png' . $quotchar;
1832 * This function changes the <body> tag into a <div> tag since we
1833 * can't really have a body-within-body.
1835 * @param $attary an array of attributes and values of <body>
1836 * @param $mailbox mailbox we're currently reading (for cid2http)
1837 * @param $message current message (for cid2http)
1838 * @param $id current message id (for cid2http)
1839 * @return a modified array of attributes to be set for <div>
1841 function sq_body2div($attary, $mailbox, $message, $id){
1842 $me = 'sq_body2div';
1843 $divattary = Array('class' => "'bodyclass'");
1845 $has_bgc_stl = $has_txt_stl = false;
1847 if (is_array($attary) && sizeof($attary) > 0){
1848 foreach ($attary as $attname=>$attvalue){
1849 $quotchar = substr($attvalue, 0, 1);
1850 $attvalue = str_replace($quotchar, "", $attvalue);
1853 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1854 $styledef .= "background-image: url('$attvalue'); ";
1857 $has_bgc_stl = true;
1858 $styledef .= "background-color: $attvalue; ";
1861 $has_txt_stl = true;
1862 $styledef .= "color: $attvalue; ";
1866 // Outlook defines a white bgcolor and no text color. This can lead to
1867 // white text on a white bg with certain themes.
1868 if ($has_bgc_stl && !$has_txt_stl) {
1869 $styledef .= "color: $text; ";
1871 if (strlen($styledef) > 0){
1872 $divattary{"style"} = "\"$styledef\"";
1879 * This is the main function and the one you should actually be calling.
1880 * There are several variables you should be aware of an which need
1881 * special description.
1883 * Since the description is quite lengthy, see it here:
1884 * http://linux.duke.edu/projects/mini/htmlfilter/
1886 * @param $body the string with HTML you wish to filter
1887 * @param $tag_list see description above
1888 * @param $rm_tags_with_content see description above
1889 * @param $self_closing_tags see description above
1890 * @param $force_tag_closing see description above
1891 * @param $rm_attnames see description above
1892 * @param $bad_attvals see description above
1893 * @param $add_attr_to_tag see description above
1894 * @param $message message object
1895 * @param $id message id
1896 * @return sanitized html safe to show on your pages.
1898 function sq_sanitize($body,
1900 $rm_tags_with_content,
1910 $me = 'sq_sanitize';
1911 $rm_tags = array_shift($tag_list);
1913 * Normalize rm_tags and rm_tags_with_content.
1915 @array_walk
($tag_list, 'sq_casenormalize');
1916 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1917 @array_walk
($self_closing_tags, 'sq_casenormalize');
1919 * See if tag_list is of tags to remove or tags to allow.
1920 * false means remove these tags
1921 * true means allow these tags
1924 $open_tags = Array();
1925 $trusted = "\n<!-- begin sanitized html -->\n";
1926 $skip_content = false;
1928 * Take care of netscape's stupid javascript entities like
1931 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1933 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1934 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1935 $free_content = substr($body, $curpos, $lt-$curpos);
1937 * Take care of <style>
1939 if ($tagname == "style" && $tagtype == 1){
1940 list($free_content, $curpos) =
1941 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
1942 if ($free_content != FALSE){
1943 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1944 $trusted .= $free_content;
1945 $trusted .= sq_tagprint($tagname, false, 2);
1949 if ($skip_content == false){
1950 $trusted .= $free_content;
1952 if ($tagname != FALSE){
1954 if ($skip_content == $tagname){
1956 * Got to the end of tag we needed to remove.
1959 $skip_content = false;
1961 if ($skip_content == false){
1962 if ($tagname == "body"){
1965 if (isset($open_tags{$tagname}) &&
1966 $open_tags{$tagname} > 0){
1967 $open_tags{$tagname}--;
1975 * $rm_tags_with_content
1977 if ($skip_content == false){
1979 * See if this is a self-closing type and change
1980 * tagtype appropriately.
1983 && in_array($tagname, $self_closing_tags)){
1987 * See if we should skip this tag and any content
1990 if ($tagtype == 1 &&
1991 in_array($tagname, $rm_tags_with_content)){
1992 $skip_content = $tagname;
1994 if (($rm_tags == false
1995 && in_array($tagname, $tag_list)) ||
1996 ($rm_tags == true &&
1997 !in_array($tagname, $tag_list))){
2001 * Convert body into div.
2003 if ($tagname == "body"){
2005 $attary = sq_body2div($attary, $mailbox,
2009 if (isset($open_tags{$tagname})){
2010 $open_tags{$tagname}++
;
2012 $open_tags{$tagname}=1;
2016 * This is where we run other checks.
2018 if (is_array($attary) && sizeof($attary) > 0){
2019 $attary = sq_fixatts($tagname,
2033 if ($tagname != false && $skip_content == false){
2034 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2039 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
2040 if ($force_tag_closing == true){
2041 foreach ($open_tags as $tagname=>$opentimes){
2042 while ($opentimes > 0){
2043 $trusted .= '</' . $tagname . '>';
2049 $trusted .= "<!-- end sanitized html -->\n";
2054 * This is a wrapper function to call html sanitizing routines.
2056 * @param $body the body of the message
2057 * @param $id the id of the message
2061 * @param boolean $take_mailto_links When TRUE, converts mailto: links
2062 * into internal SM compose links
2063 * (optional; default = TRUE)
2064 * @return a string with html safe to display in the browser.
2066 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
2068 require_once(SM_PATH
. 'functions/url_parser.php'); // for $MailTo_PReg_Match
2070 global $attachment_common_show_images, $view_unsafe_images,
2073 * Don't display attached images in HTML mode.
2075 $attachment_common_show_images = false;
2090 $rm_tags_with_content = Array(
2100 $self_closing_tags = Array(
2108 $force_tag_closing = true;
2110 $rm_attnames = Array(
2121 $secremoveimg = "../images/" . _("sec_remove_eng.png");
2122 $bad_attvals = Array(
2125 "/^src|background/i" =>
2128 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2129 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2130 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2133 "\\1$secremoveimg\\2",
2134 "\\1$secremoveimg\\2",
2135 "\\1$secremoveimg\\2",
2138 "/^href|action/i" =>
2141 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2142 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2143 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2158 "/include-source/i",
2159 "/position\s*:\s*absolute/i",
2160 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2161 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2162 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2163 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2180 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2181 $view_unsafe_images = false;
2183 if (!$view_unsafe_images){
2185 * Remove any references to http/https if view_unsafe_images set
2188 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2189 '/^([\'\"])\s*https*:.*([\'\"])/si');
2190 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2191 "\\1$secremoveimg\\1");
2192 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2193 '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
2194 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2195 "url(\\1$secremoveimg\\1)");
2198 $add_attr_to_tag = Array(
2200 Array('target'=>'"_blank"',
2201 'title'=>'"'._("This external link will open in a new window").'"'
2204 $trusted = sq_sanitize($body,
2206 $rm_tags_with_content,
2216 if (preg_match("|$secremoveimg|i", $trusted)){
2217 $has_unsafe_images = true;
2220 // we want to parse mailto's in HTML output, change to SM compose links
2221 // this is a modified version of code from url_parser.php... but Marc is
2222 // right: we need a better filtering implementation; adding this randomly
2223 // here is not a great solution
2225 if ($take_mailto_links) {
2226 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2227 global $MailTo_PReg_Match;
2228 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1);
2229 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2230 foreach ($regs[0] as $i => $mailto_before) {
2231 $mailto_params = $regs[10][$i];
2232 // get rid of any tailing quote since we have to add send_to to the end
2234 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2235 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2236 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2237 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2239 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2240 $to = 'to=' . $regs[1][$i];
2241 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2242 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2244 if ($mailto_params) //already some params, append to them
2245 $mailto_params .= '&' . $to;
2247 $mailto_params .= '?' . $to;
2251 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2253 // we'll already have target=_blank, no need to allow comp_in_new
2254 // here (which would be a lot more work anyway)
2256 global $compose_new_win;
2257 $temp_comp_in_new = $compose_new_win;
2258 $compose_new_win = 0;
2259 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2260 $compose_new_win = $temp_comp_in_new;
2262 // remove <a href=" and anything after the next quote (we only
2263 // need the uri, not the link HTML) in compose uri
2265 $comp_uri = substr($comp_uri, 9);
2266 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2267 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2276 * function SendDownloadHeaders - send file to the browser
2278 * Original Source: SM core src/download.php
2279 * moved here to make it available to other code, and separate
2280 * front end from back end functionality.
2282 * @param string $type0 first half of mime type
2283 * @param string $type1 second half of mime type
2284 * @param string $filename filename to tell the browser for downloaded file
2285 * @param boolean $force whether to force the download dialog to pop
2286 * @param optional integer $filesize send the Content-Header and length to the browser
2289 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2290 global $languages, $squirrelmail_language;
2291 $isIE = $isIE6plus = false;
2293 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2295 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2296 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2300 if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
2301 ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
2305 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2306 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2308 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2310 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2313 // A Pox on Microsoft and it's Internet Explorer!
2315 // IE has lots of bugs with file downloads.
2316 // It also has problems with SSL. Both of these cause problems
2317 // for us in this function.
2319 // See this article on Cache Control headers and SSL
2320 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2322 // The best thing you can do for IE is to upgrade to the latest
2324 //set all the Cache Control Headers for IE
2326 $filename=rawurlencode($filename);
2327 header ("Pragma: public");
2328 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2329 header ("Cache-Control: post-check=0, pre-check=0", false);
2330 header ("Cache-Control: private");
2332 //set the inline header for IE, we'll add the attachment header later if we need it
2333 header ("Content-Disposition: inline; filename=$filename");
2337 // Try to show in browser window
2338 header ("Content-Disposition: inline; filename=\"$filename\"");
2339 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2341 // Try to pop up the "save as" box
2343 // IE makes this hard. It pops up 2 save boxes, or none.
2344 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2345 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2346 // But, according to Microsoft, it is "RFC compliant but doesn't
2347 // take into account some deviations that allowed within the
2348 // specification." Doesn't that mean RFC non-compliant?
2349 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2351 // all browsers need the application/octet-stream header for this
2352 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2354 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2355 // Do not have quotes around filename, but that applied to
2356 // "attachment"... does it apply to inline too?
2357 header ("Content-Disposition: attachment; filename=\"$filename\"");
2359 if ($isIE && !$isIE6plus) {
2360 // This combination seems to work mostly. IE 5.5 SP 1 has
2361 // known issues (see the Microsoft Knowledge Base)
2363 // This works for most types, but doesn't work with Word files
2364 header ("Content-Type: application/download; name=\"$filename\"");
2366 // These are spares, just in case. :-)
2367 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2368 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2369 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2371 // another application/octet-stream forces download for Netscape
2372 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2376 //send the content-length header if the calling function provides it
2377 if ($filesize > 0) {
2378 header("Content-Length: $filesize");
2381 } // end fn SendDownloadHeaders