Removed orbz.gst-group.co.uk and added sbl.spamhaus.org
[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 ) {
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 if (!$ent_id)
377 $ent_id = 1;
ef22bc84 378 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id]", true, $response, $message);
451f74a2 379 $topline = array_shift($data);
380 while (! ereg('\\* [0-9]+ FETCH ', $topline) && $data)
a3daaaf3 381 $topline = array_shift($data);
451f74a2 382 $wholemessage = implode('', $data);
383 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
384 $ret = substr( $wholemessage, 0, $regs[1] );
385 /*
386 There is some information in the content info header that could be important
387 in order to parse html messages. Let's get them here.
388 */
389 if ( $ret{0} == '<' ) {
1c72b151 390 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
451f74a2 391 $base = '';
392 $k = 10;
393 foreach( $data as $d ) {
394 if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
395 $j = strlen( $d );
396 $i = 13;
397 $base = '';
398 while ( $i < $j &&
399 ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
400 $i++;
401 while ( $i < $j ) {
402 if ( isNoSep( $d{$i} ) )
403 $base .= $d{$i};
404 $i++;
a3daaaf3 405 }
451f74a2 406 $k = 0;
407 } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
408 $base .= substr( $d, 1 );
a3daaaf3 409 }
451f74a2 410 $k++;
a3daaaf3 411 }
451f74a2 412 if ( $base <> '' )
494424e3 413
451f74a2 414 $ret = "<base href=\"$base\">" . $ret;
415 }
416 } else if (ereg('"([^"]*)"', $topline, $regs)) {
417 $ret = $regs[1];
418 } else {
419 global $where, $what, $mailbox, $passed_id, $startMessage;
420 $par = "mailbox=".urlencode($mailbox)."&passed_id=$passed_id";
421 if (isset($where) && isset($what)) {
422 $par .= "&where=".urlencode($where)."&what=".urlencode($what);
a3daaaf3 423 } else {
451f74a2 424 $par .= "&startMessage=$startMessage&show_more=0";
425 }
426 $par .= '&response='.urlencode($response).'&message='.urlencode($message).
427 '&topline='.urlencode($topline);
a019eeb8 428
451f74a2 429 echo '<b><font color=$color[2]>' .
430 _("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!") .
431 "<A HREF=\"../src/retrievalerror.php?$par\">Submit message</A><BR>" .
432 '<tt>' . _("Response:") . "$response<BR>" .
433 _("Message:") . " $message<BR>" .
434 _("FETCH line:") . " $topline<BR></tt></font></b>";
a019eeb8 435
1c72b151 436 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
451f74a2 437 array_shift($data);
438 $wholemessage = implode('', $data);
a019eeb8 439
451f74a2 440 $ret = "---------------\n$wholemessage";
a019eeb8 441
a3daaaf3 442 }
451f74a2 443 return( $ret );
444}
d4467150 445
451f74a2 446function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
447 // do a bit of error correction. If we couldn't find the entity id, just guess
448 // that it is the first one. That is usually the case anyway.
449 if (!$ent_id) {
450 $ent_id = 1;
451 }
452 $sid = sqimap_session_id();
453 // Don't kill the connection if the browser is over a dialup
454 // and it would take over 30 seconds to download it.
b7206e1d 455
456 // donīt call set_time_limit in safe mode.
457 if (!ini_get("safe_mode")) {
458 set_time_limit(0);
459 }
451f74a2 460
461 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
462 $cnt = 0;
463 $continue = true;
464 $read = fgets ($imap_stream,4096);
465 // This could be bad -- if the section has sqimap_session_id() . ' OK'
466 // or similar, it will kill the download.
467 while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
468 if (trim($read) == ')==') {
469 $read1 = $read;
b74ba498 470 $read = fgets ($imap_stream,4096);
451f74a2 471 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
472 return;
473 } else {
474 echo decodeBody($read1, $encoding) .
475 decodeBody($read, $encoding);
476 }
477 } else if ($cnt) {
478 echo decodeBody($read, $encoding);
b74ba498 479 }
451f74a2 480 $read = fgets ($imap_stream,4096);
481 $cnt++;
482 }
483}
beb9e459 484
451f74a2 485/* -[ END MIME DECODING ]----------------------------------------------------------- */
d4467150 486
aceb0d5c 487
d4467150 488
451f74a2 489/* This is the first function called. It decides if this is a multipart
490 message or if it should be handled as a single entity
491 */
492function decodeMime ($imap_stream, &$header) {
493 global $username, $key, $imapServerAddress, $imapPort;
494 return mime_structure ($imap_stream, $header);
495}
ea48eb25 496
451f74a2 497// This is here for debugging purposese. It will print out a list
498// of all the entity IDs that are in the $message object.
499/*
500function listEntities ($message) {
501if ($message) {
502 if ($message->header->entity_id)
503 echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
504 for ($i = 0; $message->entities[$i]; $i++) {
505 $msg = listEntities($message->entities[$i], $ent_id);
506 if ($msg)
507 return $msg;
508 }
509}
510}
511*/
512
513/* returns a $message object for a particular entity id */
514function getEntity ($message, $ent_id) {
515 if ($message) {
516 if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id)) {
8beafbbc 517 return $message;
451f74a2 518 } else {
cd928157 519 for ($i = 0; isset($message->entities[$i]); $i++) {
451f74a2 520 $msg = getEntity ($message->entities[$i], $ent_id);
521 if ($msg) {
522 return $msg;
523 }
b1dadc61 524 }
451f74a2 525 }
526 }
527}
8beafbbc 528
451f74a2 529/*
530 * figures out what entity to display and returns the $message object
531 * for that entity.
532 */
533function findDisplayEntity ($message, $textOnly = 1) {
534 global $show_html_default;
535
536 $entity = 0;
537
538 if ($message) {
539 if ( $message->header->type0 == 'multipart' &&
540 ( $message->header->type1 == 'alternative' ||
541 $message->header->type1 == 'related' ) &&
542 $show_html_default && ! $textOnly ) {
543 $entity = findDisplayEntityHTML($message);
544 }
545
546 // Show text/plain or text/html -- the first one we find.
547 if ( $entity == 0 &&
548 $message->header->type0 == 'text' &&
549 ( $message->header->type1 == 'plain' ||
550 $message->header->type1 == 'html' ) &&
551 isset($message->header->entity_id) ) {
552 $entity = $message->header->entity_id;
553 }
554
555 $i = 0;
556 while ($entity == 0 && isset($message->entities[$i]) ) {
557 $entity = findDisplayEntity($message->entities[$i], $textOnly);
558 $i++;
a3daaaf3 559 }
a3daaaf3 560 }
451f74a2 561
562 return( $entity );
563}
b74ba498 564
451f74a2 565/* Shows the HTML version */
566function findDisplayEntityHTML ($message) {
8405ee35 567
451f74a2 568 if ( $message->header->type0 == 'text' &&
569 $message->header->type1 == 'html' &&
570 isset($message->header->entity_id)) {
571 return $message->header->entity_id;
572 }
573 for ($i = 0; isset($message->entities[$i]); $i ++) {
574 $entity = findDisplayEntityHTML($message->entities[$i]);
575 if ($entity != 0) {
576 return $entity;
577 }
578 }
579
580 return 0;
581}
582
583/* This returns a parsed string called $body. That string can then
584be displayed as the actual message in the HTML. It contains
585everything needed, including HTML Tags, Attachments at the
586bottom, etc.
587*/
588function formatBody($imap_stream, $message, $color, $wrap_at) {
589 // this if statement checks for the entity to show as the
590 // primary message. To add more of them, just put them in the
591 // order that is their priority.
592 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
593 $show_html_default;
594
595 $id = $message->header->id;
596 $urlmailbox = urlencode($message->header->mailbox);
597
598 // Get the right entity and redefine message to be this entity
599 // Pass the 0 to mean that we want the 'best' viewable one
600 $ent_num = findDisplayEntity ($message, 0);
601 $body_message = getEntity($message, $ent_num);
602 if (($body_message->header->type0 == 'text') ||
603 ($body_message->header->type0 == 'rfc822')) {
604
605 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
606 $body = decodeBody($body, $body_message->header->encoding);
607 $hookResults = do_hook("message_body", $body);
608 $body = $hookResults[1];
609
610 // If there are other types that shouldn't be formatted, add
611 // them here
612 if ($body_message->header->type1 == 'html') {
613 if ( $show_html_default <> 1 ) {
a3daaaf3 614 $body = strip_tags( $body );
615 translateText($body, $wrap_at, $body_message->header->charset);
616 } else {
617 $body = MagicHTML( $body, $id );
618 }
451f74a2 619 } else {
9eea179c 620 translateText($body, $wrap_at, $body_message->header->charset);
451f74a2 621 }
622
623 $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>";
624
625 /** Display the ATTACHMENTS: message if there's more than one part **/
626 $body .= "</TD></TR></TABLE>";
627 if (isset($message->entities[0])) {
628 $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
629 }
630 $body .= "</TD></TR></TABLE>";
631 } else {
632 $body = formatAttachments ($message, -1, $message->header->mailbox, $id);
633 }
634 return ($body);
635}
b74ba498 636
451f74a2 637/*
638 * A recursive function that returns a list of attachments with links
639 * to where to download these attachments
640 */
641function formatAttachments ($message, $ent_id, $mailbox, $id) {
642 global $where, $what;
643 global $startMessage, $color;
644 static $ShownHTML = 0;
645
646 $body = "";
647 if ($ShownHTML == 0) {
648 $ShownHTML = 1;
649
650 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
651 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
652 _("Attachments") . ':' .
653 "</B></TH></TR><TR><TD>\n" .
654 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
655 formatAttachments ($message, $ent_id, $mailbox, $id) .
656 "</TABLE></TD></TR></TABLE>";
657
658 return( $body );
659 }
660
661 if ($message) {
662 if (!$message->entities) {
663 $type0 = strtolower($message->header->type0);
664 $type1 = strtolower($message->header->type1);
665 $name = decodeHeader($message->header->name);
666
667 if ($message->header->entity_id != $ent_id) {
668 $filename = decodeHeader($message->header->filename);
669 if (trim($filename) == '') {
670 if (trim($name) == '') {
671 if ( trim( $message->header->id ) == '' )
672 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
673 else
674 $display_filename = 'cid: ' . $message->header->id;
675 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
676 } else {
677 $display_filename = $name;
678 $filename = $name;
679 }
680 } else {
681 $display_filename = $filename;
682 }
683
684 $urlMailbox = urlencode($mailbox);
685 $ent = urlencode($message->header->entity_id);
686
687 $DefaultLink =
688 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
689 if ($where && $what)
690 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
691 $Links['download link']['text'] = _("download");
692 $Links['download link']['href'] =
693 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
694 $ImageURL = '';
695
8196f771 696 /* this executes the attachment hook with a specific MIME-type.
697 * if that doens't have results, it tries if there's a rule
698 * for a more generic type. */
451f74a2 699 $HookResults = do_hook("attachment $type0/$type1", $Links,
700 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
701 $display_filename, $where, $what);
ae2f65a9 702 if(count($HookResults[1]) <= 1) {
703 $HookResults = do_hook("attachment $type0/*", $Links,
704 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
705 $display_filename, $where, $what);
706 }
451f74a2 707
708 $Links = $HookResults[1];
709 $DefaultLink = $HookResults[6];
710
711 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
712 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
713 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
714 '</b>&nbsp;&nbsp;</small></TD>' .
715 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
716 '<TD><SMALL>';
717 if ($message->header->description)
718 $body .= '<b>' . htmlspecialchars($message->header->description) . '</b>';
719 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
720
721
722 $SkipSpaces = 1;
723 foreach ($Links as $Val) {
724 if ($SkipSpaces) {
725 $SkipSpaces = 0;
726 } else {
727 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
728 }
729 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
730 }
b74ba498 731
451f74a2 732 unset($Links);
b74ba498 733
451f74a2 734 $body .= "</SMALL></TD></TR>\n";
735 }
736 } else {
737 for ($i = 0; $i < count($message->entities); $i++) {
738 $body .= formatAttachments ($message->entities[$i], $ent_id, $mailbox, $id);
739 }
740 }
741 return( $body );
742 }
743}
b74ba498 744
b74ba498 745
451f74a2 746/** this function decodes the body depending on the encoding type. **/
747function decodeBody($body, $encoding) {
748 $body = str_replace("\r\n", "\n", $body);
749 $encoding = strtolower($encoding);
b74ba498 750
451f74a2 751 global $show_html_default;
4809f489 752
451f74a2 753 if ($encoding == 'quoted-printable') {
754 $body = quoted_printable_decode($body);
4809f489 755
7831268e 756
451f74a2 757 while (ereg("=\n", $body))
758 $body = ereg_replace ("=\n", "", $body);
358f007e 759
451f74a2 760 } else if ($encoding == 'base64') {
761 $body = base64_decode($body);
762 }
b74ba498 763
451f74a2 764 // All other encodings are returned raw.
765 return $body;
766}
767
768/*
769 * This functions decode strings that is encoded according to
770 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
771 */
772function decodeHeader ($string, $utfencode=true) {
773 if (eregi('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
774 $string, $res)) {
0f8a1ce9 775 if (ucfirst($res[2]) == 'B') {
451f74a2 776 $replace = base64_decode($res[3]);
777 } else {
0f8a1ce9 778 $replace = str_replace('_', ' ', $res[3]);
451f74a2 779 // Convert lowercase Quoted Printable to uppercase for
780 // quoted_printable_decode to understand it.
781 while (ereg("(=(([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef])))", $replace, $res)) {
782 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
783 }
784 $replace = quoted_printable_decode($replace);
785 }
786 /* Only encode into entities by default. Some places
787 don't need the encoding, like the compose form. */
788 if ($utfencode){
789 $replace = charset_decode ($res[1], $replace);
790 }
791
792 // Remove the name of the character set.
793 $string = eregi_replace ('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
794 $replace, $string);
795
796 // In case there should be more encoding in the string: recurse
797 return (decodeHeader($string));
798 } else
799 return ($string);
800}
801
802/*
803 * Encode a string according to RFC 1522 for use in headers if it
804 * contains 8-bit characters or anything that looks like it should
805 * be encoded.
806 */
807function encodeHeader ($string) {
808 global $default_charset;
809
810 // Encode only if the string contains 8-bit characters or =?
811 $j = strlen( $string );
812 $l = strstr($string, '=?'); // Must be encoded ?
813 $ret = '';
814 for( $i=0; $i < $j; ++$i) {
f7b3ba37 815 switch( $string{$i} ) {
816 case '=':
b74ba498 817 $ret .= '=3D';
818 break;
451f74a2 819 case '?':
b74ba498 820 $ret .= '=3F';
821 break;
451f74a2 822 case '_':
b74ba498 823 $ret .= '=5F';
824 break;
451f74a2 825 case ' ':
b74ba498 826 $ret .= '_';
827 break;
451f74a2 828 default:
b74ba498 829 $k = ord( $string{$i} );
451f74a2 830 if ( $k > 126 ) {
b74ba498 831 $ret .= sprintf("=%02X", $k);
832 $l = TRUE;
833 } else
834 $ret .= $string{$i};
f7b3ba37 835 }
451f74a2 836 }
837
838 if ( $l ) {
f7b3ba37 839 $string = "=?$default_charset?Q?$ret?=";
451f74a2 840 }
841
842 return( $string );
843}
b74ba498 844
451f74a2 845/*
a3daaaf3 846 Strips dangerous tags from html messages.
451f74a2 847*/
848function MagicHTML( $body, $id ) {
849
43fdb2a4 850 global $message, $HTTP_SERVER_VARS,
5106a9be 851 $attachment_common_show_images;
451f74a2 852
5106a9be 853 $attachment_common_show_images =
854 FALSE; // Don't display attached images in HTML mode
451f74a2 855 $j = strlen( $body ); // Legnth of the HTML
856 $ret = ''; // Returned string
857 $bgcolor = '#ffffff'; // Background style color (defaults to white)
858 $textcolor = '#000000'; // Foreground style color (defaults to black)
859 $leftmargin = ''; // Left margin style
860 $title = ''; // HTML title if any
861
862 $i = 0;
863 while ( $i < $j ) {
864 if ( $body{$i} == '<' ) {
865 $pos = $i + 1;
866 $tag = '';
867 while ($body{$pos} == ' ' || $body{$pos} == "\t" ||
868 $body{$pos} == "\n") {
869 $pos ++;
870 }
871 while (strlen($tag) < 4 && $body{$pos} != ' ' &&
872 $body{$pos} != "\t" && $body{$pos} != "\n") {
873 $tag .= $body{$pos};
874 $pos ++;
875 }
876 switch( strtoupper( $tag ) ) {
877 // Strips the entire tag and contents
878 case 'APPL':
879 case 'EMBB':
880 case 'FRAM':
881 case 'SCRI':
882 case 'OBJE':
883 $etg = '/' . $tag;
884 while ( $body{$i+1}.$body{$i+2}.$body{$i+3}.$body{$i+4}.$body{$i+5} <> $etg &&
885 $i < $j ) $i++;
886 while ( $i < $j && $body{++$i} <> '>' );
887 // $ret .= "<!-- $tag removed -->";
888 break;
889 // Substitute Title
890 case 'TITL':
891 $i += 5;
892 while ( $body{$i} <> '>' && // </title>
893 $i < $j )
a3daaaf3 894 $i++;
451f74a2 895 $i++;
896 $title = '';
897 while ( $body{$i} <> '<' && // </title>
898 $i < $j ) {
899 $title .= $body{$i};
900 $i++;
901 }
902 $i += 7;
903 break;
904 // Destroy these tags
905 case 'HTML':
906 case 'HEAD':
907 case '/HTM':
908 case '/HEA':
909 case '!DOC':
910 case 'META':
911 case 'DIV ':
912 case '/DIV':
913 case '!-- ':
914 $i += 4;
915 while ( $body{$i} <> '>' &&
916 $i < $j )
917 $i++;
918 // $i++;
919 break;
920 case 'STYL':
921 $i += 5;
922 while ( $body{$i} <> '>' && // </title>
923 $i < $j )
924 $i++;
925 $i++;
926 // We parse the style to look for interesting stuff
927 $styleblk = '';
928 while ( $body{$i} <> '>' &&
929 $i < $j ) {
930 // First we get the name of the style
931 $style = '';
932 while ( $body{$i} <> '>' &&
933 $body{$i} <> '<' &&
934 $body{$i} <> '{' &&
935 $i < $j ) {
936 if ( isnoSep( $body{$i} ) )
937 $style .= $body{$i};
938 $i++;
939 }
940 stripComments( $i, $j, $body );
941 $style = strtoupper( trim( $style ) );
942 if ( $style == 'BODY' ) {
943 // Next we look into the definitions of the body style
944 while ( $body{$i} <> '>' &&
945 $body{$i} <> '}' &&
a3daaaf3 946 $i < $j ) {
451f74a2 947 // We look for the background color if any.
948 if ( substr( $body, $i, 17 ) == 'BACKGROUND-COLOR:' ) {
949 $i += 17;
950 $bgcolor = getStyleData( $i, $j, $body );
951 } elseif ( substr( $body, $i, 12 ) == 'MARGIN-LEFT:' ) {
952 $i += 12;
953 $leftmargin = getStyleData( $i, $j, $body );
954 }
a3daaaf3 955 $i++;
956 }
451f74a2 957 } else {
958 // Other style are mantained
959 $styleblk .= "$style ";
960 while ( $body{$i} <> '>' &&
961 $body{$i} <> '<' &&
962 $body{$i} <> '}' &&
963 $i < $j ) {
964 $styleblk .= $body{$i};
a3daaaf3 965 $i++;
451f74a2 966 }
967 $styleblk .= $body{$i};
968 }
969 stripComments( $i, $j, $body );
970 if ( $body{$i} <> '>' )
971 $i++;
972 }
973 if ( $styleblk <> '' )
974 $ret .= "<style>$styleblk";
975 break;
976 case 'BODY':
977 if ( $title <> '' )
978 $ret .= '<b>' . _("Title:") . " </b>$title<br>\n";
979 $ret .= "<TABLE";
980 $i += 5;
981 if (! isset($base)) {
982 $base = '';
983 }
984 $ret .= stripEvent( $i, $j, $body, $id, $base );
985 $ret .= " bgcolor=$bgcolor width=\"100%\"><tr>";
986 if ( $leftmargin <> '' )
987 $ret .= "<td width=$leftmargin>&nbsp;</td>";
988 $ret .= '<td>';
989 if (strtolower($bgcolor) == 'ffffff' ||
990 strtolower($bgcolor) == '#ffffff')
991 $ret .= '<font color=#000000>';
992 break;
993 case 'BASE':
994 $i += 5;
995 $base = '';
996 while ( !isNoSep( $body{$i} ) &&
997 $i < $j ) {
998 $i++;
999 }
1000 if ( strcasecmp( substr( $base, 0, 4 ), 'href' ) ) {
a3daaaf3 1001 $i += 5;
451f74a2 1002 while ( !isNoSep( $body{$i} ) &&
1003 $i < $j ) {
a3daaaf3 1004 $i++;
451f74a2 1005 }
1006 while ( $body{$i} <> '>' &&
a3daaaf3 1007 $i < $j ) {
451f74a2 1008 if ( $body{$i} <> '"' ) {
1009 $base .= $body{$i};
a3daaaf3 1010 }
451f74a2 1011 $i++;
a3daaaf3 1012 }
451f74a2 1013 // Debuging $ret .= "<!-- base == $base -->";
1014 if ( strcasecmp( substr( $base, 0, 4 ), 'file' ) <> 0 ) {
1015 $ret .= "\n<BASE HREF=\"$base\">\n";
a3daaaf3 1016 }
a3daaaf3 1017 }
451f74a2 1018 break;
1019 case '/BOD':
1020 $ret .= '</font></td></tr></TABLE>';
1021 $i += 6;
a3daaaf3 1022 break;
1023 default:
451f74a2 1024 // Following tags can contain some event handler, lets search it
1025 stripComments( $i, $j, $body );
1026 if (! isset($base)) {
1027 $base = '';
1028 }
1029 $ret .= stripEvent( $i, $j, $body, $id, $base ) . '>';
1030 // $ret .= "<!-- $tag detected -->";
1031 }
1032 } else {
1033 $ret .= $body{$i};
a3daaaf3 1034 }
451f74a2 1035 $i++;
1036 }
a3daaaf3 1037
451f74a2 1038return( "\n\n<!-- HTML Output ahead -->\n" .
1039 $ret .
1040 "\n<!-- END of HTML Output --><base href=\"".
494424e3 1041 get_location() . '/'.
451f74a2 1042 "\">\n\n" );
1043}
a3daaaf3 1044
451f74a2 1045function isNoSep( $char ) {
1046
1047 switch( $char ) {
1048 case ' ':
1049 case "\n":
1050 case "\t":
1051 case "\r":
1052 case '>':
1053 case '"':
1054 return( FALSE );
1055 break;
1056 default:
1057 return( TRUE );
1058 }
a3daaaf3 1059
451f74a2 1060}
a3daaaf3 1061
451f74a2 1062/*
1063 The following function is usefull to remove extra data that can cause
1064 html not to display properly. Especialy with MS stuff.
1065*/
1066
1067function stripComments( &$i, $j, &$body ) {
1068
1069 while ( $body{$i}.$body{$i+1}.$body{$i+2}.$body{$i+3} == '<!--' &&
1070 $i < $j ) {
1071 $i += 5;
1072 while ( $body{$i-2}.$body{$i-1}.$body{$i} <> '-->' &&
1073 $i < $j )
a3daaaf3 1074 $i++;
451f74a2 1075 $i++;
1076 }
a3daaaf3 1077
451f74a2 1078 return;
a3daaaf3 1079
451f74a2 1080}
a3daaaf3 1081
451f74a2 1082/* Gets the style data of a specific style */
a3daaaf3 1083
451f74a2 1084function getStyleData( &$i, $j, &$body ) {
a3daaaf3 1085
451f74a2 1086 // We skip spaces
1087 while ( $body{$i} <> '>' && !isNoSep( $body{$i} ) &&
1088 $i < $j ) {
1089 $i++;
1090 }
1091 // And get the color
1092 $ret = '';
1093 while ( isNoSep( $body{$i} ) &&
1094 $i < $j ) {
1095 $ret .= $body{$i};
1096 $i++;
1097 }
a3daaaf3 1098
451f74a2 1099 return( $ret );
1100}
a3daaaf3 1101
451f74a2 1102/*
1103Private function for strip_dangerous_tag. Look for event based coded and "remove" it
1104change on with no (onload -> noload)
1105*/
a3daaaf3 1106
451f74a2 1107function stripEvent( &$i, $j, &$body, $id, $base ) {
a3daaaf3 1108
451f74a2 1109 global $message, $base_uri;
a3daaaf3 1110
451f74a2 1111 $ret = '';
a3daaaf3 1112
451f74a2 1113 while ( $body{$i} <> '>' &&
1114 $i < $j ) {
1115 $etg = strtolower($body{$i}.$body{$i+1}.$body{$i+2});
1116 switch( $etg ) {
1117 case 'src':
1118 // This is probably a src specification
1119 $k = $i + 3;
1120 while( !isNoSep( $body{$k} )) {
1121 $k++;
1122 }
1123 if ( $body{$k} == '=' ) {
1124 /* It is indeed */
1125 $k++;
1126 while( !isNoSep( $body{$k} ) &&
1127 $k < $j ) {
1128 $k++;
1129 }
1130 $src = '';
1131 while ( $body{$k} <> '>' && isNoSep( $body{$k} ) &&
1132 $k < $j ) {
1133 $src .= $body{$k};
1134 $k++;
1135 }
1136 while( !isNoSep( $body{$k} ) &&
1137 $k < $j ) {
1138 $k++;
1139 }
1140 if ( strtolower( substr( $src, 0, 4 ) ) == 'cid:' ) {
1141 $src = substr( $src, 4 );
1142 $src = "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1143 urlencode( $message->header->mailbox ) .
1144 "&passed_ent_id=" . find_ent_id( $src, $message );
1145 } else if ( strtolower( substr( $src, 0, 4 ) ) <> 'http' ||
1146 stristr( $src, $base_uri ) ) {
1147 /* Javascript and local urls goes out */
1148 $src = '../images/' . _("sec_remove_eng.png");
1149 }
1150 $ret .= 'src="' . $src . '" ';
a2b54c4a 1151 $i = $k - 3;
451f74a2 1152 } else {
1153 $ret .= 'src';
1154 $i = $i + 3;
1155 }
1156
1157 break;
1158 case '../':
1159 // Retrolinks are not allowed without a base because they mess with SM security
1160 if ( $base == '' ) {
a3daaaf3 1161 $i += 2;
451f74a2 1162 } else {
1163 $ret .= '.';
a3daaaf3 1164 }
451f74a2 1165 break;
1166 case 'cid':
1167 // Internal link
1168 $k = $i-1;
1169 if ( $body{$i+3} == ':') {
1170 $i +=4;
1171 $name = '';
1172 while ( isNoSep( $body{$i} ) &&
1173 $i < $j ) {
1174 $name .= $body{$i++};
1175 }
1176 if ( $name <> '' ) {
1177 $ret .= "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1178 urlencode( $message->header->mailbox ) .
1179 "&passed_ent_id=" . find_ent_id( $name, $message );
1180 if ( $body{$k} == '"' )
1181 $ret .= '" ';
1182 else
1183 $ret .= ' ';
1184 }
1185 if ( $body{$i} == '>' )
1186 $i -= 1;
1187 }
1188 break;
1189 case ' on':
1190 case "\non":
1191 case "\ron":
1192 case "\ton":
1193 $ret .= ' no';
1194 $i += 2;
1195 break;
1196 case 'pt:':
1197 if ( strcasecmp( $body{$i-4}.$body{$i-3}.$body{$i-2}.$body{$i-1}.$body{$i}.$body{$i+1}.$body{$i+2}, 'script:') == 0 ) {
1198 $ret .= '_no/';
1199 } else {
1200 $ret .= $etg;
1201 }
1202 $i += 2;
1203 break;
1204 default:
1205 $ret .= $body{$i};
a3daaaf3 1206 }
451f74a2 1207 $i++;
a3daaaf3 1208 }
451f74a2 1209 return( $ret );
1210}
a3daaaf3 1211
1212
451f74a2 1213/* This function trys to locate the entity_id of a specific mime element */
a3daaaf3 1214
451f74a2 1215function find_ent_id( $id, $message ) {
a3daaaf3 1216
451f74a2 1217 $ret = '';
1218 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
a3daaaf3 1219
451f74a2 1220 if ( $message->entities[$i]->header->entity_id == '' ) {
1221 $ret = find_ent_id( $id, $message->entities[$i] );
1222 } else {
1223 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
1224 $ret = $message->entities[$i]->header->entity_id;
a3daaaf3 1225 }
1226
a3daaaf3 1227 }
451f74a2 1228
1229 return( $ret );
1230
1231}
1c72b151 1232?>