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