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