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