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 displayPageHeader( $color, urldecode($mailbox) );
38 echo "<BODY TEXT=\"$color[8]\" BGCOLOR=\"$color[4]\" LINK=\"$color[7]\" VLINK=\"$color[7]\" ALINK=\"$color[7]\">\n\n" .
40 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
41 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
42 $errormessage .= '<table><tr><td>' . htmlspecialchars($read) . '</td></tr></table>';
43 plain_error_message( $errormessage, $color );
44 echo '</body></html>';
48 foreach ($flags as $flag) {
49 $char = strtoupper($flag{1});
52 if (strtolower($flag) == '\\seen') {
57 if (strtolower($flag) == '\\answered') {
58 $msg->is_answered
= true;
62 if (strtolower($flag) == '\\deleted') {
63 $msg->is_deleted
= true;
67 if (strtolower($flag) == '\\flagged') {
68 $msg->is_flagged
= true;
72 if (strtolower($flag) == '$mdnsent') {
73 $msg->is_mdnsent
= true;
81 // listEntities($msg);
87 /* This starts the parsing of a particular structure. It is called recursively,
88 * so it can be passed different structures. It returns an object of type
90 * First, it checks to see if it is a multipart message. If it is, then it
91 * handles that as it sees is necessary. If it is just a regular entity,
92 * then it parses it and adds the necessary header information (by calling out
93 * to mime_get_elements()
96 function mime_fetch_body($imap_stream, $id, $ent_id=1) {
98 /* Do a bit of error correction. If we couldn't find the entity id, just guess
99 * 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 $sid = sqimap_session_id($uid_support);
159 /* Don't kill the connection if the browser is over a dialup
160 * and it would take over 30 seconds to download it.
161 * DonĀ“t call set_time_limit in safe mode.
164 if (!ini_get('safe_mode')) {
168 $sid_s = substr($sid,0,strpos($sid, ' '));
173 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
174 echo decodeBody($body, $encoding);
177 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
180 $read = fgets ($imap_stream,8192);
183 // This could be bad -- if the section has sqimap_session_id() . ' OK'
184 // or similar, it will kill the download.
185 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
186 if (trim($read) == ')==') {
188 $read = fgets ($imap_stream,4096);
189 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
192 echo decodeBody($read1, $encoding) .
193 decodeBody($read, $encoding);
196 echo decodeBody($read, $encoding);
198 $read = fgets ($imap_stream,4096);
205 /* -[ END MIME DECODING ]----------------------------------------------------------- */
207 /* This is here for debugging purposes. It will print out a list
208 * of all the entity IDs that are in the $message object.
210 function listEntities ($message) {
212 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
213 for ($i = 0; isset($message->entities
[$i]); $i++
) {
215 $msg = listEntities($message->entities
[$i]);
225 function getPriorityStr($priority) {
226 $priority_level = substr($priority,0,1);
228 switch($priority_level) {
229 /* Check for a higher then normal priority. */
232 $priority_string = _("High");
235 /* Check for a lower then normal priority. */
238 $priority_string = _("Low");
241 /* Check for a normal priority. */
244 $priority_level = '3';
245 $priority_string = _("Normal");
249 return $priority_string;
252 /* returns a $message object for a particular entity id */
253 function getEntity ($message, $ent_id) {
254 return $message->getEntity($ent_id);
258 * Extracted from strings.php 23/03/2002
261 function translateText(&$body, $wrap_at, $charset) {
262 global $where, $what; /* from searching */
263 global $color; /* color theme */
265 require_once(SM_PATH
. 'functions/url_parser.php');
267 $body_ary = explode("\n", $body);
268 for ($i=0; $i < count($body_ary); $i++
) {
269 $line = $body_ary[$i];
270 if (strlen($line) - 2 >= $wrap_at) {
271 sqWordWrap($line, $wrap_at);
273 $line = charset_decode($charset, $line);
274 $line = str_replace("\t", ' ', $line);
283 if ($line[$pos] == ' ') {
285 } else if (strpos($line, '>', $pos) === $pos) {
294 if (!isset($color[13])) {
295 $color[13] = '#800000';
297 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
299 if (!isset($color[14])) {
300 $color[14] = '#FF0000';
302 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
305 $body_ary[$i] = $line;
307 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
310 /* This returns a parsed string called $body. That string can then
311 * be displayed as the actual message in the HTML. It contains
312 * everything needed, including HTML Tags, Attachments at the
315 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
316 /* This if statement checks for the entity to show as the
317 * primary message. To add more of them, just put them in the
318 * order that is their priority.
320 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
321 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
323 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
324 $view_unsafe_images = false;
328 $urlmailbox = urlencode($mailbox);
329 $body_message = getEntity($message, $ent_num);
330 if (($body_message->header
->type0
== 'text') ||
331 ($body_message->header
->type0
== 'rfc822')) {
332 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
333 $body = decodeBody($body, $body_message->header
->encoding
);
334 $hookResults = do_hook("message_body", $body);
335 $body = $hookResults[1];
337 /* If there are other types that shouldn't be formatted, add
341 if ($body_message->header
->type1
== 'html') {
342 if ($show_html_default <> 1) {
343 $entity_conv = array(' ' => ' ',
350 $body = strtr($body, $entity_conv);
351 $body = strip_tags($body);
353 translateText($body, $wrap_at,
354 $body_message->header
->getParameter('charset'));
356 $body = magicHTML($body, $id, $message, $mailbox);
359 translateText($body, $wrap_at,
360 $body_message->header
->getParameter('charset'));
362 $link = 'read_body.php?passed_id=' . $id . '&ent_id='.$ent_num.
363 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
364 '&startMessage=' . $startMessage . '&show_more=0';
365 if (isset($passed_ent_id)) {
366 $link .= '&passed_ent_id='.$passed_ent_id;
368 if ($view_unsafe_images) {
369 $text = _("Hide Unsafe Images");
371 if (isset($has_unsafe_images) && $has_unsafe_images) {
372 $link .= '&view_unsafe_images=1';
373 $text = _("View Unsafe Images");
378 $body .= '<center><small><a href="'.$link.'">'.$text.
379 '</a></small></center><br>' . "\n";
385 function formatAttachments($message, $exclude_id, $mailbox, $id) {
386 global $where, $what, $startMessage, $color;
387 static $ShownHTML = 0;
389 $att_ar = $message->getAttachments($exclude_id);
391 if (!count($att_ar)) return '';
395 $urlMailbox = urlencode($mailbox);
397 foreach ($att_ar as $att) {
398 $ent = urldecode($att->entity_id
);
399 $header = $att->header
;
400 $type0 = strtolower($header->type0
);
401 $type1 = strtolower($header->type1
);
403 $links['download link']['text'] = _("download");
404 $links['download link']['href'] =
405 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
407 if ($type0 =='message' && $type1 == 'rfc822') {
408 $default_page = '../src/read_body.php';
409 $rfc822_header = $att->rfc822_header
;
410 $filename = $rfc822_header->subject
;
411 if (trim( $filename ) == '') {
412 $filename = 'untitled-[' . $ent . ']' ;
414 $from_o = $rfc822_header->from
;
415 if (is_object($from_o)) {
416 $from_name = $from_o->getAddress(false);
418 $from_name = _("Unknown sender");
420 $from_name = decodeHeader(($from_name));
421 $description = $from_name;
423 $default_page = '../src/download.php';
424 if (is_object($header->disposition
)) {
425 $filename = $header->disposition
->getProperty('filename');
426 if (trim($filename) == '') {
427 $name = decodeHeader($header->disposition
->getProperty('name'));
428 if (trim($name) == '') {
429 $name = $header->getParameter('name');
430 if(trim($name) == '') {
431 if (trim( $header->id
) == '') {
432 $filename = 'untitled-[' . $ent . ']' ;
434 $filename = 'cid: ' . $header->id
;
444 $filename = $header->getParameter('name');
445 if (!trim($filename)) {
446 if (trim( $header->id
) == '') {
447 $filename = 'untitled-[' . $ent . ']' ;
449 $filename = 'cid: ' . $header->id
;
453 if ($header->description
) {
454 $description = decodeHeader($header->description
);
460 $display_filename = $filename;
461 if (isset($passed_ent_id)) {
462 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
464 $passed_ent_id_link = '';
466 $defaultlink = $default_page . "?startMessage=$startMessage"
467 . "&passed_id=$id&mailbox=$urlMailbox"
468 . '&ent_id='.$ent.$passed_ent_id_link.'&absolute_dl=true';
469 if ($where && $what) {
470 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
472 /* This executes the attachment hook with a specific MIME-type.
473 * If that doesn't have results, it tries if there's a rule
474 * for a more generic type.
476 $hookresults = do_hook("attachment $type0/$type1", $links,
477 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
478 $display_filename, $where, $what);
479 if(count($hookresults[1]) <= 1) {
480 $hookresults = do_hook("attachment $type0/*", $links,
481 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
482 $display_filename, $where, $what);
485 $links = $hookresults[1];
486 $defaultlink = $hookresults[6];
488 $attachments .= '<TR><TD>' .
489 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A> </TD>' .
490 '<TD><SMALL><b>' . show_readable_size($header->size
) .
491 '</b> </small></TD>' .
492 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
494 $attachments .= '<b>' . $description . '</b>';
495 $attachments .= '</SMALL></TD><TD><SMALL> ';
498 foreach ($links as $val) {
502 $attachments .= ' | ';
504 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
507 $attachments .= "</TD></TR>\n";
512 /* This function decodes the body depending on the encoding type. */
513 function decodeBody($body, $encoding) {
514 global $languages, $squirrelmail_language;
515 global $show_html_default;
517 $body = str_replace("\r\n", "\n", $body);
518 $encoding = strtolower($encoding);
520 if ($encoding == 'quoted-printable' ||
521 $encoding == 'quoted_printable') {
522 $body = quoted_printable_decode($body);
524 while (ereg("=\n", $body)) {
525 $body = ereg_replace ("=\n", '', $body);
528 } else if ($encoding == 'base64') {
529 $body = base64_decode($body);
532 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
533 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
534 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
537 // All other encodings are returned raw.
542 * This functions decode strings that is encoded according to
543 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
544 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
546 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
547 global $languages, $squirrelmail_language;
548 if (is_array($string)) {
549 $string = implode("\n", $string);
552 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
553 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
554 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
555 // Do we need to return at this point?
559 $aString = explode(' ',$string);
560 foreach ($aString as $chunk) {
563 while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
564 //$aString[$i] .= $res[1];
565 //echo "match ". $res[5] . "<br>";
566 $encoding = ucfirst($res[3]);
570 $replace = base64_decode($res[4]);
571 $aString[$i] .= charset_decode($res[2],$replace);
574 $replace = str_replace('_', ' ', $res[4]);
575 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
577 /* Only encode into entities by default. Some places
578 * don't need the encoding, like the compose form.
581 $replace = charset_decode($res[2], $replace);
584 $replace = htmlspecialchars($res[4]);
587 $aString[$i] .= $replace;
595 if (!$encoded && $htmlsave) {
596 $aString[$i] = htmlspecialchars($chunk);
598 $aString[$i] .= $chunk;
603 return implode(' ',$aString);
605 return implode (' ',$aString);
610 * Encode a string according to RFC 1522 for use in headers if it
611 * contains 8-bit characters or anything that looks like it should
614 function encodeHeader ($string) {
615 global $default_charset, $languages, $squirrelmail_language;
617 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
618 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
619 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
622 // Encode only if the string contains 8-bit characters or =?
623 $j = strlen($string);
624 $l = strstr($string, '=?'); // Must be encoded ?
625 $max_l = 75 - strlen($default_charset) - 7;
629 $cur_l = $iOffset = 0;
630 for($i = 0; $i < $j; ++
$i) {
631 switch($string{$i}) {
634 if ($cur_l > $max_l) {
636 $aRet[] = "=?$default_charset?Q?$ret?=";
639 $aRet[] = substr($string,$iOffset,$i-$iOffset+
1);
649 if ($cur_l > $max_l) {
651 $aRet[] = "=?$default_charset?Q?$ret?=";
654 $aRet[] = substr($string,$iOffset,$i-$iOffset+
1);
664 if ($cur_l > $max_l) {
666 $aRet[] = "=?$default_charset?Q?$ret?=";
669 $aRet[] = substr($string,$iOffset,$i-$iOffset+
1);
679 if ($cur_l > $max_l) {
681 $aRet[] = "=?$default_charset?Q?$ret?=";
684 $aRet[] = substr($string,$iOffset,$i-$iOffset+
1);
693 $k = ord($string{$i});
696 $s = sprintf("=%02X", $k);
697 $cur_l +
= strlen($s);
698 if ($cur_l > $max_l) {
699 $aRet[] = "=?$default_charset?Q?$ret?=";
710 if ($cur_l > $max_l) {
712 $aRet[] = "=?$default_charset?Q?$ret?=";
715 $aRet[] = substr($ret,$iOffset,$i-$iOffset+
1);
729 $string = implode('',$aRet) . "=?$default_charset?Q?$ret?=";
735 /* This function trys to locate the entity_id of a specific mime element */
736 function find_ent_id($id, $message) {
737 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
738 if ($message->entities
[$i]->header
->type0
== 'multipart') {
739 $ret = find_ent_id($id, $message->entities
[$i]);
741 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
742 // if (sq_check_save_extension($message->entities[$i])) {
743 return $message->entities
[$i]->entity_id
;
751 function sq_check_save_extension($message) {
752 $filename = $message->getFilename();
753 $ext = substr($filename, strrpos($filename,'.')+
1);
754 $save_extensions = array('jpg','jpeg','gif','png','bmp');
755 return in_array($ext, $save_extensions);
760 ** HTMLFILTER ROUTINES
764 * This function returns the final tag out of the tag name, an array
765 * of attributes, and the type of the tag. This function is called by
766 * sq_sanitize internally.
768 * @param $tagname the name of the tag.
769 * @param $attary the array of attributes and their values
770 * @param $tagtype The type of the tag (see in comments).
771 * @return a string with the final tag representation.
773 function sq_tagprint($tagname, $attary, $tagtype){
777 $fulltag = '</' . $tagname . '>';
779 $fulltag = '<' . $tagname;
780 if (is_array($attary) && sizeof($attary)){
782 while (list($attname, $attvalue) = each($attary)){
783 array_push($atts, "$attname=$attvalue");
785 $fulltag .= ' ' . join(" ", $atts);
796 * A small helper function to use with array_walk. Modifies a by-ref
797 * value and makes it lowercase.
799 * @param $val a value passed by-ref.
800 * @return void since it modifies a by-ref value.
802 function sq_casenormalize(&$val){
803 $val = strtolower($val);
807 * This function skips any whitespace from the current position within
808 * a string and to the next non-whitespace value.
810 * @param $body the string
811 * @param $offset the offset within the string where we should start
812 * looking for the next non-whitespace character.
813 * @return the location within the $body where the next
814 * non-whitespace char is located.
816 function sq_skipspace($body, $offset){
817 $me = 'sq_skipspace';
818 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
819 if (sizeof($matches{1})){
820 $count = strlen($matches{1});
827 * This function looks for the next character within a string. It's
828 * really just a glorified "strpos", except it catches if failures
831 * @param $body The string to look for needle in.
832 * @param $offset Start looking from this position.
833 * @param $needle The character/string to look for.
834 * @return location of the next occurance of the needle, or
835 * strlen($body) if needle wasn't found.
837 function sq_findnxstr($body, $offset, $needle){
838 $me = 'sq_findnxstr';
839 $pos = strpos($body, $needle, $offset);
841 $pos = strlen($body);
847 * This function takes a PCRE-style regexp and tries to match it
850 * @param $body The string to look for needle in.
851 * @param $offset Start looking from here.
852 * @param $reg A PCRE-style regex to match.
853 * @return Returns a false if no matches found, or an array
854 * with the following members:
855 * - integer with the location of the match within $body
856 * - string with whatever content between offset and the match
857 * - string with whatever it is we matched
859 function sq_findnxreg($body, $offset, $reg){
860 $me = 'sq_findnxreg';
863 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
867 $retarr{0} = $offset +
strlen($matches{1});
868 $retarr{1} = $matches{1};
869 $retarr{2} = $matches{2};
875 * This function looks for the next tag.
877 * @param $body String where to look for the next tag.
878 * @param $offset Start looking from here.
879 * @return false if no more tags exist in the body, or
880 * an array with the following members:
881 * - string with the name of the tag
882 * - array with attributes and their values
883 * - integer with tag type (1, 2, or 3)
884 * - integer where the tag starts (starting "<")
885 * - integer where the tag ends (ending ">")
886 * first three members will be false, if the tag is invalid.
888 function sq_getnxtag($body, $offset){
890 if ($offset > strlen($body)){
893 $lt = sq_findnxstr($body, $offset, "<");
894 if ($lt == strlen($body)){
899 * blah blah <tag attribute="value">
902 $pos = sq_skipspace($body, $lt+
1);
903 if ($pos >= strlen($body)){
904 return Array(false, false, false, $lt, strlen($body));
907 * There are 3 kinds of tags:
908 * 1. Opening tag, e.g.:
910 * 2. Closing tag, e.g.:
912 * 3. XHTML-style content-less tag, e.g.:
916 switch (substr($body, $pos, 1)){
923 * A comment or an SGML declaration.
925 if (substr($body, $pos+
1, 2) == "--"){
926 $gt = strpos($body, "-->", $pos);
932 return Array(false, false, false, $lt, $gt);
934 $gt = sq_findnxstr($body, $pos, ">");
935 return Array(false, false, false, $lt, $gt);
940 * Assume tagtype 1 for now. If it's type 3, we'll switch values
950 * Look for next [\W-_], which will indicate the end of the tag name.
952 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
953 if ($regary == false){
954 return Array(false, false, false, $lt, strlen($body));
956 list($pos, $tagname, $match) = $regary;
957 $tagname = strtolower($tagname);
960 * $match can be either of these:
961 * '>' indicating the end of the tag entirely.
962 * '\s' indicating the end of the tag name.
963 * '/' indicating that this is type-3 xhtml tag.
965 * Whatever else we find there indicates an invalid tag.
970 * This is an xhtml-style tag with a closing / at the
971 * end, like so: <img src="blah"/>. Check if it's followed
972 * by the closing bracket. If not, then this tag is invalid
974 if (substr($body, $pos, 2) == "/>"){
978 $gt = sq_findnxstr($body, $pos, ">");
979 $retary = Array(false, false, false, $lt, $gt);
983 return Array($tagname, false, $tagtype, $lt, $pos);
987 * Check if it's whitespace
989 if (!preg_match('/\s/', $match)){
991 * This is an invalid tag! Look for the next closing ">".
993 $gt = sq_findnxstr($body, $offset, ">");
994 return Array(false, false, false, $lt, $gt);
1000 * At this point we're here:
1001 * <tagname attribute='blah'>
1004 * At this point we loop in order to find all attributes.
1010 while ($pos <= strlen($body)){
1011 $pos = sq_skipspace($body, $pos);
1012 if ($pos == strlen($body)){
1016 return Array(false, false, false, $lt, $pos);
1019 * See if we arrived at a ">" or "/>", which means that we reached
1020 * the end of the tag.
1023 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1027 $pos +
= strlen($matches{1});
1028 if ($matches{2} == "/>"){
1032 return Array($tagname, $attary, $tagtype, $lt, $pos);
1036 * There are several types of attributes, with optional
1037 * [:space:] between members.
1039 * attrname[:space:]=[:space:]'CDATA'
1041 * attrname[:space:]=[:space:]"CDATA"
1043 * attr[:space:]=[:space:]CDATA
1047 * We leave types 1 and 2 the same, type 3 we check for
1048 * '"' and convert to """ if needed, then wrap in
1049 * double quotes. Type 4 we convert into:
1052 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1053 if ($regary == false){
1055 * Looks like body ended before the end of tag.
1057 return Array(false, false, false, $lt, strlen($body));
1059 list($pos, $attname, $match) = $regary;
1060 $attname = strtolower($attname);
1062 * We arrived at the end of attribute name. Several things possible
1064 * '>' means the end of the tag and this is attribute type 4
1065 * '/' if followed by '>' means the same thing as above
1066 * '\s' means a lot of things -- look what it's followed by.
1067 * anything else means the attribute is invalid.
1072 * This is an xhtml-style tag with a closing / at the
1073 * end, like so: <img src="blah"/>. Check if it's followed
1074 * by the closing bracket. If not, then this tag is invalid
1076 if (substr($body, $pos, 2) == "/>"){
1080 $gt = sq_findnxstr($body, $pos, ">");
1081 $retary = Array(false, false, false, $lt, $gt);
1085 $attary{$attname} = '"yes"';
1086 return Array($tagname, $attary, $tagtype, $lt, $pos);
1090 * Skip whitespace and see what we arrive at.
1092 $pos = sq_skipspace($body, $pos);
1093 $char = substr($body, $pos, 1);
1095 * Two things are valid here:
1096 * '=' means this is attribute type 1 2 or 3.
1097 * \w means this was attribute type 4.
1098 * anything else we ignore and re-loop. End of tag and
1099 * invalid stuff will be caught by our checks at the beginning
1104 $pos = sq_skipspace($body, $pos);
1106 * Here are 3 possibilities:
1107 * "'" attribute type 1
1108 * '"' attribute type 2
1109 * everything else is the content of tag type 3
1111 $quot = substr($body, $pos, 1);
1113 $regary = sq_findnxreg($body, $pos+
1, "\'");
1114 if ($regary == false){
1115 return Array(false, false, false, $lt, strlen($body));
1117 list($pos, $attval, $match) = $regary;
1119 $attary{$attname} = "'" . $attval . "'";
1120 } else if ($quot == '"'){
1121 $regary = sq_findnxreg($body, $pos+
1, '\"');
1122 if ($regary == false){
1123 return Array(false, false, false, $lt, strlen($body));
1125 list($pos, $attval, $match) = $regary;
1127 $attary{$attname} = '"' . $attval . '"';
1130 * These are hateful. Look for \s, or >.
1132 $regary = sq_findnxreg($body, $pos, "[\s>]");
1133 if ($regary == false){
1134 return Array(false, false, false, $lt, strlen($body));
1136 list($pos, $attval, $match) = $regary;
1138 * If it's ">" it will be caught at the top.
1140 $attval = preg_replace("/\"/s", """, $attval);
1141 $attary{$attname} = '"' . $attval . '"';
1143 } else if (preg_match("|[\w/>]|", $char)) {
1145 * That was attribute type 4.
1147 $attary{$attname} = '"yes"';
1150 * An illegal character. Find next '>' and return.
1152 $gt = sq_findnxstr($body, $pos, ">");
1153 return Array(false, false, false, $lt, $gt);
1159 * The fact that we got here indicates that the tag end was never
1160 * found. Return invalid tag indication so it gets stripped.
1162 return Array(false, false, false, $lt, strlen($body));
1166 * This function checks attribute values for entity-encoded values
1167 * and returns them translated into 8-bit strings so we can run
1170 * @param $attvalue A string to run entity check against.
1171 * @return Translated value.
1173 function sq_deent($attvalue){
1176 * See if we have to run the checks first. All entities must start
1179 if (strpos($attvalue, "&") === false){
1183 * Check named entities first.
1185 $trans = get_html_translation_table(HTML_ENTITIES
);
1187 * Leave " in, as it can mess us up.
1189 $trans = array_flip($trans);
1190 unset($trans{"""});
1191 while (list($ent, $val) = each($trans)){
1192 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1195 * Now translate numbered entities from 1 to 255 if needed.
1197 if (strpos($attvalue, "#") !== false){
1198 $omit = Array(34, 39);
1199 for ($asc=1; $asc<256; $asc++
){
1200 if (!in_array($asc, $omit)){
1202 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1204 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1205 "$chr\\1", $attvalue);
1213 * This function runs various checks against the attributes.
1215 * @param $tagname String with the name of the tag.
1216 * @param $attary Array with all tag attributes.
1217 * @param $rm_attnames See description for sq_sanitize
1218 * @param $bad_attvals See description for sq_sanitize
1219 * @param $add_attr_to_tag See description for sq_sanitize
1220 * @param $message message object
1221 * @param $id message id
1222 * @return Array with modified attributes.
1224 function sq_fixatts($tagname,
1234 while (list($attname, $attvalue) = each($attary)){
1236 * See if this attribute should be removed.
1238 foreach ($rm_attnames as $matchtag=>$matchattrs){
1239 if (preg_match($matchtag, $tagname)){
1240 foreach ($matchattrs as $matchattr){
1241 if (preg_match($matchattr, $attname)){
1242 unset($attary{$attname});
1249 * Remove any entities.
1251 $attvalue = sq_deent($attvalue);
1254 * Now let's run checks on the attvalues.
1255 * I don't expect anyone to comprehend this. If you do,
1256 * get in touch with me so I can drive to where you live and
1257 * shake your hand personally. :)
1259 foreach ($bad_attvals as $matchtag=>$matchattrs){
1260 if (preg_match($matchtag, $tagname)){
1261 foreach ($matchattrs as $matchattr=>$valary){
1262 if (preg_match($matchattr, $attname)){
1264 * There are two arrays in valary.
1266 * Second one is replacements
1268 list($valmatch, $valrepl) = $valary;
1270 preg_replace($valmatch, $valrepl, $attvalue);
1271 if ($newvalue != $attvalue){
1272 $attary{$attname} = $newvalue;
1279 * Turn cid: urls into http-friendly ones.
1281 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1282 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1286 * See if we need to append any attributes to this tag.
1288 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1289 if (preg_match($matchtag, $tagname)){
1290 $attary = array_merge($attary, $addattary);
1297 * This function edits the style definition to make them friendly and
1298 * usable in squirrelmail.
1300 * @param $message the message object
1301 * @param $id the message id
1302 * @param $content a string with whatever is between <style> and </style>
1303 * @return a string with edited content.
1305 function sq_fixstyle($message, $id, $content){
1306 global $view_unsafe_images;
1307 $me = 'sq_fixstyle';
1309 * First look for general BODY style declaration, which would be
1311 * body {background: blah-blah}
1312 * and change it to .bodyclass so we can just assign it to a <div>
1314 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1315 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1317 * Fix url('blah') declarations.
1319 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1320 "url(\\1$secremoveimg\\2)", $content);
1322 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1325 if (!$view_unsafe_images){
1326 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1327 "url(\\1$secremoveimg\\2)", $content);
1331 * Fix urls that refer to cid:
1333 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1335 $cidurl = $matches{1};
1336 $httpurl = sq_cid2http($message, $id, $cidurl);
1337 $content = preg_replace("|url\($cidurl\)|si",
1338 "url($httpurl)", $content);
1342 * Fix stupid css declarations which lead to vulnerabilities
1345 $match = Array('/expression/si',
1348 $replace = Array('idiocy', 'idiocy', 'idiocy');
1349 $content = preg_replace($match, $replace, $content);
1354 * This function converts cid: url's into the ones that can be viewed in
1357 * @param $message the message object
1358 * @param $id the message id
1359 * @param $cidurl the cid: url.
1360 * @return a string with a http-friendly url
1362 function sq_cid2http($message, $id, $cidurl, $mailbox){
1364 * Get rid of quotes.
1366 $quotchar = substr($cidurl, 0, 1);
1367 $cidurl = str_replace($quotchar, "", $cidurl);
1368 $cidurl = substr(trim($cidurl), 4);
1369 $linkurl = find_ent_id($cidurl, $message);
1370 /* in case of non-save cid links $httpurl should be replaced by a sort of
1371 unsave link image */
1374 $httpurl = $quotchar . '../src/download.php?absolute_dl=true&' .
1375 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1376 '&ent_id=' . $linkurl . $quotchar;
1382 * This function changes the <body> tag into a <div> tag since we
1383 * can't really have a body-within-body.
1385 * @param $attary an array of attributes and values of <body>
1386 * @return a modified array of attributes to be set for <div>
1388 function sq_body2div($attary){
1389 $me = 'sq_body2div';
1390 $divattary = Array('class' => "'bodyclass'");
1391 $bgcolor = '#ffffff';
1394 if (is_array($attary) && sizeof($attary) > 0){
1395 foreach ($attary as $attname=>$attvalue){
1396 $quotchar = substr($attvalue, 0, 1);
1397 $attvalue = str_replace($quotchar, "", $attvalue);
1400 $styledef .= "background-image: url('$attvalue'); ";
1403 $styledef .= "background-color: $attvalue; ";
1406 $styledef .= "color: $attvalue; ";
1410 if (strlen($styledef) > 0){
1411 $divattary{"style"} = "\"$styledef\"";
1418 * This is the main function and the one you should actually be calling.
1419 * There are several variables you should be aware of an which need
1420 * special description.
1422 * Since the description is quite lengthy, see it here:
1423 * http://www.mricon.com/html/phpfilter.html
1425 * @param $body the string with HTML you wish to filter
1426 * @param $tag_list see description above
1427 * @param $rm_tags_with_content see description above
1428 * @param $self_closing_tags see description above
1429 * @param $force_tag_closing see description above
1430 * @param $rm_attnames see description above
1431 * @param $bad_attvals see description above
1432 * @param $add_attr_to_tag see description above
1433 * @param $message message object
1434 * @param $id message id
1435 * @return sanitized html safe to show on your pages.
1437 function sq_sanitize($body,
1439 $rm_tags_with_content,
1449 $me = 'sq_sanitize';
1451 * Normalize rm_tags and rm_tags_with_content.
1453 @array_walk
($rm_tags, 'sq_casenormalize');
1454 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1455 @array_walk
($self_closing_tags, 'sq_casenormalize');
1457 * See if tag_list is of tags to remove or tags to allow.
1458 * false means remove these tags
1459 * true means allow these tags
1461 $rm_tags = array_shift($tag_list);
1463 $open_tags = Array();
1464 $trusted = "<!-- begin sanitized html -->\n";
1465 $skip_content = false;
1467 * Take care of netscape's stupid javascript entities like
1470 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1472 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1473 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1474 $free_content = substr($body, $curpos, $lt-$curpos);
1476 * Take care of <style>
1478 if ($tagname == "style" && $tagtype == 2){
1480 * This is a closing </style>. Edit the
1481 * content before we apply it.
1483 $free_content = sq_fixstyle($message, $id, $free_content);
1485 if ($skip_content == false){
1486 $trusted .= $free_content;
1488 if ($tagname != FALSE){
1490 if ($skip_content == $tagname){
1492 * Got to the end of tag we needed to remove.
1495 $skip_content = false;
1497 if ($skip_content == false){
1498 if ($tagname == "body"){
1501 if (isset($open_tags{$tagname}) &&
1502 $open_tags{$tagname} > 0){
1503 $open_tags{$tagname}--;
1512 * $rm_tags_with_content
1514 if ($skip_content == false){
1516 * See if this is a self-closing type and change
1517 * tagtype appropriately.
1520 && in_array($tagname, $self_closing_tags)){
1524 * See if we should skip this tag and any content
1527 if ($tagtype == 1 &&
1528 in_array($tagname, $rm_tags_with_content)){
1529 $skip_content = $tagname;
1531 if (($rm_tags == false
1532 && in_array($tagname, $tag_list)) ||
1533 ($rm_tags == true &&
1534 !in_array($tagname, $tag_list))){
1538 if (isset($open_tags{$tagname})){
1539 $open_tags{$tagname}++
;
1541 $open_tags{$tagname}=1;
1545 * This is where we run other checks.
1547 if (is_array($attary) && sizeof($attary) > 0){
1548 $attary = sq_fixatts($tagname,
1559 * Convert body into div.
1561 if ($tagname == "body"){
1563 $attary = sq_body2div($attary, $message, $id);
1569 if ($tagname != false && $skip_content == false){
1570 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1575 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1576 if ($force_tag_closing == true){
1577 foreach ($open_tags as $tagname=>$opentimes){
1578 while ($opentimes > 0){
1579 $trusted .= '</' . $tagname . '>';
1585 $trusted .= "<!-- end sanitized html -->\n";
1590 * This is a wrapper function to call html sanitizing routines.
1592 * @param $body the body of the message
1593 * @param $id the id of the message
1594 * @return a string with html safe to display in the browser.
1596 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1597 global $attachment_common_show_images, $view_unsafe_images,
1600 * Don't display attached images in HTML mode.
1602 $attachment_common_show_images = false;
1615 $rm_tags_with_content = Array(
1622 $self_closing_tags = Array(
1629 $force_tag_closing = false;
1631 $rm_attnames = Array(
1641 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1642 $bad_attvals = Array(
1645 "/^src|background/i" =>
1648 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1649 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1650 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1651 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1654 "\\1$secremoveimg\\2",
1655 "\\1$secremoveimg\\2",
1656 "\\1$secremoveimg\\2",
1657 "\\1$secremoveimg\\2"
1660 "/^href|action/i" =>
1663 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1664 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1665 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1666 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1681 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1682 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1683 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1684 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1698 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1699 $view_unsafe_images = false;
1701 if (!$view_unsafe_images){
1703 * Remove any references to http/https if view_unsafe_images set
1706 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1707 '/^([\'\"])\s*https*:.*([\'\"])/si');
1708 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1709 "\\1$secremoveimg\\2");
1710 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1711 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1712 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1713 "url(\\1$secremoveimg\\2)");
1716 $add_attr_to_tag = Array(
1717 "/^a$/si" => Array('target'=>'"_new"')
1719 $trusted = sq_sanitize($body,
1721 $rm_tags_with_content,
1731 if (preg_match("|$secremoveimg|si", $trusted)){
1732 $has_unsafe_images = true;