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