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