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