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