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