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