added unsave tags (commited to stable by Konstantin)
[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(SM_PATH . 'functions/imap.php');
16 require_once(SM_PATH . '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(SM_PATH . '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(SM_PATH . '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 function find_ent_id($id, $message) {
626 for ($i = 0, $ret = ''; $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 if (sq_check_save_extension($message->entities[$i])) {
632 return $message->entities[$i]->entity_id;
633 }
634 }
635 }
636 }
637 return $ret;
638 }
639
640 function sq_check_save_extension($message) {
641 $filename = $message->getFilename();
642 $ext = substr($filename, strrpos($filename,'.')+1);
643 $save_extensions = array('jpg','jpeg','gif','png','bmp');
644 return in_array($ext, $save_extensions);
645 }
646
647
648 /**
649 ** HTMLFILTER ROUTINES
650 */
651
652 /**
653 * This function returns the final tag out of the tag name, an array
654 * of attributes, and the type of the tag. This function is called by
655 * sq_sanitize internally.
656 *
657 * @param $tagname the name of the tag.
658 * @param $attary the array of attributes and their values
659 * @param $tagtype The type of the tag (see in comments).
660 * @return a string with the final tag representation.
661 */
662 function sq_tagprint($tagname, $attary, $tagtype){
663 $me = 'sq_tagprint';
664
665 if ($tagtype == 2){
666 $fulltag = '</' . $tagname . '>';
667 } else {
668 $fulltag = '<' . $tagname;
669 if (is_array($attary) && sizeof($attary)){
670 $atts = Array();
671 while (list($attname, $attvalue) = each($attary)){
672 array_push($atts, "$attname=$attvalue");
673 }
674 $fulltag .= ' ' . join(" ", $atts);
675 }
676 if ($tagtype == 3){
677 $fulltag .= ' /';
678 }
679 $fulltag .= '>';
680 }
681 return $fulltag;
682 }
683
684 /**
685 * A small helper function to use with array_walk. Modifies a by-ref
686 * value and makes it lowercase.
687 *
688 * @param $val a value passed by-ref.
689 * @return void since it modifies a by-ref value.
690 */
691 function sq_casenormalize(&$val){
692 $val = strtolower($val);
693 }
694
695 /**
696 * This function skips any whitespace from the current position within
697 * a string and to the next non-whitespace value.
698 *
699 * @param $body the string
700 * @param $offset the offset within the string where we should start
701 * looking for the next non-whitespace character.
702 * @return the location within the $body where the next
703 * non-whitespace char is located.
704 */
705 function sq_skipspace($body, $offset){
706 $me = 'sq_skipspace';
707 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
708 if (sizeof($matches{1})){
709 $count = strlen($matches{1});
710 $offset += $count;
711 }
712 return $offset;
713 }
714
715 /**
716 * This function looks for the next character within a string. It's
717 * really just a glorified "strpos", except it catches if failures
718 * nicely.
719 *
720 * @param $body The string to look for needle in.
721 * @param $offset Start looking from this position.
722 * @param $needle The character/string to look for.
723 * @return location of the next occurance of the needle, or
724 * strlen($body) if needle wasn't found.
725 */
726 function sq_findnxstr($body, $offset, $needle){
727 $me = 'sq_findnxstr';
728 $pos = strpos($body, $needle, $offset);
729 if ($pos === FALSE){
730 $pos = strlen($body);
731 }
732 return $pos;
733 }
734
735 /**
736 * This function takes a PCRE-style regexp and tries to match it
737 * within the string.
738 *
739 * @param $body The string to look for needle in.
740 * @param $offset Start looking from here.
741 * @param $reg A PCRE-style regex to match.
742 * @return Returns a false if no matches found, or an array
743 * with the following members:
744 * - integer with the location of the match within $body
745 * - string with whatever content between offset and the match
746 * - string with whatever it is we matched
747 */
748 function sq_findnxreg($body, $offset, $reg){
749 $me = 'sq_findnxreg';
750 $matches = Array();
751 $retarr = Array();
752 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
753 if (!$matches{0}){
754 $retarr = false;
755 } else {
756 $retarr{0} = $offset + strlen($matches{1});
757 $retarr{1} = $matches{1};
758 $retarr{2} = $matches{2};
759 }
760 return $retarr;
761 }
762
763 /**
764 * This function looks for the next tag.
765 *
766 * @param $body String where to look for the next tag.
767 * @param $offset Start looking from here.
768 * @return false if no more tags exist in the body, or
769 * an array with the following members:
770 * - string with the name of the tag
771 * - array with attributes and their values
772 * - integer with tag type (1, 2, or 3)
773 * - integer where the tag starts (starting "<")
774 * - integer where the tag ends (ending ">")
775 * first three members will be false, if the tag is invalid.
776 */
777 function sq_getnxtag($body, $offset){
778 $me = 'sq_getnxtag';
779 if ($offset > strlen($body)){
780 return false;
781 }
782 $lt = sq_findnxstr($body, $offset, "<");
783 if ($lt == strlen($body)){
784 return false;
785 }
786 /**
787 * We are here:
788 * blah blah <tag attribute="value">
789 * \---------^
790 */
791 $pos = sq_skipspace($body, $lt+1);
792 if ($pos >= strlen($body)){
793 return Array(false, false, false, $lt, strlen($body));
794 }
795 /**
796 * There are 3 kinds of tags:
797 * 1. Opening tag, e.g.:
798 * <a href="blah">
799 * 2. Closing tag, e.g.:
800 * </a>
801 * 3. XHTML-style content-less tag, e.g.:
802 * <img src="blah"/>
803 */
804 $tagtype = false;
805 switch (substr($body, $pos, 1)){
806 case '/':
807 $tagtype = 2;
808 $pos++;
809 break;
810 case '!':
811 /**
812 * A comment or an SGML declaration.
813 */
814 if (substr($body, $pos+1, 2) == "--"){
815 $gt = strpos($body, "-->", $pos);
816 if ($gt === false){
817 $gt = strlen($body);
818 } else {
819 $gt += 2;
820 }
821 return Array(false, false, false, $lt, $gt);
822 } else {
823 $gt = sq_findnxstr($body, $pos, ">");
824 return Array(false, false, false, $lt, $gt);
825 }
826 break;
827 default:
828 /**
829 * Assume tagtype 1 for now. If it's type 3, we'll switch values
830 * later.
831 */
832 $tagtype = 1;
833 break;
834 }
835
836 $tag_start = $pos;
837 $tagname = '';
838 /**
839 * Look for next [\W-_], which will indicate the end of the tag name.
840 */
841 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
842 if ($regary == false){
843 return Array(false, false, false, $lt, strlen($body));
844 }
845 list($pos, $tagname, $match) = $regary;
846 $tagname = strtolower($tagname);
847
848 /**
849 * $match can be either of these:
850 * '>' indicating the end of the tag entirely.
851 * '\s' indicating the end of the tag name.
852 * '/' indicating that this is type-3 xhtml tag.
853 *
854 * Whatever else we find there indicates an invalid tag.
855 */
856 switch ($match){
857 case '/':
858 /**
859 * This is an xhtml-style tag with a closing / at the
860 * end, like so: <img src="blah"/>. Check if it's followed
861 * by the closing bracket. If not, then this tag is invalid
862 */
863 if (substr($body, $pos, 2) == "/>"){
864 $pos++;
865 $tagtype = 3;
866 } else {
867 $gt = sq_findnxstr($body, $pos, ">");
868 $retary = Array(false, false, false, $lt, $gt);
869 return $retary;
870 }
871 case '>':
872 return Array($tagname, false, $tagtype, $lt, $pos);
873 break;
874 default:
875 /**
876 * Check if it's whitespace
877 */
878 if (!preg_match('/\s/', $match)){
879 /**
880 * This is an invalid tag! Look for the next closing ">".
881 */
882 $gt = sq_findnxstr($body, $offset, ">");
883 return Array(false, false, false, $lt, $gt);
884 }
885 break;
886 }
887
888 /**
889 * At this point we're here:
890 * <tagname attribute='blah'>
891 * \-------^
892 *
893 * At this point we loop in order to find all attributes.
894 */
895 $attname = '';
896 $atttype = false;
897 $attary = Array();
898
899 while ($pos <= strlen($body)){
900 $pos = sq_skipspace($body, $pos);
901 if ($pos == strlen($body)){
902 /**
903 * Non-closed tag.
904 */
905 return Array(false, false, false, $lt, $pos);
906 }
907 /**
908 * See if we arrived at a ">" or "/>", which means that we reached
909 * the end of the tag.
910 */
911 $matches = Array();
912 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
913 /**
914 * Yep. So we did.
915 */
916 $pos += strlen($matches{1});
917 if ($matches{2} == "/>"){
918 $tagtype = 3;
919 $pos++;
920 }
921 return Array($tagname, $attary, $tagtype, $lt, $pos);
922 }
923
924 /**
925 * There are several types of attributes, with optional
926 * [:space:] between members.
927 * Type 1:
928 * attrname[:space:]=[:space:]'CDATA'
929 * Type 2:
930 * attrname[:space:]=[:space:]"CDATA"
931 * Type 3:
932 * attr[:space:]=[:space:]CDATA
933 * Type 4:
934 * attrname
935 *
936 * We leave types 1 and 2 the same, type 3 we check for
937 * '"' and convert to "&quot" if needed, then wrap in
938 * double quotes. Type 4 we convert into:
939 * attrname="yes".
940 */
941 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
942 if ($regary == false){
943 /**
944 * Looks like body ended before the end of tag.
945 */
946 return Array(false, false, false, $lt, strlen($body));
947 }
948 list($pos, $attname, $match) = $regary;
949 $attname = strtolower($attname);
950 /**
951 * We arrived at the end of attribute name. Several things possible
952 * here:
953 * '>' means the end of the tag and this is attribute type 4
954 * '/' if followed by '>' means the same thing as above
955 * '\s' means a lot of things -- look what it's followed by.
956 * anything else means the attribute is invalid.
957 */
958 switch($match){
959 case '/':
960 /**
961 * This is an xhtml-style tag with a closing / at the
962 * end, like so: <img src="blah"/>. Check if it's followed
963 * by the closing bracket. If not, then this tag is invalid
964 */
965 if (substr($body, $pos, 2) == "/>"){
966 $pos++;
967 $tagtype = 3;
968 } else {
969 $gt = sq_findnxstr($body, $pos, ">");
970 $retary = Array(false, false, false, $lt, $gt);
971 return $retary;
972 }
973 case '>':
974 $attary{$attname} = '"yes"';
975 return Array($tagname, $attary, $tagtype, $lt, $pos);
976 break;
977 default:
978 /**
979 * Skip whitespace and see what we arrive at.
980 */
981 $pos = sq_skipspace($body, $pos);
982 $char = substr($body, $pos, 1);
983 /**
984 * Two things are valid here:
985 * '=' means this is attribute type 1 2 or 3.
986 * \w means this was attribute type 4.
987 * anything else we ignore and re-loop. End of tag and
988 * invalid stuff will be caught by our checks at the beginning
989 * of the loop.
990 */
991 if ($char == "="){
992 $pos++;
993 $pos = sq_skipspace($body, $pos);
994 /**
995 * Here are 3 possibilities:
996 * "'" attribute type 1
997 * '"' attribute type 2
998 * everything else is the content of tag type 3
999 */
1000 $quot = substr($body, $pos, 1);
1001 if ($quot == "'"){
1002 $regary = sq_findnxreg($body, $pos+1, "\'");
1003 if ($regary == false){
1004 return Array(false, false, false, $lt, strlen($body));
1005 }
1006 list($pos, $attval, $match) = $regary;
1007 $pos++;
1008 $attary{$attname} = "'" . $attval . "'";
1009 } else if ($quot == '"'){
1010 $regary = sq_findnxreg($body, $pos+1, '\"');
1011 if ($regary == false){
1012 return Array(false, false, false, $lt, strlen($body));
1013 }
1014 list($pos, $attval, $match) = $regary;
1015 $pos++;
1016 $attary{$attname} = '"' . $attval . '"';
1017 } else {
1018 /**
1019 * These are hateful. Look for \s, or >.
1020 */
1021 $regary = sq_findnxreg($body, $pos, "[\s>]");
1022 if ($regary == false){
1023 return Array(false, false, false, $lt, strlen($body));
1024 }
1025 list($pos, $attval, $match) = $regary;
1026 /**
1027 * If it's ">" it will be caught at the top.
1028 */
1029 $attval = preg_replace("/\"/s", "&quot;", $attval);
1030 $attary{$attname} = '"' . $attval . '"';
1031 }
1032 } else if (preg_match("|[\w/>]|", $char)) {
1033 /**
1034 * That was attribute type 4.
1035 */
1036 $attary{$attname} = '"yes"';
1037 } else {
1038 /**
1039 * An illegal character. Find next '>' and return.
1040 */
1041 $gt = sq_findnxstr($body, $pos, ">");
1042 return Array(false, false, false, $lt, $gt);
1043 }
1044 break;
1045 }
1046 }
1047 /**
1048 * The fact that we got here indicates that the tag end was never
1049 * found. Return invalid tag indication so it gets stripped.
1050 */
1051 return Array(false, false, false, $lt, strlen($body));
1052 }
1053
1054 /**
1055 * This function checks attribute values for entity-encoded values
1056 * and returns them translated into 8-bit strings so we can run
1057 * checks on them.
1058 *
1059 * @param $attvalue A string to run entity check against.
1060 * @return Translated value.
1061 */
1062 function sq_deent($attvalue){
1063 $me = 'sq_deent';
1064 /**
1065 * See if we have to run the checks first. All entities must start
1066 * with "&".
1067 */
1068 if (strpos($attvalue, "&") === false){
1069 return $attvalue;
1070 }
1071 /**
1072 * Check named entities first.
1073 */
1074 $trans = get_html_translation_table(HTML_ENTITIES);
1075 /**
1076 * Leave &quot; in, as it can mess us up.
1077 */
1078 $trans = array_flip($trans);
1079 unset($trans{"&quot;"});
1080 while (list($ent, $val) = each($trans)){
1081 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1082 }
1083 /**
1084 * Now translate numbered entities from 1 to 255 if needed.
1085 */
1086 if (strpos($attvalue, "#") !== false){
1087 $omit = Array(34, 39);
1088 for ($asc=1; $asc<256; $asc++){
1089 if (!in_array($asc, $omit)){
1090 $chr = chr($asc);
1091 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1092 $attvalue);
1093 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1094 "$chr\\1", $attvalue);
1095 }
1096 }
1097 }
1098 return $attvalue;
1099 }
1100
1101 /**
1102 * This function runs various checks against the attributes.
1103 *
1104 * @param $tagname String with the name of the tag.
1105 * @param $attary Array with all tag attributes.
1106 * @param $rm_attnames See description for sq_sanitize
1107 * @param $bad_attvals See description for sq_sanitize
1108 * @param $add_attr_to_tag See description for sq_sanitize
1109 * @param $message message object
1110 * @param $id message id
1111 * @return Array with modified attributes.
1112 */
1113 function sq_fixatts($tagname,
1114 $attary,
1115 $rm_attnames,
1116 $bad_attvals,
1117 $add_attr_to_tag,
1118 $message,
1119 $id,
1120 $mailbox
1121 ){
1122 $me = 'sq_fixatts';
1123 while (list($attname, $attvalue) = each($attary)){
1124 /**
1125 * See if this attribute should be removed.
1126 */
1127 foreach ($rm_attnames as $matchtag=>$matchattrs){
1128 if (preg_match($matchtag, $tagname)){
1129 foreach ($matchattrs as $matchattr){
1130 if (preg_match($matchattr, $attname)){
1131 unset($attary{$attname});
1132 continue;
1133 }
1134 }
1135 }
1136 }
1137 /**
1138 * Remove any entities.
1139 */
1140 $attvalue = sq_deent($attvalue);
1141
1142 /**
1143 * Now let's run checks on the attvalues.
1144 * I don't expect anyone to comprehend this. If you do,
1145 * get in touch with me so I can drive to where you live and
1146 * shake your hand personally. :)
1147 */
1148 foreach ($bad_attvals as $matchtag=>$matchattrs){
1149 if (preg_match($matchtag, $tagname)){
1150 foreach ($matchattrs as $matchattr=>$valary){
1151 if (preg_match($matchattr, $attname)){
1152 /**
1153 * There are two arrays in valary.
1154 * First is matches.
1155 * Second one is replacements
1156 */
1157 list($valmatch, $valrepl) = $valary;
1158 $newvalue =
1159 preg_replace($valmatch, $valrepl, $attvalue);
1160 if ($newvalue != $attvalue){
1161 $attary{$attname} = $newvalue;
1162 }
1163 }
1164 }
1165 }
1166 }
1167 /**
1168 * Turn cid: urls into http-friendly ones.
1169 */
1170 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1171 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1172 }
1173 }
1174 /**
1175 * See if we need to append any attributes to this tag.
1176 */
1177 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1178 if (preg_match($matchtag, $tagname)){
1179 $attary = array_merge($attary, $addattary);
1180 }
1181 }
1182 return $attary;
1183 }
1184
1185 /**
1186 * This function edits the style definition to make them friendly and
1187 * usable in squirrelmail.
1188 *
1189 * @param $message the message object
1190 * @param $id the message id
1191 * @param $content a string with whatever is between <style> and </style>
1192 * @return a string with edited content.
1193 */
1194 function sq_fixstyle($message, $id, $content){
1195 global $view_unsafe_images;
1196 $me = 'sq_fixstyle';
1197 /**
1198 * First look for general BODY style declaration, which would be
1199 * like so:
1200 * body {background: blah-blah}
1201 * and change it to .bodyclass so we can just assign it to a <div>
1202 */
1203 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1204 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1205 /**
1206 * Fix url('blah') declarations.
1207 */
1208 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1209 "url(\\1$secremoveimg\\2)", $content);
1210 /**
1211 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1212 * is false.
1213 */
1214 if (!$view_unsafe_images){
1215 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1216 "url(\\1$secremoveimg\\2)", $content);
1217 }
1218
1219 /**
1220 * Fix urls that refer to cid:
1221 */
1222 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1223 $matches)){
1224 $cidurl = $matches{1};
1225 $httpurl = sq_cid2http($message, $id, $cidurl);
1226 $content = preg_replace("|url\($cidurl\)|si",
1227 "url($httpurl)", $content);
1228 }
1229
1230 /**
1231 * Fix stupid css declarations which lead to vulnerabilities
1232 * in IE.
1233 */
1234 $match = Array('/expression/si',
1235 '/behaviou*r/si',
1236 '/binding/si');
1237 $replace = Array('idiocy', 'idiocy', 'idiocy');
1238 $content = preg_replace($match, $replace, $content);
1239 return $content;
1240 }
1241
1242 /**
1243 * This function converts cid: url's into the ones that can be viewed in
1244 * the browser.
1245 *
1246 * @param $message the message object
1247 * @param $id the message id
1248 * @param $cidurl the cid: url.
1249 * @return a string with a http-friendly url
1250 */
1251 function sq_cid2http($message, $id, $cidurl, $mailbox){
1252 /**
1253 * Get rid of quotes.
1254 */
1255 $quotchar = substr($cidurl, 0, 1);
1256 $cidurl = str_replace($quotchar, "", $cidurl);
1257 $cidurl = substr(trim($cidurl), 4);
1258 $linkurl = find_ent_id($cidurl, $message);
1259 /* in case of non-save cid links $httpurl should be replaced by a sort of
1260 unsave link image */
1261 $httpurl = '';
1262 if ($linkurl) {
1263 $httpurl = $quotchar . '../src/download.php?absolute_dl=true&amp;' .
1264 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
1265 '&amp;ent_id=' . $linkurl . $quotchar;
1266 }
1267 return $httpurl;
1268 }
1269
1270 /**
1271 * This function changes the <body> tag into a <div> tag since we
1272 * can't really have a body-within-body.
1273 *
1274 * @param $attary an array of attributes and values of <body>
1275 * @return a modified array of attributes to be set for <div>
1276 */
1277 function sq_body2div($attary){
1278 $me = 'sq_body2div';
1279 $divattary = Array('class' => "'bodyclass'");
1280 $bgcolor = '#ffffff';
1281 $text = '#000000';
1282 $styledef = '';
1283 if (is_array($attary) && sizeof($attary) > 0){
1284 foreach ($attary as $attname=>$attvalue){
1285 $quotchar = substr($attvalue, 0, 1);
1286 $attvalue = str_replace($quotchar, "", $attvalue);
1287 switch ($attname){
1288 case 'background':
1289 $styledef .= "background-image: url('$attvalue'); ";
1290 break;
1291 case 'bgcolor':
1292 $styledef .= "background-color: $attvalue; ";
1293 break;
1294 case 'text':
1295 $styledef .= "color: $attvalue; ";
1296 break;
1297 }
1298 }
1299 if (strlen($styledef) > 0){
1300 $divattary{"style"} = "\"$styledef\"";
1301 }
1302 }
1303 return $divattary;
1304 }
1305
1306 /**
1307 * This is the main function and the one you should actually be calling.
1308 * There are several variables you should be aware of an which need
1309 * special description.
1310 *
1311 * Since the description is quite lengthy, see it here:
1312 * http://www.mricon.com/html/phpfilter.html
1313 *
1314 * @param $body the string with HTML you wish to filter
1315 * @param $tag_list see description above
1316 * @param $rm_tags_with_content see description above
1317 * @param $self_closing_tags see description above
1318 * @param $force_tag_closing see description above
1319 * @param $rm_attnames see description above
1320 * @param $bad_attvals see description above
1321 * @param $add_attr_to_tag see description above
1322 * @param $message message object
1323 * @param $id message id
1324 * @return sanitized html safe to show on your pages.
1325 */
1326 function sq_sanitize($body,
1327 $tag_list,
1328 $rm_tags_with_content,
1329 $self_closing_tags,
1330 $force_tag_closing,
1331 $rm_attnames,
1332 $bad_attvals,
1333 $add_attr_to_tag,
1334 $message,
1335 $id,
1336 $mailbox
1337 ){
1338 $me = 'sq_sanitize';
1339 /**
1340 * Normalize rm_tags and rm_tags_with_content.
1341 */
1342 @array_walk($rm_tags, 'sq_casenormalize');
1343 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1344 @array_walk($self_closing_tags, 'sq_casenormalize');
1345 /**
1346 * See if tag_list is of tags to remove or tags to allow.
1347 * false means remove these tags
1348 * true means allow these tags
1349 */
1350 $rm_tags = array_shift($tag_list);
1351 $curpos = 0;
1352 $open_tags = Array();
1353 $trusted = "<!-- begin sanitized html -->\n";
1354 $skip_content = false;
1355 /**
1356 * Take care of netscape's stupid javascript entities like
1357 * &{alert('boo')};
1358 */
1359 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
1360
1361 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1362 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1363 $free_content = substr($body, $curpos, $lt-$curpos);
1364 /**
1365 * Take care of <style>
1366 */
1367 if ($tagname == "style" && $tagtype == 2){
1368 /**
1369 * This is a closing </style>. Edit the
1370 * content before we apply it.
1371 */
1372 $free_content = sq_fixstyle($message, $id, $free_content);
1373 }
1374 if ($skip_content == false){
1375 $trusted .= $free_content;
1376 }
1377 if ($tagname != FALSE){
1378 if ($tagtype == 2){
1379 if ($skip_content == $tagname){
1380 /**
1381 * Got to the end of tag we needed to remove.
1382 */
1383 $tagname = false;
1384 $skip_content = false;
1385 } else {
1386 if ($skip_content == false){
1387 if ($tagname == "body"){
1388 $tagname = "div";
1389 } else {
1390 if (isset($open_tags{$tagname}) &&
1391 $open_tags{$tagname} > 0){
1392 $open_tags{$tagname}--;
1393 } else {
1394 $tagname = false;
1395 }
1396 }
1397 }
1398 }
1399 } else {
1400 /**
1401 * $rm_tags_with_content
1402 */
1403 if ($skip_content == false){
1404 /**
1405 * See if this is a self-closing type and change
1406 * tagtype appropriately.
1407 */
1408 if ($tagtype == 1
1409 && in_array($tagname, $self_closing_tags)){
1410 $tagtype=3;
1411 }
1412 /**
1413 * See if we should skip this tag and any content
1414 * inside it.
1415 */
1416 if ($tagtype == 1 &&
1417 in_array($tagname, $rm_tags_with_content)){
1418 $skip_content = $tagname;
1419 } else {
1420 if (($rm_tags == false
1421 && in_array($tagname, $tag_list)) ||
1422 ($rm_tags == true &&
1423 !in_array($tagname, $tag_list))){
1424 $tagname = false;
1425 } else {
1426 if ($tagtype == 1){
1427 if (isset($open_tags{$tagname})){
1428 $open_tags{$tagname}++;
1429 } else {
1430 $open_tags{$tagname}=1;
1431 }
1432 }
1433 /**
1434 * This is where we run other checks.
1435 */
1436 if (is_array($attary) && sizeof($attary) > 0){
1437 $attary = sq_fixatts($tagname,
1438 $attary,
1439 $rm_attnames,
1440 $bad_attvals,
1441 $add_attr_to_tag,
1442 $message,
1443 $id,
1444 $mailbox
1445 );
1446 }
1447 /**
1448 * Convert body into div.
1449 */
1450 if ($tagname == "body"){
1451 $tagname = "div";
1452 $attary = sq_body2div($attary, $message, $id);
1453 }
1454 }
1455 }
1456 }
1457 }
1458 if ($tagname != false && $skip_content == false){
1459 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1460 }
1461 }
1462 $curpos = $gt+1;
1463 }
1464 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1465 if ($force_tag_closing == true){
1466 foreach ($open_tags as $tagname=>$opentimes){
1467 while ($opentimes > 0){
1468 $trusted .= '</' . $tagname . '>';
1469 $opentimes--;
1470 }
1471 }
1472 $trusted .= "\n";
1473 }
1474 $trusted .= "<!-- end sanitized html -->\n";
1475 return $trusted;
1476 }
1477
1478 /**
1479 * This is a wrapper function to call html sanitizing routines.
1480 *
1481 * @param $body the body of the message
1482 * @param $id the id of the message
1483 * @return a string with html safe to display in the browser.
1484 */
1485 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1486 global $attachment_common_show_images, $view_unsafe_images,
1487 $has_unsafe_images;
1488 /**
1489 * Don't display attached images in HTML mode.
1490 */
1491 $attachment_common_show_images = false;
1492 $tag_list = Array(
1493 false,
1494 "object",
1495 "meta",
1496 "html",
1497 "head",
1498 "base",
1499 "link",
1500 "frame",
1501 "iframe"
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 ?>