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