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