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