cc44fd614057601606a8223410faab163ef7b4f2
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);
321 $body = decodeBody($body, $body_message->header
->encoding
);
322 $hookResults = do_hook("message_body", $body);
323 $body = $hookResults[1];
325 // If there are other types that shouldn't be formatted, add
327 if ($body_message->header
->type1
== 'html') {
328 if ( $show_html_default <> 1 ) {
329 $body = strip_tags( $body );
330 translateText($body, $wrap_at,
331 $body_message->header
->getParameter
['charset']);
333 $body = magicHTML( $body, $id, $message, $mailbox );
336 translateText($body, $wrap_at,
337 $body_message->header
->getParameter('charset'));
340 if ($has_unsafe_images) {
341 if ($view_unsafe_images) {
342 $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";
344 $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";
352 function formatAttachments($message, $exclude_id, $mailbox, $id) {
353 global $where, $what;
354 global $startMessage, $color;
355 static $ShownHTML = 0;
357 $att_ar = $message->getAttachments($exclude_id);
359 if (!count($att_ar)) return '';
361 $attachments = "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
362 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
363 _("Attachments") . ':' .
364 "</B></TH></TR><TR><TD>\n" .
365 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";
367 $urlMailbox = urlencode($mailbox);
369 foreach ($att_ar as $att) {
371 $ent = urldecode($att->entity_id
);
372 $header = $att->header
;
373 $type0 = strtolower($header->type0
);
374 $type1 = strtolower($header->type1
);
376 if ($type0 =='message' && $type1 == 'rfc822') {
377 $rfc822_header = $att->rfc822_header
;
378 $filename = decodeHeader($rfc822_header->subject
);
379 $display_filename = $filename;
382 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
383 if ($where && $what) {
384 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
386 $Links['download link']['text'] = _("download");
387 $Links['download link']['href'] =
388 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
391 /* this executes the attachment hook with a specific MIME-type.
392 * if that doens't have results, it tries if there's a rule
393 * for a more generic type. */
394 $HookResults = do_hook("attachment $type0/$type1", $Links,
395 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
396 if(count($HookResults[1]) <= 1) {
397 $HookResults = do_hook("attachment $type0/*", $Links,
398 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
399 $display_filename, $where, $what);
402 $Links = $HookResults[1];
403 $DefaultLink = $HookResults[6];
405 $attachments .= '<TR><TD> </TD><TD>' .
406 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
407 '<TD><SMALL><b>' . show_readable_size($header->size
) .
408 '</b> </small></TD>' .
409 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
411 $from_o = $rfc822_header->from
;
412 if (is_object($from_o)) {
413 $from_name = $from_o->getAddress(false);
415 $from_name = _("Unknown sender");
417 $from_name = decodeHeader(htmlspecialchars($from_name));
418 $attachments .= '<b>' . $from_name . '</b>';
419 $attachments .= '</SMALL></TD><TD><SMALL> ';
422 foreach ($Links as $Val) {
426 $attachments .= ' | ';
428 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
432 $filename = decodeHeader($header->getParameter('filename'));
433 if (trim($filename) == '') {
434 $name = decodeHeader($header->getParameter('name'));
435 if (trim($name) == '') {
436 if ( trim( $header->id
) == '' )
437 $display_filename = 'untitled-[' . $ent . ']' ;
439 $display_filename = 'cid: ' . $header->id
;
441 $display_filename = $name;
445 $display_filename = $filename;
449 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
450 if ($where && $what) {
451 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
453 $Links['download link']['text'] = _("download");
454 $Links['download link']['href'] =
455 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
458 /* this executes the attachment hook with a specific MIME-type.
459 * if that doens't have results, it tries if there's a rule
460 * for a more generic type. */
461 $HookResults = do_hook("attachment $type0/$type1", $Links,
462 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
463 $display_filename, $where, $what);
464 if(count($HookResults[1]) <= 1) {
465 $HookResults = do_hook("attachment $type0/*", $Links,
466 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
467 $display_filename, $where, $what);
470 $Links = $HookResults[1];
471 $DefaultLink = $HookResults[6];
473 $attachments .= '<TR><TD> </TD><TD>' .
474 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
475 '<TD><SMALL><b>' . show_readable_size($header->size
) .
476 '</b> </small></TD>' .
477 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
479 if ($message->header
->description
) {
480 $attachments .= '<b>' . htmlspecialchars(_($header->description
)) . '</b>';
482 $attachments .= '</SMALL></TD><TD><SMALL> ';
485 foreach ($Links as $Val) {
489 $attachments .= ' | ';
491 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
498 $attachments .= "</SMALL></TD></TR>\n";
500 $attachments .= "</TABLE></TD></TR></TABLE>";
505 /** this function decodes the body depending on the encoding type. **/
506 function decodeBody($body, $encoding) {
507 $body = str_replace("\r\n", "\n", $body);
508 $encoding = strtolower($encoding);
510 global $show_html_default;
512 if ($encoding == 'quoted-printable' ||
513 $encoding == 'quoted_printable') {
514 $body = quoted_printable_decode($body);
516 while (ereg("=\n", $body))
517 $body = ereg_replace ("=\n", "", $body);
519 } else if ($encoding == 'base64') {
520 $body = base64_decode($body);
523 // All other encodings are returned raw.
528 * This functions decode strings that is encoded according to
529 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
530 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
532 function decodeHeader ($string, $utfencode=true) {
533 if (is_array($string)) {
534 $string = implode("\n", $string);
537 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
540 // Ignore white-space between consecutive encoded-words
541 if (strspn($res[2], " \t") != strlen($res[2])) {
545 if (ucfirst($res[4]) == 'B') {
546 $replace = base64_decode($res[5]);
548 $replace = str_replace('_', ' ', $res[5]);
549 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
551 /* Only encode into entities by default. Some places
552 don't need the encoding, like the compose form. */
554 $replace = charset_decode($res[3], $replace);
557 $string = $prefix . $replace . substr($string, strlen($res[0]));
558 $i = strlen($prefix) +
strlen($replace);
564 * Encode a string according to RFC 1522 for use in headers if it
565 * contains 8-bit characters or anything that looks like it should
568 function encodeHeader ($string) {
569 global $default_charset;
571 // Encode only if the string contains 8-bit characters or =?
572 $j = strlen( $string );
573 $l = strstr($string, '=?'); // Must be encoded ?
575 for( $i=0; $i < $j; ++
$i) {
576 switch( $string{$i} ) {
590 $k = ord( $string{$i} );
592 $ret .= sprintf("=%02X", $k);
600 $string = "=?$default_charset?Q?$ret?=";
606 /* This function trys to locate the entity_id of a specific mime element */
608 function find_ent_id( $id, $message ) {
610 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
611 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
612 $ret = find_ent_id( $id, $message->entities
[$i] );
614 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
615 $ret = $message->entities
[$i]->entity_id
;
622 ** HTMLFILTER ROUTINES
626 * This function returns the final tag out of the tag name, an array
627 * of attributes, and the type of the tag. This function is called by
628 * sq_sanitize internally.
630 * @param $tagname the name of the tag.
631 * @param $attary the array of attributes and their values
632 * @param $tagtype The type of the tag (see in comments).
633 * @return a string with the final tag representation.
635 function sq_tagprint($tagname, $attary, $tagtype){
638 $fulltag = '</' . $tagname . '>';
640 $fulltag = '<' . $tagname;
641 if (is_array($attary) && sizeof($attary)){
643 while (list($attname, $attvalue) = each($attary)){
644 array_push($atts, "$attname=$attvalue");
646 $fulltag .= ' ' . join(" ", $atts);
657 * A small helper function to use with array_walk. Modifies a by-ref
658 * value and makes it lowercase.
660 * @param $val a value passed by-ref.
661 * @return void since it modifies a by-ref value.
663 function sq_casenormalize(&$val){
664 $val = strtolower($val);
668 * This function skips any whitespace from the current position within
669 * a string and to the next non-whitespace value.
671 * @param $body the string
672 * @param $offset the offset within the string where we should start
673 * looking for the next non-whitespace character.
674 * @return the location within the $body where the next
675 * non-whitespace char is located.
677 function sq_skipspace($body, $offset){
678 $me = "sq_skipspace";
679 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
680 if (sizeof($matches{1})){
681 $count = strlen($matches{1});
688 * This function looks for the next character within a string. It's
689 * really just a glorified "strpos", except it catches if failures
692 * @param $body The string to look for needle in.
693 * @param $offset Start looking from this position.
694 * @param $needle The character/string to look for.
695 * @return location of the next occurance of the needle, or
696 * strlen($body) if needle wasn't found.
698 function sq_findnxstr($body, $offset, $needle){
699 $me = "sq_findnxstr";
700 $pos = strpos($body, $needle, $offset);
702 $pos = strlen($body);
708 * This function takes a PCRE-style regexp and tries to match it
711 * @param $body The string to look for needle in.
712 * @param $offset Start looking from here.
713 * @param $reg A PCRE-style regex to match.
714 * @return Returns a false if no matches found, or an array
715 * with the following members:
716 * - integer with the location of the match within $body
717 * - string with whatever content between offset and the match
718 * - string with whatever it is we matched
720 function sq_findnxreg($body, $offset, $reg){
721 $me = "sq_findnxreg";
724 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
728 $retarr{0} = $offset +
strlen($matches{1});
729 $retarr{1} = $matches{1};
730 $retarr{2} = $matches{2};
736 * This function looks for the next tag.
738 * @param $body String where to look for the next tag.
739 * @param $offset Start looking from here.
740 * @return false if no more tags exist in the body, or
741 * an array with the following members:
742 * - string with the name of the tag
743 * - array with attributes and their values
744 * - integer with tag type (1, 2, or 3)
745 * - integer where the tag starts (starting "<")
746 * - integer where the tag ends (ending ">")
747 * first three members will be false, if the tag is invalid.
749 function sq_getnxtag($body, $offset){
751 if ($offset > strlen($body)){
754 $lt = sq_findnxstr($body, $offset, "<");
755 if ($lt == strlen($body)){
760 * blah blah <tag attribute="value">
763 $pos = sq_skipspace($body, $lt+
1);
764 if ($pos >= strlen($body)){
765 return Array(false, false, false, $lt, strlen($body));
768 * There are 3 kinds of tags:
769 * 1. Opening tag, e.g.:
771 * 2. Closing tag, e.g.:
773 * 3. XHTML-style content-less tag, e.g.:
777 switch (substr($body, $pos, 1)){
784 * A comment or an SGML declaration.
786 if (substr($body, $pos+
1, 2) == "--"){
787 $gt = strpos($body, "-->", $pos);
793 return Array(false, false, false, $lt, $gt);
795 $gt = sq_findnxstr($body, $pos, ">");
796 return Array(false, false, false, $lt, $gt);
801 * Assume tagtype 1 for now. If it's type 3, we'll switch values
811 * Look for next [\W-_], which will indicate the end of the tag name.
813 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
814 if ($regary == false){
815 return Array(false, false, false, $lt, strlen($body));
817 list($pos, $tagname, $match) = $regary;
818 $tagname = strtolower($tagname);
821 * $match can be either of these:
822 * '>' indicating the end of the tag entirely.
823 * '\s' indicating the end of the tag name.
824 * '/' indicating that this is type-3 xhtml tag.
826 * Whatever else we find there indicates an invalid tag.
831 * This is an xhtml-style tag with a closing / at the
832 * end, like so: <img src="blah"/>. Check if it's followed
833 * by the closing bracket. If not, then this tag is invalid
835 if (substr($body, $pos, 2) == "/>"){
839 $gt = sq_findnxstr($body, $pos, ">");
840 $retary = Array(false, false, false, $lt, $gt);
844 return Array($tagname, false, $tagtype, $lt, $pos);
848 * Check if it's whitespace
850 if (preg_match("/\s/", $match)){
853 * This is an invalid tag! Look for the next closing ">".
855 $gt = sq_findnxstr($body, $offset, ">");
856 return Array(false, false, false, $lt, $gt);
861 * At this point we're here:
862 * <tagname attribute='blah'>
865 * At this point we loop in order to find all attributes.
871 while ($pos <= strlen($body)){
872 $pos = sq_skipspace($body, $pos);
873 if ($pos == strlen($body)){
877 return Array(false, false, false, $lt, $pos);
880 * See if we arrived at a ">" or "/>", which means that we reached
881 * the end of the tag.
884 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
888 $pos +
= strlen($matches{1});
889 if ($matches{2} == "/>"){
893 return Array($tagname, $attary, $tagtype, $lt, $pos);
897 * There are several types of attributes, with optional
898 * [:space:] between members.
900 * attrname[:space:]=[:space:]'CDATA'
902 * attrname[:space:]=[:space:]"CDATA"
904 * attr[:space:]=[:space:]CDATA
908 * We leave types 1 and 2 the same, type 3 we check for
909 * '"' and convert to """ if needed, then wrap in
910 * double quotes. Type 4 we convert into:
913 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
914 if ($regary == false){
916 * Looks like body ended before the end of tag.
918 return Array(false, false, false, $lt, strlen($body));
920 list($pos, $attname, $match) = $regary;
921 $attname = strtolower($attname);
923 * We arrived at the end of attribute name. Several things possible
925 * '>' means the end of the tag and this is attribute type 4
926 * '/' if followed by '>' means the same thing as above
927 * '\s' means a lot of things -- look what it's followed by.
928 * anything else means the attribute is invalid.
933 * This is an xhtml-style tag with a closing / at the
934 * end, like so: <img src="blah"/>. Check if it's followed
935 * by the closing bracket. If not, then this tag is invalid
937 if (substr($body, $pos, 2) == "/>"){
941 $gt = sq_findnxstr($body, $pos, ">");
942 $retary = Array(false, false, false, $lt, $gt);
946 $attary{$attname} = '"yes"';
947 return Array($tagname, $attary, $tagtype, $lt, $pos);
951 * Skip whitespace and see what we arrive at.
953 $pos = sq_skipspace($body, $pos);
954 $char = substr($body, $pos, 1);
956 * Two things are valid here:
957 * '=' means this is attribute type 1 2 or 3.
958 * \w means this was attribute type 4.
959 * anything else we ignore and re-loop. End of tag and
960 * invalid stuff will be caught by our checks at the beginning
965 $pos = sq_skipspace($body, $pos);
967 * Here are 3 possibilities:
968 * "'" attribute type 1
969 * '"' attribute type 2
970 * everything else is the content of tag type 3
972 $quot = substr($body, $pos, 1);
974 $regary = sq_findnxreg($body, $pos+
1, "\'");
975 if ($regary == false){
976 return Array(false, false, false, $lt, strlen($body));
978 list($pos, $attval, $match) = $regary;
980 $attary{$attname} = "'" . $attval . "'";
981 } else if ($quot == '"'){
982 $regary = sq_findnxreg($body, $pos+
1, '\"');
983 if ($regary == false){
984 return Array(false, false, false, $lt, strlen($body));
986 list($pos, $attval, $match) = $regary;
988 $attary{$attname} = '"' . $attval . '"';
991 * These are hateful. Look for \s, or >.
993 $regary = sq_findnxreg($body, $pos, "[\s>]");
994 if ($regary == false){
995 return Array(false, false, false, $lt, strlen($body));
997 list($pos, $attval, $match) = $regary;
999 * If it's ">" it will be caught at the top.
1001 $attval = preg_replace("/\"/s", """, $attval);
1002 $attary{$attname} = '"' . $attval . '"';
1004 } else if (preg_match("|[\w/>]|", $char)) {
1006 * That was attribute type 4.
1008 $attary{$attname} = '"yes"';
1011 * An illegal character. Find next '>' and return.
1013 $gt = sq_findnxstr($body, $pos, ">");
1014 return Array(false, false, false, $lt, $gt);
1019 * The fact that we got here indicates that the tag end was never
1020 * found. Return invalid tag indication so it gets stripped.
1022 return Array(false, false, false, $lt, strlen($body));
1026 * This function checks attribute values for entity-encoded values
1027 * and returns them translated into 8-bit strings so we can run
1030 * @param $attvalue A string to run entity check against.
1031 * @return Translated value.
1033 function sq_deent($attvalue){
1036 * See if we have to run the checks first. All entities must start
1039 if (strpos($attvalue, "&") === false){
1043 * Check named entities first.
1045 $trans = get_html_translation_table(HTML_ENTITIES
);
1047 * Leave " in, as it can mess us up.
1049 $trans = array_flip($trans);
1050 unset($trans{"""});
1051 while (list($ent, $val) = each($trans)){
1052 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1055 * Now translate numbered entities from 1 to 255 if needed.
1057 if (strpos($attvalue, "#") !== false){
1058 $omit = Array(34, 39);
1059 for ($asc=1; $asc<256; $asc++
){
1060 if (!in_array($asc, $omit)){
1062 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1064 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1065 "$chr\\1", $attvalue);
1073 * This function runs various checks against the attributes.
1075 * @param $tagname String with the name of the tag.
1076 * @param $attary Array with all tag attributes.
1077 * @param $rm_attnames See description for sq_sanitize
1078 * @param $bad_attvals See description for sq_sanitize
1079 * @param $add_attr_to_tag See description for sq_sanitize
1080 * @param $message message object
1081 * @param $id message id
1082 * @return Array with modified attributes.
1084 function sq_fixatts($tagname,
1094 while (list($attname, $attvalue) = each($attary)){
1096 * See if this attribute should be removed.
1098 foreach ($rm_attnames as $matchtag=>$matchattrs){
1099 if (preg_match($matchtag, $tagname)){
1100 foreach ($matchattrs as $matchattr){
1101 if (preg_match($matchattr, $attname)){
1102 unset($attary{$attname});
1109 * Remove any entities.
1111 $attvalue = sq_deent($attvalue);
1114 * Now let's run checks on the attvalues.
1115 * I don't expect anyone to comprehend this. If you do,
1116 * get in touch with me so I can drive to where you live and
1117 * shake your hand personally. :)
1119 foreach ($bad_attvals as $matchtag=>$matchattrs){
1120 if (preg_match($matchtag, $tagname)){
1121 foreach ($matchattrs as $matchattr=>$valary){
1122 if (preg_match($matchattr, $attname)){
1124 * There are two arrays in valary.
1126 * Second one is replacements
1128 list($valmatch, $valrepl) = $valary;
1130 preg_replace($valmatch, $valrepl, $attvalue);
1131 if ($newvalue != $attvalue){
1132 $attary{$attname} = $newvalue;
1139 * Turn cid: urls into http-friendly ones.
1141 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1142 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1146 * See if we need to append any attributes to this tag.
1148 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1149 if (preg_match($matchtag, $tagname)){
1150 $attary = array_merge($attary, $addattary);
1157 * This function edits the style definition to make them friendly and
1158 * usable in squirrelmail.
1160 * @param $message the message object
1161 * @param $id the message id
1162 * @param $content a string with whatever is between <style> and </style>
1163 * @return a string with edited content.
1165 function sq_fixstyle($message, $id, $content){
1166 global $view_unsafe_images;
1167 $me = "sq_fixstyle";
1169 * First look for general BODY style declaration, which would be
1171 * body {background: blah-blah}
1172 * and change it to .bodyclass so we can just assign it to a <div>
1174 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1175 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1177 * Fix url('blah') declarations.
1179 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1180 "url(\\1$secremoveimg\\2)", $content);
1182 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1185 if (!$view_unsafe_images){
1186 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1187 "url(\\1$secremoveimg\\2)", $content);
1191 * Fix urls that refer to cid:
1193 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1195 $cidurl = $matches{1};
1196 $httpurl = sq_cid2http($message, $id, $cidurl);
1197 $content = preg_replace("|url\($cidurl\)|si",
1198 "url($httpurl)", $content);
1202 * Fix stupid css declarations which lead to vulnerabilities
1205 $match = Array('/expression/si',
1208 $replace = Array('idiocy', 'idiocy', 'idiocy');
1209 $content = preg_replace($match, $replace, $content);
1214 * This function converts cid: url's into the ones that can be viewed in
1217 * @param $message the message object
1218 * @param $id the message id
1219 * @param $cidurl the cid: url.
1220 * @return a string with a http-friendly url
1222 function sq_cid2http($message, $id, $cidurl, $mailbox){
1224 * Get rid of quotes.
1226 $quotchar = substr($cidurl, 0, 1);
1227 $cidurl = str_replace($quotchar, "", $cidurl);
1228 $cidurl = substr(trim($cidurl), 4);
1229 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1230 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1231 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1236 * This function changes the <body> tag into a <div> tag since we
1237 * can't really have a body-within-body.
1239 * @param $attary an array of attributes and values of <body>
1240 * @return a modified array of attributes to be set for <div>
1242 function sq_body2div($attary){
1243 $me = "sq_body2div";
1244 $divattary = Array("class"=>"'bodyclass'");
1248 if (is_array($attary) && sizeof($attary) > 0){
1249 foreach ($attary as $attname=>$attvalue){
1250 $quotchar = substr($attvalue, 0, 1);
1251 $attvalue = str_replace($quotchar, "", $attvalue);
1254 $styledef .= "background-image: url('$attvalue'); ";
1257 $styledef .= "background-color: $attvalue; ";
1260 $styledef .= "color: $attvalue; ";
1263 if (strlen($styledef) > 0){
1264 $divattary{"style"} = "\"$styledef\"";
1271 * This is the main function and the one you should actually be calling.
1272 * There are several variables you should be aware of an which need
1273 * special description.
1275 * Since the description is quite lengthy, see it here:
1276 * http://www.mricon.com/html/phpfilter.html
1278 * @param $body the string with HTML you wish to filter
1279 * @param $tag_list see description above
1280 * @param $rm_tags_with_content see description above
1281 * @param $self_closing_tags see description above
1282 * @param $force_tag_closing see description above
1283 * @param $rm_attnames see description above
1284 * @param $bad_attvals see description above
1285 * @param $add_attr_to_tag see description above
1286 * @param $message message object
1287 * @param $id message id
1288 * @return sanitized html safe to show on your pages.
1290 function sq_sanitize($body,
1292 $rm_tags_with_content,
1302 $me = "sq_sanitize";
1304 * Normalize rm_tags and rm_tags_with_content.
1306 @array_walk
($rm_tags, 'sq_casenormalize');
1307 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1308 @array_walk
($self_closing_tags, 'sq_casenormalize');
1310 * See if tag_list is of tags to remove or tags to allow.
1311 * false means remove these tags
1312 * true means allow these tags
1314 $rm_tags = array_shift($tag_list);
1316 $open_tags = Array();
1317 $trusted = "<!-- begin sanitized html -->\n";
1318 $skip_content = false;
1320 * Take care of netscape's stupid javascript entities like
1323 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1325 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1326 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1327 $free_content = substr($body, $curpos, $lt-$curpos);
1329 * Take care of <style>
1331 if ($tagname == "style" && $tagtype == 2){
1333 * This is a closing </style>. Edit the
1334 * content before we apply it.
1336 $free_content = sq_fixstyle($message, $id, $free_content);
1338 if ($skip_content == false){
1339 $trusted .= $free_content;
1342 if ($tagname != FALSE){
1344 if ($skip_content == $tagname){
1346 * Got to the end of tag we needed to remove.
1349 $skip_content = false;
1351 if ($skip_content == false){
1352 if ($tagname == "body"){
1355 if (isset($open_tags{$tagname}) &&
1356 $open_tags{$tagname} > 0){
1357 $open_tags{$tagname}--;
1367 * $rm_tags_with_content
1369 if ($skip_content == false){
1371 * See if this is a self-closing type and change
1372 * tagtype appropriately.
1375 && in_array($tagname, $self_closing_tags)){
1379 * See if we should skip this tag and any content
1382 if ($tagtype == 1 &&
1383 in_array($tagname, $rm_tags_with_content)){
1384 $skip_content = $tagname;
1386 if (($rm_tags == false
1387 && in_array($tagname, $tag_list)) ||
1388 ($rm_tags == true &&
1389 !in_array($tagname, $tag_list))){
1393 if (isset($open_tags{$tagname})){
1394 $open_tags{$tagname}++
;
1396 $open_tags{$tagname}=1;
1400 * This is where we run other checks.
1402 if (is_array($attary) && sizeof($attary) > 0){
1403 $attary = sq_fixatts($tagname,
1414 * Convert body into div.
1416 if ($tagname == "body"){
1418 $attary = sq_body2div($attary, $message, $id);
1425 if ($tagname != false && $skip_content == false){
1426 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1432 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1433 if ($force_tag_closing == true){
1434 foreach ($open_tags as $tagname=>$opentimes){
1435 while ($opentimes > 0){
1436 $trusted .= '</' . $tagname . '>';
1442 $trusted .= "<!-- end sanitized html -->\n";
1447 * This is a wrapper function to call html sanitizing routines.
1449 * @param $body the body of the message
1450 * @param $id the id of the message
1451 * @return a string with html safe to display in the browser.
1453 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1454 global $attachment_common_show_images, $view_unsafe_images,
1457 * Don't display attached images in HTML mode.
1459 $attachment_common_show_images = false;
1470 $rm_tags_with_content = Array(
1477 $self_closing_tags = Array(
1484 $force_tag_closing = false;
1486 $rm_attnames = Array(
1496 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1497 $bad_attvals = Array(
1500 "/^src|background/i" =>
1503 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1504 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1505 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1506 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1509 "\\1$secremoveimg\\2",
1510 "\\1$secremoveimg\\2",
1511 "\\1$secremoveimg\\2",
1512 "\\1$secremoveimg\\2"
1515 "/^href|action/i" =>
1518 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1519 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1520 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1521 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1536 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1537 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1538 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1539 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1553 if (!$view_unsafe_images){
1555 * Remove any references to http/https if view_unsafe_images set
1558 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1559 '/^([\'\"])\s*https*:.*([\'\"])/si');
1560 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1561 "\\1$secremoveimg\\2");
1562 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1563 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1564 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1565 "url(\\1$secremoveimg\\2)");
1568 $add_attr_to_tag = Array(
1569 "/^a$/si" => Array('target'=>'"_new"')
1571 $trusted = sq_sanitize($body,
1573 $rm_tags_with_content,
1583 if (preg_match("|$secremoveimg|si", $trusted)){
1584 $has_unsafe_images = true;