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