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