933523b55a66a179f2c35efcc18eeb737d329351
[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 returns the final tag out of the tag name, an array
840 * of attributes, and the type of the tag. This function is called by
841 * sq_sanitize internally.
842 *
843 * @param $tagname the name of the tag.
844 * @param $attary the array of attributes and their values
845 * @param $tagtype The type of the tag (see in comments).
846 * @return a string with the final tag representation.
847 */
848 function sq_tagprint($tagname, $attary, $tagtype){
849 $me = 'sq_tagprint';
850
851 if ($tagtype == 2){
852 $fulltag = '</' . $tagname . '>';
853 } else {
854 $fulltag = '<' . $tagname;
855 if (is_array($attary) && sizeof($attary)){
856 $atts = Array();
857 while (list($attname, $attvalue) = each($attary)){
858 array_push($atts, "$attname=$attvalue");
859 }
860 $fulltag .= ' ' . join(" ", $atts);
861 }
862 if ($tagtype == 3){
863 $fulltag .= ' /';
864 }
865 $fulltag .= '>';
866 }
867 return $fulltag;
868 }
869
870 /**
871 * A small helper function to use with array_walk. Modifies a by-ref
872 * value and makes it lowercase.
873 *
874 * @param $val a value passed by-ref.
875 * @return void since it modifies a by-ref value.
876 */
877 function sq_casenormalize(&$val){
878 $val = strtolower($val);
879 }
880
881 /**
882 * This function skips any whitespace from the current position within
883 * a string and to the next non-whitespace value.
884 *
885 * @param $body the string
886 * @param $offset the offset within the string where we should start
887 * looking for the next non-whitespace character.
888 * @return the location within the $body where the next
889 * non-whitespace char is located.
890 */
891 function sq_skipspace($body, $offset){
892 $me = 'sq_skipspace';
893 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
894 if (sizeof($matches{1})){
895 $count = strlen($matches{1});
896 $offset += $count;
897 }
898 return $offset;
899 }
900
901 /**
902 * This function looks for the next character within a string. It's
903 * really just a glorified "strpos", except it catches if failures
904 * nicely.
905 *
906 * @param $body The string to look for needle in.
907 * @param $offset Start looking from this position.
908 * @param $needle The character/string to look for.
909 * @return location of the next occurance of the needle, or
910 * strlen($body) if needle wasn't found.
911 */
912 function sq_findnxstr($body, $offset, $needle){
913 $me = 'sq_findnxstr';
914 $pos = strpos($body, $needle, $offset);
915 if ($pos === FALSE){
916 $pos = strlen($body);
917 }
918 return $pos;
919 }
920
921 /**
922 * This function takes a PCRE-style regexp and tries to match it
923 * within the string.
924 *
925 * @param $body The string to look for needle in.
926 * @param $offset Start looking from here.
927 * @param $reg A PCRE-style regex to match.
928 * @return Returns a false if no matches found, or an array
929 * with the following members:
930 * - integer with the location of the match within $body
931 * - string with whatever content between offset and the match
932 * - string with whatever it is we matched
933 */
934 function sq_findnxreg($body, $offset, $reg){
935 $me = 'sq_findnxreg';
936 $matches = Array();
937 $retarr = Array();
938 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
939 if (!isset($matches{0}) || !$matches{0}){
940 $retarr = false;
941 } else {
942 $retarr{0} = $offset + strlen($matches{1});
943 $retarr{1} = $matches{1};
944 $retarr{2} = $matches{2};
945 }
946 return $retarr;
947 }
948
949 /**
950 * This function looks for the next tag.
951 *
952 * @param $body String where to look for the next tag.
953 * @param $offset Start looking from here.
954 * @return false if no more tags exist in the body, or
955 * an array with the following members:
956 * - string with the name of the tag
957 * - array with attributes and their values
958 * - integer with tag type (1, 2, or 3)
959 * - integer where the tag starts (starting "<")
960 * - integer where the tag ends (ending ">")
961 * first three members will be false, if the tag is invalid.
962 */
963 function sq_getnxtag($body, $offset){
964 $me = 'sq_getnxtag';
965 if ($offset > strlen($body)){
966 return false;
967 }
968 $lt = sq_findnxstr($body, $offset, "<");
969 if ($lt == strlen($body)){
970 return false;
971 }
972 /**
973 * We are here:
974 * blah blah <tag attribute="value">
975 * \---------^
976 */
977 $pos = sq_skipspace($body, $lt+1);
978 if ($pos >= strlen($body)){
979 return Array(false, false, false, $lt, strlen($body));
980 }
981 /**
982 * There are 3 kinds of tags:
983 * 1. Opening tag, e.g.:
984 * <a href="blah">
985 * 2. Closing tag, e.g.:
986 * </a>
987 * 3. XHTML-style content-less tag, e.g.:
988 * <img src="blah"/>
989 */
990 $tagtype = false;
991 switch (substr($body, $pos, 1)){
992 case '/':
993 $tagtype = 2;
994 $pos++;
995 break;
996 case '!':
997 /**
998 * A comment or an SGML declaration.
999 */
1000 if (substr($body, $pos+1, 2) == "--"){
1001 $gt = strpos($body, "-->", $pos);
1002 if ($gt === false){
1003 $gt = strlen($body);
1004 } else {
1005 $gt += 2;
1006 }
1007 return Array(false, false, false, $lt, $gt);
1008 } else {
1009 $gt = sq_findnxstr($body, $pos, ">");
1010 return Array(false, false, false, $lt, $gt);
1011 }
1012 break;
1013 default:
1014 /**
1015 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1016 * later.
1017 */
1018 $tagtype = 1;
1019 break;
1020 }
1021
1022 $tag_start = $pos;
1023 $tagname = '';
1024 /**
1025 * Look for next [\W-_], which will indicate the end of the tag name.
1026 */
1027 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1028 if ($regary == false){
1029 return Array(false, false, false, $lt, strlen($body));
1030 }
1031 list($pos, $tagname, $match) = $regary;
1032 $tagname = strtolower($tagname);
1033
1034 /**
1035 * $match can be either of these:
1036 * '>' indicating the end of the tag entirely.
1037 * '\s' indicating the end of the tag name.
1038 * '/' indicating that this is type-3 xhtml tag.
1039 *
1040 * Whatever else we find there indicates an invalid tag.
1041 */
1042 switch ($match){
1043 case '/':
1044 /**
1045 * This is an xhtml-style tag with a closing / at the
1046 * end, like so: <img src="blah"/>. Check if it's followed
1047 * by the closing bracket. If not, then this tag is invalid
1048 */
1049 if (substr($body, $pos, 2) == "/>"){
1050 $pos++;
1051 $tagtype = 3;
1052 } else {
1053 $gt = sq_findnxstr($body, $pos, ">");
1054 $retary = Array(false, false, false, $lt, $gt);
1055 return $retary;
1056 }
1057 case '>':
1058 return Array($tagname, false, $tagtype, $lt, $pos);
1059 break;
1060 default:
1061 /**
1062 * Check if it's whitespace
1063 */
1064 if (!preg_match('/\s/', $match)){
1065 /**
1066 * This is an invalid tag! Look for the next closing ">".
1067 */
1068 $gt = sq_findnxstr($body, $lt, ">");
1069 return Array(false, false, false, $lt, $gt);
1070 }
1071 break;
1072 }
1073
1074 /**
1075 * At this point we're here:
1076 * <tagname attribute='blah'>
1077 * \-------^
1078 *
1079 * At this point we loop in order to find all attributes.
1080 */
1081 $attname = '';
1082 $atttype = false;
1083 $attary = Array();
1084
1085 while ($pos <= strlen($body)){
1086 $pos = sq_skipspace($body, $pos);
1087 if ($pos == strlen($body)){
1088 /**
1089 * Non-closed tag.
1090 */
1091 return Array(false, false, false, $lt, $pos);
1092 }
1093 /**
1094 * See if we arrived at a ">" or "/>", which means that we reached
1095 * the end of the tag.
1096 */
1097 $matches = Array();
1098 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1099 /**
1100 * Yep. So we did.
1101 */
1102 $pos += strlen($matches{1});
1103 if ($matches{2} == "/>"){
1104 $tagtype = 3;
1105 $pos++;
1106 }
1107 return Array($tagname, $attary, $tagtype, $lt, $pos);
1108 }
1109
1110 /**
1111 * There are several types of attributes, with optional
1112 * [:space:] between members.
1113 * Type 1:
1114 * attrname[:space:]=[:space:]'CDATA'
1115 * Type 2:
1116 * attrname[:space:]=[:space:]"CDATA"
1117 * Type 3:
1118 * attr[:space:]=[:space:]CDATA
1119 * Type 4:
1120 * attrname
1121 *
1122 * We leave types 1 and 2 the same, type 3 we check for
1123 * '"' and convert to "&quot" if needed, then wrap in
1124 * double quotes. Type 4 we convert into:
1125 * attrname="yes".
1126 */
1127 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1128 if ($regary == false){
1129 /**
1130 * Looks like body ended before the end of tag.
1131 */
1132 return Array(false, false, false, $lt, strlen($body));
1133 }
1134 list($pos, $attname, $match) = $regary;
1135 $attname = strtolower($attname);
1136 /**
1137 * We arrived at the end of attribute name. Several things possible
1138 * here:
1139 * '>' means the end of the tag and this is attribute type 4
1140 * '/' if followed by '>' means the same thing as above
1141 * '\s' means a lot of things -- look what it's followed by.
1142 * anything else means the attribute is invalid.
1143 */
1144 switch($match){
1145 case '/':
1146 /**
1147 * This is an xhtml-style tag with a closing / at the
1148 * end, like so: <img src="blah"/>. Check if it's followed
1149 * by the closing bracket. If not, then this tag is invalid
1150 */
1151 if (substr($body, $pos, 2) == "/>"){
1152 $pos++;
1153 $tagtype = 3;
1154 } else {
1155 $gt = sq_findnxstr($body, $pos, ">");
1156 $retary = Array(false, false, false, $lt, $gt);
1157 return $retary;
1158 }
1159 case '>':
1160 $attary{$attname} = '"yes"';
1161 return Array($tagname, $attary, $tagtype, $lt, $pos);
1162 break;
1163 default:
1164 /**
1165 * Skip whitespace and see what we arrive at.
1166 */
1167 $pos = sq_skipspace($body, $pos);
1168 $char = substr($body, $pos, 1);
1169 /**
1170 * Two things are valid here:
1171 * '=' means this is attribute type 1 2 or 3.
1172 * \w means this was attribute type 4.
1173 * anything else we ignore and re-loop. End of tag and
1174 * invalid stuff will be caught by our checks at the beginning
1175 * of the loop.
1176 */
1177 if ($char == "="){
1178 $pos++;
1179 $pos = sq_skipspace($body, $pos);
1180 /**
1181 * Here are 3 possibilities:
1182 * "'" attribute type 1
1183 * '"' attribute type 2
1184 * everything else is the content of tag type 3
1185 */
1186 $quot = substr($body, $pos, 1);
1187 if ($quot == "'"){
1188 $regary = sq_findnxreg($body, $pos+1, "\'");
1189 if ($regary == false){
1190 return Array(false, false, false, $lt, strlen($body));
1191 }
1192 list($pos, $attval, $match) = $regary;
1193 $pos++;
1194 $attary{$attname} = "'" . $attval . "'";
1195 } else if ($quot == '"'){
1196 $regary = sq_findnxreg($body, $pos+1, '\"');
1197 if ($regary == false){
1198 return Array(false, false, false, $lt, strlen($body));
1199 }
1200 list($pos, $attval, $match) = $regary;
1201 $pos++;
1202 $attary{$attname} = '"' . $attval . '"';
1203 } else {
1204 /**
1205 * These are hateful. Look for \s, or >.
1206 */
1207 $regary = sq_findnxreg($body, $pos, "[\s>]");
1208 if ($regary == false){
1209 return Array(false, false, false, $lt, strlen($body));
1210 }
1211 list($pos, $attval, $match) = $regary;
1212 /**
1213 * If it's ">" it will be caught at the top.
1214 */
1215 $attval = preg_replace("/\"/s", "&quot;", $attval);
1216 $attary{$attname} = '"' . $attval . '"';
1217 }
1218 } else if (preg_match("|[\w/>]|", $char)) {
1219 /**
1220 * That was attribute type 4.
1221 */
1222 $attary{$attname} = '"yes"';
1223 } else {
1224 /**
1225 * An illegal character. Find next '>' and return.
1226 */
1227 $gt = sq_findnxstr($body, $pos, ">");
1228 return Array(false, false, false, $lt, $gt);
1229 }
1230 break;
1231 }
1232 }
1233 /**
1234 * The fact that we got here indicates that the tag end was never
1235 * found. Return invalid tag indication so it gets stripped.
1236 */
1237 return Array(false, false, false, $lt, strlen($body));
1238 }
1239
1240 /**
1241 * This function checks attribute values for entity-encoded values
1242 * and returns them translated into 8-bit strings so we can run
1243 * checks on them.
1244 *
1245 * @param $attvalue A string to run entity check against.
1246 * @return Translated value.
1247 */
1248 function sq_deent($attvalue){
1249 $me = 'sq_deent';
1250 /**
1251 * See if we have to run the checks first. All entities must start
1252 * with "&".
1253 */
1254 if (strpos($attvalue, "&") === false){
1255 return $attvalue;
1256 }
1257 /**
1258 * Check named entities first.
1259 */
1260 $trans = get_html_translation_table(HTML_ENTITIES);
1261 /**
1262 * Leave &quot; in, as it can mess us up.
1263 */
1264 $trans = array_flip($trans);
1265 unset($trans{"&quot;"});
1266 while (list($ent, $val) = each($trans)){
1267 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1268 }
1269 /**
1270 * Now translate numbered entities from 1 to 255 if needed.
1271 */
1272 if (strpos($attvalue, "#") !== false){
1273 $omit = Array(34, 39);
1274 for ($asc=1; $asc<256; $asc++){
1275 if (!in_array($asc, $omit)){
1276 $chr = chr($asc);
1277 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1278 $attvalue);
1279 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1280 "$chr\\1", $attvalue);
1281 }
1282 }
1283 }
1284 return $attvalue;
1285 }
1286
1287 /**
1288 * This function runs various checks against the attributes.
1289 *
1290 * @param $tagname String with the name of the tag.
1291 * @param $attary Array with all tag attributes.
1292 * @param $rm_attnames See description for sq_sanitize
1293 * @param $bad_attvals See description for sq_sanitize
1294 * @param $add_attr_to_tag See description for sq_sanitize
1295 * @param $message message object
1296 * @param $id message id
1297 * @return Array with modified attributes.
1298 */
1299 function sq_fixatts($tagname,
1300 $attary,
1301 $rm_attnames,
1302 $bad_attvals,
1303 $add_attr_to_tag,
1304 $message,
1305 $id,
1306 $mailbox
1307 ){
1308 $me = 'sq_fixatts';
1309 while (list($attname, $attvalue) = each($attary)){
1310 /**
1311 * See if this attribute should be removed.
1312 */
1313 foreach ($rm_attnames as $matchtag=>$matchattrs){
1314 if (preg_match($matchtag, $tagname)){
1315 foreach ($matchattrs as $matchattr){
1316 if (preg_match($matchattr, $attname)){
1317 unset($attary{$attname});
1318 continue;
1319 }
1320 }
1321 }
1322 }
1323 /**
1324 * Remove any entities.
1325 */
1326 $attvalue = sq_deent($attvalue);
1327
1328 /**
1329 * Now let's run checks on the attvalues.
1330 * I don't expect anyone to comprehend this. If you do,
1331 * get in touch with me so I can drive to where you live and
1332 * shake your hand personally. :)
1333 */
1334 foreach ($bad_attvals as $matchtag=>$matchattrs){
1335 if (preg_match($matchtag, $tagname)){
1336 foreach ($matchattrs as $matchattr=>$valary){
1337 if (preg_match($matchattr, $attname)){
1338 /**
1339 * There are two arrays in valary.
1340 * First is matches.
1341 * Second one is replacements
1342 */
1343 list($valmatch, $valrepl) = $valary;
1344 $newvalue =
1345 preg_replace($valmatch, $valrepl, $attvalue);
1346 if ($newvalue != $attvalue){
1347 $attary{$attname} = $newvalue;
1348 }
1349 }
1350 }
1351 }
1352 }
1353 /**
1354 * Turn cid: urls into http-friendly ones.
1355 */
1356 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1357 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1358 }
1359 }
1360 /**
1361 * See if we need to append any attributes to this tag.
1362 */
1363 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1364 if (preg_match($matchtag, $tagname)){
1365 $attary = array_merge($attary, $addattary);
1366 }
1367 }
1368 return $attary;
1369 }
1370
1371 /**
1372 * This function edits the style definition to make them friendly and
1373 * usable in squirrelmail.
1374 *
1375 * @param $message the message object
1376 * @param $id the message id
1377 * @param $content a string with whatever is between <style> and </style>
1378 * @return a string with edited content.
1379 */
1380 function sq_fixstyle($body, $pos, $message, $id){
1381 global $view_unsafe_images;
1382 $me = 'sq_fixstyle';
1383 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1384 if ($ret == FALSE){
1385 return array(FALSE, strlen($body));
1386 }
1387 $newpos = $ret[0] + strlen($ret[2]);
1388 $content = $ret[1];
1389 /**
1390 * First look for general BODY style declaration, which would be
1391 * like so:
1392 * body {background: blah-blah}
1393 * and change it to .bodyclass so we can just assign it to a <div>
1394 */
1395 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1396 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1397 /**
1398 * Fix url('blah') declarations.
1399 */
1400 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1401 "url(\\1$secremoveimg\\2)", $content);
1402 /**
1403 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1404 * is false.
1405 */
1406 if (!$view_unsafe_images){
1407 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1408 "url(\\1$secremoveimg\\2)", $content);
1409 }
1410
1411 /**
1412 * Fix urls that refer to cid:
1413 */
1414 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1415 $content, $matches)){
1416 $cidurl = $matches{1};
1417 $httpurl = sq_cid2http($message, $id, $cidurl);
1418 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1419 "url($httpurl)", $content);
1420 }
1421
1422 /**
1423 * Fix stupid css declarations which lead to vulnerabilities
1424 * in IE.
1425 */
1426 $match = Array('/expression/i',
1427 '/behaviou*r/i',
1428 '/binding/i');
1429 $replace = Array('idiocy', 'idiocy', 'idiocy');
1430 $content = preg_replace($match, $replace, $content);
1431 return array($content, $newpos);
1432 }
1433
1434 /**
1435 * This function converts cid: url's into the ones that can be viewed in
1436 * the browser.
1437 *
1438 * @param $message the message object
1439 * @param $id the message id
1440 * @param $cidurl the cid: url.
1441 * @return a string with a http-friendly url
1442 */
1443 function sq_cid2http($message, $id, $cidurl, $mailbox){
1444 /**
1445 * Get rid of quotes.
1446 */
1447 $quotchar = substr($cidurl, 0, 1);
1448 $cidurl = str_replace($quotchar, "", $cidurl);
1449 $cidurl = substr(trim($cidurl), 4);
1450 $linkurl = find_ent_id($cidurl, $message);
1451 /* in case of non-save cid links $httpurl should be replaced by a sort of
1452 unsave link image */
1453 $httpurl = '';
1454 if ($linkurl) {
1455 $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
1456 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
1457 '&amp;ent_id=' . $linkurl . $quotchar;
1458 }
1459 return $httpurl;
1460 }
1461
1462 /**
1463 * This function changes the <body> tag into a <div> tag since we
1464 * can't really have a body-within-body.
1465 *
1466 * @param $attary an array of attributes and values of <body>
1467 * @return a modified array of attributes to be set for <div>
1468 */
1469 function sq_body2div($attary){
1470 $me = 'sq_body2div';
1471 $divattary = Array('class' => "'bodyclass'");
1472 $bgcolor = '#ffffff';
1473 $text = '#000000';
1474 $styledef = '';
1475 if (is_array($attary) && sizeof($attary) > 0){
1476 foreach ($attary as $attname=>$attvalue){
1477 $quotchar = substr($attvalue, 0, 1);
1478 $attvalue = str_replace($quotchar, "", $attvalue);
1479 switch ($attname){
1480 case 'background':
1481 $styledef .= "background-image: url('$attvalue'); ";
1482 break;
1483 case 'bgcolor':
1484 $styledef .= "background-color: $attvalue; ";
1485 break;
1486 case 'text':
1487 $styledef .= "color: $attvalue; ";
1488 break;
1489 }
1490 }
1491 if (strlen($styledef) > 0){
1492 $divattary{"style"} = "\"$styledef\"";
1493 }
1494 }
1495 return $divattary;
1496 }
1497
1498 /**
1499 * This is the main function and the one you should actually be calling.
1500 * There are several variables you should be aware of an which need
1501 * special description.
1502 *
1503 * Since the description is quite lengthy, see it here:
1504 * http://www.mricon.com/html/phpfilter.html
1505 *
1506 * @param $body the string with HTML you wish to filter
1507 * @param $tag_list see description above
1508 * @param $rm_tags_with_content see description above
1509 * @param $self_closing_tags see description above
1510 * @param $force_tag_closing see description above
1511 * @param $rm_attnames see description above
1512 * @param $bad_attvals see description above
1513 * @param $add_attr_to_tag see description above
1514 * @param $message message object
1515 * @param $id message id
1516 * @return sanitized html safe to show on your pages.
1517 */
1518 function sq_sanitize($body,
1519 $tag_list,
1520 $rm_tags_with_content,
1521 $self_closing_tags,
1522 $force_tag_closing,
1523 $rm_attnames,
1524 $bad_attvals,
1525 $add_attr_to_tag,
1526 $message,
1527 $id,
1528 $mailbox
1529 ){
1530 $me = 'sq_sanitize';
1531 $rm_tags = array_shift($tag_list);
1532 /**
1533 * Normalize rm_tags and rm_tags_with_content.
1534 */
1535 @array_walk($tag_list, 'sq_casenormalize');
1536 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1537 @array_walk($self_closing_tags, 'sq_casenormalize');
1538 /**
1539 * See if tag_list is of tags to remove or tags to allow.
1540 * false means remove these tags
1541 * true means allow these tags
1542 */
1543 $curpos = 0;
1544 $open_tags = Array();
1545 $trusted = "<!-- begin sanitized html -->\n";
1546 $skip_content = false;
1547 /**
1548 * Take care of netscape's stupid javascript entities like
1549 * &{alert('boo')};
1550 */
1551 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
1552
1553 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1554 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1555 $free_content = substr($body, $curpos, $lt-$curpos);
1556 /**
1557 * Take care of <style>
1558 */
1559 if ($tagname == "style" && $tagtype == 1){
1560 list($free_content, $curpos) =
1561 sq_fixstyle($body, $gt+1, $message, $id);
1562 if ($free_content != FALSE){
1563 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1564 $trusted .= $free_content;
1565 $trusted .= sq_tagprint($tagname, false, 2);
1566 }
1567 continue;
1568 }
1569 if ($skip_content == false){
1570 $trusted .= $free_content;
1571 }
1572 if ($tagname != FALSE){
1573 if ($tagtype == 2){
1574 if ($skip_content == $tagname){
1575 /**
1576 * Got to the end of tag we needed to remove.
1577 */
1578 $tagname = false;
1579 $skip_content = false;
1580 } else {
1581 if ($skip_content == false){
1582 if ($tagname == "body"){
1583 $tagname = "div";
1584 } else {
1585 if (isset($open_tags{$tagname}) &&
1586 $open_tags{$tagname} > 0){
1587 $open_tags{$tagname}--;
1588 } else {
1589 $tagname = false;
1590 }
1591 }
1592 }
1593 }
1594 } else {
1595 /**
1596 * $rm_tags_with_content
1597 */
1598 if ($skip_content == false){
1599 /**
1600 * See if this is a self-closing type and change
1601 * tagtype appropriately.
1602 */
1603 if ($tagtype == 1
1604 && in_array($tagname, $self_closing_tags)){
1605 $tagtype=3;
1606 }
1607 /**
1608 * See if we should skip this tag and any content
1609 * inside it.
1610 */
1611 if ($tagtype == 1 &&
1612 in_array($tagname, $rm_tags_with_content)){
1613 $skip_content = $tagname;
1614 } else {
1615 if (($rm_tags == false
1616 && in_array($tagname, $tag_list)) ||
1617 ($rm_tags == true &&
1618 !in_array($tagname, $tag_list))){
1619 $tagname = false;
1620 } else {
1621 if ($tagtype == 1){
1622 if (isset($open_tags{$tagname})){
1623 $open_tags{$tagname}++;
1624 } else {
1625 $open_tags{$tagname}=1;
1626 }
1627 }
1628 /**
1629 * This is where we run other checks.
1630 */
1631 if (is_array($attary) && sizeof($attary) > 0){
1632 $attary = sq_fixatts($tagname,
1633 $attary,
1634 $rm_attnames,
1635 $bad_attvals,
1636 $add_attr_to_tag,
1637 $message,
1638 $id,
1639 $mailbox
1640 );
1641 }
1642 /**
1643 * Convert body into div.
1644 */
1645 if ($tagname == "body"){
1646 $tagname = "div";
1647 $attary = sq_body2div($attary, $message, $id);
1648 }
1649 }
1650 }
1651 }
1652 }
1653 if ($tagname != false && $skip_content == false){
1654 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1655 }
1656 }
1657 $curpos = $gt+1;
1658 }
1659 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1660 if ($force_tag_closing == true){
1661 foreach ($open_tags as $tagname=>$opentimes){
1662 while ($opentimes > 0){
1663 $trusted .= '</' . $tagname . '>';
1664 $opentimes--;
1665 }
1666 }
1667 $trusted .= "\n";
1668 }
1669 $trusted .= "<!-- end sanitized html -->\n";
1670 return $trusted;
1671 }
1672
1673 /**
1674 * This is a wrapper function to call html sanitizing routines.
1675 *
1676 * @param $body the body of the message
1677 * @param $id the id of the message
1678 * @return a string with html safe to display in the browser.
1679 */
1680 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1681 global $attachment_common_show_images, $view_unsafe_images,
1682 $has_unsafe_images;
1683 /**
1684 * Don't display attached images in HTML mode.
1685 */
1686 $attachment_common_show_images = false;
1687 $tag_list = Array(
1688 false,
1689 "object",
1690 "meta",
1691 "html",
1692 "head",
1693 "base",
1694 "link",
1695 "frame",
1696 "iframe"
1697 );
1698
1699 $rm_tags_with_content = Array(
1700 "script",
1701 "applet",
1702 "embed",
1703 "title"
1704 );
1705
1706 $self_closing_tags = Array(
1707 "img",
1708 "br",
1709 "hr",
1710 "input"
1711 );
1712
1713 $force_tag_closing = false;
1714
1715 $rm_attnames = Array(
1716 "/.*/" =>
1717 Array(
1718 "/target/i",
1719 "/^on.*/i",
1720 "/^dynsrc/i",
1721 "/^data.*/i",
1722 "/^lowsrc.*/i"
1723 )
1724 );
1725
1726 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1727 $bad_attvals = Array(
1728 "/.*/" =>
1729 Array(
1730 "/^src|background/i" =>
1731 Array(
1732 Array(
1733 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1734 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1735 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1736 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1737 ),
1738 Array(
1739 "\\1$secremoveimg\\2",
1740 "\\1$secremoveimg\\2",
1741 "\\1$secremoveimg\\2",
1742 "\\1$secremoveimg\\2"
1743 )
1744 ),
1745 "/^href|action/i" =>
1746 Array(
1747 Array(
1748 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1749 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1750 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1751 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1752 ),
1753 Array(
1754 "\\1#\\2",
1755 "\\1#\\2",
1756 "\\1#\\2",
1757 "\\1#\\2"
1758 )
1759 ),
1760 "/^style/i" =>
1761 Array(
1762 Array(
1763 "/expression/i",
1764 "/binding/i",
1765 "/behaviou*r/i",
1766 "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
1767 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1768 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1769 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
1770 ),
1771 Array(
1772 "idiocy",
1773 "idiocy",
1774 "idiocy",
1775 "url(\\1#\\2)",
1776 "url(\\1#\\2)",
1777 "url(\\1#\\2)",
1778 "url(\\1#\\2)"
1779 )
1780 )
1781 )
1782 );
1783 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
1784 $view_unsafe_images = false;
1785 }
1786 if (!$view_unsafe_images){
1787 /**
1788 * Remove any references to http/https if view_unsafe_images set
1789 * to false.
1790 */
1791 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1792 '/^([\'\"])\s*https*:.*([\'\"])/si');
1793 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1794 "\\1$secremoveimg\\2");
1795 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1796 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1797 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1798 "url(\\1$secremoveimg\\2)");
1799 }
1800
1801 $add_attr_to_tag = Array(
1802 "/^a$/i" => Array('target'=>'"_new"')
1803 );
1804 $trusted = sq_sanitize($body,
1805 $tag_list,
1806 $rm_tags_with_content,
1807 $self_closing_tags,
1808 $force_tag_closing,
1809 $rm_attnames,
1810 $bad_attvals,
1811 $add_attr_to_tag,
1812 $message,
1813 $id,
1814 $mailbox
1815 );
1816 if (preg_match("|$secremoveimg|i", $trusted)){
1817 $has_unsafe_images = true;
1818 }
1819 return $trusted;
1820 }
1821
1822 ?>