8717a5b639d4015abf09ff98a8306756f56271ba
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') {
61 $msg->is_mdnsent
= true;
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 function getPriorityStr($priority) {
215 $priority_level = substr($priority,0,1);
217 switch($priority_level) {
218 /* check for a higher then normal priority. */
221 $priority_string = _("High");
224 /* check for a lower then normal priority. */
227 $priority_string = _("Low");
230 /* check for a normal priority. */
233 $priority_level = '3';
234 $priority_string = _("Normal");
238 return $priority_string;
241 /* returns a $message object for a particular entity id */
242 function getEntity ($message, $ent_id) {
243 return $message->getEntity($ent_id);
248 * Extracted from strings.php 23/03/2002
251 function translateText(&$body, $wrap_at, $charset) {
252 global $where, $what; /* from searching */
253 global $color; /* color theme */
255 require_once('../functions/url_parser.php');
257 $body_ary = explode("\n", $body);
259 for ($i=0; $i < count($body_ary); $i++
) {
260 $line = $body_ary[$i];
261 if (strlen($line) - 2 >= $wrap_at) {
262 sqWordWrap($line, $wrap_at);
264 $line = charset_decode($charset, $line);
265 $line = str_replace("\t", ' ', $line);
271 $j = strlen( $line );
273 while ( $pos < $j ) {
274 if ($line[$pos] == ' ') {
276 } else if (strpos($line, '>', $pos) === $pos) {
285 if (! isset($color[14])) {
286 $color[14] = '#FF0000';
288 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
290 if (! isset($color[13])) {
291 $color[13] = '#800000';
293 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
296 $body_ary[$i] = $line;
298 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
302 /* This returns a parsed string called $body. That string can then
303 be displayed as the actual message in the HTML. It contains
304 everything needed, including HTML Tags, Attachments at the
307 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
308 // this if statement checks for the entity to show as the
309 // primary message. To add more of them, just put them in the
310 // order that is their priority.
311 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
312 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
314 $has_unsafe_images= 0;
316 $urlmailbox = urlencode($mailbox);
317 $body_message = getEntity($message, $ent_num);
318 if (($body_message->header
->type0
== 'text') ||
319 ($body_message->header
->type0
== 'rfc822')) {
320 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
322 $body = decodeBody($body, $body_message->header
->encoding
);
323 $hookResults = do_hook("message_body", $body);
324 $body = $hookResults[1];
326 // If there are other types that shouldn't be formatted, add
328 if ($body_message->header
->type1
== 'html') {
329 if ( $show_html_default <> 1 ) {
330 $body = strip_tags( $body );
331 translateText($body, $wrap_at, $body_message->header
->charset
);
333 $body = magicHTML( $body, $id, $message, $mailbox );
336 translateText($body, $wrap_at, $body_message->header
->charset
);
339 if ($has_unsafe_images) {
340 if ($view_unsafe_images) {
341 $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";
343 $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";
351 function formatAttachments($message, $exclude_id, $mailbox, $id) {
352 global $where, $what;
353 global $startMessage, $color;
354 static $ShownHTML = 0;
356 $att_ar = $message->getAttachments($exclude_id);
358 if (!count($att_ar)) return '';
360 $attachments = "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
361 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
362 _("Attachments") . ':' .
363 "</B></TH></TR><TR><TD>\n" .
364 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";
366 $urlMailbox = urlencode($mailbox);
368 foreach ($att_ar as $att) {
370 $ent = urlencode($att->entity_id
);
371 $header = $att->header
;
372 $type0 = strtolower($header->type0
);
373 $type1 = strtolower($header->type1
);
375 if ($type0 =='message' && $type1 == 'rfc822') {
377 $filename = decodeHeader($header->subject
);
378 $display_filename = $filename;
381 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
382 if ($where && $what) {
383 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
385 $Links['download link']['text'] = _("download");
386 $Links['download link']['href'] =
387 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
390 /* this executes the attachment hook with a specific MIME-type.
391 * if that doens't have results, it tries if there's a rule
392 * for a more generic type. */
393 $HookResults = do_hook("attachment $type0/$type1", $Links,
394 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
395 if(count($HookResults[1]) <= 1) {
396 $HookResults = do_hook("attachment $type0/*", $Links,
397 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
398 $display_filename, $where, $what);
401 $Links = $HookResults[1];
402 $DefaultLink = $HookResults[6];
404 $attachments .= '<TR><TD> </TD><TD>' .
405 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
406 '<TD><SMALL><b>' . show_readable_size($header->size
) .
407 '</b> </small></TD>' .
408 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
410 $from_o = $header->from
;
411 if (is_object($from_o)) {
412 $from_name = $from_o->getAddress(false);
414 $from_name = _("Unknown sender");
416 $from_name = decodeHeader(htmlspecialchars($from_name));
417 $attachments .= '<b>' . $from_name . '</b>';
418 $attachments .= '</SMALL></TD><TD><SMALL> ';
421 foreach ($Links as $Val) {
425 $attachments .= ' | ';
427 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
431 $filename = decodeHeader($header->filename
);
432 if (trim($filename) == '') {
433 $name = decodeHeader($header->name
);
434 if (trim($name) == '') {
435 if ( trim( $header->id
) == '' )
436 $display_filename = 'untitled-[' . $ent . ']' ;
438 $display_filename = 'cid: ' . $header->id
;
440 $display_filename = $name;
444 $display_filename = $filename;
448 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
449 if ($where && $what) {
450 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
452 $Links['download link']['text'] = _("download");
453 $Links['download link']['href'] =
454 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
457 /* this executes the attachment hook with a specific MIME-type.
458 * if that doens't have results, it tries if there's a rule
459 * for a more generic type. */
460 $HookResults = do_hook("attachment $type0/$type1", $Links,
461 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
462 $display_filename, $where, $what);
463 if(count($HookResults[1]) <= 1) {
464 $HookResults = do_hook("attachment $type0/*", $Links,
465 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
466 $display_filename, $where, $what);
469 $Links = $HookResults[1];
470 $DefaultLink = $HookResults[6];
472 $attachments .= '<TR><TD> </TD><TD>' .
473 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
474 '<TD><SMALL><b>' . show_readable_size($header->size
) .
475 '</b> </small></TD>' .
476 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
478 if ($message->header
->description
) {
479 $attachments .= '<b>' . htmlspecialchars(_($header->description
)) . '</b>';
481 $attachments .= '</SMALL></TD><TD><SMALL> ';
484 foreach ($Links as $Val) {
488 $attachments .= ' | ';
490 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
497 $attachments .= "</SMALL></TD></TR>\n";
499 $attachments .= "</TABLE></TD></TR></TABLE>";
504 /** this function decodes the body depending on the encoding type. **/
505 function decodeBody($body, $encoding) {
506 $body = str_replace("\r\n", "\n", $body);
507 $encoding = strtolower($encoding);
509 global $show_html_default;
511 if ($encoding == 'quoted-printable' ||
512 $encoding == 'quoted_printable') {
513 $body = quoted_printable_decode($body);
515 while (ereg("=\n", $body))
516 $body = ereg_replace ("=\n", "", $body);
518 } else if ($encoding == 'base64') {
519 $body = base64_decode($body);
522 // All other encodings are returned raw.
527 * This functions decode strings that is encoded according to
528 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
529 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
531 function decodeHeader ($string, $utfencode=true) {
532 if (is_array($string)) {
533 $string = implode("\n", $string);
536 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
539 // Ignore white-space between consecutive encoded-words
540 if (strspn($res[2], " \t") != strlen($res[2])) {
544 if (ucfirst($res[4]) == 'B') {
545 $replace = base64_decode($res[5]);
547 $replace = str_replace('_', ' ', $res[5]);
548 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
550 /* Only encode into entities by default. Some places
551 don't need the encoding, like the compose form. */
553 $replace = charset_decode($res[3], $replace);
556 $string = $prefix . $replace . substr($string, strlen($res[0]));
557 $i = strlen($prefix) +
strlen($replace);
563 * Encode a string according to RFC 1522 for use in headers if it
564 * contains 8-bit characters or anything that looks like it should
567 function encodeHeader ($string) {
568 global $default_charset;
570 // Encode only if the string contains 8-bit characters or =?
571 $j = strlen( $string );
572 $l = strstr($string, '=?'); // Must be encoded ?
574 for( $i=0; $i < $j; ++
$i) {
575 switch( $string{$i} ) {
589 $k = ord( $string{$i} );
591 $ret .= sprintf("=%02X", $k);
599 $string = "=?$default_charset?Q?$ret?=";
605 /* This function trys to locate the entity_id of a specific mime element */
607 function find_ent_id( $id, $message ) {
609 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
610 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
611 $ret = find_ent_id( $id, $message->entities
[$i] );
613 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
614 $ret = $message->entities
[$i]->entity_id
;
621 ** HTMLFILTER ROUTINES
625 * This function returns the final tag out of the tag name, an array
626 * of attributes, and the type of the tag. This function is called by
627 * sq_sanitize internally.
629 * @param $tagname the name of the tag.
630 * @param $attary the array of attributes and their values
631 * @param $tagtype The type of the tag (see in comments).
632 * @return a string with the final tag representation.
634 function sq_tagprint($tagname, $attary, $tagtype){
637 $fulltag = '</' . $tagname . '>';
639 $fulltag = '<' . $tagname;
640 if (is_array($attary) && sizeof($attary)){
642 while (list($attname, $attvalue) = each($attary)){
643 array_push($atts, "$attname=$attvalue");
645 $fulltag .= ' ' . join(" ", $atts);
656 * A small helper function to use with array_walk. Modifies a by-ref
657 * value and makes it lowercase.
659 * @param $val a value passed by-ref.
660 * @return void since it modifies a by-ref value.
662 function sq_casenormalize(&$val){
663 $val = strtolower($val);
667 * This function skips any whitespace from the current position within
668 * a string and to the next non-whitespace value.
670 * @param $body the string
671 * @param $offset the offset within the string where we should start
672 * looking for the next non-whitespace character.
673 * @return the location within the $body where the next
674 * non-whitespace char is located.
676 function sq_skipspace($body, $offset){
677 $me = "sq_skipspace";
678 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
679 if (sizeof($matches{1})){
680 $count = strlen($matches{1});
687 * This function looks for the next character within a string. It's
688 * really just a glorified "strpos", except it catches if failures
691 * @param $body The string to look for needle in.
692 * @param $offset Start looking from this position.
693 * @param $needle The character/string to look for.
694 * @return location of the next occurance of the needle, or
695 * strlen($body) if needle wasn't found.
697 function sq_findnxstr($body, $offset, $needle){
698 $me = "sq_findnxstr";
699 $pos = strpos($body, $needle, $offset);
701 $pos = strlen($body);
707 * This function takes a PCRE-style regexp and tries to match it
710 * @param $body The string to look for needle in.
711 * @param $offset Start looking from here.
712 * @param $reg A PCRE-style regex to match.
713 * @return Returns a false if no matches found, or an array
714 * with the following members:
715 * - integer with the location of the match within $body
716 * - string with whatever content between offset and the match
717 * - string with whatever it is we matched
719 function sq_findnxreg($body, $offset, $reg){
720 $me = "sq_findnxreg";
723 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
727 $retarr{0} = $offset +
strlen($matches{1});
728 $retarr{1} = $matches{1};
729 $retarr{2} = $matches{2};
735 * This function looks for the next tag.
737 * @param $body String where to look for the next tag.
738 * @param $offset Start looking from here.
739 * @return false if no more tags exist in the body, or
740 * an array with the following members:
741 * - string with the name of the tag
742 * - array with attributes and their values
743 * - integer with tag type (1, 2, or 3)
744 * - integer where the tag starts (starting "<")
745 * - integer where the tag ends (ending ">")
746 * first three members will be false, if the tag is invalid.
748 function sq_getnxtag($body, $offset){
750 if ($offset > strlen($body)){
753 $lt = sq_findnxstr($body, $offset, "<");
754 if ($lt == strlen($body)){
759 * blah blah <tag attribute="value">
762 $pos = sq_skipspace($body, $lt+
1);
763 if ($pos >= strlen($body)){
764 return Array(false, false, false, $lt, strlen($body));
767 * There are 3 kinds of tags:
768 * 1. Opening tag, e.g.:
770 * 2. Closing tag, e.g.:
772 * 3. XHTML-style content-less tag, e.g.:
776 switch (substr($body, $pos, 1)){
783 * A comment or an SGML declaration.
785 if (substr($body, $pos+
1, 2) == "--"){
786 $gt = strpos($body, "-->", $pos);
792 return Array(false, false, false, $lt, $gt);
794 $gt = sq_findnxstr($body, $pos, ">");
795 return Array(false, false, false, $lt, $gt);
800 * Assume tagtype 1 for now. If it's type 3, we'll switch values
810 * Look for next [\W-_], which will indicate the end of the tag name.
812 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
813 if ($regary == false){
814 return Array(false, false, false, $lt, strlen($body));
816 list($pos, $tagname, $match) = $regary;
817 $tagname = strtolower($tagname);
820 * $match can be either of these:
821 * '>' indicating the end of the tag entirely.
822 * '\s' indicating the end of the tag name.
823 * '/' indicating that this is type-3 xhtml tag.
825 * Whatever else we find there indicates an invalid tag.
830 * This is an xhtml-style tag with a closing / at the
831 * end, like so: <img src="blah"/>. Check if it's followed
832 * by the closing bracket. If not, then this tag is invalid
834 if (substr($body, $pos, 2) == "/>"){
838 $gt = sq_findnxstr($body, $pos, ">");
839 $retary = Array(false, false, false, $lt, $gt);
843 return Array($tagname, false, $tagtype, $lt, $pos);
847 * Check if it's whitespace
849 if (preg_match("/\s/", $match)){
852 * This is an invalid tag! Look for the next closing ">".
854 $gt = sq_findnxstr($body, $offset, ">");
855 return Array(false, false, false, $lt, $gt);
860 * At this point we're here:
861 * <tagname attribute='blah'>
864 * At this point we loop in order to find all attributes.
870 while ($pos <= strlen($body)){
871 $pos = sq_skipspace($body, $pos);
872 if ($pos == strlen($body)){
876 return Array(false, false, false, $lt, $pos);
879 * See if we arrived at a ">" or "/>", which means that we reached
880 * the end of the tag.
883 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
887 $pos +
= strlen($matches{1});
888 if ($matches{2} == "/>"){
892 return Array($tagname, $attary, $tagtype, $lt, $pos);
896 * There are several types of attributes, with optional
897 * [:space:] between members.
899 * attrname[:space:]=[:space:]'CDATA'
901 * attrname[:space:]=[:space:]"CDATA"
903 * attr[:space:]=[:space:]CDATA
907 * We leave types 1 and 2 the same, type 3 we check for
908 * '"' and convert to """ if needed, then wrap in
909 * double quotes. Type 4 we convert into:
912 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
913 if ($regary == false){
915 * Looks like body ended before the end of tag.
917 return Array(false, false, false, $lt, strlen($body));
919 list($pos, $attname, $match) = $regary;
920 $attname = strtolower($attname);
922 * We arrived at the end of attribute name. Several things possible
924 * '>' means the end of the tag and this is attribute type 4
925 * '/' if followed by '>' means the same thing as above
926 * '\s' means a lot of things -- look what it's followed by.
927 * anything else means the attribute is invalid.
932 * This is an xhtml-style tag with a closing / at the
933 * end, like so: <img src="blah"/>. Check if it's followed
934 * by the closing bracket. If not, then this tag is invalid
936 if (substr($body, $pos, 2) == "/>"){
940 $gt = sq_findnxstr($body, $pos, ">");
941 $retary = Array(false, false, false, $lt, $gt);
945 $attary{$attname} = '"yes"';
946 return Array($tagname, $attary, $tagtype, $lt, $pos);
950 * Skip whitespace and see what we arrive at.
952 $pos = sq_skipspace($body, $pos);
953 $char = substr($body, $pos, 1);
955 * Two things are valid here:
956 * '=' means this is attribute type 1 2 or 3.
957 * \w means this was attribute type 4.
958 * anything else we ignore and re-loop. End of tag and
959 * invalid stuff will be caught by our checks at the beginning
964 $pos = sq_skipspace($body, $pos);
966 * Here are 3 possibilities:
967 * "'" attribute type 1
968 * '"' attribute type 2
969 * everything else is the content of tag type 3
971 $quot = substr($body, $pos, 1);
973 $regary = sq_findnxreg($body, $pos+
1, "\'");
974 if ($regary == false){
975 return Array(false, false, false, $lt, strlen($body));
977 list($pos, $attval, $match) = $regary;
979 $attary{$attname} = "'" . $attval . "'";
980 } else if ($quot == '"'){
981 $regary = sq_findnxreg($body, $pos+
1, '\"');
982 if ($regary == false){
983 return Array(false, false, false, $lt, strlen($body));
985 list($pos, $attval, $match) = $regary;
987 $attary{$attname} = '"' . $attval . '"';
990 * These are hateful. Look for \s, or >.
992 $regary = sq_findnxreg($body, $pos, "[\s>]");
993 if ($regary == false){
994 return Array(false, false, false, $lt, strlen($body));
996 list($pos, $attval, $match) = $regary;
998 * If it's ">" it will be caught at the top.
1000 $attval = preg_replace("/\"/s", """, $attval);
1001 $attary{$attname} = '"' . $attval . '"';
1003 } else if (preg_match("|[\w/>]|", $char)) {
1005 * That was attribute type 4.
1007 $attary{$attname} = '"yes"';
1010 * An illegal character. Find next '>' and return.
1012 $gt = sq_findnxstr($body, $pos, ">");
1013 return Array(false, false, false, $lt, $gt);
1018 * The fact that we got here indicates that the tag end was never
1019 * found. Return invalid tag indication so it gets stripped.
1021 return Array(false, false, false, $lt, strlen($body));
1025 * This function checks attribute values for entity-encoded values
1026 * and returns them translated into 8-bit strings so we can run
1029 * @param $attvalue A string to run entity check against.
1030 * @return Translated value.
1032 function sq_deent($attvalue){
1035 * See if we have to run the checks first. All entities must start
1038 if (strpos($attvalue, "&") === false){
1042 * Check named entities first.
1044 $trans = get_html_translation_table(HTML_ENTITIES
);
1046 * Leave " in, as it can mess us up.
1048 $trans = array_flip($trans);
1049 unset($trans{"""});
1050 while (list($ent, $val) = each($trans)){
1051 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1054 * Now translate numbered entities from 1 to 255 if needed.
1056 if (strpos($attvalue, "#") !== false){
1057 $omit = Array(34, 39);
1058 for ($asc=1; $asc<256; $asc++
){
1059 if (!in_array($asc, $omit)){
1061 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1063 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1064 "$chr\\1", $attvalue);
1072 * This function runs various checks against the attributes.
1074 * @param $tagname String with the name of the tag.
1075 * @param $attary Array with all tag attributes.
1076 * @param $rm_attnames See description for sq_sanitize
1077 * @param $bad_attvals See description for sq_sanitize
1078 * @param $add_attr_to_tag See description for sq_sanitize
1079 * @param $message message object
1080 * @param $id message id
1081 * @return Array with modified attributes.
1083 function sq_fixatts($tagname,
1093 while (list($attname, $attvalue) = each($attary)){
1095 * See if this attribute should be removed.
1097 foreach ($rm_attnames as $matchtag=>$matchattrs){
1098 if (preg_match($matchtag, $tagname)){
1099 foreach ($matchattrs as $matchattr){
1100 if (preg_match($matchattr, $attname)){
1101 unset($attary{$attname});
1108 * Remove any entities.
1110 $attvalue = sq_deent($attvalue);
1113 * Now let's run checks on the attvalues.
1114 * I don't expect anyone to comprehend this. If you do,
1115 * get in touch with me so I can drive to where you live and
1116 * shake your hand personally. :)
1118 foreach ($bad_attvals as $matchtag=>$matchattrs){
1119 if (preg_match($matchtag, $tagname)){
1120 foreach ($matchattrs as $matchattr=>$valary){
1121 if (preg_match($matchattr, $attname)){
1123 * There are two arrays in valary.
1125 * Second one is replacements
1127 list($valmatch, $valrepl) = $valary;
1129 preg_replace($valmatch, $valrepl, $attvalue);
1130 if ($newvalue != $attvalue){
1131 $attary{$attname} = $newvalue;
1138 * Turn cid: urls into http-friendly ones.
1140 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1141 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1145 * See if we need to append any attributes to this tag.
1147 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1148 if (preg_match($matchtag, $tagname)){
1149 $attary = array_merge($attary, $addattary);
1156 * This function edits the style definition to make them friendly and
1157 * usable in squirrelmail.
1159 * @param $message the message object
1160 * @param $id the message id
1161 * @param $content a string with whatever is between <style> and </style>
1162 * @return a string with edited content.
1164 function sq_fixstyle($message, $id, $content){
1165 global $view_unsafe_images;
1166 $me = "sq_fixstyle";
1168 * First look for general BODY style declaration, which would be
1170 * body {background: blah-blah}
1171 * and change it to .bodyclass so we can just assign it to a <div>
1173 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1174 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1176 * Fix url('blah') declarations.
1178 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1179 "url(\\1$secremoveimg\\2)", $content);
1181 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1184 if (!$view_unsafe_images){
1185 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1186 "url(\\1$secremoveimg\\2)", $content);
1190 * Fix urls that refer to cid:
1192 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1194 $cidurl = $matches{1};
1195 $httpurl = sq_cid2http($message, $id, $cidurl);
1196 $content = preg_replace("|url\($cidurl\)|si",
1197 "url($httpurl)", $content);
1201 * Fix stupid css declarations which lead to vulnerabilities
1204 $match = Array('/expression/si',
1207 $replace = Array('idiocy', 'idiocy', 'idiocy');
1208 $content = preg_replace($match, $replace, $content);
1213 * This function converts cid: url's into the ones that can be viewed in
1216 * @param $message the message object
1217 * @param $id the message id
1218 * @param $cidurl the cid: url.
1219 * @return a string with a http-friendly url
1221 function sq_cid2http($message, $id, $cidurl, $mailbox){
1223 * Get rid of quotes.
1225 $quotchar = substr($cidurl, 0, 1);
1226 $cidurl = str_replace($quotchar, "", $cidurl);
1227 $cidurl = substr(trim($cidurl), 4);
1228 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1229 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1230 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1235 * This function changes the <body> tag into a <div> tag since we
1236 * can't really have a body-within-body.
1238 * @param $attary an array of attributes and values of <body>
1239 * @return a modified array of attributes to be set for <div>
1241 function sq_body2div($attary){
1242 $me = "sq_body2div";
1243 $divattary = Array("class"=>"'bodyclass'");
1247 if (is_array($attary) && sizeof($attary) > 0){
1248 foreach ($attary as $attname=>$attvalue){
1249 $quotchar = substr($attvalue, 0, 1);
1250 $attvalue = str_replace($quotchar, "", $attvalue);
1253 $styledef .= "background-image: url('$attvalue'); ";
1256 $styledef .= "background-color: $attvalue; ";
1259 $styledef .= "color: $attvalue; ";
1262 if (strlen($styledef) > 0){
1263 $divattary{"style"} = "\"$styledef\"";
1270 * This is the main function and the one you should actually be calling.
1271 * There are several variables you should be aware of an which need
1272 * special description.
1274 * Since the description is quite lengthy, see it here:
1275 * http://www.mricon.com/html/phpfilter.html
1277 * @param $body the string with HTML you wish to filter
1278 * @param $tag_list see description above
1279 * @param $rm_tags_with_content see description above
1280 * @param $self_closing_tags see description above
1281 * @param $force_tag_closing see description above
1282 * @param $rm_attnames see description above
1283 * @param $bad_attvals see description above
1284 * @param $add_attr_to_tag see description above
1285 * @param $message message object
1286 * @param $id message id
1287 * @return sanitized html safe to show on your pages.
1289 function sq_sanitize($body,
1291 $rm_tags_with_content,
1301 $me = "sq_sanitize";
1303 * Normalize rm_tags and rm_tags_with_content.
1305 @array_walk
($rm_tags, 'sq_casenormalize');
1306 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1307 @array_walk
($self_closing_tags, 'sq_casenormalize');
1309 * See if tag_list is of tags to remove or tags to allow.
1310 * false means remove these tags
1311 * true means allow these tags
1313 $rm_tags = array_shift($tag_list);
1315 $open_tags = Array();
1316 $trusted = "<!-- begin sanitized html -->\n";
1317 $skip_content = false;
1319 * Take care of netscape's stupid javascript entities like
1322 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1324 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1325 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1326 $free_content = substr($body, $curpos, $lt-$curpos);
1328 * Take care of <style>
1330 if ($tagname == "style" && $tagtype == 2){
1332 * This is a closing </style>. Edit the
1333 * content before we apply it.
1335 $free_content = sq_fixstyle($message, $id, $free_content);
1337 if ($skip_content == false){
1338 $trusted .= $free_content;
1341 if ($tagname != FALSE){
1343 if ($skip_content == $tagname){
1345 * Got to the end of tag we needed to remove.
1348 $skip_content = false;
1350 if ($skip_content == false){
1351 if ($tagname == "body"){
1354 if (isset($open_tags{$tagname}) &&
1355 $open_tags{$tagname} > 0){
1356 $open_tags{$tagname}--;
1366 * $rm_tags_with_content
1368 if ($skip_content == false){
1370 * See if this is a self-closing type and change
1371 * tagtype appropriately.
1374 && in_array($tagname, $self_closing_tags)){
1378 * See if we should skip this tag and any content
1381 if ($tagtype == 1 &&
1382 in_array($tagname, $rm_tags_with_content)){
1383 $skip_content = $tagname;
1385 if (($rm_tags == false
1386 && in_array($tagname, $tag_list)) ||
1387 ($rm_tags == true &&
1388 !in_array($tagname, $tag_list))){
1392 if (isset($open_tags{$tagname})){
1393 $open_tags{$tagname}++
;
1395 $open_tags{$tagname}=1;
1399 * This is where we run other checks.
1401 if (is_array($attary) && sizeof($attary) > 0){
1402 $attary = sq_fixatts($tagname,
1413 * Convert body into div.
1415 if ($tagname == "body"){
1417 $attary = sq_body2div($attary, $message, $id);
1424 if ($tagname != false && $skip_content == false){
1425 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1431 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1432 if ($force_tag_closing == true){
1433 foreach ($open_tags as $tagname=>$opentimes){
1434 while ($opentimes > 0){
1435 $trusted .= '</' . $tagname . '>';
1441 $trusted .= "<!-- end sanitized html -->\n";
1446 * This is a wrapper function to call html sanitizing routines.
1448 * @param $body the body of the message
1449 * @param $id the id of the message
1450 * @return a string with html safe to display in the browser.
1452 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1453 global $attachment_common_show_images, $view_unsafe_images,
1456 * Don't display attached images in HTML mode.
1458 $attachment_common_show_images = false;
1469 $rm_tags_with_content = Array(
1476 $self_closing_tags = Array(
1483 $force_tag_closing = false;
1485 $rm_attnames = Array(
1495 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1496 $bad_attvals = Array(
1499 "/^src|background/i" =>
1502 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1503 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1504 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1505 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1508 "\\1$secremoveimg\\2",
1509 "\\1$secremoveimg\\2",
1510 "\\1$secremoveimg\\2",
1511 "\\1$secremoveimg\\2"
1514 "/^href|action/i" =>
1517 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1518 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1519 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1520 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1535 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1536 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1537 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1538 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1552 if (!$view_unsafe_images){
1554 * Remove any references to http/https if view_unsafe_images set
1557 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1558 '/^([\'\"])\s*https*:.*([\'\"])/si');
1559 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1560 "\\1$secremoveimg\\2");
1561 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1562 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1563 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1564 "url(\\1$secremoveimg\\2)");
1567 $add_attr_to_tag = Array(
1568 "/^a$/si" => Array('target'=>'"_new"')
1570 $trusted = sq_sanitize($body,
1572 $rm_tags_with_content,
1582 if (preg_match("|$secremoveimg|si", $trusted)){
1583 $has_unsafe_images = true;