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