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(SM_PATH
. 'functions/imap.php');
16 require_once(SM_PATH
. '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 $read = trim(substr ($read, 0, -1));
32 $msg =& new Message();
33 $res = $msg->parseStructure($read);
35 if (!is_object($msg)) {
36 include_once(SM_PATH
. 'functions/display_messages.php');
37 global $color, $mailbox;
38 displayPageHeader( $color, urldecode($mailbox) );
39 echo "<BODY TEXT=\"$color[8]\" BGCOLOR=\"$color[4]\" LINK=\"$color[7]\" VLINK=\"$color[7]\" ALINK=\"$color[7]\">\n\n" .
41 $errormessage = _("Squirrelmail could not decode the bodystructure of the message");
42 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
43 $errormessage .= '<table><tr><td>' . htmlspecialchars($read) . '</td></tr></table>';
44 plain_error_message( $errormessage, $color );
45 echo '</body></html>';
50 foreach ($flags as $flag) {
51 $char = strtoupper($flag{1});
54 if (strtolower($flag) == '\\seen') {
59 if (strtolower($flag) == '\\answered') {
60 $msg->is_answered
= true;
64 if (strtolower($flag) == '\\deleted') {
65 $msg->is_deleted
= true;
69 if (strtolower($flag) == '\\flagged') {
70 $msg->is_flagged
= true;
74 if (strtolower($flag) == '$mdnsent') {
75 $msg->is_mdnsent
= true;
83 // listEntities($msg);
87 /* This starts the parsing of a particular structure. It is called recursively,
88 * so it can be passed different structures. It returns an object of type
90 * First, it checks to see if it is a multipart message. If it is, then it
91 * handles that as it sees is necessary. If it is just a regular entity,
92 * then it parses it and adds the necessary header information (by calling out
93 * to mime_get_elements()
96 function mime_fetch_body($imap_stream, $id, $ent_id) {
98 /* Do a bit of error correction. If we couldn't find the entity id, just guess
99 * that it is the first one. That is usually the case anyway.
104 $cmd = "FETCH $id BODY[$ent_id]";
106 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
108 $topline = trim(array_shift($data));
109 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
111 $wholemessage = implode('', $data);
112 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
113 $ret = substr($wholemessage, 0, $regs[1]);
114 /* There is some information in the content info header that could be important
115 * in order to parse html messages. Let's get them here.
117 if ($ret{0} == '<') {
118 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
120 } else if (ereg('"([^"]*)"', $topline, $regs)) {
123 global $where, $what, $mailbox, $passed_id, $startMessage;
124 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
125 if (isset($where) && isset($what)) {
126 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
128 $par .= '&startMessage=' . $startMessage . '&show_more=0';
130 $par .= '&response=' . urlencode($response) .
131 '&message=' . urlencode($message) .
132 '&topline=' . urlencode($topline);
135 '<table width="80%"><tr>' .
136 '<tr><td colspan=2>' .
137 _("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!") .
138 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
139 _("Submit message") . '</A><BR> ' .
141 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
142 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
143 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
144 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
145 "</table><BR></tt></font><hr>";
147 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
149 $wholemessage = implode('', $data);
151 $ret = $wholemessage;
156 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
158 /* Do a bit of error correction. If we couldn't find the entity id, just guess
159 * that it is the first one. That is usually the case anyway.
164 $sid = sqimap_session_id($uid_support);
165 /* Don't kill the connection if the browser is over a dialup
166 * and it would take over 30 seconds to download it.
167 * Don´t call set_time_limit in safe mode.
170 if (!ini_get('safe_mode')) {
174 $sid_s = substr($sid,0,strpos($sid, ' '));
179 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
180 echo decodeBody($body, $encoding);
183 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
186 $read = fgets ($imap_stream,8192);
189 // This could be bad -- if the section has sqimap_session_id() . ' OK'
190 // or similar, it will kill the download.
191 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
192 if (trim($read) == ')==') {
194 $read = fgets ($imap_stream,4096);
195 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
198 echo decodeBody($read1, $encoding) .
199 decodeBody($read, $encoding);
202 echo decodeBody($read, $encoding);
204 $read = fgets ($imap_stream,4096);
211 /* -[ END MIME DECODING ]----------------------------------------------------------- */
213 /* This is here for debugging purposes. It will print out a list
214 * of all the entity IDs that are in the $message object.
216 function listEntities ($message) {
218 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
219 for ($i = 0; isset($message->entities
[$i]); $i++
) {
221 $msg = listEntities($message->entities
[$i]);
231 function getPriorityStr($priority) {
232 $priority_level = substr($priority,0,1);
234 switch($priority_level) {
235 /* Check for a higher then normal priority. */
238 $priority_string = _("High");
241 /* Check for a lower then normal priority. */
244 $priority_string = _("Low");
247 /* Check for a normal priority. */
250 $priority_level = '3';
251 $priority_string = _("Normal");
255 return $priority_string;
258 /* returns a $message object for a particular entity id */
259 function getEntity ($message, $ent_id) {
260 return $message->getEntity($ent_id);
264 * Extracted from strings.php 23/03/2002
267 function translateText(&$body, $wrap_at, $charset) {
268 global $where, $what; /* from searching */
269 global $color; /* color theme */
271 require_once(SM_PATH
. 'functions/url_parser.php');
273 $body_ary = explode("\n", $body);
274 for ($i=0; $i < count($body_ary); $i++
) {
275 $line = $body_ary[$i];
276 if (strlen($line) - 2 >= $wrap_at) {
277 sqWordWrap($line, $wrap_at);
279 $line = charset_decode($charset, $line);
280 $line = str_replace("\t", ' ', $line);
289 if ($line[$pos] == ' ') {
291 } else if (strpos($line, '>', $pos) === $pos) {
300 if (!isset($color[14])) {
301 $color[14] = '#FF0000';
303 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
305 if (!isset($color[13])) {
306 $color[13] = '#800000';
308 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
311 $body_ary[$i] = $line;
313 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
317 /* This returns a parsed string called $body. That string can then
318 * be displayed as the actual message in the HTML. It contains
319 * everything needed, including HTML Tags, Attachments at the
322 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
323 /* This if statement checks for the entity to show as the
324 * primary message. To add more of them, just put them in the
325 * order that is their priority.
327 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
328 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
330 $has_unsafe_images= 0;
332 $urlmailbox = urlencode($mailbox);
333 $body_message = getEntity($message, $ent_num);
334 if (($body_message->header
->type0
== 'text') ||
335 ($body_message->header
->type0
== 'rfc822')) {
336 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
337 $body = decodeBody($body, $body_message->header
->encoding
);
338 $hookResults = do_hook("message_body", $body);
339 $body = $hookResults[1];
341 /* If there are other types that shouldn't be formatted, add
345 if ($body_message->header
->type1
== 'html') {
346 if ($show_html_default <> 1) {
347 $entity_conv = array(' ' => ' ',
354 $body = strtr($body, $entity_conv);
355 $body = strip_tags($body);
357 translateText($body, $wrap_at,
358 $body_message->header
->getParameter('charset'));
360 $body = magicHTML($body, $id, $message, $mailbox);
363 translateText($body, $wrap_at,
364 $body_message->header
->getParameter('charset'));
367 if ($has_unsafe_images) {
368 if ($view_unsafe_images) {
369 $untext = '">' . _("Hide Unsafe Images");
371 $untext = '&view_unsafe_images=1">' . _("View Unsafe Images");
373 $body .= '<center><small><a href="read_body.php?passed_id=' . $id .
374 '&passed_ent_id=' . $message->entity_id
. '&mailbox=' . $urlmailbox .
375 '&sort=' . $sort . '&startMessage=' . $startMessage . '&show_more=0' .
376 $untext . '</a></small></center><br>' . "\n";
383 function formatAttachments($message, $exclude_id, $mailbox, $id) {
384 global $where, $what, $startMessage, $color;
385 static $ShownHTML = 0;
387 $att_ar = $message->getAttachments($exclude_id);
389 if (!count($att_ar)) return '';
393 $urlMailbox = urlencode($mailbox);
395 foreach ($att_ar as $att) {
396 $ent = urldecode($att->entity_id
);
397 $header = $att->header
;
398 $type0 = strtolower($header->type0
);
399 $type1 = strtolower($header->type1
);
401 $links['download link']['text'] = _("download");
402 $links['download link']['href'] =
403 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
405 if ($type0 =='message' && $type1 == 'rfc822') {
406 $default_page = '../src/read_body.php';
407 $rfc822_header = $att->rfc822_header
;
408 $filename = decodeHeader($rfc822_header->subject
);
410 $from_o = $rfc822_header->from
;
411 if (is_object($from_o)) {
412 $from_name = $from_o->getAddress(false);
414 $from_name = _("Unknown sender");
416 $from_name = decodeHeader(htmlspecialchars($from_name));
417 $description = $from_name;
419 $default_page = '../src/download.php';
420 if (is_object($header->disposition
)) {
421 $filename = decodeHeader($header->disposition
->getProperty('filename'));
422 if (trim($filename) == '') {
423 $name = decodeHeader($header->disposition
->getProperty('name'));
424 if (trim($name) == '') {
425 if (trim( $header->id
) == '') {
426 $filename = 'untitled-[' . $ent . ']' ;
428 $filename = 'cid: ' . $header->id
;
435 if (trim( $header->id
) == '') {
436 $filename = 'untitled-[' . $ent . ']' ;
438 $filename = 'cid: ' . $header->id
;
442 if ($header->description
) {
443 $description = htmlspecialchars($header->description
);
449 $display_filename = $filename;
450 if (isset($passed_ent_id)) {
451 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
453 $passed_ent_id_link = '';
455 $defaultlink = $default_page . "?startMessage=$startMessage"
456 . "&passed_id=$id&mailbox=$urlMailbox"
457 . '&ent_id='.$ent.$passed_ent_id_link;
458 if ($where && $what) {
459 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
461 /* This executes the attachment hook with a specific MIME-type.
462 * If that doesn't have results, it tries if there's a rule
463 * for a more generic type.
465 $hookresults = do_hook("attachment $type0/$type1", $links,
466 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
467 $display_filename, $where, $what);
468 if(count($hookresults[1]) <= 1) {
469 $hookresults = do_hook("attachment $type0/*", $links,
470 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
471 $display_filename, $where, $what);
474 $links = $hookresults[1];
475 $defaultlink = $hookresults[6];
477 $attachments .= '<TR><TD>' .
478 "<A HREF=\"$defaultlink\">$display_filename</A> </TD>" .
479 '<TD><SMALL><b>' . show_readable_size($header->size
) .
480 '</b> </small></TD>' .
481 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
483 $attachments .= '<b>' . $description . '</b>';
484 $attachments .= '</SMALL></TD><TD><SMALL> ';
487 foreach ($links as $val) {
491 $attachments .= ' | ';
493 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
496 $attachments .= "</TD></TR>\n";
501 /* This function decodes the body depending on the encoding type. */
502 function decodeBody($body, $encoding) {
503 global $languages, $squirrelmail_language;
504 global $show_html_default;
506 $body = str_replace("\r\n", "\n", $body);
507 $encoding = strtolower($encoding);
509 if ($encoding == 'quoted-printable' ||
510 $encoding == 'quoted_printable') {
511 $body = quoted_printable_decode($body);
513 while (ereg("=\n", $body)) {
514 $body = ereg_replace ("=\n", '', $body);
517 } else if ($encoding == 'base64') {
518 $body = base64_decode($body);
521 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
522 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
523 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
526 // All other encodings are returned raw.
531 * This functions decode strings that is encoded according to
532 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
533 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
535 function decodeHeader ($string, $utfencode=true) {
536 global $languages, $squirrelmail_language;
537 if (is_array($string)) {
538 $string = implode("\n", $string);
541 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
542 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
543 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
547 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
550 /* Ignore white-space between consecutive encoded-words. */
551 if (strspn($res[2], " \t") != strlen($res[2])) {
555 if (ucfirst($res[4]) == 'B') {
556 $replace = base64_decode($res[5]);
558 $replace = str_replace('_', ' ', $res[5]);
559 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
561 /* Only encode into entities by default. Some places
562 * don't need the encoding, like the compose form.
565 $replace = charset_decode($res[3], $replace);
568 $string = $prefix . $replace . substr($string, strlen($res[0]));
569 $i = strlen($prefix) +
strlen($replace);
575 * Encode a string according to RFC 1522 for use in headers if it
576 * contains 8-bit characters or anything that looks like it should
579 function encodeHeader ($string) {
580 global $default_charset, $languages, $squirrelmail_language;
582 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
583 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
584 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
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);
618 $string = "=?$default_charset?Q?$ret?=";
624 /* This function trys to locate the entity_id of a specific mime element */
625 function find_ent_id($id, $message) {
626 for ($i = 0, $ret = ''; $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 if (sq_check_save_extension($message->entities
[$i])) {
632 return $message->entities
[$i]->entity_id
;
640 function sq_check_save_extension($message) {
641 $filename = $message->getFilename();
642 $ext = substr($filename, strrpos($filename,'.')+
1);
643 $save_extensions = array('jpg','jpeg','gif','png','bmp');
644 return in_array($ext, $save_extensions);
649 ** HTMLFILTER ROUTINES
653 * This function returns the final tag out of the tag name, an array
654 * of attributes, and the type of the tag. This function is called by
655 * sq_sanitize internally.
657 * @param $tagname the name of the tag.
658 * @param $attary the array of attributes and their values
659 * @param $tagtype The type of the tag (see in comments).
660 * @return a string with the final tag representation.
662 function sq_tagprint($tagname, $attary, $tagtype){
666 $fulltag = '</' . $tagname . '>';
668 $fulltag = '<' . $tagname;
669 if (is_array($attary) && sizeof($attary)){
671 while (list($attname, $attvalue) = each($attary)){
672 array_push($atts, "$attname=$attvalue");
674 $fulltag .= ' ' . join(" ", $atts);
685 * A small helper function to use with array_walk. Modifies a by-ref
686 * value and makes it lowercase.
688 * @param $val a value passed by-ref.
689 * @return void since it modifies a by-ref value.
691 function sq_casenormalize(&$val){
692 $val = strtolower($val);
696 * This function skips any whitespace from the current position within
697 * a string and to the next non-whitespace value.
699 * @param $body the string
700 * @param $offset the offset within the string where we should start
701 * looking for the next non-whitespace character.
702 * @return the location within the $body where the next
703 * non-whitespace char is located.
705 function sq_skipspace($body, $offset){
706 $me = 'sq_skipspace';
707 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
708 if (sizeof($matches{1})){
709 $count = strlen($matches{1});
716 * This function looks for the next character within a string. It's
717 * really just a glorified "strpos", except it catches if failures
720 * @param $body The string to look for needle in.
721 * @param $offset Start looking from this position.
722 * @param $needle The character/string to look for.
723 * @return location of the next occurance of the needle, or
724 * strlen($body) if needle wasn't found.
726 function sq_findnxstr($body, $offset, $needle){
727 $me = 'sq_findnxstr';
728 $pos = strpos($body, $needle, $offset);
730 $pos = strlen($body);
736 * This function takes a PCRE-style regexp and tries to match it
739 * @param $body The string to look for needle in.
740 * @param $offset Start looking from here.
741 * @param $reg A PCRE-style regex to match.
742 * @return Returns a false if no matches found, or an array
743 * with the following members:
744 * - integer with the location of the match within $body
745 * - string with whatever content between offset and the match
746 * - string with whatever it is we matched
748 function sq_findnxreg($body, $offset, $reg){
749 $me = 'sq_findnxreg';
752 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
756 $retarr{0} = $offset +
strlen($matches{1});
757 $retarr{1} = $matches{1};
758 $retarr{2} = $matches{2};
764 * This function looks for the next tag.
766 * @param $body String where to look for the next tag.
767 * @param $offset Start looking from here.
768 * @return false if no more tags exist in the body, or
769 * an array with the following members:
770 * - string with the name of the tag
771 * - array with attributes and their values
772 * - integer with tag type (1, 2, or 3)
773 * - integer where the tag starts (starting "<")
774 * - integer where the tag ends (ending ">")
775 * first three members will be false, if the tag is invalid.
777 function sq_getnxtag($body, $offset){
779 if ($offset > strlen($body)){
782 $lt = sq_findnxstr($body, $offset, "<");
783 if ($lt == strlen($body)){
788 * blah blah <tag attribute="value">
791 $pos = sq_skipspace($body, $lt+
1);
792 if ($pos >= strlen($body)){
793 return Array(false, false, false, $lt, strlen($body));
796 * There are 3 kinds of tags:
797 * 1. Opening tag, e.g.:
799 * 2. Closing tag, e.g.:
801 * 3. XHTML-style content-less tag, e.g.:
805 switch (substr($body, $pos, 1)){
812 * A comment or an SGML declaration.
814 if (substr($body, $pos+
1, 2) == "--"){
815 $gt = strpos($body, "-->", $pos);
821 return Array(false, false, false, $lt, $gt);
823 $gt = sq_findnxstr($body, $pos, ">");
824 return Array(false, false, false, $lt, $gt);
829 * Assume tagtype 1 for now. If it's type 3, we'll switch values
839 * Look for next [\W-_], which will indicate the end of the tag name.
841 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
842 if ($regary == false){
843 return Array(false, false, false, $lt, strlen($body));
845 list($pos, $tagname, $match) = $regary;
846 $tagname = strtolower($tagname);
849 * $match can be either of these:
850 * '>' indicating the end of the tag entirely.
851 * '\s' indicating the end of the tag name.
852 * '/' indicating that this is type-3 xhtml tag.
854 * Whatever else we find there indicates an invalid tag.
859 * This is an xhtml-style tag with a closing / at the
860 * end, like so: <img src="blah"/>. Check if it's followed
861 * by the closing bracket. If not, then this tag is invalid
863 if (substr($body, $pos, 2) == "/>"){
867 $gt = sq_findnxstr($body, $pos, ">");
868 $retary = Array(false, false, false, $lt, $gt);
872 return Array($tagname, false, $tagtype, $lt, $pos);
876 * Check if it's whitespace
878 if (!preg_match('/\s/', $match)){
880 * This is an invalid tag! Look for the next closing ">".
882 $gt = sq_findnxstr($body, $offset, ">");
883 return Array(false, false, false, $lt, $gt);
889 * At this point we're here:
890 * <tagname attribute='blah'>
893 * At this point we loop in order to find all attributes.
899 while ($pos <= strlen($body)){
900 $pos = sq_skipspace($body, $pos);
901 if ($pos == strlen($body)){
905 return Array(false, false, false, $lt, $pos);
908 * See if we arrived at a ">" or "/>", which means that we reached
909 * the end of the tag.
912 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
916 $pos +
= strlen($matches{1});
917 if ($matches{2} == "/>"){
921 return Array($tagname, $attary, $tagtype, $lt, $pos);
925 * There are several types of attributes, with optional
926 * [:space:] between members.
928 * attrname[:space:]=[:space:]'CDATA'
930 * attrname[:space:]=[:space:]"CDATA"
932 * attr[:space:]=[:space:]CDATA
936 * We leave types 1 and 2 the same, type 3 we check for
937 * '"' and convert to """ if needed, then wrap in
938 * double quotes. Type 4 we convert into:
941 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
942 if ($regary == false){
944 * Looks like body ended before the end of tag.
946 return Array(false, false, false, $lt, strlen($body));
948 list($pos, $attname, $match) = $regary;
949 $attname = strtolower($attname);
951 * We arrived at the end of attribute name. Several things possible
953 * '>' means the end of the tag and this is attribute type 4
954 * '/' if followed by '>' means the same thing as above
955 * '\s' means a lot of things -- look what it's followed by.
956 * anything else means the attribute is invalid.
961 * This is an xhtml-style tag with a closing / at the
962 * end, like so: <img src="blah"/>. Check if it's followed
963 * by the closing bracket. If not, then this tag is invalid
965 if (substr($body, $pos, 2) == "/>"){
969 $gt = sq_findnxstr($body, $pos, ">");
970 $retary = Array(false, false, false, $lt, $gt);
974 $attary{$attname} = '"yes"';
975 return Array($tagname, $attary, $tagtype, $lt, $pos);
979 * Skip whitespace and see what we arrive at.
981 $pos = sq_skipspace($body, $pos);
982 $char = substr($body, $pos, 1);
984 * Two things are valid here:
985 * '=' means this is attribute type 1 2 or 3.
986 * \w means this was attribute type 4.
987 * anything else we ignore and re-loop. End of tag and
988 * invalid stuff will be caught by our checks at the beginning
993 $pos = sq_skipspace($body, $pos);
995 * Here are 3 possibilities:
996 * "'" attribute type 1
997 * '"' attribute type 2
998 * everything else is the content of tag type 3
1000 $quot = substr($body, $pos, 1);
1002 $regary = sq_findnxreg($body, $pos+
1, "\'");
1003 if ($regary == false){
1004 return Array(false, false, false, $lt, strlen($body));
1006 list($pos, $attval, $match) = $regary;
1008 $attary{$attname} = "'" . $attval . "'";
1009 } else if ($quot == '"'){
1010 $regary = sq_findnxreg($body, $pos+
1, '\"');
1011 if ($regary == false){
1012 return Array(false, false, false, $lt, strlen($body));
1014 list($pos, $attval, $match) = $regary;
1016 $attary{$attname} = '"' . $attval . '"';
1019 * These are hateful. Look for \s, or >.
1021 $regary = sq_findnxreg($body, $pos, "[\s>]");
1022 if ($regary == false){
1023 return Array(false, false, false, $lt, strlen($body));
1025 list($pos, $attval, $match) = $regary;
1027 * If it's ">" it will be caught at the top.
1029 $attval = preg_replace("/\"/s", """, $attval);
1030 $attary{$attname} = '"' . $attval . '"';
1032 } else if (preg_match("|[\w/>]|", $char)) {
1034 * That was attribute type 4.
1036 $attary{$attname} = '"yes"';
1039 * An illegal character. Find next '>' and return.
1041 $gt = sq_findnxstr($body, $pos, ">");
1042 return Array(false, false, false, $lt, $gt);
1048 * The fact that we got here indicates that the tag end was never
1049 * found. Return invalid tag indication so it gets stripped.
1051 return Array(false, false, false, $lt, strlen($body));
1055 * This function checks attribute values for entity-encoded values
1056 * and returns them translated into 8-bit strings so we can run
1059 * @param $attvalue A string to run entity check against.
1060 * @return Translated value.
1062 function sq_deent($attvalue){
1065 * See if we have to run the checks first. All entities must start
1068 if (strpos($attvalue, "&") === false){
1072 * Check named entities first.
1074 $trans = get_html_translation_table(HTML_ENTITIES
);
1076 * Leave " in, as it can mess us up.
1078 $trans = array_flip($trans);
1079 unset($trans{"""});
1080 while (list($ent, $val) = each($trans)){
1081 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1084 * Now translate numbered entities from 1 to 255 if needed.
1086 if (strpos($attvalue, "#") !== false){
1087 $omit = Array(34, 39);
1088 for ($asc=1; $asc<256; $asc++
){
1089 if (!in_array($asc, $omit)){
1091 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1093 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1094 "$chr\\1", $attvalue);
1102 * This function runs various checks against the attributes.
1104 * @param $tagname String with the name of the tag.
1105 * @param $attary Array with all tag attributes.
1106 * @param $rm_attnames See description for sq_sanitize
1107 * @param $bad_attvals See description for sq_sanitize
1108 * @param $add_attr_to_tag See description for sq_sanitize
1109 * @param $message message object
1110 * @param $id message id
1111 * @return Array with modified attributes.
1113 function sq_fixatts($tagname,
1123 while (list($attname, $attvalue) = each($attary)){
1125 * See if this attribute should be removed.
1127 foreach ($rm_attnames as $matchtag=>$matchattrs){
1128 if (preg_match($matchtag, $tagname)){
1129 foreach ($matchattrs as $matchattr){
1130 if (preg_match($matchattr, $attname)){
1131 unset($attary{$attname});
1138 * Remove any entities.
1140 $attvalue = sq_deent($attvalue);
1143 * Now let's run checks on the attvalues.
1144 * I don't expect anyone to comprehend this. If you do,
1145 * get in touch with me so I can drive to where you live and
1146 * shake your hand personally. :)
1148 foreach ($bad_attvals as $matchtag=>$matchattrs){
1149 if (preg_match($matchtag, $tagname)){
1150 foreach ($matchattrs as $matchattr=>$valary){
1151 if (preg_match($matchattr, $attname)){
1153 * There are two arrays in valary.
1155 * Second one is replacements
1157 list($valmatch, $valrepl) = $valary;
1159 preg_replace($valmatch, $valrepl, $attvalue);
1160 if ($newvalue != $attvalue){
1161 $attary{$attname} = $newvalue;
1168 * Turn cid: urls into http-friendly ones.
1170 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1171 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1175 * See if we need to append any attributes to this tag.
1177 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1178 if (preg_match($matchtag, $tagname)){
1179 $attary = array_merge($attary, $addattary);
1186 * This function edits the style definition to make them friendly and
1187 * usable in squirrelmail.
1189 * @param $message the message object
1190 * @param $id the message id
1191 * @param $content a string with whatever is between <style> and </style>
1192 * @return a string with edited content.
1194 function sq_fixstyle($message, $id, $content){
1195 global $view_unsafe_images;
1196 $me = 'sq_fixstyle';
1198 * First look for general BODY style declaration, which would be
1200 * body {background: blah-blah}
1201 * and change it to .bodyclass so we can just assign it to a <div>
1203 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1204 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1206 * Fix url('blah') declarations.
1208 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1209 "url(\\1$secremoveimg\\2)", $content);
1211 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1214 if (!$view_unsafe_images){
1215 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1216 "url(\\1$secremoveimg\\2)", $content);
1220 * Fix urls that refer to cid:
1222 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1224 $cidurl = $matches{1};
1225 $httpurl = sq_cid2http($message, $id, $cidurl);
1226 $content = preg_replace("|url\($cidurl\)|si",
1227 "url($httpurl)", $content);
1231 * Fix stupid css declarations which lead to vulnerabilities
1234 $match = Array('/expression/si',
1237 $replace = Array('idiocy', 'idiocy', 'idiocy');
1238 $content = preg_replace($match, $replace, $content);
1243 * This function converts cid: url's into the ones that can be viewed in
1246 * @param $message the message object
1247 * @param $id the message id
1248 * @param $cidurl the cid: url.
1249 * @return a string with a http-friendly url
1251 function sq_cid2http($message, $id, $cidurl, $mailbox){
1253 * Get rid of quotes.
1255 $quotchar = substr($cidurl, 0, 1);
1256 $cidurl = str_replace($quotchar, "", $cidurl);
1257 $cidurl = substr(trim($cidurl), 4);
1258 $linkurl = find_ent_id($cidurl, $message);
1259 /* in case of non-save cid links $httpurl should be replaced by a sort of
1260 unsave link image */
1263 $httpurl = $quotchar . '../src/download.php?absolute_dl=true&' .
1264 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1265 '&ent_id=' . $linkurl . $quotchar;
1271 * This function changes the <body> tag into a <div> tag since we
1272 * can't really have a body-within-body.
1274 * @param $attary an array of attributes and values of <body>
1275 * @return a modified array of attributes to be set for <div>
1277 function sq_body2div($attary){
1278 $me = 'sq_body2div';
1279 $divattary = Array('class' => "'bodyclass'");
1280 $bgcolor = '#ffffff';
1283 if (is_array($attary) && sizeof($attary) > 0){
1284 foreach ($attary as $attname=>$attvalue){
1285 $quotchar = substr($attvalue, 0, 1);
1286 $attvalue = str_replace($quotchar, "", $attvalue);
1289 $styledef .= "background-image: url('$attvalue'); ";
1292 $styledef .= "background-color: $attvalue; ";
1295 $styledef .= "color: $attvalue; ";
1299 if (strlen($styledef) > 0){
1300 $divattary{"style"} = "\"$styledef\"";
1307 * This is the main function and the one you should actually be calling.
1308 * There are several variables you should be aware of an which need
1309 * special description.
1311 * Since the description is quite lengthy, see it here:
1312 * http://www.mricon.com/html/phpfilter.html
1314 * @param $body the string with HTML you wish to filter
1315 * @param $tag_list see description above
1316 * @param $rm_tags_with_content see description above
1317 * @param $self_closing_tags see description above
1318 * @param $force_tag_closing see description above
1319 * @param $rm_attnames see description above
1320 * @param $bad_attvals see description above
1321 * @param $add_attr_to_tag see description above
1322 * @param $message message object
1323 * @param $id message id
1324 * @return sanitized html safe to show on your pages.
1326 function sq_sanitize($body,
1328 $rm_tags_with_content,
1338 $me = 'sq_sanitize';
1340 * Normalize rm_tags and rm_tags_with_content.
1342 @array_walk
($rm_tags, 'sq_casenormalize');
1343 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1344 @array_walk
($self_closing_tags, 'sq_casenormalize');
1346 * See if tag_list is of tags to remove or tags to allow.
1347 * false means remove these tags
1348 * true means allow these tags
1350 $rm_tags = array_shift($tag_list);
1352 $open_tags = Array();
1353 $trusted = "<!-- begin sanitized html -->\n";
1354 $skip_content = false;
1356 * Take care of netscape's stupid javascript entities like
1359 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1361 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1362 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1363 $free_content = substr($body, $curpos, $lt-$curpos);
1365 * Take care of <style>
1367 if ($tagname == "style" && $tagtype == 2){
1369 * This is a closing </style>. Edit the
1370 * content before we apply it.
1372 $free_content = sq_fixstyle($message, $id, $free_content);
1374 if ($skip_content == false){
1375 $trusted .= $free_content;
1377 if ($tagname != FALSE){
1379 if ($skip_content == $tagname){
1381 * Got to the end of tag we needed to remove.
1384 $skip_content = false;
1386 if ($skip_content == false){
1387 if ($tagname == "body"){
1390 if (isset($open_tags{$tagname}) &&
1391 $open_tags{$tagname} > 0){
1392 $open_tags{$tagname}--;
1401 * $rm_tags_with_content
1403 if ($skip_content == false){
1405 * See if this is a self-closing type and change
1406 * tagtype appropriately.
1409 && in_array($tagname, $self_closing_tags)){
1413 * See if we should skip this tag and any content
1416 if ($tagtype == 1 &&
1417 in_array($tagname, $rm_tags_with_content)){
1418 $skip_content = $tagname;
1420 if (($rm_tags == false
1421 && in_array($tagname, $tag_list)) ||
1422 ($rm_tags == true &&
1423 !in_array($tagname, $tag_list))){
1427 if (isset($open_tags{$tagname})){
1428 $open_tags{$tagname}++
;
1430 $open_tags{$tagname}=1;
1434 * This is where we run other checks.
1436 if (is_array($attary) && sizeof($attary) > 0){
1437 $attary = sq_fixatts($tagname,
1448 * Convert body into div.
1450 if ($tagname == "body"){
1452 $attary = sq_body2div($attary, $message, $id);
1458 if ($tagname != false && $skip_content == false){
1459 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1464 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1465 if ($force_tag_closing == true){
1466 foreach ($open_tags as $tagname=>$opentimes){
1467 while ($opentimes > 0){
1468 $trusted .= '</' . $tagname . '>';
1474 $trusted .= "<!-- end sanitized html -->\n";
1479 * This is a wrapper function to call html sanitizing routines.
1481 * @param $body the body of the message
1482 * @param $id the id of the message
1483 * @return a string with html safe to display in the browser.
1485 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1486 global $attachment_common_show_images, $view_unsafe_images,
1489 * Don't display attached images in HTML mode.
1491 $attachment_common_show_images = false;
1504 $rm_tags_with_content = Array(
1511 $self_closing_tags = Array(
1518 $force_tag_closing = false;
1520 $rm_attnames = Array(
1530 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1531 $bad_attvals = Array(
1534 "/^src|background/i" =>
1537 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1538 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1539 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1540 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1543 "\\1$secremoveimg\\2",
1544 "\\1$secremoveimg\\2",
1545 "\\1$secremoveimg\\2",
1546 "\\1$secremoveimg\\2"
1549 "/^href|action/i" =>
1552 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1553 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1554 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1555 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1570 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1571 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1572 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1573 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1587 if (!$view_unsafe_images){
1589 * Remove any references to http/https if view_unsafe_images set
1592 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1593 '/^([\'\"])\s*https*:.*([\'\"])/si');
1594 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1595 "\\1$secremoveimg\\2");
1596 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1597 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1598 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1599 "url(\\1$secremoveimg\\2)");
1602 $add_attr_to_tag = Array(
1603 "/^a$/si" => Array('target'=>'"_new"')
1605 $trusted = sq_sanitize($body,
1607 $rm_tags_with_content,
1617 if (preg_match("|$secremoveimg|si", $trusted)){
1618 $has_unsafe_images = true;