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