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