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