5491e91d2de2c1ed10664df33debcc233205a5a3
[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 = $from_o->getAddress(false);
445 } else {
446 $from_name = _("Unknown sender");
447 }
448 $from_name = decodeHeader(($from_name));
449 $description = $from_name;
450 } else {
451 $default_page = SM_PATH . 'src/download.php';
452 if (is_object($header->disposition)) {
453 $filename = $header->disposition->getProperty('filename');
454 if (trim($filename) == '') {
455 $name = decodeHeader($header->disposition->getProperty('name'));
456 if (trim($name) == '') {
457 $name = $header->getParameter('name');
458 if(trim($name) == '') {
459 if (trim( $header->id ) == '') {
460 $filename = 'untitled-[' . $ent . ']' ;
461 } else {
462 $filename = 'cid: ' . $header->id;
463 }
464 } else {
465 $filename = $name;
466 }
467 } else {
468 $filename = $name;
469 }
470 }
471 } else {
472 $filename = $header->getParameter('name');
473 if (!trim($filename)) {
474 if (trim( $header->id ) == '') {
475 $filename = 'untitled-[' . $ent . ']' ;
476 } else {
477 $filename = 'cid: ' . $header->id;
478 }
479 }
480 }
481 if ($header->description) {
482 $description = decodeHeader($header->description);
483 } else {
484 $description = '';
485 }
486 }
487
488 $display_filename = $filename;
489 if (isset($passed_ent_id)) {
490 $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
491 } else {
492 $passed_ent_id_link = '';
493 }
494 $defaultlink = $default_page . "?startMessage=$startMessage"
495 . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
496 . '&amp;ent_id='.$ent.$passed_ent_id_link;
497 if ($where && $what) {
498 $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
499 }
500 /* This executes the attachment hook with a specific MIME-type.
501 * If that doesn't have results, it tries if there's a rule
502 * for a more generic type.
503 */
504 $hookresults = do_hook("attachment $type0/$type1", $links,
505 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
506 $display_filename, $where, $what);
507 if(count($hookresults[1]) <= 1) {
508 $hookresults = do_hook("attachment $type0/*", $links,
509 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
510 $display_filename, $where, $what);
511 }
512
513 $links = $hookresults[1];
514 $defaultlink = $hookresults[6];
515
516 $attachments .= '<TR><TD>' .
517 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A>&nbsp;</TD>' .
518 '<TD><SMALL><b>' . show_readable_size($header->size) .
519 '</b>&nbsp;&nbsp;</small></TD>' .
520 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
521 '<TD><SMALL>';
522 $attachments .= '<b>' . $description . '</b>';
523 $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
524
525 $skipspaces = 1;
526 foreach ($links as $val) {
527 if ($skipspaces) {
528 $skipspaces = 0;
529 } else {
530 $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
531 }
532 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
533 }
534 unset($links);
535 $attachments .= "</TD></TR>\n";
536 }
537 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
538 if ($attachmentadd != '')
539 $attachments = $attachmentadd;
540 return $attachments;
541 }
542
543 function sqimap_base64_decode(&$string) {
544 $string = str_replace("\r\n", "\n", $string);
545 $string = base64_decode($string);
546 }
547
548 /* This function decodes the body depending on the encoding type. */
549 function decodeBody($body, $encoding) {
550 global $show_html_default;
551
552 $body = str_replace("\r\n", "\n", $body);
553 $encoding = strtolower($encoding);
554
555 if ($encoding == 'quoted-printable' ||
556 $encoding == 'quoted_printable') {
557 $body = quoted_printable_decode($body);
558
559 while (ereg("=\n", $body)) {
560 $body = ereg_replace ("=\n", '', $body);
561 }
562
563 } else if ($encoding == 'base64') {
564 $body = base64_decode($body);
565 }
566
567 // All other encodings are returned raw.
568 return $body;
569 }
570
571 /*
572 * This functions decode strings that is encoded according to
573 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
574 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
575 */
576 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
577 global $languages, $squirrelmail_language;
578 if (is_array($string)) {
579 $string = implode("\n", $string);
580 }
581
582 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
583 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
584 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
585 // Do we need to return at this point?
586 // return $string;
587 }
588 $i = 0;
589 $iLastMatch = -2;
590 $encoded = false;
591
592 $aString = explode(' ',$string);
593 $ret = '';
594 foreach ($aString as $chunk) {
595 if ($encoded && $chunk === ' ') {
596 continue;
597 } elseif ($chunk === ' ') {
598 $ret .= ' ';
599 continue;
600 }
601 $encoded = false;
602 /* if encoded words are not separated by a linear-space-white we still catch them */
603 $j = $i-1;
604 // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
605 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
606 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
607 if ($iLastMatch !== $j) {
608 if ($htmlsave) {
609 $ret .= '&nbsp;';
610 } else {
611 $ret .= ' ';
612 }
613 }
614 $iLastMatch = $i;
615 $j = $i;
616 $ret .= $res[1];
617 $encoding = ucfirst($res[3]);
618 switch ($encoding)
619 {
620 case 'B':
621 $replace = base64_decode($res[4]);
622 $ret .= charset_decode($res[2],$replace);
623 break;
624 case 'Q':
625 $replace = str_replace('_', ' ', $res[4]);
626 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
627 $replace);
628 /* Only encode into entities by default. Some places
629 * don't need the encoding, like the compose form.
630 */
631 if ($utfencode) {
632 $replace = charset_decode($res[2], $replace);
633 } else {
634 if ($htmlsave) {
635 $replace = htmlspecialchars($replace);
636 }
637 }
638 $ret .= $replace;
639 break;
640 default:
641 break;
642 }
643 $chunk = $res[5];
644 $encoded = true;
645 }
646 // }
647 if (!$encoded) {
648 if ($htmlsave) {
649 $ret .= '&nbsp;';
650 } else {
651 $ret .= ' ';
652 }
653 }
654
655 if (!$encoded && $htmlsave) {
656 $ret .= htmlspecialchars($chunk);
657 } else {
658 $ret .= $chunk;
659 }
660 ++$i;
661 }
662 /* remove the first added space */
663 if ($ret) {
664 if ($htmlsave) {
665 $ret = substr($ret,6);
666 } else {
667 $ret = substr($ret,1);
668 }
669 }
670
671 return $ret;
672 }
673
674 /*
675 * Encode a string according to RFC 1522 for use in headers if it
676 * contains 8-bit characters or anything that looks like it should
677 * be encoded.
678 */
679 function encodeHeader ($string) {
680 global $default_charset, $languages, $squirrelmail_language;
681
682 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
683 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
684 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
685 }
686 if (strtolower($default_charset) == 'iso-8859-1') {
687 $string = str_replace("\240",' ',$string);
688 }
689
690 // Encode only if the string contains 8-bit characters or =?
691 $j = strlen($string);
692 $max_l = 75 - strlen($default_charset) - 7;
693 $aRet = array();
694 $ret = '';
695 $iEncStart = $enc_init = false;
696 $cur_l = $iOffset = 0;
697 for($i = 0; $i < $j; ++$i) {
698 switch($string{$i})
699 {
700 case '=':
701 case '<':
702 case '>':
703 case ',':
704 case '?':
705 case '_':
706 if ($iEncStart === false) {
707 $iEncStart = $i;
708 }
709 $cur_l+=3;
710 if ($cur_l > ($max_l-2)) {
711 /* if there is an stringpart that doesn't need encoding, add it */
712 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
713 $aRet[] = "=?$default_charset?Q?$ret?=";
714 $iOffset = $i;
715 $cur_l = 0;
716 $ret = '';
717 $iEncStart = false;
718 } else {
719 $ret .= sprintf("=%02X",ord($string{$i}));
720 }
721 break;
722 case '(':
723 case ')':
724 if ($iEncStart !== false) {
725 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
726 $aRet[] = "=?$default_charset?Q?$ret?=";
727 $iOffset = $i;
728 $cur_l = 0;
729 $ret = '';
730 $iEncStart = false;
731 }
732 break;
733 case ' ':
734 if ($iEncStart !== false) {
735 $cur_l++;
736 if ($cur_l > $max_l) {
737 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
738 $aRet[] = "=?$default_charset?Q?$ret?=";
739 $iOffset = $i;
740 $cur_l = 0;
741 $ret = '';
742 $iEncStart = false;
743 } else {
744 $ret .= '_';
745 }
746 }
747 break;
748 default:
749 $k = ord($string{$i});
750 if ($k > 126) {
751 if ($iEncStart === false) {
752 // do not start encoding in the middle of a string, also take the rest of the word.
753 $sLeadString = substr($string,0,$i);
754 $aLeadString = explode(' ',$sLeadString);
755 $sToBeEncoded = array_pop($aLeadString);
756 $iEncStart = $i - strlen($sToBeEncoded);
757 $ret .= $sToBeEncoded;
758 $cur_l += strlen($sToBeEncoded);
759 }
760 $cur_l += 3;
761 /* first we add the encoded string that reached it's max size */
762 if ($cur_l > ($max_l-2)) {
763 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
764 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
765 $cur_l = 3;
766 $ret = '';
767 $iOffset = $i;
768 $iEncStart = $i;
769 }
770 $enc_init = true;
771 $ret .= sprintf("=%02X", $k);
772 } else {
773 if ($iEncStart !== false) {
774 $cur_l++;
775 if ($cur_l > $max_l) {
776 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
777 $aRet[] = "=?$default_charset?Q?$ret?=";
778 $iEncStart = false;
779 $iOffset = $i;
780 $cur_l = 0;
781 $ret = '';
782 } else {
783 $ret .= $string{$i};
784 }
785 }
786 }
787 break;
788 }
789 }
790
791 if ($enc_init) {
792 if ($iEncStart !== false) {
793 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
794 $aRet[] = "=?$default_charset?Q?$ret?=";
795 } else {
796 $aRet[] = substr($string,$iOffset);
797 }
798 $string = implode('',$aRet);
799 }
800 return $string;
801 }
802
803 /* This function trys to locate the entity_id of a specific mime element */
804 function find_ent_id($id, $message) {
805 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
806 if ($message->entities[$i]->header->type0 == 'multipart') {
807 $ret = find_ent_id($id, $message->entities[$i]);
808 } else {
809 if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
810 // if (sq_check_save_extension($message->entities[$i])) {
811 return $message->entities[$i]->entity_id;
812 // }
813 }
814 }
815 }
816 return $ret;
817 }
818
819 function sq_check_save_extension($message) {
820 $filename = $message->getFilename();
821 $ext = substr($filename, strrpos($filename,'.')+1);
822 $save_extensions = array('jpg','jpeg','gif','png','bmp');
823 return in_array($ext, $save_extensions);
824 }
825
826
827 /**
828 ** HTMLFILTER ROUTINES
829 */
830
831 /**
832 * This function returns the final tag out of the tag name, an array
833 * of attributes, and the type of the tag. This function is called by
834 * sq_sanitize internally.
835 *
836 * @param $tagname the name of the tag.
837 * @param $attary the array of attributes and their values
838 * @param $tagtype The type of the tag (see in comments).
839 * @return a string with the final tag representation.
840 */
841 function sq_tagprint($tagname, $attary, $tagtype){
842 $me = 'sq_tagprint';
843
844 if ($tagtype == 2){
845 $fulltag = '</' . $tagname . '>';
846 } else {
847 $fulltag = '<' . $tagname;
848 if (is_array($attary) && sizeof($attary)){
849 $atts = Array();
850 while (list($attname, $attvalue) = each($attary)){
851 array_push($atts, "$attname=$attvalue");
852 }
853 $fulltag .= ' ' . join(" ", $atts);
854 }
855 if ($tagtype == 3){
856 $fulltag .= ' /';
857 }
858 $fulltag .= '>';
859 }
860 return $fulltag;
861 }
862
863 /**
864 * A small helper function to use with array_walk. Modifies a by-ref
865 * value and makes it lowercase.
866 *
867 * @param $val a value passed by-ref.
868 * @return void since it modifies a by-ref value.
869 */
870 function sq_casenormalize(&$val){
871 $val = strtolower($val);
872 }
873
874 /**
875 * This function skips any whitespace from the current position within
876 * a string and to the next non-whitespace value.
877 *
878 * @param $body the string
879 * @param $offset the offset within the string where we should start
880 * looking for the next non-whitespace character.
881 * @return the location within the $body where the next
882 * non-whitespace char is located.
883 */
884 function sq_skipspace($body, $offset){
885 $me = 'sq_skipspace';
886 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
887 if (sizeof($matches{1})){
888 $count = strlen($matches{1});
889 $offset += $count;
890 }
891 return $offset;
892 }
893
894 /**
895 * This function looks for the next character within a string. It's
896 * really just a glorified "strpos", except it catches if failures
897 * nicely.
898 *
899 * @param $body The string to look for needle in.
900 * @param $offset Start looking from this position.
901 * @param $needle The character/string to look for.
902 * @return location of the next occurance of the needle, or
903 * strlen($body) if needle wasn't found.
904 */
905 function sq_findnxstr($body, $offset, $needle){
906 $me = 'sq_findnxstr';
907 $pos = strpos($body, $needle, $offset);
908 if ($pos === FALSE){
909 $pos = strlen($body);
910 }
911 return $pos;
912 }
913
914 /**
915 * This function takes a PCRE-style regexp and tries to match it
916 * within the string.
917 *
918 * @param $body The string to look for needle in.
919 * @param $offset Start looking from here.
920 * @param $reg A PCRE-style regex to match.
921 * @return Returns a false if no matches found, or an array
922 * with the following members:
923 * - integer with the location of the match within $body
924 * - string with whatever content between offset and the match
925 * - string with whatever it is we matched
926 */
927 function sq_findnxreg($body, $offset, $reg){
928 $me = 'sq_findnxreg';
929 $matches = Array();
930 $retarr = Array();
931 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
932 if (!isset($matches{0}) || !$matches{0}){
933 $retarr = false;
934 } else {
935 $retarr{0} = $offset + strlen($matches{1});
936 $retarr{1} = $matches{1};
937 $retarr{2} = $matches{2};
938 }
939 return $retarr;
940 }
941
942 /**
943 * This function looks for the next tag.
944 *
945 * @param $body String where to look for the next tag.
946 * @param $offset Start looking from here.
947 * @return false if no more tags exist in the body, or
948 * an array with the following members:
949 * - string with the name of the tag
950 * - array with attributes and their values
951 * - integer with tag type (1, 2, or 3)
952 * - integer where the tag starts (starting "<")
953 * - integer where the tag ends (ending ">")
954 * first three members will be false, if the tag is invalid.
955 */
956 function sq_getnxtag($body, $offset){
957 $me = 'sq_getnxtag';
958 if ($offset > strlen($body)){
959 return false;
960 }
961 $lt = sq_findnxstr($body, $offset, "<");
962 if ($lt == strlen($body)){
963 return false;
964 }
965 /**
966 * We are here:
967 * blah blah <tag attribute="value">
968 * \---------^
969 */
970 $pos = sq_skipspace($body, $lt+1);
971 if ($pos >= strlen($body)){
972 return Array(false, false, false, $lt, strlen($body));
973 }
974 /**
975 * There are 3 kinds of tags:
976 * 1. Opening tag, e.g.:
977 * <a href="blah">
978 * 2. Closing tag, e.g.:
979 * </a>
980 * 3. XHTML-style content-less tag, e.g.:
981 * <img src="blah"/>
982 */
983 $tagtype = false;
984 switch (substr($body, $pos, 1)){
985 case '/':
986 $tagtype = 2;
987 $pos++;
988 break;
989 case '!':
990 /**
991 * A comment or an SGML declaration.
992 */
993 if (substr($body, $pos+1, 2) == "--"){
994 $gt = strpos($body, "-->", $pos);
995 if ($gt === false){
996 $gt = strlen($body);
997 } else {
998 $gt += 2;
999 }
1000 return Array(false, false, false, $lt, $gt);
1001 } else {
1002 $gt = sq_findnxstr($body, $pos, ">");
1003 return Array(false, false, false, $lt, $gt);
1004 }
1005 break;
1006 default:
1007 /**
1008 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1009 * later.
1010 */
1011 $tagtype = 1;
1012 break;
1013 }
1014
1015 $tag_start = $pos;
1016 $tagname = '';
1017 /**
1018 * Look for next [\W-_], which will indicate the end of the tag name.
1019 */
1020 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1021 if ($regary == false){
1022 return Array(false, false, false, $lt, strlen($body));
1023 }
1024 list($pos, $tagname, $match) = $regary;
1025 $tagname = strtolower($tagname);
1026
1027 /**
1028 * $match can be either of these:
1029 * '>' indicating the end of the tag entirely.
1030 * '\s' indicating the end of the tag name.
1031 * '/' indicating that this is type-3 xhtml tag.
1032 *
1033 * Whatever else we find there indicates an invalid tag.
1034 */
1035 switch ($match){
1036 case '/':
1037 /**
1038 * This is an xhtml-style tag with a closing / at the
1039 * end, like so: <img src="blah"/>. Check if it's followed
1040 * by the closing bracket. If not, then this tag is invalid
1041 */
1042 if (substr($body, $pos, 2) == "/>"){
1043 $pos++;
1044 $tagtype = 3;
1045 } else {
1046 $gt = sq_findnxstr($body, $pos, ">");
1047 $retary = Array(false, false, false, $lt, $gt);
1048 return $retary;
1049 }
1050 case '>':
1051 return Array($tagname, false, $tagtype, $lt, $pos);
1052 break;
1053 default:
1054 /**
1055 * Check if it's whitespace
1056 */
1057 if (!preg_match('/\s/', $match)){
1058 /**
1059 * This is an invalid tag! Look for the next closing ">".
1060 */
1061 $gt = sq_findnxstr($body, $lt, ">");
1062 return Array(false, false, false, $lt, $gt);
1063 }
1064 break;
1065 }
1066
1067 /**
1068 * At this point we're here:
1069 * <tagname attribute='blah'>
1070 * \-------^
1071 *
1072 * At this point we loop in order to find all attributes.
1073 */
1074 $attname = '';
1075 $atttype = false;
1076 $attary = Array();
1077
1078 while ($pos <= strlen($body)){
1079 $pos = sq_skipspace($body, $pos);
1080 if ($pos == strlen($body)){
1081 /**
1082 * Non-closed tag.
1083 */
1084 return Array(false, false, false, $lt, $pos);
1085 }
1086 /**
1087 * See if we arrived at a ">" or "/>", which means that we reached
1088 * the end of the tag.
1089 */
1090 $matches = Array();
1091 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1092 /**
1093 * Yep. So we did.
1094 */
1095 $pos += strlen($matches{1});
1096 if ($matches{2} == "/>"){
1097 $tagtype = 3;
1098 $pos++;
1099 }
1100 return Array($tagname, $attary, $tagtype, $lt, $pos);
1101 }
1102
1103 /**
1104 * There are several types of attributes, with optional
1105 * [:space:] between members.
1106 * Type 1:
1107 * attrname[:space:]=[:space:]'CDATA'
1108 * Type 2:
1109 * attrname[:space:]=[:space:]"CDATA"
1110 * Type 3:
1111 * attr[:space:]=[:space:]CDATA
1112 * Type 4:
1113 * attrname
1114 *
1115 * We leave types 1 and 2 the same, type 3 we check for
1116 * '"' and convert to "&quot" if needed, then wrap in
1117 * double quotes. Type 4 we convert into:
1118 * attrname="yes".
1119 */
1120 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1121 if ($regary == false){
1122 /**
1123 * Looks like body ended before the end of tag.
1124 */
1125 return Array(false, false, false, $lt, strlen($body));
1126 }
1127 list($pos, $attname, $match) = $regary;
1128 $attname = strtolower($attname);
1129 /**
1130 * We arrived at the end of attribute name. Several things possible
1131 * here:
1132 * '>' means the end of the tag and this is attribute type 4
1133 * '/' if followed by '>' means the same thing as above
1134 * '\s' means a lot of things -- look what it's followed by.
1135 * anything else means the attribute is invalid.
1136 */
1137 switch($match){
1138 case '/':
1139 /**
1140 * This is an xhtml-style tag with a closing / at the
1141 * end, like so: <img src="blah"/>. Check if it's followed
1142 * by the closing bracket. If not, then this tag is invalid
1143 */
1144 if (substr($body, $pos, 2) == "/>"){
1145 $pos++;
1146 $tagtype = 3;
1147 } else {
1148 $gt = sq_findnxstr($body, $pos, ">");
1149 $retary = Array(false, false, false, $lt, $gt);
1150 return $retary;
1151 }
1152 case '>':
1153 $attary{$attname} = '"yes"';
1154 return Array($tagname, $attary, $tagtype, $lt, $pos);
1155 break;
1156 default:
1157 /**
1158 * Skip whitespace and see what we arrive at.
1159 */
1160 $pos = sq_skipspace($body, $pos);
1161 $char = substr($body, $pos, 1);
1162 /**
1163 * Two things are valid here:
1164 * '=' means this is attribute type 1 2 or 3.
1165 * \w means this was attribute type 4.
1166 * anything else we ignore and re-loop. End of tag and
1167 * invalid stuff will be caught by our checks at the beginning
1168 * of the loop.
1169 */
1170 if ($char == "="){
1171 $pos++;
1172 $pos = sq_skipspace($body, $pos);
1173 /**
1174 * Here are 3 possibilities:
1175 * "'" attribute type 1
1176 * '"' attribute type 2
1177 * everything else is the content of tag type 3
1178 */
1179 $quot = substr($body, $pos, 1);
1180 if ($quot == "'"){
1181 $regary = sq_findnxreg($body, $pos+1, "\'");
1182 if ($regary == false){
1183 return Array(false, false, false, $lt, strlen($body));
1184 }
1185 list($pos, $attval, $match) = $regary;
1186 $pos++;
1187 $attary{$attname} = "'" . $attval . "'";
1188 } else if ($quot == '"'){
1189 $regary = sq_findnxreg($body, $pos+1, '\"');
1190 if ($regary == false){
1191 return Array(false, false, false, $lt, strlen($body));
1192 }
1193 list($pos, $attval, $match) = $regary;
1194 $pos++;
1195 $attary{$attname} = '"' . $attval . '"';
1196 } else {
1197 /**
1198 * These are hateful. Look for \s, or >.
1199 */
1200 $regary = sq_findnxreg($body, $pos, "[\s>]");
1201 if ($regary == false){
1202 return Array(false, false, false, $lt, strlen($body));
1203 }
1204 list($pos, $attval, $match) = $regary;
1205 /**
1206 * If it's ">" it will be caught at the top.
1207 */
1208 $attval = preg_replace("/\"/s", "&quot;", $attval);
1209 $attary{$attname} = '"' . $attval . '"';
1210 }
1211 } else if (preg_match("|[\w/>]|", $char)) {
1212 /**
1213 * That was attribute type 4.
1214 */
1215 $attary{$attname} = '"yes"';
1216 } else {
1217 /**
1218 * An illegal character. Find next '>' and return.
1219 */
1220 $gt = sq_findnxstr($body, $pos, ">");
1221 return Array(false, false, false, $lt, $gt);
1222 }
1223 break;
1224 }
1225 }
1226 /**
1227 * The fact that we got here indicates that the tag end was never
1228 * found. Return invalid tag indication so it gets stripped.
1229 */
1230 return Array(false, false, false, $lt, strlen($body));
1231 }
1232
1233 /**
1234 * This function checks attribute values for entity-encoded values
1235 * and returns them translated into 8-bit strings so we can run
1236 * checks on them.
1237 *
1238 * @param $attvalue A string to run entity check against.
1239 * @return Translated value.
1240 */
1241 function sq_deent($attvalue){
1242 $me = 'sq_deent';
1243 /**
1244 * See if we have to run the checks first. All entities must start
1245 * with "&".
1246 */
1247 if (strpos($attvalue, "&") === false){
1248 return $attvalue;
1249 }
1250 /**
1251 * Check named entities first.
1252 */
1253 $trans = get_html_translation_table(HTML_ENTITIES);
1254 /**
1255 * Leave &quot; in, as it can mess us up.
1256 */
1257 $trans = array_flip($trans);
1258 unset($trans{"&quot;"});
1259 while (list($ent, $val) = each($trans)){
1260 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1261 }
1262 /**
1263 * Now translate numbered entities from 1 to 255 if needed.
1264 */
1265 if (strpos($attvalue, "#") !== false){
1266 $omit = Array(34, 39);
1267 for ($asc=1; $asc<256; $asc++){
1268 if (!in_array($asc, $omit)){
1269 $chr = chr($asc);
1270 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1271 $attvalue);
1272 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1273 "$chr\\1", $attvalue);
1274 }
1275 }
1276 }
1277 return $attvalue;
1278 }
1279
1280 /**
1281 * This function runs various checks against the attributes.
1282 *
1283 * @param $tagname String with the name of the tag.
1284 * @param $attary Array with all tag attributes.
1285 * @param $rm_attnames See description for sq_sanitize
1286 * @param $bad_attvals See description for sq_sanitize
1287 * @param $add_attr_to_tag See description for sq_sanitize
1288 * @param $message message object
1289 * @param $id message id
1290 * @return Array with modified attributes.
1291 */
1292 function sq_fixatts($tagname,
1293 $attary,
1294 $rm_attnames,
1295 $bad_attvals,
1296 $add_attr_to_tag,
1297 $message,
1298 $id,
1299 $mailbox
1300 ){
1301 $me = 'sq_fixatts';
1302 while (list($attname, $attvalue) = each($attary)){
1303 /**
1304 * See if this attribute should be removed.
1305 */
1306 foreach ($rm_attnames as $matchtag=>$matchattrs){
1307 if (preg_match($matchtag, $tagname)){
1308 foreach ($matchattrs as $matchattr){
1309 if (preg_match($matchattr, $attname)){
1310 unset($attary{$attname});
1311 continue;
1312 }
1313 }
1314 }
1315 }
1316 /**
1317 * Remove any entities.
1318 */
1319 $attvalue = sq_deent($attvalue);
1320
1321 /**
1322 * Now let's run checks on the attvalues.
1323 * I don't expect anyone to comprehend this. If you do,
1324 * get in touch with me so I can drive to where you live and
1325 * shake your hand personally. :)
1326 */
1327 foreach ($bad_attvals as $matchtag=>$matchattrs){
1328 if (preg_match($matchtag, $tagname)){
1329 foreach ($matchattrs as $matchattr=>$valary){
1330 if (preg_match($matchattr, $attname)){
1331 /**
1332 * There are two arrays in valary.
1333 * First is matches.
1334 * Second one is replacements
1335 */
1336 list($valmatch, $valrepl) = $valary;
1337 $newvalue =
1338 preg_replace($valmatch, $valrepl, $attvalue);
1339 if ($newvalue != $attvalue){
1340 $attary{$attname} = $newvalue;
1341 }
1342 }
1343 }
1344 }
1345 }
1346 /**
1347 * Turn cid: urls into http-friendly ones.
1348 */
1349 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1350 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1351 }
1352 }
1353 /**
1354 * See if we need to append any attributes to this tag.
1355 */
1356 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1357 if (preg_match($matchtag, $tagname)){
1358 $attary = array_merge($attary, $addattary);
1359 }
1360 }
1361 return $attary;
1362 }
1363
1364 /**
1365 * This function edits the style definition to make them friendly and
1366 * usable in squirrelmail.
1367 *
1368 * @param $message the message object
1369 * @param $id the message id
1370 * @param $content a string with whatever is between <style> and </style>
1371 * @return a string with edited content.
1372 */
1373 function sq_fixstyle($body, $pos, $message, $id){
1374 global $view_unsafe_images;
1375 $me = 'sq_fixstyle';
1376 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1377 if ($ret == FALSE){
1378 return array(FALSE, strlen($body));
1379 }
1380 $newpos = $ret[0] + strlen($ret[2]);
1381 $content = $ret[1];
1382 /**
1383 * First look for general BODY style declaration, which would be
1384 * like so:
1385 * body {background: blah-blah}
1386 * and change it to .bodyclass so we can just assign it to a <div>
1387 */
1388 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1389 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1390 /**
1391 * Fix url('blah') declarations.
1392 */
1393 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1394 "url(\\1$secremoveimg\\2)", $content);
1395 /**
1396 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1397 * is false.
1398 */
1399 if (!$view_unsafe_images){
1400 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1401 "url(\\1$secremoveimg\\2)", $content);
1402 }
1403
1404 /**
1405 * Fix urls that refer to cid:
1406 */
1407 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1408 $content, $matches)){
1409 $cidurl = $matches{1};
1410 $httpurl = sq_cid2http($message, $id, $cidurl);
1411 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1412 "url($httpurl)", $content);
1413 }
1414
1415 /**
1416 * Fix stupid css declarations which lead to vulnerabilities
1417 * in IE.
1418 */
1419 $match = Array('/expression/i',
1420 '/behaviou*r/i',
1421 '/binding/i');
1422 $replace = Array('idiocy', 'idiocy', 'idiocy');
1423 $content = preg_replace($match, $replace, $content);
1424 return array($content, $newpos);
1425 }
1426
1427 /**
1428 * This function converts cid: url's into the ones that can be viewed in
1429 * the browser.
1430 *
1431 * @param $message the message object
1432 * @param $id the message id
1433 * @param $cidurl the cid: url.
1434 * @return a string with a http-friendly url
1435 */
1436 function sq_cid2http($message, $id, $cidurl, $mailbox){
1437 /**
1438 * Get rid of quotes.
1439 */
1440 $quotchar = substr($cidurl, 0, 1);
1441 $cidurl = str_replace($quotchar, "", $cidurl);
1442 $cidurl = substr(trim($cidurl), 4);
1443 $linkurl = find_ent_id($cidurl, $message);
1444 /* in case of non-save cid links $httpurl should be replaced by a sort of
1445 unsave link image */
1446 $httpurl = '';
1447 if ($linkurl) {
1448 $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
1449 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
1450 '&amp;ent_id=' . $linkurl . $quotchar;
1451 }
1452 return $httpurl;
1453 }
1454
1455 /**
1456 * This function changes the <body> tag into a <div> tag since we
1457 * can't really have a body-within-body.
1458 *
1459 * @param $attary an array of attributes and values of <body>
1460 * @return a modified array of attributes to be set for <div>
1461 */
1462 function sq_body2div($attary){
1463 $me = 'sq_body2div';
1464 $divattary = Array('class' => "'bodyclass'");
1465 $bgcolor = '#ffffff';
1466 $text = '#000000';
1467 $styledef = '';
1468 if (is_array($attary) && sizeof($attary) > 0){
1469 foreach ($attary as $attname=>$attvalue){
1470 $quotchar = substr($attvalue, 0, 1);
1471 $attvalue = str_replace($quotchar, "", $attvalue);
1472 switch ($attname){
1473 case 'background':
1474 $styledef .= "background-image: url('$attvalue'); ";
1475 break;
1476 case 'bgcolor':
1477 $styledef .= "background-color: $attvalue; ";
1478 break;
1479 case 'text':
1480 $styledef .= "color: $attvalue; ";
1481 break;
1482 }
1483 }
1484 if (strlen($styledef) > 0){
1485 $divattary{"style"} = "\"$styledef\"";
1486 }
1487 }
1488 return $divattary;
1489 }
1490
1491 /**
1492 * This is the main function and the one you should actually be calling.
1493 * There are several variables you should be aware of an which need
1494 * special description.
1495 *
1496 * Since the description is quite lengthy, see it here:
1497 * http://www.mricon.com/html/phpfilter.html
1498 *
1499 * @param $body the string with HTML you wish to filter
1500 * @param $tag_list see description above
1501 * @param $rm_tags_with_content see description above
1502 * @param $self_closing_tags see description above
1503 * @param $force_tag_closing see description above
1504 * @param $rm_attnames see description above
1505 * @param $bad_attvals see description above
1506 * @param $add_attr_to_tag see description above
1507 * @param $message message object
1508 * @param $id message id
1509 * @return sanitized html safe to show on your pages.
1510 */
1511 function sq_sanitize($body,
1512 $tag_list,
1513 $rm_tags_with_content,
1514 $self_closing_tags,
1515 $force_tag_closing,
1516 $rm_attnames,
1517 $bad_attvals,
1518 $add_attr_to_tag,
1519 $message,
1520 $id,
1521 $mailbox
1522 ){
1523 $me = 'sq_sanitize';
1524 $rm_tags = array_shift($tag_list);
1525 /**
1526 * Normalize rm_tags and rm_tags_with_content.
1527 */
1528 @array_walk($tag_list, 'sq_casenormalize');
1529 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1530 @array_walk($self_closing_tags, 'sq_casenormalize');
1531 /**
1532 * See if tag_list is of tags to remove or tags to allow.
1533 * false means remove these tags
1534 * true means allow these tags
1535 */
1536 $curpos = 0;
1537 $open_tags = Array();
1538 $trusted = "<!-- begin sanitized html -->\n";
1539 $skip_content = false;
1540 /**
1541 * Take care of netscape's stupid javascript entities like
1542 * &{alert('boo')};
1543 */
1544 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
1545
1546 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1547 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1548 $free_content = substr($body, $curpos, $lt-$curpos);
1549 /**
1550 * Take care of <style>
1551 */
1552 if ($tagname == "style" && $tagtype == 1){
1553 list($free_content, $curpos) =
1554 sq_fixstyle($body, $gt+1, $message, $id);
1555 if ($free_content != FALSE){
1556 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1557 $trusted .= $free_content;
1558 $trusted .= sq_tagprint($tagname, false, 2);
1559 }
1560 continue;
1561 }
1562 if ($skip_content == false){
1563 $trusted .= $free_content;
1564 }
1565 if ($tagname != FALSE){
1566 if ($tagtype == 2){
1567 if ($skip_content == $tagname){
1568 /**
1569 * Got to the end of tag we needed to remove.
1570 */
1571 $tagname = false;
1572 $skip_content = false;
1573 } else {
1574 if ($skip_content == false){
1575 if ($tagname == "body"){
1576 $tagname = "div";
1577 } else {
1578 if (isset($open_tags{$tagname}) &&
1579 $open_tags{$tagname} > 0){
1580 $open_tags{$tagname}--;
1581 } else {
1582 $tagname = false;
1583 }
1584 }
1585 }
1586 }
1587 } else {
1588 /**
1589 * $rm_tags_with_content
1590 */
1591 if ($skip_content == false){
1592 /**
1593 * See if this is a self-closing type and change
1594 * tagtype appropriately.
1595 */
1596 if ($tagtype == 1
1597 && in_array($tagname, $self_closing_tags)){
1598 $tagtype=3;
1599 }
1600 /**
1601 * See if we should skip this tag and any content
1602 * inside it.
1603 */
1604 if ($tagtype == 1 &&
1605 in_array($tagname, $rm_tags_with_content)){
1606 $skip_content = $tagname;
1607 } else {
1608 if (($rm_tags == false
1609 && in_array($tagname, $tag_list)) ||
1610 ($rm_tags == true &&
1611 !in_array($tagname, $tag_list))){
1612 $tagname = false;
1613 } else {
1614 if ($tagtype == 1){
1615 if (isset($open_tags{$tagname})){
1616 $open_tags{$tagname}++;
1617 } else {
1618 $open_tags{$tagname}=1;
1619 }
1620 }
1621 /**
1622 * This is where we run other checks.
1623 */
1624 if (is_array($attary) && sizeof($attary) > 0){
1625 $attary = sq_fixatts($tagname,
1626 $attary,
1627 $rm_attnames,
1628 $bad_attvals,
1629 $add_attr_to_tag,
1630 $message,
1631 $id,
1632 $mailbox
1633 );
1634 }
1635 /**
1636 * Convert body into div.
1637 */
1638 if ($tagname == "body"){
1639 $tagname = "div";
1640 $attary = sq_body2div($attary, $message, $id);
1641 }
1642 }
1643 }
1644 }
1645 }
1646 if ($tagname != false && $skip_content == false){
1647 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1648 }
1649 }
1650 $curpos = $gt+1;
1651 }
1652 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1653 if ($force_tag_closing == true){
1654 foreach ($open_tags as $tagname=>$opentimes){
1655 while ($opentimes > 0){
1656 $trusted .= '</' . $tagname . '>';
1657 $opentimes--;
1658 }
1659 }
1660 $trusted .= "\n";
1661 }
1662 $trusted .= "<!-- end sanitized html -->\n";
1663 return $trusted;
1664 }
1665
1666 /**
1667 * This is a wrapper function to call html sanitizing routines.
1668 *
1669 * @param $body the body of the message
1670 * @param $id the id of the message
1671 * @return a string with html safe to display in the browser.
1672 */
1673 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1674 global $attachment_common_show_images, $view_unsafe_images,
1675 $has_unsafe_images;
1676 /**
1677 * Don't display attached images in HTML mode.
1678 */
1679 $attachment_common_show_images = false;
1680 $tag_list = Array(
1681 false,
1682 "object",
1683 "meta",
1684 "html",
1685 "head",
1686 "base",
1687 "link",
1688 "frame",
1689 "iframe"
1690 );
1691
1692 $rm_tags_with_content = Array(
1693 "script",
1694 "applet",
1695 "embed",
1696 "title"
1697 );
1698
1699 $self_closing_tags = Array(
1700 "img",
1701 "br",
1702 "hr",
1703 "input"
1704 );
1705
1706 $force_tag_closing = false;
1707
1708 $rm_attnames = Array(
1709 "/.*/" =>
1710 Array(
1711 "/target/i",
1712 "/^on.*/i",
1713 "/^dynsrc/i",
1714 "/^data.*/i",
1715 "/^lowsrc.*/i"
1716 )
1717 );
1718
1719 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1720 $bad_attvals = Array(
1721 "/.*/" =>
1722 Array(
1723 "/^src|background/i" =>
1724 Array(
1725 Array(
1726 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1727 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1728 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1729 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1730 ),
1731 Array(
1732 "\\1$secremoveimg\\2",
1733 "\\1$secremoveimg\\2",
1734 "\\1$secremoveimg\\2",
1735 "\\1$secremoveimg\\2"
1736 )
1737 ),
1738 "/^href|action/i" =>
1739 Array(
1740 Array(
1741 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1742 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1743 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1744 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1745 ),
1746 Array(
1747 "\\1#\\2",
1748 "\\1#\\2",
1749 "\\1#\\2",
1750 "\\1#\\2"
1751 )
1752 ),
1753 "/^style/i" =>
1754 Array(
1755 Array(
1756 "/expression/i",
1757 "/binding/i",
1758 "/behaviou*r/i",
1759 "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
1760 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1761 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1762 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
1763 ),
1764 Array(
1765 "idiocy",
1766 "idiocy",
1767 "idiocy",
1768 "url(\\1#\\2)",
1769 "url(\\1#\\2)",
1770 "url(\\1#\\2)",
1771 "url(\\1#\\2)"
1772 )
1773 )
1774 )
1775 );
1776 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
1777 $view_unsafe_images = false;
1778 }
1779 if (!$view_unsafe_images){
1780 /**
1781 * Remove any references to http/https if view_unsafe_images set
1782 * to false.
1783 */
1784 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1785 '/^([\'\"])\s*https*:.*([\'\"])/si');
1786 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1787 "\\1$secremoveimg\\2");
1788 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1789 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1790 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1791 "url(\\1$secremoveimg\\2)");
1792 }
1793
1794 $add_attr_to_tag = Array(
1795 "/^a$/i" => Array('target'=>'"_new"')
1796 );
1797 $trusted = sq_sanitize($body,
1798 $tag_list,
1799 $rm_tags_with_content,
1800 $self_closing_tags,
1801 $force_tag_closing,
1802 $rm_attnames,
1803 $bad_attvals,
1804 $add_attr_to_tag,
1805 $message,
1806 $id,
1807 $mailbox
1808 );
1809 if (preg_match("|$secremoveimg|i", $trusted)){
1810 $has_unsafe_images = true;
1811 }
1812 return $trusted;
1813 }
1814
1815 ?>