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