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