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 $res = $msg->parseStructure($read);
37 foreach ($flags as $flag) {
38 $char = strtoupper($flag{1});
41 if (strtolower($flag) == '\\seen') {
46 if (strtolower($flag) == '\\answered') {
47 $msg->is_answered
= true;
51 if (strtolower($flag) == '\\deleted') {
52 $msg->is_deleted
= true;
56 if (strtolower($flag) == '\\flagged') {
57 $msg->is_flagged
= true;
61 if (strtolower($flag) == '$mdnsent') {
62 $msg->is_mdnsent
= true;
70 // listEntities($msg);
74 /* this starts the parsing of a particular structure. It is called recursively,
75 * so it can be passed different structures. It returns an object of type
77 * First, it checks to see if it is a multipart message. If it is, then it
78 * handles that as it sees is necessary. If it is just a regular entity,
79 * then it parses it and adds the necessary header information (by calling out
80 * to mime_get_elements()
83 function mime_fetch_body($imap_stream, $id, $ent_id) {
86 * do a bit of error correction. If we couldn't find the entity id, just guess
87 * that it is the first one. That is usually the case anyway.
92 $cmd = "FETCH $id BODY[$ent_id]";
94 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
96 $topline = trim(array_shift( $data ));
97 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
99 $wholemessage = implode('', $data);
100 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
102 $ret = substr( $wholemessage, 0, $regs[1] );
104 There is some information in the content info header that could be important
105 in order to parse html messages. Let's get them here.
107 if ( $ret{0} == '<' ) {
108 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
110 } else if (ereg('"([^"]*)"', $topline, $regs)) {
113 global $where, $what, $mailbox, $passed_id, $startMessage;
114 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
115 if (isset($where) && isset($what)) {
116 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
118 $par .= "&startMessage=$startMessage&show_more=0";
120 $par .= '&response=' . urlencode($response) .
121 '&message=' . urlencode($message).
122 '&topline=' . urlencode($topline);
125 '<table width="80%"><tr>' .
126 '<tr><td colspan=2>' .
127 _("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!") .
128 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
129 _("Submit message") . '</A><BR> ' .
131 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
132 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
133 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
134 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
135 "</table><BR></tt></font><hr>";
137 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
139 $wholemessage = implode('', $data);
141 $ret = $wholemessage;
146 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
148 // do a bit of error correction. If we couldn't find the entity id, just guess
149 // that it is the first one. That is usually the case anyway.
153 $sid = sqimap_session_id($uid_support);
154 // Don't kill the connection if the browser is over a dialup
155 // and it would take over 30 seconds to download it.
157 // donĀ“t call set_time_limit in safe mode.
158 if (!ini_get("safe_mode")) {
162 $sid_s = substr($sid,0,strpos($sid, ' '));
167 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
168 echo decodeBody($body, $encoding);
171 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
174 $read = fgets ($imap_stream,8192);
177 // This could be bad -- if the section has sqimap_session_id() . ' OK'
178 // or similar, it will kill the download.
179 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
180 if (trim($read) == ')==') {
182 $read = fgets ($imap_stream,4096);
183 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
186 echo decodeBody($read1, $encoding) .
187 decodeBody($read, $encoding);
190 echo decodeBody($read, $encoding);
192 $read = fgets ($imap_stream,4096);
199 /* -[ END MIME DECODING ]----------------------------------------------------------- */
202 * Checks to see if $message contains content of type $type0/$type1
203 * returns the first entity number it finds of that type, or NULL if
204 * none is found. Takes optional argument $start to allow the caller
205 * to continue where they left off
207 function findDisplayEntity($message, $type0, $type1, $start=0) {
209 for ($i = $start;isset($message->entities
[$i]); $i++
) {
210 $entity = $message->entities
[$i];
211 if ($entity->type0
== $type0 && $entity->type1
== $type1) {
219 // This is here for debugging purposese. It will print out a list
220 // of all the entity IDs that are in the $message object.
222 function listEntities ($message) {
224 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
225 for ($i = 0;isset($message->entities
[$i]); $i++
) {
227 $msg = listEntities($message->entities
[$i]);
237 function getPriorityStr($priority) {
238 $priority_level = substr($priority,0,1);
240 switch($priority_level) {
241 /* check for a higher then normal priority. */
244 $priority_string = _("High");
247 /* check for a lower then normal priority. */
250 $priority_string = _("Low");
253 /* check for a normal priority. */
256 $priority_level = '3';
257 $priority_string = _("Normal");
261 return $priority_string;
264 /* returns a $message object for a particular entity id */
265 function getEntity ($message, $ent_id) {
266 return $message->getEntity($ent_id);
271 * Extracted from strings.php 23/03/2002
274 function translateText(&$body, $wrap_at, $charset) {
275 global $where, $what; /* from searching */
276 global $color; /* color theme */
278 require_once('../functions/url_parser.php');
280 $body_ary = explode("\n", $body);
282 for ($i=0; $i < count($body_ary); $i++
) {
283 $line = $body_ary[$i];
284 if (strlen($line) - 2 >= $wrap_at) {
285 sqWordWrap($line, $wrap_at);
287 $line = charset_decode($charset, $line);
288 $line = str_replace("\t", ' ', $line);
294 $j = strlen( $line );
296 while ( $pos < $j ) {
297 if ($line[$pos] == ' ') {
299 } else if (strpos($line, '>', $pos) === $pos) {
308 if (! isset($color[14])) {
309 $color[14] = '#FF0000';
311 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
313 if (! isset($color[13])) {
314 $color[13] = '#800000';
316 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
319 $body_ary[$i] = $line;
321 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
325 /* This returns a parsed string called $body. That string can then
326 be displayed as the actual message in the HTML. It contains
327 everything needed, including HTML Tags, Attachments at the
330 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
331 // this if statement checks for the entity to show as the
332 // primary message. To add more of them, just put them in the
333 // order that is their priority.
334 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
335 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
337 $has_unsafe_images= 0;
339 $urlmailbox = urlencode($mailbox);
340 $body_message = getEntity($message, $ent_num);
341 if (($body_message->header
->type0
== 'text') ||
342 ($body_message->header
->type0
== 'rfc822')) {
343 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
344 $body = decodeBody($body, $body_message->header
->encoding
);
345 $hookResults = do_hook("message_body", $body);
346 $body = $hookResults[1];
348 // If there are other types that shouldn't be formatted, add
350 if ($body_message->header
->type1
== 'html') {
351 if ( $show_html_default <> 1 ) {
352 $body = strip_tags( $body );
353 translateText($body, $wrap_at,
354 $body_message->header
->getParameter
['charset']);
356 $body = magicHTML( $body, $id, $message, $mailbox );
359 translateText($body, $wrap_at,
360 $body_message->header
->getParameter('charset'));
363 if ($has_unsafe_images) {
364 if ($view_unsafe_images) {
365 $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";
367 $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";
375 function formatAttachments($message, $exclude_id, $mailbox, $id) {
376 global $where, $what;
377 global $startMessage, $color;
378 static $ShownHTML = 0;
380 $att_ar = $message->getAttachments($exclude_id);
382 if (!count($att_ar)) return '';
386 $urlMailbox = urlencode($mailbox);
388 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 $Links['download link']['text'] = _("download");
395 $Links['download link']['href'] =
396 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
398 if ($type0 =='message' && $type1 == 'rfc822') {
399 $default_page = '../src/read_body.php';
400 $rfc822_header = $att->rfc822_header
;
401 $filename = decodeHeader($rfc822_header->subject
);
403 $from_o = $rfc822_header->from
;
404 if (is_object($from_o)) {
405 $from_name = $from_o->getAddress(false);
407 $from_name = _("Unknown sender");
409 $from_name = decodeHeader(htmlspecialchars($from_name));
411 $default_page = '../src/download.php';
412 $filename = decodeHeader($header->getParameter('filename'));
413 if (trim($filename) == '') {
414 $name = decodeHeader($header->getParameter('name'));
415 if (trim($name) == '') {
416 if ( trim( $header->id
) == '' )
417 $filename = 'untitled-[' . $ent . ']' ;
419 $filename = 'cid: ' . $header->id
;
424 if ($message->header
->description
) {
425 $from_name = htmlspecialchars(_($header->description
));
429 $display_filename = $filename;
430 $DefaultLink = $default_page . "?startMessage=$startMessage"
431 . "&passed_id=$id&mailbox=$urlMailbox"
432 . "&passed_ent_id=$ent";
433 if ($where && $what) {
434 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
436 /* this executes the attachment hook with a specific MIME-type.
437 * if that doens't have results, it tries if there's a rule
438 * for a more generic type. */
439 $HookResults = do_hook("attachment $type0/$type1", $Links,
440 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
441 $display_filename, $where, $what);
442 if(count($HookResults[1]) <= 1) {
443 $HookResults = do_hook("attachment $type0/*", $Links,
444 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
445 $display_filename, $where, $what);
448 $Links = $HookResults[1];
449 $DefaultLink = $HookResults[6];
451 $attachments .= '<TR><TD>' .
452 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
453 '<TD><SMALL><b>' . show_readable_size($header->size
) .
454 '</b> </small></TD>' .
455 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
457 $attachments .= '<b>' . $from_name . '</b>';
458 $attachments .= '</SMALL></TD><TD><SMALL> ';
461 foreach ($Links as $Val) {
465 $attachments .= ' | ';
467 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
470 $attachments .= "</TD></TR>\n";
475 /** this function decodes the body depending on the encoding type. **/
476 function decodeBody($body, $encoding) {
477 $body = str_replace("\r\n", "\n", $body);
478 $encoding = strtolower($encoding);
480 global $show_html_default;
482 if ($encoding == 'quoted-printable' ||
483 $encoding == 'quoted_printable') {
484 $body = quoted_printable_decode($body);
486 while (ereg("=\n", $body))
487 $body = ereg_replace ("=\n", "", $body);
489 } else if ($encoding == 'base64') {
490 $body = base64_decode($body);
493 // All other encodings are returned raw.
498 * This functions decode strings that is encoded according to
499 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
500 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
502 function decodeHeader ($string, $utfencode=true) {
503 if (is_array($string)) {
504 $string = implode("\n", $string);
507 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
510 // Ignore white-space between consecutive encoded-words
511 if (strspn($res[2], " \t") != strlen($res[2])) {
515 if (ucfirst($res[4]) == 'B') {
516 $replace = base64_decode($res[5]);
518 $replace = str_replace('_', ' ', $res[5]);
519 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
521 /* Only encode into entities by default. Some places
522 don't need the encoding, like the compose form. */
524 $replace = charset_decode($res[3], $replace);
527 $string = $prefix . $replace . substr($string, strlen($res[0]));
528 $i = strlen($prefix) +
strlen($replace);
534 * Encode a string according to RFC 1522 for use in headers if it
535 * contains 8-bit characters or anything that looks like it should
538 function encodeHeader ($string) {
539 global $default_charset;
541 // Encode only if the string contains 8-bit characters or =?
542 $j = strlen( $string );
543 $l = strstr($string, '=?'); // Must be encoded ?
545 for( $i=0; $i < $j; ++
$i) {
546 switch( $string{$i} ) {
560 $k = ord( $string{$i} );
562 $ret .= sprintf("=%02X", $k);
570 $string = "=?$default_charset?Q?$ret?=";
576 /* This function trys to locate the entity_id of a specific mime element */
578 function find_ent_id( $id, $message ) {
580 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
581 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
582 $ret = find_ent_id( $id, $message->entities
[$i] );
584 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
585 $ret = $message->entities
[$i]->entity_id
;
592 ** HTMLFILTER ROUTINES
596 * This function returns the final tag out of the tag name, an array
597 * of attributes, and the type of the tag. This function is called by
598 * sq_sanitize internally.
600 * @param $tagname the name of the tag.
601 * @param $attary the array of attributes and their values
602 * @param $tagtype The type of the tag (see in comments).
603 * @return a string with the final tag representation.
605 function sq_tagprint($tagname, $attary, $tagtype){
608 $fulltag = '</' . $tagname . '>';
610 $fulltag = '<' . $tagname;
611 if (is_array($attary) && sizeof($attary)){
613 while (list($attname, $attvalue) = each($attary)){
614 array_push($atts, "$attname=$attvalue");
616 $fulltag .= ' ' . join(" ", $atts);
627 * A small helper function to use with array_walk. Modifies a by-ref
628 * value and makes it lowercase.
630 * @param $val a value passed by-ref.
631 * @return void since it modifies a by-ref value.
633 function sq_casenormalize(&$val){
634 $val = strtolower($val);
638 * This function skips any whitespace from the current position within
639 * a string and to the next non-whitespace value.
641 * @param $body the string
642 * @param $offset the offset within the string where we should start
643 * looking for the next non-whitespace character.
644 * @return the location within the $body where the next
645 * non-whitespace char is located.
647 function sq_skipspace($body, $offset){
648 $me = "sq_skipspace";
649 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
650 if (sizeof($matches{1})){
651 $count = strlen($matches{1});
658 * This function looks for the next character within a string. It's
659 * really just a glorified "strpos", except it catches if failures
662 * @param $body The string to look for needle in.
663 * @param $offset Start looking from this position.
664 * @param $needle The character/string to look for.
665 * @return location of the next occurance of the needle, or
666 * strlen($body) if needle wasn't found.
668 function sq_findnxstr($body, $offset, $needle){
669 $me = "sq_findnxstr";
670 $pos = strpos($body, $needle, $offset);
672 $pos = strlen($body);
678 * This function takes a PCRE-style regexp and tries to match it
681 * @param $body The string to look for needle in.
682 * @param $offset Start looking from here.
683 * @param $reg A PCRE-style regex to match.
684 * @return Returns a false if no matches found, or an array
685 * with the following members:
686 * - integer with the location of the match within $body
687 * - string with whatever content between offset and the match
688 * - string with whatever it is we matched
690 function sq_findnxreg($body, $offset, $reg){
691 $me = "sq_findnxreg";
694 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
698 $retarr{0} = $offset +
strlen($matches{1});
699 $retarr{1} = $matches{1};
700 $retarr{2} = $matches{2};
706 * This function looks for the next tag.
708 * @param $body String where to look for the next tag.
709 * @param $offset Start looking from here.
710 * @return false if no more tags exist in the body, or
711 * an array with the following members:
712 * - string with the name of the tag
713 * - array with attributes and their values
714 * - integer with tag type (1, 2, or 3)
715 * - integer where the tag starts (starting "<")
716 * - integer where the tag ends (ending ">")
717 * first three members will be false, if the tag is invalid.
719 function sq_getnxtag($body, $offset){
721 if ($offset > strlen($body)){
724 $lt = sq_findnxstr($body, $offset, "<");
725 if ($lt == strlen($body)){
730 * blah blah <tag attribute="value">
733 $pos = sq_skipspace($body, $lt+
1);
734 if ($pos >= strlen($body)){
735 return Array(false, false, false, $lt, strlen($body));
738 * There are 3 kinds of tags:
739 * 1. Opening tag, e.g.:
741 * 2. Closing tag, e.g.:
743 * 3. XHTML-style content-less tag, e.g.:
747 switch (substr($body, $pos, 1)){
754 * A comment or an SGML declaration.
756 if (substr($body, $pos+
1, 2) == "--"){
757 $gt = strpos($body, "-->", $pos);
763 return Array(false, false, false, $lt, $gt);
765 $gt = sq_findnxstr($body, $pos, ">");
766 return Array(false, false, false, $lt, $gt);
771 * Assume tagtype 1 for now. If it's type 3, we'll switch values
781 * Look for next [\W-_], which will indicate the end of the tag name.
783 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
784 if ($regary == false){
785 return Array(false, false, false, $lt, strlen($body));
787 list($pos, $tagname, $match) = $regary;
788 $tagname = strtolower($tagname);
791 * $match can be either of these:
792 * '>' indicating the end of the tag entirely.
793 * '\s' indicating the end of the tag name.
794 * '/' indicating that this is type-3 xhtml tag.
796 * Whatever else we find there indicates an invalid tag.
801 * This is an xhtml-style tag with a closing / at the
802 * end, like so: <img src="blah"/>. Check if it's followed
803 * by the closing bracket. If not, then this tag is invalid
805 if (substr($body, $pos, 2) == "/>"){
809 $gt = sq_findnxstr($body, $pos, ">");
810 $retary = Array(false, false, false, $lt, $gt);
814 return Array($tagname, false, $tagtype, $lt, $pos);
818 * Check if it's whitespace
820 if (preg_match("/\s/", $match)){
823 * This is an invalid tag! Look for the next closing ">".
825 $gt = sq_findnxstr($body, $offset, ">");
826 return Array(false, false, false, $lt, $gt);
831 * At this point we're here:
832 * <tagname attribute='blah'>
835 * At this point we loop in order to find all attributes.
841 while ($pos <= strlen($body)){
842 $pos = sq_skipspace($body, $pos);
843 if ($pos == strlen($body)){
847 return Array(false, false, false, $lt, $pos);
850 * See if we arrived at a ">" or "/>", which means that we reached
851 * the end of the tag.
854 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
858 $pos +
= strlen($matches{1});
859 if ($matches{2} == "/>"){
863 return Array($tagname, $attary, $tagtype, $lt, $pos);
867 * There are several types of attributes, with optional
868 * [:space:] between members.
870 * attrname[:space:]=[:space:]'CDATA'
872 * attrname[:space:]=[:space:]"CDATA"
874 * attr[:space:]=[:space:]CDATA
878 * We leave types 1 and 2 the same, type 3 we check for
879 * '"' and convert to """ if needed, then wrap in
880 * double quotes. Type 4 we convert into:
883 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
884 if ($regary == false){
886 * Looks like body ended before the end of tag.
888 return Array(false, false, false, $lt, strlen($body));
890 list($pos, $attname, $match) = $regary;
891 $attname = strtolower($attname);
893 * We arrived at the end of attribute name. Several things possible
895 * '>' means the end of the tag and this is attribute type 4
896 * '/' if followed by '>' means the same thing as above
897 * '\s' means a lot of things -- look what it's followed by.
898 * anything else means the attribute is invalid.
903 * This is an xhtml-style tag with a closing / at the
904 * end, like so: <img src="blah"/>. Check if it's followed
905 * by the closing bracket. If not, then this tag is invalid
907 if (substr($body, $pos, 2) == "/>"){
911 $gt = sq_findnxstr($body, $pos, ">");
912 $retary = Array(false, false, false, $lt, $gt);
916 $attary{$attname} = '"yes"';
917 return Array($tagname, $attary, $tagtype, $lt, $pos);
921 * Skip whitespace and see what we arrive at.
923 $pos = sq_skipspace($body, $pos);
924 $char = substr($body, $pos, 1);
926 * Two things are valid here:
927 * '=' means this is attribute type 1 2 or 3.
928 * \w means this was attribute type 4.
929 * anything else we ignore and re-loop. End of tag and
930 * invalid stuff will be caught by our checks at the beginning
935 $pos = sq_skipspace($body, $pos);
937 * Here are 3 possibilities:
938 * "'" attribute type 1
939 * '"' attribute type 2
940 * everything else is the content of tag type 3
942 $quot = substr($body, $pos, 1);
944 $regary = sq_findnxreg($body, $pos+
1, "\'");
945 if ($regary == false){
946 return Array(false, false, false, $lt, strlen($body));
948 list($pos, $attval, $match) = $regary;
950 $attary{$attname} = "'" . $attval . "'";
951 } else if ($quot == '"'){
952 $regary = sq_findnxreg($body, $pos+
1, '\"');
953 if ($regary == false){
954 return Array(false, false, false, $lt, strlen($body));
956 list($pos, $attval, $match) = $regary;
958 $attary{$attname} = '"' . $attval . '"';
961 * These are hateful. Look for \s, or >.
963 $regary = sq_findnxreg($body, $pos, "[\s>]");
964 if ($regary == false){
965 return Array(false, false, false, $lt, strlen($body));
967 list($pos, $attval, $match) = $regary;
969 * If it's ">" it will be caught at the top.
971 $attval = preg_replace("/\"/s", """, $attval);
972 $attary{$attname} = '"' . $attval . '"';
974 } else if (preg_match("|[\w/>]|", $char)) {
976 * That was attribute type 4.
978 $attary{$attname} = '"yes"';
981 * An illegal character. Find next '>' and return.
983 $gt = sq_findnxstr($body, $pos, ">");
984 return Array(false, false, false, $lt, $gt);
989 * The fact that we got here indicates that the tag end was never
990 * found. Return invalid tag indication so it gets stripped.
992 return Array(false, false, false, $lt, strlen($body));
996 * This function checks attribute values for entity-encoded values
997 * and returns them translated into 8-bit strings so we can run
1000 * @param $attvalue A string to run entity check against.
1001 * @return Translated value.
1003 function sq_deent($attvalue){
1006 * See if we have to run the checks first. All entities must start
1009 if (strpos($attvalue, "&") === false){
1013 * Check named entities first.
1015 $trans = get_html_translation_table(HTML_ENTITIES
);
1017 * Leave " in, as it can mess us up.
1019 $trans = array_flip($trans);
1020 unset($trans{"""});
1021 while (list($ent, $val) = each($trans)){
1022 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1025 * Now translate numbered entities from 1 to 255 if needed.
1027 if (strpos($attvalue, "#") !== false){
1028 $omit = Array(34, 39);
1029 for ($asc=1; $asc<256; $asc++
){
1030 if (!in_array($asc, $omit)){
1032 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1034 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1035 "$chr\\1", $attvalue);
1043 * This function runs various checks against the attributes.
1045 * @param $tagname String with the name of the tag.
1046 * @param $attary Array with all tag attributes.
1047 * @param $rm_attnames See description for sq_sanitize
1048 * @param $bad_attvals See description for sq_sanitize
1049 * @param $add_attr_to_tag See description for sq_sanitize
1050 * @param $message message object
1051 * @param $id message id
1052 * @return Array with modified attributes.
1054 function sq_fixatts($tagname,
1064 while (list($attname, $attvalue) = each($attary)){
1066 * See if this attribute should be removed.
1068 foreach ($rm_attnames as $matchtag=>$matchattrs){
1069 if (preg_match($matchtag, $tagname)){
1070 foreach ($matchattrs as $matchattr){
1071 if (preg_match($matchattr, $attname)){
1072 unset($attary{$attname});
1079 * Remove any entities.
1081 $attvalue = sq_deent($attvalue);
1084 * Now let's run checks on the attvalues.
1085 * I don't expect anyone to comprehend this. If you do,
1086 * get in touch with me so I can drive to where you live and
1087 * shake your hand personally. :)
1089 foreach ($bad_attvals as $matchtag=>$matchattrs){
1090 if (preg_match($matchtag, $tagname)){
1091 foreach ($matchattrs as $matchattr=>$valary){
1092 if (preg_match($matchattr, $attname)){
1094 * There are two arrays in valary.
1096 * Second one is replacements
1098 list($valmatch, $valrepl) = $valary;
1100 preg_replace($valmatch, $valrepl, $attvalue);
1101 if ($newvalue != $attvalue){
1102 $attary{$attname} = $newvalue;
1109 * Turn cid: urls into http-friendly ones.
1111 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1112 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1116 * See if we need to append any attributes to this tag.
1118 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1119 if (preg_match($matchtag, $tagname)){
1120 $attary = array_merge($attary, $addattary);
1127 * This function edits the style definition to make them friendly and
1128 * usable in squirrelmail.
1130 * @param $message the message object
1131 * @param $id the message id
1132 * @param $content a string with whatever is between <style> and </style>
1133 * @return a string with edited content.
1135 function sq_fixstyle($message, $id, $content){
1136 global $view_unsafe_images;
1137 $me = "sq_fixstyle";
1139 * First look for general BODY style declaration, which would be
1141 * body {background: blah-blah}
1142 * and change it to .bodyclass so we can just assign it to a <div>
1144 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1145 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1147 * Fix url('blah') declarations.
1149 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1150 "url(\\1$secremoveimg\\2)", $content);
1152 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1155 if (!$view_unsafe_images){
1156 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1157 "url(\\1$secremoveimg\\2)", $content);
1161 * Fix urls that refer to cid:
1163 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1165 $cidurl = $matches{1};
1166 $httpurl = sq_cid2http($message, $id, $cidurl);
1167 $content = preg_replace("|url\($cidurl\)|si",
1168 "url($httpurl)", $content);
1172 * Fix stupid css declarations which lead to vulnerabilities
1175 $match = Array('/expression/si',
1178 $replace = Array('idiocy', 'idiocy', 'idiocy');
1179 $content = preg_replace($match, $replace, $content);
1184 * This function converts cid: url's into the ones that can be viewed in
1187 * @param $message the message object
1188 * @param $id the message id
1189 * @param $cidurl the cid: url.
1190 * @return a string with a http-friendly url
1192 function sq_cid2http($message, $id, $cidurl, $mailbox){
1194 * Get rid of quotes.
1196 $quotchar = substr($cidurl, 0, 1);
1197 $cidurl = str_replace($quotchar, "", $cidurl);
1198 $cidurl = substr(trim($cidurl), 4);
1199 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1200 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1201 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1206 * This function changes the <body> tag into a <div> tag since we
1207 * can't really have a body-within-body.
1209 * @param $attary an array of attributes and values of <body>
1210 * @return a modified array of attributes to be set for <div>
1212 function sq_body2div($attary){
1213 $me = "sq_body2div";
1214 $divattary = Array("class"=>"'bodyclass'");
1218 if (is_array($attary) && sizeof($attary) > 0){
1219 foreach ($attary as $attname=>$attvalue){
1220 $quotchar = substr($attvalue, 0, 1);
1221 $attvalue = str_replace($quotchar, "", $attvalue);
1224 $styledef .= "background-image: url('$attvalue'); ";
1227 $styledef .= "background-color: $attvalue; ";
1230 $styledef .= "color: $attvalue; ";
1233 if (strlen($styledef) > 0){
1234 $divattary{"style"} = "\"$styledef\"";
1241 * This is the main function and the one you should actually be calling.
1242 * There are several variables you should be aware of an which need
1243 * special description.
1245 * Since the description is quite lengthy, see it here:
1246 * http://www.mricon.com/html/phpfilter.html
1248 * @param $body the string with HTML you wish to filter
1249 * @param $tag_list see description above
1250 * @param $rm_tags_with_content see description above
1251 * @param $self_closing_tags see description above
1252 * @param $force_tag_closing see description above
1253 * @param $rm_attnames see description above
1254 * @param $bad_attvals see description above
1255 * @param $add_attr_to_tag see description above
1256 * @param $message message object
1257 * @param $id message id
1258 * @return sanitized html safe to show on your pages.
1260 function sq_sanitize($body,
1262 $rm_tags_with_content,
1272 $me = "sq_sanitize";
1274 * Normalize rm_tags and rm_tags_with_content.
1276 @array_walk
($rm_tags, 'sq_casenormalize');
1277 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1278 @array_walk
($self_closing_tags, 'sq_casenormalize');
1280 * See if tag_list is of tags to remove or tags to allow.
1281 * false means remove these tags
1282 * true means allow these tags
1284 $rm_tags = array_shift($tag_list);
1286 $open_tags = Array();
1287 $trusted = "<!-- begin sanitized html -->\n";
1288 $skip_content = false;
1290 * Take care of netscape's stupid javascript entities like
1293 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1295 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1296 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1297 $free_content = substr($body, $curpos, $lt-$curpos);
1299 * Take care of <style>
1301 if ($tagname == "style" && $tagtype == 2){
1303 * This is a closing </style>. Edit the
1304 * content before we apply it.
1306 $free_content = sq_fixstyle($message, $id, $free_content);
1308 if ($skip_content == false){
1309 $trusted .= $free_content;
1312 if ($tagname != FALSE){
1314 if ($skip_content == $tagname){
1316 * Got to the end of tag we needed to remove.
1319 $skip_content = false;
1321 if ($skip_content == false){
1322 if ($tagname == "body"){
1325 if (isset($open_tags{$tagname}) &&
1326 $open_tags{$tagname} > 0){
1327 $open_tags{$tagname}--;
1337 * $rm_tags_with_content
1339 if ($skip_content == false){
1341 * See if this is a self-closing type and change
1342 * tagtype appropriately.
1345 && in_array($tagname, $self_closing_tags)){
1349 * See if we should skip this tag and any content
1352 if ($tagtype == 1 &&
1353 in_array($tagname, $rm_tags_with_content)){
1354 $skip_content = $tagname;
1356 if (($rm_tags == false
1357 && in_array($tagname, $tag_list)) ||
1358 ($rm_tags == true &&
1359 !in_array($tagname, $tag_list))){
1363 if (isset($open_tags{$tagname})){
1364 $open_tags{$tagname}++
;
1366 $open_tags{$tagname}=1;
1370 * This is where we run other checks.
1372 if (is_array($attary) && sizeof($attary) > 0){
1373 $attary = sq_fixatts($tagname,
1384 * Convert body into div.
1386 if ($tagname == "body"){
1388 $attary = sq_body2div($attary, $message, $id);
1395 if ($tagname != false && $skip_content == false){
1396 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1402 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1403 if ($force_tag_closing == true){
1404 foreach ($open_tags as $tagname=>$opentimes){
1405 while ($opentimes > 0){
1406 $trusted .= '</' . $tagname . '>';
1412 $trusted .= "<!-- end sanitized html -->\n";
1417 * This is a wrapper function to call html sanitizing routines.
1419 * @param $body the body of the message
1420 * @param $id the id of the message
1421 * @return a string with html safe to display in the browser.
1423 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1424 global $attachment_common_show_images, $view_unsafe_images,
1427 * Don't display attached images in HTML mode.
1429 $attachment_common_show_images = false;
1440 $rm_tags_with_content = Array(
1447 $self_closing_tags = Array(
1454 $force_tag_closing = false;
1456 $rm_attnames = Array(
1466 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1467 $bad_attvals = Array(
1470 "/^src|background/i" =>
1473 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1474 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1475 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1476 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1479 "\\1$secremoveimg\\2",
1480 "\\1$secremoveimg\\2",
1481 "\\1$secremoveimg\\2",
1482 "\\1$secremoveimg\\2"
1485 "/^href|action/i" =>
1488 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1489 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1490 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1491 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1506 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1507 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1508 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1509 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1523 if (!$view_unsafe_images){
1525 * Remove any references to http/https if view_unsafe_images set
1528 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1529 '/^([\'\"])\s*https*:.*([\'\"])/si');
1530 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1531 "\\1$secremoveimg\\2");
1532 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1533 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1534 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1535 "url(\\1$secremoveimg\\2)");
1538 $add_attr_to_tag = Array(
1539 "/^a$/si" => Array('target'=>'"_new"')
1541 $trusted = sq_sanitize($body,
1543 $rm_tags_with_content,
1553 if (preg_match("|$secremoveimg|si", $trusted)){
1554 $has_unsafe_images = true;