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