896933fede17db0bb1d943d42568a37498d8670d
[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 /* --------------------------------------------------------------------------------- */
19 /* MIME DECODING */
20 /* --------------------------------------------------------------------------------- */
21
22 /* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
25 */
26
27 function mime_structure ($bodystructure, $flags=array()) {
28
29 // isolate the body structure and remove beginning and end parenthesis
30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
31 $msg = &new message();
32 $read = trim(substr ($read, 0, -1));
33 $res = $msg->parseStructure($read);
34 $msg = $res[0];
35 $msg->setEnt('0');
36 if (count($flags)) {
37 foreach ($flags as $flag) {
38 $char = strtoupper($flag{1});
39 switch ($char) {
40 case 'S':
41 if (strtolower($flag) == '\\seen') {
42 $msg->is_seen = true;
43 }
44 break;
45 case 'A':
46 if (strtolower($flag) == '\\answered') {
47 $msg->is_answered = true;
48 }
49 break;
50 case 'D':
51 if (strtolower($flag) == '\\deleted') {
52 $msg->is_deleted = true;
53 }
54 break;
55 case 'F':
56 if (strtolower($flag) == '\\flagged') {
57 $msg->is_flagged = true;
58 }
59 break;
60 case 'M':
61 if (strtolower($flag) == '$mdnsent') {
62 $msg->is_mdnsent = true;
63 }
64 break;
65 default:
66 break;
67 }
68 }
69 }
70 // listEntities($msg);
71 return( $msg );
72 }
73
74 /* this starts the parsing of a particular structure. It is called recursively,
75 * so it can be passed different structures. It returns an object of type
76 * $message.
77 * First, it checks to see if it is a multipart message. If it is, then it
78 * handles that as it sees is necessary. If it is just a regular entity,
79 * then it parses it and adds the necessary header information (by calling out
80 * to mime_get_elements()
81 */
82
83 function mime_fetch_body($imap_stream, $id, $ent_id) {
84 global $uid_support;
85 /*
86 * do a bit of error correction. If we couldn't find the entity id, just guess
87 * that it is the first one. That is usually the case anyway.
88 */
89 if (!$ent_id) {
90 $ent_id = 1;
91 }
92 $cmd = "FETCH $id BODY[$ent_id]";
93
94 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
95 do {
96 $topline = trim(array_shift( $data ));
97 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
98
99 $wholemessage = implode('', $data);
100 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
101
102 $ret = substr( $wholemessage, 0, $regs[1] );
103 /*
104 There is some information in the content info header that could be important
105 in order to parse html messages. Let's get them here.
106 */
107 if ( $ret{0} == '<' ) {
108 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
109 }
110 } else if (ereg('"([^"]*)"', $topline, $regs)) {
111 $ret = $regs[1];
112 } else {
113 global $where, $what, $mailbox, $passed_id, $startMessage;
114 $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
115 if (isset($where) && isset($what)) {
116 $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
117 } else {
118 $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
119 }
120 $par .= '&amp;response=' . urlencode($response) .
121 '&amp;message=' . urlencode($message).
122 '&amp;topline=' . urlencode($topline);
123
124 echo '<tt><br>' .
125 '<table width="80%"><tr>' .
126 '<tr><td colspan=2>' .
127 _("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!") .
128 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
129 _("Submit message") . '</A><BR>&nbsp;' .
130 '</td></tr>' .
131 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
132 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
133 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
134 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
135 "</table><BR></tt></font><hr>";
136
137 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
138 array_shift($data);
139 $wholemessage = implode('', $data);
140
141 $ret = $wholemessage;
142 }
143 return( $ret );
144 }
145
146 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
147 global $uid_support;
148 // do a bit of error correction. If we couldn't find the entity id, just guess
149 // that it is the first one. That is usually the case anyway.
150 if (!$ent_id) {
151 $ent_id = 1;
152 }
153 $sid = sqimap_session_id($uid_support);
154 // Don't kill the connection if the browser is over a dialup
155 // and it would take over 30 seconds to download it.
156
157 // donĀ“t call set_time_limit in safe mode.
158 if (!ini_get("safe_mode")) {
159 set_time_limit(0);
160 }
161 if ($uid_support) {
162 $sid_s = substr($sid,0,strpos($sid, ' '));
163 } else {
164 $sid_s = $sid;
165 }
166
167 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
168 echo decodeBody($body, $encoding);
169 return;
170 /*
171 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
172 $cnt = 0;
173 $continue = true;
174 $read = fgets ($imap_stream,8192);
175
176
177 // This could be bad -- if the section has sqimap_session_id() . ' OK'
178 // or similar, it will kill the download.
179 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
180 if (trim($read) == ')==') {
181 $read1 = $read;
182 $read = fgets ($imap_stream,4096);
183 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
184 return;
185 } else {
186 echo decodeBody($read1, $encoding) .
187 decodeBody($read, $encoding);
188 }
189 } else if ($cnt) {
190 echo decodeBody($read, $encoding);
191 }
192 $read = fgets ($imap_stream,4096);
193 $cnt++;
194 // break;
195 }
196 */
197 }
198
199 /* -[ END MIME DECODING ]----------------------------------------------------------- */
200
201 /* findDisplayEntity
202 * Checks to see if $message contains content of type $type0/$type1
203 * returns the first entity number it finds of that type, or NULL if
204 * none is found. Takes optional argument $start to allow the caller
205 * to continue where they left off
206 */
207 function findDisplayEntity($message, $type0, $type1, $start=0) {
208 if ($message) {
209 for ($i = $start;isset($message->entities[$i]); $i++) {
210 $entity = $message->entities[$i];
211 if ($entity->type0 == $type0 && $entity->type1 == $type1) {
212 return $i;
213 }
214 }
215 }
216 return NULL;
217 }
218
219 // This is here for debugging purposese. It will print out a list
220 // of all the entity IDs that are in the $message object.
221
222 function listEntities ($message) {
223 if ($message) {
224 echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
225 for ($i = 0;isset($message->entities[$i]); $i++) {
226 echo "$i : ";
227 $msg = listEntities($message->entities[$i]);
228
229 if ($msg) {
230 echo "return: ";
231 return $msg;
232 }
233 }
234 }
235 }
236
237 function getPriorityStr($priority) {
238 $priority_level = substr($priority,0,1);
239
240 switch($priority_level) {
241 /* check for a higher then normal priority. */
242 case '1':
243 case '2':
244 $priority_string = _("High");
245 break;
246
247 /* check for a lower then normal priority. */
248 case '4':
249 case '5':
250 $priority_string = _("Low");
251 break;
252
253 /* check for a normal priority. */
254 case '3':
255 default:
256 $priority_level = '3';
257 $priority_string = _("Normal");
258 break;
259
260 }
261 return $priority_string;
262 }
263
264 /* returns a $message object for a particular entity id */
265 function getEntity ($message, $ent_id) {
266 return $message->getEntity($ent_id);
267 }
268
269 /*
270 * translateText
271 * Extracted from strings.php 23/03/2002
272 */
273
274 function translateText(&$body, $wrap_at, $charset) {
275 global $where, $what; /* from searching */
276 global $color; /* color theme */
277
278 require_once('../functions/url_parser.php');
279
280 $body_ary = explode("\n", $body);
281 $PriorQuotes = 0;
282 for ($i=0; $i < count($body_ary); $i++) {
283 $line = $body_ary[$i];
284 if (strlen($line) - 2 >= $wrap_at) {
285 sqWordWrap($line, $wrap_at);
286 }
287 $line = charset_decode($charset, $line);
288 $line = str_replace("\t", ' ', $line);
289
290 parseUrl ($line);
291
292 $Quotes = 0;
293 $pos = 0;
294 $j = strlen( $line );
295
296 while ( $pos < $j ) {
297 if ($line[$pos] == ' ') {
298 $pos ++;
299 } else if (strpos($line, '&gt;', $pos) === $pos) {
300 $pos += 4;
301 $Quotes ++;
302 } else {
303 break;
304 }
305 }
306
307 if ($Quotes > 1) {
308 if (! isset($color[14])) {
309 $color[14] = '#FF0000';
310 }
311 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
312 } elseif ($Quotes) {
313 if (! isset($color[13])) {
314 $color[13] = '#800000';
315 }
316 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
317 }
318
319 $body_ary[$i] = $line;
320 }
321 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
322 }
323
324
325 /* This returns a parsed string called $body. That string can then
326 be displayed as the actual message in the HTML. It contains
327 everything needed, including HTML Tags, Attachments at the
328 bottom, etc.
329 */
330 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
331 // this if statement checks for the entity to show as the
332 // primary message. To add more of them, just put them in the
333 // order that is their priority.
334 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
335 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
336
337 $has_unsafe_images= 0;
338 $body = '';
339 $urlmailbox = urlencode($mailbox);
340 $body_message = getEntity($message, $ent_num);
341 if (($body_message->header->type0 == 'text') ||
342 ($body_message->header->type0 == 'rfc822')) {
343 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
344 $body = decodeBody($body, $body_message->header->encoding);
345 $hookResults = do_hook("message_body", $body);
346 $body = $hookResults[1];
347
348 // If there are other types that shouldn't be formatted, add
349 // them here
350 if ($body_message->header->type1 == 'html') {
351 if ( $show_html_default <> 1 ) {
352 $entity_conv = array('&nbsp;' => ' ',
353 '&gt;' => '>',
354 '&lt;' => '<');
355 $body = strip_tags( $body );
356 $body = strtr($body, $entity_conv);
357 $body = trim($body);
358 translateText($body, $wrap_at,
359 $body_message->header->getParameter['charset']);
360 } else {
361 $body = magicHTML( $body, $id, $message, $mailbox );
362 }
363 } else {
364 translateText($body, $wrap_at,
365 $body_message->header->getParameter('charset'));
366 }
367
368 if ($has_unsafe_images) {
369 if ($view_unsafe_images) {
370 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;passed_ent_id=".$message->entity_id."&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
371 } else {
372 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;passed_ent_id=".$message->entity_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";
373 }
374 }
375 }
376 return ($body);
377 }
378
379
380 function formatAttachments($message, $exclude_id, $mailbox, $id) {
381 global $where, $what;
382 global $startMessage, $color;
383 static $ShownHTML = 0;
384
385 $att_ar = $message->getAttachments($exclude_id);
386
387 if (!count($att_ar)) return '';
388
389 $attachments = '';
390
391 $urlMailbox = urlencode($mailbox);
392
393 foreach ($att_ar as $att) {
394 $ent = urldecode($att->entity_id);
395 $header = $att->header;
396 $type0 = strtolower($header->type0);
397 $type1 = strtolower($header->type1);
398 $name = '';
399 $Links['download link']['text'] = _("download");
400 $Links['download link']['href'] =
401 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
402 $ImageURL = '';
403 if ($type0 =='message' && $type1 == 'rfc822') {
404 $default_page = '../src/read_body.php';
405 $rfc822_header = $att->rfc822_header;
406 $filename = decodeHeader($rfc822_header->subject);
407
408 $from_o = $rfc822_header->from;
409 if (is_object($from_o)) {
410 $from_name = $from_o->getAddress(false);
411 } else {
412 $from_name = _("Unknown sender");
413 }
414 $from_name = decodeHeader(htmlspecialchars($from_name));
415 $description = $from_name;
416 } else {
417 $default_page = '../src/download.php';
418 if (is_object($header->disposition)) {
419 $filename = decodeHeader($header->disposition->getProperty('filename'));
420 if (trim($filename) == '') {
421 $name = decodeHeader($header->disposition->getProperty('name'));
422 if (trim($name) == '') {
423 if ( trim( $header->id ) == '' )
424 $filename = 'untitled-[' . $ent . ']' ;
425 else
426 $filename = 'cid: ' . $header->id;
427 } else {
428 $filename = $name;
429 }
430 }
431 } else {
432 if ( trim( $header->id ) == '' )
433 $filename = 'untitled-[' . $ent . ']' ;
434 else
435 $filename = 'cid: ' . $header->id;
436 }
437
438 if ($header->description) {
439 $description = htmlspecialchars($header->description);
440 } else {
441 $description = '';
442 }
443 }
444
445 $display_filename = $filename;
446 if (isset($passed_ent_id)) {
447 $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
448 } else {
449 $passed_ent_id_link = '';
450 }
451 $DefaultLink = $default_page . "?startMessage=$startMessage"
452 . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
453 . '&amp;ent_id='.$ent.$passed_ent_id_link;
454 if ($where && $what) {
455 $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
456 }
457 /* this executes the attachment hook with a specific MIME-type.
458 * if that doens't have results, it tries if there's a rule
459 * for a more generic type. */
460 $HookResults = do_hook("attachment $type0/$type1", $Links,
461 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
462 $display_filename, $where, $what);
463 if(count($HookResults[1]) <= 1) {
464 $HookResults = do_hook("attachment $type0/*", $Links,
465 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
466 $display_filename, $where, $what);
467 }
468
469 $Links = $HookResults[1];
470 $DefaultLink = $HookResults[6];
471
472 $attachments .= '<TR><TD>' .
473 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
474 '<TD><SMALL><b>' . show_readable_size($header->size) .
475 '</b>&nbsp;&nbsp;</small></TD>' .
476 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
477 '<TD><SMALL>';
478 $attachments .= '<b>' . $description . '</b>';
479 $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
480
481 $SkipSpaces = 1;
482 foreach ($Links as $Val) {
483 if ($SkipSpaces) {
484 $SkipSpaces = 0;
485 } else {
486 $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
487 }
488 $attachments .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
489 }
490 unset($Links);
491 $attachments .= "</TD></TR>\n";
492 }
493 return $attachments;
494 }
495
496 /** this function decodes the body depending on the encoding type. **/
497 function decodeBody($body, $encoding) {
498 global $languages, $squirrelmail_language;
499
500 $body = str_replace("\r\n", "\n", $body);
501 $encoding = strtolower($encoding);
502
503 global $show_html_default;
504
505 if ($encoding == 'quoted-printable' ||
506 $encoding == 'quoted_printable') {
507 $body = quoted_printable_decode($body);
508
509 while (ereg("=\n", $body))
510 $body = ereg_replace ("=\n", "", $body);
511
512 } else if ($encoding == 'base64') {
513 $body = base64_decode($body);
514 }
515
516 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
517 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
518 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
519 }
520
521 // All other encodings are returned raw.
522 return $body;
523 }
524
525 /*
526 * This functions decode strings that is encoded according to
527 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
528 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
529 */
530 function decodeHeader ($string, $utfencode=true) {
531 global $languages, $squirrelmail_language;
532 if (is_array($string)) {
533 $string = implode("\n", $string);
534 }
535
536 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
537 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
538 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
539 }
540
541 $i = 0;
542 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
543 $string, $res)) {
544 $prefix = $res[1];
545 // Ignore white-space between consecutive encoded-words
546 if (strspn($res[2], " \t") != strlen($res[2])) {
547 $prefix .= $res[2];
548 }
549
550 if (ucfirst($res[4]) == 'B') {
551 $replace = base64_decode($res[5]);
552 } else {
553 $replace = str_replace('_', ' ', $res[5]);
554 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
555 $replace);
556 /* Only encode into entities by default. Some places
557 don't need the encoding, like the compose form. */
558 if ($utfencode) {
559 $replace = charset_decode($res[3], $replace);
560 }
561 }
562 $string = $prefix . $replace . substr($string, strlen($res[0]));
563 $i = strlen($prefix) + strlen($replace);
564 }
565 return( $string );
566 }
567
568 /*
569 * Encode a string according to RFC 1522 for use in headers if it
570 * contains 8-bit characters or anything that looks like it should
571 * be encoded.
572 */
573 function encodeHeader ($string) {
574 global $default_charset, $languages, $squirrelmail_language;
575
576 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
577 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
578 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
579 }
580
581 // Encode only if the string contains 8-bit characters or =?
582 $j = strlen( $string );
583 $l = strstr($string, '=?'); // Must be encoded ?
584 $ret = '';
585 for( $i=0; $i < $j; ++$i) {
586 switch( $string{$i} ) {
587 case '=':
588 $ret .= '=3D';
589 break;
590 case '?':
591 $ret .= '=3F';
592 break;
593 case '_':
594 $ret .= '=5F';
595 break;
596 case ' ':
597 $ret .= '_';
598 break;
599 default:
600 $k = ord( $string{$i} );
601 if ( $k > 126 ) {
602 $ret .= sprintf("=%02X", $k);
603 $l = TRUE;
604 } else
605 $ret .= $string{$i};
606 }
607 }
608
609 if ( $l ) {
610 $string = "=?$default_charset?Q?$ret?=";
611 }
612
613 return( $string );
614 }
615
616 /* This function trys to locate the entity_id of a specific mime element */
617
618 function find_ent_id( $id, $message ) {
619 $ret = '';
620 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
621 if ( $message->entities[$i]->header->type0 == 'multipart') {
622 $ret = find_ent_id( $id, $message->entities[$i] );
623 } else {
624 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
625 $ret = $message->entities[$i]->entity_id;
626 }
627 }
628 return( $ret );
629 }
630
631 /**
632 ** HTMLFILTER ROUTINES
633 */
634
635 /**
636 * This function returns the final tag out of the tag name, an array
637 * of attributes, and the type of the tag. This function is called by
638 * sq_sanitize internally.
639 *
640 * @param $tagname the name of the tag.
641 * @param $attary the array of attributes and their values
642 * @param $tagtype The type of the tag (see in comments).
643 * @return a string with the final tag representation.
644 */
645 function sq_tagprint($tagname, $attary, $tagtype){
646 $me = "sq_tagprint";
647 if ($tagtype == 2){
648 $fulltag = '</' . $tagname . '>';
649 } else {
650 $fulltag = '<' . $tagname;
651 if (is_array($attary) && sizeof($attary)){
652 $atts = Array();
653 while (list($attname, $attvalue) = each($attary)){
654 array_push($atts, "$attname=$attvalue");
655 }
656 $fulltag .= ' ' . join(" ", $atts);
657 }
658 if ($tagtype == 3){
659 $fulltag .= " /";
660 }
661 $fulltag .= ">";
662 }
663 return $fulltag;
664 }
665
666 /**
667 * A small helper function to use with array_walk. Modifies a by-ref
668 * value and makes it lowercase.
669 *
670 * @param $val a value passed by-ref.
671 * @return void since it modifies a by-ref value.
672 */
673 function sq_casenormalize(&$val){
674 $val = strtolower($val);
675 }
676
677 /**
678 * This function skips any whitespace from the current position within
679 * a string and to the next non-whitespace value.
680 *
681 * @param $body the string
682 * @param $offset the offset within the string where we should start
683 * looking for the next non-whitespace character.
684 * @return the location within the $body where the next
685 * non-whitespace char is located.
686 */
687 function sq_skipspace($body, $offset){
688 $me = "sq_skipspace";
689 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
690 if (sizeof($matches{1})){
691 $count = strlen($matches{1});
692 $offset += $count;
693 }
694 return $offset;
695 }
696
697 /**
698 * This function looks for the next character within a string. It's
699 * really just a glorified "strpos", except it catches if failures
700 * nicely.
701 *
702 * @param $body The string to look for needle in.
703 * @param $offset Start looking from this position.
704 * @param $needle The character/string to look for.
705 * @return location of the next occurance of the needle, or
706 * strlen($body) if needle wasn't found.
707 */
708 function sq_findnxstr($body, $offset, $needle){
709 $me = "sq_findnxstr";
710 $pos = strpos($body, $needle, $offset);
711 if ($pos === FALSE){
712 $pos = strlen($body);
713 }
714 return $pos;
715 }
716
717 /**
718 * This function takes a PCRE-style regexp and tries to match it
719 * within the string.
720 *
721 * @param $body The string to look for needle in.
722 * @param $offset Start looking from here.
723 * @param $reg A PCRE-style regex to match.
724 * @return Returns a false if no matches found, or an array
725 * with the following members:
726 * - integer with the location of the match within $body
727 * - string with whatever content between offset and the match
728 * - string with whatever it is we matched
729 */
730 function sq_findnxreg($body, $offset, $reg){
731 $me = "sq_findnxreg";
732 $matches = Array();
733 $retarr = Array();
734 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
735 if (!$matches{0}){
736 $retarr = false;
737 } else {
738 $retarr{0} = $offset + strlen($matches{1});
739 $retarr{1} = $matches{1};
740 $retarr{2} = $matches{2};
741 }
742 return $retarr;
743 }
744
745 /**
746 * This function looks for the next tag.
747 *
748 * @param $body String where to look for the next tag.
749 * @param $offset Start looking from here.
750 * @return false if no more tags exist in the body, or
751 * an array with the following members:
752 * - string with the name of the tag
753 * - array with attributes and their values
754 * - integer with tag type (1, 2, or 3)
755 * - integer where the tag starts (starting "<")
756 * - integer where the tag ends (ending ">")
757 * first three members will be false, if the tag is invalid.
758 */
759 function sq_getnxtag($body, $offset){
760 $me = "sq_getnxtag";
761 if ($offset > strlen($body)){
762 return false;
763 }
764 $lt = sq_findnxstr($body, $offset, "<");
765 if ($lt == strlen($body)){
766 return false;
767 }
768 /**
769 * We are here:
770 * blah blah <tag attribute="value">
771 * \---------^
772 */
773 $pos = sq_skipspace($body, $lt+1);
774 if ($pos >= strlen($body)){
775 return Array(false, false, false, $lt, strlen($body));
776 }
777 /**
778 * There are 3 kinds of tags:
779 * 1. Opening tag, e.g.:
780 * <a href="blah">
781 * 2. Closing tag, e.g.:
782 * </a>
783 * 3. XHTML-style content-less tag, e.g.:
784 * <img src="blah"/>
785 */
786 $tagtype = false;
787 switch (substr($body, $pos, 1)){
788 case "/":
789 $tagtype = 2;
790 $pos++;
791 break;
792 case "!":
793 /**
794 * A comment or an SGML declaration.
795 */
796 if (substr($body, $pos+1, 2) == "--"){
797 $gt = strpos($body, "-->", $pos);
798 if ($gt === false){
799 $gt = strlen($body);
800 } else {
801 $gt += 2;
802 }
803 return Array(false, false, false, $lt, $gt);
804 } else {
805 $gt = sq_findnxstr($body, $pos, ">");
806 return Array(false, false, false, $lt, $gt);
807 }
808 break;
809 default:
810 /**
811 * Assume tagtype 1 for now. If it's type 3, we'll switch values
812 * later.
813 */
814 $tagtype = 1;
815 break;
816 }
817
818 $tag_start = $pos;
819 $tagname = '';
820 /**
821 * Look for next [\W-_], which will indicate the end of the tag name.
822 */
823 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
824 if ($regary == false){
825 return Array(false, false, false, $lt, strlen($body));
826 }
827 list($pos, $tagname, $match) = $regary;
828 $tagname = strtolower($tagname);
829
830 /**
831 * $match can be either of these:
832 * '>' indicating the end of the tag entirely.
833 * '\s' indicating the end of the tag name.
834 * '/' indicating that this is type-3 xhtml tag.
835 *
836 * Whatever else we find there indicates an invalid tag.
837 */
838 switch ($match){
839 case "/":
840 /**
841 * This is an xhtml-style tag with a closing / at the
842 * end, like so: <img src="blah"/>. Check if it's followed
843 * by the closing bracket. If not, then this tag is invalid
844 */
845 if (substr($body, $pos, 2) == "/>"){
846 $pos++;
847 $tagtype = 3;
848 } else {
849 $gt = sq_findnxstr($body, $pos, ">");
850 $retary = Array(false, false, false, $lt, $gt);
851 return $retary;
852 }
853 case ">":
854 return Array($tagname, false, $tagtype, $lt, $pos);
855 break;
856 default:
857 /**
858 * Check if it's whitespace
859 */
860 if (preg_match("/\s/", $match)){
861 } else {
862 /**
863 * This is an invalid tag! Look for the next closing ">".
864 */
865 $gt = sq_findnxstr($body, $offset, ">");
866 return Array(false, false, false, $lt, $gt);
867 }
868 }
869
870 /**
871 * At this point we're here:
872 * <tagname attribute='blah'>
873 * \-------^
874 *
875 * At this point we loop in order to find all attributes.
876 */
877 $attname = '';
878 $atttype = false;
879 $attary = Array();
880
881 while ($pos <= strlen($body)){
882 $pos = sq_skipspace($body, $pos);
883 if ($pos == strlen($body)){
884 /**
885 * Non-closed tag.
886 */
887 return Array(false, false, false, $lt, $pos);
888 }
889 /**
890 * See if we arrived at a ">" or "/>", which means that we reached
891 * the end of the tag.
892 */
893 $matches = Array();
894 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
895 /**
896 * Yep. So we did.
897 */
898 $pos += strlen($matches{1});
899 if ($matches{2} == "/>"){
900 $tagtype = 3;
901 $pos++;
902 }
903 return Array($tagname, $attary, $tagtype, $lt, $pos);
904 }
905
906 /**
907 * There are several types of attributes, with optional
908 * [:space:] between members.
909 * Type 1:
910 * attrname[:space:]=[:space:]'CDATA'
911 * Type 2:
912 * attrname[:space:]=[:space:]"CDATA"
913 * Type 3:
914 * attr[:space:]=[:space:]CDATA
915 * Type 4:
916 * attrname
917 *
918 * We leave types 1 and 2 the same, type 3 we check for
919 * '"' and convert to "&quot" if needed, then wrap in
920 * double quotes. Type 4 we convert into:
921 * attrname="yes".
922 */
923 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
924 if ($regary == false){
925 /**
926 * Looks like body ended before the end of tag.
927 */
928 return Array(false, false, false, $lt, strlen($body));
929 }
930 list($pos, $attname, $match) = $regary;
931 $attname = strtolower($attname);
932 /**
933 * We arrived at the end of attribute name. Several things possible
934 * here:
935 * '>' means the end of the tag and this is attribute type 4
936 * '/' if followed by '>' means the same thing as above
937 * '\s' means a lot of things -- look what it's followed by.
938 * anything else means the attribute is invalid.
939 */
940 switch($match){
941 case "/":
942 /**
943 * This is an xhtml-style tag with a closing / at the
944 * end, like so: <img src="blah"/>. Check if it's followed
945 * by the closing bracket. If not, then this tag is invalid
946 */
947 if (substr($body, $pos, 2) == "/>"){
948 $pos++;
949 $tagtype = 3;
950 } else {
951 $gt = sq_findnxstr($body, $pos, ">");
952 $retary = Array(false, false, false, $lt, $gt);
953 return $retary;
954 }
955 case ">":
956 $attary{$attname} = '"yes"';
957 return Array($tagname, $attary, $tagtype, $lt, $pos);
958 break;
959 default:
960 /**
961 * Skip whitespace and see what we arrive at.
962 */
963 $pos = sq_skipspace($body, $pos);
964 $char = substr($body, $pos, 1);
965 /**
966 * Two things are valid here:
967 * '=' means this is attribute type 1 2 or 3.
968 * \w means this was attribute type 4.
969 * anything else we ignore and re-loop. End of tag and
970 * invalid stuff will be caught by our checks at the beginning
971 * of the loop.
972 */
973 if ($char == "="){
974 $pos++;
975 $pos = sq_skipspace($body, $pos);
976 /**
977 * Here are 3 possibilities:
978 * "'" attribute type 1
979 * '"' attribute type 2
980 * everything else is the content of tag type 3
981 */
982 $quot = substr($body, $pos, 1);
983 if ($quot == "'"){
984 $regary = sq_findnxreg($body, $pos+1, "\'");
985 if ($regary == false){
986 return Array(false, false, false, $lt, strlen($body));
987 }
988 list($pos, $attval, $match) = $regary;
989 $pos++;
990 $attary{$attname} = "'" . $attval . "'";
991 } else if ($quot == '"'){
992 $regary = sq_findnxreg($body, $pos+1, '\"');
993 if ($regary == false){
994 return Array(false, false, false, $lt, strlen($body));
995 }
996 list($pos, $attval, $match) = $regary;
997 $pos++;
998 $attary{$attname} = '"' . $attval . '"';
999 } else {
1000 /**
1001 * These are hateful. Look for \s, or >.
1002 */
1003 $regary = sq_findnxreg($body, $pos, "[\s>]");
1004 if ($regary == false){
1005 return Array(false, false, false, $lt, strlen($body));
1006 }
1007 list($pos, $attval, $match) = $regary;
1008 /**
1009 * If it's ">" it will be caught at the top.
1010 */
1011 $attval = preg_replace("/\"/s", "&quot;", $attval);
1012 $attary{$attname} = '"' . $attval . '"';
1013 }
1014 } else if (preg_match("|[\w/>]|", $char)) {
1015 /**
1016 * That was attribute type 4.
1017 */
1018 $attary{$attname} = '"yes"';
1019 } else {
1020 /**
1021 * An illegal character. Find next '>' and return.
1022 */
1023 $gt = sq_findnxstr($body, $pos, ">");
1024 return Array(false, false, false, $lt, $gt);
1025 }
1026 }
1027 }
1028 /**
1029 * The fact that we got here indicates that the tag end was never
1030 * found. Return invalid tag indication so it gets stripped.
1031 */
1032 return Array(false, false, false, $lt, strlen($body));
1033 }
1034
1035 /**
1036 * This function checks attribute values for entity-encoded values
1037 * and returns them translated into 8-bit strings so we can run
1038 * checks on them.
1039 *
1040 * @param $attvalue A string to run entity check against.
1041 * @return Translated value.
1042 */
1043 function sq_deent($attvalue){
1044 $me="sq_deent";
1045 /**
1046 * See if we have to run the checks first. All entities must start
1047 * with "&".
1048 */
1049 if (strpos($attvalue, "&") === false){
1050 return $attvalue;
1051 }
1052 /**
1053 * Check named entities first.
1054 */
1055 $trans = get_html_translation_table(HTML_ENTITIES);
1056 /**
1057 * Leave &quot; in, as it can mess us up.
1058 */
1059 $trans = array_flip($trans);
1060 unset($trans{"&quot;"});
1061 while (list($ent, $val) = each($trans)){
1062 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1063 }
1064 /**
1065 * Now translate numbered entities from 1 to 255 if needed.
1066 */
1067 if (strpos($attvalue, "#") !== false){
1068 $omit = Array(34, 39);
1069 for ($asc=1; $asc<256; $asc++){
1070 if (!in_array($asc, $omit)){
1071 $chr = chr($asc);
1072 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1073 $attvalue);
1074 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1075 "$chr\\1", $attvalue);
1076 }
1077 }
1078 }
1079 return $attvalue;
1080 }
1081
1082 /**
1083 * This function runs various checks against the attributes.
1084 *
1085 * @param $tagname String with the name of the tag.
1086 * @param $attary Array with all tag attributes.
1087 * @param $rm_attnames See description for sq_sanitize
1088 * @param $bad_attvals See description for sq_sanitize
1089 * @param $add_attr_to_tag See description for sq_sanitize
1090 * @param $message message object
1091 * @param $id message id
1092 * @return Array with modified attributes.
1093 */
1094 function sq_fixatts($tagname,
1095 $attary,
1096 $rm_attnames,
1097 $bad_attvals,
1098 $add_attr_to_tag,
1099 $message,
1100 $id,
1101 $mailbox
1102 ){
1103 $me = "sq_fixatts";
1104 while (list($attname, $attvalue) = each($attary)){
1105 /**
1106 * See if this attribute should be removed.
1107 */
1108 foreach ($rm_attnames as $matchtag=>$matchattrs){
1109 if (preg_match($matchtag, $tagname)){
1110 foreach ($matchattrs as $matchattr){
1111 if (preg_match($matchattr, $attname)){
1112 unset($attary{$attname});
1113 continue;
1114 }
1115 }
1116 }
1117 }
1118 /**
1119 * Remove any entities.
1120 */
1121 $attvalue = sq_deent($attvalue);
1122
1123 /**
1124 * Now let's run checks on the attvalues.
1125 * I don't expect anyone to comprehend this. If you do,
1126 * get in touch with me so I can drive to where you live and
1127 * shake your hand personally. :)
1128 */
1129 foreach ($bad_attvals as $matchtag=>$matchattrs){
1130 if (preg_match($matchtag, $tagname)){
1131 foreach ($matchattrs as $matchattr=>$valary){
1132 if (preg_match($matchattr, $attname)){
1133 /**
1134 * There are two arrays in valary.
1135 * First is matches.
1136 * Second one is replacements
1137 */
1138 list($valmatch, $valrepl) = $valary;
1139 $newvalue =
1140 preg_replace($valmatch, $valrepl, $attvalue);
1141 if ($newvalue != $attvalue){
1142 $attary{$attname} = $newvalue;
1143 }
1144 }
1145 }
1146 }
1147 }
1148 /**
1149 * Turn cid: urls into http-friendly ones.
1150 */
1151 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1152 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1153 }
1154 }
1155 /**
1156 * See if we need to append any attributes to this tag.
1157 */
1158 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1159 if (preg_match($matchtag, $tagname)){
1160 $attary = array_merge($attary, $addattary);
1161 }
1162 }
1163 return $attary;
1164 }
1165
1166 /**
1167 * This function edits the style definition to make them friendly and
1168 * usable in squirrelmail.
1169 *
1170 * @param $message the message object
1171 * @param $id the message id
1172 * @param $content a string with whatever is between <style> and </style>
1173 * @return a string with edited content.
1174 */
1175 function sq_fixstyle($message, $id, $content){
1176 global $view_unsafe_images;
1177 $me = "sq_fixstyle";
1178 /**
1179 * First look for general BODY style declaration, which would be
1180 * like so:
1181 * body {background: blah-blah}
1182 * and change it to .bodyclass so we can just assign it to a <div>
1183 */
1184 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1185 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1186 /**
1187 * Fix url('blah') declarations.
1188 */
1189 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1190 "url(\\1$secremoveimg\\2)", $content);
1191 /**
1192 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1193 * is false.
1194 */
1195 if (!$view_unsafe_images){
1196 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1197 "url(\\1$secremoveimg\\2)", $content);
1198 }
1199
1200 /**
1201 * Fix urls that refer to cid:
1202 */
1203 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1204 $matches)){
1205 $cidurl = $matches{1};
1206 $httpurl = sq_cid2http($message, $id, $cidurl);
1207 $content = preg_replace("|url\($cidurl\)|si",
1208 "url($httpurl)", $content);
1209 }
1210
1211 /**
1212 * Fix stupid css declarations which lead to vulnerabilities
1213 * in IE.
1214 */
1215 $match = Array('/expression/si',
1216 '/behaviou*r/si',
1217 '/binding/si');
1218 $replace = Array('idiocy', 'idiocy', 'idiocy');
1219 $content = preg_replace($match, $replace, $content);
1220 return $content;
1221 }
1222
1223 /**
1224 * This function converts cid: url's into the ones that can be viewed in
1225 * the browser.
1226 *
1227 * @param $message the message object
1228 * @param $id the message id
1229 * @param $cidurl the cid: url.
1230 * @return a string with a http-friendly url
1231 */
1232 function sq_cid2http($message, $id, $cidurl, $mailbox){
1233 /**
1234 * Get rid of quotes.
1235 */
1236 $quotchar = substr($cidurl, 0, 1);
1237 $cidurl = str_replace($quotchar, "", $cidurl);
1238 $cidurl = substr(trim($cidurl), 4);
1239 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
1240 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
1241 "&amp;ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1242 return $httpurl;
1243 }
1244
1245 /**
1246 * This function changes the <body> tag into a <div> tag since we
1247 * can't really have a body-within-body.
1248 *
1249 * @param $attary an array of attributes and values of <body>
1250 * @return a modified array of attributes to be set for <div>
1251 */
1252 function sq_body2div($attary){
1253 $me = "sq_body2div";
1254 $divattary = Array("class"=>"'bodyclass'");
1255 $bgcolor="#ffffff";
1256 $text="#000000";
1257 $styledef="";
1258 if (is_array($attary) && sizeof($attary) > 0){
1259 foreach ($attary as $attname=>$attvalue){
1260 $quotchar = substr($attvalue, 0, 1);
1261 $attvalue = str_replace($quotchar, "", $attvalue);
1262 switch ($attname){
1263 case "background":
1264 $styledef .= "background-image: url('$attvalue'); ";
1265 break;
1266 case "bgcolor":
1267 $styledef .= "background-color: $attvalue; ";
1268 break;
1269 case "text":
1270 $styledef .= "color: $attvalue; ";
1271 }
1272 }
1273 if (strlen($styledef) > 0){
1274 $divattary{"style"} = "\"$styledef\"";
1275 }
1276 }
1277 return $divattary;
1278 }
1279
1280 /**
1281 * This is the main function and the one you should actually be calling.
1282 * There are several variables you should be aware of an which need
1283 * special description.
1284 *
1285 * Since the description is quite lengthy, see it here:
1286 * http://www.mricon.com/html/phpfilter.html
1287 *
1288 * @param $body the string with HTML you wish to filter
1289 * @param $tag_list see description above
1290 * @param $rm_tags_with_content see description above
1291 * @param $self_closing_tags see description above
1292 * @param $force_tag_closing see description above
1293 * @param $rm_attnames see description above
1294 * @param $bad_attvals see description above
1295 * @param $add_attr_to_tag see description above
1296 * @param $message message object
1297 * @param $id message id
1298 * @return sanitized html safe to show on your pages.
1299 */
1300 function sq_sanitize($body,
1301 $tag_list,
1302 $rm_tags_with_content,
1303 $self_closing_tags,
1304 $force_tag_closing,
1305 $rm_attnames,
1306 $bad_attvals,
1307 $add_attr_to_tag,
1308 $message,
1309 $id,
1310 $mailbox
1311 ){
1312 $me = "sq_sanitize";
1313 /**
1314 * Normalize rm_tags and rm_tags_with_content.
1315 */
1316 @array_walk($rm_tags, 'sq_casenormalize');
1317 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1318 @array_walk($self_closing_tags, 'sq_casenormalize');
1319 /**
1320 * See if tag_list is of tags to remove or tags to allow.
1321 * false means remove these tags
1322 * true means allow these tags
1323 */
1324 $rm_tags = array_shift($tag_list);
1325 $curpos = 0;
1326 $open_tags = Array();
1327 $trusted = "<!-- begin sanitized html -->\n";
1328 $skip_content = false;
1329 /**
1330 * Take care of netscape's stupid javascript entities like
1331 * &{alert('boo')};
1332 */
1333 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
1334
1335 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1336 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1337 $free_content = substr($body, $curpos, $lt-$curpos);
1338 /**
1339 * Take care of <style>
1340 */
1341 if ($tagname == "style" && $tagtype == 2){
1342 /**
1343 * This is a closing </style>. Edit the
1344 * content before we apply it.
1345 */
1346 $free_content = sq_fixstyle($message, $id, $free_content);
1347 }
1348 if ($skip_content == false){
1349 $trusted .= $free_content;
1350 } else {
1351 }
1352 if ($tagname != FALSE){
1353 if ($tagtype == 2){
1354 if ($skip_content == $tagname){
1355 /**
1356 * Got to the end of tag we needed to remove.
1357 */
1358 $tagname = false;
1359 $skip_content = false;
1360 } else {
1361 if ($skip_content == false){
1362 if ($tagname == "body"){
1363 $tagname = "div";
1364 } else {
1365 if (isset($open_tags{$tagname}) &&
1366 $open_tags{$tagname} > 0){
1367 $open_tags{$tagname}--;
1368 } else {
1369 $tagname = false;
1370 }
1371 }
1372 } else {
1373 }
1374 }
1375 } else {
1376 /**
1377 * $rm_tags_with_content
1378 */
1379 if ($skip_content == false){
1380 /**
1381 * See if this is a self-closing type and change
1382 * tagtype appropriately.
1383 */
1384 if ($tagtype == 1
1385 && in_array($tagname, $self_closing_tags)){
1386 $tagtype=3;
1387 }
1388 /**
1389 * See if we should skip this tag and any content
1390 * inside it.
1391 */
1392 if ($tagtype == 1 &&
1393 in_array($tagname, $rm_tags_with_content)){
1394 $skip_content = $tagname;
1395 } else {
1396 if (($rm_tags == false
1397 && in_array($tagname, $tag_list)) ||
1398 ($rm_tags == true &&
1399 !in_array($tagname, $tag_list))){
1400 $tagname = false;
1401 } else {
1402 if ($tagtype == 1){
1403 if (isset($open_tags{$tagname})){
1404 $open_tags{$tagname}++;
1405 } else {
1406 $open_tags{$tagname}=1;
1407 }
1408 }
1409 /**
1410 * This is where we run other checks.
1411 */
1412 if (is_array($attary) && sizeof($attary) > 0){
1413 $attary = sq_fixatts($tagname,
1414 $attary,
1415 $rm_attnames,
1416 $bad_attvals,
1417 $add_attr_to_tag,
1418 $message,
1419 $id,
1420 $mailbox
1421 );
1422 }
1423 /**
1424 * Convert body into div.
1425 */
1426 if ($tagname == "body"){
1427 $tagname = "div";
1428 $attary = sq_body2div($attary, $message, $id);
1429 }
1430 }
1431 }
1432 } else {
1433 }
1434 }
1435 if ($tagname != false && $skip_content == false){
1436 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1437 }
1438 } else {
1439 }
1440 $curpos = $gt+1;
1441 }
1442 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1443 if ($force_tag_closing == true){
1444 foreach ($open_tags as $tagname=>$opentimes){
1445 while ($opentimes > 0){
1446 $trusted .= '</' . $tagname . '>';
1447 $opentimes--;
1448 }
1449 }
1450 $trusted .= "\n";
1451 }
1452 $trusted .= "<!-- end sanitized html -->\n";
1453 return $trusted;
1454 }
1455
1456 /**
1457 * This is a wrapper function to call html sanitizing routines.
1458 *
1459 * @param $body the body of the message
1460 * @param $id the id of the message
1461 * @return a string with html safe to display in the browser.
1462 */
1463 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1464 global $attachment_common_show_images, $view_unsafe_images,
1465 $has_unsafe_images;
1466 /**
1467 * Don't display attached images in HTML mode.
1468 */
1469 $attachment_common_show_images = false;
1470 $tag_list = Array(
1471 false,
1472 "object",
1473 "meta",
1474 "html",
1475 "head",
1476 "base",
1477 "link"
1478 );
1479
1480 $rm_tags_with_content = Array(
1481 "script",
1482 "applet",
1483 "embed",
1484 "title"
1485 );
1486
1487 $self_closing_tags = Array(
1488 "img",
1489 "br",
1490 "hr",
1491 "input"
1492 );
1493
1494 $force_tag_closing = false;
1495
1496 $rm_attnames = Array(
1497 "/.*/" =>
1498 Array(
1499 "/target/si",
1500 "/^on.*/si",
1501 "/^dynsrc/si",
1502 "/^data.*/si"
1503 )
1504 );
1505
1506 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1507 $bad_attvals = Array(
1508 "/.*/" =>
1509 Array(
1510 "/^src|background/i" =>
1511 Array(
1512 Array(
1513 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1514 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1515 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1516 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1517 ),
1518 Array(
1519 "\\1$secremoveimg\\2",
1520 "\\1$secremoveimg\\2",
1521 "\\1$secremoveimg\\2",
1522 "\\1$secremoveimg\\2"
1523 )
1524 ),
1525 "/^href|action/i" =>
1526 Array(
1527 Array(
1528 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1529 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1530 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1531 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1532 ),
1533 Array(
1534 "\\1#\\2",
1535 "\\1#\\2",
1536 "\\1#\\2",
1537 "\\1#\\2"
1538 )
1539 ),
1540 "/^style/si" =>
1541 Array(
1542 Array(
1543 "/expression/si",
1544 "/binding/si",
1545 "/behaviou*r/si",
1546 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1547 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1548 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1549 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1550 ),
1551 Array(
1552 "idiocy",
1553 "idiocy",
1554 "idiocy",
1555 "url(\\1#\\2)",
1556 "url(\\1#\\2)",
1557 "url(\\1#\\2)",
1558 "url(\\1#\\2)"
1559 )
1560 )
1561 )
1562 );
1563 if (!$view_unsafe_images){
1564 /**
1565 * Remove any references to http/https if view_unsafe_images set
1566 * to false.
1567 */
1568 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1569 '/^([\'\"])\s*https*:.*([\'\"])/si');
1570 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1571 "\\1$secremoveimg\\2");
1572 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1573 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1574 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1575 "url(\\1$secremoveimg\\2)");
1576 }
1577
1578 $add_attr_to_tag = Array(
1579 "/^a$/si" => Array('target'=>'"_new"')
1580 );
1581 $trusted = sq_sanitize($body,
1582 $tag_list,
1583 $rm_tags_with_content,
1584 $self_closing_tags,
1585 $force_tag_closing,
1586 $rm_attnames,
1587 $bad_attvals,
1588 $add_attr_to_tag,
1589 $message,
1590 $id,
1591 $mailbox
1592 );
1593 if (preg_match("|$secremoveimg|si", $trusted)){
1594 $has_unsafe_images = true;
1595 }
1596 return $trusted;
1597 }
1598
1599 ?>