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);
35 if (!is_object($msg)) {
36 include_once( '../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) {
99 * do a bit of error correction. If we couldn't find the entity id, just guess
100 * that it is the first one. That is usually the case anyway.
105 $cmd = "FETCH $id BODY[$ent_id]";
107 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
109 $topline = trim(array_shift( $data ));
110 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
112 $wholemessage = implode('', $data);
113 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
115 $ret = substr( $wholemessage, 0, $regs[1] );
117 There is some information in the content info header that could be important
118 in order to parse html messages. Let's get them here.
120 if ( $ret{0} == '<' ) {
121 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
123 } else if (ereg('"([^"]*)"', $topline, $regs)) {
126 global $where, $what, $mailbox, $passed_id, $startMessage;
127 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
128 if (isset($where) && isset($what)) {
129 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
131 $par .= "&startMessage=$startMessage&show_more=0";
133 $par .= '&response=' . urlencode($response) .
134 '&message=' . urlencode($message).
135 '&topline=' . urlencode($topline);
138 '<table width="80%"><tr>' .
139 '<tr><td colspan=2>' .
140 _("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!") .
141 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
142 _("Submit message") . '</A><BR> ' .
144 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
145 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
146 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
147 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
148 "</table><BR></tt></font><hr>";
150 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
152 $wholemessage = implode('', $data);
154 $ret = $wholemessage;
159 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
161 // do a bit of error correction. If we couldn't find the entity id, just guess
162 // that it is the first one. That is usually the case anyway.
166 $sid = sqimap_session_id($uid_support);
167 // Don't kill the connection if the browser is over a dialup
168 // and it would take over 30 seconds to download it.
170 // don´t call set_time_limit in safe mode.
171 if (!ini_get("safe_mode")) {
175 $sid_s = substr($sid,0,strpos($sid, ' '));
180 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
181 echo decodeBody($body, $encoding);
184 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
187 $read = fgets ($imap_stream,8192);
190 // This could be bad -- if the section has sqimap_session_id() . ' OK'
191 // or similar, it will kill the download.
192 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
193 if (trim($read) == ')==') {
195 $read = fgets ($imap_stream,4096);
196 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
199 echo decodeBody($read1, $encoding) .
200 decodeBody($read, $encoding);
203 echo decodeBody($read, $encoding);
205 $read = fgets ($imap_stream,4096);
212 /* -[ END MIME DECODING ]----------------------------------------------------------- */
214 // This is here for debugging purposese. It will print out a list
215 // of all the entity IDs that are in the $message object.
217 function listEntities ($message) {
219 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
220 for ($i = 0;isset($message->entities
[$i]); $i++
) {
222 $msg = listEntities($message->entities
[$i]);
232 function getPriorityStr($priority) {
233 $priority_level = substr($priority,0,1);
235 switch($priority_level) {
236 /* check for a higher then normal priority. */
239 $priority_string = _("High");
242 /* check for a lower then normal priority. */
245 $priority_string = _("Low");
248 /* check for a normal priority. */
251 $priority_level = '3';
252 $priority_string = _("Normal");
256 return $priority_string;
259 /* returns a $message object for a particular entity id */
260 function getEntity ($message, $ent_id) {
261 return $message->getEntity($ent_id);
266 * Extracted from strings.php 23/03/2002
269 function translateText(&$body, $wrap_at, $charset) {
270 global $where, $what; /* from searching */
271 global $color; /* color theme */
273 require_once('../functions/url_parser.php');
275 $body_ary = explode("\n", $body);
277 for ($i=0; $i < count($body_ary); $i++
) {
278 $line = $body_ary[$i];
279 if (strlen($line) - 2 >= $wrap_at) {
280 sqWordWrap($line, $wrap_at);
282 $line = charset_decode($charset, $line);
283 $line = str_replace("\t", ' ', $line);
289 $j = strlen( $line );
291 while ( $pos < $j ) {
292 if ($line[$pos] == ' ') {
294 } else if (strpos($line, '>', $pos) === $pos) {
303 if (! isset($color[14])) {
304 $color[14] = '#FF0000';
306 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
308 if (! isset($color[13])) {
309 $color[13] = '#800000';
311 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
314 $body_ary[$i] = $line;
316 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
320 /* This returns a parsed string called $body. That string can then
321 be displayed as the actual message in the HTML. It contains
322 everything needed, including HTML Tags, Attachments at the
325 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
326 // this if statement checks for the entity to show as the
327 // primary message. To add more of them, just put them in the
328 // order that is their priority.
329 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
330 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
332 $has_unsafe_images= 0;
334 $urlmailbox = urlencode($mailbox);
335 $body_message = getEntity($message, $ent_num);
336 if (($body_message->header
->type0
== 'text') ||
337 ($body_message->header
->type0
== 'rfc822')) {
338 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
339 $body = decodeBody($body, $body_message->header
->encoding
);
340 $hookResults = do_hook("message_body", $body);
341 $body = $hookResults[1];
343 // If there are other types that shouldn't be formatted, add
346 if ($body_message->header
->type1
== 'html') {
347 if ( $show_html_default <> 1 ) {
348 $entity_conv = array(' ' => ' ',
351 $body = strip_tags( $body );
352 $body = strtr($body, $entity_conv);
354 translateText($body, $wrap_at,
355 $body_message->header
->getParameter('charset'));
357 $body = magicHTML( $body, $id, $message, $mailbox );
360 translateText($body, $wrap_at,
361 $body_message->header
->getParameter('charset'));
364 if ($has_unsafe_images) {
365 if ($view_unsafe_images) {
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\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
368 $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";
376 function formatAttachments($message, $exclude_id, $mailbox, $id) {
377 global $where, $what, $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&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));
410 $description = $from_name;
412 $default_page = '../src/download.php';
413 if (is_object($header->disposition
)) {
414 $filename = decodeHeader($header->disposition
->getProperty('filename'));
415 if (trim($filename) == '') {
416 $name = decodeHeader($header->disposition
->getProperty('name'));
417 if (trim($name) == '') {
418 if ( trim( $header->id
) == '' )
419 $filename = 'untitled-[' . $ent . ']' ;
421 $filename = 'cid: ' . $header->id
;
427 if ( trim( $header->id
) == '' )
428 $filename = 'untitled-[' . $ent . ']' ;
430 $filename = 'cid: ' . $header->id
;
433 if ($header->description
) {
434 $description = htmlspecialchars($header->description
);
440 $display_filename = $filename;
441 if (isset($passed_ent_id)) {
442 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
444 $passed_ent_id_link = '';
446 $DefaultLink = $default_page . "?startMessage=$startMessage"
447 . "&passed_id=$id&mailbox=$urlMailbox"
448 . '&ent_id='.$ent.$passed_ent_id_link;
449 if ($where && $what) {
450 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
452 /* this executes the attachment hook with a specific MIME-type.
453 * if that doens't have results, it tries if there's a rule
454 * for a more generic type. */
455 $HookResults = do_hook("attachment $type0/$type1", $Links,
456 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
457 $display_filename, $where, $what);
458 if(count($HookResults[1]) <= 1) {
459 $HookResults = do_hook("attachment $type0/*", $Links,
460 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
461 $display_filename, $where, $what);
464 $Links = $HookResults[1];
465 $DefaultLink = $HookResults[6];
467 $attachments .= '<TR><TD>' .
468 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
469 '<TD><SMALL><b>' . show_readable_size($header->size
) .
470 '</b> </small></TD>' .
471 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
473 $attachments .= '<b>' . $description . '</b>';
474 $attachments .= '</SMALL></TD><TD><SMALL> ';
477 foreach ($Links as $Val) {
481 $attachments .= ' | ';
483 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
486 $attachments .= "</TD></TR>\n";
491 /** this function decodes the body depending on the encoding type. **/
492 function decodeBody($body, $encoding) {
493 global $languages, $squirrelmail_language;
495 $body = str_replace("\r\n", "\n", $body);
496 $encoding = strtolower($encoding);
498 global $show_html_default;
500 if ($encoding == 'quoted-printable' ||
501 $encoding == 'quoted_printable') {
502 $body = quoted_printable_decode($body);
504 while (ereg("=\n", $body)) {
505 $body = ereg_replace ("=\n", '', $body);
508 } else if ($encoding == 'base64') {
509 $body = base64_decode($body);
512 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
513 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
514 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
517 // All other encodings are returned raw.
522 * This functions decode strings that is encoded according to
523 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
524 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
526 function decodeHeader ($string, $utfencode=true) {
527 global $languages, $squirrelmail_language;
528 if (is_array($string)) {
529 $string = implode("\n", $string);
532 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
533 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
534 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
538 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
541 // Ignore white-space between consecutive encoded-words
542 if (strspn($res[2], " \t") != strlen($res[2])) {
546 if (ucfirst($res[4]) == 'B') {
547 $replace = base64_decode($res[5]);
549 $replace = str_replace('_', ' ', $res[5]);
550 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
552 /* Only encode into entities by default. Some places
553 don't need the encoding, like the compose form. */
555 $replace = charset_decode($res[3], $replace);
558 $string = $prefix . $replace . substr($string, strlen($res[0]));
559 $i = strlen($prefix) +
strlen($replace);
565 * Encode a string according to RFC 1522 for use in headers if it
566 * contains 8-bit characters or anything that looks like it should
569 function encodeHeader ($string) {
570 global $default_charset, $languages, $squirrelmail_language;
572 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
573 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
574 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
577 // Encode only if the string contains 8-bit characters or =?
578 $j = strlen( $string );
579 $l = strstr($string, '=?'); // Must be encoded ?
581 for( $i=0; $i < $j; ++
$i) {
582 switch( $string{$i} ) {
596 $k = ord( $string{$i} );
598 $ret .= sprintf("=%02X", $k);
606 $string = "=?$default_charset?Q?$ret?=";
612 /* This function trys to locate the entity_id of a specific mime element */
614 function find_ent_id( $id, $message ) {
616 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
617 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
618 $ret = find_ent_id( $id, $message->entities
[$i] );
620 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 ) {
621 if (sq_check_save_extension($message->entities
[$i])) {
622 $ret = $message->entities
[$i]->entity_id
;
632 function sq_check_save_extension($message) {
633 $filename = $message->getFilename();
634 $ext = substr($filename, strrpos($filename,'.')+
1);
635 $save_extensions = array('jpg','jpeg','gif','png','bmp');
636 return (in_array($ext, $save_extensions));
641 ** HTMLFILTER ROUTINES
645 * This function returns the final tag out of the tag name, an array
646 * of attributes, and the type of the tag. This function is called by
647 * sq_sanitize internally.
649 * @param $tagname the name of the tag.
650 * @param $attary the array of attributes and their values
651 * @param $tagtype The type of the tag (see in comments).
652 * @return a string with the final tag representation.
654 function sq_tagprint($tagname, $attary, $tagtype){
659 $fulltag = '</' . $tagname . '>';
661 $fulltag = '<' . $tagname;
662 if (is_array($attary) && sizeof($attary)){
664 while (list($attname, $attvalue) = each($attary)){
665 array_push($atts, "$attname=$attvalue");
667 $fulltag .= ' ' . join(" ", $atts);
678 * A small helper function to use with array_walk. Modifies a by-ref
679 * value and makes it lowercase.
681 * @param $val a value passed by-ref.
682 * @return void since it modifies a by-ref value.
684 function sq_casenormalize(&$val){
685 $val = strtolower($val);
689 * This function skips any whitespace from the current position within
690 * a string and to the next non-whitespace value.
692 * @param $body the string
693 * @param $offset the offset within the string where we should start
694 * looking for the next non-whitespace character.
695 * @return the location within the $body where the next
696 * non-whitespace char is located.
698 function sq_skipspace($body, $offset){
699 $me = 'sq_skipspace';
700 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
701 if (sizeof($matches{1})){
702 $count = strlen($matches{1});
709 * This function looks for the next character within a string. It's
710 * really just a glorified "strpos", except it catches if failures
713 * @param $body The string to look for needle in.
714 * @param $offset Start looking from this position.
715 * @param $needle The character/string to look for.
716 * @return location of the next occurance of the needle, or
717 * strlen($body) if needle wasn't found.
719 function sq_findnxstr($body, $offset, $needle){
720 $me = 'sq_findnxstr';
721 $pos = strpos($body, $needle, $offset);
723 $pos = strlen($body);
729 * This function takes a PCRE-style regexp and tries to match it
732 * @param $body The string to look for needle in.
733 * @param $offset Start looking from here.
734 * @param $reg A PCRE-style regex to match.
735 * @return Returns a false if no matches found, or an array
736 * with the following members:
737 * - integer with the location of the match within $body
738 * - string with whatever content between offset and the match
739 * - string with whatever it is we matched
741 function sq_findnxreg($body, $offset, $reg){
742 $me = 'sq_findnxreg';
745 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
749 $retarr{0} = $offset +
strlen($matches{1});
750 $retarr{1} = $matches{1};
751 $retarr{2} = $matches{2};
757 * This function looks for the next tag.
759 * @param $body String where to look for the next tag.
760 * @param $offset Start looking from here.
761 * @return false if no more tags exist in the body, or
762 * an array with the following members:
763 * - string with the name of the tag
764 * - array with attributes and their values
765 * - integer with tag type (1, 2, or 3)
766 * - integer where the tag starts (starting "<")
767 * - integer where the tag ends (ending ">")
768 * first three members will be false, if the tag is invalid.
770 function sq_getnxtag($body, $offset){
772 if ($offset > strlen($body)){
775 $lt = sq_findnxstr($body, $offset, "<");
776 if ($lt == strlen($body)){
781 * blah blah <tag attribute="value">
784 $pos = sq_skipspace($body, $lt+
1);
785 if ($pos >= strlen($body)){
786 return Array(false, false, false, $lt, strlen($body));
789 * There are 3 kinds of tags:
790 * 1. Opening tag, e.g.:
792 * 2. Closing tag, e.g.:
794 * 3. XHTML-style content-less tag, e.g.:
798 switch (substr($body, $pos, 1)){
805 * A comment or an SGML declaration.
807 if (substr($body, $pos+
1, 2) == "--"){
808 $gt = strpos($body, "-->", $pos);
814 return Array(false, false, false, $lt, $gt);
816 $gt = sq_findnxstr($body, $pos, ">");
817 return Array(false, false, false, $lt, $gt);
822 * Assume tagtype 1 for now. If it's type 3, we'll switch values
832 * Look for next [\W-_], which will indicate the end of the tag name.
834 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
835 if ($regary == false){
836 return Array(false, false, false, $lt, strlen($body));
838 list($pos, $tagname, $match) = $regary;
839 $tagname = strtolower($tagname);
842 * $match can be either of these:
843 * '>' indicating the end of the tag entirely.
844 * '\s' indicating the end of the tag name.
845 * '/' indicating that this is type-3 xhtml tag.
847 * Whatever else we find there indicates an invalid tag.
852 * This is an xhtml-style tag with a closing / at the
853 * end, like so: <img src="blah"/>. Check if it's followed
854 * by the closing bracket. If not, then this tag is invalid
856 if (substr($body, $pos, 2) == "/>"){
860 $gt = sq_findnxstr($body, $pos, ">");
861 $retary = Array(false, false, false, $lt, $gt);
865 return Array($tagname, false, $tagtype, $lt, $pos);
869 * Check if it's whitespace
871 if (preg_match("/\s/", $match)){
874 * This is an invalid tag! Look for the next closing ">".
876 $gt = sq_findnxstr($body, $offset, ">");
877 return Array(false, false, false, $lt, $gt);
882 * At this point we're here:
883 * <tagname attribute='blah'>
886 * At this point we loop in order to find all attributes.
892 while ($pos <= strlen($body)){
893 $pos = sq_skipspace($body, $pos);
894 if ($pos == strlen($body)){
898 return Array(false, false, false, $lt, $pos);
901 * See if we arrived at a ">" or "/>", which means that we reached
902 * the end of the tag.
905 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
909 $pos +
= strlen($matches{1});
910 if ($matches{2} == "/>"){
914 return Array($tagname, $attary, $tagtype, $lt, $pos);
918 * There are several types of attributes, with optional
919 * [:space:] between members.
921 * attrname[:space:]=[:space:]'CDATA'
923 * attrname[:space:]=[:space:]"CDATA"
925 * attr[:space:]=[:space:]CDATA
929 * We leave types 1 and 2 the same, type 3 we check for
930 * '"' and convert to """ if needed, then wrap in
931 * double quotes. Type 4 we convert into:
934 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
935 if ($regary == false){
937 * Looks like body ended before the end of tag.
939 return Array(false, false, false, $lt, strlen($body));
941 list($pos, $attname, $match) = $regary;
942 $attname = strtolower($attname);
944 * We arrived at the end of attribute name. Several things possible
946 * '>' means the end of the tag and this is attribute type 4
947 * '/' if followed by '>' means the same thing as above
948 * '\s' means a lot of things -- look what it's followed by.
949 * anything else means the attribute is invalid.
954 * This is an xhtml-style tag with a closing / at the
955 * end, like so: <img src="blah"/>. Check if it's followed
956 * by the closing bracket. If not, then this tag is invalid
958 if (substr($body, $pos, 2) == "/>"){
962 $gt = sq_findnxstr($body, $pos, ">");
963 $retary = Array(false, false, false, $lt, $gt);
967 $attary{$attname} = '"yes"';
968 return Array($tagname, $attary, $tagtype, $lt, $pos);
972 * Skip whitespace and see what we arrive at.
974 $pos = sq_skipspace($body, $pos);
975 $char = substr($body, $pos, 1);
977 * Two things are valid here:
978 * '=' means this is attribute type 1 2 or 3.
979 * \w means this was attribute type 4.
980 * anything else we ignore and re-loop. End of tag and
981 * invalid stuff will be caught by our checks at the beginning
986 $pos = sq_skipspace($body, $pos);
988 * Here are 3 possibilities:
989 * "'" attribute type 1
990 * '"' attribute type 2
991 * everything else is the content of tag type 3
993 $quot = substr($body, $pos, 1);
995 $regary = sq_findnxreg($body, $pos+
1, "\'");
996 if ($regary == false){
997 return Array(false, false, false, $lt, strlen($body));
999 list($pos, $attval, $match) = $regary;
1001 $attary{$attname} = "'" . $attval . "'";
1002 } else if ($quot == '"'){
1003 $regary = sq_findnxreg($body, $pos+
1, '\"');
1004 if ($regary == false){
1005 return Array(false, false, false, $lt, strlen($body));
1007 list($pos, $attval, $match) = $regary;
1009 $attary{$attname} = '"' . $attval . '"';
1012 * These are hateful. Look for \s, or >.
1014 $regary = sq_findnxreg($body, $pos, "[\s>]");
1015 if ($regary == false){
1016 return Array(false, false, false, $lt, strlen($body));
1018 list($pos, $attval, $match) = $regary;
1020 * If it's ">" it will be caught at the top.
1022 $attval = preg_replace("/\"/s", """, $attval);
1023 $attary{$attname} = '"' . $attval . '"';
1025 } else if (preg_match("|[\w/>]|", $char)) {
1027 * That was attribute type 4.
1029 $attary{$attname} = '"yes"';
1032 * An illegal character. Find next '>' and return.
1034 $gt = sq_findnxstr($body, $pos, ">");
1035 return Array(false, false, false, $lt, $gt);
1040 * The fact that we got here indicates that the tag end was never
1041 * found. Return invalid tag indication so it gets stripped.
1043 return Array(false, false, false, $lt, strlen($body));
1047 * This function checks attribute values for entity-encoded values
1048 * and returns them translated into 8-bit strings so we can run
1051 * @param $attvalue A string to run entity check against.
1052 * @return Translated value.
1054 function sq_deent($attvalue){
1057 * See if we have to run the checks first. All entities must start
1060 if (strpos($attvalue, "&") === false){
1064 * Check named entities first.
1066 $trans = get_html_translation_table(HTML_ENTITIES
);
1068 * Leave " in, as it can mess us up.
1070 $trans = array_flip($trans);
1071 unset($trans{"""});
1072 while (list($ent, $val) = each($trans)){
1073 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1076 * Now translate numbered entities from 1 to 255 if needed.
1078 if (strpos($attvalue, "#") !== false){
1079 $omit = Array(34, 39);
1080 for ($asc=1; $asc<256; $asc++
){
1081 if (!in_array($asc, $omit)){
1083 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1085 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1086 "$chr\\1", $attvalue);
1094 * This function runs various checks against the attributes.
1096 * @param $tagname String with the name of the tag.
1097 * @param $attary Array with all tag attributes.
1098 * @param $rm_attnames See description for sq_sanitize
1099 * @param $bad_attvals See description for sq_sanitize
1100 * @param $add_attr_to_tag See description for sq_sanitize
1101 * @param $message message object
1102 * @param $id message id
1103 * @return Array with modified attributes.
1105 function sq_fixatts($tagname,
1115 while (list($attname, $attvalue) = each($attary)){
1117 * See if this attribute should be removed.
1119 foreach ($rm_attnames as $matchtag=>$matchattrs){
1120 if (preg_match($matchtag, $tagname)){
1121 foreach ($matchattrs as $matchattr){
1122 if (preg_match($matchattr, $attname)){
1123 unset($attary{$attname});
1130 * Remove any entities.
1132 $attvalue = sq_deent($attvalue);
1135 * Now let's run checks on the attvalues.
1136 * I don't expect anyone to comprehend this. If you do,
1137 * get in touch with me so I can drive to where you live and
1138 * shake your hand personally. :)
1140 foreach ($bad_attvals as $matchtag=>$matchattrs){
1141 if (preg_match($matchtag, $tagname)){
1142 foreach ($matchattrs as $matchattr=>$valary){
1143 if (preg_match($matchattr, $attname)){
1145 * There are two arrays in valary.
1147 * Second one is replacements
1149 list($valmatch, $valrepl) = $valary;
1151 preg_replace($valmatch, $valrepl, $attvalue);
1152 if ($newvalue != $attvalue){
1153 $attary{$attname} = $newvalue;
1160 * Turn cid: urls into http-friendly ones.
1162 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1163 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1167 * See if we need to append any attributes to this tag.
1169 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1170 if (preg_match($matchtag, $tagname)){
1171 $attary = array_merge($attary, $addattary);
1178 * This function edits the style definition to make them friendly and
1179 * usable in squirrelmail.
1181 * @param $message the message object
1182 * @param $id the message id
1183 * @param $content a string with whatever is between <style> and </style>
1184 * @return a string with edited content.
1186 function sq_fixstyle($message, $id, $content){
1187 global $view_unsafe_images;
1188 $me = 'sq_fixstyle';
1190 * First look for general BODY style declaration, which would be
1192 * body {background: blah-blah}
1193 * and change it to .bodyclass so we can just assign it to a <div>
1195 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1196 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1198 * Fix url('blah') declarations.
1200 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1201 "url(\\1$secremoveimg\\2)", $content);
1203 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1206 if (!$view_unsafe_images){
1207 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1208 "url(\\1$secremoveimg\\2)", $content);
1212 * Fix urls that refer to cid:
1214 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1216 $cidurl = $matches{1};
1217 $httpurl = sq_cid2http($message, $id, $cidurl);
1218 $content = preg_replace("|url\($cidurl\)|si",
1219 "url($httpurl)", $content);
1223 * Fix stupid css declarations which lead to vulnerabilities
1226 $match = Array('/expression/si',
1229 $replace = Array('idiocy', 'idiocy', 'idiocy');
1230 $content = preg_replace($match, $replace, $content);
1235 * This function converts cid: url's into the ones that can be viewed in
1238 * @param $message the message object
1239 * @param $id the message id
1240 * @param $cidurl the cid: url.
1241 * @return a string with a http-friendly url
1243 function sq_cid2http($message, $id, $cidurl, $mailbox){
1245 * Get rid of quotes.
1247 $quotchar = substr($cidurl, 0, 1);
1248 $cidurl = str_replace($quotchar, "", $cidurl);
1249 $cidurl = substr(trim($cidurl), 4);
1250 $linkurl = find_ent_id($cidurl, $message);
1251 /* in case of non-save cid links $httpurl should be replaced by a sort of
1252 unsave link image */
1255 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1256 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1257 "&ent_id=" . $linkurl . $quotchar;
1263 * This function changes the <body> tag into a <div> tag since we
1264 * can't really have a body-within-body.
1266 * @param $attary an array of attributes and values of <body>
1267 * @return a modified array of attributes to be set for <div>
1269 function sq_body2div($attary){
1270 $me = 'sq_body2div';
1271 $divattary = Array( 'class' => "'bodyclass'" );
1272 $bgcolor = '#ffffff';
1275 if (is_array($attary) && sizeof($attary) > 0){
1276 foreach ($attary as $attname=>$attvalue){
1277 $quotchar = substr($attvalue, 0, 1);
1278 $attvalue = str_replace($quotchar, "", $attvalue);
1281 $styledef .= "background-image: url('$attvalue'); ";
1284 $styledef .= "background-color: $attvalue; ";
1287 $styledef .= "color: $attvalue; ";
1290 if (strlen($styledef) > 0){
1291 $divattary{"style"} = "\"$styledef\"";
1298 * This is the main function and the one you should actually be calling.
1299 * There are several variables you should be aware of an which need
1300 * special description.
1302 * Since the description is quite lengthy, see it here:
1303 * http://www.mricon.com/html/phpfilter.html
1305 * @param $body the string with HTML you wish to filter
1306 * @param $tag_list see description above
1307 * @param $rm_tags_with_content see description above
1308 * @param $self_closing_tags see description above
1309 * @param $force_tag_closing see description above
1310 * @param $rm_attnames see description above
1311 * @param $bad_attvals see description above
1312 * @param $add_attr_to_tag see description above
1313 * @param $message message object
1314 * @param $id message id
1315 * @return sanitized html safe to show on your pages.
1317 function sq_sanitize($body,
1319 $rm_tags_with_content,
1329 $me = 'sq_sanitize';
1331 * Normalize rm_tags and rm_tags_with_content.
1333 @array_walk
($rm_tags, 'sq_casenormalize');
1334 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1335 @array_walk
($self_closing_tags, 'sq_casenormalize');
1337 * See if tag_list is of tags to remove or tags to allow.
1338 * false means remove these tags
1339 * true means allow these tags
1341 $rm_tags = array_shift($tag_list);
1343 $open_tags = Array();
1344 $trusted = "<!-- begin sanitized html -->\n";
1345 $skip_content = false;
1347 * Take care of netscape's stupid javascript entities like
1350 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1352 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1353 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1354 $free_content = substr($body, $curpos, $lt-$curpos);
1356 * Take care of <style>
1358 if ($tagname == "style" && $tagtype == 2){
1360 * This is a closing </style>. Edit the
1361 * content before we apply it.
1363 $free_content = sq_fixstyle($message, $id, $free_content);
1365 if ($skip_content == false){
1366 $trusted .= $free_content;
1369 if ($tagname != FALSE){
1371 if ($skip_content == $tagname){
1373 * Got to the end of tag we needed to remove.
1376 $skip_content = false;
1378 if ($skip_content == false){
1379 if ($tagname == "body"){
1382 if (isset($open_tags{$tagname}) &&
1383 $open_tags{$tagname} > 0){
1384 $open_tags{$tagname}--;
1394 * $rm_tags_with_content
1396 if ($skip_content == false){
1398 * See if this is a self-closing type and change
1399 * tagtype appropriately.
1402 && in_array($tagname, $self_closing_tags)){
1406 * See if we should skip this tag and any content
1409 if ($tagtype == 1 &&
1410 in_array($tagname, $rm_tags_with_content)){
1411 $skip_content = $tagname;
1413 if (($rm_tags == false
1414 && in_array($tagname, $tag_list)) ||
1415 ($rm_tags == true &&
1416 !in_array($tagname, $tag_list))){
1420 if (isset($open_tags{$tagname})){
1421 $open_tags{$tagname}++
;
1423 $open_tags{$tagname}=1;
1427 * This is where we run other checks.
1429 if (is_array($attary) && sizeof($attary) > 0){
1430 $attary = sq_fixatts($tagname,
1441 * Convert body into div.
1443 if ($tagname == "body"){
1445 $attary = sq_body2div($attary, $message, $id);
1452 if ($tagname != false && $skip_content == false){
1453 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1459 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1460 if ($force_tag_closing == true){
1461 foreach ($open_tags as $tagname=>$opentimes){
1462 while ($opentimes > 0){
1463 $trusted .= '</' . $tagname . '>';
1469 $trusted .= "<!-- end sanitized html -->\n";
1474 * This is a wrapper function to call html sanitizing routines.
1476 * @param $body the body of the message
1477 * @param $id the id of the message
1478 * @return a string with html safe to display in the browser.
1480 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1481 global $attachment_common_show_images, $view_unsafe_images,
1484 * Don't display attached images in HTML mode.
1486 $attachment_common_show_images = false;
1497 $rm_tags_with_content = Array(
1504 $self_closing_tags = Array(
1511 $force_tag_closing = false;
1513 $rm_attnames = Array(
1523 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1524 $bad_attvals = Array(
1527 "/^src|background/i" =>
1530 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1531 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1532 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1533 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1536 "\\1$secremoveimg\\2",
1537 "\\1$secremoveimg\\2",
1538 "\\1$secremoveimg\\2",
1539 "\\1$secremoveimg\\2"
1542 "/^href|action/i" =>
1545 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1546 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1547 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1548 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1563 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1564 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1565 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1566 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1580 if (!$view_unsafe_images){
1582 * Remove any references to http/https if view_unsafe_images set
1585 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1586 '/^([\'\"])\s*https*:.*([\'\"])/si');
1587 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1588 "\\1$secremoveimg\\2");
1589 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1590 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1591 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1592 "url(\\1$secremoveimg\\2)");
1595 $add_attr_to_tag = Array(
1596 "/^a$/si" => Array('target'=>'"_new"')
1598 $trusted = sq_sanitize($body,
1600 $rm_tags_with_content,
1610 if (preg_match("|$secremoveimg|si", $trusted)){
1611 $has_unsafe_images = true;