d4ac2e735dc1639724de9841082f4e1cec96fdca
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 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
167 echo decodeBody($body, $encoding);
170 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
173 $read = fgets ($imap_stream,8192);
176 // This could be bad -- if the section has sqimap_session_id() . ' OK'
177 // or similar, it will kill the download.
178 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
179 if (trim($read) == ')==') {
181 $read = fgets ($imap_stream,4096);
182 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
185 echo decodeBody($read1, $encoding) .
186 decodeBody($read, $encoding);
189 echo decodeBody($read, $encoding);
191 $read = fgets ($imap_stream,4096);
198 /* -[ END MIME DECODING ]----------------------------------------------------------- */
201 * Checks to see if $message contains content of type $type0/$type1
202 * returns the first entity number it finds of that type, or NULL if
203 * none is found. Takes optional argument $start to allow the caller
204 * to continue where they left off
206 function findDisplayEntity($message, $type0, $type1, $start=0) {
208 for ($i = $start;isset($message->entities
[$i]); $i++
) {
209 $entity = $message->entities
[$i];
210 if ($entity->type0
== $type0 && $entity->type1
== $type1) {
218 // This is here for debugging purposese. It will print out a list
219 // of all the entity IDs that are in the $message object.
221 function listEntities ($message) {
223 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
224 for ($i = 0;isset($message->entities
[$i]); $i++
) {
226 $msg = listEntities($message->entities
[$i]);
236 function getPriorityStr($priority) {
237 $priority_level = substr($priority,0,1);
239 switch($priority_level) {
240 /* check for a higher then normal priority. */
243 $priority_string = _("High");
246 /* check for a lower then normal priority. */
249 $priority_string = _("Low");
252 /* check for a normal priority. */
255 $priority_level = '3';
256 $priority_string = _("Normal");
260 return $priority_string;
263 /* returns a $message object for a particular entity id */
264 function getEntity ($message, $ent_id) {
265 return $message->getEntity($ent_id);
270 * Extracted from strings.php 23/03/2002
273 function translateText(&$body, $wrap_at, $charset) {
274 global $where, $what; /* from searching */
275 global $color; /* color theme */
277 require_once('../functions/url_parser.php');
279 $body_ary = explode("\n", $body);
281 for ($i=0; $i < count($body_ary); $i++
) {
282 $line = $body_ary[$i];
283 if (strlen($line) - 2 >= $wrap_at) {
284 sqWordWrap($line, $wrap_at);
286 $line = charset_decode($charset, $line);
287 $line = str_replace("\t", ' ', $line);
293 $j = strlen( $line );
295 while ( $pos < $j ) {
296 if ($line[$pos] == ' ') {
298 } else if (strpos($line, '>', $pos) === $pos) {
307 if (! isset($color[14])) {
308 $color[14] = '#FF0000';
310 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
312 if (! isset($color[13])) {
313 $color[13] = '#800000';
315 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
318 $body_ary[$i] = $line;
320 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
324 /* This returns a parsed string called $body. That string can then
325 be displayed as the actual message in the HTML. It contains
326 everything needed, including HTML Tags, Attachments at the
329 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
330 // this if statement checks for the entity to show as the
331 // primary message. To add more of them, just put them in the
332 // order that is their priority.
333 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
334 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
336 $has_unsafe_images= 0;
338 $urlmailbox = urlencode($mailbox);
339 $body_message = getEntity($message, $ent_num);
340 if (($body_message->header
->type0
== 'text') ||
341 ($body_message->header
->type0
== 'rfc822')) {
342 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
343 $body = decodeBody($body, $body_message->header
->encoding
);
344 $hookResults = do_hook("message_body", $body);
345 $body = $hookResults[1];
347 // If there are other types that shouldn't be formatted, add
349 if ($body_message->header
->type1
== 'html') {
350 if ( $show_html_default <> 1 ) {
351 $body = strip_tags( $body );
352 translateText($body, $wrap_at,
353 $body_message->header
->getParameter
['charset']);
355 $body = magicHTML( $body, $id, $message, $mailbox );
358 translateText($body, $wrap_at,
359 $body_message->header
->getParameter('charset'));
362 if ($has_unsafe_images) {
363 if ($view_unsafe_images) {
364 $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";
366 $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";
374 function formatAttachments($message, $exclude_id, $mailbox, $id) {
375 global $where, $what;
376 global $startMessage, $color;
377 static $ShownHTML = 0;
379 $att_ar = $message->getAttachments($exclude_id);
381 if (!count($att_ar)) return '';
385 $urlMailbox = urlencode($mailbox);
387 foreach ($att_ar as $att) {
389 $ent = urldecode($att->entity_id
);
390 $header = $att->header
;
391 $type0 = strtolower($header->type0
);
392 $type1 = strtolower($header->type1
);
394 if ($type0 =='message' && $type1 == 'rfc822') {
395 $rfc822_header = $att->rfc822_header
;
396 $filename = decodeHeader($rfc822_header->subject
);
397 $display_filename = $filename;
400 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
401 if ($where && $what) {
402 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
404 $Links['download link']['text'] = _("download");
405 $Links['download link']['href'] =
406 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
409 /* this executes the attachment hook with a specific MIME-type.
410 * if that doens't have results, it tries if there's a rule
411 * for a more generic type. */
412 $HookResults = do_hook("attachment $type0/$type1", $Links,
413 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
414 if(count($HookResults[1]) <= 1) {
415 $HookResults = do_hook("attachment $type0/*", $Links,
416 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
417 $display_filename, $where, $what);
420 $Links = $HookResults[1];
421 $DefaultLink = $HookResults[6];
423 $attachments .= '<TR><TD>' .
424 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
425 '<TD><SMALL><b>' . show_readable_size($header->size
) .
426 '</b> </small></TD>' .
427 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
429 $from_o = $rfc822_header->from
;
430 if (is_object($from_o)) {
431 $from_name = $from_o->getAddress(false);
433 $from_name = _("Unknown sender");
435 $from_name = decodeHeader(htmlspecialchars($from_name));
436 $attachments .= '<b>' . $from_name . '</b>';
437 $attachments .= '</SMALL></TD><TD><SMALL> ';
440 foreach ($Links as $Val) {
444 $attachments .= ' | ';
446 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
449 $attachments .= "</TD></TR>\n";
451 $filename = decodeHeader($header->getParameter('filename'));
452 if (trim($filename) == '') {
453 $name = decodeHeader($header->getParameter('name'));
454 if (trim($name) == '') {
455 if ( trim( $header->id
) == '' )
456 $display_filename = 'untitled-[' . $ent . ']' ;
458 $display_filename = 'cid: ' . $header->id
;
460 $display_filename = $name;
464 $display_filename = $filename;
468 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
469 if ($where && $what) {
470 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
472 $Links['download link']['text'] = _("download");
473 $Links['download link']['href'] =
474 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
477 /* this executes the attachment hook with a specific MIME-type.
478 * if that doens't have results, it tries if there's a rule
479 * for a more generic type. */
480 $HookResults = do_hook("attachment $type0/$type1", $Links,
481 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
482 $display_filename, $where, $what);
483 if(count($HookResults[1]) <= 1) {
484 $HookResults = do_hook("attachment $type0/*", $Links,
485 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
486 $display_filename, $where, $what);
489 $Links = $HookResults[1];
490 $DefaultLink = $HookResults[6];
492 $attachments .= '<TR><TD>' .
493 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
494 '<TD><SMALL><b>' . show_readable_size($header->size
) .
495 '</b> </small></TD>' .
496 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
498 if ($message->header
->description
) {
499 $attachments .= '<b>' . htmlspecialchars(_($header->description
)) . '</b>';
501 $attachments .= '</SMALL></TD><TD><SMALL> ';
504 foreach ($Links as $Val) {
508 $attachments .= ' | ';
510 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
512 $attachments .= "</TD></TR>\n";
521 /** this function decodes the body depending on the encoding type. **/
522 function decodeBody($body, $encoding) {
523 $body = str_replace("\r\n", "\n", $body);
524 $encoding = strtolower($encoding);
526 global $show_html_default;
528 if ($encoding == 'quoted-printable' ||
529 $encoding == 'quoted_printable') {
530 $body = quoted_printable_decode($body);
532 while (ereg("=\n", $body))
533 $body = ereg_replace ("=\n", "", $body);
535 } else if ($encoding == 'base64') {
536 $body = base64_decode($body);
539 // All other encodings are returned raw.
544 * This functions decode strings that is encoded according to
545 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
546 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
548 function decodeHeader ($string, $utfencode=true) {
549 if (is_array($string)) {
550 $string = implode("\n", $string);
553 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
556 // Ignore white-space between consecutive encoded-words
557 if (strspn($res[2], " \t") != strlen($res[2])) {
561 if (ucfirst($res[4]) == 'B') {
562 $replace = base64_decode($res[5]);
564 $replace = str_replace('_', ' ', $res[5]);
565 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
567 /* Only encode into entities by default. Some places
568 don't need the encoding, like the compose form. */
570 $replace = charset_decode($res[3], $replace);
573 $string = $prefix . $replace . substr($string, strlen($res[0]));
574 $i = strlen($prefix) +
strlen($replace);
580 * Encode a string according to RFC 1522 for use in headers if it
581 * contains 8-bit characters or anything that looks like it should
584 function encodeHeader ($string) {
585 global $default_charset;
587 // Encode only if the string contains 8-bit characters or =?
588 $j = strlen( $string );
589 $l = strstr($string, '=?'); // Must be encoded ?
591 for( $i=0; $i < $j; ++
$i) {
592 switch( $string{$i} ) {
606 $k = ord( $string{$i} );
608 $ret .= sprintf("=%02X", $k);
616 $string = "=?$default_charset?Q?$ret?=";
622 /* This function trys to locate the entity_id of a specific mime element */
624 function find_ent_id( $id, $message ) {
626 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
627 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
628 $ret = find_ent_id( $id, $message->entities
[$i] );
630 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
631 $ret = $message->entities
[$i]->entity_id
;
638 ** HTMLFILTER ROUTINES
642 * This function returns the final tag out of the tag name, an array
643 * of attributes, and the type of the tag. This function is called by
644 * sq_sanitize internally.
646 * @param $tagname the name of the tag.
647 * @param $attary the array of attributes and their values
648 * @param $tagtype The type of the tag (see in comments).
649 * @return a string with the final tag representation.
651 function sq_tagprint($tagname, $attary, $tagtype){
654 $fulltag = '</' . $tagname . '>';
656 $fulltag = '<' . $tagname;
657 if (is_array($attary) && sizeof($attary)){
659 while (list($attname, $attvalue) = each($attary)){
660 array_push($atts, "$attname=$attvalue");
662 $fulltag .= ' ' . join(" ", $atts);
673 * A small helper function to use with array_walk. Modifies a by-ref
674 * value and makes it lowercase.
676 * @param $val a value passed by-ref.
677 * @return void since it modifies a by-ref value.
679 function sq_casenormalize(&$val){
680 $val = strtolower($val);
684 * This function skips any whitespace from the current position within
685 * a string and to the next non-whitespace value.
687 * @param $body the string
688 * @param $offset the offset within the string where we should start
689 * looking for the next non-whitespace character.
690 * @return the location within the $body where the next
691 * non-whitespace char is located.
693 function sq_skipspace($body, $offset){
694 $me = "sq_skipspace";
695 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
696 if (sizeof($matches{1})){
697 $count = strlen($matches{1});
704 * This function looks for the next character within a string. It's
705 * really just a glorified "strpos", except it catches if failures
708 * @param $body The string to look for needle in.
709 * @param $offset Start looking from this position.
710 * @param $needle The character/string to look for.
711 * @return location of the next occurance of the needle, or
712 * strlen($body) if needle wasn't found.
714 function sq_findnxstr($body, $offset, $needle){
715 $me = "sq_findnxstr";
716 $pos = strpos($body, $needle, $offset);
718 $pos = strlen($body);
724 * This function takes a PCRE-style regexp and tries to match it
727 * @param $body The string to look for needle in.
728 * @param $offset Start looking from here.
729 * @param $reg A PCRE-style regex to match.
730 * @return Returns a false if no matches found, or an array
731 * with the following members:
732 * - integer with the location of the match within $body
733 * - string with whatever content between offset and the match
734 * - string with whatever it is we matched
736 function sq_findnxreg($body, $offset, $reg){
737 $me = "sq_findnxreg";
740 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
744 $retarr{0} = $offset +
strlen($matches{1});
745 $retarr{1} = $matches{1};
746 $retarr{2} = $matches{2};
752 * This function looks for the next tag.
754 * @param $body String where to look for the next tag.
755 * @param $offset Start looking from here.
756 * @return false if no more tags exist in the body, or
757 * an array with the following members:
758 * - string with the name of the tag
759 * - array with attributes and their values
760 * - integer with tag type (1, 2, or 3)
761 * - integer where the tag starts (starting "<")
762 * - integer where the tag ends (ending ">")
763 * first three members will be false, if the tag is invalid.
765 function sq_getnxtag($body, $offset){
767 if ($offset > strlen($body)){
770 $lt = sq_findnxstr($body, $offset, "<");
771 if ($lt == strlen($body)){
776 * blah blah <tag attribute="value">
779 $pos = sq_skipspace($body, $lt+
1);
780 if ($pos >= strlen($body)){
781 return Array(false, false, false, $lt, strlen($body));
784 * There are 3 kinds of tags:
785 * 1. Opening tag, e.g.:
787 * 2. Closing tag, e.g.:
789 * 3. XHTML-style content-less tag, e.g.:
793 switch (substr($body, $pos, 1)){
800 * A comment or an SGML declaration.
802 if (substr($body, $pos+
1, 2) == "--"){
803 $gt = strpos($body, "-->", $pos);
809 return Array(false, false, false, $lt, $gt);
811 $gt = sq_findnxstr($body, $pos, ">");
812 return Array(false, false, false, $lt, $gt);
817 * Assume tagtype 1 for now. If it's type 3, we'll switch values
827 * Look for next [\W-_], which will indicate the end of the tag name.
829 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
830 if ($regary == false){
831 return Array(false, false, false, $lt, strlen($body));
833 list($pos, $tagname, $match) = $regary;
834 $tagname = strtolower($tagname);
837 * $match can be either of these:
838 * '>' indicating the end of the tag entirely.
839 * '\s' indicating the end of the tag name.
840 * '/' indicating that this is type-3 xhtml tag.
842 * Whatever else we find there indicates an invalid tag.
847 * This is an xhtml-style tag with a closing / at the
848 * end, like so: <img src="blah"/>. Check if it's followed
849 * by the closing bracket. If not, then this tag is invalid
851 if (substr($body, $pos, 2) == "/>"){
855 $gt = sq_findnxstr($body, $pos, ">");
856 $retary = Array(false, false, false, $lt, $gt);
860 return Array($tagname, false, $tagtype, $lt, $pos);
864 * Check if it's whitespace
866 if (preg_match("/\s/", $match)){
869 * This is an invalid tag! Look for the next closing ">".
871 $gt = sq_findnxstr($body, $offset, ">");
872 return Array(false, false, false, $lt, $gt);
877 * At this point we're here:
878 * <tagname attribute='blah'>
881 * At this point we loop in order to find all attributes.
887 while ($pos <= strlen($body)){
888 $pos = sq_skipspace($body, $pos);
889 if ($pos == strlen($body)){
893 return Array(false, false, false, $lt, $pos);
896 * See if we arrived at a ">" or "/>", which means that we reached
897 * the end of the tag.
900 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
904 $pos +
= strlen($matches{1});
905 if ($matches{2} == "/>"){
909 return Array($tagname, $attary, $tagtype, $lt, $pos);
913 * There are several types of attributes, with optional
914 * [:space:] between members.
916 * attrname[:space:]=[:space:]'CDATA'
918 * attrname[:space:]=[:space:]"CDATA"
920 * attr[:space:]=[:space:]CDATA
924 * We leave types 1 and 2 the same, type 3 we check for
925 * '"' and convert to """ if needed, then wrap in
926 * double quotes. Type 4 we convert into:
929 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
930 if ($regary == false){
932 * Looks like body ended before the end of tag.
934 return Array(false, false, false, $lt, strlen($body));
936 list($pos, $attname, $match) = $regary;
937 $attname = strtolower($attname);
939 * We arrived at the end of attribute name. Several things possible
941 * '>' means the end of the tag and this is attribute type 4
942 * '/' if followed by '>' means the same thing as above
943 * '\s' means a lot of things -- look what it's followed by.
944 * anything else means the attribute is invalid.
949 * This is an xhtml-style tag with a closing / at the
950 * end, like so: <img src="blah"/>. Check if it's followed
951 * by the closing bracket. If not, then this tag is invalid
953 if (substr($body, $pos, 2) == "/>"){
957 $gt = sq_findnxstr($body, $pos, ">");
958 $retary = Array(false, false, false, $lt, $gt);
962 $attary{$attname} = '"yes"';
963 return Array($tagname, $attary, $tagtype, $lt, $pos);
967 * Skip whitespace and see what we arrive at.
969 $pos = sq_skipspace($body, $pos);
970 $char = substr($body, $pos, 1);
972 * Two things are valid here:
973 * '=' means this is attribute type 1 2 or 3.
974 * \w means this was attribute type 4.
975 * anything else we ignore and re-loop. End of tag and
976 * invalid stuff will be caught by our checks at the beginning
981 $pos = sq_skipspace($body, $pos);
983 * Here are 3 possibilities:
984 * "'" attribute type 1
985 * '"' attribute type 2
986 * everything else is the content of tag type 3
988 $quot = substr($body, $pos, 1);
990 $regary = sq_findnxreg($body, $pos+
1, "\'");
991 if ($regary == false){
992 return Array(false, false, false, $lt, strlen($body));
994 list($pos, $attval, $match) = $regary;
996 $attary{$attname} = "'" . $attval . "'";
997 } else if ($quot == '"'){
998 $regary = sq_findnxreg($body, $pos+
1, '\"');
999 if ($regary == false){
1000 return Array(false, false, false, $lt, strlen($body));
1002 list($pos, $attval, $match) = $regary;
1004 $attary{$attname} = '"' . $attval . '"';
1007 * These are hateful. Look for \s, or >.
1009 $regary = sq_findnxreg($body, $pos, "[\s>]");
1010 if ($regary == false){
1011 return Array(false, false, false, $lt, strlen($body));
1013 list($pos, $attval, $match) = $regary;
1015 * If it's ">" it will be caught at the top.
1017 $attval = preg_replace("/\"/s", """, $attval);
1018 $attary{$attname} = '"' . $attval . '"';
1020 } else if (preg_match("|[\w/>]|", $char)) {
1022 * That was attribute type 4.
1024 $attary{$attname} = '"yes"';
1027 * An illegal character. Find next '>' and return.
1029 $gt = sq_findnxstr($body, $pos, ">");
1030 return Array(false, false, false, $lt, $gt);
1035 * The fact that we got here indicates that the tag end was never
1036 * found. Return invalid tag indication so it gets stripped.
1038 return Array(false, false, false, $lt, strlen($body));
1042 * This function checks attribute values for entity-encoded values
1043 * and returns them translated into 8-bit strings so we can run
1046 * @param $attvalue A string to run entity check against.
1047 * @return Translated value.
1049 function sq_deent($attvalue){
1052 * See if we have to run the checks first. All entities must start
1055 if (strpos($attvalue, "&") === false){
1059 * Check named entities first.
1061 $trans = get_html_translation_table(HTML_ENTITIES
);
1063 * Leave " in, as it can mess us up.
1065 $trans = array_flip($trans);
1066 unset($trans{"""});
1067 while (list($ent, $val) = each($trans)){
1068 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1071 * Now translate numbered entities from 1 to 255 if needed.
1073 if (strpos($attvalue, "#") !== false){
1074 $omit = Array(34, 39);
1075 for ($asc=1; $asc<256; $asc++
){
1076 if (!in_array($asc, $omit)){
1078 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1080 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1081 "$chr\\1", $attvalue);
1089 * This function runs various checks against the attributes.
1091 * @param $tagname String with the name of the tag.
1092 * @param $attary Array with all tag attributes.
1093 * @param $rm_attnames See description for sq_sanitize
1094 * @param $bad_attvals See description for sq_sanitize
1095 * @param $add_attr_to_tag See description for sq_sanitize
1096 * @param $message message object
1097 * @param $id message id
1098 * @return Array with modified attributes.
1100 function sq_fixatts($tagname,
1110 while (list($attname, $attvalue) = each($attary)){
1112 * See if this attribute should be removed.
1114 foreach ($rm_attnames as $matchtag=>$matchattrs){
1115 if (preg_match($matchtag, $tagname)){
1116 foreach ($matchattrs as $matchattr){
1117 if (preg_match($matchattr, $attname)){
1118 unset($attary{$attname});
1125 * Remove any entities.
1127 $attvalue = sq_deent($attvalue);
1130 * Now let's run checks on the attvalues.
1131 * I don't expect anyone to comprehend this. If you do,
1132 * get in touch with me so I can drive to where you live and
1133 * shake your hand personally. :)
1135 foreach ($bad_attvals as $matchtag=>$matchattrs){
1136 if (preg_match($matchtag, $tagname)){
1137 foreach ($matchattrs as $matchattr=>$valary){
1138 if (preg_match($matchattr, $attname)){
1140 * There are two arrays in valary.
1142 * Second one is replacements
1144 list($valmatch, $valrepl) = $valary;
1146 preg_replace($valmatch, $valrepl, $attvalue);
1147 if ($newvalue != $attvalue){
1148 $attary{$attname} = $newvalue;
1155 * Turn cid: urls into http-friendly ones.
1157 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1158 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1162 * See if we need to append any attributes to this tag.
1164 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1165 if (preg_match($matchtag, $tagname)){
1166 $attary = array_merge($attary, $addattary);
1173 * This function edits the style definition to make them friendly and
1174 * usable in squirrelmail.
1176 * @param $message the message object
1177 * @param $id the message id
1178 * @param $content a string with whatever is between <style> and </style>
1179 * @return a string with edited content.
1181 function sq_fixstyle($message, $id, $content){
1182 global $view_unsafe_images;
1183 $me = "sq_fixstyle";
1185 * First look for general BODY style declaration, which would be
1187 * body {background: blah-blah}
1188 * and change it to .bodyclass so we can just assign it to a <div>
1190 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1191 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1193 * Fix url('blah') declarations.
1195 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1196 "url(\\1$secremoveimg\\2)", $content);
1198 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1201 if (!$view_unsafe_images){
1202 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1203 "url(\\1$secremoveimg\\2)", $content);
1207 * Fix urls that refer to cid:
1209 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1211 $cidurl = $matches{1};
1212 $httpurl = sq_cid2http($message, $id, $cidurl);
1213 $content = preg_replace("|url\($cidurl\)|si",
1214 "url($httpurl)", $content);
1218 * Fix stupid css declarations which lead to vulnerabilities
1221 $match = Array('/expression/si',
1224 $replace = Array('idiocy', 'idiocy', 'idiocy');
1225 $content = preg_replace($match, $replace, $content);
1230 * This function converts cid: url's into the ones that can be viewed in
1233 * @param $message the message object
1234 * @param $id the message id
1235 * @param $cidurl the cid: url.
1236 * @return a string with a http-friendly url
1238 function sq_cid2http($message, $id, $cidurl, $mailbox){
1240 * Get rid of quotes.
1242 $quotchar = substr($cidurl, 0, 1);
1243 $cidurl = str_replace($quotchar, "", $cidurl);
1244 $cidurl = substr(trim($cidurl), 4);
1245 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1246 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1247 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1252 * This function changes the <body> tag into a <div> tag since we
1253 * can't really have a body-within-body.
1255 * @param $attary an array of attributes and values of <body>
1256 * @return a modified array of attributes to be set for <div>
1258 function sq_body2div($attary){
1259 $me = "sq_body2div";
1260 $divattary = Array("class"=>"'bodyclass'");
1264 if (is_array($attary) && sizeof($attary) > 0){
1265 foreach ($attary as $attname=>$attvalue){
1266 $quotchar = substr($attvalue, 0, 1);
1267 $attvalue = str_replace($quotchar, "", $attvalue);
1270 $styledef .= "background-image: url('$attvalue'); ";
1273 $styledef .= "background-color: $attvalue; ";
1276 $styledef .= "color: $attvalue; ";
1279 if (strlen($styledef) > 0){
1280 $divattary{"style"} = "\"$styledef\"";
1287 * This is the main function and the one you should actually be calling.
1288 * There are several variables you should be aware of an which need
1289 * special description.
1291 * Since the description is quite lengthy, see it here:
1292 * http://www.mricon.com/html/phpfilter.html
1294 * @param $body the string with HTML you wish to filter
1295 * @param $tag_list see description above
1296 * @param $rm_tags_with_content see description above
1297 * @param $self_closing_tags see description above
1298 * @param $force_tag_closing see description above
1299 * @param $rm_attnames see description above
1300 * @param $bad_attvals see description above
1301 * @param $add_attr_to_tag see description above
1302 * @param $message message object
1303 * @param $id message id
1304 * @return sanitized html safe to show on your pages.
1306 function sq_sanitize($body,
1308 $rm_tags_with_content,
1318 $me = "sq_sanitize";
1320 * Normalize rm_tags and rm_tags_with_content.
1322 @array_walk
($rm_tags, 'sq_casenormalize');
1323 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1324 @array_walk
($self_closing_tags, 'sq_casenormalize');
1326 * See if tag_list is of tags to remove or tags to allow.
1327 * false means remove these tags
1328 * true means allow these tags
1330 $rm_tags = array_shift($tag_list);
1332 $open_tags = Array();
1333 $trusted = "<!-- begin sanitized html -->\n";
1334 $skip_content = false;
1336 * Take care of netscape's stupid javascript entities like
1339 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1341 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1342 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1343 $free_content = substr($body, $curpos, $lt-$curpos);
1345 * Take care of <style>
1347 if ($tagname == "style" && $tagtype == 2){
1349 * This is a closing </style>. Edit the
1350 * content before we apply it.
1352 $free_content = sq_fixstyle($message, $id, $free_content);
1354 if ($skip_content == false){
1355 $trusted .= $free_content;
1358 if ($tagname != FALSE){
1360 if ($skip_content == $tagname){
1362 * Got to the end of tag we needed to remove.
1365 $skip_content = false;
1367 if ($skip_content == false){
1368 if ($tagname == "body"){
1371 if (isset($open_tags{$tagname}) &&
1372 $open_tags{$tagname} > 0){
1373 $open_tags{$tagname}--;
1383 * $rm_tags_with_content
1385 if ($skip_content == false){
1387 * See if this is a self-closing type and change
1388 * tagtype appropriately.
1391 && in_array($tagname, $self_closing_tags)){
1395 * See if we should skip this tag and any content
1398 if ($tagtype == 1 &&
1399 in_array($tagname, $rm_tags_with_content)){
1400 $skip_content = $tagname;
1402 if (($rm_tags == false
1403 && in_array($tagname, $tag_list)) ||
1404 ($rm_tags == true &&
1405 !in_array($tagname, $tag_list))){
1409 if (isset($open_tags{$tagname})){
1410 $open_tags{$tagname}++
;
1412 $open_tags{$tagname}=1;
1416 * This is where we run other checks.
1418 if (is_array($attary) && sizeof($attary) > 0){
1419 $attary = sq_fixatts($tagname,
1430 * Convert body into div.
1432 if ($tagname == "body"){
1434 $attary = sq_body2div($attary, $message, $id);
1441 if ($tagname != false && $skip_content == false){
1442 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1448 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1449 if ($force_tag_closing == true){
1450 foreach ($open_tags as $tagname=>$opentimes){
1451 while ($opentimes > 0){
1452 $trusted .= '</' . $tagname . '>';
1458 $trusted .= "<!-- end sanitized html -->\n";
1463 * This is a wrapper function to call html sanitizing routines.
1465 * @param $body the body of the message
1466 * @param $id the id of the message
1467 * @return a string with html safe to display in the browser.
1469 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1470 global $attachment_common_show_images, $view_unsafe_images,
1473 * Don't display attached images in HTML mode.
1475 $attachment_common_show_images = false;
1486 $rm_tags_with_content = Array(
1493 $self_closing_tags = Array(
1500 $force_tag_closing = false;
1502 $rm_attnames = Array(
1512 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1513 $bad_attvals = Array(
1516 "/^src|background/i" =>
1519 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1520 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1521 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1522 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1525 "\\1$secremoveimg\\2",
1526 "\\1$secremoveimg\\2",
1527 "\\1$secremoveimg\\2",
1528 "\\1$secremoveimg\\2"
1531 "/^href|action/i" =>
1534 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1535 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1536 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1537 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1552 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1553 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1554 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1555 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1569 if (!$view_unsafe_images){
1571 * Remove any references to http/https if view_unsafe_images set
1574 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1575 '/^([\'\"])\s*https*:.*([\'\"])/si');
1576 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1577 "\\1$secremoveimg\\2");
1578 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1579 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1580 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1581 "url(\\1$secremoveimg\\2)");
1584 $add_attr_to_tag = Array(
1585 "/^a$/si" => Array('target'=>'"_new"')
1587 $trusted = sq_sanitize($body,
1589 $rm_tags_with_content,
1599 if (preg_match("|$secremoveimg|si", $trusted)){
1600 $has_unsafe_images = true;