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