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