e8b7664f30fc0a2de88776af36e110f1b66a79cd
6 * Copyright (c) 1999-2002 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('../functions/imap.php');
16 require_once('../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 $msg = &new message();
32 $read = trim(substr ($read, 0, -1));
33 $msg = $msg->parseStructure($read,0);
36 foreach ($flags as $flag) {
37 $char = strtoupper($flag{1});
40 if (strtolower($flag) == '\\seen') {
45 if (strtolower($flag) == '\\answered') {
46 $msg->is_answered
= true;
50 if (strtolower($flag) == '\\deleted') {
51 $msg->is_deleted
= true;
55 if (strtolower($flag) == '\\flagged') {
56 $msg->is_flagged
= true;
60 if (strtolower($flag) == '\$mdnsent') {
69 // listEntities($msg);
73 /* this starts the parsing of a particular structure. It is called recursively,
74 * so it can be passed different structures. It returns an object of type
76 * First, it checks to see if it is a multipart message. If it is, then it
77 * handles that as it sees is necessary. If it is just a regular entity,
78 * then it parses it and adds the necessary header information (by calling out
79 * to mime_get_elements()
82 function mime_fetch_body($imap_stream, $id, $ent_id) {
85 * do a bit of error correction. If we couldn't find the entity id, just guess
86 * that it is the first one. That is usually the case anyway.
91 $cmd = "FETCH $id BODY[$ent_id]";
93 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
95 $topline = trim(array_shift( $data ));
96 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
98 $wholemessage = implode('', $data);
99 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
101 $ret = substr( $wholemessage, 0, $regs[1] );
103 There is some information in the content info header that could be important
104 in order to parse html messages. Let's get them here.
106 if ( $ret{0} == '<' ) {
107 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
109 } else if (ereg('"([^"]*)"', $topline, $regs)) {
112 global $where, $what, $mailbox, $passed_id, $startMessage;
113 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
114 if (isset($where) && isset($what)) {
115 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
117 $par .= "&startMessage=$startMessage&show_more=0";
119 $par .= '&response=' . urlencode($response) .
120 '&message=' . urlencode($message).
121 '&topline=' . urlencode($topline);
124 '<table width="80%"><tr>' .
125 '<tr><td colspan=2>' .
126 _("Body retrieval error. The reason for this is most probably that the message is malformed. Please help us making future versions better by submitting this message to the developers knowledgebase!") .
127 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
128 _("Submit message") . '</A><BR> ' .
130 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
131 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
132 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
133 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
134 "</table><BR></tt></font><hr>";
136 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
138 $wholemessage = implode('', $data);
140 $ret = $wholemessage;
145 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
147 // do a bit of error correction. If we couldn't find the entity id, just guess
148 // that it is the first one. That is usually the case anyway.
152 $sid = sqimap_session_id($uid_support);
153 // Don't kill the connection if the browser is over a dialup
154 // and it would take over 30 seconds to download it.
156 // donĀ“t call set_time_limit in safe mode.
157 if (!ini_get("safe_mode")) {
161 $sid_s = substr($sid,0,strpos($sid, ' '));
166 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
169 $read = fgets ($imap_stream,8192);
172 // This could be bad -- if the section has sqimap_session_id() . ' OK'
173 // or similar, it will kill the download.
174 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
175 if (trim($read) == ')==') {
177 $read = fgets ($imap_stream,4096);
178 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
181 echo decodeBody($read1, $encoding) .
182 decodeBody($read, $encoding);
185 echo decodeBody($read, $encoding);
187 $read = fgets ($imap_stream,4096);
193 /* -[ END MIME DECODING ]----------------------------------------------------------- */
196 // This is here for debugging purposese. It will print out a list
197 // of all the entity IDs that are in the $message object.
199 function listEntities ($message) {
201 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
202 for ($i = 0;isset($message->entities
[$i]); $i++
) {
204 $msg = listEntities($message->entities
[$i]);
214 /* returns a $message object for a particular entity id */
215 function getEntity ($message, $ent_id) {
216 return $message->getEntity($ent_id);
221 * Extracted from strings.php 23/03/2002
224 function translateText(&$body, $wrap_at, $charset) {
225 global $where, $what; /* from searching */
226 global $color; /* color theme */
228 require_once('../functions/url_parser.php');
230 $body_ary = explode("\n", $body);
232 for ($i=0; $i < count($body_ary); $i++
) {
233 $line = $body_ary[$i];
234 if (strlen($line) - 2 >= $wrap_at) {
235 sqWordWrap($line, $wrap_at);
237 $line = charset_decode($charset, $line);
238 $line = str_replace("\t", ' ', $line);
244 $j = strlen( $line );
246 while ( $pos < $j ) {
247 if ($line[$pos] == ' ') {
249 } else if (strpos($line, '>', $pos) === $pos) {
258 if (! isset($color[14])) {
259 $color[14] = '#FF0000';
261 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
263 if (! isset($color[13])) {
264 $color[13] = '#800000';
266 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
269 $body_ary[$i] = $line;
271 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
275 /* This returns a parsed string called $body. That string can then
276 be displayed as the actual message in the HTML. It contains
277 everything needed, including HTML Tags, Attachments at the
280 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
281 // this if statement checks for the entity to show as the
282 // primary message. To add more of them, just put them in the
283 // order that is their priority.
284 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
285 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
287 $has_unsafe_images= 0;
289 $urlmailbox = urlencode($mailbox);
290 $body_message = getEntity($message, $ent_num);
291 if (($body_message->header
->type0
== 'text') ||
292 ($body_message->header
->type0
== 'rfc822')) {
293 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
295 $body = decodeBody($body, $body_message->header
->encoding
);
296 $hookResults = do_hook("message_body", $body);
297 $body = $hookResults[1];
299 // If there are other types that shouldn't be formatted, add
301 if ($body_message->header
->type1
== 'html') {
302 if ( $show_html_default <> 1 ) {
303 $body = strip_tags( $body );
304 translateText($body, $wrap_at, $body_message->header
->charset
);
306 $body = magicHTML( $body, $id, $message, $mailbox );
309 translateText($body, $wrap_at, $body_message->header
->charset
);
312 if ($has_unsafe_images) {
313 if ($view_unsafe_images) {
314 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&passed_ent_id=".$message->entity_id
."&mailbox=$urlmailbox&sort=$sort&startMessage=$startMessage&show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
316 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&passed_ent_id=".$message->entity_id
."&mailbox=$urlmailbox&sort=$sort&startMessage=$startMessage&show_more=0&view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
324 function formatAttachments($message, $exclude_id, $mailbox, $id) {
325 global $where, $what;
326 global $startMessage, $color;
327 static $ShownHTML = 0;
329 $att_ar = $message->getAttachments($exclude_id);
331 if (!count($att_ar)) return '';
333 $attachments = "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
334 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
335 _("Attachments") . ':' .
336 "</B></TH></TR><TR><TD>\n" .
337 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";
339 $urlMailbox = urlencode($mailbox);
341 foreach ($att_ar as $att) {
343 $ent = urlencode($att->entity_id
);
344 $header = $att->header
;
345 $type0 = strtolower($header->type0
);
346 $type1 = strtolower($header->type1
);
348 if ($type0 =='message' && $type1 == 'rfc822') {
350 $filename = decodeHeader($header->subject
);
351 $display_filename = $filename;
354 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
355 if ($where && $what) {
356 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
358 $Links['download link']['text'] = _("download");
359 $Links['download link']['href'] =
360 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
363 /* this executes the attachment hook with a specific MIME-type.
364 * if that doens't have results, it tries if there's a rule
365 * for a more generic type. */
366 $HookResults = do_hook("attachment $type0/$type1", $Links,
367 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
368 if(count($HookResults[1]) <= 1) {
369 $HookResults = do_hook("attachment $type0/*", $Links,
370 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
371 $display_filename, $where, $what);
374 $Links = $HookResults[1];
375 $DefaultLink = $HookResults[6];
377 $attachments .= '<TR><TD> </TD><TD>' .
378 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
379 '<TD><SMALL><b>' . show_readable_size($header->size
) .
380 '</b> </small></TD>' .
381 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
383 $from_o = $header->from
;
384 if (isset($from_o)) {
385 $from_name = $from_o->getAddress(false);
387 $from_name = _("Unknown sender");
389 $from_name = decodeHeader(htmlspecialchars($from_name));
390 $attachments .= '<b>' . $from_name . '</b>';
391 $attachments .= '</SMALL></TD><TD><SMALL> ';
394 foreach ($Links as $Val) {
398 $attachments .= ' | ';
400 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
404 $filename = decodeHeader($header->filename
);
405 if (trim($filename) == '') {
406 if (trim($name) == '') {
407 if ( trim( $header->id
) == '' )
408 $display_filename = 'untitled-[' . $ent . ']' ;
410 $display_filename = 'cid: ' . $header->id
;
412 $display_filename = $name;
416 $display_filename = $filename;
420 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
421 if ($where && $what) {
422 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
424 $Links['download link']['text'] = _("download");
425 $Links['download link']['href'] =
426 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
429 /* this executes the attachment hook with a specific MIME-type.
430 * if that doens't have results, it tries if there's a rule
431 * for a more generic type. */
432 $HookResults = do_hook("attachment $type0/$type1", $Links,
433 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
434 $display_filename, $where, $what);
435 if(count($HookResults[1]) <= 1) {
436 $HookResults = do_hook("attachment $type0/*", $Links,
437 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
438 $display_filename, $where, $what);
441 $Links = $HookResults[1];
442 $DefaultLink = $HookResults[6];
444 $attachments .= '<TR><TD> </TD><TD>' .
445 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
446 '<TD><SMALL><b>' . show_readable_size($header->size
) .
447 '</b> </small></TD>' .
448 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
450 if ($message->header
->description
) {
451 $attachments .= '<b>' . htmlspecialchars(_($header->description
)) . '</b>';
453 $attachments .= '</SMALL></TD><TD><SMALL> ';
456 foreach ($Links as $Val) {
460 $attachments .= ' | ';
462 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
469 $attachments .= "</SMALL></TD></TR>\n";
471 $attachments .= "</TABLE></TD></TR></TABLE>";
476 /** this function decodes the body depending on the encoding type. **/
477 function decodeBody($body, $encoding) {
478 $body = str_replace("\r\n", "\n", $body);
479 $encoding = strtolower($encoding);
481 global $show_html_default;
483 if ($encoding == 'quoted-printable' ||
484 $encoding == 'quoted_printable') {
485 $body = quoted_printable_decode($body);
487 while (ereg("=\n", $body))
488 $body = ereg_replace ("=\n", "", $body);
490 } else if ($encoding == 'base64') {
491 $body = base64_decode($body);
494 // All other encodings are returned raw.
499 * This functions decode strings that is encoded according to
500 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
501 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
503 function decodeHeader ($string, $utfencode=true) {
504 if (is_array($string)) {
505 $string = implode("\n", $string);
508 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
511 // Ignore white-space between consecutive encoded-words
512 if (strspn($res[2], " \t") != strlen($res[2])) {
516 if (ucfirst($res[4]) == 'B') {
517 $replace = base64_decode($res[5]);
519 $replace = str_replace('_', ' ', $res[5]);
520 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
522 /* Only encode into entities by default. Some places
523 don't need the encoding, like the compose form. */
525 $replace = charset_decode($res[3], $replace);
528 $string = $prefix . $replace . substr($string, strlen($res[0]));
529 $i = strlen($prefix) +
strlen($replace);
535 * Encode a string according to RFC 1522 for use in headers if it
536 * contains 8-bit characters or anything that looks like it should
539 function encodeHeader ($string) {
540 global $default_charset;
542 // Encode only if the string contains 8-bit characters or =?
543 $j = strlen( $string );
544 $l = strstr($string, '=?'); // Must be encoded ?
546 for( $i=0; $i < $j; ++
$i) {
547 switch( $string{$i} ) {
561 $k = ord( $string{$i} );
563 $ret .= sprintf("=%02X", $k);
571 $string = "=?$default_charset?Q?$ret?=";
577 /* This function trys to locate the entity_id of a specific mime element */
579 function find_ent_id( $id, $message ) {
581 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
582 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
583 $ret = find_ent_id( $id, $message->entities
[$i] );
585 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
586 $ret = $message->entities
[$i]->entity_id
;
593 ** HTMLFILTER ROUTINES
597 * This function returns the final tag out of the tag name, an array
598 * of attributes, and the type of the tag. This function is called by
599 * sq_sanitize internally.
601 * @param $tagname the name of the tag.
602 * @param $attary the array of attributes and their values
603 * @param $tagtype The type of the tag (see in comments).
604 * @return a string with the final tag representation.
606 function sq_tagprint($tagname, $attary, $tagtype){
609 $fulltag = '</' . $tagname . '>';
611 $fulltag = '<' . $tagname;
612 if (is_array($attary) && sizeof($attary)){
614 while (list($attname, $attvalue) = each($attary)){
615 array_push($atts, "$attname=$attvalue");
617 $fulltag .= ' ' . join(" ", $atts);
628 * A small helper function to use with array_walk. Modifies a by-ref
629 * value and makes it lowercase.
631 * @param $val a value passed by-ref.
632 * @return void since it modifies a by-ref value.
634 function sq_casenormalize(&$val){
635 $val = strtolower($val);
639 * This function skips any whitespace from the current position within
640 * a string and to the next non-whitespace value.
642 * @param $body the string
643 * @param $offset the offset within the string where we should start
644 * looking for the next non-whitespace character.
645 * @return the location within the $body where the next
646 * non-whitespace char is located.
648 function sq_skipspace($body, $offset){
649 $me = "sq_skipspace";
650 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
651 if (sizeof($matches{1})){
652 $count = strlen($matches{1});
659 * This function looks for the next character within a string. It's
660 * really just a glorified "strpos", except it catches if failures
663 * @param $body The string to look for needle in.
664 * @param $offset Start looking from this position.
665 * @param $needle The character/string to look for.
666 * @return location of the next occurance of the needle, or
667 * strlen($body) if needle wasn't found.
669 function sq_findnxstr($body, $offset, $needle){
670 $me = "sq_findnxstr";
671 $pos = strpos($body, $needle, $offset);
673 $pos = strlen($body);
679 * This function takes a PCRE-style regexp and tries to match it
682 * @param $body The string to look for needle in.
683 * @param $offset Start looking from here.
684 * @param $reg A PCRE-style regex to match.
685 * @return Returns a false if no matches found, or an array
686 * with the following members:
687 * - integer with the location of the match within $body
688 * - string with whatever content between offset and the match
689 * - string with whatever it is we matched
691 function sq_findnxreg($body, $offset, $reg){
692 $me = "sq_findnxreg";
695 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
699 $retarr{0} = $offset +
strlen($matches{1});
700 $retarr{1} = $matches{1};
701 $retarr{2} = $matches{2};
707 * This function looks for the next tag.
709 * @param $body String where to look for the next tag.
710 * @param $offset Start looking from here.
711 * @return false if no more tags exist in the body, or
712 * an array with the following members:
713 * - string with the name of the tag
714 * - array with attributes and their values
715 * - integer with tag type (1, 2, or 3)
716 * - integer where the tag starts (starting "<")
717 * - integer where the tag ends (ending ">")
718 * first three members will be false, if the tag is invalid.
720 function sq_getnxtag($body, $offset){
722 if ($offset > strlen($body)){
725 $lt = sq_findnxstr($body, $offset, "<");
726 if ($lt == strlen($body)){
731 * blah blah <tag attribute="value">
734 $pos = sq_skipspace($body, $lt+
1);
735 if ($pos >= strlen($body)){
736 return Array(false, false, false, $lt, strlen($body));
739 * There are 3 kinds of tags:
740 * 1. Opening tag, e.g.:
742 * 2. Closing tag, e.g.:
744 * 3. XHTML-style content-less tag, e.g.:
748 switch (substr($body, $pos, 1)){
755 * A comment or an SGML declaration.
757 if (substr($body, $pos+
1, 2) == "--"){
758 $gt = strpos($body, "-->", $pos);
764 return Array(false, false, false, $lt, $gt);
766 $gt = sq_findnxstr($body, $pos, ">");
767 return Array(false, false, false, $lt, $gt);
772 * Assume tagtype 1 for now. If it's type 3, we'll switch values
782 * Look for next [\W-_], which will indicate the end of the tag name.
784 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
785 if ($regary == false){
786 return Array(false, false, false, $lt, strlen($body));
788 list($pos, $tagname, $match) = $regary;
789 $tagname = strtolower($tagname);
792 * $match can be either of these:
793 * '>' indicating the end of the tag entirely.
794 * '\s' indicating the end of the tag name.
795 * '/' indicating that this is type-3 xhtml tag.
797 * Whatever else we find there indicates an invalid tag.
802 * This is an xhtml-style tag with a closing / at the
803 * end, like so: <img src="blah"/>. Check if it's followed
804 * by the closing bracket. If not, then this tag is invalid
806 if (substr($body, $pos, 2) == "/>"){
810 $gt = sq_findnxstr($body, $pos, ">");
811 $retary = Array(false, false, false, $lt, $gt);
815 return Array($tagname, false, $tagtype, $lt, $pos);
819 * Check if it's whitespace
821 if (preg_match("/\s/", $match)){
824 * This is an invalid tag! Look for the next closing ">".
826 $gt = sq_findnxstr($body, $offset, ">");
827 return Array(false, false, false, $lt, $gt);
832 * At this point we're here:
833 * <tagname attribute='blah'>
836 * At this point we loop in order to find all attributes.
842 while ($pos <= strlen($body)){
843 $pos = sq_skipspace($body, $pos);
844 if ($pos == strlen($body)){
848 return Array(false, false, false, $lt, $pos);
851 * See if we arrived at a ">" or "/>", which means that we reached
852 * the end of the tag.
855 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
859 $pos +
= strlen($matches{1});
860 if ($matches{2} == "/>"){
864 return Array($tagname, $attary, $tagtype, $lt, $pos);
868 * There are several types of attributes, with optional
869 * [:space:] between members.
871 * attrname[:space:]=[:space:]'CDATA'
873 * attrname[:space:]=[:space:]"CDATA"
875 * attr[:space:]=[:space:]CDATA
879 * We leave types 1 and 2 the same, type 3 we check for
880 * '"' and convert to """ if needed, then wrap in
881 * double quotes. Type 4 we convert into:
884 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
885 if ($regary == false){
887 * Looks like body ended before the end of tag.
889 return Array(false, false, false, $lt, strlen($body));
891 list($pos, $attname, $match) = $regary;
892 $attname = strtolower($attname);
894 * We arrived at the end of attribute name. Several things possible
896 * '>' means the end of the tag and this is attribute type 4
897 * '/' if followed by '>' means the same thing as above
898 * '\s' means a lot of things -- look what it's followed by.
899 * anything else means the attribute is invalid.
904 * This is an xhtml-style tag with a closing / at the
905 * end, like so: <img src="blah"/>. Check if it's followed
906 * by the closing bracket. If not, then this tag is invalid
908 if (substr($body, $pos, 2) == "/>"){
912 $gt = sq_findnxstr($body, $pos, ">");
913 $retary = Array(false, false, false, $lt, $gt);
917 $attary{$attname} = '"yes"';
918 return Array($tagname, $attary, $tagtype, $lt, $pos);
922 * Skip whitespace and see what we arrive at.
924 $pos = sq_skipspace($body, $pos);
925 $char = substr($body, $pos, 1);
927 * Two things are valid here:
928 * '=' means this is attribute type 1 2 or 3.
929 * \w means this was attribute type 4.
930 * anything else we ignore and re-loop. End of tag and
931 * invalid stuff will be caught by our checks at the beginning
936 $pos = sq_skipspace($body, $pos);
938 * Here are 3 possibilities:
939 * "'" attribute type 1
940 * '"' attribute type 2
941 * everything else is the content of tag type 3
943 $quot = substr($body, $pos, 1);
945 $regary = sq_findnxreg($body, $pos+
1, "\'");
946 if ($regary == false){
947 return Array(false, false, false, $lt, strlen($body));
949 list($pos, $attval, $match) = $regary;
951 $attary{$attname} = "'" . $attval . "'";
952 } else if ($quot == '"'){
953 $regary = sq_findnxreg($body, $pos+
1, '\"');
954 if ($regary == false){
955 return Array(false, false, false, $lt, strlen($body));
957 list($pos, $attval, $match) = $regary;
959 $attary{$attname} = '"' . $attval . '"';
962 * These are hateful. Look for \s, or >.
964 $regary = sq_findnxreg($body, $pos, "[\s>]");
965 if ($regary == false){
966 return Array(false, false, false, $lt, strlen($body));
968 list($pos, $attval, $match) = $regary;
970 * If it's ">" it will be caught at the top.
972 $attval = preg_replace("/\"/s", """, $attval);
973 $attary{$attname} = '"' . $attval . '"';
975 } else if (preg_match("|[\w/>]|", $char)) {
977 * That was attribute type 4.
979 $attary{$attname} = '"yes"';
982 * An illegal character. Find next '>' and return.
984 $gt = sq_findnxstr($body, $pos, ">");
985 return Array(false, false, false, $lt, $gt);
990 * The fact that we got here indicates that the tag end was never
991 * found. Return invalid tag indication so it gets stripped.
993 return Array(false, false, false, $lt, strlen($body));
997 * This function checks attribute values for entity-encoded values
998 * and returns them translated into 8-bit strings so we can run
1001 * @param $attvalue A string to run entity check against.
1002 * @return Translated value.
1004 function sq_deent($attvalue){
1007 * See if we have to run the checks first. All entities must start
1010 if (strpos($attvalue, "&") === false){
1014 * Check named entities first.
1016 $trans = get_html_translation_table(HTML_ENTITIES
);
1018 * Leave " in, as it can mess us up.
1020 $trans = array_flip($trans);
1021 unset($trans{"""});
1022 while (list($ent, $val) = each($trans)){
1023 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1026 * Now translate numbered entities from 1 to 255 if needed.
1028 if (strpos($attvalue, "#") !== false){
1029 $omit = Array(34, 39);
1030 for ($asc=1; $asc<256; $asc++
){
1031 if (!in_array($asc, $omit)){
1033 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1035 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1036 "$chr\\1", $attvalue);
1044 * This function runs various checks against the attributes.
1046 * @param $tagname String with the name of the tag.
1047 * @param $attary Array with all tag attributes.
1048 * @param $rm_attnames See description for sq_sanitize
1049 * @param $bad_attvals See description for sq_sanitize
1050 * @param $add_attr_to_tag See description for sq_sanitize
1051 * @param $message message object
1052 * @param $id message id
1053 * @return Array with modified attributes.
1055 function sq_fixatts($tagname,
1065 while (list($attname, $attvalue) = each($attary)){
1067 * See if this attribute should be removed.
1069 foreach ($rm_attnames as $matchtag=>$matchattrs){
1070 if (preg_match($matchtag, $tagname)){
1071 foreach ($matchattrs as $matchattr){
1072 if (preg_match($matchattr, $attname)){
1073 unset($attary{$attname});
1080 * Remove any entities.
1082 $attvalue = sq_deent($attvalue);
1085 * Now let's run checks on the attvalues.
1086 * I don't expect anyone to comprehend this. If you do,
1087 * get in touch with me so I can drive to where you live and
1088 * shake your hand personally. :)
1090 foreach ($bad_attvals as $matchtag=>$matchattrs){
1091 if (preg_match($matchtag, $tagname)){
1092 foreach ($matchattrs as $matchattr=>$valary){
1093 if (preg_match($matchattr, $attname)){
1095 * There are two arrays in valary.
1097 * Second one is replacements
1099 list($valmatch, $valrepl) = $valary;
1101 preg_replace($valmatch, $valrepl, $attvalue);
1102 if ($newvalue != $attvalue){
1103 $attary{$attname} = $newvalue;
1110 * Turn cid: urls into http-friendly ones.
1112 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1113 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1117 * See if we need to append any attributes to this tag.
1119 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1120 if (preg_match($matchtag, $tagname)){
1121 $attary = array_merge($attary, $addattary);
1128 * This function edits the style definition to make them friendly and
1129 * usable in squirrelmail.
1131 * @param $message the message object
1132 * @param $id the message id
1133 * @param $content a string with whatever is between <style> and </style>
1134 * @return a string with edited content.
1136 function sq_fixstyle($message, $id, $content){
1137 global $view_unsafe_images;
1138 $me = "sq_fixstyle";
1140 * First look for general BODY style declaration, which would be
1142 * body {background: blah-blah}
1143 * and change it to .bodyclass so we can just assign it to a <div>
1145 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1146 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1148 * Fix url('blah') declarations.
1150 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1151 "url(\\1$secremoveimg\\2)", $content);
1153 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1156 if (!$view_unsafe_images){
1157 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1158 "url(\\1$secremoveimg\\2)", $content);
1162 * Fix urls that refer to cid:
1164 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1166 $cidurl = $matches{1};
1167 $httpurl = sq_cid2http($message, $id, $cidurl);
1168 $content = preg_replace("|url\($cidurl\)|si",
1169 "url($httpurl)", $content);
1173 * Fix stupid css declarations which lead to vulnerabilities
1176 $match = Array('/expression/si',
1179 $replace = Array('idiocy', 'idiocy', 'idiocy');
1180 $content = preg_replace($match, $replace, $content);
1185 * This function converts cid: url's into the ones that can be viewed in
1188 * @param $message the message object
1189 * @param $id the message id
1190 * @param $cidurl the cid: url.
1191 * @return a string with a http-friendly url
1193 function sq_cid2http($message, $id, $cidurl, $mailbox){
1195 * Get rid of quotes.
1197 $quotchar = substr($cidurl, 0, 1);
1198 $cidurl = str_replace($quotchar, "", $cidurl);
1199 $cidurl = substr(trim($cidurl), 4);
1200 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1201 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1202 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1207 * This function changes the <body> tag into a <div> tag since we
1208 * can't really have a body-within-body.
1210 * @param $attary an array of attributes and values of <body>
1211 * @return a modified array of attributes to be set for <div>
1213 function sq_body2div($attary){
1214 $me = "sq_body2div";
1215 $divattary = Array("class"=>"'bodyclass'");
1219 if (is_array($attary) && sizeof($attary) > 0){
1220 foreach ($attary as $attname=>$attvalue){
1221 $quotchar = substr($attvalue, 0, 1);
1222 $attvalue = str_replace($quotchar, "", $attvalue);
1225 $styledef .= "background-image: url('$attvalue'); ";
1228 $styledef .= "background-color: $attvalue; ";
1231 $styledef .= "color: $attvalue; ";
1234 if (strlen($styledef) > 0){
1235 $divattary{"style"} = "\"$styledef\"";
1242 * This is the main function and the one you should actually be calling.
1243 * There are several variables you should be aware of an which need
1244 * special description.
1246 * Since the description is quite lengthy, see it here:
1247 * http://www.mricon.com/html/phpfilter.html
1249 * @param $body the string with HTML you wish to filter
1250 * @param $tag_list see description above
1251 * @param $rm_tags_with_content see description above
1252 * @param $self_closing_tags see description above
1253 * @param $force_tag_closing see description above
1254 * @param $rm_attnames see description above
1255 * @param $bad_attvals see description above
1256 * @param $add_attr_to_tag see description above
1257 * @param $message message object
1258 * @param $id message id
1259 * @return sanitized html safe to show on your pages.
1261 function sq_sanitize($body,
1263 $rm_tags_with_content,
1273 $me = "sq_sanitize";
1275 * Normalize rm_tags and rm_tags_with_content.
1277 @array_walk
($rm_tags, 'sq_casenormalize');
1278 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1279 @array_walk
($self_closing_tags, 'sq_casenormalize');
1281 * See if tag_list is of tags to remove or tags to allow.
1282 * false means remove these tags
1283 * true means allow these tags
1285 $rm_tags = array_shift($tag_list);
1287 $open_tags = Array();
1288 $trusted = "<!-- begin sanitized html -->\n";
1289 $skip_content = false;
1291 * Take care of netscape's stupid javascript entities like
1294 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1296 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1297 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1298 $free_content = substr($body, $curpos, $lt-$curpos);
1300 * Take care of <style>
1302 if ($tagname == "style" && $tagtype == 2){
1304 * This is a closing </style>. Edit the
1305 * content before we apply it.
1307 $free_content = sq_fixstyle($message, $id, $free_content);
1309 if ($skip_content == false){
1310 $trusted .= $free_content;
1313 if ($tagname != FALSE){
1315 if ($skip_content == $tagname){
1317 * Got to the end of tag we needed to remove.
1320 $skip_content = false;
1322 if ($skip_content == false){
1323 if ($tagname == "body"){
1326 if (isset($open_tags{$tagname}) &&
1327 $open_tags{$tagname} > 0){
1328 $open_tags{$tagname}--;
1338 * $rm_tags_with_content
1340 if ($skip_content == false){
1342 * See if this is a self-closing type and change
1343 * tagtype appropriately.
1346 && in_array($tagname, $self_closing_tags)){
1350 * See if we should skip this tag and any content
1353 if ($tagtype == 1 &&
1354 in_array($tagname, $rm_tags_with_content)){
1355 $skip_content = $tagname;
1357 if (($rm_tags == false
1358 && in_array($tagname, $tag_list)) ||
1359 ($rm_tags == true &&
1360 !in_array($tagname, $tag_list))){
1364 if (isset($open_tags{$tagname})){
1365 $open_tags{$tagname}++
;
1367 $open_tags{$tagname}=1;
1371 * This is where we run other checks.
1373 if (is_array($attary) && sizeof($attary) > 0){
1374 $attary = sq_fixatts($tagname,
1385 * Convert body into div.
1387 if ($tagname == "body"){
1389 $attary = sq_body2div($attary, $message, $id);
1396 if ($tagname != false && $skip_content == false){
1397 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1403 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1404 if ($force_tag_closing == true){
1405 foreach ($open_tags as $tagname=>$opentimes){
1406 while ($opentimes > 0){
1407 $trusted .= '</' . $tagname . '>';
1413 $trusted .= "<!-- end sanitized html -->\n";
1418 * This is a wrapper function to call html sanitizing routines.
1420 * @param $body the body of the message
1421 * @param $id the id of the message
1422 * @return a string with html safe to display in the browser.
1424 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1425 global $attachment_common_show_images, $view_unsafe_images,
1428 * Don't display attached images in HTML mode.
1430 $attachment_common_show_images = false;
1441 $rm_tags_with_content = Array(
1448 $self_closing_tags = Array(
1455 $force_tag_closing = false;
1457 $rm_attnames = Array(
1467 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1468 $bad_attvals = Array(
1471 "/^src|background/i" =>
1474 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1475 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1476 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1477 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1480 "\\1$secremoveimg\\2",
1481 "\\1$secremoveimg\\2",
1482 "\\1$secremoveimg\\2",
1483 "\\1$secremoveimg\\2"
1486 "/^href|action/i" =>
1489 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1490 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1491 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1492 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1507 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1508 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1509 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1510 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1524 if (!$view_unsafe_images){
1526 * Remove any references to http/https if view_unsafe_images set
1529 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1530 '/^([\'\"])\s*https*:.*([\'\"])/si');
1531 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1532 "\\1$secremoveimg\\2");
1533 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1534 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1535 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1536 "url(\\1$secremoveimg\\2)");
1539 $add_attr_to_tag = Array(
1540 "/^a$/si" => Array('target'=>'"_new"')
1542 $trusted = sq_sanitize($body,
1544 $rm_tags_with_content,
1554 if (preg_match("|$secremoveimg|si", $trusted)){
1555 $has_unsafe_images = true;