Bug-Fix
[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
35586184 23 var $type0 = '', $type1 = '', $boundary = '', $charset = '';
24 var $encoding = '', $size = 0, $to = array(), $from = '', $date = '';
25 var $cc = array(), $bcc = array(), $reply_to = '', $subject = '';
26 var $id = 0, $mailbox = '', $description = '', $filename = '';
27 var $entity_id = 0, $message_id = 0, $name = '';
28 // var $priority = "";
29}
b74ba498 30
451f74a2 31class message {
32 /** message is the object that contains messages. It is a recursive
33 object in that through the $entities variable, it can contain
34 more objects of type message. See documentation in mime.txt for
35 a better description of how this works.
36 **/
37 var $header = '';
38 var $entities = array();
39
40 function addEntity ($msg) {
41 $this->entities[] = $msg;
42 }
43}
8beafbbc 44
451f74a2 45/* --------------------------------------------------------------------------------- */
46/* MIME DECODING */
47/* --------------------------------------------------------------------------------- */
b74ba498 48
451f74a2 49/* This function gets the structure of a message and stores it in the "message" class.
50 * It will return this object for use with all relevant header information and
51 * fully parsed into the standard "message" object format.
52 */
53function mime_structure ($imap_stream, $header) {
54
55 sqimap_messages_flag ($imap_stream, $header->id, $header->id, 'Seen');
56 $ssid = sqimap_session_id();
57 $lsid = strlen( $ssid );
58 $id = $header->id;
59 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
60 //
61 // This should use sqimap_read_data instead of reading it itself
62 //
63 $read = fgets ($imap_stream, 10000);
64 $bodystructure = '';
65 while ( substr($read, 0, $lsid) <> $ssid &&
66 !feof( $imap_stream ) ) {
67 $bodystructure .= $read;
68 $read = fgets ($imap_stream, 10000);
69 }
70 $read = $bodystructure;
71
72 // isolate the body structure and remove beginning and end parenthesis
73 $read = trim(substr ($read, strpos(strtolower($read), 'bodystructure') + 13));
74 $read = trim(substr ($read, 0, -1));
75 $end = mime_match_parenthesis(0, $read);
76 while ($end == strlen($read)-1) {
77 $read = trim(substr ($read, 0, -1));
78 $read = trim(substr ($read, 1));
79 $end = mime_match_parenthesis(0, $read);
80 }
81
82 $msg = mime_parse_structure ($read, 0);
83 $msg->header = $header;
84
85 return( $msg );
86}
b74ba498 87
451f74a2 88/* this starts the parsing of a particular structure. It is called recursively,
89 * so it can be passed different structures. It returns an object of type
90 * $message.
91 * First, it checks to see if it is a multipart message. If it is, then it
92 * handles that as it sees is necessary. If it is just a regular entity,
93 * then it parses it and adds the necessary header information (by calling out
94 * to mime_get_elements()
95 */
96function mime_parse_structure ($structure, $ent_id) {
97
98 $msg = new message();
99 if ($structure{0} == '(') {
100 $ent_id = mime_new_element_level($ent_id);
101 $start = $end = -1;
102 do {
103 $start = $end+1;
104 $end = mime_match_parenthesis ($start, $structure);
105
106 $element = substr($structure, $start+1, ($end - $start)-1);
107 $ent_id = mime_increment_id ($ent_id);
108 $newmsg = mime_parse_structure ($element, $ent_id);
109 $msg->addEntity ($newmsg);
110 } while ($structure{$end+1} == '(');
111 } else {
112 // parse the elements
113 $msg = mime_get_element ($structure, $msg, $ent_id);
114 }
115 return $msg;
116}
e4a256af 117
451f74a2 118/* Increments the element ID. An element id can look like any of
119 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
120 * the last number of the element id, changing 1.2 to 1.3.
121 */
122function mime_increment_id ($id) {
123
124 if (strpos($id, ".")) {
125 $first = substr($id, 0, strrpos($id, "."));
126 $last = substr($id, strrpos($id, ".")+1);
127 $last++;
128 $new = $first . "." .$last;
129 } else {
130 $new = $id + 1;
131 }
132
133 return $new;
134}
135
136/*
137 * See comment for mime_increment_id().
138 * This adds another level on to the entity_id changing 1.3 to 1.3.0
139 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
140 * before it can be used. I left it this way so as not to have
141 * to make a special case if it is the first entity_id. It
142 * always increments it, and that works fine.
143 */
144function mime_new_element_level ($id) {
145
146 if (!$id) {
147 $id = 0;
148 } else {
149 $id = $id . '.0';
150 }
151
152 return( $id );
153}
154
155function mime_get_element (&$structure, $msg, $ent_id) {
156
157 $elem_num = 1;
158 $msg->header = new msg_header();
159 $msg->header->entity_id = $ent_id;
160 $properties = array();
161
162 while (strlen($structure) > 0) {
163 $structure = trim($structure);
164 $char = $structure{0};
165
166 if (strtolower(substr($structure, 0, 3)) == 'nil') {
167 $text = '';
168 $structure = substr($structure, 3);
169 } else if ($char == '"') {
170 // loop through until we find the matching quote, and return that as a string
171 $pos = 1;
172 $text = '';
173 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
174 $text .= $char;
175 $pos++;
176 }
177 $structure = substr($structure, strlen($text) + 2);
178 } else if ($char == '(') {
179 // comment me
180 $end = mime_match_parenthesis (0, $structure);
181 $sub = substr($structure, 1, $end-1);
182 $properties = mime_get_props($properties, $sub);
183 $structure = substr($structure, strlen($sub) + 2);
184 } else {
185 // loop through until we find a space or an end parenthesis
186 $pos = 0;
187 $char = $structure{$pos};
188 $text = '';
189 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
190 $text .= $char;
191 $pos++;
192 $char = $structure{$pos};
193 }
194 $structure = substr($structure, strlen($text));
195 }
196
197 // This is where all the text parts get put into the header
198 switch ($elem_num) {
199 case 1:
200 $msg->header->type0 = strtolower($text);
201 break;
202 case 2:
203 $msg->header->type1 = strtolower($text);
204 break;
205 case 4: // Id
206 // Invisimail enclose images with <>
207 $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
208 break;
209 case 5:
210 $msg->header->description = $text;
211 break;
212 case 6:
213 $msg->header->encoding = strtolower($text);
214 break;
215 case 7:
216 $msg->header->size = $text;
217 break;
218 default:
219 if ($msg->header->type0 == 'text' && $elem_num == 8) {
220 // This is a plain text message, so lets get the number of lines
221 // that it contains.
222 $msg->header->num_lines = $text;
223
224 } else if ($msg->header->type0 == 'message' && $msg->header->type1 == 'rfc822' && $elem_num == 8) {
225 // This is an encapsulated message, so lets start all over again and
226 // parse this message adding it on to the existing one.
227 $structure = trim($structure);
228 if ( $structure{0} == '(' ) {
229 $e = mime_match_parenthesis (0, $structure);
230 $structure = substr($structure, 0, $e);
231 $structure = substr($structure, 1);
232 $m = mime_parse_structure($structure, $msg->header->entity_id);
233
234 // the following conditional is there to correct a bug that wasn't
235 // incrementing the entity IDs correctly because of the special case
236 // that message/rfc822 is. This fixes it fine.
237 if (substr($structure, 1, 1) != '(')
238 $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
239
240 // Now we'll go through and reformat the results.
241 if ($m->entities) {
242 for ($i=0; $i < count($m->entities); $i++) {
243 $msg->addEntity($m->entities[$i]);
244 }
245 } else {
246 $msg->addEntity($m);
247 }
248 $structure = "";
249 }
250 }
251 break;
252 }
253 $elem_num++;
254 $text = "";
255 }
256 // loop through the additional properties and put those in the various headers
257 if ($msg->header->type0 != 'message') {
258 for ($i=0; $i < count($properties); $i++) {
259 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
260 }
261 }
262
263 return $msg;
264}
265
266/*
267 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
268 * figure out how to do this part, so I decided to go to bed. I woke up
269 * in the morning and had a flash of insight. I went to the white-board
270 * and scribbled it out, then spent a bit programming it, and this is the
271 * result. Nothing complicated, but I think my brain was fried yesterday.
272 * Funny how that happens some times.
273 *
274 * This gets properties in a nested parenthesisized list. For example,
275 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
276 * This returns an array called $props with all paired up properties.
277 * It ignores the "attachment" for now, maybe that should change later
278 * down the road. In this case, what is returned is:
279 * $props[0]["name"] = "filename";
280 * $props[0]["value"] = "luke.tar.gz";
281 */
282function mime_get_props ($props, $structure) {
283
284 while (strlen($structure) > 0) {
285 $structure = trim($structure);
286 $char = $structure{0};
287
288 if ($char == '"') {
289 $pos = 1;
290 $tmp = '';
291 while ( ( $char = $structure{$pos} ) != '"' &&
292 $pos < strlen($structure)) {
293 $tmp .= $char;
294 $pos++;
295 }
296 $structure = trim(substr($structure, strlen($tmp) + 2));
297 $char = $structure{0};
298
299 if ($char == '"') {
300 $pos = 1;
301 $value = '';
302 while ( ( $char = $structure{$pos} ) != '"' &&
303 $pos < strlen($structure) ) {
304 $value .= $char;
305 $pos++;
306 }
307 $structure = trim(substr($structure, strlen($tmp) + 2));
308
309 $k = count($props);
310 $props[$k]['name'] = strtolower($tmp);
311 $props[$k]['value'] = $value;
312 } else if ($char == '(') {
313 $end = mime_match_parenthesis (0, $structure);
314 $sub = substr($structure, 1, $end-1);
315 if (! isset($props))
316 $props = array();
317 $props = mime_get_props($props, $sub);
318 $structure = substr($structure, strlen($sub) + 2);
319 }
320 return $props;
321 } else if ($char == '(') {
322 $end = mime_match_parenthesis (0, $structure);
323 $sub = substr($structure, 1, $end-1);
324 $props = mime_get_props($props, $sub);
325 $structure = substr($structure, strlen($sub) + 2);
326 return $props;
327 } else {
328 return $props;
329 }
330 }
331}
332
333/*
334 * Matches parenthesis. It will return the position of the matching
335 * parenthesis in $structure. For instance, if $structure was:
336 * ("text" "plain" ("val1name", "1") nil ... )
337 * x x
338 * then this would return 42 to match up those two.
339 */
340function mime_match_parenthesis ($pos, $structure) {
341
342 $j = strlen( $structure );
343
344 // ignore all extra characters
345 // If inside of a string, skip string -- Boundary IDs and other
346 // things can have ) in them.
347 if ( $structure{$pos} != '(' ) {
348 return( $j );
349 }
350
351 while ( $pos < $j ) {
352 $pos++;
353 if ($structure{$pos} == ')') {
8beafbbc 354 return $pos;
451f74a2 355 } elseif ($structure{$pos} == '"') {
b74ba498 356 $pos++;
451f74a2 357 while ( $structure{$pos} != '"' &&
358 $pos < $j ) {
359 if (substr($structure, $pos, 2) == '\\"') {
b74ba498 360 $pos++;
451f74a2 361 } elseif (substr($structure, $pos, 2) == '\\\\') {
b74ba498 362 $pos++;
451f74a2 363 }
b74ba498 364 $pos++;
5ffe5a7e 365 }
451f74a2 366 } elseif ( $structure{$pos} == '(' ) {
8beafbbc 367 $pos = mime_match_parenthesis ($pos, $structure);
451f74a2 368 }
369 }
370 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
371 return( $pos );
372}
373
374function mime_fetch_body ($imap_stream, $id, $ent_id ) {
375 // do a bit of error correction. If we couldn't find the entity id, just guess
376 // that it is the first one. That is usually the case anyway.
377 if (!$ent_id)
378 $ent_id = 1;
379 $sid = sqimap_session_id();
380 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
381 $data = sqimap_read_data ($imap_stream, $sid, true, $response, $message);
382 $topline = array_shift($data);
383 while (! ereg('\\* [0-9]+ FETCH ', $topline) && $data)
a3daaaf3 384 $topline = array_shift($data);
451f74a2 385 $wholemessage = implode('', $data);
386 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
387 $ret = substr( $wholemessage, 0, $regs[1] );
388 /*
389 There is some information in the content info header that could be important
390 in order to parse html messages. Let's get them here.
391 */
392 if ( $ret{0} == '<' ) {
393 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id.MIME]\r\n");
394 $data = sqimap_read_data ($imap_stream, $sid, true, $response, $message);
395 $base = '';
396 $k = 10;
397 foreach( $data as $d ) {
398 if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
399 $j = strlen( $d );
400 $i = 13;
401 $base = '';
402 while ( $i < $j &&
403 ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
404 $i++;
405 while ( $i < $j ) {
406 if ( isNoSep( $d{$i} ) )
407 $base .= $d{$i};
408 $i++;
a3daaaf3 409 }
451f74a2 410 $k = 0;
411 } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
412 $base .= substr( $d, 1 );
a3daaaf3 413 }
451f74a2 414 $k++;
a3daaaf3 415 }
451f74a2 416 if ( $base <> '' )
417 $ret = "<base href=\"$base\">" . $ret;
418 }
419 } else if (ereg('"([^"]*)"', $topline, $regs)) {
420 $ret = $regs[1];
421 } else {
422 global $where, $what, $mailbox, $passed_id, $startMessage;
423 $par = "mailbox=".urlencode($mailbox)."&passed_id=$passed_id";
424 if (isset($where) && isset($what)) {
425 $par .= "&where=".urlencode($where)."&what=".urlencode($what);
a3daaaf3 426 } else {
451f74a2 427 $par .= "&startMessage=$startMessage&show_more=0";
428 }
429 $par .= '&response='.urlencode($response).'&message='.urlencode($message).
430 '&topline='.urlencode($topline);
a019eeb8 431
451f74a2 432 echo '<b><font color=$color[2]>' .
433 _("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!") .
434 "<A HREF=\"../src/retrievalerror.php?$par\">Submit message</A><BR>" .
435 '<tt>' . _("Response:") . "$response<BR>" .
436 _("Message:") . " $message<BR>" .
437 _("FETCH line:") . " $topline<BR></tt></font></b>";
a019eeb8 438
451f74a2 439 fputs ($imap_stream, "$sid FETCH $passed_id BODY[]\r\n");
440 $data = sqimap_read_data ($imap_stream, $sid, true, $response, $message);
441 array_shift($data);
442 $wholemessage = implode('', $data);
a019eeb8 443
451f74a2 444 $ret = "---------------\n$wholemessage";
a019eeb8 445
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.
459 set_time_limit(0);
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
696 $HookResults = do_hook("attachment $type0/$type1", $Links,
697 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
698 $display_filename, $where, $what);
699
700 $Links = $HookResults[1];
701 $DefaultLink = $HookResults[6];
702
703 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
704 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
705 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
706 '</b>&nbsp;&nbsp;</small></TD>' .
707 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
708 '<TD><SMALL>';
709 if ($message->header->description)
710 $body .= '<b>' . htmlspecialchars($message->header->description) . '</b>';
711 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
712
713
714 $SkipSpaces = 1;
715 foreach ($Links as $Val) {
716 if ($SkipSpaces) {
717 $SkipSpaces = 0;
718 } else {
719 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
720 }
721 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
722 }
b74ba498 723
451f74a2 724 unset($Links);
b74ba498 725
451f74a2 726 $body .= "</SMALL></TD></TR>\n";
727 }
728 } else {
729 for ($i = 0; $i < count($message->entities); $i++) {
730 $body .= formatAttachments ($message->entities[$i], $ent_id, $mailbox, $id);
731 }
732 }
733 return( $body );
734 }
735}
b74ba498 736
b74ba498 737
451f74a2 738/** this function decodes the body depending on the encoding type. **/
739function decodeBody($body, $encoding) {
740 $body = str_replace("\r\n", "\n", $body);
741 $encoding = strtolower($encoding);
b74ba498 742
451f74a2 743 global $show_html_default;
4809f489 744
451f74a2 745 if ($encoding == 'quoted-printable') {
746 $body = quoted_printable_decode($body);
4809f489 747
7831268e 748
451f74a2 749 while (ereg("=\n", $body))
750 $body = ereg_replace ("=\n", "", $body);
358f007e 751
451f74a2 752 } else if ($encoding == 'base64') {
753 $body = base64_decode($body);
754 }
b74ba498 755
451f74a2 756 // All other encodings are returned raw.
757 return $body;
758}
759
760/*
761 * This functions decode strings that is encoded according to
762 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
763 */
764function decodeHeader ($string, $utfencode=true) {
765 if (eregi('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
766 $string, $res)) {
767 if (ucfirst($res[2]) == "B") {
768 $replace = base64_decode($res[3]);
769 } else {
770 $replace = ereg_replace("_", " ", $res[3]);
771 // Convert lowercase Quoted Printable to uppercase for
772 // quoted_printable_decode to understand it.
773 while (ereg("(=(([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef])))", $replace, $res)) {
774 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
775 }
776 $replace = quoted_printable_decode($replace);
777 }
778 /* Only encode into entities by default. Some places
779 don't need the encoding, like the compose form. */
780 if ($utfencode){
781 $replace = charset_decode ($res[1], $replace);
782 }
783
784 // Remove the name of the character set.
785 $string = eregi_replace ('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
786 $replace, $string);
787
788 // In case there should be more encoding in the string: recurse
789 return (decodeHeader($string));
790 } else
791 return ($string);
792}
793
794/*
795 * Encode a string according to RFC 1522 for use in headers if it
796 * contains 8-bit characters or anything that looks like it should
797 * be encoded.
798 */
799function encodeHeader ($string) {
800 global $default_charset;
801
802 // Encode only if the string contains 8-bit characters or =?
803 $j = strlen( $string );
804 $l = strstr($string, '=?'); // Must be encoded ?
805 $ret = '';
806 for( $i=0; $i < $j; ++$i) {
f7b3ba37 807 switch( $string{$i} ) {
808 case '=':
b74ba498 809 $ret .= '=3D';
810 break;
451f74a2 811 case '?':
b74ba498 812 $ret .= '=3F';
813 break;
451f74a2 814 case '_':
b74ba498 815 $ret .= '=5F';
816 break;
451f74a2 817 case ' ':
b74ba498 818 $ret .= '_';
819 break;
451f74a2 820 default:
b74ba498 821 $k = ord( $string{$i} );
451f74a2 822 if ( $k > 126 ) {
b74ba498 823 $ret .= sprintf("=%02X", $k);
824 $l = TRUE;
825 } else
826 $ret .= $string{$i};
f7b3ba37 827 }
451f74a2 828 }
829
830 if ( $l ) {
f7b3ba37 831 $string = "=?$default_charset?Q?$ret?=";
451f74a2 832 }
833
834 return( $string );
835}
b74ba498 836
451f74a2 837/*
a3daaaf3 838 Strips dangerous tags from html messages.
451f74a2 839*/
840function MagicHTML( $body, $id ) {
841
842 global $message, $PHP_SELF, $HTTP_SERVER_VARS;
843
844 $j = strlen( $body ); // Legnth of the HTML
845 $ret = ''; // Returned string
846 $bgcolor = '#ffffff'; // Background style color (defaults to white)
847 $textcolor = '#000000'; // Foreground style color (defaults to black)
848 $leftmargin = ''; // Left margin style
849 $title = ''; // HTML title if any
850
851 $i = 0;
852 while ( $i < $j ) {
853 if ( $body{$i} == '<' ) {
854 $pos = $i + 1;
855 $tag = '';
856 while ($body{$pos} == ' ' || $body{$pos} == "\t" ||
857 $body{$pos} == "\n") {
858 $pos ++;
859 }
860 while (strlen($tag) < 4 && $body{$pos} != ' ' &&
861 $body{$pos} != "\t" && $body{$pos} != "\n") {
862 $tag .= $body{$pos};
863 $pos ++;
864 }
865 switch( strtoupper( $tag ) ) {
866 // Strips the entire tag and contents
867 case 'APPL':
868 case 'EMBB':
869 case 'FRAM':
870 case 'SCRI':
871 case 'OBJE':
872 $etg = '/' . $tag;
873 while ( $body{$i+1}.$body{$i+2}.$body{$i+3}.$body{$i+4}.$body{$i+5} <> $etg &&
874 $i < $j ) $i++;
875 while ( $i < $j && $body{++$i} <> '>' );
876 // $ret .= "<!-- $tag removed -->";
877 break;
878 // Substitute Title
879 case 'TITL':
880 $i += 5;
881 while ( $body{$i} <> '>' && // </title>
882 $i < $j )
a3daaaf3 883 $i++;
451f74a2 884 $i++;
885 $title = '';
886 while ( $body{$i} <> '<' && // </title>
887 $i < $j ) {
888 $title .= $body{$i};
889 $i++;
890 }
891 $i += 7;
892 break;
893 // Destroy these tags
894 case 'HTML':
895 case 'HEAD':
896 case '/HTM':
897 case '/HEA':
898 case '!DOC':
899 case 'META':
900 case 'DIV ':
901 case '/DIV':
902 case '!-- ':
903 $i += 4;
904 while ( $body{$i} <> '>' &&
905 $i < $j )
906 $i++;
907 // $i++;
908 break;
909 case 'STYL':
910 $i += 5;
911 while ( $body{$i} <> '>' && // </title>
912 $i < $j )
913 $i++;
914 $i++;
915 // We parse the style to look for interesting stuff
916 $styleblk = '';
917 while ( $body{$i} <> '>' &&
918 $i < $j ) {
919 // First we get the name of the style
920 $style = '';
921 while ( $body{$i} <> '>' &&
922 $body{$i} <> '<' &&
923 $body{$i} <> '{' &&
924 $i < $j ) {
925 if ( isnoSep( $body{$i} ) )
926 $style .= $body{$i};
927 $i++;
928 }
929 stripComments( $i, $j, $body );
930 $style = strtoupper( trim( $style ) );
931 if ( $style == 'BODY' ) {
932 // Next we look into the definitions of the body style
933 while ( $body{$i} <> '>' &&
934 $body{$i} <> '}' &&
a3daaaf3 935 $i < $j ) {
451f74a2 936 // We look for the background color if any.
937 if ( substr( $body, $i, 17 ) == 'BACKGROUND-COLOR:' ) {
938 $i += 17;
939 $bgcolor = getStyleData( $i, $j, $body );
940 } elseif ( substr( $body, $i, 12 ) == 'MARGIN-LEFT:' ) {
941 $i += 12;
942 $leftmargin = getStyleData( $i, $j, $body );
943 }
a3daaaf3 944 $i++;
945 }
451f74a2 946 } else {
947 // Other style are mantained
948 $styleblk .= "$style ";
949 while ( $body{$i} <> '>' &&
950 $body{$i} <> '<' &&
951 $body{$i} <> '}' &&
952 $i < $j ) {
953 $styleblk .= $body{$i};
a3daaaf3 954 $i++;
451f74a2 955 }
956 $styleblk .= $body{$i};
957 }
958 stripComments( $i, $j, $body );
959 if ( $body{$i} <> '>' )
960 $i++;
961 }
962 if ( $styleblk <> '' )
963 $ret .= "<style>$styleblk";
964 break;
965 case 'BODY':
966 if ( $title <> '' )
967 $ret .= '<b>' . _("Title:") . " </b>$title<br>\n";
968 $ret .= "<TABLE";
969 $i += 5;
970 if (! isset($base)) {
971 $base = '';
972 }
973 $ret .= stripEvent( $i, $j, $body, $id, $base );
974 $ret .= " bgcolor=$bgcolor width=\"100%\"><tr>";
975 if ( $leftmargin <> '' )
976 $ret .= "<td width=$leftmargin>&nbsp;</td>";
977 $ret .= '<td>';
978 if (strtolower($bgcolor) == 'ffffff' ||
979 strtolower($bgcolor) == '#ffffff')
980 $ret .= '<font color=#000000>';
981 break;
982 case 'BASE':
983 $i += 5;
984 $base = '';
985 while ( !isNoSep( $body{$i} ) &&
986 $i < $j ) {
987 $i++;
988 }
989 if ( strcasecmp( substr( $base, 0, 4 ), 'href' ) ) {
a3daaaf3 990 $i += 5;
451f74a2 991 while ( !isNoSep( $body{$i} ) &&
992 $i < $j ) {
a3daaaf3 993 $i++;
451f74a2 994 }
995 while ( $body{$i} <> '>' &&
a3daaaf3 996 $i < $j ) {
451f74a2 997 if ( $body{$i} <> '"' ) {
998 $base .= $body{$i};
a3daaaf3 999 }
451f74a2 1000 $i++;
a3daaaf3 1001 }
451f74a2 1002 // Debuging $ret .= "<!-- base == $base -->";
1003 if ( strcasecmp( substr( $base, 0, 4 ), 'file' ) <> 0 ) {
1004 $ret .= "\n<BASE HREF=\"$base\">\n";
a3daaaf3 1005 }
a3daaaf3 1006 }
451f74a2 1007 break;
1008 case '/BOD':
1009 $ret .= '</font></td></tr></TABLE>';
1010 $i += 6;
a3daaaf3 1011 break;
1012 default:
451f74a2 1013 // Following tags can contain some event handler, lets search it
1014 stripComments( $i, $j, $body );
1015 if (! isset($base)) {
1016 $base = '';
1017 }
1018 $ret .= stripEvent( $i, $j, $body, $id, $base ) . '>';
1019 // $ret .= "<!-- $tag detected -->";
1020 }
1021 } else {
1022 $ret .= $body{$i};
a3daaaf3 1023 }
451f74a2 1024 $i++;
1025 }
a3daaaf3 1026
451f74a2 1027return( "\n\n<!-- HTML Output ahead -->\n" .
1028 $ret .
1029 "\n<!-- END of HTML Output --><base href=\"".
1030 $HTTP_SERVER_VARS["SERVER_NAME"] . substr( $PHP_SELF, 0, strlen( $PHP_SELF ) - 13 ) .
1031 "\">\n\n" );
1032}
a3daaaf3 1033
451f74a2 1034function isNoSep( $char ) {
1035
1036 switch( $char ) {
1037 case ' ':
1038 case "\n":
1039 case "\t":
1040 case "\r":
1041 case '>':
1042 case '"':
1043 return( FALSE );
1044 break;
1045 default:
1046 return( TRUE );
1047 }
a3daaaf3 1048
451f74a2 1049}
a3daaaf3 1050
451f74a2 1051/*
1052 The following function is usefull to remove extra data that can cause
1053 html not to display properly. Especialy with MS stuff.
1054*/
1055
1056function stripComments( &$i, $j, &$body ) {
1057
1058 while ( $body{$i}.$body{$i+1}.$body{$i+2}.$body{$i+3} == '<!--' &&
1059 $i < $j ) {
1060 $i += 5;
1061 while ( $body{$i-2}.$body{$i-1}.$body{$i} <> '-->' &&
1062 $i < $j )
a3daaaf3 1063 $i++;
451f74a2 1064 $i++;
1065 }
a3daaaf3 1066
451f74a2 1067 return;
a3daaaf3 1068
451f74a2 1069}
a3daaaf3 1070
451f74a2 1071/* Gets the style data of a specific style */
a3daaaf3 1072
451f74a2 1073function getStyleData( &$i, $j, &$body ) {
a3daaaf3 1074
451f74a2 1075 // We skip spaces
1076 while ( $body{$i} <> '>' && !isNoSep( $body{$i} ) &&
1077 $i < $j ) {
1078 $i++;
1079 }
1080 // And get the color
1081 $ret = '';
1082 while ( isNoSep( $body{$i} ) &&
1083 $i < $j ) {
1084 $ret .= $body{$i};
1085 $i++;
1086 }
a3daaaf3 1087
451f74a2 1088 return( $ret );
1089}
a3daaaf3 1090
451f74a2 1091/*
1092Private function for strip_dangerous_tag. Look for event based coded and "remove" it
1093change on with no (onload -> noload)
1094*/
a3daaaf3 1095
451f74a2 1096function stripEvent( &$i, $j, &$body, $id, $base ) {
a3daaaf3 1097
451f74a2 1098 global $message, $base_uri;
a3daaaf3 1099
451f74a2 1100 $ret = '';
a3daaaf3 1101
451f74a2 1102 while ( $body{$i} <> '>' &&
1103 $i < $j ) {
1104 $etg = strtolower($body{$i}.$body{$i+1}.$body{$i+2});
1105 switch( $etg ) {
1106 case 'src':
1107 // This is probably a src specification
1108 $k = $i + 3;
1109 while( !isNoSep( $body{$k} )) {
1110 $k++;
1111 }
1112 if ( $body{$k} == '=' ) {
1113 /* It is indeed */
1114 $k++;
1115 while( !isNoSep( $body{$k} ) &&
1116 $k < $j ) {
1117 $k++;
1118 }
1119 $src = '';
1120 while ( $body{$k} <> '>' && isNoSep( $body{$k} ) &&
1121 $k < $j ) {
1122 $src .= $body{$k};
1123 $k++;
1124 }
1125 while( !isNoSep( $body{$k} ) &&
1126 $k < $j ) {
1127 $k++;
1128 }
1129 if ( strtolower( substr( $src, 0, 4 ) ) == 'cid:' ) {
1130 $src = substr( $src, 4 );
1131 $src = "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1132 urlencode( $message->header->mailbox ) .
1133 "&passed_ent_id=" . find_ent_id( $src, $message );
1134 } else if ( strtolower( substr( $src, 0, 4 ) ) <> 'http' ||
1135 stristr( $src, $base_uri ) ) {
1136 /* Javascript and local urls goes out */
1137 $src = '../images/' . _("sec_remove_eng.png");
1138 }
1139 $ret .= 'src="' . $src . '" ';
a2b54c4a 1140 $i = $k - 3;
451f74a2 1141 } else {
1142 $ret .= 'src';
1143 $i = $i + 3;
1144 }
1145
1146 break;
1147 case '../':
1148 // Retrolinks are not allowed without a base because they mess with SM security
1149 if ( $base == '' ) {
a3daaaf3 1150 $i += 2;
451f74a2 1151 } else {
1152 $ret .= '.';
a3daaaf3 1153 }
451f74a2 1154 break;
1155 case 'cid':
1156 // Internal link
1157 $k = $i-1;
1158 if ( $body{$i+3} == ':') {
1159 $i +=4;
1160 $name = '';
1161 while ( isNoSep( $body{$i} ) &&
1162 $i < $j ) {
1163 $name .= $body{$i++};
1164 }
1165 if ( $name <> '' ) {
1166 $ret .= "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=" .
1167 urlencode( $message->header->mailbox ) .
1168 "&passed_ent_id=" . find_ent_id( $name, $message );
1169 if ( $body{$k} == '"' )
1170 $ret .= '" ';
1171 else
1172 $ret .= ' ';
1173 }
1174 if ( $body{$i} == '>' )
1175 $i -= 1;
1176 }
1177 break;
1178 case ' on':
1179 case "\non":
1180 case "\ron":
1181 case "\ton":
1182 $ret .= ' no';
1183 $i += 2;
1184 break;
1185 case 'pt:':
1186 if ( strcasecmp( $body{$i-4}.$body{$i-3}.$body{$i-2}.$body{$i-1}.$body{$i}.$body{$i+1}.$body{$i+2}, 'script:') == 0 ) {
1187 $ret .= '_no/';
1188 } else {
1189 $ret .= $etg;
1190 }
1191 $i += 2;
1192 break;
1193 default:
1194 $ret .= $body{$i};
a3daaaf3 1195 }
451f74a2 1196 $i++;
a3daaaf3 1197 }
451f74a2 1198 return( $ret );
1199}
a3daaaf3 1200
1201
451f74a2 1202/* This function trys to locate the entity_id of a specific mime element */
a3daaaf3 1203
451f74a2 1204function find_ent_id( $id, $message ) {
a3daaaf3 1205
451f74a2 1206 $ret = '';
1207 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
a3daaaf3 1208
451f74a2 1209 if ( $message->entities[$i]->header->entity_id == '' ) {
1210 $ret = find_ent_id( $id, $message->entities[$i] );
1211 } else {
1212 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
1213 $ret = $message->entities[$i]->header->entity_id;
a3daaaf3 1214 }
1215
a3daaaf3 1216 }
451f74a2 1217
1218 return( $ret );
1219
1220}
1221?>