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