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