ce2be9b894cef4b9b36c9f8bad8ff4bf27d625e6
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains the functions necessary to detect and decode MIME
15 require_once('../functions/imap.php');
16 require_once('../functions/attachment_common.php');
18 /* --------------------------------------------------------------------------------- */
20 /* --------------------------------------------------------------------------------- */
22 /* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
27 function mime_structure ($bodystructure, $flags=array()) {
29 // isolate the body structure and remove beginning and end parenthesis
30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
31 $msg = &new message();
32 $read = trim(substr ($read, 0, -1));
33 $msg = $msg->parseStructure($read,0);
36 foreach ($flags as $flag) {
37 $char = strtoupper($flag{1});
40 if (strtolower($flag) == '\\seen') {
45 if (strtolower($flag) == '\\answered') {
46 $msg->is_answered
= true;
50 if (strtolower($flag) == '\\deleted') {
51 $msg->is_deleted
= true;
55 if (strtolower($flag) == '\\flagged') {
56 $msg->is_flagged
= true;
60 if (strtolower($flag) == '\$mdnsent') {
69 // listEntities($msg);
73 /* this starts the parsing of a particular structure. It is called recursively,
74 * so it can be passed different structures. It returns an object of type
76 * First, it checks to see if it is a multipart message. If it is, then it
77 * handles that as it sees is necessary. If it is just a regular entity,
78 * then it parses it and adds the necessary header information (by calling out
79 * to mime_get_elements()
82 function mime_fetch_body($imap_stream, $id, $ent_id) {
85 * do a bit of error correction. If we couldn't find the entity id, just guess
86 * that it is the first one. That is usually the case anyway.
91 $cmd = "FETCH $id BODY[$ent_id]";
93 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
95 $topline = trim(array_shift( $data ));
96 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
98 $wholemessage = implode('', $data);
99 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
101 $ret = substr( $wholemessage, 0, $regs[1] );
103 There is some information in the content info header that could be important
104 in order to parse html messages. Let's get them here.
106 if ( $ret{0} == '<' ) {
107 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
109 } else if (ereg('"([^"]*)"', $topline, $regs)) {
112 global $where, $what, $mailbox, $passed_id, $startMessage;
113 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
114 if (isset($where) && isset($what)) {
115 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
117 $par .= "&startMessage=$startMessage&show_more=0";
119 $par .= '&response=' . urlencode($response) .
120 '&message=' . urlencode($message).
121 '&topline=' . urlencode($topline);
124 '<table width="80%"><tr>' .
125 '<tr><td colspan=2>' .
126 _("Body retrieval error. The reason for this is most probably that the message is malformed. Please help us making future versions better by submitting this message to the developers knowledgebase!") .
127 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
128 _("Submit message") . '</A><BR> ' .
130 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
131 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
132 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
133 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
134 "</table><BR></tt></font><hr>";
136 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
138 $wholemessage = implode('', $data);
140 $ret = $wholemessage;
145 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
147 // do a bit of error correction. If we couldn't find the entity id, just guess
148 // that it is the first one. That is usually the case anyway.
152 $sid = sqimap_session_id($uid_support);
153 // Don't kill the connection if the browser is over a dialup
154 // and it would take over 30 seconds to download it.
156 // donĀ“t call set_time_limit in safe mode.
157 if (!ini_get("safe_mode")) {
161 $sid_s = substr($sid,0,strpos($sid, ' '));
166 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
169 $read = fgets ($imap_stream,8192);
172 // if (preg_match('/.*\{(\d+)\}.*/',$read,$regs)) {
175 $size_div = (int) ($size / 4096);
176 $size_mod = $size % 4096;
177 if (!$size_mod) $size_div++;
179 for ($i=0;$i<$size_div;$i++) {
180 $read .= fread ($imap_stream,4096);
183 $read .= fread ($imap_stream, $size_mod);
185 echo decodeBody($read, $encoding);
188 // This could be bad -- if the section has sqimap_session_id() . ' OK'
189 // or similar, it will kill the download.
190 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
191 if (trim($read) == ')==') {
193 $read = fgets ($imap_stream,4096);
194 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
197 echo decodeBody($read1, $encoding) .
198 decodeBody($read, $encoding);
201 echo decodeBody($read, $encoding);
203 $read = fgets ($imap_stream,4096);
209 /* -[ END MIME DECODING ]----------------------------------------------------------- */
212 // This is here for debugging purposese. It will print out a list
213 // of all the entity IDs that are in the $message object.
215 function listEntities ($message) {
217 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
218 for ($i = 0;isset($message->entities
[$i]); $i++
) {
220 $msg = listEntities($message->entities
[$i]);
231 /* returns a $message object for a particular entity id */
232 function getEntity ($message, $ent_id) {
233 return $message->getEntity($ent_id);
237 * figures out what entity to display and returns the $message object
240 function findDisplayEntity ($msg, $textOnly = true, $entity = array() ) {
241 global $show_html_default;
245 $type = $msg->type0
.'/'.$msg->type1
;
246 if ( $type == 'multipart/alternative') {
247 $msg = findAlternativeEntity($msg, $textOnly);
248 if (count($msg->entities
) == 0) {
249 $entity[] = $msg->entity_id
;
252 $entity =findDisplayEntity($msg,$textOnly, $entity);
254 } else if ( $type == 'multipart/related') {
255 $msgs = findRelatedEntity($msg);
256 for ($i = 0; $i < count($msgs); $i++
) {
258 if (count($msg->entities
) == 0) {
259 $entity[] = $msg->entity_id
;
262 $entity =findDisplayEntity($msg,$textOnly, $entity);
265 } else if ( count($entity) == 0 &&
266 $msg->type0
== 'text' &&
267 ( $msg->type1
== 'plain' ||
268 $msg->type1
== 'html' ) &&
269 isset($msg->entity_id
) ) {
270 if (count($msg->entities
) == 0) {
271 $entity[] = $msg->entity_id
;
275 while ( isset($msg->entities
[$i]) && count($entity) == 0 && !$found ) {
276 $entity = findDisplayEntity($msg->entities
[$i], $textOnly, $entity);
280 if ( !isset($entity[0]) ) {
286 /* Shows the HTML version */
287 function findDisplayEntityHTML ($message) {
289 if ( $message->header
->type0
== 'text' &&
290 $message->header
->type1
== 'html' &&
291 isset($message->header
->entity_id
)) {
292 return $message->header
->entity_id
;
294 for ($i = 0; isset($message->entities
[$i]); $i ++
) {
295 if ( $message->header
->type0
== 'message' &&
296 $message->header
->type1
== 'rfc822' &&
297 isset($message->header
->entity_id
)) {
301 $entity = findDisplayEntityHTML($message->entities
[$i]);
310 function findAlternativeEntity ($message, $textOnly) {
311 global $show_html_default;
312 /* if we are dealing with alternative parts then we choose the best
313 * viewable message supported by SM.
315 if ($show_html_default && !$textOnly) {
316 $alt_order = array ('text/plain','text/html');
318 $alt_order = array ('text/plain');
323 for ($i = 0; $i < count($message->entities
); $i ++
) {
324 $type = $message->entities
[$i]->header
->type0
.'/'.$message->entities
[$i]->header
->type1
;
325 if ($type == 'multipart/related') {
326 $type = $message->entities
[$i]->header
->type
;
328 for ($j = $k; $j < count($alt_order); $j++
) {
329 if ($alt_order[$j] == $type && $j > $best_view) {
336 return $message->entities
[$ent_id];
339 function findRelatedEntity ($message) {
341 for ($i = 0; $i < count($message->entities
); $i ++
) {
342 $type = $message->entities
[$i]->header
->type0
.'/'.$message->entities
[$i]->header
->type1
;
343 if ($message->header
->type
== $type) {
344 $msgs[] = $message->entities
[$i];
352 * Extracted from strings.php 23/03/2002
355 function translateText(&$body, $wrap_at, $charset) {
356 global $where, $what; /* from searching */
357 global $color; /* color theme */
359 require_once('../functions/url_parser.php');
361 $body_ary = explode("\n", $body);
363 for ($i=0; $i < count($body_ary); $i++
) {
364 $line = $body_ary[$i];
365 if (strlen($line) - 2 >= $wrap_at) {
366 sqWordWrap($line, $wrap_at);
368 $line = charset_decode($charset, $line);
369 $line = str_replace("\t", ' ', $line);
375 $j = strlen( $line );
377 while ( $pos < $j ) {
378 if ($line[$pos] == ' ') {
380 } else if (strpos($line, '>', $pos) === $pos) {
389 if (! isset($color[14])) {
390 $color[14] = '#FF0000';
392 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
394 if (! isset($color[13])) {
395 $color[13] = '#800000';
397 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
400 $body_ary[$i] = $line;
402 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
406 /* This returns a parsed string called $body. That string can then
407 be displayed as the actual message in the HTML. It contains
408 everything needed, including HTML Tags, Attachments at the
411 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
412 // this if statement checks for the entity to show as the
413 // primary message. To add more of them, just put them in the
414 // order that is their priority.
415 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
416 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
418 $has_unsafe_images = 0;
420 if ($message->type0
== 'message' && $message->type1
== 'rfc822') {
421 $message = $message->entities
[0];
423 $urlmailbox = urlencode($message->mailbox
);
424 $body_message = getEntity($message, $ent_num);
425 if (($body_message->header
->type0
== 'text') ||
426 ($body_message->header
->type0
== 'rfc822')) {
427 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
429 $body = decodeBody($body, $body_message->header
->encoding
);
430 $hookResults = do_hook("message_body", $body);
431 $body = $hookResults[1];
432 // If there are other types that shouldn't be formatted, add
434 if ($body_message->header
->type1
== 'html') {
435 if ( $show_html_default <> 1 ) {
436 $body = strip_tags( $body );
437 translateText($body, $wrap_at, $body_message->header
->charset
);
439 $body = magicHTML( $body, $id, $message, $mailbox );
442 translateText($body, $wrap_at, $body_message->header
->charset
);
444 $body .= "<CENTER><SMALL><A HREF=\"../src/download.php?absolute_dl=true&passed_id=$id&passed_ent_id=$ent_num&mailbox=$urlmailbox&showHeaders=1\">". _("Download this as a file") ."</A></SMALL></CENTER><BR>";
445 if ($has_unsafe_images) {
446 if ($view_unsafe_images) {
447 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&mailbox=$urlmailbox&sort=$sort&startMessage=$startMessage&show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
449 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&mailbox=$urlmailbox&sort=$sort&startMessage=$startMessage&show_more=0&view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
453 /** Display the ATTACHMENTS: message if there's more than one part **/
454 if (isset($message->entities
[1])) {
455 /* Header-type alternative means we choose the best one to display
456 so don't show the alternatives as attachment. Header-type related
457 means that the attachments are already part of the related message.
459 if ($message->header
->type1
!='related' && $message->header
->type1
!='alternative') {
460 $body .= formatAttachments ($message, $ent_num, $mailbox, $id);
464 $body = formatAttachments ($message, -1, $message->mailbox
, $id);
470 * A recursive function that returns a list of attachments with links
471 * to where to download these attachments
473 function formatAttachments($message, $ent_id, $mailbox, $id) {
474 global $where, $what;
475 global $startMessage, $color;
476 static $ShownHTML = 0;
479 if ($ShownHTML == 0) {
482 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
483 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
484 _("Attachments") . ':' .
485 "</B></TH></TR><TR><TD>\n" .
486 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
487 formatAttachments($message, $ent_id, $mailbox, $id) .
488 "</TABLE></TD></TR></TABLE>";
490 } else if ($message) {
491 $header = $message->header
;
492 $type0 = strtolower($header->type0
);
493 $type1 = strtolower($header->type1
);
495 if (isset($header->name
)) {
496 $name = decodeHeader($header->name
);
498 if ($type0 =='message' && $type1 == 'rfc822') {
500 $filename = decodeHeader($message->header
->subject
);
501 $display_filename = $filename;
503 $urlMailbox = urlencode($mailbox);
504 $ent = urlencode($message->entity_id
);
507 "../src/read_body.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
508 if ($where && $what) {
509 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
511 $Links['download link']['text'] = _("download");
512 $Links['download link']['href'] =
513 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
516 /* this executes the attachment hook with a specific MIME-type.
517 * if that doens't have results, it tries if there's a rule
518 * for a more generic type. */
519 $HookResults = do_hook("attachment $type0/$type1", $Links,
520 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
521 if(count($HookResults[1]) <= 1) {
522 $HookResults = do_hook("attachment $type0/*", $Links,
523 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
524 $display_filename, $where, $what);
527 $Links = $HookResults[1];
528 $DefaultLink = $HookResults[6];
530 $body .= '<TR><TD> </TD><TD>' .
531 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
532 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
533 '</b> </small></TD>' .
534 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
536 $from_o = $message->header
->from
;
537 if (isset($from_o)) {
538 $from_name = $from_o->getAddress(false);
540 $from_name = _("Unknown sender");
542 $from_name = decodeHeader(htmlspecialchars($from_name));
543 $body .= '<b>' . $from_name . '</b>';
544 $body .= '</SMALL></TD><TD><SMALL> ';
547 foreach ($Links as $Val) {
551 $body .= ' | ';
553 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
558 $body .= "</SMALL></TD></TR>\n";
562 } elseif (!$message->entities
) {
564 $type0 = strtolower($message->header
->type0
);
565 $type1 = strtolower($message->header
->type1
);
566 $name = decodeHeader($message->header
->name
);
568 if ($message->entity_id
!= $ent_id) {
569 $filename = decodeHeader($message->header
->filename
);
570 if (trim($filename) == '') {
571 if (trim($name) == '') {
572 if ( trim( $message->header
->id
) == '' )
573 $display_filename = 'untitled-[' . $message->entity_id
. ']' ;
575 $display_filename = 'cid: ' . $message->header
->id
;
576 // $display_filename = 'untitled-[' . $message->entity_id . ']' ;
578 $display_filename = $name;
582 $display_filename = $filename;
585 $urlMailbox = urlencode($mailbox);
586 $ent = urlencode($message->entity_id
);
589 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
590 if ($where && $what) {
591 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
593 $Links['download link']['text'] = _("download");
594 $Links['download link']['href'] =
595 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
598 /* this executes the attachment hook with a specific MIME-type.
599 * if that doens't have results, it tries if there's a rule
600 * for a more generic type. */
601 $HookResults = do_hook("attachment $type0/$type1", $Links,
602 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
603 $display_filename, $where, $what);
604 if(count($HookResults[1]) <= 1) {
605 $HookResults = do_hook("attachment $type0/*", $Links,
606 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
607 $display_filename, $where, $what);
610 $Links = $HookResults[1];
611 $DefaultLink = $HookResults[6];
613 $body .= '<TR><TD> </TD><TD>' .
614 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
615 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
616 '</b> </small></TD>' .
617 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
619 if ($message->header
->description
) {
620 $body .= '<b>' . htmlspecialchars(_($message->header
->description
)) . '</b>';
622 $body .= '</SMALL></TD><TD><SMALL> ';
626 foreach ($Links as $Val) {
630 $body .= ' | ';
632 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
637 $body .= "</SMALL></TD></TR>\n";
640 for ($i = 0; $i < count($message->entities
); $i++
) {
641 $body .= formatAttachments($message->entities
[$i], $ent_id, $mailbox, $id);
649 /** this function decodes the body depending on the encoding type. **/
650 function decodeBody($body, $encoding) {
651 $body = str_replace("\r\n", "\n", $body);
652 $encoding = strtolower($encoding);
654 global $show_html_default;
656 if ($encoding == 'quoted-printable' ||
657 $encoding == 'quoted_printable') {
658 $body = quoted_printable_decode($body);
660 while (ereg("=\n", $body))
661 $body = ereg_replace ("=\n", "", $body);
663 } else if ($encoding == 'base64') {
664 $body = base64_decode($body);
667 // All other encodings are returned raw.
672 * This functions decode strings that is encoded according to
673 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
674 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
676 function decodeHeader ($string, $utfencode=true) {
677 if (is_array($string)) {
678 $string = implode("\n", $string);
681 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
684 // Ignore white-space between consecutive encoded-words
685 if (strspn($res[2], " \t") != strlen($res[2])) {
689 if (ucfirst($res[4]) == 'B') {
690 $replace = base64_decode($res[5]);
692 $replace = str_replace('_', ' ', $res[5]);
693 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
695 /* Only encode into entities by default. Some places
696 don't need the encoding, like the compose form. */
698 $replace = charset_decode($res[3], $replace);
701 $string = $prefix . $replace . substr($string, strlen($res[0]));
702 $i = strlen($prefix) +
strlen($replace);
708 * Encode a string according to RFC 1522 for use in headers if it
709 * contains 8-bit characters or anything that looks like it should
712 function encodeHeader ($string) {
713 global $default_charset;
715 // Encode only if the string contains 8-bit characters or =?
716 $j = strlen( $string );
717 $l = strstr($string, '=?'); // Must be encoded ?
719 for( $i=0; $i < $j; ++
$i) {
720 switch( $string{$i} ) {
734 $k = ord( $string{$i} );
736 $ret .= sprintf("=%02X", $k);
744 $string = "=?$default_charset?Q?$ret?=";
750 /* This function trys to locate the entity_id of a specific mime element */
752 function find_ent_id( $id, $message ) {
754 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
755 if ( $message->entities
[$i]->header
->type0
== 'multipart') {
756 $ret = find_ent_id( $id, $message->entities
[$i] );
758 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
759 $ret = $message->entities
[$i]->entity_id
;
766 ** HTMLFILTER ROUTINES
770 * This function returns the final tag out of the tag name, an array
771 * of attributes, and the type of the tag. This function is called by
772 * sq_sanitize internally.
774 * @param $tagname the name of the tag.
775 * @param $attary the array of attributes and their values
776 * @param $tagtype The type of the tag (see in comments).
777 * @return a string with the final tag representation.
779 function sq_tagprint($tagname, $attary, $tagtype){
782 $fulltag = '</' . $tagname . '>';
784 $fulltag = '<' . $tagname;
785 if (is_array($attary) && sizeof($attary)){
787 while (list($attname, $attvalue) = each($attary)){
788 array_push($atts, "$attname=$attvalue");
790 $fulltag .= ' ' . join(" ", $atts);
801 * A small helper function to use with array_walk. Modifies a by-ref
802 * value and makes it lowercase.
804 * @param $val a value passed by-ref.
805 * @return void since it modifies a by-ref value.
807 function sq_casenormalize(&$val){
808 $val = strtolower($val);
812 * This function skips any whitespace from the current position within
813 * a string and to the next non-whitespace value.
815 * @param $body the string
816 * @param $offset the offset within the string where we should start
817 * looking for the next non-whitespace character.
818 * @return the location within the $body where the next
819 * non-whitespace char is located.
821 function sq_skipspace($body, $offset){
822 $me = "sq_skipspace";
823 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
824 if (sizeof($matches{1})){
825 $count = strlen($matches{1});
832 * This function looks for the next character within a string. It's
833 * really just a glorified "strpos", except it catches if failures
836 * @param $body The string to look for needle in.
837 * @param $offset Start looking from this position.
838 * @param $needle The character/string to look for.
839 * @return location of the next occurance of the needle, or
840 * strlen($body) if needle wasn't found.
842 function sq_findnxstr($body, $offset, $needle){
843 $me = "sq_findnxstr";
844 $pos = strpos($body, $needle, $offset);
846 $pos = strlen($body);
852 * This function takes a PCRE-style regexp and tries to match it
855 * @param $body The string to look for needle in.
856 * @param $offset Start looking from here.
857 * @param $reg A PCRE-style regex to match.
858 * @return Returns a false if no matches found, or an array
859 * with the following members:
860 * - integer with the location of the match within $body
861 * - string with whatever content between offset and the match
862 * - string with whatever it is we matched
864 function sq_findnxreg($body, $offset, $reg){
865 $me = "sq_findnxreg";
868 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
872 $retarr{0} = $offset +
strlen($matches{1});
873 $retarr{1} = $matches{1};
874 $retarr{2} = $matches{2};
880 * This function looks for the next tag.
882 * @param $body String where to look for the next tag.
883 * @param $offset Start looking from here.
884 * @return false if no more tags exist in the body, or
885 * an array with the following members:
886 * - string with the name of the tag
887 * - array with attributes and their values
888 * - integer with tag type (1, 2, or 3)
889 * - integer where the tag starts (starting "<")
890 * - integer where the tag ends (ending ">")
891 * first three members will be false, if the tag is invalid.
893 function sq_getnxtag($body, $offset){
895 if ($offset > strlen($body)){
898 $lt = sq_findnxstr($body, $offset, "<");
899 if ($lt == strlen($body)){
904 * blah blah <tag attribute="value">
907 $pos = sq_skipspace($body, $lt+
1);
908 if ($pos >= strlen($body)){
909 return Array(false, false, false, $lt, strlen($body));
912 * There are 3 kinds of tags:
913 * 1. Opening tag, e.g.:
915 * 2. Closing tag, e.g.:
917 * 3. XHTML-style content-less tag, e.g.:
921 switch (substr($body, $pos, 1)){
928 * A comment or an SGML declaration.
930 if (substr($body, $pos+
1, 2) == "--"){
931 $gt = strpos($body, "-->", $pos);
937 return Array(false, false, false, $lt, $gt);
939 $gt = sq_findnxstr($body, $pos, ">");
940 return Array(false, false, false, $lt, $gt);
945 * Assume tagtype 1 for now. If it's type 3, we'll switch values
955 * Look for next [\W-_], which will indicate the end of the tag name.
957 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
958 if ($regary == false){
959 return Array(false, false, false, $lt, strlen($body));
961 list($pos, $tagname, $match) = $regary;
962 $tagname = strtolower($tagname);
965 * $match can be either of these:
966 * '>' indicating the end of the tag entirely.
967 * '\s' indicating the end of the tag name.
968 * '/' indicating that this is type-3 xhtml tag.
970 * Whatever else we find there indicates an invalid tag.
975 * This is an xhtml-style tag with a closing / at the
976 * end, like so: <img src="blah"/>. Check if it's followed
977 * by the closing bracket. If not, then this tag is invalid
979 if (substr($body, $pos, 2) == "/>"){
983 $gt = sq_findnxstr($body, $pos, ">");
984 $retary = Array(false, false, false, $lt, $gt);
988 return Array($tagname, false, $tagtype, $lt, $pos);
992 * Check if it's whitespace
994 if (preg_match("/\s/", $match)){
997 * This is an invalid tag! Look for the next closing ">".
999 $gt = sq_findnxstr($body, $offset, ">");
1000 return Array(false, false, false, $lt, $gt);
1005 * At this point we're here:
1006 * <tagname attribute='blah'>
1009 * At this point we loop in order to find all attributes.
1015 while ($pos <= strlen($body)){
1016 $pos = sq_skipspace($body, $pos);
1017 if ($pos == strlen($body)){
1021 return Array(false, false, false, $lt, $pos);
1024 * See if we arrived at a ">" or "/>", which means that we reached
1025 * the end of the tag.
1028 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1032 $pos +
= strlen($matches{1});
1033 if ($matches{2} == "/>"){
1037 return Array($tagname, $attary, $tagtype, $lt, $pos);
1041 * There are several types of attributes, with optional
1042 * [:space:] between members.
1044 * attrname[:space:]=[:space:]'CDATA'
1046 * attrname[:space:]=[:space:]"CDATA"
1048 * attr[:space:]=[:space:]CDATA
1052 * We leave types 1 and 2 the same, type 3 we check for
1053 * '"' and convert to """ if needed, then wrap in
1054 * double quotes. Type 4 we convert into:
1057 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1058 if ($regary == false){
1060 * Looks like body ended before the end of tag.
1062 return Array(false, false, false, $lt, strlen($body));
1064 list($pos, $attname, $match) = $regary;
1065 $attname = strtolower($attname);
1067 * We arrived at the end of attribute name. Several things possible
1069 * '>' means the end of the tag and this is attribute type 4
1070 * '/' if followed by '>' means the same thing as above
1071 * '\s' means a lot of things -- look what it's followed by.
1072 * anything else means the attribute is invalid.
1077 * This is an xhtml-style tag with a closing / at the
1078 * end, like so: <img src="blah"/>. Check if it's followed
1079 * by the closing bracket. If not, then this tag is invalid
1081 if (substr($body, $pos, 2) == "/>"){
1085 $gt = sq_findnxstr($body, $pos, ">");
1086 $retary = Array(false, false, false, $lt, $gt);
1090 $attary{$attname} = '"yes"';
1091 return Array($tagname, $attary, $tagtype, $lt, $pos);
1095 * Skip whitespace and see what we arrive at.
1097 $pos = sq_skipspace($body, $pos);
1098 $char = substr($body, $pos, 1);
1100 * Two things are valid here:
1101 * '=' means this is attribute type 1 2 or 3.
1102 * \w means this was attribute type 4.
1103 * anything else we ignore and re-loop. End of tag and
1104 * invalid stuff will be caught by our checks at the beginning
1109 $pos = sq_skipspace($body, $pos);
1111 * Here are 3 possibilities:
1112 * "'" attribute type 1
1113 * '"' attribute type 2
1114 * everything else is the content of tag type 3
1116 $quot = substr($body, $pos, 1);
1118 $regary = sq_findnxreg($body, $pos+
1, "\'");
1119 if ($regary == false){
1120 return Array(false, false, false, $lt, strlen($body));
1122 list($pos, $attval, $match) = $regary;
1124 $attary{$attname} = "'" . $attval . "'";
1125 } else if ($quot == '"'){
1126 $regary = sq_findnxreg($body, $pos+
1, '\"');
1127 if ($regary == false){
1128 return Array(false, false, false, $lt, strlen($body));
1130 list($pos, $attval, $match) = $regary;
1132 $attary{$attname} = '"' . $attval . '"';
1135 * These are hateful. Look for \s, or >.
1137 $regary = sq_findnxreg($body, $pos, "[\s>]");
1138 if ($regary == false){
1139 return Array(false, false, false, $lt, strlen($body));
1141 list($pos, $attval, $match) = $regary;
1143 * If it's ">" it will be caught at the top.
1145 $attval = preg_replace("/\"/s", """, $attval);
1146 $attary{$attname} = '"' . $attval . '"';
1148 } else if (preg_match("|[\w/>]|", $char)) {
1150 * That was attribute type 4.
1152 $attary{$attname} = '"yes"';
1155 * An illegal character. Find next '>' and return.
1157 $gt = sq_findnxstr($body, $pos, ">");
1158 return Array(false, false, false, $lt, $gt);
1163 * The fact that we got here indicates that the tag end was never
1164 * found. Return invalid tag indication so it gets stripped.
1166 return Array(false, false, false, $lt, strlen($body));
1170 * This function checks attribute values for entity-encoded values
1171 * and returns them translated into 8-bit strings so we can run
1174 * @param $attvalue A string to run entity check against.
1175 * @return Translated value.
1177 function sq_deent($attvalue){
1180 * See if we have to run the checks first. All entities must start
1183 if (strpos($attvalue, "&") === false){
1187 * Check named entities first.
1189 $trans = get_html_translation_table(HTML_ENTITIES
);
1191 * Leave " in, as it can mess us up.
1193 $trans = array_flip($trans);
1194 unset($trans{"""});
1195 while (list($ent, $val) = each($trans)){
1196 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1199 * Now translate numbered entities from 1 to 255 if needed.
1201 if (strpos($attvalue, "#") !== false){
1202 $omit = Array(34, 39);
1203 for ($asc=1; $asc<256; $asc++
){
1204 if (!in_array($asc, $omit)){
1206 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1208 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1209 "$chr\\1", $attvalue);
1217 * This function runs various checks against the attributes.
1219 * @param $tagname String with the name of the tag.
1220 * @param $attary Array with all tag attributes.
1221 * @param $rm_attnames See description for sq_sanitize
1222 * @param $bad_attvals See description for sq_sanitize
1223 * @param $add_attr_to_tag See description for sq_sanitize
1224 * @param $message message object
1225 * @param $id message id
1226 * @return Array with modified attributes.
1228 function sq_fixatts($tagname,
1238 while (list($attname, $attvalue) = each($attary)){
1240 * See if this attribute should be removed.
1242 foreach ($rm_attnames as $matchtag=>$matchattrs){
1243 if (preg_match($matchtag, $tagname)){
1244 foreach ($matchattrs as $matchattr){
1245 if (preg_match($matchattr, $attname)){
1246 unset($attary{$attname});
1253 * Remove any entities.
1255 $attvalue = sq_deent($attvalue);
1258 * Now let's run checks on the attvalues.
1259 * I don't expect anyone to comprehend this. If you do,
1260 * get in touch with me so I can drive to where you live and
1261 * shake your hand personally. :)
1263 foreach ($bad_attvals as $matchtag=>$matchattrs){
1264 if (preg_match($matchtag, $tagname)){
1265 foreach ($matchattrs as $matchattr=>$valary){
1266 if (preg_match($matchattr, $attname)){
1268 * There are two arrays in valary.
1270 * Second one is replacements
1272 list($valmatch, $valrepl) = $valary;
1274 preg_replace($valmatch, $valrepl, $attvalue);
1275 if ($newvalue != $attvalue){
1276 $attary{$attname} = $newvalue;
1283 * Turn cid: urls into http-friendly ones.
1285 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1286 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1290 * See if we need to append any attributes to this tag.
1292 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1293 if (preg_match($matchtag, $tagname)){
1294 $attary = array_merge($attary, $addattary);
1301 * This function edits the style definition to make them friendly and
1302 * usable in squirrelmail.
1304 * @param $message the message object
1305 * @param $id the message id
1306 * @param $content a string with whatever is between <style> and </style>
1307 * @return a string with edited content.
1309 function sq_fixstyle($message, $id, $content){
1310 global $view_unsafe_images;
1311 $me = "sq_fixstyle";
1313 * First look for general BODY style declaration, which would be
1315 * body {background: blah-blah}
1316 * and change it to .bodyclass so we can just assign it to a <div>
1318 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1319 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1321 * Fix url('blah') declarations.
1323 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1324 "url(\\1$secremoveimg\\2)", $content);
1326 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1329 if (!$view_unsafe_images){
1330 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1331 "url(\\1$secremoveimg\\2)", $content);
1335 * Fix urls that refer to cid:
1337 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1339 $cidurl = $matches{1};
1340 $httpurl = sq_cid2http($message, $id, $cidurl);
1341 $content = preg_replace("|url\($cidurl\)|si",
1342 "url($httpurl)", $content);
1346 * Fix stupid css declarations which lead to vulnerabilities
1349 $match = Array('/expression/si',
1352 $replace = Array('idiocy', 'idiocy', 'idiocy');
1353 $content = preg_replace($match, $replace, $content);
1358 * This function converts cid: url's into the ones that can be viewed in
1361 * @param $message the message object
1362 * @param $id the message id
1363 * @param $cidurl the cid: url.
1364 * @return a string with a http-friendly url
1366 function sq_cid2http($message, $id, $cidurl, $mailbox){
1368 * Get rid of quotes.
1370 $quotchar = substr($cidurl, 0, 1);
1371 $cidurl = str_replace($quotchar, "", $cidurl);
1372 $cidurl = substr(trim($cidurl), 4);
1373 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1374 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1375 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1380 * This function changes the <body> tag into a <div> tag since we
1381 * can't really have a body-within-body.
1383 * @param $attary an array of attributes and values of <body>
1384 * @return a modified array of attributes to be set for <div>
1386 function sq_body2div($attary){
1387 $me = "sq_body2div";
1388 $divattary = Array("class"=>"'bodyclass'");
1392 if (is_array($attary) && sizeof($attary) > 0){
1393 foreach ($attary as $attname=>$attvalue){
1394 $quotchar = substr($attvalue, 0, 1);
1395 $attvalue = str_replace($quotchar, "", $attvalue);
1398 $styledef .= "background-image: url('$attvalue'); ";
1401 $styledef .= "background-color: $attvalue; ";
1404 $styledef .= "color: $attvalue; ";
1407 if (strlen($styledef) > 0){
1408 $divattary{"style"} = "\"$styledef\"";
1415 * This is the main function and the one you should actually be calling.
1416 * There are several variables you should be aware of an which need
1417 * special description.
1419 * Since the description is quite lengthy, see it here:
1420 * http://www.mricon.com/html/phpfilter.html
1422 * @param $body the string with HTML you wish to filter
1423 * @param $tag_list see description above
1424 * @param $rm_tags_with_content see description above
1425 * @param $self_closing_tags see description above
1426 * @param $force_tag_closing see description above
1427 * @param $rm_attnames see description above
1428 * @param $bad_attvals see description above
1429 * @param $add_attr_to_tag see description above
1430 * @param $message message object
1431 * @param $id message id
1432 * @return sanitized html safe to show on your pages.
1434 function sq_sanitize($body,
1436 $rm_tags_with_content,
1446 $me = "sq_sanitize";
1448 * Normalize rm_tags and rm_tags_with_content.
1450 @array_walk
($rm_tags, 'sq_casenormalize');
1451 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1452 @array_walk
($self_closing_tags, 'sq_casenormalize');
1454 * See if tag_list is of tags to remove or tags to allow.
1455 * false means remove these tags
1456 * true means allow these tags
1458 $rm_tags = array_shift($tag_list);
1460 $open_tags = Array();
1461 $trusted = "<!-- begin sanitized html -->\n";
1462 $skip_content = false;
1464 * Take care of netscape's stupid javascript entities like
1467 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1469 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1470 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1471 $free_content = substr($body, $curpos, $lt-$curpos);
1473 * Take care of <style>
1475 if ($tagname == "style" && $tagtype == 2){
1477 * This is a closing </style>. Edit the
1478 * content before we apply it.
1480 $free_content = sq_fixstyle($message, $id, $free_content);
1482 if ($skip_content == false){
1483 $trusted .= $free_content;
1486 if ($tagname != FALSE){
1488 if ($skip_content == $tagname){
1490 * Got to the end of tag we needed to remove.
1493 $skip_content = false;
1495 if ($skip_content == false){
1496 if ($tagname == "body"){
1499 if (isset($open_tags{$tagname}) &&
1500 $open_tags{$tagname} > 0){
1501 $open_tags{$tagname}--;
1511 * $rm_tags_with_content
1513 if ($skip_content == false){
1515 * See if this is a self-closing type and change
1516 * tagtype appropriately.
1519 && in_array($tagname, $self_closing_tags)){
1523 * See if we should skip this tag and any content
1526 if ($tagtype == 1 &&
1527 in_array($tagname, $rm_tags_with_content)){
1528 $skip_content = $tagname;
1530 if (($rm_tags == false
1531 && in_array($tagname, $tag_list)) ||
1532 ($rm_tags == true &&
1533 !in_array($tagname, $tag_list))){
1537 if (isset($open_tags{$tagname})){
1538 $open_tags{$tagname}++
;
1540 $open_tags{$tagname}=1;
1544 * This is where we run other checks.
1546 if (is_array($attary) && sizeof($attary) > 0){
1547 $attary = sq_fixatts($tagname,
1558 * Convert body into div.
1560 if ($tagname == "body"){
1562 $attary = sq_body2div($attary, $message, $id);
1569 if ($tagname != false && $skip_content == false){
1570 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1576 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1577 if ($force_tag_closing == true){
1578 foreach ($open_tags as $tagname=>$opentimes){
1579 while ($opentimes > 0){
1580 $trusted .= '</' . $tagname . '>';
1586 $trusted .= "<!-- end sanitized html -->\n";
1591 * This is a wrapper function to call html sanitizing routines.
1593 * @param $body the body of the message
1594 * @param $id the id of the message
1595 * @return a string with html safe to display in the browser.
1597 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1598 global $attachment_common_show_images, $view_unsafe_images,
1601 * Don't display attached images in HTML mode.
1603 $attachment_common_show_images = false;
1613 $rm_tags_with_content = Array(
1620 $self_closing_tags = Array(
1627 $force_tag_closing = false;
1629 $rm_attnames = Array(
1639 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1640 $bad_attvals = Array(
1643 "/^src|background/i" =>
1646 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1647 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1648 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1649 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1652 "\\1$secremoveimg\\2",
1653 "\\1$secremoveimg\\2",
1654 "\\1$secremoveimg\\2",
1655 "\\1$secremoveimg\\2"
1658 "/^href|action/i" =>
1661 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1662 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1663 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1664 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1679 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1680 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1681 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1682 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1696 if (!$view_unsafe_images){
1698 * Remove any references to http/https if view_unsafe_images set
1701 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1702 '/^([\'\"])\s*https*:.*([\'\"])/si');
1703 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1704 "\\1$secremoveimg\\2");
1705 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1706 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1707 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1708 "url(\\1$secremoveimg\\2)");
1711 $add_attr_to_tag = Array(
1712 "/^a$/si" => Array('target'=>'"_new"')
1714 $trusted = sq_sanitize($body,
1716 $rm_tags_with_content,
1726 if (preg_match("|$secremoveimg|si", $trusted)){
1727 $has_unsafe_images = true;