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