61ee7357139860568ce2628c0a83ac0f4e20c7e9
[squirrelmail.git] / functions / mime.php
1 <?php
2
3 /**
4 * mime.php
5 *
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains the functions necessary to detect and decode MIME
10 * messages.
11 *
12 * $Id$
13 */
14
15 require_once('../functions/imap.php');
16 require_once('../functions/attachment_common.php');
17
18 /** Setting up the objects that have the structure for the message **/
19 class msg_header {
20 /** msg_header contains generic variables for values that **/
21 /** could be in a header. **/
22
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;
28 }
29
30 class message {
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.
35 **/
36 var $header = '', $entities = array();
37
38 function addEntity ($msg) {
39 $this->entities[] = $msg;
40 }
41 }
42
43 /* --------------------------------------------------------------------------------- */
44 /* MIME DECODING */
45 /* --------------------------------------------------------------------------------- */
46
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.
50 */
51 function mime_structure ($imap_stream, $header) {
52
53 sqimap_messages_flag ($imap_stream, $header->id, $header->id, 'Seen');
54 $ssid = sqimap_session_id();
55 $lsid = strlen( $ssid );
56 $id = $header->id;
57 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
58 //
59 // This should use sqimap_read_data instead of reading it itself
60 //
61 $read = fgets ($imap_stream, 9216);
62 $bodystructure = '';
63 while ( substr($read, 0, $lsid) <> $ssid &&
64 !feof( $imap_stream ) ) {
65 $bodystructure .= $read;
66 $read = fgets ($imap_stream, 9216);
67 }
68 $read = $bodystructure;
69
70 // isolate the body structure and remove beginning and end parenthesis
71 $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);
78 }
79
80 $msg = mime_parse_structure ($read, 0);
81 $msg->header = $header;
82
83 return( $msg );
84 }
85
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
88 * $message.
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()
93 */
94 function mime_parse_structure ($structure, $ent_id) {
95
96 $msg = new message();
97 if ($structure{0} == '(') {
98 $ent_id = mime_new_element_level($ent_id);
99 $start = $end = -1;
100 do {
101 $start = $end+1;
102 $end = mime_match_parenthesis ($start, $structure);
103
104 $element = substr($structure, $start+1, ($end - $start)-1);
105 $ent_id = mime_increment_id ($ent_id);
106 $newmsg = mime_parse_structure ($element, $ent_id);
107 $msg->addEntity ($newmsg);
108 } while ($structure{$end+1} == '(');
109 } else {
110 // parse the elements
111 $msg = mime_get_element ($structure, $msg, $ent_id);
112 }
113 return $msg;
114 }
115
116 /* Increments the element ID. An element id can look like any of
117 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
118 * the last number of the element id, changing 1.2 to 1.3.
119 */
120 function mime_increment_id ($id) {
121
122 if (strpos($id, '.')) {
123 $first = substr($id, 0, strrpos($id, '.'));
124 $last = substr($id, strrpos($id, '.')+1);
125 $last++;
126 $new = $first . '.' .$last;
127 } else {
128 $new = $id + 1;
129 }
130
131 return $new;
132 }
133
134 /*
135 * See comment for mime_increment_id().
136 * This adds another level on to the entity_id changing 1.3 to 1.3.0
137 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
138 * before it can be used. I left it this way so as not to have
139 * to make a special case if it is the first entity_id. It
140 * always increments it, and that works fine.
141 */
142 function mime_new_element_level ($id) {
143
144 if (!$id) {
145 $id = 0;
146 } else {
147 $id = $id . '.0';
148 }
149
150 return( $id );
151 }
152
153 function mime_get_element (&$structure, $msg, $ent_id) {
154
155 $elem_num = 1;
156 $msg->header = new msg_header();
157 $msg->header->entity_id = $ent_id;
158 $properties = array();
159
160 while (strlen($structure) > 0) {
161 $structure = trim($structure);
162 $char = $structure{0};
163
164 if (strtolower(substr($structure, 0, 3)) == 'nil') {
165 $text = '';
166 $structure = substr($structure, 3);
167 } else if ($char == '"') {
168 // loop through until we find the matching quote, and return that as a string
169 $pos = 1;
170 $text = '';
171 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
172 $text .= $char;
173 $pos++;
174 }
175 $structure = substr($structure, strlen($text) + 2);
176 } else if ($char == '(') {
177 // comment me
178 $end = mime_match_parenthesis (0, $structure);
179 $sub = substr($structure, 1, $end-1);
180 $properties = mime_get_props($properties, $sub);
181 $structure = substr($structure, strlen($sub) + 2);
182 } else {
183 // loop through until we find a space or an end parenthesis
184 $pos = 0;
185 $char = $structure{$pos};
186 $text = '';
187 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
188 $text .= $char;
189 $pos++;
190 $char = $structure{$pos};
191 }
192 $structure = substr($structure, strlen($text));
193 }
194
195 // This is where all the text parts get put into the header
196 switch ($elem_num) {
197 case 1:
198 $msg->header->type0 = strtolower($text);
199 break;
200 case 2:
201 $msg->header->type1 = strtolower($text);
202 break;
203 case 4: // Id
204 // Invisimail enclose images with <>
205 $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
206 break;
207 case 5:
208 $msg->header->description = $text;
209 break;
210 case 6:
211 $msg->header->encoding = strtolower($text);
212 break;
213 case 7:
214 $msg->header->size = $text;
215 break;
216 default:
217 if ($msg->header->type0 == 'text' && $elem_num == 8) {
218 // This is a plain text message, so lets get the number of lines
219 // that it contains.
220 $msg->header->num_lines = $text;
221
222 } else if ($msg->header->type0 == 'message' && $msg->header->type1 == 'rfc822' && $elem_num == 8) {
223 // This is an encapsulated message, so lets start all over again and
224 // parse this message adding it on to the existing one.
225 $structure = trim($structure);
226 if ( $structure{0} == '(' ) {
227 $e = mime_match_parenthesis (0, $structure);
228 $structure = substr($structure, 0, $e);
229 $structure = substr($structure, 1);
230 $m = mime_parse_structure($structure, $msg->header->entity_id);
231
232 // the following conditional is there to correct a bug that wasn't
233 // incrementing the entity IDs correctly because of the special case
234 // that message/rfc822 is. This fixes it fine.
235 if (substr($structure, 1, 1) != '(')
236 $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
237
238 // Now we'll go through and reformat the results.
239 if ($m->entities) {
240 for ($i=0; $i < count($m->entities); $i++) {
241 $msg->addEntity($m->entities[$i]);
242 }
243 } else {
244 $msg->addEntity($m);
245 }
246 $structure = "";
247 }
248 }
249 break;
250 }
251 $elem_num++;
252 $text = "";
253 }
254 // loop through the additional properties and put those in the various headers
255 if ($msg->header->type0 != 'message') {
256 for ($i=0; $i < count($properties); $i++) {
257 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
258 }
259 }
260
261 return $msg;
262 }
263
264 /*
265 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
266 * figure out how to do this part, so I decided to go to bed. I woke up
267 * in the morning and had a flash of insight. I went to the white-board
268 * and scribbled it out, then spent a bit programming it, and this is the
269 * result. Nothing complicated, but I think my brain was fried yesterday.
270 * Funny how that happens some times.
271 *
272 * This gets properties in a nested parenthesisized list. For example,
273 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
274 * This returns an array called $props with all paired up properties.
275 * It ignores the "attachment" for now, maybe that should change later
276 * down the road. In this case, what is returned is:
277 * $props[0]["name"] = "filename";
278 * $props[0]["value"] = "luke.tar.gz";
279 */
280 function mime_get_props ($props, $structure) {
281
282 while (strlen($structure) > 0) {
283 $structure = trim($structure);
284 $char = $structure{0};
285
286 if ($char == '"') {
287 $pos = 1;
288 $tmp = '';
289 while ( ( $char = $structure{$pos} ) != '"' &&
290 $pos < strlen($structure)) {
291 $tmp .= $char;
292 $pos++;
293 }
294 $structure = trim(substr($structure, strlen($tmp) + 2));
295 $char = $structure{0};
296
297 if ($char == '"') {
298 $pos = 1;
299 $value = '';
300 while ( ( $char = $structure{$pos} ) != '"' &&
301 $pos < strlen($structure) ) {
302 $value .= $char;
303 $pos++;
304 }
305 $structure = trim(substr($structure, strlen($tmp) + 2));
306
307 $k = count($props);
308 $props[$k]['name'] = strtolower($tmp);
309 $props[$k]['value'] = $value;
310 } else if ($char == '(') {
311 $end = mime_match_parenthesis (0, $structure);
312 $sub = substr($structure, 1, $end-1);
313 if (! isset($props))
314 $props = array();
315 $props = mime_get_props($props, $sub);
316 $structure = substr($structure, strlen($sub) + 2);
317 }
318 return $props;
319 } else if ($char == '(') {
320 $end = mime_match_parenthesis (0, $structure);
321 $sub = substr($structure, 1, $end-1);
322 $props = mime_get_props($props, $sub);
323 $structure = substr($structure, strlen($sub) + 2);
324 return $props;
325 } else {
326 return $props;
327 }
328 }
329 }
330
331 /*
332 * Matches parenthesis. It will return the position of the matching
333 * parenthesis in $structure. For instance, if $structure was:
334 * ("text" "plain" ("val1name", "1") nil ... )
335 * x x
336 * then this would return 42 to match up those two.
337 */
338 function mime_match_parenthesis ($pos, $structure) {
339
340 $j = strlen( $structure );
341
342 // ignore all extra characters
343 // If inside of a string, skip string -- Boundary IDs and other
344 // things can have ) in them.
345 if ( $structure{$pos} != '(' ) {
346 return( $j );
347 }
348
349 while ( $pos < $j ) {
350 $pos++;
351 if ($structure{$pos} == ')') {
352 return $pos;
353 } elseif ($structure{$pos} == '"') {
354 $pos++;
355 while ( $structure{$pos} != '"' &&
356 $pos < $j ) {
357 if (substr($structure, $pos, 2) == '\\"') {
358 $pos++;
359 } elseif (substr($structure, $pos, 2) == '\\\\') {
360 $pos++;
361 }
362 $pos++;
363 }
364 } elseif ( $structure{$pos} == '(' ) {
365 $pos = mime_match_parenthesis ($pos, $structure);
366 }
367 }
368 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
369 return( $pos );
370 }
371
372 function mime_fetch_body($imap_stream, $id, $ent_id ) {
373
374 /*
375 * do a bit of error correction. If we couldn't find the entity id, just guess
376 * that it is the first one. That is usually the case anyway.
377 */
378 if (!$ent_id) {
379 $ent_id = 1;
380 }
381
382 $cmd = "FETCH $id BODY[$ent_id]";
383 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
384
385 do {
386 $topline = array_shift( $data );
387 } while( $topline && $topline == '*' && !preg_match( '/\\* [0-9] FETCH.*/i', $topline )) ;
388 $wholemessage = implode('', $data);
389 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
390
391 $ret = substr( $wholemessage, 0, $regs[1] );
392 /*
393 There is some information in the content info header that could be important
394 in order to parse html messages. Let's get them here.
395 */
396 if ( $ret{0} == '<' ) {
397 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
398 $base = '';
399 $k = 10;
400 foreach( $data as $d ) {
401 if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
402 $j = strlen( $d );
403 $i = 13;
404 $base = '';
405 while ( $i < $j &&
406 ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
407 $i++;
408 while ( $i < $j ) {
409 if ( isNoSep( $d{$i} ) )
410 $base .= $d{$i};
411 $i++;
412 }
413 $k = 0;
414 } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
415 $base .= substr( $d, 1 );
416 }
417 $k++;
418 }
419 if ( $base <> '' ) {
420 $ret = "<base href=\"$base\">" . $ret;
421 }
422 }
423 } else if (ereg('"([^"]*)"', $topline, $regs)) {
424 $ret = $regs[1];
425 } else {
426 global $where, $what, $mailbox, $passed_id, $startMessage;
427 $par = 'mailbox=' . urlencode($mailbox) . "&passed_id=$passed_id";
428 if (isset($where) && isset($what)) {
429 $par .= '&where='. urlencode($where) . "&what=" . urlencode($what);
430 } else {
431 $par .= "&startMessage=$startMessage&show_more=0";
432 }
433 $par .= '&response=' . urlencode($response) .
434 '&message=' . urlencode($message).
435 '&topline=' . urlencode($topline);
436
437 echo '<tt><br>' .
438 '<table width="80%"><tr>' .
439 '<tr><td colspan=2>' .
440 _("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!") .
441 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
442 _("Submit message") . '</A><BR>&nbsp;' .
443 '</td></tr>' .
444 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
445 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
446 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
447 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
448 "</table><BR></tt></font><hr>";
449
450 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
451 array_shift($data);
452 $wholemessage = implode('', $data);
453
454 $ret = $wholemessage;
455 }
456 return( $ret );
457 }
458
459 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
460 // do a bit of error correction. If we couldn't find the entity id, just guess
461 // that it is the first one. That is usually the case anyway.
462 if (!$ent_id) {
463 $ent_id = 1;
464 }
465 $sid = sqimap_session_id();
466 // Don't kill the connection if the browser is over a dialup
467 // and it would take over 30 seconds to download it.
468
469 // donĀ“t call set_time_limit in safe mode.
470 if (!ini_get("safe_mode")) {
471 set_time_limit(0);
472 }
473
474 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
475 $cnt = 0;
476 $continue = true;
477 $read = fgets ($imap_stream,4096);
478 // This could be bad -- if the section has sqimap_session_id() . ' OK'
479 // or similar, it will kill the download.
480 while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
481 if (trim($read) == ')==') {
482 $read1 = $read;
483 $read = fgets ($imap_stream,4096);
484 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
485 return;
486 } else {
487 echo decodeBody($read1, $encoding) .
488 decodeBody($read, $encoding);
489 }
490 } else if ($cnt) {
491 echo decodeBody($read, $encoding);
492 }
493 $read = fgets ($imap_stream,4096);
494 $cnt++;
495 }
496 }
497
498 /* -[ END MIME DECODING ]----------------------------------------------------------- */
499
500
501
502 /* This is the first function called. It decides if this is a multipart
503 message or if it should be handled as a single entity
504 */
505 function decodeMime ($imap_stream, &$header) {
506 global $username, $key, $imapServerAddress, $imapPort;
507 return mime_structure ($imap_stream, $header);
508 }
509
510 // This is here for debugging purposese. It will print out a list
511 // of all the entity IDs that are in the $message object.
512 /*
513 function listEntities ($message) {
514 if ($message) {
515 if ($message->header->entity_id)
516 echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
517 for ($i = 0; $message->entities[$i]; $i++) {
518 $msg = listEntities($message->entities[$i], $ent_id);
519 if ($msg)
520 return $msg;
521 }
522 }
523 }
524 */
525
526 /* returns a $message object for a particular entity id */
527 function getEntity ($message, $ent_id) {
528 if ($message) {
529 if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id)) {
530 return $message;
531 } else {
532 for ($i = 0; isset($message->entities[$i]); $i++) {
533 $msg = getEntity ($message->entities[$i], $ent_id);
534 if ($msg) {
535 return $msg;
536 }
537 }
538 }
539 }
540 }
541
542 /*
543 * figures out what entity to display and returns the $message object
544 * for that entity.
545 */
546 function findDisplayEntity ($message, $textOnly = 1) {
547 global $show_html_default;
548
549 $entity = 0;
550
551 if ($message) {
552 if ( $message->header->type0 == 'multipart' &&
553 ( $message->header->type1 == 'alternative' ||
554 $message->header->type1 == 'related' ) &&
555 $show_html_default && ! $textOnly ) {
556 $entity = findDisplayEntityHTML($message);
557 }
558
559 // Show text/plain or text/html -- the first one we find.
560 if ( $entity == 0 &&
561 $message->header->type0 == 'text' &&
562 ( $message->header->type1 == 'plain' ||
563 $message->header->type1 == 'html' ) &&
564 isset($message->header->entity_id) ) {
565 $entity = $message->header->entity_id;
566 }
567
568 $i = 0;
569 while ($entity == 0 && isset($message->entities[$i]) ) {
570 $entity = findDisplayEntity($message->entities[$i], $textOnly);
571 $i++;
572 }
573 }
574
575 return( $entity );
576 }
577
578 /* Shows the HTML version */
579 function findDisplayEntityHTML ($message) {
580
581 if ( $message->header->type0 == 'text' &&
582 $message->header->type1 == 'html' &&
583 isset($message->header->entity_id)) {
584 return $message->header->entity_id;
585 }
586 for ($i = 0; isset($message->entities[$i]); $i ++) {
587 $entity = findDisplayEntityHTML($message->entities[$i]);
588 if ($entity != 0) {
589 return $entity;
590 }
591 }
592
593 return 0;
594 }
595
596 /* This returns a parsed string called $body. That string can then
597 be displayed as the actual message in the HTML. It contains
598 everything needed, including HTML Tags, Attachments at the
599 bottom, etc.
600 */
601 function formatBody($imap_stream, $message, $color, $wrap_at) {
602 // this if statement checks for the entity to show as the
603 // primary message. To add more of them, just put them in the
604 // order that is their priority.
605 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
606 $show_html_default;
607
608 $id = $message->header->id;
609 $urlmailbox = urlencode($message->header->mailbox);
610
611 // Get the right entity and redefine message to be this entity
612 // Pass the 0 to mean that we want the 'best' viewable one
613 $ent_num = findDisplayEntity ($message, 0);
614 $body_message = getEntity($message, $ent_num);
615 if (($body_message->header->type0 == 'text') ||
616 ($body_message->header->type0 == 'rfc822')) {
617
618 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
619 $body = decodeBody($body, $body_message->header->encoding);
620 $hookResults = do_hook("message_body", $body);
621 $body = $hookResults[1];
622
623 // If there are other types that shouldn't be formatted, add
624 // them here
625 if ($body_message->header->type1 == 'html') {
626 if ( $show_html_default <> 1 ) {
627 $body = strip_tags( $body );
628 translateText($body, $wrap_at, $body_message->header->charset);
629 } else {
630 $body = MagicHTML( $body, $id );
631 }
632 } else {
633 translateText($body, $wrap_at, $body_message->header->charset);
634 }
635
636 $body .= "<SMALL><CENTER><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></CENTER><BR></SMALL>";
637
638 /** Display the ATTACHMENTS: message if there's more than one part **/
639 $body .= "</TD></TR></TABLE>";
640 if (isset($message->entities[0])) {
641 $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
642 }
643 $body .= "</TD></TR></TABLE>";
644 } else {
645 $body = formatAttachments ($message, -1, $message->header->mailbox, $id);
646 }
647 return ($body);
648 }
649
650 /*
651 * A recursive function that returns a list of attachments with links
652 * to where to download these attachments
653 */
654 function formatAttachments($message, $ent_id, $mailbox, $id) {
655 global $where, $what;
656 global $startMessage, $color;
657 static $ShownHTML = 0;
658
659 $body = '';
660 if ($ShownHTML == 0) {
661
662 $ShownHTML = 1;
663 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
664 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
665 _("Attachments") . ':' .
666 "</B></TH></TR><TR><TD>\n" .
667 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
668 formatAttachments($message, $ent_id, $mailbox, $id) .
669 "</TABLE></TD></TR></TABLE>";
670
671 } else if ($message) {
672
673 if (!$message->entities) {
674
675 $type0 = strtolower($message->header->type0);
676 $type1 = strtolower($message->header->type1);
677 $name = decodeHeader($message->header->name);
678
679 if ($message->header->entity_id != $ent_id) {
680 $filename = decodeHeader($message->header->filename);
681 if (trim($filename) == '') {
682 if (trim($name) == '') {
683 if ( trim( $message->header->id ) == '' )
684 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
685 else
686 $display_filename = 'cid: ' . $message->header->id;
687 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
688 } else {
689 $display_filename = $name;
690 $filename = $name;
691 }
692 } else {
693 $display_filename = $filename;
694 }
695
696 $urlMailbox = urlencode($mailbox);
697 $ent = urlencode($message->header->entity_id);
698
699 $DefaultLink =
700 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
701 if ($where && $what) {
702 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
703 }
704 $Links['download link']['text'] = _("download");
705 $Links['download link']['href'] =
706 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
707 $ImageURL = '';
708
709 /* this executes the attachment hook with a specific MIME-type.
710 * if that doens't have results, it tries if there's a rule
711 * for a more generic type. */
712 $HookResults = do_hook("attachment $type0/$type1", $Links,
713 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
714 $display_filename, $where, $what);
715 if(count($HookResults[1]) <= 1) {
716 $HookResults = do_hook("attachment $type0/*", $Links,
717 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
718 $display_filename, $where, $what);
719 }
720
721 $Links = $HookResults[1];
722 $DefaultLink = $HookResults[6];
723
724 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
725 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
726 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
727 '</b>&nbsp;&nbsp;</small></TD>' .
728 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
729 '<TD><SMALL>';
730 if ($message->header->description) {
731 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
732 }
733 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
734
735
736 $SkipSpaces = 1;
737 foreach ($Links as $Val) {
738 if ($SkipSpaces) {
739 $SkipSpaces = 0;
740 } else {
741 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
742 }
743 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
744 }
745
746 unset($Links);
747
748 $body .= "</SMALL></TD></TR>\n";
749 }
750 } else {
751 for ($i = 0; $i < count($message->entities); $i++) {
752 $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
753 }
754 }
755 }
756 return( $body );
757 }
758
759
760 /** this function decodes the body depending on the encoding type. **/
761 function decodeBody($body, $encoding) {
762 $body = str_replace("\r\n", "\n", $body);
763 $encoding = strtolower($encoding);
764
765 global $show_html_default;
766
767 if ($encoding == 'quoted-printable') {
768 $body = quoted_printable_decode($body);
769
770
771 while (ereg("=\n", $body))
772 $body = ereg_replace ("=\n", "", $body);
773
774 } else if ($encoding == 'base64') {
775 $body = base64_decode($body);
776 }
777
778 // All other encodings are returned raw.
779 return $body;
780 }
781
782 /*
783 * This functions decode strings that is encoded according to
784 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
785 */
786 function decodeHeader ($string, $utfencode=true) {
787
788 if ( is_array( $string ) ) {
789 $string = implode("\n", $string );
790 }
791
792 if (eregi('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
793 $string, $res)) {
794 if (ucfirst($res[2]) == 'B') {
795 $replace = base64_decode($res[3]);
796 } else {
797 $replace = str_replace('_', ' ', $res[3]);
798 // Convert lowercase Quoted Printable to uppercase for
799 // quoted_printable_decode to understand it.
800 while (ereg("(=(([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef])))",
801 $replace, $res)) {
802 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
803 }
804 $replace = quoted_printable_decode($replace);
805 }
806 /* Only encode into entities by default. Some places
807 don't need the encoding, like the compose form. */
808 if ($utfencode){
809 $replace = charset_decode ($res[1], $replace);
810 }
811
812 // Remove the name of the character set.
813 $string = eregi_replace ('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
814 $replace, $string);
815
816 // In case there should be more encoding in the string: recurse
817 $string = decodeHeader($string);
818 }
819
820 return ($string);
821 }
822
823 /*
824 * Encode a string according to RFC 1522 for use in headers if it
825 * contains 8-bit characters or anything that looks like it should
826 * be encoded.
827 */
828 function encodeHeader ($string) {
829 global $default_charset;
830
831 // Encode only if the string contains 8-bit characters or =?
832 $j = strlen( $string );
833 $l = strstr($string, '=?'); // Must be encoded ?
834 $ret = '';
835 for( $i=0; $i < $j; ++$i) {
836 switch( $string{$i} ) {
837 case '=':
838 $ret .= '=3D';
839 break;
840 case '?':
841 $ret .= '=3F';
842 break;
843 case '_':
844 $ret .= '=5F';
845 break;
846 case ' ':
847 $ret .= '_';
848 break;
849 default:
850 $k = ord( $string{$i} );
851 if ( $k > 126 ) {
852 $ret .= sprintf("=%02X", $k);
853 $l = TRUE;
854 } else
855 $ret .= $string{$i};
856 }
857 }
858
859 if ( $l ) {
860 $string = "=?$default_charset?Q?$ret?=";
861 }
862
863 return( $string );
864 }
865
866 /*
867 Strips dangerous tags from html messages.
868 */
869 function MagicHTML( $body, $id ) {
870
871 global $message, $HTTP_SERVER_VARS,
872 $attachment_common_show_images;
873
874 $attachment_common_show_images =
875 FALSE; // Don't display attached images in HTML mode
876 $j = strlen( $body ); // Legnth of the HTML
877 $ret = ''; // Returned string
878 $bgcolor = '#ffffff'; // Background style color (defaults to white)
879 $textcolor = '#000000'; // Foreground style color (defaults to black)
880 $leftmargin = ''; // Left margin style
881 $title = ''; // HTML title if any
882
883 $i = 0;
884 while ( $i < $j ) {
885 if ( $body{$i} == '<' ) {
886 $pos = $i + 1;
887 $tag = '';
888 while ($body{$pos} == ' ' || $body{$pos} == "\t" ||
889 $body{$pos} == "\n") {
890 $pos ++;
891 }
892 while (strlen($tag) < 4 && $body{$pos} != ' ' &&
893 $body{$pos} != "\t" && $body{$pos} != "\n") {
894 $tag .= $body{$pos};
895 $pos ++;
896 }
897 switch( strtoupper( $tag ) ) {
898 // Strips the entire tag and contents
899 case 'APPL':
900 case 'EMBB':
901 case 'FRAM':
902 case 'SCRI':
903 case 'OBJE':
904 $etg = '/' . $tag;
905 while ( $body{$i+1}.$body{$i+2}.$body{$i+3}.$body{$i+4}.$body{$i+5} <> $etg &&
906 $i < $j ) $i++;
907 while ( $i < $j && $body{++$i} <> '>' );
908 // $ret .= "<!-- $tag removed -->";
909 break;
910 // Substitute Title
911 case 'TITL':
912 $i += 5;
913 while ( $body{$i} <> '>' && // </title>
914 $i < $j )
915 $i++;
916 $i++;
917 $title = '';
918 while ( $body{$i} <> '<' && // </title>
919 $i < $j ) {
920 $title .= $body{$i};
921 $i++;
922 }
923 $i += 7;
924 break;
925 // Destroy these tags
926 case 'HTML':
927 case 'HEAD':
928 case '/HTM':
929 case '/HEA':
930 case '!DOC':
931 case 'META':
932 //case 'DIV ':
933 //case '/DIV':
934 case '!-- ':
935 $i += 4;
936 while ( $body{$i} <> '>' &&
937 $i < $j )
938 $i++;
939 // $i++;
940 break;
941 case 'STYL':
942 $i += 5;
943 while ( $body{$i} <> '>' && // </title>
944 $i < $j )
945 $i++;
946 $i++;
947 // We parse the style to look for interesting stuff
948 $styleblk = '';
949 while ( $body{$i} <> '>' &&
950 $i < $j ) {
951 // First we get the name of the style
952 $style = '';
953 while ( $body{$i} <> '>' &&
954 $body{$i} <> '<' &&
955 $body{$i} <> '{' &&
956 $i < $j ) {
957 if ( isnoSep( $body{$i} ) )
958 $style .= $body{$i};
959 $i++;
960 }
961 stripComments( $i, $j, $body );
962 $style = strtoupper( trim( $style ) );
963 if ( $style == 'BODY' ) {
964 // Next we look into the definitions of the body style
965 while ( $body{$i} <> '>' &&
966 $body{$i} <> '}' &&
967 $i < $j ) {
968 // We look for the background color if any.
969 if ( substr( $body, $i, 17 ) == 'BACKGROUND-COLOR:' ) {
970 $i += 17;
971 $bgcolor = getStyleData( $i, $j, $body );
972 } elseif ( substr( $body, $i, 12 ) == 'MARGIN-LEFT:' ) {
973 $i += 12;
974 $leftmargin = getStyleData( $i, $j, $body );
975 }
976 $i++;
977 }
978 } else {
979 // Other style are mantained
980 $styleblk .= "$style ";
981 while ( $body{$i} <> '>' &&
982 $body{$i} <> '<' &&
983 $body{$i} <> '}' &&
984 $i < $j ) {
985 $styleblk .= $body{$i};
986 $i++;
987 }
988 $styleblk .= $body{$i};
989 }
990 stripComments( $i, $j, $body );
991 if ( $body{$i} <> '>' )
992 $i++;
993 }
994 if ( $styleblk <> '' )
995 $ret .= "<style>$styleblk";
996 break;
997 case 'BODY':
998 if ( $title <> '' )
999 $ret .= '<b>' . _("Title:") . " </b>$title<br>\n";
1000 $ret .= "<TABLE";
1001 $i += 5;
1002 if (! isset($base)) {
1003 $base = '';
1004 }
1005 $ret .= stripEvent( $i, $j, $body, $id, $base );
1006 $ret .= " bgcolor=$bgcolor width=\"100%\"><tr>";
1007 if ( $leftmargin <> '' )
1008 $ret .= "<td width=$leftmargin>&nbsp;</td>";
1009 $ret .= '<td>';
1010 if (strtolower($bgcolor) == 'ffffff' ||
1011 strtolower($bgcolor) == '#ffffff')
1012 $ret .= '<font color=#000000>';
1013 break;
1014 case 'BASE':
1015 $i += 5;
1016 $base = '';
1017 while ( !isNoSep( $body{$i} ) &&
1018 $i < $j ) {
1019 $i++;
1020 }
1021 if ( strcasecmp( substr( $base, 0, 4 ), 'href' ) ) {
1022 $i += 5;
1023 while ( !isNoSep( $body{$i} ) &&
1024 $i < $j ) {
1025 $i++;
1026 }
1027 while ( $body{$i} <> '>' &&
1028 $i < $j ) {
1029 if ( $body{$i} <> '"' ) {
1030 $base .= $body{$i};
1031 }
1032 $i++;
1033 }
1034 // Debuging $ret .= "<!-- base == $base -->";
1035 if ( strcasecmp( substr( $base, 0, 4 ), 'file' ) <> 0 ) {
1036 $ret .= "\n<BASE HREF=\"$base\">\n";
1037 }
1038 }
1039 break;
1040 case '/BOD':
1041 $ret .= '</font></td></tr></TABLE>';
1042 $i += 6;
1043 break;
1044 default:
1045 // Following tags can contain some event handler, lets search it
1046 stripComments( $i, $j, $body );
1047 if (! isset($base)) {
1048 $base = '';
1049 }
1050 $ret .= stripEvent( $i, $j, $body, $id, $base ) . '>';
1051 // $ret .= "<!-- $tag detected -->";
1052 }
1053 } else {
1054 $ret .= $body{$i};
1055 }
1056 $i++;
1057 }
1058
1059 return( "\n\n<!-- HTML Output ahead -->\n" .
1060 $ret .
1061 "\n<!-- END of HTML Output --><base href=\"".
1062 get_location() . '/'.
1063 "\">\n\n" );
1064 }
1065
1066 function isNoSep( $char ) {
1067
1068 switch( $char ) {
1069 case ' ':
1070 case "\n":
1071 case "\t":
1072 case "\r":
1073 case '>':
1074 case '"':
1075 return( FALSE );
1076 break;
1077 default:
1078 return( TRUE );
1079 }
1080
1081 }
1082
1083 /*
1084 The following function is usefull to remove extra data that can cause
1085 html not to display properly. Especialy with MS stuff.
1086 */
1087
1088 function stripComments( &$i, $j, &$body ) {
1089
1090 while ( $body{$i}.$body{$i+1}.$body{$i+2}.$body{$i+3} == '<!--' &&
1091 $i < $j ) {
1092 $i += 5;
1093 while ( $body{$i-2}.$body{$i-1}.$body{$i} <> '-->' &&
1094 $i < $j )
1095 $i++;
1096 $i++;
1097 }
1098
1099 return;
1100
1101 }
1102
1103 /* Gets the style data of a specific style */
1104
1105 function getStyleData( &$i, $j, &$body ) {
1106
1107 // We skip spaces
1108 while ( $body{$i} <> '>' && !isNoSep( $body{$i} ) &&
1109 $i < $j ) {
1110 $i++;
1111 }
1112 // And get the color
1113 $ret = '';
1114 while ( isNoSep( $body{$i} ) &&
1115 $i < $j ) {
1116 $ret .= $body{$i};
1117 $i++;
1118 }
1119
1120 return( $ret );
1121 }
1122
1123 /*
1124 Private function for strip_dangerous_tag. Look for event based coded and "remove" it
1125 change on with no (onload -> noload)
1126 */
1127
1128 function stripEvent( &$i, $j, &$body, $id, $base ) {
1129
1130 global $message, $base_uri;
1131
1132 $ret = '';
1133
1134 while ( $body{$i} <> '>' &&
1135 $i < $j ) {
1136 $etg = strtolower($body{$i}.$body{$i+1}.$body{$i+2});
1137 switch( $etg ) {
1138 case 'src':
1139 // This is probably a src specification
1140 $k = $i + 3;
1141 while( !isNoSep( $body{$k} )) {
1142 $k++;
1143 }
1144 if ( $body{$k} == '=' ) {
1145 /* It is indeed */
1146 $k++;
1147 while( !isNoSep( $body{$k} ) &&
1148 $k < $j ) {
1149 $k++;
1150 }
1151 $src = '';
1152 while ( $body{$k} <> '>' && isNoSep( $body{$k} ) &&
1153 $k < $j ) {
1154 $src .= $body{$k};
1155 $k++;
1156 }
1157 while( !isNoSep( $body{$k} ) &&
1158 $k < $j ) {
1159 $k++;
1160 }
1161 if ( strtolower( substr( $src, 0, 4 ) ) == 'cid:' ) {
1162 $src = substr( $src, 4 );
1163 $src = "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1164 urlencode( $message->header->mailbox ) .
1165 "&passed_ent_id=" . find_ent_id( $src, $message );
1166 } else if ( strtolower( substr( $src, 0, 4 ) ) <> 'http' ||
1167 stristr( $src, $base_uri ) ) {
1168 /* Javascript and local urls goes out */
1169 $src = '../images/' . _("sec_remove_eng.png");
1170 }
1171 $ret .= 'src="' . $src . '" ';
1172 $i = $k - 2;
1173 } else {
1174 $ret .= 'src';
1175 $i = $i + 3;
1176 }
1177
1178 break;
1179 case '../':
1180 // Retrolinks are not allowed without a base because they mess with SM security
1181 if ( $base == '' ) {
1182 $i += 2;
1183 } else {
1184 $ret .= '.';
1185 }
1186 break;
1187 case 'cid':
1188 // Internal link
1189 $k = $i-1;
1190 if ( $body{$i+3} == ':') {
1191 $i +=4;
1192 $name = '';
1193 while ( isNoSep( $body{$i} ) &&
1194 $i < $j ) {
1195 $name .= $body{$i++};
1196 }
1197 if ( $name <> '' ) {
1198 $ret .= "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1199 urlencode( $message->header->mailbox ) .
1200 "&passed_ent_id=" . find_ent_id( $name, $message );
1201 if ( $body{$k} == '"' )
1202 $ret .= '" ';
1203 else
1204 $ret .= ' ';
1205 }
1206 if ( $body{$i} == '>' )
1207 $i -= 1;
1208 }
1209 break;
1210 case ' on':
1211 case "\non":
1212 case "\ron":
1213 case "\ton":
1214 $ret .= ' no';
1215 $i += 2;
1216 break;
1217 case 'pt:':
1218 if ( strcasecmp( $body{$i-4}.$body{$i-3}.$body{$i-2}.$body{$i-1}.$body{$i}.$body{$i+1}.$body{$i+2}, 'script:') == 0 ) {
1219 $ret .= '_no/';
1220 } else {
1221 $ret .= $etg;
1222 }
1223 $i += 2;
1224 break;
1225 default:
1226 $ret .= $body{$i};
1227 }
1228 $i++;
1229 }
1230 return( $ret );
1231 }
1232
1233
1234 /* This function trys to locate the entity_id of a specific mime element */
1235
1236 function find_ent_id( $id, $message ) {
1237
1238 $ret = '';
1239 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
1240
1241 if ( $message->entities[$i]->header->entity_id == '' ) {
1242 $ret = find_ent_id( $id, $message->entities[$i] );
1243 } else {
1244 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
1245 $ret = $message->entities[$i]->header->entity_id;
1246 }
1247
1248 }
1249
1250 return( $ret );
1251
1252 }
1253 ?>