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