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