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