6 * Copyright (c) 1999-2003 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
15 require_once(SM_PATH
. 'functions/imap.php');
16 require_once(SM_PATH
. 'functions/attachment_common.php');
18 /* -------------------------------------------------------------------------- */
20 /* -------------------------------------------------------------------------- */
22 /* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
27 function mime_structure ($bodystructure, $flags=array()) {
29 /* Isolate the body structure and remove beginning and end parenthesis. */
30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
31 $read = trim(substr ($read, 0, -1));
33 $msg = Message
::parseStructure($read,$i);
34 if (!is_object($msg)) {
35 include_once(SM_PATH
. 'functions/display_messages.php');
36 global $color, $mailbox;
37 /* removed urldecode because $_GET is auto urldecoded ??? */
38 displayPageHeader( $color, $mailbox );
39 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
40 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
41 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
42 plain_error_message( $errormessage, $color );
43 echo '</body></html>';
47 foreach ($flags as $flag) {
48 $char = strtoupper($flag{1});
51 if (strtolower($flag) == '\\seen') {
56 if (strtolower($flag) == '\\answered') {
57 $msg->is_answered
= true;
61 if (strtolower($flag) == '\\deleted') {
62 $msg->is_deleted
= true;
66 if (strtolower($flag) == '\\flagged') {
67 $msg->is_flagged
= true;
71 if (strtolower($flag) == '$mdnsent') {
72 $msg->is_mdnsent
= true;
80 // listEntities($msg);
86 /* This starts the parsing of a particular structure. It is called recursively,
87 * so it can be passed different structures. It returns an object of type
89 * First, it checks to see if it is a multipart message. If it is, then it
90 * handles that as it sees is necessary. If it is just a regular entity,
91 * then it parses it and adds the necessary header information (by calling out
92 * to mime_get_elements()
95 function mime_fetch_body($imap_stream, $id, $ent_id=1) {
97 /* Do a bit of error correction. If we couldn't find the entity id, just guess
98 * that it is the first one. That is usually the case anyway.
102 $cmd = "FETCH $id BODY[]";
104 $cmd = "FETCH $id BODY[$ent_id]";
107 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
109 $topline = trim(array_shift($data));
110 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
112 $wholemessage = implode('', $data);
113 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
114 $ret = substr($wholemessage, 0, $regs[1]);
115 /* There is some information in the content info header that could be important
116 * in order to parse html messages. Let's get them here.
118 // if ($ret{0} == '<') {
119 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
121 } else if (ereg('"([^"]*)"', $topline, $regs)) {
124 global $where, $what, $mailbox, $passed_id, $startMessage;
125 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
126 if (isset($where) && isset($what)) {
127 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
129 $par .= '&startMessage=' . $startMessage . '&show_more=0';
131 $par .= '&response=' . urlencode($response) .
132 '&message=' . urlencode($message) .
133 '&topline=' . urlencode($topline);
136 '<table width="80%"><tr>' .
137 '<tr><td colspan=2>' .
138 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
140 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
141 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
142 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
143 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
144 "</table><BR></tt></font><hr>";
146 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
148 $wholemessage = implode('', $data);
150 $ret = $wholemessage;
155 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
158 /* Don't kill the connection if the browser is over a dialup
159 * and it would take over 30 seconds to download it.
160 * DonĀ“t call set_time_limit in safe mode.
163 if (!ini_get('safe_mode')) {
166 /* in case of base64 encoded attachments, do not buffer them.
167 Instead, echo the decoded attachment directly to screen */
168 if (strtolower($encoding) == 'base64') {
170 $query = "FETCH $id BODY[]";
172 $query = "FETCH $id BODY[$ent_id]";
174 sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
176 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
177 echo decodeBody($body, $encoding);
181 TODO, use the same method for quoted printable.
182 However, I assume that quoted printable attachments aren't that large
183 so the performancegain / memory usage drop will be minimal.
184 If we decide to add that then we need to adapt sqimap_fread because
185 we need to split te result on \n and fread doesn't stop at \n. That
186 means we also should provide $results from sqimap_fread (by ref) to
187 te function and set $no_return to false. The $filter function for
188 quoted printable should handle unsetting of $results.
191 TODO 2: find out how we write to the output stream php://stdout. fwrite
192 doesn't work because 'php://stdout isn't a stream.
197 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
200 $read = fgets ($imap_stream,8192);
203 // This could be bad -- if the section has sqimap_session_id() . ' OK'
204 // or similar, it will kill the download.
205 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
206 if (trim($read) == ')==') {
208 $read = fgets ($imap_stream,4096);
209 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
212 echo decodeBody($read1, $encoding) .
213 decodeBody($read, $encoding);
216 echo decodeBody($read, $encoding);
218 $read = fgets ($imap_stream,4096);
225 /* -[ END MIME DECODING ]----------------------------------------------------------- */
227 /* This is here for debugging purposes. It will print out a list
228 * of all the entity IDs that are in the $message object.
230 function listEntities ($message) {
232 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
233 for ($i = 0; isset($message->entities
[$i]); $i++
) {
235 $msg = listEntities($message->entities
[$i]);
245 function getPriorityStr($priority) {
246 $priority_level = substr($priority,0,1);
248 switch($priority_level) {
249 /* Check for a higher then normal priority. */
252 $priority_string = _("High");
255 /* Check for a lower then normal priority. */
258 $priority_string = _("Low");
261 /* Check for a normal priority. */
264 $priority_level = '3';
265 $priority_string = _("Normal");
269 return $priority_string;
272 /* returns a $message object for a particular entity id */
273 function getEntity ($message, $ent_id) {
274 return $message->getEntity($ent_id);
278 * Extracted from strings.php 23/03/2002
281 function translateText(&$body, $wrap_at, $charset) {
282 global $where, $what; /* from searching */
283 global $color; /* color theme */
285 require_once(SM_PATH
. 'functions/url_parser.php');
287 $body_ary = explode("\n", $body);
288 for ($i=0; $i < count($body_ary); $i++
) {
289 $line = $body_ary[$i];
290 if (strlen($line) - 2 >= $wrap_at) {
291 sqWordWrap($line, $wrap_at);
293 $line = charset_decode($charset, $line);
294 $line = str_replace("\t", ' ', $line);
303 if ($line[$pos] == ' ') {
305 } else if (strpos($line, '>', $pos) === $pos) {
314 if (!isset($color[13])) {
315 $color[13] = '#800000';
317 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
319 if (!isset($color[14])) {
320 $color[14] = '#FF0000';
322 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
325 $body_ary[$i] = $line;
327 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
330 /* This returns a parsed string called $body. That string can then
331 * be displayed as the actual message in the HTML. It contains
332 * everything needed, including HTML Tags, Attachments at the
335 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
336 /* This if statement checks for the entity to show as the
337 * primary message. To add more of them, just put them in the
338 * order that is their priority.
340 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
341 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
342 global $languages, $squirrelmail_language;
344 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
345 $view_unsafe_images = false;
349 $urlmailbox = urlencode($mailbox);
350 $body_message = getEntity($message, $ent_num);
351 if (($body_message->header
->type0
== 'text') ||
352 ($body_message->header
->type0
== 'rfc822')) {
353 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
354 $body = decodeBody($body, $body_message->header
->encoding
);
356 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
357 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
358 if (mb_detect_encoding($body) != 'ASCII') {
359 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
362 $hookResults = do_hook("message_body", $body);
363 $body = $hookResults[1];
365 /* If there are other types that shouldn't be formatted, add
369 if ($body_message->header
->type1
== 'html') {
370 if ($show_html_default <> 1) {
371 $entity_conv = array(' ' => ' ',
378 $body = strtr($body, $entity_conv);
379 $body = strip_tags($body);
381 translateText($body, $wrap_at,
382 $body_message->header
->getParameter('charset'));
384 $body = magicHTML($body, $id, $message, $mailbox);
387 translateText($body, $wrap_at,
388 $body_message->header
->getParameter('charset'));
390 $link = 'read_body.php?passed_id=' . $id . '&ent_id='.$ent_num.
391 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
392 '&startMessage=' . $startMessage . '&show_more=0';
393 if (isset($passed_ent_id)) {
394 $link .= '&passed_ent_id='.$passed_ent_id;
396 if ($view_unsafe_images) {
397 $text = _("Hide Unsafe Images");
399 if (isset($has_unsafe_images) && $has_unsafe_images) {
400 $link .= '&view_unsafe_images=1';
401 $text = _("View Unsafe Images");
406 $body .= '<center><small><a href="'.$link.'">'.$text.
407 '</a></small></center><br>' . "\n";
413 function formatAttachments($message, $exclude_id, $mailbox, $id) {
414 global $where, $what, $startMessage, $color;
415 static $ShownHTML = 0;
417 $att_ar = $message->getAttachments($exclude_id);
419 if (!count($att_ar)) return '';
423 $urlMailbox = urlencode($mailbox);
425 foreach ($att_ar as $att) {
426 $ent = $att->entity_id
;
427 $header = $att->header
;
428 $type0 = strtolower($header->type0
);
429 $type1 = strtolower($header->type1
);
431 $links['download link']['text'] = _("download");
432 $links['download link']['href'] = SM_PATH
.
433 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
435 if ($type0 =='message' && $type1 == 'rfc822') {
436 $default_page = SM_PATH
. 'src/read_body.php';
437 $rfc822_header = $att->rfc822_header
;
438 $filename = $rfc822_header->subject
;
439 if (trim( $filename ) == '') {
440 $filename = 'untitled-[' . $ent . ']' ;
442 $from_o = $rfc822_header->from
;
443 if (is_object($from_o)) {
444 $from_name = decodeHeader($from_o->getAddress(false));
446 $from_name = _("Unknown sender");
448 $description = $from_name;
450 $default_page = SM_PATH
. 'src/download.php';
451 if (is_object($header->disposition
)) {
452 $filename = $header->disposition
->getProperty('filename');
453 if (trim($filename) == '') {
454 $name = decodeHeader($header->disposition
->getProperty('name'));
455 if (trim($name) == '') {
456 $name = $header->getParameter('name');
457 if(trim($name) == '') {
458 if (trim( $header->id
) == '') {
459 $filename = 'untitled-[' . $ent . ']' ;
461 $filename = 'cid: ' . $header->id
;
471 $filename = $header->getParameter('name');
472 if (!trim($filename)) {
473 if (trim( $header->id
) == '') {
474 $filename = 'untitled-[' . $ent . ']' ;
476 $filename = 'cid: ' . $header->id
;
480 if ($header->description
) {
481 $description = decodeHeader($header->description
);
487 $display_filename = $filename;
488 if (isset($passed_ent_id)) {
489 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
491 $passed_ent_id_link = '';
493 $defaultlink = $default_page . "?startMessage=$startMessage"
494 . "&passed_id=$id&mailbox=$urlMailbox"
495 . '&ent_id='.$ent.$passed_ent_id_link;
496 if ($where && $what) {
497 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
499 /* This executes the attachment hook with a specific MIME-type.
500 * If that doesn't have results, it tries if there's a rule
501 * for a more generic type.
503 $hookresults = do_hook("attachment $type0/$type1", $links,
504 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
505 $display_filename, $where, $what);
506 if(count($hookresults[1]) <= 1) {
507 $hookresults = do_hook("attachment $type0/*", $links,
508 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
509 $display_filename, $where, $what);
512 $links = $hookresults[1];
513 $defaultlink = $hookresults[6];
515 $attachments .= '<TR><TD>' .
516 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A> </TD>' .
517 '<TD><SMALL><b>' . show_readable_size($header->size
) .
518 '</b> </small></TD>' .
519 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
521 $attachments .= '<b>' . $description . '</b>';
522 $attachments .= '</SMALL></TD><TD><SMALL> ';
525 foreach ($links as $val) {
529 $attachments .= ' | ';
531 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
534 $attachments .= "</TD></TR>\n";
536 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
537 if ($attachmentadd != '')
538 $attachments = $attachmentadd;
542 function sqimap_base64_decode(&$string) {
543 $string = str_replace("\r\n", "\n", $string);
544 $string = base64_decode($string);
547 /* This function decodes the body depending on the encoding type. */
548 function decodeBody($body, $encoding) {
549 global $show_html_default;
551 $body = str_replace("\r\n", "\n", $body);
552 $encoding = strtolower($encoding);
554 $encoding_handler = do_hook_function('decode_body', $encoding);
557 // plugins get first shot at decoding the body
559 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
560 $body = $encoding_handler('decode', $body);
562 } else if ($encoding == 'quoted-printable' ||
563 $encoding == 'quoted_printable') {
564 $body = quoted_printable_decode($body);
566 while (ereg("=\n", $body)) {
567 $body = ereg_replace ("=\n", '', $body);
570 } else if ($encoding == 'base64') {
571 $body = base64_decode($body);
574 // All other encodings are returned raw.
579 * This functions decode strings that is encoded according to
580 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
581 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
583 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
584 global $languages, $squirrelmail_language;
585 if (is_array($string)) {
586 $string = implode("\n", $string);
589 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
590 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
591 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
592 // Do we need to return at this point?
599 $aString = explode(' ',$string);
601 foreach ($aString as $chunk) {
602 if ($encoded && $chunk === '') {
604 } elseif ($chunk === '') {
609 /* if encoded words are not separated by a linear-space-white we still catch them */
611 // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
612 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
613 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
614 if ($iLastMatch !== $j) {
624 $encoding = ucfirst($res[3]);
628 $replace = base64_decode($res[4]);
629 $ret .= charset_decode($res[2],$replace);
632 $replace = str_replace('_', ' ', $res[4]);
633 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
635 /* Only encode into entities by default. Some places
636 * don't need the encoding, like the compose form.
639 $replace = charset_decode($res[2], $replace);
642 $replace = htmlspecialchars($replace);
662 if (!$encoded && $htmlsave) {
663 $ret .= htmlspecialchars($chunk);
669 /* remove the first added space */
672 $ret = substr($ret,6);
674 $ret = substr($ret,1);
682 * Encode a string according to RFC 1522 for use in headers if it
683 * contains 8-bit characters or anything that looks like it should
686 function encodeHeader ($string) {
687 global $default_charset, $languages, $squirrelmail_language;
689 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
690 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
691 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
693 if (strtolower($default_charset) == 'iso-8859-1') {
694 $string = str_replace("\240",' ',$string);
697 // Encode only if the string contains 8-bit characters or =?
698 $j = strlen($string);
699 $max_l = 75 - strlen($default_charset) - 7;
702 $iEncStart = $enc_init = false;
703 $cur_l = $iOffset = 0;
704 for($i = 0; $i < $j; ++
$i) {
713 if ($iEncStart === false) {
717 if ($cur_l > ($max_l-2)) {
718 /* if there is an stringpart that doesn't need encoding, add it */
719 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
720 $aRet[] = "=?$default_charset?Q?$ret?=";
726 $ret .= sprintf("=%02X",ord($string{$i}));
731 if ($iEncStart !== false) {
732 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
733 $aRet[] = "=?$default_charset?Q?$ret?=";
741 if ($iEncStart !== false) {
743 if ($cur_l > $max_l) {
744 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
745 $aRet[] = "=?$default_charset?Q?$ret?=";
756 $k = ord($string{$i});
758 if ($iEncStart === false) {
759 // do not start encoding in the middle of a string, also take the rest of the word.
760 $sLeadString = substr($string,0,$i);
761 $aLeadString = explode(' ',$sLeadString);
762 $sToBeEncoded = array_pop($aLeadString);
763 $iEncStart = $i - strlen($sToBeEncoded);
764 $ret .= $sToBeEncoded;
765 $cur_l +
= strlen($sToBeEncoded);
768 /* first we add the encoded string that reached it's max size */
769 if ($cur_l > ($max_l-2)) {
770 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
771 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
778 $ret .= sprintf("=%02X", $k);
780 if ($iEncStart !== false) {
782 if ($cur_l > $max_l) {
783 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
784 $aRet[] = "=?$default_charset?Q?$ret?=";
799 if ($iEncStart !== false) {
800 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
801 $aRet[] = "=?$default_charset?Q?$ret?=";
803 $aRet[] = substr($string,$iOffset);
805 $string = implode('',$aRet);
810 /* This function trys to locate the entity_id of a specific mime element */
811 function find_ent_id($id, $message) {
812 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
813 if ($message->entities
[$i]->header
->type0
== 'multipart') {
814 $ret = find_ent_id($id, $message->entities
[$i]);
816 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
817 // if (sq_check_save_extension($message->entities[$i])) {
818 return $message->entities
[$i]->entity_id
;
826 function sq_check_save_extension($message) {
827 $filename = $message->getFilename();
828 $ext = substr($filename, strrpos($filename,'.')+
1);
829 $save_extensions = array('jpg','jpeg','gif','png','bmp');
830 return in_array($ext, $save_extensions);
835 ** HTMLFILTER ROUTINES
839 * This function is more or less a wrapper around stripslashes. Apparently
840 * Explorer is stupid enough to just remove the backslashes and then
841 * execute the content of the attribute as if nothing happened.
844 * @param attvalue The value of the attribute
845 * @return attvalue The value of the attribute stripslashed.
847 function sq_unbackslash($attvalue){
849 * Remove any backslashes. See if there are any first.
851 if (strstr($attvalue, '\\') !== false){
852 $attvalue = stripslashes($attvalue);
858 * Kill any tabs, newlines, or carriage returns. Our friends the
859 * makers of the browser with 95% market value decided that it'd
860 * be funny to make "java[tab]script" be just as good as "javascript".
862 * @param attvalue The attribute value before extraneous spaces removed.
863 * @return attvalue The attribute value after extraneous spaces removed.
865 function sq_unspace($attvalue){
866 if (strcspn($attvalue, "\t\r\n") != strlen($attvalue)){
867 $attvalue = str_replace(Array("\t", "\r", "\n"), Array('', '', ''),
874 * This function returns the final tag out of the tag name, an array
875 * of attributes, and the type of the tag. This function is called by
876 * sq_sanitize internally.
878 * @param $tagname the name of the tag.
879 * @param $attary the array of attributes and their values
880 * @param $tagtype The type of the tag (see in comments).
881 * @return a string with the final tag representation.
883 function sq_tagprint($tagname, $attary, $tagtype){
887 $fulltag = '</' . $tagname . '>';
889 $fulltag = '<' . $tagname;
890 if (is_array($attary) && sizeof($attary)){
892 while (list($attname, $attvalue) = each($attary)){
893 array_push($atts, "$attname=$attvalue");
895 $fulltag .= ' ' . join(" ", $atts);
906 * A small helper function to use with array_walk. Modifies a by-ref
907 * value and makes it lowercase.
909 * @param $val a value passed by-ref.
910 * @return void since it modifies a by-ref value.
912 function sq_casenormalize(&$val){
913 $val = strtolower($val);
917 * This function skips any whitespace from the current position within
918 * a string and to the next non-whitespace value.
920 * @param $body the string
921 * @param $offset the offset within the string where we should start
922 * looking for the next non-whitespace character.
923 * @return the location within the $body where the next
924 * non-whitespace char is located.
926 function sq_skipspace($body, $offset){
927 $me = 'sq_skipspace';
928 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
929 if (sizeof($matches{1})){
930 $count = strlen($matches{1});
937 * This function looks for the next character within a string. It's
938 * really just a glorified "strpos", except it catches if failures
941 * @param $body The string to look for needle in.
942 * @param $offset Start looking from this position.
943 * @param $needle The character/string to look for.
944 * @return location of the next occurance of the needle, or
945 * strlen($body) if needle wasn't found.
947 function sq_findnxstr($body, $offset, $needle){
948 $me = 'sq_findnxstr';
949 $pos = strpos($body, $needle, $offset);
951 $pos = strlen($body);
957 * This function takes a PCRE-style regexp and tries to match it
960 * @param $body The string to look for needle in.
961 * @param $offset Start looking from here.
962 * @param $reg A PCRE-style regex to match.
963 * @return Returns a false if no matches found, or an array
964 * with the following members:
965 * - integer with the location of the match within $body
966 * - string with whatever content between offset and the match
967 * - string with whatever it is we matched
969 function sq_findnxreg($body, $offset, $reg){
970 $me = 'sq_findnxreg';
973 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
974 if (!isset($matches{0}) ||
!$matches{0}){
977 $retarr{0} = $offset +
strlen($matches{1});
978 $retarr{1} = $matches{1};
979 $retarr{2} = $matches{2};
985 * This function looks for the next tag.
987 * @param $body String where to look for the next tag.
988 * @param $offset Start looking from here.
989 * @return false if no more tags exist in the body, or
990 * an array with the following members:
991 * - string with the name of the tag
992 * - array with attributes and their values
993 * - integer with tag type (1, 2, or 3)
994 * - integer where the tag starts (starting "<")
995 * - integer where the tag ends (ending ">")
996 * first three members will be false, if the tag is invalid.
998 function sq_getnxtag($body, $offset){
1000 if ($offset > strlen($body)){
1003 $lt = sq_findnxstr($body, $offset, "<");
1004 if ($lt == strlen($body)){
1009 * blah blah <tag attribute="value">
1012 $pos = sq_skipspace($body, $lt+
1);
1013 if ($pos >= strlen($body)){
1014 return Array(false, false, false, $lt, strlen($body));
1017 * There are 3 kinds of tags:
1018 * 1. Opening tag, e.g.:
1020 * 2. Closing tag, e.g.:
1022 * 3. XHTML-style content-less tag, e.g.:
1026 switch (substr($body, $pos, 1)){
1033 * A comment or an SGML declaration.
1035 if (substr($body, $pos+
1, 2) == "--"){
1036 $gt = strpos($body, "-->", $pos);
1038 $gt = strlen($body);
1042 return Array(false, false, false, $lt, $gt);
1044 $gt = sq_findnxstr($body, $pos, ">");
1045 return Array(false, false, false, $lt, $gt);
1050 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1060 * Look for next [\W-_], which will indicate the end of the tag name.
1062 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1063 if ($regary == false){
1064 return Array(false, false, false, $lt, strlen($body));
1066 list($pos, $tagname, $match) = $regary;
1067 $tagname = strtolower($tagname);
1070 * $match can be either of these:
1071 * '>' indicating the end of the tag entirely.
1072 * '\s' indicating the end of the tag name.
1073 * '/' indicating that this is type-3 xhtml tag.
1075 * Whatever else we find there indicates an invalid tag.
1080 * This is an xhtml-style tag with a closing / at the
1081 * end, like so: <img src="blah"/>. Check if it's followed
1082 * by the closing bracket. If not, then this tag is invalid
1084 if (substr($body, $pos, 2) == "/>"){
1088 $gt = sq_findnxstr($body, $pos, ">");
1089 $retary = Array(false, false, false, $lt, $gt);
1093 return Array($tagname, false, $tagtype, $lt, $pos);
1097 * Check if it's whitespace
1099 if (!preg_match('/\s/', $match)){
1101 * This is an invalid tag! Look for the next closing ">".
1103 $gt = sq_findnxstr($body, $lt, ">");
1104 return Array(false, false, false, $lt, $gt);
1110 * At this point we're here:
1111 * <tagname attribute='blah'>
1114 * At this point we loop in order to find all attributes.
1120 while ($pos <= strlen($body)){
1121 $pos = sq_skipspace($body, $pos);
1122 if ($pos == strlen($body)){
1126 return Array(false, false, false, $lt, $pos);
1129 * See if we arrived at a ">" or "/>", which means that we reached
1130 * the end of the tag.
1133 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1137 $pos +
= strlen($matches{1});
1138 if ($matches{2} == "/>"){
1142 return Array($tagname, $attary, $tagtype, $lt, $pos);
1146 * There are several types of attributes, with optional
1147 * [:space:] between members.
1149 * attrname[:space:]=[:space:]'CDATA'
1151 * attrname[:space:]=[:space:]"CDATA"
1153 * attr[:space:]=[:space:]CDATA
1157 * We leave types 1 and 2 the same, type 3 we check for
1158 * '"' and convert to """ if needed, then wrap in
1159 * double quotes. Type 4 we convert into:
1162 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1163 if ($regary == false){
1165 * Looks like body ended before the end of tag.
1167 return Array(false, false, false, $lt, strlen($body));
1169 list($pos, $attname, $match) = $regary;
1170 $attname = strtolower($attname);
1172 * We arrived at the end of attribute name. Several things possible
1174 * '>' means the end of the tag and this is attribute type 4
1175 * '/' if followed by '>' means the same thing as above
1176 * '\s' means a lot of things -- look what it's followed by.
1177 * anything else means the attribute is invalid.
1182 * This is an xhtml-style tag with a closing / at the
1183 * end, like so: <img src="blah"/>. Check if it's followed
1184 * by the closing bracket. If not, then this tag is invalid
1186 if (substr($body, $pos, 2) == "/>"){
1190 $gt = sq_findnxstr($body, $pos, ">");
1191 $retary = Array(false, false, false, $lt, $gt);
1195 $attary{$attname} = '"yes"';
1196 return Array($tagname, $attary, $tagtype, $lt, $pos);
1200 * Skip whitespace and see what we arrive at.
1202 $pos = sq_skipspace($body, $pos);
1203 $char = substr($body, $pos, 1);
1205 * Two things are valid here:
1206 * '=' means this is attribute type 1 2 or 3.
1207 * \w means this was attribute type 4.
1208 * anything else we ignore and re-loop. End of tag and
1209 * invalid stuff will be caught by our checks at the beginning
1214 $pos = sq_skipspace($body, $pos);
1216 * Here are 3 possibilities:
1217 * "'" attribute type 1
1218 * '"' attribute type 2
1219 * everything else is the content of tag type 3
1221 $quot = substr($body, $pos, 1);
1223 $regary = sq_findnxreg($body, $pos+
1, "\'");
1224 if ($regary == false){
1225 return Array(false, false, false, $lt, strlen($body));
1227 list($pos, $attval, $match) = $regary;
1229 $attary{$attname} = "'" . $attval . "'";
1230 } else if ($quot == '"'){
1231 $regary = sq_findnxreg($body, $pos+
1, '\"');
1232 if ($regary == false){
1233 return Array(false, false, false, $lt, strlen($body));
1235 list($pos, $attval, $match) = $regary;
1237 $attary{$attname} = '"' . $attval . '"';
1240 * These are hateful. Look for \s, or >.
1242 $regary = sq_findnxreg($body, $pos, "[\s>]");
1243 if ($regary == false){
1244 return Array(false, false, false, $lt, strlen($body));
1246 list($pos, $attval, $match) = $regary;
1248 * If it's ">" it will be caught at the top.
1250 $attval = preg_replace("/\"/s", """, $attval);
1251 $attary{$attname} = '"' . $attval . '"';
1253 } else if (preg_match("|[\w/>]|", $char)) {
1255 * That was attribute type 4.
1257 $attary{$attname} = '"yes"';
1260 * An illegal character. Find next '>' and return.
1262 $gt = sq_findnxstr($body, $pos, ">");
1263 return Array(false, false, false, $lt, $gt);
1269 * The fact that we got here indicates that the tag end was never
1270 * found. Return invalid tag indication so it gets stripped.
1272 return Array(false, false, false, $lt, strlen($body));
1276 * This function checks attribute values for entity-encoded values
1277 * and returns them translated into 8-bit strings so we can run
1280 * @param $attvalue A string to run entity check against.
1281 * @return Translated value.
1283 function sq_deent($attvalue){
1286 * See if we have to run the checks first. All entities must start
1289 if (strpos($attvalue, "&") === false){
1293 * Check named entities first.
1295 $trans = get_html_translation_table(HTML_ENTITIES
);
1297 * Leave " in, as it can mess us up.
1299 $trans = array_flip($trans);
1300 unset($trans{"""});
1301 while (list($ent, $val) = each($trans)){
1302 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1305 * Now translate numbered entities from 1 to 255 if needed.
1307 if (strpos($attvalue, "#") !== false){
1308 $omit = Array(34, 39);
1309 for ($asc=1; $asc<256; $asc++
){
1310 if (!in_array($asc, $omit)){
1312 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1314 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1315 "$chr\\1", $attvalue);
1323 * This function runs various checks against the attributes.
1325 * @param $tagname String with the name of the tag.
1326 * @param $attary Array with all tag attributes.
1327 * @param $rm_attnames See description for sq_sanitize
1328 * @param $bad_attvals See description for sq_sanitize
1329 * @param $add_attr_to_tag See description for sq_sanitize
1330 * @param $message message object
1331 * @param $id message id
1332 * @return Array with modified attributes.
1334 function sq_fixatts($tagname,
1344 while (list($attname, $attvalue) = each($attary)){
1346 * See if this attribute should be removed.
1348 foreach ($rm_attnames as $matchtag=>$matchattrs){
1349 if (preg_match($matchtag, $tagname)){
1350 foreach ($matchattrs as $matchattr){
1351 if (preg_match($matchattr, $attname)){
1352 unset($attary{$attname});
1359 * Remove any backslashes, entities, and extraneous whitespace.
1361 $attvalue = sq_unbackslash($attvalue);
1362 $attvalue = sq_deent($attvalue);
1363 $attvalue = sq_unspace($attvalue);
1366 * Now let's run checks on the attvalues.
1367 * I don't expect anyone to comprehend this. If you do,
1368 * get in touch with me so I can drive to where you live and
1369 * shake your hand personally. :)
1371 foreach ($bad_attvals as $matchtag=>$matchattrs){
1372 if (preg_match($matchtag, $tagname)){
1373 foreach ($matchattrs as $matchattr=>$valary){
1374 if (preg_match($matchattr, $attname)){
1376 * There are two arrays in valary.
1378 * Second one is replacements
1380 list($valmatch, $valrepl) = $valary;
1382 preg_replace($valmatch, $valrepl, $attvalue);
1383 if ($newvalue != $attvalue){
1384 $attary{$attname} = $newvalue;
1391 * Turn cid: urls into http-friendly ones.
1393 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1394 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1398 * See if we need to append any attributes to this tag.
1400 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1401 if (preg_match($matchtag, $tagname)){
1402 $attary = array_merge($attary, $addattary);
1409 * This function edits the style definition to make them friendly and
1410 * usable in squirrelmail.
1412 * @param $message the message object
1413 * @param $id the message id
1414 * @param $content a string with whatever is between <style> and </style>
1415 * @return a string with edited content.
1417 function sq_fixstyle($body, $pos, $message, $id){
1418 global $view_unsafe_images;
1419 $me = 'sq_fixstyle';
1420 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1422 return array(FALSE, strlen($body));
1424 $newpos = $ret[0] +
strlen($ret[2]);
1427 * First look for general BODY style declaration, which would be
1429 * body {background: blah-blah}
1430 * and change it to .bodyclass so we can just assign it to a <div>
1432 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1433 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1435 * Fix url('blah') declarations.
1437 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1438 "url(\\1$secremoveimg\\2)", $content);
1440 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1443 if (!$view_unsafe_images){
1444 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1445 "url(\\1$secremoveimg\\2)", $content);
1449 * Fix urls that refer to cid:
1451 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1452 $content, $matches)){
1453 $cidurl = $matches{1};
1454 $httpurl = sq_cid2http($message, $id, $cidurl);
1455 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1456 "url($httpurl)", $content);
1460 * Fix stupid css declarations which lead to vulnerabilities
1463 $match = Array('/expression/i',
1466 '/include-source/i');
1467 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
1468 $content = preg_replace($match, $replace, $content);
1469 return array($content, $newpos);
1473 * This function converts cid: url's into the ones that can be viewed in
1476 * @param $message the message object
1477 * @param $id the message id
1478 * @param $cidurl the cid: url.
1479 * @return a string with a http-friendly url
1481 function sq_cid2http($message, $id, $cidurl, $mailbox){
1483 * Get rid of quotes.
1485 $quotchar = substr($cidurl, 0, 1);
1486 if ($quotchar == '"' ||
$quotchar == "'"){
1487 $cidurl = str_replace($quotchar, "", $cidurl);
1491 $cidurl = substr(trim($cidurl), 4);
1492 $linkurl = find_ent_id($cidurl, $message);
1493 /* in case of non-save cid links $httpurl should be replaced by a sort of
1494 unsave link image */
1497 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1498 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1499 '&ent_id=' . $linkurl . $quotchar;
1505 * This function changes the <body> tag into a <div> tag since we
1506 * can't really have a body-within-body.
1508 * @param $attary an array of attributes and values of <body>
1509 * @param $mailbox mailbox we're currently reading (for cid2http)
1510 * @param $message current message (for cid2http)
1511 * @param $id current message id (for cid2http)
1512 * @return a modified array of attributes to be set for <div>
1514 function sq_body2div($attary, $mailbox, $message, $id){
1515 $me = 'sq_body2div';
1516 $divattary = Array('class' => "'bodyclass'");
1517 $bgcolor = '#ffffff';
1520 if (is_array($attary) && sizeof($attary) > 0){
1521 foreach ($attary as $attname=>$attvalue){
1522 $quotchar = substr($attvalue, 0, 1);
1523 $attvalue = str_replace($quotchar, "", $attvalue);
1526 $attvalue = sq_cid2http($message, $id,
1527 $attvalue, $mailbox);
1528 $styledef .= "background-image: url('$attvalue'); ";
1531 $styledef .= "background-color: $attvalue; ";
1534 $styledef .= "color: $attvalue; ";
1538 if (strlen($styledef) > 0){
1539 $divattary{"style"} = "\"$styledef\"";
1546 * This is the main function and the one you should actually be calling.
1547 * There are several variables you should be aware of an which need
1548 * special description.
1550 * Since the description is quite lengthy, see it here:
1551 * http://www.mricon.com/html/phpfilter.html
1553 * @param $body the string with HTML you wish to filter
1554 * @param $tag_list see description above
1555 * @param $rm_tags_with_content see description above
1556 * @param $self_closing_tags see description above
1557 * @param $force_tag_closing see description above
1558 * @param $rm_attnames see description above
1559 * @param $bad_attvals see description above
1560 * @param $add_attr_to_tag see description above
1561 * @param $message message object
1562 * @param $id message id
1563 * @return sanitized html safe to show on your pages.
1565 function sq_sanitize($body,
1567 $rm_tags_with_content,
1577 $me = 'sq_sanitize';
1578 $rm_tags = array_shift($tag_list);
1580 * Normalize rm_tags and rm_tags_with_content.
1582 @array_walk
($tag_list, 'sq_casenormalize');
1583 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1584 @array_walk
($self_closing_tags, 'sq_casenormalize');
1586 * See if tag_list is of tags to remove or tags to allow.
1587 * false means remove these tags
1588 * true means allow these tags
1591 $open_tags = Array();
1592 $trusted = "\n<!-- begin sanitized html -->\n";
1593 $skip_content = false;
1595 * Take care of netscape's stupid javascript entities like
1598 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1600 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1601 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1602 $free_content = substr($body, $curpos, $lt-$curpos);
1604 * Take care of <style>
1606 if ($tagname == "style" && $tagtype == 1){
1607 list($free_content, $curpos) =
1608 sq_fixstyle($body, $gt+
1, $message, $id);
1609 if ($free_content != FALSE){
1610 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1611 $trusted .= $free_content;
1612 $trusted .= sq_tagprint($tagname, false, 2);
1616 if ($skip_content == false){
1617 $trusted .= $free_content;
1619 if ($tagname != FALSE){
1621 if ($skip_content == $tagname){
1623 * Got to the end of tag we needed to remove.
1626 $skip_content = false;
1628 if ($skip_content == false){
1629 if ($tagname == "body"){
1632 if (isset($open_tags{$tagname}) &&
1633 $open_tags{$tagname} > 0){
1634 $open_tags{$tagname}--;
1642 * $rm_tags_with_content
1644 if ($skip_content == false){
1646 * See if this is a self-closing type and change
1647 * tagtype appropriately.
1650 && in_array($tagname, $self_closing_tags)){
1654 * See if we should skip this tag and any content
1657 if ($tagtype == 1 &&
1658 in_array($tagname, $rm_tags_with_content)){
1659 $skip_content = $tagname;
1661 if (($rm_tags == false
1662 && in_array($tagname, $tag_list)) ||
1663 ($rm_tags == true &&
1664 !in_array($tagname, $tag_list))){
1668 * Convert body into div.
1670 if ($tagname == "body"){
1672 $attary = sq_body2div($attary, $mailbox,
1676 if (isset($open_tags{$tagname})){
1677 $open_tags{$tagname}++
;
1679 $open_tags{$tagname}=1;
1683 * This is where we run other checks.
1685 if (is_array($attary) && sizeof($attary) > 0){
1686 $attary = sq_fixatts($tagname,
1700 if ($tagname != false && $skip_content == false){
1701 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1706 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1707 if ($force_tag_closing == true){
1708 foreach ($open_tags as $tagname=>$opentimes){
1709 while ($opentimes > 0){
1710 $trusted .= '</' . $tagname . '>';
1716 $trusted .= "<!-- end sanitized html -->\n";
1721 * This is a wrapper function to call html sanitizing routines.
1723 * @param $body the body of the message
1724 * @param $id the id of the message
1725 * @return a string with html safe to display in the browser.
1727 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1728 global $attachment_common_show_images, $view_unsafe_images,
1731 * Don't display attached images in HTML mode.
1733 $attachment_common_show_images = false;
1748 $rm_tags_with_content = Array(
1757 $self_closing_tags = Array(
1764 $force_tag_closing = true;
1766 $rm_attnames = Array(
1777 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1778 $bad_attvals = Array(
1781 "/^src|background/i" =>
1784 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1785 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1786 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1789 "\\1$secremoveimg\\2",
1790 "\\1$secremoveimg\\2",
1791 "\\1$secremoveimg\\2",
1792 "\\1$secremoveimg\\2"
1795 "/^href|action/i" =>
1798 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1799 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1800 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1815 "/include-source/i",
1816 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1817 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1818 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
1833 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1834 $view_unsafe_images = false;
1836 if (!$view_unsafe_images){
1838 * Remove any references to http/https if view_unsafe_images set
1841 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1842 '/^([\'\"])\s*https*:.*([\'\"])/si');
1843 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1844 "\\1$secremoveimg\\1");
1845 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1846 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1847 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1848 "url(\\1$secremoveimg\\1)");
1851 $add_attr_to_tag = Array(
1853 Array('target'=>'"_new"',
1854 'title'=>'"'._("This external link will open in a new window").'"'
1857 $trusted = sq_sanitize($body,
1859 $rm_tags_with_content,
1869 if (preg_match("|$secremoveimg|i", $trusted)){
1870 $has_unsafe_images = true;