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 /** Setting up the objects that have the structure for the message **/
20 /** msg_header contains generic variables for values that **/
21 /** could be in a header. **/
23 var $type0 = '', $type1 = '', $boundary = '', $charset = '',
24 $encoding = '', $size = 0, $to = array(), $from = '', $date = '',
25 $cc = array(), $bcc = array(), $reply_to = '', $subject = '',
26 $id = 0, $mailbox = '', $description = '', $filename = '',
27 $entity_id = 0, $message_id = 0, $name = '', $priority = 3, $type = '';
31 /** message is the object that contains messages. It is a recursive
32 object in that through the $entities variable, it can contain
33 more objects of type message. See documentation in mime.txt for
34 a better description of how this works.
36 var $header = '', $entities = array();
38 function addEntity ($msg) {
39 $this->entities
[] = $msg;
43 /* --------------------------------------------------------------------------------- */
45 /* --------------------------------------------------------------------------------- */
47 /* This function gets the structure of a message and stores it in the "message" class.
48 * It will return this object for use with all relevant header information and
49 * fully parsed into the standard "message" object format.
51 function mime_structure ($imap_stream, $header) {
53 $ssid = sqimap_session_id();
54 $lsid = strlen( $ssid );
56 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
58 // This should use sqimap_read_data instead of reading it itself
60 $read = fgets ($imap_stream, 9216);
62 while ( substr($read, 0, $lsid) <> $ssid &&
63 !feof( $imap_stream ) ) {
64 $bodystructure .= $read;
65 $read = fgets ($imap_stream, 9216);
67 $read = $bodystructure;
69 // isolate the body structure and remove beginning and end parenthesis
70 $read = trim(substr ($read, strpos(strtolower($read), 'bodystructure') +
13));
72 $read = trim(substr ($read, 0, -1));
73 $end = mime_match_parenthesis(0, $read);
74 while ($end == strlen($read)-1) {
75 $read = trim(substr ($read, 0, -1));
76 $read = trim(substr ($read, 1));
77 $end = mime_match_parenthesis(0, $read);
80 $msg = mime_parse_structure ($read, 0);
81 $msg->header
= $header;
86 /* this starts the parsing of a particular structure. It is called recursively,
87 * so it can be passed different structures. It returns an object of type
89 * First, it checks to see if it is a multipart message. If it is, then it
90 * handles that as it sees is necessary. If it is just a regular entity,
91 * then it parses it and adds the necessary header information (by calling out
92 * to mime_get_elements()
94 function mime_parse_structure ($structure, $ent_id) {
96 $properties = array();
98 if ($structure{0} == '(') {
99 $old_ent_id = $ent_id;
100 $ent_id = mime_new_element_level($ent_id);
104 $end = mime_match_parenthesis ($start, $structure);
106 /* check if we are dealing with a new entity-level */
107 $i = strrpos($ent_id,'.');
109 $ent = substr($ent_id, $i+
1);
113 /* add "forgotten" parent entities (alternative and relative) */
115 /* new entity levels have information about the type (type1) and
116 * the properties. This information is situated at the end of the
117 * structure string like for example (example between the brackets)
118 * [ "RELATED" ("BOUNDARY" "myboundary" "TYPE" "plain/html") ]
121 /* get the involved properties for parsing to mime_get_properties */
122 $startprop = strrpos($structure,'(');
123 $properties_str = substr($structure,$startprop);
124 $endprop = mime_match_parenthesis ($startprop, $structure);
125 $propstr = substr($structure, $startprop +
1, ($endprop - $startprop)-1);
126 /* cut off the used properties */
128 $structure_end = substr($structure, $endprop+
2);
129 $structure = trim(substr($structure,0,$startprop));
133 $pos = strrpos($structure,' ');
134 $type1 = strtolower(substr($structure, $pos+
2, (count($structure)-2)));
137 if ($pos && $startprop) {
138 $structure = trim(substr($structure, 0, $pos));
141 /* process the found information */
142 $properties = mime_get_props($properties, $properties_str);
143 if (count($properties)>0) {
144 $msg->header
->entity_id
= $old_ent_id;
145 $msg->header
->type0
= 'multipart';
146 $msg->header
->type1
= $type1;
147 for ($i=0; $i < count($properties); $i++
) {
148 $msg->header
->{$properties[$i]['name']} = $properties[$i]['value'];
151 $structure = $structure . ' ' . $structure_end;
153 $element = substr($structure, $start+
1, ($end - $start)-1);
154 $ent_id = mime_increment_id ($ent_id);
155 $newmsg = mime_parse_structure ($element, $ent_id);
156 /* set mailbox in case of message/rfc822 entities */
157 if (isset($newmsg->header
->type0
) && isset($newmsg->header
->type1
)) {
158 if ($newmsg->header
->type0
== 'message' && $newmsg->header
->type1
== 'rfc822') {
159 $newmsg->header
->mailbox
=$mailbox;
162 $msg->addEntity ($newmsg);
164 } while ($structure{$end+
1} == '(');
166 // parse the elements
167 $msg = mime_get_element ($structure, $msg, $ent_id);
173 /* Increments the element ID. An element id can look like any of
174 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
175 * the last number of the element id, changing 1.2 to 1.3.
177 function mime_increment_id ($id) {
179 if (strpos($id, '.')) {
180 $first = substr($id, 0, strrpos($id, '.'));
181 $last = substr($id, strrpos($id, '.')+
1);
183 $new = $first . '.' .$last;
192 * See comment for mime_increment_id().
193 * This adds another level on to the entity_id changing 1.3 to 1.3.0
194 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
195 * before it can be used. I left it this way so as not to have
196 * to make a special case if it is the first entity_id. It
197 * always increments it, and that works fine.
199 function mime_new_element_level ($id) {
210 function mime_get_element (&$structure, $msg, $ent_id) {
213 $msg->header
= new msg_header();
214 $msg->header
->entity_id
= $ent_id;
215 $properties = array();
216 while (strlen($structure) > 0) {
217 $structure = trim($structure);
218 $char = $structure{0};
220 if (strtolower(substr($structure, 0, 3)) == 'nil') {
222 $structure = substr($structure, 3);
223 } else if ($char == '"') {
224 // loop through until we find the matching quote, and return that as a string
227 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
231 $structure = substr($structure, strlen($text) +
2);
232 } else if ($char == '(') {
234 $end = mime_match_parenthesis (0, $structure);
235 $sub = substr($structure, 1, $end-1);
236 $properties = mime_get_props($properties, $sub);
237 $structure = substr($structure, strlen($sub) +
2);
239 // loop through until we find a space or an end parenthesis
241 $char = $structure{$pos};
243 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
246 $char = $structure{$pos};
248 $structure = substr($structure, strlen($text));
251 // This is where all the text parts get put into the header
254 $msg->header
->type0
= strtolower($text);
257 $msg->header
->type1
= strtolower($text);
260 // Invisimail enclose images with <>
261 $msg->header
->id
= str_replace( '<', '', str_replace( '>', '', $text ) );
264 $msg->header
->description
= $text;
267 $msg->header
->encoding
= strtolower($text);
270 $msg->header
->size
= $text;
273 if ($msg->header
->type0
== 'text' && $elem_num == 8) {
274 // This is a plain text message, so lets get the number of lines
276 $msg->header
->num_lines
= $text;
278 } else if ($msg->header
->type0
== 'message' && $msg->header
->type1
== 'rfc822' && $elem_num == 8) {
279 // This is an encapsulated message, so lets start all over again and
280 // parse this message adding it on to the existing one.
281 $structure = trim($structure);
282 if ( $structure{0} == '(' ) {
283 $e = mime_match_parenthesis (0, $structure);
284 $structure = substr($structure, 0, $e);
285 $structure = substr($structure, 1);
286 $m = mime_parse_structure($structure, $msg->header
->entity_id
);
288 // the following conditional is there to correct a bug that wasn't
289 // incrementing the entity IDs correctly because of the special case
290 // that message/rfc822 is. This fixes it fine.
291 if (substr($structure, 1, 1) != '(')
292 $m->header
->entity_id
= mime_increment_id(mime_new_element_level($ent_id));
294 // Now we'll go through and reformat the results.
296 for ($i=0; $i < count($m->entities
); $i++
) {
297 $msg->addEntity($m->entities
[$i]);
310 // loop through the additional properties and put those in the various headers
311 for ($i=0; $i < count($properties); $i++
) {
312 $msg->header
->{$properties[$i]['name']} = $properties[$i]['value'];
319 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
320 * figure out how to do this part, so I decided to go to bed. I woke up
321 * in the morning and had a flash of insight. I went to the white-board
322 * and scribbled it out, then spent a bit programming it, and this is the
323 * result. Nothing complicated, but I think my brain was fried yesterday.
324 * Funny how that happens some times.
326 * This gets properties in a nested parenthesisized list. For example,
327 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
328 * This returns an array called $props with all paired up properties.
329 * It ignores the "attachment" for now, maybe that should change later
330 * down the road. In this case, what is returned is:
331 * $props[0]["name"] = "filename";
332 * $props[0]["value"] = "luke.tar.gz";
334 function mime_get_props ($props, $structure) {
336 while (strlen($structure) > 0) {
337 $structure = trim($structure);
338 $char = $structure{0};
342 while ( ( $char = $structure{$pos} ) != '"' &&
343 $pos < strlen($structure)) {
347 $structure = trim(substr($structure, strlen($tmp) +
2));
348 $char = $structure{0};
353 while ( ( $char = $structure{$pos} ) != '"' &&
354 $pos < strlen($structure) ) {
358 $structure = trim(substr($structure, strlen($value) +
2));
360 $props[$k]['name'] = strtolower($tmp);
361 $props[$k]['value'] = $value;
362 if ($structure != '') {
363 mime_get_props($props, $structure);
367 } else if ($char == '(') {
368 $end = mime_match_parenthesis (0, $structure);
369 $sub = substr($structure, 1, $end-1);
372 $props = mime_get_props($props, $sub);
373 $structure = substr($structure, strlen($sub) +
2);
376 } else if ($char == '(') {
377 $end = mime_match_parenthesis (0, $structure);
378 $sub = substr($structure, 1, $end-1);
379 $props = mime_get_props($props, $sub);
380 $structure = substr($structure, strlen($sub) +
2);
389 * Matches parenthesis. It will return the position of the matching
390 * parenthesis in $structure. For instance, if $structure was:
391 * ("text" "plain" ("val1name", "1") nil ... )
393 * then this would return 42 to match up those two.
395 function mime_match_parenthesis ($pos, $structure) {
397 $j = strlen( $structure );
399 // ignore all extra characters
400 // If inside of a string, skip string -- Boundary IDs and other
401 // things can have ) in them.
402 if ( $structure{$pos} != '(' ) {
406 while ( $pos < $j ) {
408 if ($structure{$pos} == ')') {
410 } elseif ($structure{$pos} == '"') {
412 while ( $structure{$pos} != '"' &&
414 if (substr($structure, $pos, 2) == '\\"') {
416 } elseif (substr($structure, $pos, 2) == '\\\\') {
421 } elseif ( $structure{$pos} == '(' ) {
422 $pos = mime_match_parenthesis ($pos, $structure);
425 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
429 function mime_fetch_body($imap_stream, $id, $ent_id ) {
432 * do a bit of error correction. If we couldn't find the entity id, just guess
433 * that it is the first one. That is usually the case anyway.
439 $cmd = "FETCH $id BODY[$ent_id]";
440 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
443 $topline = trim(array_shift( $data ));
444 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
445 $wholemessage = implode('', $data);
446 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
448 $ret = substr( $wholemessage, 0, $regs[1] );
450 There is some information in the content info header that could be important
451 in order to parse html messages. Let's get them here.
453 if ( $ret{0} == '<' ) {
454 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
455 /* BASE within HTML documents is illegal (see w3 spec)
458 * foreach( $data as $d ) {
459 * if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
464 * ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
466 * while ( $i < $j ) {
467 * if ( isNoSep( $d{$i} ) )
472 * } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
473 * $base .= substr( $d, 1 );
477 * if ( $base <> '' ) {
478 * $ret = "<base href=\"$base\">" . $ret;
482 } else if (ereg('"([^"]*)"', $topline, $regs)) {
485 global $where, $what, $mailbox, $passed_id, $startMessage;
486 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
487 if (isset($where) && isset($what)) {
488 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
490 $par .= "&startMessage=$startMessage&show_more=0";
492 $par .= '&response=' . urlencode($response) .
493 '&message=' . urlencode($message).
494 '&topline=' . urlencode($topline);
497 '<table width="80%"><tr>' .
498 '<tr><td colspan=2>' .
499 _("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!") .
500 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
501 _("Submit message") . '</A><BR> ' .
503 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
504 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
505 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
506 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
507 "</table><BR></tt></font><hr>";
509 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
511 $wholemessage = implode('', $data);
513 $ret = $wholemessage;
518 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
519 // do a bit of error correction. If we couldn't find the entity id, just guess
520 // that it is the first one. That is usually the case anyway.
524 $sid = sqimap_session_id();
525 // Don't kill the connection if the browser is over a dialup
526 // and it would take over 30 seconds to download it.
528 // don´t call set_time_limit in safe mode.
529 if (!ini_get("safe_mode")) {
533 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
536 $read = fgets ($imap_stream,4096);
537 // This could be bad -- if the section has sqimap_session_id() . ' OK'
538 // or similar, it will kill the download.
539 while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
540 if (trim($read) == ')==') {
542 $read = fgets ($imap_stream,4096);
543 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
546 echo decodeBody($read1, $encoding) .
547 decodeBody($read, $encoding);
550 echo decodeBody($read, $encoding);
552 $read = fgets ($imap_stream,4096);
557 /* -[ END MIME DECODING ]----------------------------------------------------------- */
561 /* This is the first function called. It decides if this is a multipart
562 message or if it should be handled as a single entity
564 function decodeMime ($imap_stream, &$header) {
565 global $username, $key, $imapServerAddress, $imapPort;
566 return mime_structure ($imap_stream, $header);
569 // This is here for debugging purposese. It will print out a list
570 // of all the entity IDs that are in the $message object.
572 function listEntities ($message) {
574 if ($message->header
->entity_id
)
575 echo "<tt>" . $message->header
->entity_id
. ' : ' . $message->header
->type0
. '/' . $message->header
->type1
. '<br>';
576 for ($i = 0; $message->entities
[$i]; $i++
) {
577 $msg = listEntities($message->entities
[$i], $ent_id);
585 /* returns a $message object for a particular entity id */
586 function getEntity ($message, $ent_id) {
588 if ($message->header
->entity_id
== $ent_id && strlen($ent_id) == strlen($message->header
->entity_id
))
592 for ($i = 0; isset($message->entities
[$i]); $i++
) {
593 $msg = getEntity ($message->entities
[$i], $ent_id);
603 * figures out what entity to display and returns the $message object
606 function findDisplayEntity ($msg, $textOnly = 1) {
607 global $show_html_default;
612 if ( $msg->header
->type0
== 'multipart' &&
613 ( $msg->header
->type1
== 'alternative' ||
614 $msg->header
->type1
== 'mixed' ||
615 $msg->header
->type1
== 'related' ) &&
616 $show_html_default && ! $textOnly ) {
617 $entity = findDisplayEntityHTML($msg);
620 // Show text/plain or text/html -- the first one we find.
622 $msg->header
->type0
== 'text' &&
623 ( $msg->header
->type1
== 'plain' ||
624 $msg->header
->type1
== 'html' ) &&
625 isset($msg->header
->entity_id
) ) {
626 $entity = $msg->header
->entity_id
;
630 while ($entity == 0 && isset($msg->entities
[$i]) ) {
631 $entity = findDisplayEntity($msg->entities
[$i], $textOnly);
639 /* Shows the HTML version */
640 function findDisplayEntityHTML ($message) {
642 if ( $message->header
->type0
== 'text' &&
643 $message->header
->type1
== 'html' &&
644 isset($message->header
->entity_id
)) {
645 return $message->header
->entity_id
;
647 for ($i = 0; isset($message->entities
[$i]); $i ++
) {
648 if ( $message->header
->type0
== 'message' &&
649 $message->header
->type1
== 'rfc822' &&
650 isset($message->header
->entity_id
)) {
653 $entity = findDisplayEntityHTML($message->entities
[$i]);
664 * Extracted from strings.php 23/03/2002
667 function translateText(&$body, $wrap_at, $charset) {
668 global $where, $what; /* from searching */
669 global $color; /* color theme */
671 require_once('../functions/url_parser.php');
673 $body_ary = explode("\n", $body);
675 for ($i=0; $i < count($body_ary); $i++
) {
676 $line = $body_ary[$i];
677 if (strlen($line) - 2 >= $wrap_at) {
678 sqWordWrap($line, $wrap_at);
680 $line = charset_decode($charset, $line);
681 $line = str_replace("\t", ' ', $line);
687 $j = strlen( $line );
689 while ( $pos < $j ) {
690 if ($line[$pos] == ' ') {
692 } else if (strpos($line, '>', $pos) === $pos) {
701 if (! isset($color[14])) {
702 $color[14] = '#FF0000';
704 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
706 if (! isset($color[13])) {
707 $color[13] = '#800000';
709 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
712 $body_ary[$i] = $line;
714 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
717 /* debugfunction for looping through entities and displaying correct entities */
718 function listMyEntities ($message) {
721 if ($message->header
->entity_id
) {
722 echo "<tt>" . $message->header
->entity_id
. ' : ' . $message->header
->type0
. '/' . $message->header
->type1
. '<br>';
724 if (!($message->header
->type0
== 'message' && $message->header
->type1
== 'rfc822')) {
725 if (isset($message->header
->boundary
) ) {
726 $ent_id = $message->header
->entity_id
;
727 $var = $message->header
->boundary
;
729 echo "<b>$ent_id boundary = $var</b><br>";
731 if (isset($message->header
->type
) ) {
732 $var = $message->header
->type
;
734 echo "<b>$ent_id type = $var</b><br>";
736 for ($i = 0; $message->entities
[$i]; $i++
) {
737 $msg = listMyEntities($message->entities
[$i]);
740 if ($msg ) return $msg;
748 /* This returns a parsed string called $body. That string can then
749 be displayed as the actual message in the HTML. It contains
750 everything needed, including HTML Tags, Attachments at the
753 function formatBody($imap_stream, $message, $color, $wrap_at) {
754 // this if statement checks for the entity to show as the
755 // primary message. To add more of them, just put them in the
756 // order that is their priority.
757 global $startMessage, $username, $key, $imapServerAddress, $imapPort, $body,
758 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
760 $has_unsafe_images = 0;
762 $id = $message->header
->id
;
764 $urlmailbox = urlencode($message->header
->mailbox
);
765 // Get the right entity and redefine message to be this entity
766 // Pass the 0 to mean that we want the 'best' viewable one
767 $ent_num = findDisplayEntity ($message, 0);
768 $body_message = getEntity($message, $ent_num);
769 if (($body_message->header
->type0
== 'text') ||
770 ($body_message->header
->type0
== 'rfc822')) {
771 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
772 $body = decodeBody($body, $body_message->header
->encoding
);
773 $hookResults = do_hook("message_body", $body);
774 $body = $hookResults[1];
775 // If there are other types that shouldn't be formatted, add
777 if ($body_message->header
->type1
== 'html') {
778 if ( $show_html_default <> 1 ) {
779 $body = strip_tags( $body );
780 translateText($body, $wrap_at, $body_message->header
->charset
);
782 $body = MagicHTML( $body, $id );
785 translateText($body, $wrap_at, $body_message->header
->charset
);
788 $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>";
789 if ($has_unsafe_images) {
790 if ($view_unsafe_images) {
791 $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";
793 $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";
797 /** Display the ATTACHMENTS: message if there's more than one part **/
798 if (isset($message->entities
[1])) {
799 $body .= formatAttachments ($message, $ent_num, $message->header
->mailbox
, $id);
802 $body = formatAttachments ($message, -1, $message->header
->mailbox
, $id);
808 * A recursive function that returns a list of attachments with links
809 * to where to download these attachments
811 function formatAttachments($message, $ent_id, $mailbox, $id) {
812 global $where, $what;
813 global $startMessage, $color;
814 static $ShownHTML = 0;
817 if ($ShownHTML == 0) {
820 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
821 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
822 _("Attachments") . ':' .
823 "</B></TH></TR><TR><TD>\n" .
824 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
825 formatAttachments($message, $ent_id, $mailbox, $id) .
826 "</TABLE></TD></TR></TABLE>";
828 } else if ($message) {
829 $header = $message->header
;
830 $type0 = strtolower($header->type0
);
831 $type1 = strtolower($header->type1
);
833 if (isset($header->name
)) {
834 $name = decodeHeader($header->name
);
836 if ($type0 =='message' && $type1 == 'rfc822') {
838 $filename = decodeHeader($message->header
->filename
);
839 if (trim($filename) == '') {
840 if (trim($name) == '') {
841 $display_filename = 'untitled-[' . $message->header
->entity_id
. ']' ;
843 $display_filename = $name;
847 $display_filename = $filename;
850 $urlMailbox = urlencode($mailbox);
851 $ent = urlencode($message->header
->entity_id
);
854 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
855 if ($where && $what) {
856 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
858 $Links['download link']['text'] = _("download");
859 $Links['download link']['href'] =
860 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
863 /* this executes the attachment hook with a specific MIME-type.
864 * if that doens't have results, it tries if there's a rule
865 * for a more generic type. */
866 $HookResults = do_hook("attachment $type0/$type1", $Links,
867 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
868 if(count($HookResults[1]) <= 1) {
869 $HookResults = do_hook("attachment $type0/*", $Links,
870 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
871 $display_filename, $where, $what);
874 $Links = $HookResults[1];
875 $DefaultLink = $HookResults[6];
877 $body .= '<TR><TD> </TD><TD>' .
878 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
879 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
880 '</b> </small></TD>' .
881 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
883 if ($message->header
->description
) {
884 $body .= '<b>' . htmlspecialchars(_($message->header
->description
)) . '</b>';
886 $body .= '</SMALL></TD><TD><SMALL> ';
890 foreach ($Links as $Val) {
894 $body .= ' | ';
896 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
901 $body .= "</SMALL></TD></TR>\n";
905 } elseif (!$message->entities
) {
907 $type0 = strtolower($message->header
->type0
);
908 $type1 = strtolower($message->header
->type1
);
909 $name = decodeHeader($message->header
->name
);
911 if ($message->header
->entity_id
!= $ent_id) {
912 $filename = decodeHeader($message->header
->filename
);
913 if (trim($filename) == '') {
914 if (trim($name) == '') {
915 if ( trim( $message->header
->id
) == '' )
916 $display_filename = 'untitled-[' . $message->header
->entity_id
. ']' ;
918 $display_filename = 'cid: ' . $message->header
->id
;
919 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
921 $display_filename = $name;
925 $display_filename = $filename;
928 $urlMailbox = urlencode($mailbox);
929 $ent = urlencode($message->header
->entity_id
);
932 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
933 if ($where && $what) {
934 $DefaultLink = '&where='. urlencode($where).'&what='.urlencode($what);
936 $Links['download link']['text'] = _("download");
937 $Links['download link']['href'] =
938 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
941 /* this executes the attachment hook with a specific MIME-type.
942 * if that doens't have results, it tries if there's a rule
943 * for a more generic type. */
944 $HookResults = do_hook("attachment $type0/$type1", $Links,
945 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
946 $display_filename, $where, $what);
947 if(count($HookResults[1]) <= 1) {
948 $HookResults = do_hook("attachment $type0/*", $Links,
949 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
950 $display_filename, $where, $what);
953 $Links = $HookResults[1];
954 $DefaultLink = $HookResults[6];
956 $body .= '<TR><TD> </TD><TD>' .
957 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
958 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
959 '</b> </small></TD>' .
960 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
962 if ($message->header
->description
) {
963 $body .= '<b>' . htmlspecialchars(_($message->header
->description
)) . '</b>';
965 $body .= '</SMALL></TD><TD><SMALL> ';
969 foreach ($Links as $Val) {
973 $body .= ' | ';
975 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
980 $body .= "</SMALL></TD></TR>\n";
983 for ($i = 0; $i < count($message->entities
); $i++
) {
984 $body .= formatAttachments($message->entities
[$i], $ent_id, $mailbox, $id);
992 /** this function decodes the body depending on the encoding type. **/
993 function decodeBody($body, $encoding) {
994 $body = str_replace("\r\n", "\n", $body);
995 $encoding = strtolower($encoding);
997 global $show_html_default;
999 if ($encoding == 'quoted-printable') {
1000 $body = quoted_printable_decode($body);
1003 while (ereg("=\n", $body))
1004 $body = ereg_replace ("=\n", "", $body);
1006 } else if ($encoding == 'base64') {
1007 $body = base64_decode($body);
1010 // All other encodings are returned raw.
1015 * This functions decode strings that is encoded according to
1016 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
1017 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
1019 function decodeHeader ($string, $utfencode=true) {
1020 if (is_array($string)) {
1021 $string = implode("\n", $string);
1024 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
1027 // Ignore white-space between consecutive encoded-words
1028 if (strspn($res[2], " \t") != strlen($res[2])) {
1032 if (ucfirst($res[4]) == 'B') {
1033 $replace = base64_decode($res[5]);
1035 $replace = str_replace('_', ' ', $res[5]);
1036 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
1038 /* Only encode into entities by default. Some places
1039 don't need the encoding, like the compose form. */
1041 $replace = charset_decode($res[3], $replace);
1044 $string = $prefix . $replace . substr($string, strlen($res[0]));
1045 $i = strlen($prefix) +
strlen($replace);
1051 * Encode a string according to RFC 1522 for use in headers if it
1052 * contains 8-bit characters or anything that looks like it should
1055 function encodeHeader ($string) {
1056 global $default_charset;
1058 // Encode only if the string contains 8-bit characters or =?
1059 $j = strlen( $string );
1060 $l = strstr($string, '=?'); // Must be encoded ?
1062 for( $i=0; $i < $j; ++
$i) {
1063 switch( $string{$i} ) {
1077 $k = ord( $string{$i} );
1079 $ret .= sprintf("=%02X", $k);
1082 $ret .= $string{$i};
1087 $string = "=?$default_charset?Q?$ret?=";
1093 /* This function trys to locate the entity_id of a specific mime element */
1095 function find_ent_id( $id, $message ) {
1097 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
1098 if (( $message->entities
[$i]->header
->type1
== 'alternative') ||
1099 ( $message->entities
[$i]->header
->type1
== 'related') ||
1100 ( $message->entities
[$i]->header
->type1
== 'mixed')) {
1101 $ret = find_ent_id( $id, $message->entities
[$i] );
1103 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
1104 $ret = $message->entities
[$i]->header
->entity_id
;
1112 ** HTMLFILTER ROUTINES
1116 * This function returns the final tag out of the tag name, an array
1117 * of attributes, and the type of the tag. This function is called by
1118 * sq_sanitize internally.
1120 * @param $tagname the name of the tag.
1121 * @param $attary the array of attributes and their values
1122 * @param $tagtype The type of the tag (see in comments).
1123 * @return a string with the final tag representation.
1125 function sq_tagprint($tagname, $attary, $tagtype){
1126 $me = "sq_tagprint";
1128 $fulltag = '</' . $tagname . '>';
1130 $fulltag = '<' . $tagname;
1131 if (is_array($attary) && sizeof($attary)){
1133 while (list($attname, $attvalue) = each($attary)){
1134 array_push($atts, "$attname=$attvalue");
1136 $fulltag .= ' ' . join(" ", $atts);
1147 * A small helper function to use with array_walk. Modifies a by-ref
1148 * value and makes it lowercase.
1150 * @param $val a value passed by-ref.
1151 * @return void since it modifies a by-ref value.
1153 function sq_casenormalize(&$val){
1154 $val = strtolower($val);
1158 * This function skips any whitespace from the current position within
1159 * a string and to the next non-whitespace value.
1161 * @param $body the string
1162 * @param $offset the offset within the string where we should start
1163 * looking for the next non-whitespace character.
1164 * @return the location within the $body where the next
1165 * non-whitespace char is located.
1167 function sq_skipspace($body, $offset){
1168 $me = "sq_skipspace";
1169 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
1170 if (sizeof($matches{1})){
1171 $count = strlen($matches{1});
1178 * This function looks for the next character within a string. It's
1179 * really just a glorified "strpos", except it catches if failures
1182 * @param $body The string to look for needle in.
1183 * @param $offset Start looking from this position.
1184 * @param $needle The character/string to look for.
1185 * @return location of the next occurance of the needle, or
1186 * strlen($body) if needle wasn't found.
1188 function sq_findnxstr($body, $offset, $needle){
1189 $me = "sq_findnxstr";
1190 $pos = strpos($body, $needle, $offset);
1191 if ($pos === FALSE){
1192 $pos = strlen($body);
1198 * This function takes a PCRE-style regexp and tries to match it
1199 * within the string.
1201 * @param $body The string to look for needle in.
1202 * @param $offset Start looking from here.
1203 * @param $reg A PCRE-style regex to match.
1204 * @return Returns a false if no matches found, or an array
1205 * with the following members:
1206 * - integer with the location of the match within $body
1207 * - string with whatever content between offset and the match
1208 * - string with whatever it is we matched
1210 function sq_findnxreg($body, $offset, $reg){
1211 $me = "sq_findnxreg";
1214 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
1218 $retarr{0} = $offset +
strlen($matches{1});
1219 $retarr{1} = $matches{1};
1220 $retarr{2} = $matches{2};
1226 * This function looks for the next tag.
1228 * @param $body String where to look for the next tag.
1229 * @param $offset Start looking from here.
1230 * @return false if no more tags exist in the body, or
1231 * an array with the following members:
1232 * - string with the name of the tag
1233 * - array with attributes and their values
1234 * - integer with tag type (1, 2, or 3)
1235 * - integer where the tag starts (starting "<")
1236 * - integer where the tag ends (ending ">")
1237 * first three members will be false, if the tag is invalid.
1239 function sq_getnxtag($body, $offset){
1240 $me = "sq_getnxtag";
1241 if ($offset > strlen($body)){
1244 $lt = sq_findnxstr($body, $offset, "<");
1245 if ($lt == strlen($body)){
1250 * blah blah <tag attribute="value">
1253 $pos = sq_skipspace($body, $lt+
1);
1254 if ($pos >= strlen($body)){
1255 return Array(false, false, false, $lt, strlen($body));
1258 * There are 3 kinds of tags:
1259 * 1. Opening tag, e.g.:
1261 * 2. Closing tag, e.g.:
1263 * 3. XHTML-style content-less tag, e.g.:
1267 switch (substr($body, $pos, 1)){
1274 * A comment or an SGML declaration.
1276 if (substr($body, $pos+
1, 2) == "--"){
1277 $gt = strpos($body, "-->", $pos)+
2;
1279 $gt = strlen($body);
1281 return Array(false, false, false, $lt, $gt);
1283 $gt = sq_findnxstr($body, $pos, ">");
1284 return Array(false, false, false, $lt, $gt);
1289 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1299 * Look for next [\W-_], which will indicate the end of the tag name.
1301 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1302 if ($regary == false){
1303 return Array(false, false, false, $lt, strlen($body));
1305 list($pos, $tagname, $match) = $regary;
1306 $tagname = strtolower($tagname);
1309 * $match can be either of these:
1310 * '>' indicating the end of the tag entirely.
1311 * '\s' indicating the end of the tag name.
1312 * '/' indicating that this is type-3 xhtml tag.
1314 * Whatever else we find there indicates an invalid tag.
1319 * This is an xhtml-style tag with a closing / at the
1320 * end, like so: <img src="blah"/>. Check if it's followed
1321 * by the closing bracket. If not, then this tag is invalid
1323 if (substr($body, $pos, 2) == "/>"){
1327 $gt = sq_findnxstr($body, $pos, ">");
1328 $retary = Array(false, false, false, $lt, $gt);
1332 return Array($tagname, false, $tagtype, $lt, $pos);
1336 * Check if it's whitespace
1338 if (preg_match("/\s/", $match)){
1341 * This is an invalid tag! Look for the next closing ">".
1343 $gt = sq_findnxstr($body, $offset, ">");
1344 return Array(false, false, false, $lt, $gt);
1349 * At this point we're here:
1350 * <tagname attribute='blah'>
1353 * At this point we loop in order to find all attributes.
1359 while ($pos <= strlen($body)){
1360 $pos = sq_skipspace($body, $pos);
1361 if ($pos == strlen($body)){
1365 return Array(false, false, false, $lt, $pos);
1368 * See if we arrived at a ">" or "/>", which means that we reached
1369 * the end of the tag.
1372 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1376 $pos +
= strlen($matches{1});
1377 if ($matches{2} == "/>"){
1381 return Array($tagname, $attary, $tagtype, $lt, $pos);
1385 * There are several types of attributes, with optional
1386 * [:space:] between members.
1388 * attrname[:space:]=[:space:]'CDATA'
1390 * attrname[:space:]=[:space:]"CDATA"
1392 * attr[:space:]=[:space:]CDATA
1396 * We leave types 1 and 2 the same, type 3 we check for
1397 * '"' and convert to """ if needed, then wrap in
1398 * double quotes. Type 4 we convert into:
1401 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1402 if ($regary == false){
1404 * Looks like body ended before the end of tag.
1406 return Array(false, false, false, $lt, strlen($body));
1408 list($pos, $attname, $match) = $regary;
1409 $attname = strtolower($attname);
1411 * We arrived at the end of attribute name. Several things possible
1413 * '>' means the end of the tag and this is attribute type 4
1414 * '/' if followed by '>' means the same thing as above
1415 * '\s' means a lot of things -- look what it's followed by.
1416 * anything else means the attribute is invalid.
1421 * This is an xhtml-style tag with a closing / at the
1422 * end, like so: <img src="blah"/>. Check if it's followed
1423 * by the closing bracket. If not, then this tag is invalid
1425 if (substr($body, $pos, 2) == "/>"){
1429 $gt = getnxstr($body, $pos, ">");
1430 $retary = Array(false, false, false, $lt, $gt);
1434 $attary{$attname} = '"yes"';
1435 return Array($tagname, $attary, $tagtype, $lt, $pos);
1439 * Skip whitespace and see what we arrive at.
1441 $pos = sq_skipspace($body, $pos);
1442 $char = substr($body, $pos, 1);
1444 * Two things are valid here:
1445 * '=' means this is attribute type 1 2 or 3.
1446 * \w means this was attribute type 4.
1447 * anything else we ignore and re-loop. End of tag and
1448 * invalid stuff will be caught by our checks at the beginning
1453 $pos = sq_skipspace($body, $pos);
1455 * Here are 3 possibilities:
1456 * "'" attribute type 1
1457 * '"' attribute type 2
1458 * everything else is the content of tag type 3
1460 $quot = substr($body, $pos, 1);
1462 $regary = sq_findnxreg($body, $pos+
1, "\'");
1463 if ($regary == false){
1464 return Array(false, false, false, $lt, strlen($body));
1466 list($pos, $attval, $match) = $regary;
1468 $attary{$attname} = "'" . $attval . "'";
1469 } else if ($quot == '"'){
1470 $regary = sq_findnxreg($body, $pos+
1, '\"');
1471 if ($regary == false){
1472 return Array(false, false, false, $lt, strlen($body));
1474 list($pos, $attval, $match) = $regary;
1476 $attary{$attname} = '"' . $attval . '"';
1479 * These are hateful. Look for \s, or >.
1481 $regary = sq_findnxreg($body, $pos, "[\s>]");
1482 if ($regary == false){
1483 return Array(false, false, false, $lt, strlen($body));
1485 list($pos, $attval, $match) = $regary;
1487 * If it's ">" it will be caught at the top.
1489 $attval = preg_replace("/\"/s", """, $attval);
1490 $attary{$attname} = '"' . $attval . '"';
1492 } else if (preg_match("|[\w/>]|", $char)) {
1494 * That was attribute type 4.
1496 $attary{$attname} = '"yes"';
1499 * An illegal character. Find next '>' and return.
1501 $gt = sq_findnxstr($body, $pos, ">");
1502 return Array(false, false, false, $lt, $gt);
1507 * The fact that we got here indicates that the tag end was never
1508 * found. Return invalid tag indication so it gets stripped.
1510 return Array(false, false, false, $lt, strlen($body));
1514 * This function checks attribute values for entity-encoded values
1515 * and returns them translated into 8-bit strings so we can run
1518 * @param $attvalue A string to run entity check against.
1519 * @return Translated value.
1521 function sq_deent($attvalue){
1524 * See if we have to run the checks first. All entities must start
1527 if (strpos($attvalue, "&") === false){
1531 * Check named entities first.
1533 $trans = get_html_translation_table(HTML_ENTITIES
);
1535 * Leave " in, as it can mess us up.
1537 $trans = array_flip($trans);
1538 unset($trans{"""});
1539 while (list($ent, $val) = each($trans)){
1540 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1543 * Now translate numbered entities from 1 to 255 if needed.
1545 if (strpos($attvalue, "#") !== false){
1546 $omit = Array(34, 39);
1547 for ($asc=1; $asc<256; $asc++
){
1548 if (!in_array($asc, $omit)){
1550 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1552 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1553 "$chr\\1", $attvalue);
1561 * This function runs various checks against the attributes.
1563 * @param $tagname String with the name of the tag.
1564 * @param $attary Array with all tag attributes.
1565 * @param $rm_attnames See description for sq_sanitize
1566 * @param $bad_attvals See description for sq_sanitize
1567 * @param $add_attr_to_tag See description for sq_sanitize
1568 * @param $message message object
1569 * @param $id message id
1570 * @return Array with modified attributes.
1572 function sq_fixatts($tagname,
1581 while (list($attname, $attvalue) = each($attary)){
1583 * See if this attribute should be removed.
1585 foreach ($rm_attnames as $matchtag=>$matchattrs){
1586 if (preg_match($matchtag, $tagname)){
1587 foreach ($matchattrs as $matchattr){
1588 if (preg_match($matchattr, $attname)){
1589 unset($attary{$attname});
1596 * Remove any entities.
1598 $attvalue = sq_deent($attvalue);
1601 * Now let's run checks on the attvalues.
1602 * I don't expect anyone to comprehend this. If you do,
1603 * get in touch with me so I can drive to where you live and
1604 * shake your hand personally. :)
1606 foreach ($bad_attvals as $matchtag=>$matchattrs){
1607 if (preg_match($matchtag, $tagname)){
1608 foreach ($matchattrs as $matchattr=>$valary){
1609 if (preg_match($matchattr, $attname)){
1611 * There are two arrays in valary.
1613 * Second one is replacements
1615 list($valmatch, $valrepl) = $valary;
1617 preg_replace($valmatch, $valrepl, $attvalue);
1618 if ($newvalue != $attvalue){
1619 $attary{$attname} = $newvalue;
1626 * Turn cid: urls into http-friendly ones.
1628 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1629 $attary{$attname} = sq_cid2http($message, $id, $attvalue);
1633 * See if we need to append any attributes to this tag.
1635 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1636 if (preg_match($matchtag, $tagname)){
1637 $attary = array_merge($attary, $addattary);
1644 * This function edits the style definition to make them friendly and
1645 * usable in squirrelmail.
1647 * @param $message the message object
1648 * @param $id the message id
1649 * @param $content a string with whatever is between <style> and </style>
1650 * @return a string with edited content.
1652 function sq_fixstyle($message, $id, $content){
1653 global $view_unsafe_images;
1654 $me = "sq_fixstyle";
1656 * First look for general BODY style declaration, which would be
1658 * body {background: blah-blah}
1659 * and change it to .bodyclass so we can just assign it to a <div>
1661 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1662 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1664 * Fix url('blah') declarations.
1666 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1667 "url(\\1$secremoveimg\\2)", $content);
1669 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1672 if (!$view_unsafe_images){
1673 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1674 "url(\\1$secremoveimg\\2)", $content);
1678 * Fix urls that refer to cid:
1680 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1682 $cidurl = $matches{1};
1683 $httpurl = sq_cid2http($message, $id, $cidurl);
1684 $content = preg_replace("|url\($cidurl\)|si",
1685 "url($httpurl)", $content);
1689 * Fix stupid expression: declarations which lead to vulnerabilities
1692 $content = preg_replace("/expression\s*:/si", "idiocy:", $content);
1697 * This function converts cid: url's into the ones that can be viewed in
1700 * @param $message the message object
1701 * @param $id the message id
1702 * @param $cidurl the cid: url.
1703 * @return a string with a http-friendly url
1705 function sq_cid2http($message, $id, $cidurl){
1707 * Get rid of quotes.
1709 $quotchar = substr($cidurl, 0, 1);
1710 $cidurl = str_replace($quotchar, "", $cidurl);
1711 $cidurl = substr(trim($cidurl), 4);
1712 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&" .
1713 "passed_id=$id&mailbox=" . urlencode($message->header
->mailbox
) .
1714 "&passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1719 * This function changes the <body> tag into a <div> tag since we
1720 * can't really have a body-within-body.
1722 * @param $attary an array of attributes and values of <body>
1723 * @return a modified array of attributes to be set for <div>
1725 function sq_body2div($attary){
1726 $me = "sq_body2div";
1727 $divattary = Array("class"=>"'bodyclass'");
1731 if (is_array($attary) && sizeof($attary) > 0){
1732 foreach ($attary as $attname=>$attvalue){
1733 $quotchar = substr($attvalue, 0, 1);
1734 $attvalue = str_replace($quotchar, "", $attvalue);
1737 $styledef .= "background-image: url('$attvalue'); ";
1740 $styledef .= "background-color: $attvalue; ";
1743 $styledef .= "color: $attvalue; ";
1746 if (strlen($styledef) > 0){
1747 $divattary{"style"} = "\"$styledef\"";
1754 * This is the main function and the one you should actually be calling.
1755 * There are several variables you should be aware of an which need
1756 * special description.
1758 * Since the description is quite lengthy, see it here:
1759 * http://www.mricon.com/html/phpfilter.html
1761 * @param $body the string with HTML you wish to filter
1762 * @param $tag_list see description above
1763 * @param $rm_tags_with_content see description above
1764 * @param $self_closing_tags see description above
1765 * @param $force_tag_closing see description above
1766 * @param $rm_attnames see description above
1767 * @param $bad_attvals see description above
1768 * @param $add_attr_to_tag see description above
1769 * @param $message message object
1770 * @param $id message id
1771 * @return sanitized html safe to show on your pages.
1773 function sq_sanitize($body,
1775 $rm_tags_with_content,
1784 $me = "sq_sanitize";
1786 * Normalize rm_tags and rm_tags_with_content.
1788 @array_walk
($rm_tags, 'sq_casenormalize');
1789 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1790 @array_walk
($self_closing_tags, 'sq_casenormalize');
1792 * See if tag_list is of tags to remove or tags to allow.
1793 * false means remove these tags
1794 * true means allow these tags
1796 $rm_tags = array_shift($tag_list);
1798 $open_tags = Array();
1799 $trusted = "<!-- begin sanitized html -->\n";
1800 $skip_content = false;
1802 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1803 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1804 $free_content = substr($body, $curpos, $lt-$curpos);
1806 * Take care of <style>
1808 if ($tagname == "style" && $tagtype == 2){
1810 * This is a closing </style>. Edit the
1811 * content before we apply it.
1813 $free_content = sq_fixstyle($message, $id, $free_content);
1815 if ($skip_content == false){
1816 $trusted .= $free_content;
1819 if ($tagname != FALSE){
1821 if ($skip_content == $tagname){
1823 * Got to the end of tag we needed to remove.
1826 $skip_content = false;
1828 if ($skip_content == false){
1829 if ($tagname == "body"){
1832 if (isset($open_tags{$tagname}) &&
1833 $open_tags{$tagname} > 0){
1834 $open_tags{$tagname}--;
1844 * $rm_tags_with_content
1846 if ($skip_content == false){
1848 * See if this is a self-closing type and change
1849 * tagtype appropriately.
1852 && in_array($tagname, $self_closing_tags)){
1856 * See if we should skip this tag and any content
1859 if ($tagtype == 1 &&
1860 in_array($tagname, $rm_tags_with_content)){
1861 $skip_content = $tagname;
1863 if (($rm_tags == false
1864 && in_array($tagname, $tag_list)) ||
1865 ($rm_tags == true &&
1866 !in_array($tagname, $tag_list))){
1870 if (isset($open_tags{$tagname})){
1871 $open_tags{$tagname}++
;
1873 $open_tags{$tagname}=1;
1877 * This is where we run other checks.
1879 if (is_array($attary) && sizeof($attary) > 0){
1880 $attary = sq_fixatts($tagname,
1890 * Convert body into div.
1892 if ($tagname == "body"){
1894 $attary = sq_body2div($attary, $message, $id);
1901 if ($tagname != false && $skip_content == false){
1902 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1908 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1909 if ($force_tag_closing == true){
1910 foreach ($open_tags as $tagname=>$opentimes){
1911 while ($opentimes > 0){
1912 $trusted .= '</' . $tagname . '>';
1918 $trusted .= "<!-- end sanitized html -->\n";
1923 * This is a wrapper function to call html sanitizing routines.
1925 * @param $body the body of the message
1926 * @param $id the id of the message
1927 * @return a string with html safe to display in the browser.
1929 function magicHTML($body, $id){
1930 global $attachment_common_show_images, $view_unsafe_images,
1931 $has_unsafe_images, $message;
1933 * Don't display attached images in HTML mode.
1935 $attachment_common_show_images = false;
1945 $rm_tags_with_content = Array(
1952 $self_closing_tags = Array(
1959 $force_tag_closing = false;
1961 $rm_attnames = Array(
1969 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1970 $bad_attvals = Array(
1973 "/^src|background|href|action/i" =>
1976 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1977 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si"
1980 "\\1$secremoveimg\\2",
1981 "\\1$secremoveimg\\2"
1987 "/expression\s*:/si",
1988 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1989 "/url\(([\'\"])\s*\S+script:.*([\'\"])\)/si"
1993 "url(\\1$secremoveimg\\2)",
1994 "url(\\1$secremoveimg\\2)"
1999 if (!$view_unsafe_images){
2001 * Remove any references to http/https if view_unsafe_images set
2007 "/^src|background/i" =>
2010 "/^([\'\"])\s*https*:.*([\'\"])/si"
2013 "\\1$secremoveimg\\2"
2019 "/url\(([\'\"])\s*https*:.*([\'\"])\)/si"
2022 "url(\\1$secremoveimg\\2)"
2027 $bad_attvals = array_merge($bad_attvals, $addendum);
2030 $add_attr_to_tag = Array(
2031 "/^a$/si" => Array('target'=>'"_new"')
2033 $trusted = sq_sanitize($body,
2035 $rm_tags_with_content,
2044 if (preg_match("|$secremoveimg|si", $trusted)){
2045 $has_unsafe_images = true;