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