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