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