2a56b561f1e0ea85c4d9adf7c20572ec7a5dd6d1
[squirrelmail.git] / functions / mime.php
1 <?php
2
3 /**
4 * mime.php
5 *
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
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 */
14
15 require_once('../functions/imap.php');
16 require_once('../functions/attachment_common.php');
17
18 /** Setting up the objects that have the structure for the message **/
19 class msg_header {
20 /** msg_header contains generic variables for values that **/
21 /** could be in a header. **/
22
23 var $type0 = '', $type1 = '', $boundary = '', $charset = '',
24 $encoding = '', $size = 0, $to = array(), $from = '', $date = '',
25 $cc = array(), $bcc = array(), $reply_to = '', $subject = '',
26 $id = 0, $mailbox = '', $description = '', $filename = '',
27 $entity_id = 0, $message_id = 0, $name = '', $priority = 3, $type = '';
28 }
29
30 class message {
31 /** message is the object that contains messages. It is a recursive
32 object in that through the $entities variable, it can contain
33 more objects of type message. See documentation in mime.txt for
34 a better description of how this works.
35 **/
36 var $header = '', $entities = array();
37
38 function addEntity ($msg) {
39 $this->entities[] = $msg;
40 }
41 }
42
43 /* --------------------------------------------------------------------------------- */
44 /* MIME DECODING */
45 /* --------------------------------------------------------------------------------- */
46
47 /* This function gets the structure of a message and stores it in the "message" class.
48 * It will return this object for use with all relevant header information and
49 * fully parsed into the standard "message" object format.
50 */
51 function mime_structure ($imap_stream, $header) {
52
53 $ssid = sqimap_session_id();
54 $lsid = strlen( $ssid );
55 $id = $header->id;
56 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
57 //
58 // This should use sqimap_read_data instead of reading it itself
59 //
60 $read = fgets ($imap_stream, 9216);
61 $bodystructure = '';
62 while ( substr($read, 0, $lsid) <> $ssid &&
63 !feof( $imap_stream ) ) {
64 $bodystructure .= $read;
65 $read = fgets ($imap_stream, 9216);
66 }
67 $read = $bodystructure;
68
69 // isolate the body structure and remove beginning and end parenthesis
70 $read = trim(substr ($read, strpos(strtolower($read), 'bodystructure') + 13));
71
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 }
79
80 $msg = mime_parse_structure ($read, 0);
81 $msg->header = $header;
82
83 return( $msg );
84 }
85
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()
93 */
94 function mime_parse_structure ($structure, $ent_id) {
95 global $mailbox;
96 $properties = array();
97 $msg = new message();
98 if ($structure{0} == '(') {
99 $old_ent_id = $ent_id;
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 /* check if we are dealing with a new entity-level */
107 $i = strrpos($ent_id,'.');
108 if ($i>0) {
109 $ent = substr($ent_id, $i+1);
110 } else {
111 $ent = '';
112 }
113 /* add "forgotten" parent entities (alternative and relative) */
114 if ($ent == '0') {
115 /* new entity levels have information about the type (type1) and
116 * the properties. This information is situated at the end of the
117 * structure string like for example (example between the brackets)
118 * [ "RELATED" ("BOUNDARY" "myboundary" "TYPE" "plain/html") ]
119 */
120
121 /* get the involved properties for parsing to mime_get_properties */
122 $startprop = strrpos($structure,'(');
123 $properties_str = substr($structure,$startprop);
124 $endprop = mime_match_parenthesis ($startprop, $structure);
125 $propstr = substr($structure, $startprop + 1, ($endprop - $startprop)-1);
126 /* cut off the used properties */
127 if ($startprop) {
128 $structure_end = substr($structure, $endprop+2);
129 $structure = trim(substr($structure,0,$startprop));
130 }
131
132 /* get type1 */
133 $pos = strrpos($structure,' ');
134 $type1 = strtolower(substr($structure, $pos+2, (count($structure)-2)));
135
136 /* cut off type1 */
137 if ($pos && $startprop) {
138 $structure = trim(substr($structure, 0, $pos));
139 }
140
141 /* process the found information */
142 $properties = mime_get_props($properties, $properties_str);
143 if (count($properties)>0) {
144 $msg->header->entity_id = $old_ent_id;
145 $msg->header->type0 = 'multipart';
146 $msg->header->type1 = $type1;
147 for ($i=0; $i < count($properties); $i++) {
148 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
149 }
150 }
151 $structure = $structure . ' ' . $structure_end;
152 }
153 $element = substr($structure, $start+1, ($end - $start)-1);
154 $ent_id = mime_increment_id ($ent_id);
155 $newmsg = mime_parse_structure ($element, $ent_id);
156 /* set mailbox in case of message/rfc822 entities */
157 if (isset($newmsg->header->type0) && isset($newmsg->header->type1)) {
158 if ($newmsg->header->type0 == 'message' && $newmsg->header->type1 == 'rfc822') {
159 $newmsg->header->mailbox=$mailbox;
160 }
161 }
162 $msg->addEntity ($newmsg);
163
164 } while ($structure{$end+1} == '(');
165 } else {
166 // parse the elements
167 $msg = mime_get_element ($structure, $msg, $ent_id);
168 }
169 return $msg;
170 }
171
172
173 /* Increments the element ID. An element id can look like any of
174 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
175 * the last number of the element id, changing 1.2 to 1.3.
176 */
177 function mime_increment_id ($id) {
178
179 if (strpos($id, '.')) {
180 $first = substr($id, 0, strrpos($id, '.'));
181 $last = substr($id, strrpos($id, '.')+1);
182 $last++;
183 $new = $first . '.' .$last;
184 } else {
185 $new = $id + 1;
186 }
187
188 return $new;
189 }
190
191 /*
192 * See comment for mime_increment_id().
193 * This adds another level on to the entity_id changing 1.3 to 1.3.0
194 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
195 * before it can be used. I left it this way so as not to have
196 * to make a special case if it is the first entity_id. It
197 * always increments it, and that works fine.
198 */
199 function mime_new_element_level ($id) {
200
201 if (!$id) {
202 $id = 0;
203 } else {
204 $id = $id . '.0';
205 }
206
207 return( $id );
208 }
209
210 function mime_get_element (&$structure, $msg, $ent_id) {
211
212 $elem_num = 1;
213 $msg->header = new msg_header();
214 $msg->header->entity_id = $ent_id;
215 $properties = array();
216 while (strlen($structure) > 0) {
217 $structure = trim($structure);
218 $char = $structure{0};
219
220 if (strtolower(substr($structure, 0, 3)) == 'nil') {
221 $text = '';
222 $structure = substr($structure, 3);
223 } else if ($char == '"') {
224 // loop through until we find the matching quote, and return that as a string
225 $pos = 1;
226 $text = '';
227 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
228 $text .= $char;
229 $pos++;
230 }
231 $structure = substr($structure, strlen($text) + 2);
232 } else if ($char == '{') {
233 /**
234 * loop through until we find the matching quote,
235 * and return that as a string
236 */
237 $pos = 1;
238 $len = '';
239 while (($char = $structure{$pos}) != '}'
240 && $pos < strlen($structure)) {
241 $len .= $char;
242 $pos++;
243 }
244 $structure = substr($structure, strlen($len) + 4);
245 $text = substr($structure, 0, $len);
246 $structure = substr($structure, $len + 1);
247 } else if ($char == '(') {
248 // comment me
249 $end = mime_match_parenthesis (0, $structure);
250 $sub = substr($structure, 1, $end-1);
251 $properties = mime_get_props($properties, $sub);
252 $structure = substr($structure, strlen($sub) + 2);
253 } else {
254 // loop through until we find a space or an end parenthesis
255 $pos = 0;
256 $char = $structure{$pos};
257 $text = '';
258 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
259 $text .= $char;
260 $pos++;
261 $char = $structure{$pos};
262 }
263 $structure = substr($structure, strlen($text));
264 }
265
266 // This is where all the text parts get put into the header
267 switch ($elem_num) {
268 case 1:
269 $msg->header->type0 = strtolower($text);
270 break;
271 case 2:
272 $msg->header->type1 = strtolower($text);
273 break;
274 case 4: // Id
275 // Invisimail enclose images with <>
276 $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
277 break;
278 case 5:
279 $msg->header->description = $text;
280 break;
281 case 6:
282 $msg->header->encoding = strtolower($text);
283 break;
284 case 7:
285 $msg->header->size = $text;
286 break;
287 default:
288 if ($msg->header->type0 == 'text' && $elem_num == 8) {
289 // This is a plain text message, so lets get the number of lines
290 // that it contains.
291 $msg->header->num_lines = $text;
292
293 } else if ($msg->header->type0 == 'message' && $msg->header->type1 == 'rfc822' && $elem_num == 8) {
294 // This is an encapsulated message, so lets start all over again and
295 // parse this message adding it on to the existing one.
296 $structure = trim($structure);
297 if ( $structure{0} == '(' ) {
298 $e = mime_match_parenthesis (0, $structure);
299 $structure = substr($structure, 0, $e);
300 $structure = substr($structure, 1);
301 $m = mime_parse_structure($structure, $msg->header->entity_id);
302
303 // the following conditional is there to correct a bug that wasn't
304 // incrementing the entity IDs correctly because of the special case
305 // that message/rfc822 is. This fixes it fine.
306 if (substr($structure, 1, 1) != '(')
307 $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
308
309 // Now we'll go through and reformat the results.
310 if ($m->entities) {
311 for ($i=0; $i < count($m->entities); $i++) {
312 $msg->addEntity($m->entities[$i]);
313 }
314 } else {
315 $msg->addEntity($m);
316 }
317 $structure = "";
318 }
319 }
320 break;
321 }
322 $elem_num++;
323 $text = "";
324 }
325 // loop through the additional properties and put those in the various headers
326 for ($i=0; $i < count($properties); $i++) {
327 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
328 }
329
330 return $msg;
331 }
332
333 /*
334 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
335 * figure out how to do this part, so I decided to go to bed. I woke up
336 * in the morning and had a flash of insight. I went to the white-board
337 * and scribbled it out, then spent a bit programming it, and this is the
338 * result. Nothing complicated, but I think my brain was fried yesterday.
339 * Funny how that happens some times.
340 *
341 * This gets properties in a nested parenthesisized list. For example,
342 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
343 * This returns an array called $props with all paired up properties.
344 * It ignores the "attachment" for now, maybe that should change later
345 * down the road. In this case, what is returned is:
346 * $props[0]["name"] = "filename";
347 * $props[0]["value"] = "luke.tar.gz";
348 */
349 function mime_get_props ($props, $structure) {
350
351 while (strlen($structure) > 0) {
352 $structure = trim($structure);
353 $char = $structure{0};
354 if ($char == '"') {
355 $pos = 1;
356 $tmp = '';
357 while ( ( $char = $structure{$pos} ) != '"' &&
358 $pos < strlen($structure)) {
359 $tmp .= $char;
360 $pos++;
361 }
362 $structure = trim(substr($structure, strlen($tmp) + 2));
363 $char = $structure{0};
364
365 if ($char == '"') {
366 $pos = 1;
367 $value = '';
368 while ( ( $char = $structure{$pos} ) != '"' &&
369 $pos < strlen($structure) ) {
370 $value .= $char;
371 $pos++;
372 }
373 $structure = trim(substr($structure, strlen($value) + 2));
374 $k = count($props);
375 $props[$k]['name'] = strtolower($tmp);
376 $props[$k]['value'] = $value;
377 if ($structure != '') {
378 mime_get_props($props, $structure);
379 } else {
380 return $props;
381 }
382 } else if ($char == '(') {
383 $end = mime_match_parenthesis (0, $structure);
384 $sub = substr($structure, 1, $end-1);
385 if (! isset($props))
386 $props = array();
387 $props = mime_get_props($props, $sub);
388 $structure = substr($structure, strlen($sub) + 2);
389 return $props;
390 }
391 } else if ($char == '(') {
392 $end = mime_match_parenthesis (0, $structure);
393 $sub = substr($structure, 1, $end-1);
394 $props = mime_get_props($props, $sub);
395 $structure = substr($structure, strlen($sub) + 2);
396 return $props;
397 } else {
398 return $props;
399 }
400 }
401 }
402
403 /*
404 * Matches parenthesis. It will return the position of the matching
405 * parenthesis in $structure. For instance, if $structure was:
406 * ("text" "plain" ("val1name", "1") nil ... )
407 * x x
408 * then this would return 42 to match up those two.
409 */
410 function mime_match_parenthesis ($pos, $structure) {
411
412 $j = strlen( $structure );
413
414 // ignore all extra characters
415 // If inside of a string, skip string -- Boundary IDs and other
416 // things can have ) in them.
417 if ( $structure{$pos} != '(' ) {
418 return( $j );
419 }
420
421 while ( $pos < $j ) {
422 $pos++;
423 if ($structure{$pos} == ')') {
424 return $pos;
425 } elseif ($structure{$pos} == '"') {
426 $pos++;
427 while ( $structure{$pos} != '"' &&
428 $pos < $j ) {
429 if (substr($structure, $pos, 2) == '\\"') {
430 $pos++;
431 } elseif (substr($structure, $pos, 2) == '\\\\') {
432 $pos++;
433 }
434 $pos++;
435 }
436 } elseif ( $structure{$pos} == '(' ) {
437 $pos = mime_match_parenthesis ($pos, $structure);
438 }
439 }
440 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
441 return( $pos );
442 }
443
444 function mime_fetch_body($imap_stream, $id, $ent_id) {
445
446 /*
447 * do a bit of error correction. If we couldn't find the entity id, just guess
448 * that it is the first one. That is usually the case anyway.
449 */
450 if (!$ent_id) {
451 $ent_id = 1;
452 }
453 $cmd = "FETCH $id BODY[$ent_id]";
454
455 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
456 do {
457 $topline = trim(array_shift( $data ));
458 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
459 $wholemessage = implode('', $data);
460 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
461
462 $ret = substr( $wholemessage, 0, $regs[1] );
463 /*
464 There is some information in the content info header that could be important
465 in order to parse html messages. Let's get them here.
466 */
467 if ( $ret{0} == '<' ) {
468 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
469 /* BASE within HTML documents is illegal (see w3 spec)
470 * $base = '';
471 * $k = 10;
472 * foreach( $data as $d ) {
473 * if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
474 * $j = strlen( $d );
475 * $i = 13;
476 * $base = '';
477 * while ( $i < $j &&
478 * ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
479 * $i++;
480 * while ( $i < $j ) {
481 * if ( isNoSep( $d{$i} ) )
482 * $base .= $d{$i};
483 * $i++;
484 * }
485 * $k = 0;
486 * } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
487 * $base .= substr( $d, 1 );
488 * }
489 * $k++;
490 * }
491 * if ( $base <> '' ) {
492 * $ret = "<base href=\"$base\">" . $ret;
493 * }
494 * */
495 }
496 } else if (ereg('"([^"]*)"', $topline, $regs)) {
497 $ret = $regs[1];
498 } else {
499 global $where, $what, $mailbox, $passed_id, $startMessage;
500 $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
501 if (isset($where) && isset($what)) {
502 $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
503 } else {
504 $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
505 }
506 $par .= '&amp;response=' . urlencode($response) .
507 '&amp;message=' . urlencode($message).
508 '&amp;topline=' . urlencode($topline);
509
510 echo '<tt><br>' .
511 '<table width="80%"><tr>' .
512 '<tr><td colspan=2>' .
513 _("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!") .
514 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
515 _("Submit message") . '</A><BR>&nbsp;' .
516 '</td></tr>' .
517 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
518 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
519 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
520 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
521 "</table><BR></tt></font><hr>";
522
523 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
524 array_shift($data);
525 $wholemessage = implode('', $data);
526
527 $ret = $wholemessage;
528 }
529 return( $ret );
530 }
531
532 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
533 // do a bit of error correction. If we couldn't find the entity id, just guess
534 // that it is the first one. That is usually the case anyway.
535 if (!$ent_id) {
536 $ent_id = 1;
537 }
538 $sid = sqimap_session_id();
539 // Don't kill the connection if the browser is over a dialup
540 // and it would take over 30 seconds to download it.
541
542 // donĀ“t call set_time_limit in safe mode.
543 if (!ini_get("safe_mode")) {
544 set_time_limit(0);
545 }
546
547 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
548 $cnt = 0;
549 $continue = true;
550 $read = fgets ($imap_stream,4096);
551 // This could be bad -- if the section has sqimap_session_id() . ' OK'
552 // or similar, it will kill the download.
553 while (!ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
554 if (trim($read) == ')==') {
555 $read1 = $read;
556 $read = fgets ($imap_stream,4096);
557 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
558 return;
559 } else {
560 echo decodeBody($read1, $encoding) .
561 decodeBody($read, $encoding);
562 }
563 } else if ($cnt) {
564 echo decodeBody($read, $encoding);
565 }
566 $read = fgets ($imap_stream,4096);
567 $cnt++;
568 }
569 }
570
571 /* -[ END MIME DECODING ]----------------------------------------------------------- */
572
573
574
575 /* This is the first function called. It decides if this is a multipart
576 message or if it should be handled as a single entity
577 */
578 function decodeMime ($imap_stream, &$header) {
579 global $username, $key, $imapServerAddress, $imapPort;
580 return mime_structure ($imap_stream, $header);
581 }
582
583 // This is here for debugging purposese. It will print out a list
584 // of all the entity IDs that are in the $message object.
585
586 function listEntities ($message) {
587 if ($message) {
588 if ($message->header->entity_id)
589 echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
590 for ($i = 0; $message->entities[$i]; $i++) {
591 $msg = listEntities($message->entities[$i], $ent_id);
592 if ($msg)
593 return $msg;
594 }
595 }
596 }
597
598
599 /* returns a $message object for a particular entity id */
600 function getEntity ($message, $ent_id) {
601 if ($message) {
602 if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id))
603 {
604 return $message;
605 } else {
606 for ($i = 0; isset($message->entities[$i]); $i++) {
607 $msg = getEntity ($message->entities[$i], $ent_id);
608 if ($msg) {
609 return $msg;
610 }
611 }
612 }
613 }
614 }
615
616 /*
617 * figures out what entity to display and returns the $message object
618 * for that entity.
619 */
620 function findDisplayEntity ($msg, $textOnly = 1) {
621 global $show_html_default;
622
623 $entity = array();
624 $found = false;
625 if ($msg) {
626 $type = $msg->header->type0.'/'.$msg->header->type1;
627 if ( $type == 'multipart/alternative') {
628 $msg = findAlternativeEntity($msg);
629 if (count($msg->entities) == 0) {
630 $entity[] = $msg->header->entity_id;
631 } else {
632 $found = true;
633 $entity = findDisplayEntity($msg,$textOnly);
634 }
635 } else if ( $type == 'multipart/related') {
636 $msg = findRelatedEntity($msg);
637 if (count($msg->entities) == 0) {
638 $entity[] = $msg->header->entity_id;
639 } else {
640 $found = true;
641 $entity = findDisplayEntity($msg,$textOnly);
642 }
643 } else if ( count($entity) == 0 &&
644 $msg->header->type0 == 'text' &&
645 ( $msg->header->type1 == 'plain' ||
646 $msg->header->type1 == 'html' ) &&
647 isset($msg->header->entity_id) ) {
648 if (count($msg->entities) == 0) {
649 $entity[] = $msg->header->entity_id;
650 }
651 }
652 $i = 0;
653 while ( isset($msg->entities[$i]) && count($entity) == 0 && !$found ) {
654 $entity = findDisplayEntity($msg->entities[$i], $textOnly);
655 $i++;
656 }
657 }
658 if ( !isset($entity[0]) ) {
659 $entity[]="";
660 }
661 return( $entity );
662 }
663
664 /* Shows the HTML version */
665 function findDisplayEntityHTML ($message) {
666
667 if ( $message->header->type0 == 'text' &&
668 $message->header->type1 == 'html' &&
669 isset($message->header->entity_id)) {
670 return $message->header->entity_id;
671 }
672 for ($i = 0; isset($message->entities[$i]); $i ++) {
673 if ( $message->header->type0 == 'message' &&
674 $message->header->type1 == 'rfc822' &&
675 isset($message->header->entity_id)) {
676 return 0;
677 }
678
679 $entity = findDisplayEntityHTML($message->entities[$i]);
680 if ($entity != 0) {
681 return $entity;
682 }
683 }
684
685 return 0;
686 }
687
688 function findAlternativeEntity ($message) {
689 global $show_html_default;
690 /* if we are dealing with alternative parts then we choose the best
691 * viewable message supported by SM.
692 */
693 if ($show_html_default) {
694 $alt_order = array ('text/plain','text/html');
695 } else {
696 $alt_order = array ('text/plain');
697 }
698 $best_view = 0;
699 $k = 0;
700 for ($i = 0; $i < count($message->entities); $i ++) {
701 $type = $message->entities[$i]->header->type0.'/'.$message->entities[$i]->header->type1;
702 if ($type == 'multipart/related') {
703 $type = $message->entities[$i]->header->type;
704 }
705 for ($j = $k; $j < count($alt_order); $j++) {
706 if ($alt_order[$j] == $type && $j > $best_view) {
707 $best_view = $j;
708 $k = $j;
709 }
710 }
711 }
712 return $message->entities[$best_view];
713 }
714
715 function findRelatedEntity ($message) {
716 for ($i = 0; $i < count($message->entities); $i ++) {
717 $type = $message->entities[$i]->header->type0.'/'.$message->entities[$i]->header->type1;
718 if ($message->header->type == $type) {
719 return $message->entities[$i];
720 }
721 }
722 return $message->entities[0];
723 }
724
725 /*
726 * translateText
727 * Extracted from strings.php 23/03/2002
728 */
729
730 function translateText(&$body, $wrap_at, $charset) {
731 global $where, $what; /* from searching */
732 global $color; /* color theme */
733
734 require_once('../functions/url_parser.php');
735
736 $body_ary = explode("\n", $body);
737 $PriorQuotes = 0;
738 for ($i=0; $i < count($body_ary); $i++) {
739 $line = $body_ary[$i];
740 if (strlen($line) - 2 >= $wrap_at) {
741 sqWordWrap($line, $wrap_at);
742 }
743 $line = charset_decode($charset, $line);
744 $line = str_replace("\t", ' ', $line);
745
746 parseUrl ($line);
747
748 $Quotes = 0;
749 $pos = 0;
750 $j = strlen( $line );
751
752 while ( $pos < $j ) {
753 if ($line[$pos] == ' ') {
754 $pos ++;
755 } else if (strpos($line, '&gt;', $pos) === $pos) {
756 $pos += 4;
757 $Quotes ++;
758 } else {
759 break;
760 }
761 }
762
763 if ($Quotes > 1) {
764 if (! isset($color[14])) {
765 $color[14] = '#FF0000';
766 }
767 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
768 } elseif ($Quotes) {
769 if (! isset($color[13])) {
770 $color[13] = '#800000';
771 }
772 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
773 }
774
775 $body_ary[$i] = $line;
776 }
777 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
778 }
779
780 /* debugfunction for looping through entities and displaying correct entities */
781 function listMyEntities ($message) {
782
783 if ($message) {
784 if ($message->header->entity_id) {
785 echo "<tt>" . $message->header->entity_id . ' : ' . $message->header->type0 . '/' . $message->header->type1 . '<br>';
786 }
787 if (!($message->header->type0 == 'message' && $message->header->type1 == 'rfc822')) {
788 if (isset($message->header->boundary) ) {
789 $ent_id = $message->header->entity_id;
790 $var = $message->header->boundary;
791 if ($var !='')
792 echo "<b>$ent_id boundary = $var</b><br>";
793 }
794 if (isset($message->header->type) ) {
795 $var = $message->header->type;
796 if ($var !='')
797 echo "<b>$ent_id type = $var</b><br>";
798 }
799 for ($i = 0; $message->entities[$i]; $i++) {
800 $msg = listMyEntities($message->entities[$i]);
801 }
802
803 if ($msg ) return $msg;
804 }
805 }
806
807 }
808
809
810
811 /* This returns a parsed string called $body. That string can then
812 be displayed as the actual message in the HTML. It contains
813 everything needed, including HTML Tags, Attachments at the
814 bottom, etc.
815 */
816 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num) {
817 // this if statement checks for the entity to show as the
818 // primary message. To add more of them, just put them in the
819 // order that is their priority.
820 global $startMessage, $username, $key, $imapServerAddress, $imapPort, $body,
821 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
822
823 $has_unsafe_images = 0;
824
825 $id = $message->header->id;
826
827 $urlmailbox = urlencode($message->header->mailbox);
828
829 $body_message = getEntity($message, $ent_num);
830 if (($body_message->header->type0 == 'text') ||
831 ($body_message->header->type0 == 'rfc822')) {
832 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
833
834 $body = decodeBody($body, $body_message->header->encoding);
835 $hookResults = do_hook("message_body", $body);
836 $body = $hookResults[1];
837 // If there are other types that shouldn't be formatted, add
838 // them here
839 if ($body_message->header->type1 == 'html') {
840 if ( $show_html_default <> 1 ) {
841 $body = strip_tags( $body );
842 translateText($body, $wrap_at, $body_message->header->charset);
843 } else {
844 $body = magicHTML( $body, $id, $message );
845 }
846 } else {
847 translateText($body, $wrap_at, $body_message->header->charset);
848 }
849
850 $body .= "<CENTER><SMALL><A HREF=\"../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;passed_ent_id=$ent_num&amp;mailbox=$urlmailbox&amp;showHeaders=1\">". _("Download this as a file") ."</A></SMALL></CENTER><BR>";
851 if ($has_unsafe_images) {
852 if ($view_unsafe_images) {
853 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
854 } else {
855 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0&amp;view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
856 }
857 }
858
859 /** Display the ATTACHMENTS: message if there's more than one part **/
860 if (isset($message->entities[1])) {
861 /* Header-type alternative means we choose the best one to display
862 so don't show the alternatives as attachment. Header-type related
863 means that the attachments are already part of the related message.
864 */
865 if ($message->header->type1 !='related' && $message->header->type1 !='alternative') {
866 $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
867 }
868 }
869 } else {
870 $body = formatAttachments ($message, -1, $message->header->mailbox, $id);
871 }
872 return ($body);
873 }
874
875 /*
876 * A recursive function that returns a list of attachments with links
877 * to where to download these attachments
878 */
879 function formatAttachments($message, $ent_id, $mailbox, $id) {
880 global $where, $what;
881 global $startMessage, $color;
882 static $ShownHTML = 0;
883
884 $body = '';
885 if ($ShownHTML == 0) {
886
887 $ShownHTML = 1;
888 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
889 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
890 _("Attachments") . ':' .
891 "</B></TH></TR><TR><TD>\n" .
892 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
893 formatAttachments($message, $ent_id, $mailbox, $id) .
894 "</TABLE></TD></TR></TABLE>";
895
896 } else if ($message) {
897 $header = $message->header;
898 $type0 = strtolower($header->type0);
899 $type1 = strtolower($header->type1);
900 $name = '';
901 if (isset($header->name)) {
902 $name = decodeHeader($header->name);
903 }
904 if ($type0 =='message' && $type1 == 'rfc822') {
905
906 $filename = decodeHeader($message->header->filename);
907 if (trim($filename) == '') {
908 if (trim($name) == '') {
909 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
910 } else {
911 $display_filename = $name;
912 $filename = $name;
913 }
914 } else {
915 $display_filename = $filename;
916 }
917
918 $urlMailbox = urlencode($mailbox);
919 $ent = urlencode($message->header->entity_id);
920
921 $DefaultLink =
922 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
923 if ($where && $what) {
924 $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
925 }
926 $Links['download link']['text'] = _("download");
927 $Links['download link']['href'] =
928 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
929 $ImageURL = '';
930
931 /* this executes the attachment hook with a specific MIME-type.
932 * if that doens't have results, it tries if there's a rule
933 * for a more generic type. */
934 $HookResults = do_hook("attachment $type0/$type1", $Links,
935 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
936 if(count($HookResults[1]) <= 1) {
937 $HookResults = do_hook("attachment $type0/*", $Links,
938 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
939 $display_filename, $where, $what);
940 }
941
942 $Links = $HookResults[1];
943 $DefaultLink = $HookResults[6];
944
945 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
946 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
947 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
948 '</b>&nbsp;&nbsp;</small></TD>' .
949 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
950 '<TD><SMALL>';
951 if ($message->header->description) {
952 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
953 }
954 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
955
956
957 $SkipSpaces = 1;
958 foreach ($Links as $Val) {
959 if ($SkipSpaces) {
960 $SkipSpaces = 0;
961 } else {
962 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
963 }
964 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
965 }
966
967 unset($Links);
968
969 $body .= "</SMALL></TD></TR>\n";
970
971 return( $body );
972
973 } elseif (!$message->entities) {
974
975 $type0 = strtolower($message->header->type0);
976 $type1 = strtolower($message->header->type1);
977 $name = decodeHeader($message->header->name);
978
979 if ($message->header->entity_id != $ent_id) {
980 $filename = decodeHeader($message->header->filename);
981 if (trim($filename) == '') {
982 if (trim($name) == '') {
983 if ( trim( $message->header->id ) == '' )
984 $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
985 else
986 $display_filename = 'cid: ' . $message->header->id;
987 // $display_filename = 'untitled-[' . $message->header->entity_id . ']' ;
988 } else {
989 $display_filename = $name;
990 $filename = $name;
991 }
992 } else {
993 $display_filename = $filename;
994 }
995
996 $urlMailbox = urlencode($mailbox);
997 $ent = urlencode($message->header->entity_id);
998
999 $DefaultLink =
1000 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
1001 if ($where && $what) {
1002 $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
1003 }
1004 $Links['download link']['text'] = _("download");
1005 $Links['download link']['href'] =
1006 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
1007 $ImageURL = '';
1008
1009 /* this executes the attachment hook with a specific MIME-type.
1010 * if that doens't have results, it tries if there's a rule
1011 * for a more generic type. */
1012 $HookResults = do_hook("attachment $type0/$type1", $Links,
1013 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
1014 $display_filename, $where, $what);
1015 if(count($HookResults[1]) <= 1) {
1016 $HookResults = do_hook("attachment $type0/*", $Links,
1017 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
1018 $display_filename, $where, $what);
1019 }
1020
1021 $Links = $HookResults[1];
1022 $DefaultLink = $HookResults[6];
1023
1024 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
1025 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
1026 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
1027 '</b>&nbsp;&nbsp;</small></TD>' .
1028 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
1029 '<TD><SMALL>';
1030 if ($message->header->description) {
1031 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
1032 }
1033 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
1034
1035
1036 $SkipSpaces = 1;
1037 foreach ($Links as $Val) {
1038 if ($SkipSpaces) {
1039 $SkipSpaces = 0;
1040 } else {
1041 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
1042 }
1043 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
1044 }
1045
1046 unset($Links);
1047
1048 $body .= "</SMALL></TD></TR>\n";
1049 }
1050 } else {
1051 for ($i = 0; $i < count($message->entities); $i++) {
1052 $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
1053 }
1054 }
1055 }
1056 return( $body );
1057 }
1058
1059
1060 /** this function decodes the body depending on the encoding type. **/
1061 function decodeBody($body, $encoding) {
1062 $body = str_replace("\r\n", "\n", $body);
1063 $encoding = strtolower($encoding);
1064
1065 global $show_html_default;
1066
1067 if ($encoding == 'quoted-printable' ||
1068 $encoding == 'quoted_printable') {
1069 $body = quoted_printable_decode($body);
1070
1071
1072 while (ereg("=\n", $body))
1073 $body = ereg_replace ("=\n", "", $body);
1074
1075 } else if ($encoding == 'base64') {
1076 $body = base64_decode($body);
1077 }
1078
1079 // All other encodings are returned raw.
1080 return $body;
1081 }
1082
1083 /*
1084 * This functions decode strings that is encoded according to
1085 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
1086 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
1087 */
1088 function decodeHeader ($string, $utfencode=true) {
1089 if (is_array($string)) {
1090 $string = implode("\n", $string);
1091 }
1092 $i = 0;
1093 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
1094 $string, $res)) {
1095 $prefix = $res[1];
1096 // Ignore white-space between consecutive encoded-words
1097 if (strspn($res[2], " \t") != strlen($res[2])) {
1098 $prefix .= $res[2];
1099 }
1100
1101 if (ucfirst($res[4]) == 'B') {
1102 $replace = base64_decode($res[5]);
1103 } else {
1104 $replace = str_replace('_', ' ', $res[5]);
1105 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
1106 $replace);
1107 /* Only encode into entities by default. Some places
1108 don't need the encoding, like the compose form. */
1109 if ($utfencode) {
1110 $replace = charset_decode($res[3], $replace);
1111 }
1112 }
1113 $string = $prefix . $replace . substr($string, strlen($res[0]));
1114 $i = strlen($prefix) + strlen($replace);
1115 }
1116 return( $string );
1117 }
1118
1119 /*
1120 * Encode a string according to RFC 1522 for use in headers if it
1121 * contains 8-bit characters or anything that looks like it should
1122 * be encoded.
1123 */
1124 function encodeHeader ($string) {
1125 global $default_charset;
1126
1127 // Encode only if the string contains 8-bit characters or =?
1128 $j = strlen( $string );
1129 $l = strstr($string, '=?'); // Must be encoded ?
1130 $ret = '';
1131 for( $i=0; $i < $j; ++$i) {
1132 switch( $string{$i} ) {
1133 case '=':
1134 $ret .= '=3D';
1135 break;
1136 case '?':
1137 $ret .= '=3F';
1138 break;
1139 case '_':
1140 $ret .= '=5F';
1141 break;
1142 case ' ':
1143 $ret .= '_';
1144 break;
1145 default:
1146 $k = ord( $string{$i} );
1147 if ( $k > 126 ) {
1148 $ret .= sprintf("=%02X", $k);
1149 $l = TRUE;
1150 } else
1151 $ret .= $string{$i};
1152 }
1153 }
1154
1155 if ( $l ) {
1156 $string = "=?$default_charset?Q?$ret?=";
1157 }
1158
1159 return( $string );
1160 }
1161
1162 /* This function trys to locate the entity_id of a specific mime element */
1163
1164 function find_ent_id( $id, $message ) {
1165 $ret = '';
1166 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
1167 if (( $message->entities[$i]->header->type1 == 'alternative') ||
1168 ( $message->entities[$i]->header->type1 == 'related') ||
1169 ( $message->entities[$i]->header->type1 == 'mixed')) {
1170 $ret = find_ent_id( $id, $message->entities[$i] );
1171 } else {
1172 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
1173 $ret = $message->entities[$i]->header->entity_id;
1174 }
1175
1176 }
1177 return( $ret );
1178 }
1179
1180 /**
1181 ** HTMLFILTER ROUTINES
1182 */
1183
1184 /**
1185 * This function returns the final tag out of the tag name, an array
1186 * of attributes, and the type of the tag. This function is called by
1187 * sq_sanitize internally.
1188 *
1189 * @param $tagname the name of the tag.
1190 * @param $attary the array of attributes and their values
1191 * @param $tagtype The type of the tag (see in comments).
1192 * @return a string with the final tag representation.
1193 */
1194 function sq_tagprint($tagname, $attary, $tagtype){
1195 $me = "sq_tagprint";
1196 if ($tagtype == 2){
1197 $fulltag = '</' . $tagname . '>';
1198 } else {
1199 $fulltag = '<' . $tagname;
1200 if (is_array($attary) && sizeof($attary)){
1201 $atts = Array();
1202 while (list($attname, $attvalue) = each($attary)){
1203 array_push($atts, "$attname=$attvalue");
1204 }
1205 $fulltag .= ' ' . join(" ", $atts);
1206 }
1207 if ($tagtype == 3){
1208 $fulltag .= " /";
1209 }
1210 $fulltag .= ">";
1211 }
1212 return $fulltag;
1213 }
1214
1215 /**
1216 * A small helper function to use with array_walk. Modifies a by-ref
1217 * value and makes it lowercase.
1218 *
1219 * @param $val a value passed by-ref.
1220 * @return void since it modifies a by-ref value.
1221 */
1222 function sq_casenormalize(&$val){
1223 $val = strtolower($val);
1224 }
1225
1226 /**
1227 * This function skips any whitespace from the current position within
1228 * a string and to the next non-whitespace value.
1229 *
1230 * @param $body the string
1231 * @param $offset the offset within the string where we should start
1232 * looking for the next non-whitespace character.
1233 * @return the location within the $body where the next
1234 * non-whitespace char is located.
1235 */
1236 function sq_skipspace($body, $offset){
1237 $me = "sq_skipspace";
1238 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
1239 if (sizeof($matches{1})){
1240 $count = strlen($matches{1});
1241 $offset += $count;
1242 }
1243 return $offset;
1244 }
1245
1246 /**
1247 * This function looks for the next character within a string. It's
1248 * really just a glorified "strpos", except it catches if failures
1249 * nicely.
1250 *
1251 * @param $body The string to look for needle in.
1252 * @param $offset Start looking from this position.
1253 * @param $needle The character/string to look for.
1254 * @return location of the next occurance of the needle, or
1255 * strlen($body) if needle wasn't found.
1256 */
1257 function sq_findnxstr($body, $offset, $needle){
1258 $me = "sq_findnxstr";
1259 $pos = strpos($body, $needle, $offset);
1260 if ($pos === FALSE){
1261 $pos = strlen($body);
1262 }
1263 return $pos;
1264 }
1265
1266 /**
1267 * This function takes a PCRE-style regexp and tries to match it
1268 * within the string.
1269 *
1270 * @param $body The string to look for needle in.
1271 * @param $offset Start looking from here.
1272 * @param $reg A PCRE-style regex to match.
1273 * @return Returns a false if no matches found, or an array
1274 * with the following members:
1275 * - integer with the location of the match within $body
1276 * - string with whatever content between offset and the match
1277 * - string with whatever it is we matched
1278 */
1279 function sq_findnxreg($body, $offset, $reg){
1280 $me = "sq_findnxreg";
1281 $matches = Array();
1282 $retarr = Array();
1283 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
1284 if (!$matches{0}){
1285 $retarr = false;
1286 } else {
1287 $retarr{0} = $offset + strlen($matches{1});
1288 $retarr{1} = $matches{1};
1289 $retarr{2} = $matches{2};
1290 }
1291 return $retarr;
1292 }
1293
1294 /**
1295 * This function looks for the next tag.
1296 *
1297 * @param $body String where to look for the next tag.
1298 * @param $offset Start looking from here.
1299 * @return false if no more tags exist in the body, or
1300 * an array with the following members:
1301 * - string with the name of the tag
1302 * - array with attributes and their values
1303 * - integer with tag type (1, 2, or 3)
1304 * - integer where the tag starts (starting "<")
1305 * - integer where the tag ends (ending ">")
1306 * first three members will be false, if the tag is invalid.
1307 */
1308 function sq_getnxtag($body, $offset){
1309 $me = "sq_getnxtag";
1310 if ($offset > strlen($body)){
1311 return false;
1312 }
1313 $lt = sq_findnxstr($body, $offset, "<");
1314 if ($lt == strlen($body)){
1315 return false;
1316 }
1317 /**
1318 * We are here:
1319 * blah blah <tag attribute="value">
1320 * \---------^
1321 */
1322 $pos = sq_skipspace($body, $lt+1);
1323 if ($pos >= strlen($body)){
1324 return Array(false, false, false, $lt, strlen($body));
1325 }
1326 /**
1327 * There are 3 kinds of tags:
1328 * 1. Opening tag, e.g.:
1329 * <a href="blah">
1330 * 2. Closing tag, e.g.:
1331 * </a>
1332 * 3. XHTML-style content-less tag, e.g.:
1333 * <img src="blah"/>
1334 */
1335 $tagtype = false;
1336 switch (substr($body, $pos, 1)){
1337 case "/":
1338 $tagtype = 2;
1339 $pos++;
1340 break;
1341 case "!":
1342 /**
1343 * A comment or an SGML declaration.
1344 */
1345 if (substr($body, $pos+1, 2) == "--"){
1346 $gt = strpos($body, "-->", $pos)+2;
1347 if ($gt === false){
1348 $gt = strlen($body);
1349 }
1350 return Array(false, false, false, $lt, $gt);
1351 } else {
1352 $gt = sq_findnxstr($body, $pos, ">");
1353 return Array(false, false, false, $lt, $gt);
1354 }
1355 break;
1356 default:
1357 /**
1358 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1359 * later.
1360 */
1361 $tagtype = 1;
1362 break;
1363 }
1364
1365 $tag_start = $pos;
1366 $tagname = '';
1367 /**
1368 * Look for next [\W-_], which will indicate the end of the tag name.
1369 */
1370 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1371 if ($regary == false){
1372 return Array(false, false, false, $lt, strlen($body));
1373 }
1374 list($pos, $tagname, $match) = $regary;
1375 $tagname = strtolower($tagname);
1376
1377 /**
1378 * $match can be either of these:
1379 * '>' indicating the end of the tag entirely.
1380 * '\s' indicating the end of the tag name.
1381 * '/' indicating that this is type-3 xhtml tag.
1382 *
1383 * Whatever else we find there indicates an invalid tag.
1384 */
1385 switch ($match){
1386 case "/":
1387 /**
1388 * This is an xhtml-style tag with a closing / at the
1389 * end, like so: <img src="blah"/>. Check if it's followed
1390 * by the closing bracket. If not, then this tag is invalid
1391 */
1392 if (substr($body, $pos, 2) == "/>"){
1393 $pos++;
1394 $tagtype = 3;
1395 } else {
1396 $gt = sq_findnxstr($body, $pos, ">");
1397 $retary = Array(false, false, false, $lt, $gt);
1398 return $retary;
1399 }
1400 case ">":
1401 return Array($tagname, false, $tagtype, $lt, $pos);
1402 break;
1403 default:
1404 /**
1405 * Check if it's whitespace
1406 */
1407 if (preg_match("/\s/", $match)){
1408 } else {
1409 /**
1410 * This is an invalid tag! Look for the next closing ">".
1411 */
1412 $gt = sq_findnxstr($body, $offset, ">");
1413 return Array(false, false, false, $lt, $gt);
1414 }
1415 }
1416
1417 /**
1418 * At this point we're here:
1419 * <tagname attribute='blah'>
1420 * \-------^
1421 *
1422 * At this point we loop in order to find all attributes.
1423 */
1424 $attname = '';
1425 $atttype = false;
1426 $attary = Array();
1427
1428 while ($pos <= strlen($body)){
1429 $pos = sq_skipspace($body, $pos);
1430 if ($pos == strlen($body)){
1431 /**
1432 * Non-closed tag.
1433 */
1434 return Array(false, false, false, $lt, $pos);
1435 }
1436 /**
1437 * See if we arrived at a ">" or "/>", which means that we reached
1438 * the end of the tag.
1439 */
1440 $matches = Array();
1441 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1442 /**
1443 * Yep. So we did.
1444 */
1445 $pos += strlen($matches{1});
1446 if ($matches{2} == "/>"){
1447 $tagtype = 3;
1448 $pos++;
1449 }
1450 return Array($tagname, $attary, $tagtype, $lt, $pos);
1451 }
1452
1453 /**
1454 * There are several types of attributes, with optional
1455 * [:space:] between members.
1456 * Type 1:
1457 * attrname[:space:]=[:space:]'CDATA'
1458 * Type 2:
1459 * attrname[:space:]=[:space:]"CDATA"
1460 * Type 3:
1461 * attr[:space:]=[:space:]CDATA
1462 * Type 4:
1463 * attrname
1464 *
1465 * We leave types 1 and 2 the same, type 3 we check for
1466 * '"' and convert to "&quot" if needed, then wrap in
1467 * double quotes. Type 4 we convert into:
1468 * attrname="yes".
1469 */
1470 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1471 if ($regary == false){
1472 /**
1473 * Looks like body ended before the end of tag.
1474 */
1475 return Array(false, false, false, $lt, strlen($body));
1476 }
1477 list($pos, $attname, $match) = $regary;
1478 $attname = strtolower($attname);
1479 /**
1480 * We arrived at the end of attribute name. Several things possible
1481 * here:
1482 * '>' means the end of the tag and this is attribute type 4
1483 * '/' if followed by '>' means the same thing as above
1484 * '\s' means a lot of things -- look what it's followed by.
1485 * anything else means the attribute is invalid.
1486 */
1487 switch($match){
1488 case "/":
1489 /**
1490 * This is an xhtml-style tag with a closing / at the
1491 * end, like so: <img src="blah"/>. Check if it's followed
1492 * by the closing bracket. If not, then this tag is invalid
1493 */
1494 if (substr($body, $pos, 2) == "/>"){
1495 $pos++;
1496 $tagtype = 3;
1497 } else {
1498 $gt = sq_findnxstr($body, $pos, ">");
1499 $retary = Array(false, false, false, $lt, $gt);
1500 return $retary;
1501 }
1502 case ">":
1503 $attary{$attname} = '"yes"';
1504 return Array($tagname, $attary, $tagtype, $lt, $pos);
1505 break;
1506 default:
1507 /**
1508 * Skip whitespace and see what we arrive at.
1509 */
1510 $pos = sq_skipspace($body, $pos);
1511 $char = substr($body, $pos, 1);
1512 /**
1513 * Two things are valid here:
1514 * '=' means this is attribute type 1 2 or 3.
1515 * \w means this was attribute type 4.
1516 * anything else we ignore and re-loop. End of tag and
1517 * invalid stuff will be caught by our checks at the beginning
1518 * of the loop.
1519 */
1520 if ($char == "="){
1521 $pos++;
1522 $pos = sq_skipspace($body, $pos);
1523 /**
1524 * Here are 3 possibilities:
1525 * "'" attribute type 1
1526 * '"' attribute type 2
1527 * everything else is the content of tag type 3
1528 */
1529 $quot = substr($body, $pos, 1);
1530 if ($quot == "'"){
1531 $regary = sq_findnxreg($body, $pos+1, "\'");
1532 if ($regary == false){
1533 return Array(false, false, false, $lt, strlen($body));
1534 }
1535 list($pos, $attval, $match) = $regary;
1536 $pos++;
1537 $attary{$attname} = "'" . $attval . "'";
1538 } else if ($quot == '"'){
1539 $regary = sq_findnxreg($body, $pos+1, '\"');
1540 if ($regary == false){
1541 return Array(false, false, false, $lt, strlen($body));
1542 }
1543 list($pos, $attval, $match) = $regary;
1544 $pos++;
1545 $attary{$attname} = '"' . $attval . '"';
1546 } else {
1547 /**
1548 * These are hateful. Look for \s, or >.
1549 */
1550 $regary = sq_findnxreg($body, $pos, "[\s>]");
1551 if ($regary == false){
1552 return Array(false, false, false, $lt, strlen($body));
1553 }
1554 list($pos, $attval, $match) = $regary;
1555 /**
1556 * If it's ">" it will be caught at the top.
1557 */
1558 $attval = preg_replace("/\"/s", "&quot;", $attval);
1559 $attary{$attname} = '"' . $attval . '"';
1560 }
1561 } else if (preg_match("|[\w/>]|", $char)) {
1562 /**
1563 * That was attribute type 4.
1564 */
1565 $attary{$attname} = '"yes"';
1566 } else {
1567 /**
1568 * An illegal character. Find next '>' and return.
1569 */
1570 $gt = sq_findnxstr($body, $pos, ">");
1571 return Array(false, false, false, $lt, $gt);
1572 }
1573 }
1574 }
1575 /**
1576 * The fact that we got here indicates that the tag end was never
1577 * found. Return invalid tag indication so it gets stripped.
1578 */
1579 return Array(false, false, false, $lt, strlen($body));
1580 }
1581
1582 /**
1583 * This function checks attribute values for entity-encoded values
1584 * and returns them translated into 8-bit strings so we can run
1585 * checks on them.
1586 *
1587 * @param $attvalue A string to run entity check against.
1588 * @return Translated value.
1589 */
1590 function sq_deent($attvalue){
1591 $me="sq_deent";
1592 /**
1593 * See if we have to run the checks first. All entities must start
1594 * with "&".
1595 */
1596 if (strpos($attvalue, "&") === false){
1597 return $attvalue;
1598 }
1599 /**
1600 * Check named entities first.
1601 */
1602 $trans = get_html_translation_table(HTML_ENTITIES);
1603 /**
1604 * Leave &quot; in, as it can mess us up.
1605 */
1606 $trans = array_flip($trans);
1607 unset($trans{"&quot;"});
1608 while (list($ent, $val) = each($trans)){
1609 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1610 }
1611 /**
1612 * Now translate numbered entities from 1 to 255 if needed.
1613 */
1614 if (strpos($attvalue, "#") !== false){
1615 $omit = Array(34, 39);
1616 for ($asc=1; $asc<256; $asc++){
1617 if (!in_array($asc, $omit)){
1618 $chr = chr($asc);
1619 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1620 $attvalue);
1621 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1622 "$chr\\1", $attvalue);
1623 }
1624 }
1625 }
1626 return $attvalue;
1627 }
1628
1629 /**
1630 * This function runs various checks against the attributes.
1631 *
1632 * @param $tagname String with the name of the tag.
1633 * @param $attary Array with all tag attributes.
1634 * @param $rm_attnames See description for sq_sanitize
1635 * @param $bad_attvals See description for sq_sanitize
1636 * @param $add_attr_to_tag See description for sq_sanitize
1637 * @param $message message object
1638 * @param $id message id
1639 * @return Array with modified attributes.
1640 */
1641 function sq_fixatts($tagname,
1642 $attary,
1643 $rm_attnames,
1644 $bad_attvals,
1645 $add_attr_to_tag,
1646 $message,
1647 $id
1648 ){
1649 $me = "sq_fixatts";
1650 while (list($attname, $attvalue) = each($attary)){
1651 /**
1652 * See if this attribute should be removed.
1653 */
1654 foreach ($rm_attnames as $matchtag=>$matchattrs){
1655 if (preg_match($matchtag, $tagname)){
1656 foreach ($matchattrs as $matchattr){
1657 if (preg_match($matchattr, $attname)){
1658 unset($attary{$attname});
1659 continue;
1660 }
1661 }
1662 }
1663 }
1664 /**
1665 * Remove any entities.
1666 */
1667 $attvalue = sq_deent($attvalue);
1668
1669 /**
1670 * Now let's run checks on the attvalues.
1671 * I don't expect anyone to comprehend this. If you do,
1672 * get in touch with me so I can drive to where you live and
1673 * shake your hand personally. :)
1674 */
1675 foreach ($bad_attvals as $matchtag=>$matchattrs){
1676 if (preg_match($matchtag, $tagname)){
1677 foreach ($matchattrs as $matchattr=>$valary){
1678 if (preg_match($matchattr, $attname)){
1679 /**
1680 * There are two arrays in valary.
1681 * First is matches.
1682 * Second one is replacements
1683 */
1684 list($valmatch, $valrepl) = $valary;
1685 $newvalue =
1686 preg_replace($valmatch, $valrepl, $attvalue);
1687 if ($newvalue != $attvalue){
1688 $attary{$attname} = $newvalue;
1689 }
1690 }
1691 }
1692 }
1693 }
1694 /**
1695 * Turn cid: urls into http-friendly ones.
1696 */
1697 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1698 $attary{$attname} = sq_cid2http($message, $id, $attvalue);
1699 }
1700 }
1701 /**
1702 * See if we need to append any attributes to this tag.
1703 */
1704 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1705 if (preg_match($matchtag, $tagname)){
1706 $attary = array_merge($attary, $addattary);
1707 }
1708 }
1709 return $attary;
1710 }
1711
1712 /**
1713 * This function edits the style definition to make them friendly and
1714 * usable in squirrelmail.
1715 *
1716 * @param $message the message object
1717 * @param $id the message id
1718 * @param $content a string with whatever is between <style> and </style>
1719 * @return a string with edited content.
1720 */
1721 function sq_fixstyle($message, $id, $content){
1722 global $view_unsafe_images;
1723 $me = "sq_fixstyle";
1724 /**
1725 * First look for general BODY style declaration, which would be
1726 * like so:
1727 * body {background: blah-blah}
1728 * and change it to .bodyclass so we can just assign it to a <div>
1729 */
1730 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1731 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1732 /**
1733 * Fix url('blah') declarations.
1734 */
1735 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1736 "url(\\1$secremoveimg\\2)", $content);
1737 /**
1738 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1739 * is false.
1740 */
1741 if (!$view_unsafe_images){
1742 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1743 "url(\\1$secremoveimg\\2)", $content);
1744 }
1745
1746 /**
1747 * Fix urls that refer to cid:
1748 */
1749 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1750 $matches)){
1751 $cidurl = $matches{1};
1752 $httpurl = sq_cid2http($message, $id, $cidurl);
1753 $content = preg_replace("|url\($cidurl\)|si",
1754 "url($httpurl)", $content);
1755 }
1756
1757 /**
1758 * Fix stupid expression: declarations which lead to vulnerabilities
1759 * in IE.
1760 */
1761 $content = preg_replace("/expression\s*:/si", "idiocy:", $content);
1762 return $content;
1763 }
1764
1765 /**
1766 * This function converts cid: url's into the ones that can be viewed in
1767 * the browser.
1768 *
1769 * @param $message the message object
1770 * @param $id the message id
1771 * @param $cidurl the cid: url.
1772 * @return a string with a http-friendly url
1773 */
1774 function sq_cid2http($message, $id, $cidurl){
1775 /**
1776 * Get rid of quotes.
1777 */
1778 $quotchar = substr($cidurl, 0, 1);
1779 $cidurl = str_replace($quotchar, "", $cidurl);
1780 $cidurl = substr(trim($cidurl), 4);
1781 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
1782 "passed_id=$id&amp;mailbox=" . urlencode($message->header->mailbox) .
1783 "&amp;passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1784 return $httpurl;
1785 }
1786
1787 /**
1788 * This function changes the <body> tag into a <div> tag since we
1789 * can't really have a body-within-body.
1790 *
1791 * @param $attary an array of attributes and values of <body>
1792 * @return a modified array of attributes to be set for <div>
1793 */
1794 function sq_body2div($attary){
1795 $me = "sq_body2div";
1796 $divattary = Array("class"=>"'bodyclass'");
1797 $bgcolor="#ffffff";
1798 $text="#000000";
1799 $styledef="";
1800 if (is_array($attary) && sizeof($attary) > 0){
1801 foreach ($attary as $attname=>$attvalue){
1802 $quotchar = substr($attvalue, 0, 1);
1803 $attvalue = str_replace($quotchar, "", $attvalue);
1804 switch ($attname){
1805 case "background":
1806 $styledef .= "background-image: url('$attvalue'); ";
1807 break;
1808 case "bgcolor":
1809 $styledef .= "background-color: $attvalue; ";
1810 break;
1811 case "text":
1812 $styledef .= "color: $attvalue; ";
1813 }
1814 }
1815 if (strlen($styledef) > 0){
1816 $divattary{"style"} = "\"$styledef\"";
1817 }
1818 }
1819 return $divattary;
1820 }
1821
1822 /**
1823 * This is the main function and the one you should actually be calling.
1824 * There are several variables you should be aware of an which need
1825 * special description.
1826 *
1827 * Since the description is quite lengthy, see it here:
1828 * http://www.mricon.com/html/phpfilter.html
1829 *
1830 * @param $body the string with HTML you wish to filter
1831 * @param $tag_list see description above
1832 * @param $rm_tags_with_content see description above
1833 * @param $self_closing_tags see description above
1834 * @param $force_tag_closing see description above
1835 * @param $rm_attnames see description above
1836 * @param $bad_attvals see description above
1837 * @param $add_attr_to_tag see description above
1838 * @param $message message object
1839 * @param $id message id
1840 * @return sanitized html safe to show on your pages.
1841 */
1842 function sq_sanitize($body,
1843 $tag_list,
1844 $rm_tags_with_content,
1845 $self_closing_tags,
1846 $force_tag_closing,
1847 $rm_attnames,
1848 $bad_attvals,
1849 $add_attr_to_tag,
1850 $message,
1851 $id
1852 ){
1853 $me = "sq_sanitize";
1854 /**
1855 * Normalize rm_tags and rm_tags_with_content.
1856 */
1857 @array_walk($rm_tags, 'sq_casenormalize');
1858 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1859 @array_walk($self_closing_tags, 'sq_casenormalize');
1860 /**
1861 * See if tag_list is of tags to remove or tags to allow.
1862 * false means remove these tags
1863 * true means allow these tags
1864 */
1865 $rm_tags = array_shift($tag_list);
1866 $curpos = 0;
1867 $open_tags = Array();
1868 $trusted = "<!-- begin sanitized html -->\n";
1869 $skip_content = false;
1870
1871 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1872 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1873 $free_content = substr($body, $curpos, $lt-$curpos);
1874 /**
1875 * Take care of <style>
1876 */
1877 if ($tagname == "style" && $tagtype == 2){
1878 /**
1879 * This is a closing </style>. Edit the
1880 * content before we apply it.
1881 */
1882 $free_content = sq_fixstyle($message, $id, $free_content);
1883 }
1884 if ($skip_content == false){
1885 $trusted .= $free_content;
1886 } else {
1887 }
1888 if ($tagname != FALSE){
1889 if ($tagtype == 2){
1890 if ($skip_content == $tagname){
1891 /**
1892 * Got to the end of tag we needed to remove.
1893 */
1894 $tagname = false;
1895 $skip_content = false;
1896 } else {
1897 if ($skip_content == false){
1898 if ($tagname == "body"){
1899 $tagname = "div";
1900 } else {
1901 if (isset($open_tags{$tagname}) &&
1902 $open_tags{$tagname} > 0){
1903 $open_tags{$tagname}--;
1904 } else {
1905 $tagname = false;
1906 }
1907 }
1908 } else {
1909 }
1910 }
1911 } else {
1912 /**
1913 * $rm_tags_with_content
1914 */
1915 if ($skip_content == false){
1916 /**
1917 * See if this is a self-closing type and change
1918 * tagtype appropriately.
1919 */
1920 if ($tagtype == 1
1921 && in_array($tagname, $self_closing_tags)){
1922 $tagtype=3;
1923 }
1924 /**
1925 * See if we should skip this tag and any content
1926 * inside it.
1927 */
1928 if ($tagtype == 1 &&
1929 in_array($tagname, $rm_tags_with_content)){
1930 $skip_content = $tagname;
1931 } else {
1932 if (($rm_tags == false
1933 && in_array($tagname, $tag_list)) ||
1934 ($rm_tags == true &&
1935 !in_array($tagname, $tag_list))){
1936 $tagname = false;
1937 } else {
1938 if ($tagtype == 1){
1939 if (isset($open_tags{$tagname})){
1940 $open_tags{$tagname}++;
1941 } else {
1942 $open_tags{$tagname}=1;
1943 }
1944 }
1945 /**
1946 * This is where we run other checks.
1947 */
1948 if (is_array($attary) && sizeof($attary) > 0){
1949 $attary = sq_fixatts($tagname,
1950 $attary,
1951 $rm_attnames,
1952 $bad_attvals,
1953 $add_attr_to_tag,
1954 $message,
1955 $id
1956 );
1957 }
1958 /**
1959 * Convert body into div.
1960 */
1961 if ($tagname == "body"){
1962 $tagname = "div";
1963 $attary = sq_body2div($attary, $message, $id);
1964 }
1965 }
1966 }
1967 } else {
1968 }
1969 }
1970 if ($tagname != false && $skip_content == false){
1971 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1972 }
1973 } else {
1974 }
1975 $curpos = $gt+1;
1976 }
1977 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1978 if ($force_tag_closing == true){
1979 foreach ($open_tags as $tagname=>$opentimes){
1980 while ($opentimes > 0){
1981 $trusted .= '</' . $tagname . '>';
1982 $opentimes--;
1983 }
1984 }
1985 $trusted .= "\n";
1986 }
1987 $trusted .= "<!-- end sanitized html -->\n";
1988 return $trusted;
1989 }
1990
1991 /**
1992 * This is a wrapper function to call html sanitizing routines.
1993 *
1994 * @param $body the body of the message
1995 * @param $id the id of the message
1996 * @return a string with html safe to display in the browser.
1997 */
1998 function magicHTML($body, $id, $message){
1999 global $attachment_common_show_images, $view_unsafe_images,
2000 $has_unsafe_images;
2001 /**
2002 * Don't display attached images in HTML mode.
2003 */
2004 $attachment_common_show_images = false;
2005 $tag_list = Array(
2006 false,
2007 "object",
2008 "meta",
2009 "html",
2010 "head",
2011 "base"
2012 );
2013
2014 $rm_tags_with_content = Array(
2015 "script",
2016 "applet",
2017 "embed",
2018 "title"
2019 );
2020
2021 $self_closing_tags = Array(
2022 "img",
2023 "br",
2024 "hr",
2025 "input"
2026 );
2027
2028 $force_tag_closing = false;
2029
2030 $rm_attnames = Array(
2031 "/.*/" =>
2032 Array(
2033 "/target/si",
2034 "/^on.*/si"
2035 )
2036 );
2037
2038 $secremoveimg = "../images/" . _("sec_remove_eng.png");
2039 $bad_attvals = Array(
2040 "/.*/" =>
2041 Array(
2042 "/^src|background|href|action/i" =>
2043 Array(
2044 Array(
2045 "|^([\'\"])\s*\.\./.*([\'\"])|si",
2046 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si"
2047 ),
2048 Array(
2049 "\\1$secremoveimg\\2",
2050 "\\1$secremoveimg\\2"
2051 )
2052 ),
2053 "/^style/si" =>
2054 Array(
2055 Array(
2056 "/expression\s*:/si",
2057 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
2058 "/url\(([\'\"])\s*\S+script:.*([\'\"])\)/si"
2059 ),
2060 Array(
2061 "idiocy:",
2062 "url(\\1$secremoveimg\\2)",
2063 "url(\\1$secremoveimg\\2)"
2064 )
2065 )
2066 )
2067 );
2068 if (!$view_unsafe_images){
2069 /**
2070 * Remove any references to http/https if view_unsafe_images set
2071 * to false.
2072 */
2073 $addendum = Array(
2074 "/.*/" =>
2075 Array(
2076 "/^src|background/i" =>
2077 Array(
2078 Array(
2079 "/^([\'\"])\s*https*:.*([\'\"])/si"
2080 ),
2081 Array(
2082 "\\1$secremoveimg\\2"
2083 )
2084 ),
2085 "/^style/si" =>
2086 Array(
2087 Array(
2088 "/url\(([\'\"])\s*https*:.*([\'\"])\)/si"
2089 ),
2090 Array(
2091 "url(\\1$secremoveimg\\2)"
2092 )
2093 )
2094 )
2095 );
2096 $bad_attvals = array_merge($bad_attvals, $addendum);
2097 }
2098
2099 $add_attr_to_tag = Array(
2100 "/^a$/si" => Array('target'=>'"_new"')
2101 );
2102 $trusted = sq_sanitize($body,
2103 $tag_list,
2104 $rm_tags_with_content,
2105 $self_closing_tags,
2106 $force_tag_closing,
2107 $rm_attnames,
2108 $bad_attvals,
2109 $add_attr_to_tag,
2110 $message,
2111 $id
2112 );
2113 if (preg_match("|$secremoveimg|si", $trusted)){
2114 $has_unsafe_images = true;
2115 }
2116 return $trusted;
2117 }
2118 ?>