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