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