Comments removal
[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 $ssid = sqimap_session_id();
54 $lsid = strlen( $ssid );
55 $id = $header->id;
56 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
57 //
58 // This should use sqimap_read_data instead of reading it itself
59 //
60 $read = fgets ($imap_stream, 9216);
61 $bodystructure = '';
62 while ( substr($read, 0, $lsid) <> $ssid &&
63 !feof( $imap_stream ) ) {
64 $bodystructure .= $read;
65 $read = fgets ($imap_stream, 9216);
66 }
67 $read = $bodystructure;
68
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);
77 }
78
79 $msg = mime_parse_structure ($read, 0);
80 $msg->header = $header;
81
82 return( $msg );
83 }
84
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
87 * $message.
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()
92 */
93 function mime_parse_structure ($structure, $ent_id) {
94
95 $msg = new message();
96 if ($structure{0} == '(') {
97 $ent_id = mime_new_element_level($ent_id);
98 $start = $end = -1;
99 do {
100 $start = $end+1;
101 $end = mime_match_parenthesis ($start, $structure);
102
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} == '(');
108 } else {
109 // parse the elements
110 $msg = mime_get_element ($structure, $msg, $ent_id);
111 }
112 return $msg;
113 }
114
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.
118 */
119 function mime_increment_id ($id) {
120
121 if (strpos($id, '.')) {
122 $first = substr($id, 0, strrpos($id, '.'));
123 $last = substr($id, strrpos($id, '.')+1);
124 $last++;
125 $new = $first . '.' .$last;
126 } else {
127 $new = $id + 1;
128 }
129
130 return $new;
131 }
132
133 /*
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.
140 */
141 function mime_new_element_level ($id) {
142
143 if (!$id) {
144 $id = 0;
145 } else {
146 $id = $id . '.0';
147 }
148
149 return( $id );
150 }
151
152 function mime_get_element (&$structure, $msg, $ent_id) {
153
154 $elem_num = 1;
155 $msg->header = new msg_header();
156 $msg->header->entity_id = $ent_id;
157 $properties = array();
158
159 while (strlen($structure) > 0) {
160 $structure = trim($structure);
161 $char = $structure{0};
162
163 if (strtolower(substr($structure, 0, 3)) == 'nil') {
164 $text = '';
165 $structure = substr($structure, 3);
166 } else if ($char == '"') {
167 // loop through until we find the matching quote, and return that as a string
168 $pos = 1;
169 $text = '';
170 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
171 $text .= $char;
172 $pos++;
173 }
174 $structure = substr($structure, strlen($text) + 2);
175 } else if ($char == '(') {
176 // comment me
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);
181 } else {
182 // loop through until we find a space or an end parenthesis
183 $pos = 0;
184 $char = $structure{$pos};
185 $text = '';
186 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
187 $text .= $char;
188 $pos++;
189 $char = $structure{$pos};
190 }
191 $structure = substr($structure, strlen($text));
192 }
193
194 // This is where all the text parts get put into the header
195 switch ($elem_num) {
196 case 1:
197 $msg->header->type0 = strtolower($text);
198 break;
199 case 2:
200 $msg->header->type1 = strtolower($text);
201 break;
202 case 4: // Id
203 // Invisimail enclose images with <>
204 $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
205 break;
206 case 5:
207 $msg->header->description = $text;
208 break;
209 case 6:
210 $msg->header->encoding = strtolower($text);
211 break;
212 case 7:
213 $msg->header->size = $text;
214 break;
215 default:
216 if ($msg->header->type0 == 'text' && $elem_num == 8) {
217 // This is a plain text message, so lets get the number of lines
218 // that it contains.
219 $msg->header->num_lines = $text;
220
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);
230
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));
236
237 // Now we'll go through and reformat the results.
238 if ($m->entities) {
239 for ($i=0; $i < count($m->entities); $i++) {
240 $msg->addEntity($m->entities[$i]);
241 }
242 } else {
243 $msg->addEntity($m);
244 }
245 $structure = "";
246 }
247 }
248 break;
249 }
250 $elem_num++;
251 $text = "";
252 }
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'];
257 }
258 // }
259
260 return $msg;
261 }
262
263 /*
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.
270 *
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";
278 */
279 function mime_get_props ($props, $structure) {
280
281 while (strlen($structure) > 0) {
282 $structure = trim($structure);
283 $char = $structure{0};
284
285 if ($char == '"') {
286 $pos = 1;
287 $tmp = '';
288 while ( ( $char = $structure{$pos} ) != '"' &&
289 $pos < strlen($structure)) {
290 $tmp .= $char;
291 $pos++;
292 }
293 $structure = trim(substr($structure, strlen($tmp) + 2));
294 $char = $structure{0};
295
296 if ($char == '"') {
297 $pos = 1;
298 $value = '';
299 while ( ( $char = $structure{$pos} ) != '"' &&
300 $pos < strlen($structure) ) {
301 $value .= $char;
302 $pos++;
303 }
304 $structure = trim(substr($structure, strlen($tmp) + 2));
305
306 $k = count($props);
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);
312 if (! isset($props))
313 $props = array();
314 $props = mime_get_props($props, $sub);
315 $structure = substr($structure, strlen($sub) + 2);
316 }
317 return $props;
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);
323 return $props;
324 } else {
325 return $props;
326 }
327 }
328 }
329
330 /*
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 ... )
334 * x x
335 * then this would return 42 to match up those two.
336 */
337 function mime_match_parenthesis ($pos, $structure) {
338
339 $j = strlen( $structure );
340
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} != '(' ) {
345 return( $j );
346 }
347
348 while ( $pos < $j ) {
349 $pos++;
350 if ($structure{$pos} == ')') {
351 return $pos;
352 } elseif ($structure{$pos} == '"') {
353 $pos++;
354 while ( $structure{$pos} != '"' &&
355 $pos < $j ) {
356 if (substr($structure, $pos, 2) == '\\"') {
357 $pos++;
358 } elseif (substr($structure, $pos, 2) == '\\\\') {
359 $pos++;
360 }
361 $pos++;
362 }
363 } elseif ( $structure{$pos} == '(' ) {
364 $pos = mime_match_parenthesis ($pos, $structure);
365 }
366 }
367 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
368 return( $pos );
369 }
370
371 function mime_fetch_body($imap_stream, $id, $ent_id ) {
372
373 /*
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.
376 */
377 if (!$ent_id) {
378 $ent_id = 1;
379 }
380
381 $cmd = "FETCH $id BODY[$ent_id]";
382 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
383
384 do {
385 $topline = array_shift( $data );
386 } while( $topline && $topline == '*' && !preg_match( '/\\* [0-9] FETCH.*/i', $topline )) ;
387 $wholemessage = implode('', $data);
388 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
389
390 $ret = substr( $wholemessage, 0, $regs[1] );
391 /*
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.
394 */
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)
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 }
424 } else if (ereg('"([^"]*)"', $topline, $regs)) {
425 $ret = $regs[1];
426 } else {
427 global $where, $what, $mailbox, $passed_id, $startMessage;
428 $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
429 if (isset($where) && isset($what)) {
430 $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
431 } else {
432 $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
433 }
434 $par .= '&amp;response=' . urlencode($response) .
435 '&amp;message=' . urlencode($message).
436 '&amp;topline=' . urlencode($topline);
437
438 echo '<tt><br>' .
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>&nbsp;' .
444 '</td></tr>' .
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>";
450
451 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
452 array_shift($data);
453 $wholemessage = implode('', $data);
454
455 $ret = $wholemessage;
456 }
457 return( $ret );
458 }
459
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.
463 if (!$ent_id) {
464 $ent_id = 1;
465 }
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.
469
470 // don´t call set_time_limit in safe mode.
471 if (!ini_get("safe_mode")) {
472 set_time_limit(0);
473 }
474
475 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
476 $cnt = 0;
477 $continue = true;
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) == ')==') {
483 $read1 = $read;
484 $read = fgets ($imap_stream,4096);
485 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
486 return;
487 } else {
488 echo decodeBody($read1, $encoding) .
489 decodeBody($read, $encoding);
490 }
491 } else if ($cnt) {
492 echo decodeBody($read, $encoding);
493 }
494 $read = fgets ($imap_stream,4096);
495 $cnt++;
496 }
497 }
498
499 /* -[ END MIME DECODING ]----------------------------------------------------------- */
500
501
502
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
505 */
506 function decodeMime ($imap_stream, &$header) {
507 global $username, $key, $imapServerAddress, $imapPort;
508 return mime_structure ($imap_stream, $header);
509 }
510
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.
513
514 function listEntities ($message) {
515 if ($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);
520 if ($msg)
521 return $msg;
522 }
523 }
524 }
525
526
527 /* returns a $message object for a particular entity id */
528 function getEntity ($message, $ent_id) {
529 if ($message) {
530 if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id)) {
531 return $message;
532 } else {
533 for ($i = 0; isset($message->entities[$i]); $i++) {
534 $msg = getEntity ($message->entities[$i], $ent_id);
535 if ($msg) {
536 return $msg;
537 }
538 }
539 }
540 }
541 }
542
543 /*
544 * figures out what entity to display and returns the $message object
545 * for that entity.
546 */
547 function findDisplayEntity ($message, $textOnly = 1) {
548 global $show_html_default;
549
550 $entity = 0;
551
552 if ($message) {
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);
559 }
560
561 // Show text/plain or text/html -- the first one we find.
562 if ( $entity == 0 &&
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;
568 }
569
570 $i = 0;
571 while ($entity == 0 && isset($message->entities[$i]) ) {
572 $entity = findDisplayEntity($message->entities[$i], $textOnly);
573 $i++;
574 }
575 }
576
577 return( $entity );
578 }
579
580 /* Shows the HTML version */
581 function findDisplayEntityHTML ($message) {
582
583 if ( $message->header->type0 == 'text' &&
584 $message->header->type1 == 'html' &&
585 isset($message->header->entity_id)) {
586 return $message->header->entity_id;
587 }
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)) {
592 return 0;
593 }
594 $entity = findDisplayEntityHTML($message->entities[$i]);
595 if ($entity != 0) {
596 return $entity;
597 }
598 }
599
600 return 0;
601 }
602
603 /* This returns a parsed string called $body. That string can then
604 be displayed as the actual message in the HTML. It contains
605 everything needed, including HTML Tags, Attachments at the
606 bottom, etc.
607 */
608 function formatBody($imap_stream, $message, $color, $wrap_at) {
609 // this if statement checks for the entity to show as the
610 // primary message. To add more of them, just put them in the
611 // order that is their priority.
612 global $startMessage, $username, $key, $imapServerAddress, $imapPort, $body,
613 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
614
615 $has_unsafe_images = 0;
616
617 $id = $message->header->id;
618
619 $urlmailbox = urlencode($message->header->mailbox);
620
621 // Get the right entity and redefine message to be this entity
622 // Pass the 0 to mean that we want the 'best' viewable one
623 $ent_num = findDisplayEntity ($message, 0);
624 $body_message = getEntity($message, $ent_num);
625
626 if (($body_message->header->type0 == 'text') ||
627 ($body_message->header->type0 == 'rfc822')) {
628 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
629 $body = decodeBody($body, $body_message->header->encoding);
630 $hookResults = do_hook("message_body", $body);
631 $body = $hookResults[1];
632
633 // If there are other types that shouldn't be formatted, add
634 // them here
635 if ($body_message->header->type1 == 'html') {
636 if ( $show_html_default <> 1 ) {
637 $body = strip_tags( $body );
638 translateText($body, $wrap_at, $body_message->header->charset);
639 } else {
640 $body = MagicHTML( $body, $id );
641 }
642 } else {
643 translateText($body, $wrap_at, $body_message->header->charset);
644 }
645
646 $body .= "<CENTER><SMALL><A HREF=\"../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;passed_ent_id=$ent_num&amp;mailbox=$urlmailbox&amp;showHeaders=1\">". _("Download this as a file") ."</A></SMALL></CENTER><BR>";
647 if ($has_unsafe_images) {
648 if ($view_unsafe_images) {
649 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
650 } else {
651 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0&amp;view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
652 }
653 }
654
655 /** Display the ATTACHMENTS: message if there's more than one part **/
656 if (isset($message->entities[0])) {
657 $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
658 }
659 } else {
660 $body = formatAttachments ($message, -1, $message->header->mailbox, $id);
661 }
662 return ($body);
663 }
664
665 /*
666 * A recursive function that returns a list of attachments with links
667 * to where to download these attachments
668 */
669 function formatAttachments($message, $ent_id, $mailbox, $id) {
670 global $where, $what;
671 global $startMessage, $color;
672 static $ShownHTML = 0;
673
674 $body = '';
675 if ($ShownHTML == 0) {
676
677 $ShownHTML = 1;
678 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
679 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
680 _("Attachments") . ':' .
681 "</B></TH></TR><TR><TD>\n" .
682 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
683 formatAttachments($message, $ent_id, $mailbox, $id) .
684 "</TABLE></TD></TR></TABLE>";
685
686 } else if ($message) {
687 $header = $message->header;
688 $type0 = strtolower($header->type0);
689 $type1 = strtolower($header->type1);
690 $name = decodeHeader($header->name);
691
692 if ($type0 =='message' && $type1 = 'rfc822') {
693
694 $filename = decodeHeader($message->header->filename);
695 if (trim($filename) == '') {
696 if (trim($name) == '') {
697 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
698 } else {
699 $display_filename = $name;
700 $filename = $name;
701 }
702 } else {
703 $display_filename = $filename;
704 }
705
706 $urlMailbox = urlencode($mailbox);
707 $ent = urlencode($message->header->entity_id);
708
709 $DefaultLink =
710 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
711 if ($where && $what) {
712 $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
713 }
714 $Links['download link']['text'] = _("download");
715 $Links['download link']['href'] =
716 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
717 $ImageURL = '';
718
719 /* this executes the attachment hook with a specific MIME-type.
720 * if that doens't have results, it tries if there's a rule
721 * for a more generic type. */
722 $HookResults = do_hook("attachment $type0/$type1", $Links,
723 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
724 if(count($HookResults[1]) <= 1) {
725 $HookResults = do_hook("attachment $type0/*", $Links,
726 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
727 $display_filename, $where, $what);
728 }
729
730 $Links = $HookResults[1];
731 $DefaultLink = $HookResults[6];
732
733 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
734 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
735 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
736 '</b>&nbsp;&nbsp;</small></TD>' .
737 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
738 '<TD><SMALL>';
739 if ($message->header->description) {
740 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
741 }
742 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
743
744
745 $SkipSpaces = 1;
746 foreach ($Links as $Val) {
747 if ($SkipSpaces) {
748 $SkipSpaces = 0;
749 } else {
750 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
751 }
752 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
753 }
754
755 unset($Links);
756
757 $body .= "</SMALL></TD></TR>\n";
758
759 return( $body );
760
761 } elseif (!$message->entities) {
762
763 $type0 = strtolower($message->header->type0);
764 $type1 = strtolower($message->header->type1);
765 $name = decodeHeader($message->header->name);
766
767 if ($message->header->entity_id != $ent_id) {
768 $filename = decodeHeader($message->header->filename);
769 if (trim($filename) == '') {
770 if (trim($name) == '') {
771 if ( trim( $message->header->id ) == '' )
772 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
773 else
774 $display_filename = 'cid: ' . $message->header->id;
775 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
776 } else {
777 $display_filename = $name;
778 $filename = $name;
779 }
780 } else {
781 $display_filename = $filename;
782 }
783
784 $urlMailbox = urlencode($mailbox);
785 $ent = urlencode($message->header->entity_id);
786
787 $DefaultLink =
788 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
789 if ($where && $what) {
790 $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
791 }
792 $Links['download link']['text'] = _("download");
793 $Links['download link']['href'] =
794 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
795 $ImageURL = '';
796
797 /* this executes the attachment hook with a specific MIME-type.
798 * if that doens't have results, it tries if there's a rule
799 * for a more generic type. */
800 $HookResults = do_hook("attachment $type0/$type1", $Links,
801 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
802 $display_filename, $where, $what);
803 if(count($HookResults[1]) <= 1) {
804 $HookResults = do_hook("attachment $type0/*", $Links,
805 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
806 $display_filename, $where, $what);
807 }
808
809 $Links = $HookResults[1];
810 $DefaultLink = $HookResults[6];
811
812 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
813 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
814 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
815 '</b>&nbsp;&nbsp;</small></TD>' .
816 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
817 '<TD><SMALL>';
818 if ($message->header->description) {
819 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
820 }
821 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
822
823
824 $SkipSpaces = 1;
825 foreach ($Links as $Val) {
826 if ($SkipSpaces) {
827 $SkipSpaces = 0;
828 } else {
829 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
830 }
831 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
832 }
833
834 unset($Links);
835
836 $body .= "</SMALL></TD></TR>\n";
837 }
838 } else {
839 for ($i = 0; $i < count($message->entities); $i++) {
840 $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
841 }
842 }
843 }
844 return( $body );
845 }
846
847
848 /** this function decodes the body depending on the encoding type. **/
849 function decodeBody($body, $encoding) {
850 $body = str_replace("\r\n", "\n", $body);
851 $encoding = strtolower($encoding);
852
853 global $show_html_default;
854
855 if ($encoding == 'quoted-printable') {
856 $body = quoted_printable_decode($body);
857
858
859 while (ereg("=\n", $body))
860 $body = ereg_replace ("=\n", "", $body);
861
862 } else if ($encoding == 'base64') {
863 $body = base64_decode($body);
864 }
865
866 // All other encodings are returned raw.
867 return $body;
868 }
869
870 /*
871 * This functions decode strings that is encoded according to
872 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
873 */
874 function decodeHeader ($string, $utfencode=true) {
875
876 if ( is_array( $string ) ) {
877 $string = implode("\n", $string );
878 }
879
880 if (eregi('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
881 $string, $res)) {
882 if (ucfirst($res[2]) == 'B') {
883 $replace = base64_decode($res[3]);
884 } else {
885 $replace = str_replace('_', ' ', $res[3]);
886 // Convert lowercase Quoted Printable to uppercase for
887 // quoted_printable_decode to understand it.
888 while (ereg("(=(([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef])))",
889 $replace, $res)) {
890 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
891 }
892 $replace = quoted_printable_decode($replace);
893 }
894 /* Only encode into entities by default. Some places
895 don't need the encoding, like the compose form. */
896 if ($utfencode){
897 $replace = charset_decode ($res[1], $replace);
898 }
899
900 // Remove the name of the character set.
901 $string = eregi_replace ('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
902 $replace, $string);
903
904 // In case there should be more encoding in the string: recurse
905 $string = decodeHeader($string);
906 }
907
908 return ($string);
909 }
910
911 /*
912 * Encode a string according to RFC 1522 for use in headers if it
913 * contains 8-bit characters or anything that looks like it should
914 * be encoded.
915 */
916 function encodeHeader ($string) {
917 global $default_charset;
918
919 // Encode only if the string contains 8-bit characters or =?
920 $j = strlen( $string );
921 $l = strstr($string, '=?'); // Must be encoded ?
922 $ret = '';
923 for( $i=0; $i < $j; ++$i) {
924 switch( $string{$i} ) {
925 case '=':
926 $ret .= '=3D';
927 break;
928 case '?':
929 $ret .= '=3F';
930 break;
931 case '_':
932 $ret .= '=5F';
933 break;
934 case ' ':
935 $ret .= '_';
936 break;
937 default:
938 $k = ord( $string{$i} );
939 if ( $k > 126 ) {
940 $ret .= sprintf("=%02X", $k);
941 $l = TRUE;
942 } else
943 $ret .= $string{$i};
944 }
945 }
946
947 if ( $l ) {
948 $string = "=?$default_charset?Q?$ret?=";
949 }
950
951 return( $string );
952 }
953
954 /*
955 Strips dangerous tags from html messages.
956 */
957 function MagicHTML( $body, $id ) {
958
959 global $message, $HTTP_SERVER_VARS,
960 $attachment_common_show_images;
961
962 $attachment_common_show_images =
963 FALSE; // Don't display attached images in HTML mode
964 $j = strlen( $body ); // Legnth of the HTML
965 $ret = ''; // Returned string
966 $bgcolor = '#ffffff'; // Background style color (defaults to white)
967 $textcolor = '#000000'; // Foreground style color (defaults to black)
968 $leftmargin = ''; // Left margin style
969 $title = ''; // HTML title if any
970
971 $i = 0;
972 while ( $i < $j ) {
973 if ( $body{$i} == '<' ) {
974 $pos = $i + 1;
975 $tag = '';
976 while ($body{$pos} == ' ' || $body{$pos} == "\t" ||
977 $body{$pos} == "\n" ) {
978 $pos ++;
979 }
980 while (strlen($tag) < 4 && $body{$pos} != ' ' &&
981 $body{$pos} != "\t" && $body{$pos} != "\n" &&
982 $pos < $j ) {
983 $tag .= $body{$pos};
984 $pos ++;
985 }
986 /*
987 A comment in HTML is only three characters and isn't
988 guaranteed to have a space after it. This fudges so
989 it will be caught by the switch statement.
990 */
991 if (ereg("!--", $tag)) {
992 $tag = "!-- ";
993 }
994 switch( strtoupper( $tag ) ) {
995 // Strips the entire tag and contents
996 case 'APPL':
997 case 'EMBE':
998 case 'FRAM':
999 case 'SCRI':
1000 case 'OBJE':
1001 $etg = '/' . $tag;
1002 while ( $body{$i+1}.$body{$i+2}.$body{$i+3}.$body{$i+4}.$body{$i+5} <> $etg &&
1003 $i < $j ) $i++;
1004 while ( $i < $j && $body{++$i} <> '>' );
1005 // $ret .= "<!-- $tag removed -->";
1006 break;
1007 // Substitute Title
1008 case 'TITL':
1009 $i += 5;
1010 while ( $body{$i} <> '>' && // </title>
1011 $i < $j )
1012 $i++;
1013 $i++;
1014 $title = '';
1015 while ( $body{$i} <> '<' && // </title>
1016 $i < $j ) {
1017 $title .= $body{$i};
1018 $i++;
1019 }
1020 $i += 7;
1021 break;
1022 // Destroy these tags
1023 case 'HTML':
1024 case 'HEAD':
1025 case '/HTM':
1026 case '/HEA':
1027 case '!DOC':
1028 case 'META':
1029 //case 'DIV ':
1030 //case '/DIV':
1031 case '!-- ':
1032 $i += 4;
1033 while ( $body{$i} <> '>' &&
1034 $i < $j )
1035 $i++;
1036 // $i++;
1037 break;
1038 case 'STYL':
1039 $i += 5;
1040 while ( $body{$i} <> '>' && // </title>
1041 $i < $j )
1042 $i++;
1043 $i++;
1044 // We parse the style to look for interesting stuff
1045 $styleblk = '';
1046 while ( $body{$i} <> '>' &&
1047 $i < $j ) {
1048 // First we get the name of the style
1049 $style = '';
1050 while ( $body{$i} <> '>' &&
1051 $body{$i} <> '<' &&
1052 $body{$i} <> '{' &&
1053 $i < $j ) {
1054 if ( isnoSep( $body{$i} ) )
1055 $style .= $body{$i};
1056 $i++;
1057 }
1058 stripComments( $i, $j, $body );
1059 $style = strtoupper( trim( $style ) );
1060 if ( $style == 'BODY' ) {
1061 // Next we look into the definitions of the body style
1062 while ( $body{$i} <> '>' &&
1063 $body{$i} <> '}' &&
1064 $i < $j ) {
1065 // We look for the background color if any.
1066 if ( substr( $body, $i, 17 ) == 'BACKGROUND-COLOR:' ) {
1067 $i += 17;
1068 $bgcolor = getStyleData( $i, $j, $body );
1069 } elseif ( substr( $body, $i, 12 ) == 'MARGIN-LEFT:' ) {
1070 $i += 12;
1071 $leftmargin = getStyleData( $i, $j, $body );
1072 }
1073 $i++;
1074 }
1075 } else {
1076 // Other style are mantained
1077 $styleblk .= "$style ";
1078 while ( $body{$i} <> '>' &&
1079 $body{$i} <> '<' &&
1080 $body{$i} <> '}' &&
1081 $i < $j ) {
1082 $styleblk .= $body{$i};
1083 $i++;
1084 }
1085 $styleblk .= $body{$i};
1086 }
1087 stripComments( $i, $j, $body );
1088 if ( $body{$i} <> '>' )
1089 $i++;
1090 }
1091 if ( $styleblk <> '' )
1092 $ret .= "<style>$styleblk";
1093 break;
1094 case 'BODY':
1095 if ( $title <> '' )
1096 $ret .= '<b>' . _("Title:") . " </b>$title<br>\n";
1097 $ret .= "<TABLE";
1098 $i += 5;
1099 if (! isset($base)) {
1100 $base = '';
1101 }
1102 $ret .= stripEvent( $i, $j, $body, $id, $base );
1103 $ret .= " bgcolor=$bgcolor width=\"100%\"><tr>";
1104 if ( $leftmargin <> '' )
1105 $ret .= "<td width=$leftmargin>&nbsp;</td>";
1106 $ret .= '<td>';
1107 if (strtolower($bgcolor) == 'ffffff' ||
1108 strtolower($bgcolor) == '#ffffff')
1109 $ret .= '<font color=#000000>';
1110 break;
1111 case 'BASE':
1112 $i += 4;
1113 $base = '';
1114 if ( strncasecmp($body{$i}, 'font', 4) ) {
1115 $i += 5;
1116 while ( !isNoSep( $body{$i} ) && $i < $j ) {
1117 $i++;
1118 }
1119 while ( $body{$i} <> '>' && $i < $j ) {
1120 $base .= $body{$i};
1121 $i++;
1122 }
1123 $ret .= "<BASEFONT $base>\n";
1124 break;
1125 }
1126 $i++;
1127 while ( !isNoSep( $body{$i} ) &&
1128 $i < $j ) {
1129 $i++;
1130 }
1131 if ( strcasecmp( substr( $base, 0, 4 ), 'href' ) ) {
1132 $i += 5;
1133 while ( !isNoSep( $body{$i} ) &&
1134 $i < $j ) {
1135 $i++;
1136 }
1137 while ( $body{$i} <> '>' &&
1138 $i < $j ) {
1139 if ( $body{$i} <> '"' ) {
1140 $base .= $body{$i};
1141 }
1142 $i++;
1143 }
1144 // Debuging $ret .= "<!-- base == $base -->";
1145 if ( strcasecmp( substr( $base, 0, 4 ), 'file' ) <> 0 ) {
1146 $ret .= "\n<BASE HREF=\"$base\">\n";
1147 }
1148 }
1149 break;
1150 case '/BOD':
1151 $ret .= '</font></td></tr></TABLE>';
1152 $i += 6;
1153 break;
1154 default:
1155 // Following tags can contain some event handler, lets search it
1156 stripComments( $i, $j, $body );
1157 if (! isset($base)) {
1158 $base = '';
1159 }
1160 $ret .= stripEvent( $i, $j, $body, $id, $base ) . '>';
1161 // $ret .= "<!-- $tag detected -->";
1162 }
1163 } else {
1164 $ret .= $body{$i};
1165 }
1166 $i++;
1167 }
1168
1169 return( "\n\n<!-- HTML Output ahead -->\n" .
1170 $ret .
1171 /* Base is illegal within HTML
1172 "\n<!-- END of HTML Output --><base href=\"".
1173 get_location() . '/'.
1174 "\">\n\n" );
1175 */
1176 "\n<!-- END of HTML Output -->\n\n" );
1177 }
1178
1179 function isNoSep( $char ) {
1180
1181 switch( $char ) {
1182 case ' ':
1183 case "\n":
1184 case "\t":
1185 case "\r":
1186 case '>':
1187 case '"':
1188 return( FALSE );
1189 break;
1190 default:
1191 return( TRUE );
1192 }
1193
1194 }
1195
1196 /*
1197 The following function is usefull to remove extra data that can cause
1198 html not to display properly. Especialy with MS stuff.
1199 */
1200
1201 function stripComments( &$i, $j, &$body ) {
1202
1203 while ( $body{$i}.$body{$i+1} == '<!' &&
1204 $i < $j ) {
1205 $i += 5;
1206 while ( $body{$i-2}.$body{$i-1}.$body{$i} <> '-->' &&
1207 $i < $j )
1208 $i++;
1209 $i++;
1210 }
1211
1212 return;
1213
1214 }
1215
1216 /* Gets the style data of a specific style */
1217
1218 function getStyleData( &$i, $j, &$body ) {
1219
1220 // We skip spaces
1221 while ( $body{$i} <> '>' && !isNoSep( $body{$i} ) &&
1222 $i < $j ) {
1223 $i++;
1224 }
1225 // And get the color
1226 $ret = '';
1227 while ( isNoSep( $body{$i} ) &&
1228 $i < $j ) {
1229 $ret .= $body{$i};
1230 $i++;
1231 }
1232
1233 return( $ret );
1234 }
1235
1236 /*
1237 Private function for strip_dangerous_tag. Look for event based coded and "remove" it
1238 change on with no (onload -> noload)
1239 */
1240
1241 function stripEvent( &$i, $j, &$body, $id, $base ) {
1242
1243 global $message, $base_uri, $has_unsafe_images, $view_unsafe_images;
1244
1245 $ret = '';
1246
1247 while ( $body{$i} <> '>' &&
1248 $i < $j ) {
1249 $etg = strtolower($body{$i}.$body{$i+1}.$body{$i+2});
1250 switch( $etg ) {
1251 case 'src':
1252 // This is probably a src specification
1253 $k = $i + 3;
1254 while( !isNoSep( $body{$k} )) {
1255 $k++;
1256 }
1257 if ( $body{$k} == '=' ) {
1258 /* It is indeed */
1259 $k++;
1260 while( !isNoSep( $body{$k} ) &&
1261 $k < $j ) {
1262 $k++;
1263 }
1264 $src = '';
1265 while ( $body{$k} <> '>' && isNoSep( $body{$k} ) &&
1266 $k < $j ) {
1267 $src .= $body{$k};
1268 $k++;
1269 }
1270 $k++;
1271 while( !isNoSep( $body{$k} ) &&
1272 $k < $j ) {
1273 $k++;
1274 }
1275 $k++;
1276 if ( strtolower( substr( $src, 0, 4 ) ) == 'cid:' ) {
1277 $src = substr( $src, 4 );
1278 $src = "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=" .
1279 urlencode( $message->header->mailbox ) .
1280 "&amp;passed_ent_id=" . find_ent_id( $src, $message );
1281 } else if ( strtolower( substr( $src, 0, 4 ) ) <> 'http' ||
1282 stristr( $src, $base_uri ) ) {
1283 /* Javascript and local urls goes out */
1284 if (!$view_unsafe_images) {
1285 $src = '../images/' . _("sec_remove_eng.png");
1286 }
1287 $has_unsafe_images = 1;
1288 }
1289 $ret .= 'src="' . $src . '" ';
1290 $i = $k - 2;
1291 } else {
1292 $ret .= 'src';
1293 $i = $i + 3;
1294 }
1295
1296 break;
1297 case '../':
1298 // Retrolinks are not allowed without a base because they mess with SM security
1299 if ( $base == '' ) {
1300 $i += 2;
1301 } else {
1302 $ret .= '.';
1303 }
1304 break;
1305 case 'cid':
1306 // Internal link
1307 $k = $i-1;
1308 if ( $body{$i+3} == ':') {
1309 $i +=4;
1310 $name = '';
1311 while ( isNoSep( $body{$i} ) &&
1312 $i < $j ) {
1313 $name .= $body{$i++};
1314 }
1315 if ( $name <> '' ) {
1316 $ret .= "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=" .
1317 urlencode( $message->header->mailbox ) .
1318 "&amp;passed_ent_id=" . find_ent_id( $name, $message );
1319 if ( $body{$k} == '"' )
1320 $ret .= '" ';
1321 else
1322 $ret .= ' ';
1323 }
1324 if ( $body{$i} == '>' )
1325 $i -= 1;
1326 }
1327 break;
1328 case ' on':
1329 case "\non":
1330 case "\ron":
1331 case "\ton":
1332 $ret .= ' no';
1333 $i += 2;
1334 break;
1335 case 'pt:':
1336 if ( strcasecmp( $body{$i-4}.$body{$i-3}.$body{$i-2}.$body{$i-1}.$body{$i}.$body{$i+1}.$body{$i+2}, 'script:') == 0 ) {
1337 $ret .= '_no/';
1338 } else {
1339 $ret .= $etg;
1340 }
1341 $i += 2;
1342 break;
1343 default:
1344 $ret .= $body{$i};
1345 }
1346 $i++;
1347 }
1348 return( $ret );
1349 }
1350
1351
1352 /* This function trys to locate the entity_id of a specific mime element */
1353
1354 function find_ent_id( $id, $message ) {
1355
1356 $ret = '';
1357 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
1358
1359 if ( $message->entities[$i]->header->entity_id == '' ) {
1360 $ret = find_ent_id( $id, $message->entities[$i] );
1361 } else {
1362 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
1363 $ret = $message->entities[$i]->header->entity_id;
1364 }
1365
1366 }
1367
1368 return( $ret );
1369
1370 }
1371 ?>