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 ]----------------------------------------------------------- */
197 * Checks to see if $message contains content of type $type0/$type1
198 * returns the first entity number it finds of that type, or NULL if
199 * none is found. Takes optional argument $start to allow the caller
200 * to continue where they left off
202 function findDisplayEntity($message, $type0, $type1, $start=0) {
204 for ($i = $start;isset($message->entities
[$i]); $i++
) {
205 $entity = $message->entities
[$i];
206 if ($entity->type0
== $type0 && $entity->type1
== $type1) {
213 // This is here for debugging purposese. It will print out a list
214 // of all the entity IDs that are in the $message object.
216 function listEntities ($message) {
218 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
219 for ($i = 0;isset($message->entities
[$i]); $i++
) {
221 $msg = listEntities($message->entities
[$i]);
231 function getPriorityStr($priority) {
232 $priority_level = substr($priority,0,1);
234 switch($priority_level) {
235 /* check for a higher then normal priority. */
238 $priority_string = _("High");
241 /* check for a lower then normal priority. */
244 $priority_string = _("Low");
247 /* check for a normal priority. */
250 $priority_level = '3';
251 $priority_string = _("Normal");
255 return $priority_string;
258 /* returns a $message object for a particular entity id */
259 function getEntity ($message, $ent_id) {
260 return $message->getEntity($ent_id);
265 * Extracted from strings.php 23/03/2002
268 function translateText(&$body, $wrap_at, $charset) {
269 global $where, $what; /* from searching */
270 global $color; /* color theme */
272 require_once('../functions/url_parser.php');
274 $body_ary = explode("\n", $body);
276 for ($i=0; $i < count($body_ary); $i++
) {
277 $line = $body_ary[$i];
278 if (strlen($line) - 2 >= $wrap_at) {
279 sqWordWrap($line, $wrap_at);
281 $line = charset_decode($charset, $line);
282 $line = str_replace("\t", ' ', $line);
288 $j = strlen( $line );
290 while ( $pos < $j ) {
291 if ($line[$pos] == ' ') {
293 } else if (strpos($line, '>', $pos) === $pos) {
302 if (! isset($color[14])) {
303 $color[14] = '#FF0000';
305 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
307 if (! isset($color[13])) {
308 $color[13] = '#800000';
310 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
313 $body_ary[$i] = $line;
315 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
319 /* This returns a parsed string called $body. That string can then
320 be displayed as the actual message in the HTML. It contains
321 everything needed, including HTML Tags, Attachments at the
324 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
325 // this if statement checks for the entity to show as the
326 // primary message. To add more of them, just put them in the
327 // order that is their priority.
328 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
329 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
331 $has_unsafe_images= 0;
333 $urlmailbox = urlencode($mailbox);
334 $body_message = getEntity($message, $ent_num);
335 if (($body_message->header
->type0
== 'text') ||
336 ($body_message->header
->type0
== 'rfc822')) {
337 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
338 $body = decodeBody($body, $body_message->header
->encoding
);
339 $hookResults = do_hook("message_body", $body);
340 $body = $hookResults[1];
342 // If there are other types that shouldn't be formatted, add
344 if ($body_message->header
->type1
== 'html') {
345 if ( $show_html_default <> 1 ) {
346 $body = strip_tags( $body );
347 translateText($body, $wrap_at,
348 $body_message->header
->getParameter
['charset']);
350 $body = magicHTML( $body, $id, $message, $mailbox );
353 translateText($body, $wrap_at,
354 $body_message->header
->getParameter('charset'));
357 if ($has_unsafe_images) {
358 if ($view_unsafe_images) {
359 $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";
361 $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";
369 function formatAttachments($message, $exclude_id, $mailbox, $id) {
370 global $where, $what;
371 global $startMessage, $color;
372 static $ShownHTML = 0;
374 $att_ar = $message->getAttachments($exclude_id);
376 if (!count($att_ar)) return '';
378 $attachments = "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
379 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
380 _("Attachments") . ':' .
381 "</B></TH></TR><TR><TD>\n" .
382 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";
384 $urlMailbox = urlencode($mailbox);
386 foreach ($att_ar as $att) {
388 $ent = urldecode($att->entity_id
);
389 $header = $att->header
;
390 $type0 = strtolower($header->type0
);
391 $type1 = strtolower($header->type1
);
393 if ($type0 =='message' && $type1 == 'rfc822') {
394 $rfc822_header = $att->rfc822_header
;
395 $filename = decodeHeader($rfc822_header->subject
);
396 $display_filename = $filename;
399 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
400 if ($where && $what) {
401 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
403 $Links['download link']['text'] = _("download");
404 $Links['download link']['href'] =
405 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
408 /* this executes the attachment hook with a specific MIME-type.
409 * if that doens't have results, it tries if there's a rule
410 * for a more generic type. */
411 $HookResults = do_hook("attachment $type0/$type1", $Links,
412 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
413 if(count($HookResults[1]) <= 1) {
414 $HookResults = do_hook("attachment $type0/*", $Links,
415 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
416 $display_filename, $where, $what);
419 $Links = $HookResults[1];
420 $DefaultLink = $HookResults[6];
422 $attachments .= '<TR><TD> </TD><TD>' .
423 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
424 '<TD><SMALL><b>' . show_readable_size($header->size
) .
425 '</b> </small></TD>' .
426 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
428 $from_o = $rfc822_header->from
;
429 if (is_object($from_o)) {
430 $from_name = $from_o->getAddress(false);
432 $from_name = _("Unknown sender");
434 $from_name = decodeHeader(htmlspecialchars($from_name));
435 $attachments .= '<b>' . $from_name . '</b>';
436 $attachments .= '</SMALL></TD><TD><SMALL> ';
439 foreach ($Links as $Val) {
443 $attachments .= ' | ';
445 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
449 $filename = decodeHeader($header->getParameter('filename'));
450 if (trim($filename) == '') {
451 $name = decodeHeader($header->getParameter('name'));
452 if (trim($name) == '') {
453 if ( trim( $header->id
) == '' )
454 $display_filename = 'untitled-[' . $ent . ']' ;
456 $display_filename = 'cid: ' . $header->id
;
458 $display_filename = $name;
462 $display_filename = $filename;
466 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
467 if ($where && $what) {
468 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
470 $Links['download link']['text'] = _("download");
471 $Links['download link']['href'] =
472 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
475 /* this executes the attachment hook with a specific MIME-type.
476 * if that doens't have results, it tries if there's a rule
477 * for a more generic type. */
478 $HookResults = do_hook("attachment $type0/$type1", $Links,
479 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
480 $display_filename, $where, $what);
481 if(count($HookResults[1]) <= 1) {
482 $HookResults = do_hook("attachment $type0/*", $Links,
483 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
484 $display_filename, $where, $what);
487 $Links = $HookResults[1];
488 $DefaultLink = $HookResults[6];
490 $attachments .= '<TR><TD> </TD><TD>' .
491 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
492 '<TD><SMALL><b>' . show_readable_size($header->size
) .
493 '</b> </small></TD>' .
494 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
496 if ($message->header
->description
) {
497 $attachments .= '<b>' . htmlspecialchars(_($header->description
)) . '</b>';
499 $attachments .= '</SMALL></TD><TD><SMALL> ';
502 foreach ($Links as $Val) {
506 $attachments .= ' | ';
508 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
515 $attachments .= "</SMALL></TD></TR>\n";
517 $attachments .= "</TABLE></TD></TR></TABLE>";
522 /** this function decodes the body depending on the encoding type. **/
523 function decodeBody($body, $encoding) {
524 $body = str_replace("\r\n", "\n", $body);
525 $encoding = strtolower($encoding);
527 global $show_html_default;
529 if ($encoding == 'quoted-printable' ||
530 $encoding == 'quoted_printable') {
531 $body = quoted_printable_decode($body);
533 while (ereg("=\n", $body))
534 $body = ereg_replace ("=\n", "", $body);
536 } else if ($encoding == 'base64') {
537 $body = base64_decode($body);
540 // All other encodings are returned raw.
545 * This functions decode strings that is encoded according to
546 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
547 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
549 function decodeHeader ($string, $utfencode=true) {
550 if (is_array($string)) {
551 $string = implode("\n", $string);
554 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
557 // Ignore white-space between consecutive encoded-words
558 if (strspn($res[2], " \t") != strlen($res[2])) {
562 if (ucfirst($res[4]) == 'B') {
563 $replace = base64_decode($res[5]);
565 $replace = str_replace('_', ' ', $res[5]);
566 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
568 /* Only encode into entities by default. Some places
569 don't need the encoding, like the compose form. */
571 $replace = charset_decode($res[3], $replace);
574 $string = $prefix . $replace . substr($string, strlen($res[0]));
575 $i = strlen($prefix) +
strlen($replace);
581 * Encode a string according to RFC 1522 for use in headers if it
582 * contains 8-bit characters or anything that looks like it should
585 function encodeHeader ($string) {
586 global $default_charset;
588 // Encode only if the string contains 8-bit characters or =?
589 $j = strlen( $string );
590 $l = strstr($string, '=?'); // Must be encoded ?
592 for( $i=0; $i < $j; ++
$i) {
593 switch( $string{$i} ) {
607 $k = ord( $string{$i} );
609 $ret .= sprintf("=%02X", $k);
617 $string = "=?$default_charset?Q?$ret?=";
623 /* This function trys to locate the entity_id of a specific mime element */
625 function find_ent_id( $id, $message ) {
627 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
628 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
629 $ret = find_ent_id( $id, $message->entities
[$i] );
631 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
632 $ret = $message->entities
[$i]->entity_id
;
639 ** HTMLFILTER ROUTINES
643 * This function returns the final tag out of the tag name, an array
644 * of attributes, and the type of the tag. This function is called by
645 * sq_sanitize internally.
647 * @param $tagname the name of the tag.
648 * @param $attary the array of attributes and their values
649 * @param $tagtype The type of the tag (see in comments).
650 * @return a string with the final tag representation.
652 function sq_tagprint($tagname, $attary, $tagtype){
655 $fulltag = '</' . $tagname . '>';
657 $fulltag = '<' . $tagname;
658 if (is_array($attary) && sizeof($attary)){
660 while (list($attname, $attvalue) = each($attary)){
661 array_push($atts, "$attname=$attvalue");
663 $fulltag .= ' ' . join(" ", $atts);
674 * A small helper function to use with array_walk. Modifies a by-ref
675 * value and makes it lowercase.
677 * @param $val a value passed by-ref.
678 * @return void since it modifies a by-ref value.
680 function sq_casenormalize(&$val){
681 $val = strtolower($val);
685 * This function skips any whitespace from the current position within
686 * a string and to the next non-whitespace value.
688 * @param $body the string
689 * @param $offset the offset within the string where we should start
690 * looking for the next non-whitespace character.
691 * @return the location within the $body where the next
692 * non-whitespace char is located.
694 function sq_skipspace($body, $offset){
695 $me = "sq_skipspace";
696 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
697 if (sizeof($matches{1})){
698 $count = strlen($matches{1});
705 * This function looks for the next character within a string. It's
706 * really just a glorified "strpos", except it catches if failures
709 * @param $body The string to look for needle in.
710 * @param $offset Start looking from this position.
711 * @param $needle The character/string to look for.
712 * @return location of the next occurance of the needle, or
713 * strlen($body) if needle wasn't found.
715 function sq_findnxstr($body, $offset, $needle){
716 $me = "sq_findnxstr";
717 $pos = strpos($body, $needle, $offset);
719 $pos = strlen($body);
725 * This function takes a PCRE-style regexp and tries to match it
728 * @param $body The string to look for needle in.
729 * @param $offset Start looking from here.
730 * @param $reg A PCRE-style regex to match.
731 * @return Returns a false if no matches found, or an array
732 * with the following members:
733 * - integer with the location of the match within $body
734 * - string with whatever content between offset and the match
735 * - string with whatever it is we matched
737 function sq_findnxreg($body, $offset, $reg){
738 $me = "sq_findnxreg";
741 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
745 $retarr{0} = $offset +
strlen($matches{1});
746 $retarr{1} = $matches{1};
747 $retarr{2} = $matches{2};
753 * This function looks for the next tag.
755 * @param $body String where to look for the next tag.
756 * @param $offset Start looking from here.
757 * @return false if no more tags exist in the body, or
758 * an array with the following members:
759 * - string with the name of the tag
760 * - array with attributes and their values
761 * - integer with tag type (1, 2, or 3)
762 * - integer where the tag starts (starting "<")
763 * - integer where the tag ends (ending ">")
764 * first three members will be false, if the tag is invalid.
766 function sq_getnxtag($body, $offset){
768 if ($offset > strlen($body)){
771 $lt = sq_findnxstr($body, $offset, "<");
772 if ($lt == strlen($body)){
777 * blah blah <tag attribute="value">
780 $pos = sq_skipspace($body, $lt+
1);
781 if ($pos >= strlen($body)){
782 return Array(false, false, false, $lt, strlen($body));
785 * There are 3 kinds of tags:
786 * 1. Opening tag, e.g.:
788 * 2. Closing tag, e.g.:
790 * 3. XHTML-style content-less tag, e.g.:
794 switch (substr($body, $pos, 1)){
801 * A comment or an SGML declaration.
803 if (substr($body, $pos+
1, 2) == "--"){
804 $gt = strpos($body, "-->", $pos);
810 return Array(false, false, false, $lt, $gt);
812 $gt = sq_findnxstr($body, $pos, ">");
813 return Array(false, false, false, $lt, $gt);
818 * Assume tagtype 1 for now. If it's type 3, we'll switch values
828 * Look for next [\W-_], which will indicate the end of the tag name.
830 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
831 if ($regary == false){
832 return Array(false, false, false, $lt, strlen($body));
834 list($pos, $tagname, $match) = $regary;
835 $tagname = strtolower($tagname);
838 * $match can be either of these:
839 * '>' indicating the end of the tag entirely.
840 * '\s' indicating the end of the tag name.
841 * '/' indicating that this is type-3 xhtml tag.
843 * Whatever else we find there indicates an invalid tag.
848 * This is an xhtml-style tag with a closing / at the
849 * end, like so: <img src="blah"/>. Check if it's followed
850 * by the closing bracket. If not, then this tag is invalid
852 if (substr($body, $pos, 2) == "/>"){
856 $gt = sq_findnxstr($body, $pos, ">");
857 $retary = Array(false, false, false, $lt, $gt);
861 return Array($tagname, false, $tagtype, $lt, $pos);
865 * Check if it's whitespace
867 if (preg_match("/\s/", $match)){
870 * This is an invalid tag! Look for the next closing ">".
872 $gt = sq_findnxstr($body, $offset, ">");
873 return Array(false, false, false, $lt, $gt);
878 * At this point we're here:
879 * <tagname attribute='blah'>
882 * At this point we loop in order to find all attributes.
888 while ($pos <= strlen($body)){
889 $pos = sq_skipspace($body, $pos);
890 if ($pos == strlen($body)){
894 return Array(false, false, false, $lt, $pos);
897 * See if we arrived at a ">" or "/>", which means that we reached
898 * the end of the tag.
901 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
905 $pos +
= strlen($matches{1});
906 if ($matches{2} == "/>"){
910 return Array($tagname, $attary, $tagtype, $lt, $pos);
914 * There are several types of attributes, with optional
915 * [:space:] between members.
917 * attrname[:space:]=[:space:]'CDATA'
919 * attrname[:space:]=[:space:]"CDATA"
921 * attr[:space:]=[:space:]CDATA
925 * We leave types 1 and 2 the same, type 3 we check for
926 * '"' and convert to """ if needed, then wrap in
927 * double quotes. Type 4 we convert into:
930 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
931 if ($regary == false){
933 * Looks like body ended before the end of tag.
935 return Array(false, false, false, $lt, strlen($body));
937 list($pos, $attname, $match) = $regary;
938 $attname = strtolower($attname);
940 * We arrived at the end of attribute name. Several things possible
942 * '>' means the end of the tag and this is attribute type 4
943 * '/' if followed by '>' means the same thing as above
944 * '\s' means a lot of things -- look what it's followed by.
945 * anything else means the attribute is invalid.
950 * This is an xhtml-style tag with a closing / at the
951 * end, like so: <img src="blah"/>. Check if it's followed
952 * by the closing bracket. If not, then this tag is invalid
954 if (substr($body, $pos, 2) == "/>"){
958 $gt = sq_findnxstr($body, $pos, ">");
959 $retary = Array(false, false, false, $lt, $gt);
963 $attary{$attname} = '"yes"';
964 return Array($tagname, $attary, $tagtype, $lt, $pos);
968 * Skip whitespace and see what we arrive at.
970 $pos = sq_skipspace($body, $pos);
971 $char = substr($body, $pos, 1);
973 * Two things are valid here:
974 * '=' means this is attribute type 1 2 or 3.
975 * \w means this was attribute type 4.
976 * anything else we ignore and re-loop. End of tag and
977 * invalid stuff will be caught by our checks at the beginning
982 $pos = sq_skipspace($body, $pos);
984 * Here are 3 possibilities:
985 * "'" attribute type 1
986 * '"' attribute type 2
987 * everything else is the content of tag type 3
989 $quot = substr($body, $pos, 1);
991 $regary = sq_findnxreg($body, $pos+
1, "\'");
992 if ($regary == false){
993 return Array(false, false, false, $lt, strlen($body));
995 list($pos, $attval, $match) = $regary;
997 $attary{$attname} = "'" . $attval . "'";
998 } else if ($quot == '"'){
999 $regary = sq_findnxreg($body, $pos+
1, '\"');
1000 if ($regary == false){
1001 return Array(false, false, false, $lt, strlen($body));
1003 list($pos, $attval, $match) = $regary;
1005 $attary{$attname} = '"' . $attval . '"';
1008 * These are hateful. Look for \s, or >.
1010 $regary = sq_findnxreg($body, $pos, "[\s>]");
1011 if ($regary == false){
1012 return Array(false, false, false, $lt, strlen($body));
1014 list($pos, $attval, $match) = $regary;
1016 * If it's ">" it will be caught at the top.
1018 $attval = preg_replace("/\"/s", """, $attval);
1019 $attary{$attname} = '"' . $attval . '"';
1021 } else if (preg_match("|[\w/>]|", $char)) {
1023 * That was attribute type 4.
1025 $attary{$attname} = '"yes"';
1028 * An illegal character. Find next '>' and return.
1030 $gt = sq_findnxstr($body, $pos, ">");
1031 return Array(false, false, false, $lt, $gt);
1036 * The fact that we got here indicates that the tag end was never
1037 * found. Return invalid tag indication so it gets stripped.
1039 return Array(false, false, false, $lt, strlen($body));
1043 * This function checks attribute values for entity-encoded values
1044 * and returns them translated into 8-bit strings so we can run
1047 * @param $attvalue A string to run entity check against.
1048 * @return Translated value.
1050 function sq_deent($attvalue){
1053 * See if we have to run the checks first. All entities must start
1056 if (strpos($attvalue, "&") === false){
1060 * Check named entities first.
1062 $trans = get_html_translation_table(HTML_ENTITIES
);
1064 * Leave " in, as it can mess us up.
1066 $trans = array_flip($trans);
1067 unset($trans{"""});
1068 while (list($ent, $val) = each($trans)){
1069 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1072 * Now translate numbered entities from 1 to 255 if needed.
1074 if (strpos($attvalue, "#") !== false){
1075 $omit = Array(34, 39);
1076 for ($asc=1; $asc<256; $asc++
){
1077 if (!in_array($asc, $omit)){
1079 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1081 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1082 "$chr\\1", $attvalue);
1090 * This function runs various checks against the attributes.
1092 * @param $tagname String with the name of the tag.
1093 * @param $attary Array with all tag attributes.
1094 * @param $rm_attnames See description for sq_sanitize
1095 * @param $bad_attvals See description for sq_sanitize
1096 * @param $add_attr_to_tag See description for sq_sanitize
1097 * @param $message message object
1098 * @param $id message id
1099 * @return Array with modified attributes.
1101 function sq_fixatts($tagname,
1111 while (list($attname, $attvalue) = each($attary)){
1113 * See if this attribute should be removed.
1115 foreach ($rm_attnames as $matchtag=>$matchattrs){
1116 if (preg_match($matchtag, $tagname)){
1117 foreach ($matchattrs as $matchattr){
1118 if (preg_match($matchattr, $attname)){
1119 unset($attary{$attname});
1126 * Remove any entities.
1128 $attvalue = sq_deent($attvalue);
1131 * Now let's run checks on the attvalues.
1132 * I don't expect anyone to comprehend this. If you do,
1133 * get in touch with me so I can drive to where you live and
1134 * shake your hand personally. :)
1136 foreach ($bad_attvals as $matchtag=>$matchattrs){
1137 if (preg_match($matchtag, $tagname)){
1138 foreach ($matchattrs as $matchattr=>$valary){
1139 if (preg_match($matchattr, $attname)){
1141 * There are two arrays in valary.
1143 * Second one is replacements
1145 list($valmatch, $valrepl) = $valary;
1147 preg_replace($valmatch, $valrepl, $attvalue);
1148 if ($newvalue != $attvalue){
1149 $attary{$attname} = $newvalue;
1156 * Turn cid: urls into http-friendly ones.
1158 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1159 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1163 * See if we need to append any attributes to this tag.
1165 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1166 if (preg_match($matchtag, $tagname)){
1167 $attary = array_merge($attary, $addattary);
1174 * This function edits the style definition to make them friendly and
1175 * usable in squirrelmail.
1177 * @param $message the message object
1178 * @param $id the message id
1179 * @param $content a string with whatever is between <style> and </style>
1180 * @return a string with edited content.
1182 function sq_fixstyle($message, $id, $content){
1183 global $view_unsafe_images;
1184 $me = "sq_fixstyle";
1186 * First look for general BODY style declaration, which would be
1188 * body {background: blah-blah}
1189 * and change it to .bodyclass so we can just assign it to a <div>
1191 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1192 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1194 * Fix url('blah') declarations.
1196 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1197 "url(\\1$secremoveimg\\2)", $content);
1199 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1202 if (!$view_unsafe_images){
1203 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1204 "url(\\1$secremoveimg\\2)", $content);
1208 * Fix urls that refer to cid:
1210 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1212 $cidurl = $matches{1};
1213 $httpurl = sq_cid2http($message, $id, $cidurl);
1214 $content = preg_replace("|url\($cidurl\)|si",
1215 "url($httpurl)", $content);
1219 * Fix stupid css declarations which lead to vulnerabilities
1222 $match = Array('/expression/si',
1225 $replace = Array('idiocy', 'idiocy', 'idiocy');
1226 $content = preg_replace($match, $replace, $content);
1231 * This function converts cid: url's into the ones that can be viewed in
1234 * @param $message the message object
1235 * @param $id the message id
1236 * @param $cidurl the cid: url.
1237 * @return a string with a http-friendly url
1239 function sq_cid2http($message, $id, $cidurl, $mailbox){
1241 * Get rid of quotes.
1243 $quotchar = substr($cidurl, 0, 1);
1244 $cidurl = str_replace($quotchar, "", $cidurl);
1245 $cidurl = substr(trim($cidurl), 4);
1246 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1247 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1248 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1253 * This function changes the <body> tag into a <div> tag since we
1254 * can't really have a body-within-body.
1256 * @param $attary an array of attributes and values of <body>
1257 * @return a modified array of attributes to be set for <div>
1259 function sq_body2div($attary){
1260 $me = "sq_body2div";
1261 $divattary = Array("class"=>"'bodyclass'");
1265 if (is_array($attary) && sizeof($attary) > 0){
1266 foreach ($attary as $attname=>$attvalue){
1267 $quotchar = substr($attvalue, 0, 1);
1268 $attvalue = str_replace($quotchar, "", $attvalue);
1271 $styledef .= "background-image: url('$attvalue'); ";
1274 $styledef .= "background-color: $attvalue; ";
1277 $styledef .= "color: $attvalue; ";
1280 if (strlen($styledef) > 0){
1281 $divattary{"style"} = "\"$styledef\"";
1288 * This is the main function and the one you should actually be calling.
1289 * There are several variables you should be aware of an which need
1290 * special description.
1292 * Since the description is quite lengthy, see it here:
1293 * http://www.mricon.com/html/phpfilter.html
1295 * @param $body the string with HTML you wish to filter
1296 * @param $tag_list see description above
1297 * @param $rm_tags_with_content see description above
1298 * @param $self_closing_tags see description above
1299 * @param $force_tag_closing see description above
1300 * @param $rm_attnames see description above
1301 * @param $bad_attvals see description above
1302 * @param $add_attr_to_tag see description above
1303 * @param $message message object
1304 * @param $id message id
1305 * @return sanitized html safe to show on your pages.
1307 function sq_sanitize($body,
1309 $rm_tags_with_content,
1319 $me = "sq_sanitize";
1321 * Normalize rm_tags and rm_tags_with_content.
1323 @array_walk
($rm_tags, 'sq_casenormalize');
1324 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1325 @array_walk
($self_closing_tags, 'sq_casenormalize');
1327 * See if tag_list is of tags to remove or tags to allow.
1328 * false means remove these tags
1329 * true means allow these tags
1331 $rm_tags = array_shift($tag_list);
1333 $open_tags = Array();
1334 $trusted = "<!-- begin sanitized html -->\n";
1335 $skip_content = false;
1337 * Take care of netscape's stupid javascript entities like
1340 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1342 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1343 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1344 $free_content = substr($body, $curpos, $lt-$curpos);
1346 * Take care of <style>
1348 if ($tagname == "style" && $tagtype == 2){
1350 * This is a closing </style>. Edit the
1351 * content before we apply it.
1353 $free_content = sq_fixstyle($message, $id, $free_content);
1355 if ($skip_content == false){
1356 $trusted .= $free_content;
1359 if ($tagname != FALSE){
1361 if ($skip_content == $tagname){
1363 * Got to the end of tag we needed to remove.
1366 $skip_content = false;
1368 if ($skip_content == false){
1369 if ($tagname == "body"){
1372 if (isset($open_tags{$tagname}) &&
1373 $open_tags{$tagname} > 0){
1374 $open_tags{$tagname}--;
1384 * $rm_tags_with_content
1386 if ($skip_content == false){
1388 * See if this is a self-closing type and change
1389 * tagtype appropriately.
1392 && in_array($tagname, $self_closing_tags)){
1396 * See if we should skip this tag and any content
1399 if ($tagtype == 1 &&
1400 in_array($tagname, $rm_tags_with_content)){
1401 $skip_content = $tagname;
1403 if (($rm_tags == false
1404 && in_array($tagname, $tag_list)) ||
1405 ($rm_tags == true &&
1406 !in_array($tagname, $tag_list))){
1410 if (isset($open_tags{$tagname})){
1411 $open_tags{$tagname}++
;
1413 $open_tags{$tagname}=1;
1417 * This is where we run other checks.
1419 if (is_array($attary) && sizeof($attary) > 0){
1420 $attary = sq_fixatts($tagname,
1431 * Convert body into div.
1433 if ($tagname == "body"){
1435 $attary = sq_body2div($attary, $message, $id);
1442 if ($tagname != false && $skip_content == false){
1443 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1449 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1450 if ($force_tag_closing == true){
1451 foreach ($open_tags as $tagname=>$opentimes){
1452 while ($opentimes > 0){
1453 $trusted .= '</' . $tagname . '>';
1459 $trusted .= "<!-- end sanitized html -->\n";
1464 * This is a wrapper function to call html sanitizing routines.
1466 * @param $body the body of the message
1467 * @param $id the id of the message
1468 * @return a string with html safe to display in the browser.
1470 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1471 global $attachment_common_show_images, $view_unsafe_images,
1474 * Don't display attached images in HTML mode.
1476 $attachment_common_show_images = false;
1487 $rm_tags_with_content = Array(
1494 $self_closing_tags = Array(
1501 $force_tag_closing = false;
1503 $rm_attnames = Array(
1513 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1514 $bad_attvals = Array(
1517 "/^src|background/i" =>
1520 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1521 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1522 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1523 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1526 "\\1$secremoveimg\\2",
1527 "\\1$secremoveimg\\2",
1528 "\\1$secremoveimg\\2",
1529 "\\1$secremoveimg\\2"
1532 "/^href|action/i" =>
1535 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1536 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1537 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1538 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1553 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1554 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1555 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1556 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1570 if (!$view_unsafe_images){
1572 * Remove any references to http/https if view_unsafe_images set
1575 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1576 '/^([\'\"])\s*https*:.*([\'\"])/si');
1577 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1578 "\\1$secremoveimg\\2");
1579 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1580 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1581 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1582 "url(\\1$secremoveimg\\2)");
1585 $add_attr_to_tag = Array(
1586 "/^a$/si" => Array('target'=>'"_new"')
1588 $trusted = sq_sanitize($body,
1590 $rm_tags_with_content,
1600 if (preg_match("|$secremoveimg|si", $trusted)){
1601 $has_unsafe_images = true;