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