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;
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));
71 $read = trim(substr ($read, 0, -1));
72 $end = mime_match_parenthesis(0, $read);
73 while ($end == strlen($read)-1) {
74 $read = trim(substr ($read, 0, -1));
75 $read = trim(substr ($read, 1));
76 $end = mime_match_parenthesis(0, $read);
79 $msg = mime_parse_structure ($read, 0);
80 $msg->header
= $header;
85 /* this starts the parsing of a particular structure. It is called recursively,
86 * so it can be passed different structures. It returns an object of type
88 * First, it checks to see if it is a multipart message. If it is, then it
89 * handles that as it sees is necessary. If it is just a regular entity,
90 * then it parses it and adds the necessary header information (by calling out
91 * to mime_get_elements()
93 function mime_parse_structure ($structure, $ent_id) {
96 if ($structure{0} == '(') {
97 $ent_id = mime_new_element_level($ent_id);
101 $end = mime_match_parenthesis ($start, $structure);
103 $element = substr($structure, $start+
1, ($end - $start)-1);
104 $ent_id = mime_increment_id ($ent_id);
105 $newmsg = mime_parse_structure ($element, $ent_id);
106 $msg->addEntity ($newmsg);
107 } while ($structure{$end+
1} == '(');
109 // parse the elements
110 $msg = mime_get_element ($structure, $msg, $ent_id);
115 /* Increments the element ID. An element id can look like any of
116 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
117 * the last number of the element id, changing 1.2 to 1.3.
119 function mime_increment_id ($id) {
121 if (strpos($id, '.')) {
122 $first = substr($id, 0, strrpos($id, '.'));
123 $last = substr($id, strrpos($id, '.')+
1);
125 $new = $first . '.' .$last;
134 * See comment for mime_increment_id().
135 * This adds another level on to the entity_id changing 1.3 to 1.3.0
136 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
137 * before it can be used. I left it this way so as not to have
138 * to make a special case if it is the first entity_id. It
139 * always increments it, and that works fine.
141 function mime_new_element_level ($id) {
152 function mime_get_element (&$structure, $msg, $ent_id) {
155 $msg->header
= new msg_header();
156 $msg->header
->entity_id
= $ent_id;
157 $properties = array();
159 while (strlen($structure) > 0) {
160 $structure = trim($structure);
161 $char = $structure{0};
163 if (strtolower(substr($structure, 0, 3)) == 'nil') {
165 $structure = substr($structure, 3);
166 } else if ($char == '"') {
167 // loop through until we find the matching quote, and return that as a string
170 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
174 $structure = substr($structure, strlen($text) +
2);
175 } else if ($char == '(') {
177 $end = mime_match_parenthesis (0, $structure);
178 $sub = substr($structure, 1, $end-1);
179 $properties = mime_get_props($properties, $sub);
180 $structure = substr($structure, strlen($sub) +
2);
182 // loop through until we find a space or an end parenthesis
184 $char = $structure{$pos};
186 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
189 $char = $structure{$pos};
191 $structure = substr($structure, strlen($text));
194 // This is where all the text parts get put into the header
197 $msg->header
->type0
= strtolower($text);
200 $msg->header
->type1
= strtolower($text);
203 // Invisimail enclose images with <>
204 $msg->header
->id
= str_replace( '<', '', str_replace( '>', '', $text ) );
207 $msg->header
->description
= $text;
210 $msg->header
->encoding
= strtolower($text);
213 $msg->header
->size
= $text;
216 if ($msg->header
->type0
== 'text' && $elem_num == 8) {
217 // This is a plain text message, so lets get the number of lines
219 $msg->header
->num_lines
= $text;
221 } else if ($msg->header
->type0
== 'message' && $msg->header
->type1
== 'rfc822' && $elem_num == 8) {
222 // This is an encapsulated message, so lets start all over again and
223 // parse this message adding it on to the existing one.
224 $structure = trim($structure);
225 if ( $structure{0} == '(' ) {
226 $e = mime_match_parenthesis (0, $structure);
227 $structure = substr($structure, 0, $e);
228 $structure = substr($structure, 1);
229 $m = mime_parse_structure($structure, $msg->header
->entity_id
);
231 // the following conditional is there to correct a bug that wasn't
232 // incrementing the entity IDs correctly because of the special case
233 // that message/rfc822 is. This fixes it fine.
234 if (substr($structure, 1, 1) != '(')
235 $m->header
->entity_id
= mime_increment_id(mime_new_element_level($ent_id));
237 // Now we'll go through and reformat the results.
239 for ($i=0; $i < count($m->entities
); $i++
) {
240 $msg->addEntity($m->entities
[$i]);
253 // loop through the additional properties and put those in the various headers
254 // if ($msg->header->type0 != 'message') {
255 for ($i=0; $i < count($properties); $i++
) {
256 $msg->header
->{$properties[$i]['name']} = $properties[$i]['value'];
264 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
265 * figure out how to do this part, so I decided to go to bed. I woke up
266 * in the morning and had a flash of insight. I went to the white-board
267 * and scribbled it out, then spent a bit programming it, and this is the
268 * result. Nothing complicated, but I think my brain was fried yesterday.
269 * Funny how that happens some times.
271 * This gets properties in a nested parenthesisized list. For example,
272 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
273 * This returns an array called $props with all paired up properties.
274 * It ignores the "attachment" for now, maybe that should change later
275 * down the road. In this case, what is returned is:
276 * $props[0]["name"] = "filename";
277 * $props[0]["value"] = "luke.tar.gz";
279 function mime_get_props ($props, $structure) {
281 while (strlen($structure) > 0) {
282 $structure = trim($structure);
283 $char = $structure{0};
288 while ( ( $char = $structure{$pos} ) != '"' &&
289 $pos < strlen($structure)) {
293 $structure = trim(substr($structure, strlen($tmp) +
2));
294 $char = $structure{0};
299 while ( ( $char = $structure{$pos} ) != '"' &&
300 $pos < strlen($structure) ) {
304 $structure = trim(substr($structure, strlen($tmp) +
2));
307 $props[$k]['name'] = strtolower($tmp);
308 $props[$k]['value'] = $value;
309 } else if ($char == '(') {
310 $end = mime_match_parenthesis (0, $structure);
311 $sub = substr($structure, 1, $end-1);
314 $props = mime_get_props($props, $sub);
315 $structure = substr($structure, strlen($sub) +
2);
318 } else if ($char == '(') {
319 $end = mime_match_parenthesis (0, $structure);
320 $sub = substr($structure, 1, $end-1);
321 $props = mime_get_props($props, $sub);
322 $structure = substr($structure, strlen($sub) +
2);
331 * Matches parenthesis. It will return the position of the matching
332 * parenthesis in $structure. For instance, if $structure was:
333 * ("text" "plain" ("val1name", "1") nil ... )
335 * then this would return 42 to match up those two.
337 function mime_match_parenthesis ($pos, $structure) {
339 $j = strlen( $structure );
341 // ignore all extra characters
342 // If inside of a string, skip string -- Boundary IDs and other
343 // things can have ) in them.
344 if ( $structure{$pos} != '(' ) {
348 while ( $pos < $j ) {
350 if ($structure{$pos} == ')') {
352 } elseif ($structure{$pos} == '"') {
354 while ( $structure{$pos} != '"' &&
356 if (substr($structure, $pos, 2) == '\\"') {
358 } elseif (substr($structure, $pos, 2) == '\\\\') {
363 } elseif ( $structure{$pos} == '(' ) {
364 $pos = mime_match_parenthesis ($pos, $structure);
367 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
371 function mime_fetch_body($imap_stream, $id, $ent_id ) {
374 * do a bit of error correction. If we couldn't find the entity id, just guess
375 * that it is the first one. That is usually the case anyway.
381 $cmd = "FETCH $id BODY[$ent_id]";
382 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
385 $topline = trim(array_shift( $data ));
386 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
387 $wholemessage = implode('', $data);
388 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
390 $ret = substr( $wholemessage, 0, $regs[1] );
392 There is some information in the content info header that could be important
393 in order to parse html messages. Let's get them here.
395 if ( $ret{0} == '<' ) {
396 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
397 /* BASE within HTML documents is illegal (see w3 spec)
400 * foreach( $data as $d ) {
401 * if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
406 * ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
408 * while ( $i < $j ) {
409 * if ( isNoSep( $d{$i} ) )
414 * } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
415 * $base .= substr( $d, 1 );
419 * if ( $base <> '' ) {
420 * $ret = "<base href=\"$base\">" . $ret;
424 } else if (ereg('"([^"]*)"', $topline, $regs)) {
427 global $where, $what, $mailbox, $passed_id, $startMessage;
428 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
429 if (isset($where) && isset($what)) {
430 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
432 $par .= "&startMessage=$startMessage&show_more=0";
434 $par .= '&response=' . urlencode($response) .
435 '&message=' . urlencode($message).
436 '&topline=' . urlencode($topline);
439 '<table width="80%"><tr>' .
440 '<tr><td colspan=2>' .
441 _("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!") .
442 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
443 _("Submit message") . '</A><BR> ' .
445 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
446 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
447 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
448 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
449 "</table><BR></tt></font><hr>";
451 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
453 $wholemessage = implode('', $data);
455 $ret = $wholemessage;
460 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
461 // do a bit of error correction. If we couldn't find the entity id, just guess
462 // that it is the first one. That is usually the case anyway.
466 $sid = sqimap_session_id();
467 // Don't kill the connection if the browser is over a dialup
468 // and it would take over 30 seconds to download it.
470 // don´t call set_time_limit in safe mode.
471 if (!ini_get("safe_mode")) {
475 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
478 $read = fgets ($imap_stream,4096);
479 // This could be bad -- if the section has sqimap_session_id() . ' OK'
480 // or similar, it will kill the download.
481 while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
482 if (trim($read) == ')==') {
484 $read = fgets ($imap_stream,4096);
485 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
488 echo decodeBody($read1, $encoding) .
489 decodeBody($read, $encoding);
492 echo decodeBody($read, $encoding);
494 $read = fgets ($imap_stream,4096);
499 /* -[ END MIME DECODING ]----------------------------------------------------------- */
503 /* This is the first function called. It decides if this is a multipart
504 message or if it should be handled as a single entity
506 function decodeMime ($imap_stream, &$header) {
507 global $username, $key, $imapServerAddress, $imapPort;
508 return mime_structure ($imap_stream, $header);
511 // This is here for debugging purposese. It will print out a list
512 // of all the entity IDs that are in the $message object.
514 function listEntities ($message) {
516 if ($message->header
->entity_id
)
517 echo "<tt>" . $message->header
->entity_id
. ' : ' . $message->header
->type0
. '/' . $message->header
->type1
. '<br>';
518 for ($i = 0; $message->entities
[$i]; $i++
) {
519 $msg = listEntities($message->entities
[$i], $ent_id);
527 /* returns a $message object for a particular entity id */
528 function getEntity ($message, $ent_id) {
530 if ($message->header
->entity_id
== $ent_id && strlen($ent_id) == strlen($message->header
->entity_id
)) {
533 for ($i = 0; isset($message->entities
[$i]); $i++
) {
534 $msg = getEntity ($message->entities
[$i], $ent_id);
544 * figures out what entity to display and returns the $message object
547 function findDisplayEntity ($message, $textOnly = 1) {
548 global $show_html_default;
553 if ( $message->header
->type0
== 'multipart' &&
554 ( $message->header
->type1
== 'alternative' ||
555 $message->header
->type1
== 'mixed' ||
556 $message->header
->type1
== 'related' ) &&
557 $show_html_default && ! $textOnly ) {
558 $entity = findDisplayEntityHTML($message);
561 // Show text/plain or text/html -- the first one we find.
563 $message->header
->type0
== 'text' &&
564 ( $message->header
->type1
== 'plain' ||
565 $message->header
->type1
== 'html' ) &&
566 isset($message->header
->entity_id
) ) {
567 $entity = $message->header
->entity_id
;
571 while ($entity == 0 && isset($message->entities
[$i]) ) {
572 $entity = findDisplayEntity($message->entities
[$i], $textOnly);
580 /* Shows the HTML version */
581 function findDisplayEntityHTML ($message) {
583 if ( $message->header
->type0
== 'text' &&
584 $message->header
->type1
== 'html' &&
585 isset($message->header
->entity_id
)) {
586 return $message->header
->entity_id
;
588 for ($i = 0; isset($message->entities
[$i]); $i ++
) {
589 if ( $message->header
->type0
== 'message' &&
590 $message->header
->type1
== 'rfc822' &&
591 isset($message->header
->entity_id
)) {
594 $entity = findDisplayEntityHTML($message->entities
[$i]);
605 * Extracted from strings.php 23/03/2002
608 function translateText(&$body, $wrap_at, $charset) {
609 global $where, $what; /* from searching */
610 global $color; /* color theme */
612 require_once('../functions/url_parser.php');
614 $body_ary = explode("\n", $body);
616 for ($i=0; $i < count($body_ary); $i++
) {
617 $line = $body_ary[$i];
618 if (strlen($line) - 2 >= $wrap_at) {
619 sqWordWrap($line, $wrap_at);
621 $line = charset_decode($charset, $line);
622 $line = str_replace("\t", ' ', $line);
628 $j = strlen( $line );
630 while ( $pos < $j ) {
631 if ($line[$pos] == ' ') {
633 } else if (strpos($line, '>', $pos) === $pos) {
642 if (! isset($color[14])) {
643 $color[14] = '#FF0000';
645 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
647 if (! isset($color[13])) {
648 $color[13] = '#800000';
650 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
653 $body_ary[$i] = $line;
655 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
658 /* This returns a parsed string called $body. That string can then
659 be displayed as the actual message in the HTML. It contains
660 everything needed, including HTML Tags, Attachments at the
663 function formatBody($imap_stream, $message, $color, $wrap_at) {
664 // this if statement checks for the entity to show as the
665 // primary message. To add more of them, just put them in the
666 // order that is their priority.
667 global $startMessage, $username, $key, $imapServerAddress, $imapPort, $body,
668 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
670 $has_unsafe_images = 0;
672 $id = $message->header
->id
;
674 $urlmailbox = urlencode($message->header
->mailbox
);
676 // Get the right entity and redefine message to be this entity
677 // Pass the 0 to mean that we want the 'best' viewable one
678 $ent_num = findDisplayEntity ($message, 0);
679 $body_message = getEntity($message, $ent_num);
681 if (($body_message->header
->type0
== 'text') ||
682 ($body_message->header
->type0
== 'rfc822')) {
683 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
684 $body = decodeBody($body, $body_message->header
->encoding
);
685 $hookResults = do_hook("message_body", $body);
686 $body = $hookResults[1];
688 // If there are other types that shouldn't be formatted, add
690 if ($body_message->header
->type1
== 'html') {
691 if ( $show_html_default <> 1 ) {
692 $body = strip_tags( $body );
693 translateText($body, $wrap_at, $body_message->header
->charset
);
695 $body = MagicHTML( $body, $id );
698 translateText($body, $wrap_at, $body_message->header
->charset
);
701 $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>";
702 if ($has_unsafe_images) {
703 if ($view_unsafe_images) {
704 $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";
706 $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";
710 /** Display the ATTACHMENTS: message if there's more than one part **/
711 if (isset($message->entities
[0])) {
712 $body .= formatAttachments ($message, $ent_num, $message->header
->mailbox
, $id);
715 $body = formatAttachments ($message, -1, $message->header
->mailbox
, $id);
721 * A recursive function that returns a list of attachments with links
722 * to where to download these attachments
724 function formatAttachments($message, $ent_id, $mailbox, $id) {
725 global $where, $what;
726 global $startMessage, $color;
727 static $ShownHTML = 0;
730 if ($ShownHTML == 0) {
733 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
734 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
735 _("Attachments") . ':' .
736 "</B></TH></TR><TR><TD>\n" .
737 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
738 formatAttachments($message, $ent_id, $mailbox, $id) .
739 "</TABLE></TD></TR></TABLE>";
741 } else if ($message) {
742 $header = $message->header
;
743 $type0 = strtolower($header->type0
);
744 $type1 = strtolower($header->type1
);
745 $name = decodeHeader($header->name
);
747 if ($type0 =='message' && $type1 = 'rfc822') {
749 $filename = decodeHeader($message->header
->filename
);
750 if (trim($filename) == '') {
751 if (trim($name) == '') {
752 $display_filename = 'untitled-[' . $message->header
->entity_id
. ']' ;
754 $display_filename = $name;
758 $display_filename = $filename;
761 $urlMailbox = urlencode($mailbox);
762 $ent = urlencode($message->header
->entity_id
);
765 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
766 if ($where && $what) {
767 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
769 $Links['download link']['text'] = _("download");
770 $Links['download link']['href'] =
771 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
774 /* this executes the attachment hook with a specific MIME-type.
775 * if that doens't have results, it tries if there's a rule
776 * for a more generic type. */
777 $HookResults = do_hook("attachment $type0/$type1", $Links,
778 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
779 if(count($HookResults[1]) <= 1) {
780 $HookResults = do_hook("attachment $type0/*", $Links,
781 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
782 $display_filename, $where, $what);
785 $Links = $HookResults[1];
786 $DefaultLink = $HookResults[6];
788 $body .= '<TR><TD> </TD><TD>' .
789 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
790 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
791 '</b> </small></TD>' .
792 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
794 if ($message->header
->description
) {
795 $body .= '<b>' . htmlspecialchars(_($message->header
->description
)) . '</b>';
797 $body .= '</SMALL></TD><TD><SMALL> ';
801 foreach ($Links as $Val) {
805 $body .= ' | ';
807 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
812 $body .= "</SMALL></TD></TR>\n";
816 } elseif (!$message->entities
) {
818 $type0 = strtolower($message->header
->type0
);
819 $type1 = strtolower($message->header
->type1
);
820 $name = decodeHeader($message->header
->name
);
822 if ($message->header
->entity_id
!= $ent_id) {
823 $filename = decodeHeader($message->header
->filename
);
824 if (trim($filename) == '') {
825 if (trim($name) == '') {
826 if ( trim( $message->header
->id
) == '' )
827 $display_filename = 'untitled-[' . $message->header
->entity_id
. ']' ;
829 $display_filename = 'cid: ' . $message->header
->id
;
830 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
832 $display_filename = $name;
836 $display_filename = $filename;
839 $urlMailbox = urlencode($mailbox);
840 $ent = urlencode($message->header
->entity_id
);
843 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
844 if ($where && $what) {
845 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
847 $Links['download link']['text'] = _("download");
848 $Links['download link']['href'] =
849 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
852 /* this executes the attachment hook with a specific MIME-type.
853 * if that doens't have results, it tries if there's a rule
854 * for a more generic type. */
855 $HookResults = do_hook("attachment $type0/$type1", $Links,
856 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
857 $display_filename, $where, $what);
858 if(count($HookResults[1]) <= 1) {
859 $HookResults = do_hook("attachment $type0/*", $Links,
860 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
861 $display_filename, $where, $what);
864 $Links = $HookResults[1];
865 $DefaultLink = $HookResults[6];
867 $body .= '<TR><TD> </TD><TD>' .
868 "<A HREF=\"$DefaultLink\">$display_filename</A> </TD>" .
869 '<TD><SMALL><b>' . show_readable_size($message->header
->size
) .
870 '</b> </small></TD>' .
871 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
873 if ($message->header
->description
) {
874 $body .= '<b>' . htmlspecialchars(_($message->header
->description
)) . '</b>';
876 $body .= '</SMALL></TD><TD><SMALL> ';
880 foreach ($Links as $Val) {
884 $body .= ' | ';
886 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
891 $body .= "</SMALL></TD></TR>\n";
894 for ($i = 0; $i < count($message->entities
); $i++
) {
895 $body .= formatAttachments($message->entities
[$i], $ent_id, $mailbox, $id);
903 /** this function decodes the body depending on the encoding type. **/
904 function decodeBody($body, $encoding) {
905 $body = str_replace("\r\n", "\n", $body);
906 $encoding = strtolower($encoding);
908 global $show_html_default;
910 if ($encoding == 'quoted-printable') {
911 $body = quoted_printable_decode($body);
914 while (ereg("=\n", $body))
915 $body = ereg_replace ("=\n", "", $body);
917 } else if ($encoding == 'base64') {
918 $body = base64_decode($body);
921 // All other encodings are returned raw.
926 * This functions decode strings that is encoded according to
927 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
928 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
930 function decodeHeader ($string, $utfencode=true) {
931 if (is_array($string)) {
932 $string = implode("\n", $string);
935 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
938 // Ignore white-space between consecutive encoded-words
939 if (strspn($res[2], " \t") != strlen($res[2])) {
943 if (ucfirst($res[4]) == 'B') {
944 $replace = base64_decode($res[5]);
946 $replace = str_replace('_', ' ', $res[5]);
947 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
949 /* Only encode into entities by default. Some places
950 don't need the encoding, like the compose form. */
952 $replace = charset_decode($res[3], $replace);
955 $string = $prefix . $replace . substr($string, strlen($res[0]));
956 $i = strlen($prefix) +
strlen($replace);
962 * Encode a string according to RFC 1522 for use in headers if it
963 * contains 8-bit characters or anything that looks like it should
966 function encodeHeader ($string) {
967 global $default_charset;
969 // Encode only if the string contains 8-bit characters or =?
970 $j = strlen( $string );
971 $l = strstr($string, '=?'); // Must be encoded ?
973 for( $i=0; $i < $j; ++
$i) {
974 switch( $string{$i} ) {
988 $k = ord( $string{$i} );
990 $ret .= sprintf("=%02X", $k);
998 $string = "=?$default_charset?Q?$ret?=";
1005 Strips dangerous tags from html messages.
1007 function MagicHTML( $body, $id ) {
1009 global $message, $HTTP_SERVER_VARS,
1010 $attachment_common_show_images;
1012 $attachment_common_show_images =
1013 FALSE; // Don't display attached images in HTML mode
1014 $j = strlen( $body ); // Legnth of the HTML
1015 $ret = ''; // Returned string
1016 $bgcolor = '#ffffff'; // Background style color (defaults to white)
1017 $textcolor = '#000000'; // Foreground style color (defaults to black)
1018 $leftmargin = ''; // Left margin style
1019 $title = ''; // HTML title if any
1023 if ( $body{$i} == '<' ) {
1026 while ($body{$pos} == ' ' ||
$body{$pos} == "\t" ||
1027 $body{$pos} == "\n" ) {
1030 while (strlen($tag) < 4 && $body{$pos} != ' ' &&
1031 $body{$pos} != "\t" && $body{$pos} != "\n" &&
1033 $tag .= $body{$pos};
1037 A comment in HTML is only three characters and isn't
1038 guaranteed to have a space after it. This fudges so
1039 it will be caught by the switch statement.
1041 if (ereg("!--", $tag)) {
1044 switch( strtoupper( $tag ) ) {
1045 // Strips the entire tag and contents
1052 while ( $body{$i+
1}.$body{$i+
2}.$body{$i+
3}.$body{$i+
4}.$body{$i+
5} <> $etg &&
1054 while ( $i < $j && $body{++
$i} <> '>' );
1055 // $ret .= "<!-- $tag removed -->";
1060 while ( $body{$i} <> '>' && // </title>
1065 while ( $body{$i} <> '<' && // </title>
1067 $title .= $body{$i};
1072 // Destroy these tags
1083 while ( $body{$i} <> '>' &&
1090 while ( $body{$i} <> '>' && // </title>
1094 // We parse the style to look for interesting stuff
1096 while ( $body{$i} <> '>' &&
1098 // First we get the name of the style
1100 while ( $body{$i} <> '>' &&
1104 if ( isnoSep( $body{$i} ) )
1105 $style .= $body{$i};
1108 stripComments( $i, $j, $body );
1109 $style = strtoupper( trim( $style ) );
1110 if ( $style == 'BODY' ) {
1111 // Next we look into the definitions of the body style
1112 while ( $body{$i} <> '>' &&
1115 // We look for the background color if any.
1116 if ( substr( $body, $i, 17 ) == 'BACKGROUND-COLOR:' ) {
1118 $bgcolor = getStyleData( $i, $j, $body );
1119 } elseif ( substr( $body, $i, 12 ) == 'MARGIN-LEFT:' ) {
1121 $leftmargin = getStyleData( $i, $j, $body );
1126 // Other style are mantained
1127 $styleblk .= "$style ";
1128 while ( $body{$i} <> '>' &&
1132 $styleblk .= $body{$i};
1135 $styleblk .= $body{$i};
1137 stripComments( $i, $j, $body );
1138 if ( $body{$i} <> '>' )
1141 if ( $styleblk <> '' )
1142 $ret .= "<style>$styleblk";
1146 $ret .= '<b>' . _("Title:") . " </b>$title<br>\n";
1149 if (! isset($base)) {
1152 $ret .= stripEvent( $i, $j, $body, $id, $base );
1153 $ret .= " bgcolor=$bgcolor width=\"100%\"><tr>";
1154 if ( $leftmargin <> '' )
1155 $ret .= "<td width=$leftmargin> </td>";
1157 if (strtolower($bgcolor) == 'ffffff' ||
1158 strtolower($bgcolor) == '#ffffff')
1159 $ret .= '<font color=#000000>';
1164 if ( strncasecmp($body{$i}, 'font', 4) ) {
1166 while ( !isNoSep( $body{$i} ) && $i < $j ) {
1169 while ( $body{$i} <> '>' && $i < $j ) {
1173 $ret .= "<BASEFONT $base>\n";
1177 while ( !isNoSep( $body{$i} ) &&
1181 if ( strcasecmp( substr( $base, 0, 4 ), 'href' ) ) {
1183 while ( !isNoSep( $body{$i} ) &&
1187 while ( $body{$i} <> '>' &&
1189 if ( $body{$i} <> '"' ) {
1194 // Debuging $ret .= "<!-- base == $base -->";
1195 if ( strcasecmp( substr( $base, 0, 4 ), 'file' ) <> 0 ) {
1196 $ret .= "\n<BASE HREF=\"$base\">\n";
1201 $ret .= '</font></td></tr></TABLE>';
1205 // Following tags can contain some event handler, lets search it
1206 stripComments( $i, $j, $body );
1207 if (! isset($base)) {
1210 $ret .= stripEvent( $i, $j, $body, $id, $base ) . '>';
1211 // $ret .= "<!-- $tag detected -->";
1219 return( "\n\n<!-- HTML Output ahead -->\n" .
1221 /* Base is illegal within HTML
1222 "\n<!-- END of HTML Output --><base href=\"".
1223 get_location() . '/'.
1226 "\n<!-- END of HTML Output -->\n\n" );
1229 function isNoSep( $char ) {
1247 The following function is usefull to remove extra data that can cause
1248 html not to display properly. Especialy with MS stuff.
1251 function stripComments( &$i, $j, &$body ) {
1253 while ( $body{$i}.$body{$i+
1}.$body{$i+
2}.$body{$i+
3} == '<!--' &&
1256 while ( $body{$i-2}.$body{$i-1}.$body{$i} <> '-->' &&
1266 /* Gets the style data of a specific style */
1268 function getStyleData( &$i, $j, &$body ) {
1271 while ( $body{$i} <> '>' && !isNoSep( $body{$i} ) &&
1275 // And get the color
1277 while ( isNoSep( $body{$i} ) &&
1287 Private function for strip_dangerous_tag. Look for event based coded and "remove" it
1288 change on with no (onload -> noload)
1291 function stripEvent( &$i, $j, &$body, $id, $base ) {
1293 global $message, $base_uri, $has_unsafe_images, $view_unsafe_images;
1297 while ( $body{$i} <> '>' &&
1299 $etg = strtolower($body{$i}.$body{$i+
1}.$body{$i+
2});
1302 // This is probably a src specification
1304 while( !isNoSep( $body{$k} )) {
1307 if ( $body{$k} == '=' ) {
1310 while( !isNoSep( $body{$k} ) &&
1315 while ( $body{$k} <> '>' && isNoSep( $body{$k} ) &&
1321 while( !isNoSep( $body{$k} ) &&
1326 if ( strtolower( substr( $src, 0, 4 ) ) == 'cid:' ) {
1327 $src = substr( $src, 4 );
1328 $src = "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1329 urlencode( $message->header
->mailbox
) .
1330 "&passed_ent_id=" . find_ent_id( $src, $message );
1331 } else if ( strtolower( substr( $src, 0, 4 ) ) <> 'http' ||
1332 stristr( $src, $base_uri ) ) {
1333 /* Javascript and local urls goes out */
1334 if (!$view_unsafe_images) {
1335 $src = '../images/' . _("sec_remove_eng.png");
1337 $has_unsafe_images = 1;
1339 $ret .= 'src="' . $src . '" ';
1348 // Retrolinks are not allowed without a base because they mess with SM security
1349 if ( $base == '' ) {
1358 if ( $body{$i+
3} == ':') {
1361 while ( isNoSep( $body{$i} ) &&
1363 $name .= $body{$i++
};
1365 if ( $name <> '' ) {
1366 $ret .= "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1367 urlencode( $message->header
->mailbox
) .
1368 "&passed_ent_id=" . find_ent_id( $name, $message );
1369 if ( $body{$k} == '"' )
1374 if ( $body{$i} == '>' )
1386 if ( strcasecmp( $body{$i-4}.$body{$i-3}.$body{$i-2}.$body{$i-1}.$body{$i}.$body{$i+
1}.$body{$i+
2}, 'script:') == 0 ) {
1402 /* This function trys to locate the entity_id of a specific mime element */
1404 function find_ent_id( $id, $message ) {
1407 for ($i=0; $ret == '' && $i < count($message->entities
); $i++
) {
1409 if ( $message->entities
[$i]->header
->entity_id
== '' ) {
1410 $ret = find_ent_id( $id, $message->entities
[$i] );
1412 if ( strcasecmp( $message->entities
[$i]->header
->id
, $id ) == 0 )
1413 $ret = $message->entities
[$i]->header
->entity_id
;