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