6 * This contains the functions necessary to detect and decode MIME
9 * @copyright © 1999-2007 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @package squirrelmail
16 * dependency information
19 class/mime/Message.class.php
20 Message::parseStructure
21 functions/page_header.php
23 functions/display_messages.php
26 functions/imap_general.php
33 functions/attachment_common.php
34 functions/display_messages.php
36 magicHtml => url_parser
37 translateText => url_parser
42 /* -------------------------------------------------------------------------- */
44 /* -------------------------------------------------------------------------- */
47 * Get the MIME structure
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.
53 function mime_structure ($bodystructure, $flags=array()) {
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));
59 $msg = Message
::parseStructure($read,$i);
61 if (!is_object($msg)) {
62 global $color, $mailbox;
63 /* removed urldecode because $_GET is auto urldecoded ??? */
64 displayPageHeader( $color, $mailbox );
65 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
66 $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
67 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
68 plain_error_message( $errormessage, $color );
69 echo '</body></html>';
73 foreach ($flags as $flag) {
74 //FIXME: please document why it is we have to check the first char of the flag but we then go ahead and do a full string comparison anyway. Is this a speed enhancement? If not, let's keep it simple and just compare the full string and forget the switch block.
75 $char = strtoupper($flag{1});
78 if (strtolower($flag) == '\\seen') {
83 if (strtolower($flag) == '\\answered') {
84 $msg->is_answered
= true;
88 if (strtolower($flag) == '\\deleted') {
89 $msg->is_deleted
= true;
93 if (strtolower($flag) == '\\flagged') {
94 $msg->is_flagged
= true;
98 if (strtolower($flag) == '$mdnsent') {
99 $msg->is_mdnsent
= true;
107 // listEntities($msg);
113 /* This starts the parsing of a particular structure. It is called recursively,
114 * so it can be passed different structures. It returns an object of type
116 * First, it checks to see if it is a multipart message. If it is, then it
117 * handles that as it sees is necessary. If it is just a regular entity,
118 * then it parses it and adds the necessary header information (by calling out
119 * to mime_get_elements()
122 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
123 /* Do a bit of error correction. If we couldn't find the entity id, just guess
124 * that it is the first one. That is usually the case anyway.
128 $cmd = "FETCH $id BODY[]";
130 $cmd = "FETCH $id BODY[$ent_id]";
133 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
135 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
137 $topline = trim(array_shift($data));
138 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
140 $wholemessage = implode('', $data);
141 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
142 $ret = substr($wholemessage, 0, $regs[1]);
143 /* There is some information in the content info header that could be important
144 * in order to parse html messages. Let's get them here.
146 // if ($ret{0} == '<') {
147 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
149 } else if (ereg('"([^"]*)"', $topline, $regs)) {
152 global $where, $what, $mailbox, $passed_id, $startMessage;
153 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
154 if (isset($where) && isset($what)) {
155 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
157 $par .= '&startMessage=' . $startMessage . '&show_more=0';
159 $par .= '&response=' . urlencode($response) .
160 '&message=' . urlencode($message) .
161 '&topline=' . urlencode($topline);
164 '<table width="80%"><tr>' .
165 '<tr><td colspan="2">' .
166 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
168 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
169 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
170 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
171 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
172 "</table><br /></tt></font><hr />";
174 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
176 $wholemessage = implode('', $data);
178 $ret = $wholemessage;
183 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
185 /* Don't kill the connection if the browser is over a dialup
186 * and it would take over 30 seconds to download it.
187 * Don't call set_time_limit in safe mode.
190 if (!ini_get('safe_mode')) {
193 /* in case of base64 encoded attachments, do not buffer them.
194 Instead, echo the decoded attachment directly to screen */
195 if (strtolower($encoding) == 'base64') {
197 $query = "FETCH $id BODY[]";
199 $query = "FETCH $id BODY[$ent_id]";
201 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode',$rStream,true);
203 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
204 if (is_resource($rStream)) {
205 fputs($rStream,decodeBody($body,$encoding));
207 echo decodeBody($body, $encoding);
212 TODO, use the same method for quoted printable.
213 However, I assume that quoted printable attachments aren't that large
214 so the performancegain / memory usage drop will be minimal.
215 If we decide to add that then we need to adapt sqimap_fread because
216 we need to split te result on \n and fread doesn't stop at \n. That
217 means we also should provide $results from sqimap_fread (by ref) to
218 te function and set $no_return to false. The $filter function for
219 quoted printable should handle unsetting of $results.
222 TODO 2: find out how we write to the output stream php://stdout. fwrite
223 doesn't work because 'php://stdout isn't a stream.
229 /* -[ END MIME DECODING ]----------------------------------------------------------- */
231 /* This is here for debugging purposes. It will print out a list
232 * of all the entity IDs that are in the $message object.
234 function listEntities ($message) {
236 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br />';
237 for ($i = 0; isset($message->entities
[$i]); $i++
) {
239 $msg = listEntities($message->entities
[$i]);
249 function getPriorityStr($priority) {
250 $priority_level = substr($priority,0,1);
252 switch($priority_level) {
253 /* Check for a higher then normal priority. */
256 $priority_string = _("High");
259 /* Check for a lower then normal priority. */
262 $priority_string = _("Low");
265 /* Check for a normal priority. */
268 $priority_level = '3';
269 $priority_string = _("Normal");
273 return $priority_string;
276 /* returns a $message object for a particular entity id */
277 function getEntity ($message, $ent_id) {
278 return $message->getEntity($ent_id);
282 * Extracted from strings.php 23/03/2002
285 function translateText(&$body, $wrap_at, $charset) {
286 global $where, $what; /* from searching */
287 global $color; /* color theme */
289 // require_once(SM_PATH . 'functions/url_parser.php');
291 $body_ary = explode("\n", $body);
292 for ($i=0; $i < count($body_ary); $i++
) {
293 $line = $body_ary[$i];
294 if (strlen($line) - 2 >= $wrap_at) {
295 sqWordWrap($line, $wrap_at, $charset);
297 $line = charset_decode($charset, $line);
298 $line = str_replace("\t", ' ', $line);
307 if ($line[$pos] == ' ') {
309 } else if (strpos($line, '>', $pos) === $pos) {
318 $line = '<span class="quote1">' . $line . '</span>';
320 $line = '<span class="quote2">' . $line . '</span>';
323 $body_ary[$i] = $line;
325 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
329 * This returns a parsed string called $body. That string can then
330 * be displayed as the actual message in the HTML. It contains
331 * everything needed, including HTML Tags, Attachments at the
334 * Since 1.2.0 function uses message_body hook.
335 * Till 1.3.0 function included output of formatAttachments().
337 * @param resource $imap_stream imap connection resource
338 * @param object $message squirrelmail message object
339 * @param array $color squirrelmail color theme array
340 * @param integer $wrap_at number of characters per line
341 * @param string $ent_num (since 1.3.0) message part id
342 * @param integer $id (since 1.3.0) message id
343 * @param string $mailbox (since 1.3.0) imap folder name
344 * @param boolean $clean (since 1.5.1) Do not output stuff that's irrelevant for the printable version.
345 * @return string html formated message text
347 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=FALSE) {
348 /* This if statement checks for the entity to show as the
349 * primary message. To add more of them, just put them in the
350 * order that is their priority.
352 global $startMessage, $languages, $squirrelmail_language,
353 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
354 $use_iframe, $iframe_height, $download_and_unsafe_link,
355 $download_href, $unsafe_image_toggle_href, $unsafe_image_toggle_text,
358 $nbsp = $oTemplate->fetch('non_breaking_space.tpl');
360 // workaround for not updated config.php
361 if (! isset($use_iframe)) $use_iframe = false;
363 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
364 $view_unsafe_images = false;
368 $urlmailbox = urlencode($mailbox);
369 $body_message = getEntity($message, $ent_num);
370 if (($body_message->header
->type0
== 'text') ||
371 ($body_message->header
->type0
== 'rfc822')) {
372 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
373 $body = decodeBody($body, $body_message->header
->encoding
);
375 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
376 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode')) {
377 if (mb_detect_encoding($body) != 'ASCII') {
378 $body = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decode',$body);
382 /* As of 1.5.2, $body is passed (and modified) by reference */
383 do_hook('message_body', $body);
385 /* If there are other types that shouldn't be formatted, add
389 if ($body_message->header
->type1
== 'html') {
390 if ($show_html_default <> 1) {
391 $entity_conv = array(' ' => ' ',
400 $body = strtr($body, $entity_conv);
401 $body = strip_tags($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.
409 * If we don't add html message between iframe tags,
410 * we must detect unsafe images and modify $has_unsafe_images.
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);
416 // creating iframe url
417 $iframeurl=sqm_baseuri().'src/view_html.php?'
418 . 'mailbox=' . $urlmailbox
419 . '&passed_id=' . $id
420 . '&ent_id=' . $ent_num
421 . '&view_unsafe_images=' . (int) $view_unsafe_images;
424 $oTemplate->assign('iframe_url', $iframeurl);
425 $oTemplate->assign('html_body', $html_body);
427 $body = $oTemplate->fetch('read_html_iframe.tpl');
429 // old way of html rendering
431 * convert character set. charset_decode does not remove html special chars
432 * applied by magicHTML functions and does not sanitize them second time if
433 * fourth argument is true.
435 $charset = $body_message->header
->getParameter('charset');
436 if (!empty($charset)) {
437 $body = charset_decode($charset,$body,false,true);
439 $body = magicHTML($body, $id, $message, $mailbox);
442 translateText($body, $wrap_at,
443 $body_message->header
->getParameter('charset'));
446 // if this is the clean display (i.e. printer friendly), stop here.
451 $download_and_unsafe_link = '';
453 $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
454 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
455 '&startMessage=' . $startMessage . '&show_more=0';
456 if (isset($passed_ent_id)) {
457 $link .= '&passed_ent_id='.$passed_ent_id;
459 $download_href = SM_PATH
. 'src/download.php?absolute_dl=true&' . $link;
460 $download_and_unsafe_link .= "$nbsp|$nbsp"
461 . create_hyperlink($download_href, _("Download this as a file"));
462 if ($view_unsafe_images) {
463 $text = _("Hide Unsafe Images");
465 if (isset($has_unsafe_images) && $has_unsafe_images) {
466 $link .= '&view_unsafe_images=1';
467 $text = _("View Unsafe Images");
473 $unsafe_image_toggle_href = SM_PATH
. 'src/read_body.php?'.$link;
474 $unsafe_image_toggle_text = $text;
475 $download_and_unsafe_link .= "$nbsp|$nbsp"
476 . create_hyperlink($unsafe_image_toggle_href, $text);
483 * Generate attachments array for passing to templates. Separated from
484 * formatAttachments() below so that the same array can be given to the
485 * print-friendly version.
488 * @param object $message SquirrelMail message object
489 * @param array $exclude_id message parts that are not attachments.
490 * @param string $mailbox mailbox name
491 * @param integer $id message id
493 function buildAttachmentArray($message, $exclude_id, $mailbox, $id) {
494 global $where, $what, $startMessage, $color, $passed_ent_id, $base_uri;
496 $att_ar = $message->getAttachments($exclude_id);
497 $urlMailbox = urlencode($mailbox);
499 $attachments = array();
500 foreach ($att_ar as $att) {
501 $ent = $att->entity_id
;
502 $header = $att->header
;
503 $type0 = strtolower($header->type0
);
504 $type1 = strtolower($header->type1
);
507 $links['download link']['text'] = _("Download");
508 $links['download link']['href'] = $base_uri .
509 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
511 if ($type0 =='message' && $type1 == 'rfc822') {
512 $default_page = $base_uri . 'src/read_body.php';
513 $rfc822_header = $att->rfc822_header
;
514 $filename = $rfc822_header->subject
;
515 if (trim( $filename ) == '') {
516 $filename = 'untitled-[' . $ent . ']' ;
518 $from_o = $rfc822_header->from
;
519 if (is_object($from_o)) {
520 $from_name = decodeHeader($from_o->getAddress(false));
521 } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
522 // something weird happens when a digest message is opened and you return to the digest
523 // now the from object is part of an array. Probably the parseHeader call overwrites the info
524 // retrieved from the bodystructure in a different way. We need to fix this later.
525 // possible starting point, do not fetch header we already have and inspect how
526 // the rfc822_header object behaves.
527 $from_name = decodeHeader($from_o[0]->getAddress(false));
529 $from_name = _("Unknown sender");
531 $description = _("From").': '.$from_name;
533 $default_page = $base_uri . 'src/download.php';
534 $filename = $att->getFilename();
535 if ($header->description
) {
536 $description = decodeHeader($header->description
);
542 $display_filename = $filename;
543 if (isset($passed_ent_id)) {
544 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
546 $passed_ent_id_link = '';
548 $defaultlink = $default_page . "?startMessage=$startMessage"
549 . "&passed_id=$id&mailbox=$urlMailbox"
550 . '&ent_id='.$ent.$passed_ent_id_link;
551 if ($where && $what) {
552 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
554 // IE does make use of mime content sniffing. Forcing a download
555 // prohibit execution of XSS inside an application/octet-stream attachment
556 if ($type0 == 'application' && $type1 == 'octet-stream') {
557 $defaultlink .= '&absolute_dl=true';
560 /* This executes the attachment hook with a specific MIME-type.
561 * If that doesn't have results, it tries if there's a rule
562 * for a more generic type. Finally, a hook for ALL attachment
563 * types is run as well.
565 /* The API for this hook has changed as of 1.5.2 so that all plugin
566 arguments are passed in an array instead of each their own plugin
567 argument, and arguments are passed by reference, so instead of
568 returning any changes, changes should simply be made to the original
569 arguments themselves. */
570 do_hook("attachment $type0/$type1", $temp=array(&$links,
571 &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
572 &$display_filename, &$where, &$what));
573 if(count($links) <= 1) {
574 /* The API for this hook has changed as of 1.5.2 so that all plugin
575 arguments are passed in an array instead of each their own plugin
576 argument, and arguments are passed by reference, so instead of
577 returning any changes, changes should simply be made to the original
578 arguments themselves. */
579 do_hook("attachment $type0/*", $temp=array(&$links,
580 &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
581 &$display_filename, &$where, &$what));
583 /* The API for this hook has changed as of 1.5.2 so that all plugin
584 arguments are passed in an array instead of each their own plugin
585 argument, and arguments are passed by reference, so instead of
586 returning any changes, changes should simply be made to the original
587 arguments themselves. */
588 do_hook("attachment */*", $temp=array(&$links,
589 &$startMessage, &$id, &$urlMailbox, &$ent, &$defaultlink,
590 &$display_filename, &$where, &$what));
592 $this_attachment = array();
593 $this_attachment['Name'] = decodeHeader($display_filename);
594 $this_attachment['Description'] = $description;
595 $this_attachment['DefaultHREF'] = $defaultlink;
596 $this_attachment['DownloadHREF'] = $links['download link']['href'];
597 $this_attachment['ViewHREF'] = isset($links['attachment_common']) ?
$links['attachment_common']['href'] : '';
598 $this_attachment['Size'] = $header->size
;
599 $this_attachment['ContentType'] = htmlspecialchars($type0 .'/'. $type1);
600 $this_attachment['OtherLinks'] = array();
601 foreach ($links as $val) {
602 if ($val['text']==_("Download") ||
$val['text'] == _("View"))
604 if (empty($val['text']) && empty($val['extra']))
608 $temp['HREF'] = $val['href'];
609 $temp['Text'] = (empty($val['text']) ?
'' : $val['text']) . (empty($val['extra']) ?
'' : $val['extra']);
610 $this_attachment['OtherLinks'][] = $temp;
612 $attachments[] = $this_attachment;
621 * Displays attachment links and information
623 * Since 1.3.0 function is not included in formatBody() call.
625 * Since 1.0.2 uses attachment $type0/$type1 hook.
626 * Since 1.2.5 uses attachment $type0/* hook.
627 * Since 1.5.0 uses attachments_bottom hook.
628 * Since 1.5.2 uses templates and does *not* return a value.
630 * @param object $message SquirrelMail message object
631 * @param array $exclude_id message parts that are not attachments.
632 * @param string $mailbox mailbox name
633 * @param integer $id message id
635 function formatAttachments($message, $exclude_id, $mailbox, $id) {
638 $attach = buildAttachmentArray($message, $exclude_id, $mailbox, $id);
640 $oTemplate->assign('attachments', $attach);
641 $oTemplate->display('read_attachments.tpl');
644 function sqimap_base64_decode(&$string) {
646 // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
647 // fly decoding (to reduce memory usage) you have to check if the
648 // data has incomplete pairs
650 // Remove the noise in order to check if the 4 bytes pairs are complete
651 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
654 $iMod = strlen($string) %
4;
656 $sStringRem = substr($string,-$iMod);
657 // Check if $sStringRem contains padding characters
658 if (substr($sStringRem,-1) != '=') {
659 $string = substr($string,0,-$iMod);
664 $string = base64_decode($string);
669 * Decodes encoded message body
671 * This function decodes the body depending on the encoding type.
672 * Currently quoted-printable and base64 encodings are supported.
673 * decode_body hook was added to this function in 1.4.2/1.5.0
674 * @param string $body encoded message body
675 * @param string $encoding used encoding
676 * @return string decoded string
679 function decodeBody($body, $encoding) {
681 $body = str_replace("\r\n", "\n", $body);
682 $encoding = strtolower($encoding);
684 $encoding_handler = do_hook('decode_body', $encoding);
687 // plugins get first shot at decoding the body
689 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
690 $body = $encoding_handler('decode', $body);
692 } elseif ($encoding == 'quoted-printable' ||
693 $encoding == 'quoted_printable') {
695 * quoted_printable_decode() function is broken in older
696 * php versions. Text with \r\n decoding was fixed only
697 * in php 4.3.0. Minimal code requirement 4.0.4 +
698 * str_replace("\r\n", "\n", $body); call.
700 $body = quoted_printable_decode($body);
701 } elseif ($encoding == 'base64') {
702 $body = base64_decode($body);
705 // All other encodings are returned raw.
712 * This function decodes strings that are encoded according to
713 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
714 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
716 * @param string $string header string that has to be made readable
717 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
718 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
719 * @param boolean $decide decide if string can be utfencoded. defaults to false
720 * @return string decoded header string
722 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
723 global $languages, $squirrelmail_language,$default_charset;
724 if (is_array($string)) {
725 $string = implode("\n", $string);
728 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
729 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader')) {
730 $string = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_decodeheader', $string);
731 // Do we need to return at this point?
738 $aString = explode(' ',$string);
740 foreach ($aString as $chunk) {
741 if ($encoded && $chunk === '') {
743 } elseif ($chunk === '') {
748 /* if encoded words are not separated by a linear-space-white we still catch them */
751 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
752 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
753 if ($iLastMatch !== $j) {
763 $ret .= htmlspecialchars($res[1]);
767 $encoding = ucfirst($res[3]);
769 /* decide about valid decoding */
770 if ($decide && is_conversion_safe($res[2])) {
772 $can_be_encoded=true;
774 $can_be_encoded=false;
779 $replace = base64_decode($res[4]);
781 if ($can_be_encoded) {
782 /* convert string to different charset,
783 * if functions asks for it (usually in compose)
785 $ret .= charset_convert($res[2],$replace,$default_charset,$htmlsave);
787 // convert string to html codes in order to display it
788 $ret .= charset_decode($res[2],$replace);
792 $replace = htmlspecialchars($replace);
798 $replace = str_replace('_', ' ', $res[4]);
799 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
802 if ($can_be_encoded) {
803 /* convert string to different charset,
804 * if functions asks for it (usually in compose)
806 $replace = charset_convert($res[2], $replace,$default_charset,$htmlsave);
808 // convert string to html codes in order to display it
809 $replace = charset_decode($res[2], $replace);
813 $replace = htmlspecialchars($replace);
832 if (!$encoded && $htmlsave) {
833 $ret .= htmlspecialchars($chunk);
839 /* remove the first added space */
842 $ret = substr($ret,5);
844 $ret = substr($ret,1);
854 * Function uses XTRA_CODE _encodeheader function, if such function exists.
856 * Function uses Q encoding by default and encodes a string according to RFC
857 * 1522 for use in headers if it contains 8-bit characters or anything that
858 * looks like it should be encoded.
860 * Function switches to B encoding and encodeHeaderBase64() function, if
861 * string is 8bit and multibyte character set supported by mbstring extension
862 * is used. It can cause E_USER_NOTICE errors, if interface is used with
863 * multibyte character set unsupported by mbstring extension.
865 * @param string $string header string, that has to be encoded
866 * @return string quoted-printable encoded string
867 * @todo make $mb_charsets system wide constant
869 function encodeHeader ($string) {
870 global $default_charset, $languages, $squirrelmail_language;
872 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
873 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader')) {
874 return call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_encodeheader', $string);
877 // Use B encoding for multibyte charsets
878 $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
879 if (in_array($default_charset,$mb_charsets) &&
880 in_array($default_charset,sq_mb_list_encodings()) &&
881 sq_is8bit($string)) {
882 return encodeHeaderBase64($string,$default_charset);
883 } elseif (in_array($default_charset,$mb_charsets) &&
884 sq_is8bit($string) &&
885 ! in_array($default_charset,sq_mb_list_encodings())) {
886 // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
887 // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
890 // Encode only if the string contains 8-bit characters or =?
891 $j = strlen($string);
892 $max_l = 75 - strlen($default_charset) - 7;
895 $iEncStart = $enc_init = false;
896 $cur_l = $iOffset = 0;
897 for($i = 0; $i < $j; ++
$i) {
906 if ($iEncStart === false) {
910 if ($cur_l > ($max_l-2)) {
911 /* if there is an stringpart that doesn't need encoding, add it */
912 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
913 $aRet[] = "=?$default_charset?Q?$ret?=";
919 $ret .= sprintf("=%02X",ord($string{$i}));
924 if ($iEncStart !== false) {
925 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
926 $aRet[] = "=?$default_charset?Q?$ret?=";
934 if ($iEncStart !== false) {
936 if ($cur_l > $max_l) {
937 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
938 $aRet[] = "=?$default_charset?Q?$ret?=";
949 $k = ord($string{$i});
951 if ($iEncStart === false) {
952 // do not start encoding in the middle of a string, also take the rest of the word.
953 $sLeadString = substr($string,0,$i);
954 $aLeadString = explode(' ',$sLeadString);
955 $sToBeEncoded = array_pop($aLeadString);
956 $iEncStart = $i - strlen($sToBeEncoded);
957 $ret .= $sToBeEncoded;
958 $cur_l +
= strlen($sToBeEncoded);
961 /* first we add the encoded string that reached it's max size */
962 if ($cur_l > ($max_l-2)) {
963 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
964 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
971 $ret .= sprintf("=%02X", $k);
973 if ($iEncStart !== false) {
975 if ($cur_l > $max_l) {
976 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
977 $aRet[] = "=?$default_charset?Q?$ret?=";
992 if ($iEncStart !== false) {
993 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
994 $aRet[] = "=?$default_charset?Q?$ret?=";
996 $aRet[] = substr($string,$iOffset);
998 $string = implode('',$aRet);
1004 * Encodes string according to rfc2047 B encoding header formating rules
1006 * It is recommended way to encode headers with character sets that store
1007 * symbols in more than one byte.
1009 * Function requires mbstring support. If required mbstring functions are missing,
1010 * function returns false and sets E_USER_WARNING level error message.
1012 * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
1013 * that mbstring functions will generate E_WARNING errors, if unsupported
1014 * character set is used. mb_encode_mimeheader function provided by php
1015 * mbstring extension is not used in order to get better control of header
1018 * Used php code functions - function_exists(), trigger_error(), strlen()
1019 * (is used with charset names and base64 strings). Used php mbstring
1020 * functions - mb_strlen and mb_substr.
1022 * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
1023 * encoding), rfc 2822 (header folding)
1025 * @param string $string header string that must be encoded
1026 * @param string $charset character set. Must be supported by mbstring extension.
1027 * Use sq_mb_list_encodings() to detect supported charsets.
1028 * @return string string encoded according to rfc2047 B encoding formating rules
1030 * @todo First header line can be wrapped to $iMaxLength - $HeaderFieldLength - 1
1031 * @todo Do we want to control max length of header?
1032 * @todo Do we want to control EOL (end-of-line) marker?
1033 * @todo Do we want to translate error message?
1035 function encodeHeaderBase64($string,$charset) {
1037 * Check mbstring function requirements.
1039 if (! function_exists('mb_strlen') ||
1040 ! function_exists('mb_substr')) {
1041 // set E_USER_WARNING
1042 trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING
);
1047 // initial return array
1051 * header length = 75 symbols max (same as in encodeHeader)
1052 * remove $charset length
1053 * remove =? ? ?= (5 chars)
1054 * remove 2 more chars (\r\n ?)
1056 $iMaxLength = 75 - strlen($charset) - 7;
1058 // set first character position
1061 // loop through all characters. count characters and not bytes.
1062 for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++
) {
1063 // encode string from starting character to current character.
1064 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1066 // Check encoded string length
1067 if(strlen($encoded_string)>$iMaxLength) {
1068 // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
1069 $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
1071 // set new starting character
1072 $iStartCharNum = $iCharNum-1;
1074 // encode last char (in case it is last character in string)
1075 $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
1076 } // if string is shorter than max length - add next character
1079 // add last encoded string to array
1080 $aRet[] = $encoded_string;
1082 // set initial return string
1085 // loop through encoded strings
1086 foreach($aRet as $string) {
1087 // TODO: Do we want to control EOL (end-of-line) marker
1088 if ($sRet!='') $sRet.= " ";
1090 // add header tags and encoded string to return string
1091 $sRet.= '=?'.$charset.'?B?'.$string.'?=';
1097 /* This function trys to locate the entity_id of a specific mime element */
1098 function find_ent_id($id, $message) {
1099 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
1100 if ($message->entities
[$i]->header
->type0
== 'multipart') {
1101 $ret = find_ent_id($id, $message->entities
[$i]);
1103 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
1104 // if (sq_check_save_extension($message->entities[$i])) {
1105 return $message->entities
[$i]->entity_id
;
1107 } elseif (!empty($message->entities
[$i]->header
->parameters
['name'])) {
1109 * This is part of a fix for Outlook Express 6.x generating
1110 * cid URLs without creating content-id headers
1113 if (strcasecmp($message->entities
[$i]->header
->parameters
['name'], $id) == 0) {
1114 return $message->entities
[$i]->entity_id
;
1122 function sq_check_save_extension($message) {
1123 $filename = $message->getFilename();
1124 $ext = substr($filename, strrpos($filename,'.')+
1);
1125 $save_extensions = array('jpg','jpeg','gif','png','bmp');
1126 return in_array($ext, $save_extensions);
1131 ** HTMLFILTER ROUTINES
1135 * This function checks attribute values for entity-encoded values
1136 * and returns them translated into 8-bit strings so we can run
1139 * @param $attvalue A string to run entity check against.
1140 * @return Nothing, modifies a reference value.
1142 function sq_defang(&$attvalue){
1145 * Skip this if there aren't ampersands or backslashes.
1147 if (strpos($attvalue, '&') === false
1148 && strpos($attvalue, '\\') === false){
1152 // before deent, translate the dangerous unicode characters and ... to safe values
1153 // otherwise the regular expressions do not match.
1159 $m = $m ||
sq_deent($attvalue, '/\�*(\d+);*/s');
1160 $m = $m ||
sq_deent($attvalue, '/\�*((\d|[a-f])+);*/si', true);
1161 $m = $m ||
sq_deent($attvalue, '/\\\\(\d+)/s', true);
1162 } while ($m == true);
1163 $attvalue = stripslashes($attvalue);
1167 * Kill any tabs, newlines, or carriage returns. Our friends the
1168 * makers of the browser with 95% market value decided that it'd
1169 * be funny to make "java[tab]script" be just as good as "javascript".
1171 * @param attvalue The attribute value before extraneous spaces removed.
1172 * @return attvalue Nothing, modifies a reference value.
1174 function sq_unspace(&$attvalue){
1176 if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
1177 $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
1178 Array('', '', '', '', ''), $attvalue);
1183 * Translate all dangerous Unicode or Shift_JIS characters which are accepted by
1184 * IE as regular characters.
1186 * @param attvalue The attribute value before dangerous characters are translated.
1187 * @return attvalue Nothing, modifies a reference value.
1188 * @author Marc Groot Koerkamp.
1190 function sq_fixIE_idiocy(&$attvalue) {
1192 $attvalue = str_replace("\0", "", $attvalue);
1194 $attvalue = preg_replace("/(\/\*.*?\*\/)/","",$attvalue);
1196 // IE has the evil habit of accepting every possible value for the attribute expression.
1197 // The table below contains characters which are parsed by IE if they are used in the "expression"
1199 $aDangerousCharsReplacementTable = array(
1200 array('ʟ', 'ʟ' ,/* L UNICODE IPA Extension */
1201 'ʀ', 'ʀ' ,/* R UNICODE IPA Extension */
1202 'ɴ', 'ɴ' ,/* N UNICODE IPA Extension */
1203 'E', 'E' ,/* Unicode FULLWIDTH LATIN CAPITAL LETTER E */
1204 'e', 'e' ,/* Unicode FULLWIDTH LATIN SMALL LETTER E */
1205 'X', 'X',/* Unicode FULLWIDTH LATIN CAPITAL LETTER X */
1206 'x', 'x',/* Unicode FULLWIDTH LATIN SMALL LETTER X */
1207 'P', 'P',/* Unicode FULLWIDTH LATIN CAPITAL LETTER P */
1208 'p', 'p',/* Unicode FULLWIDTH LATIN SMALL LETTER P */
1209 'R', 'R',/* Unicode FULLWIDTH LATIN CAPITAL LETTER R */
1210 'r', 'r',/* Unicode FULLWIDTH LATIN SMALL LETTER R */
1211 'S', 'S',/* Unicode FULLWIDTH LATIN CAPITAL LETTER S */
1212 's', 's',/* Unicode FULLWIDTH LATIN SMALL LETTER S */
1213 'I', 'I',/* Unicode FULLWIDTH LATIN CAPITAL LETTER I */
1214 'i', 'i',/* Unicode FULLWIDTH LATIN SMALL LETTER I */
1215 'O', 'O',/* Unicode FULLWIDTH LATIN CAPITAL LETTER O */
1216 'o', 'o',/* Unicode FULLWIDTH LATIN SMALL LETTER O */
1217 'N', 'N',/* Unicode FULLWIDTH LATIN CAPITAL LETTER N */
1218 'n', 'n',/* Unicode FULLWIDTH LATIN SMALL LETTER N */
1219 'L', 'L',/* Unicode FULLWIDTH LATIN CAPITAL LETTER L */
1220 'l', 'l',/* Unicode FULLWIDTH LATIN SMALL LETTER L */
1221 'U', 'U',/* Unicode FULLWIDTH LATIN CAPITAL LETTER U */
1222 'u', 'u',/* Unicode FULLWIDTH LATIN SMALL LETTER U */
1223 'ⁿ', 'ⁿ' ,/* Unicode SUPERSCRIPT LATIN SMALL LETTER N */
1224 "\xEF\xBC\xA5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER E */ // in unicode this is some Chinese char range
1225 "\xEF\xBD\x85", /* Shift JIS FULLWIDTH LATIN SMALL LETTER E */
1226 "\xEF\xBC\xB8", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER X */
1227 "\xEF\xBD\x98", /* Shift JIS FULLWIDTH LATIN SMALL LETTER X */
1228 "\xEF\xBC\xB0", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER P */
1229 "\xEF\xBD\x90", /* Shift JIS FULLWIDTH LATIN SMALL LETTER P */
1230 "\xEF\xBC\xB2", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER R */
1231 "\xEF\xBD\x92", /* Shift JIS FULLWIDTH LATIN SMALL LETTER R */
1232 "\xEF\xBC\xB3", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER S */
1233 "\xEF\xBD\x93", /* Shift JIS FULLWIDTH LATIN SMALL LETTER S */
1234 "\xEF\xBC\xA9", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER I */
1235 "\xEF\xBD\x89", /* Shift JIS FULLWIDTH LATIN SMALL LETTER I */
1236 "\xEF\xBC\xAF", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER O */
1237 "\xEF\xBD\x8F", /* Shift JIS FULLWIDTH LATIN SMALL LETTER O */
1238 "\xEF\xBC\xAE", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER N */
1239 "\xEF\xBD\x8E", /* Shift JIS FULLWIDTH LATIN SMALL LETTER N */
1240 "\xEF\xBC\xAC", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER L */
1241 "\xEF\xBD\x8C", /* Shift JIS FULLWIDTH LATIN SMALL LETTER L */
1242 "\xEF\xBC\xB5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER U */
1243 "\xEF\xBD\x95", /* Shift JIS FULLWIDTH LATIN SMALL LETTER U */
1244 "\xE2\x81\xBF", /* Shift JIS FULLWIDTH SUPERSCRIPT N */
1245 "\xCA\x9F", /* L UNICODE IPA Extension */
1246 "\xCA\x80", /* R UNICODE IPA Extension */
1247 "\xC9\xB4"), /* N UNICODE IPA Extension */
1248 array('l', 'l', 'r','r','n','n',
1249 'E','E','e','e','X','X','x','x','P','P','p','p','R','R','r','r','S','S','s','s','I','I',
1250 'i','i','O','O','o','o','N','N','n','n','L','L','l','l','U','U','u','u','n','n',
1251 'E','e','X','x','P','p','R','r','S','s','I','i','O','o','N','n','L','l','U','u','n','l','r','n'));
1252 $attvalue = str_replace($aDangerousCharsReplacementTable[0],$aDangerousCharsReplacementTable[1],$attvalue);
1254 // Escapes are useful for special characters like "{}[]()'&. In other cases they are
1256 $attvalue = preg_replace("/(\\\\)([a-zA-Z]{1})/",'$2',$attvalue);
1260 * This function returns the final tag out of the tag name, an array
1261 * of attributes, and the type of the tag. This function is called by
1262 * sq_sanitize internally.
1264 * @param $tagname the name of the tag.
1265 * @param $attary the array of attributes and their values
1266 * @param $tagtype The type of the tag (see in comments).
1267 * @return a string with the final tag representation.
1269 function sq_tagprint($tagname, $attary, $tagtype){
1270 $me = 'sq_tagprint';
1273 $fulltag = '</' . $tagname . '>';
1275 $fulltag = '<' . $tagname;
1276 if (is_array($attary) && sizeof($attary)){
1278 while (list($attname, $attvalue) = each($attary)){
1279 array_push($atts, "$attname=$attvalue");
1281 $fulltag .= ' ' . join(" ", $atts);
1292 * A small helper function to use with array_walk. Modifies a by-ref
1293 * value and makes it lowercase.
1295 * @param $val a value passed by-ref.
1296 * @return void since it modifies a by-ref value.
1298 function sq_casenormalize(&$val){
1299 $val = strtolower($val);
1303 * This function skips any whitespace from the current position within
1304 * a string and to the next non-whitespace value.
1306 * @param $body the string
1307 * @param $offset the offset within the string where we should start
1308 * looking for the next non-whitespace character.
1309 * @return the location within the $body where the next
1310 * non-whitespace char is located.
1312 function sq_skipspace($body, $offset){
1313 $me = 'sq_skipspace';
1314 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1315 if (sizeof($matches{1})){
1316 $count = strlen($matches{1});
1323 * This function looks for the next character within a string. It's
1324 * really just a glorified "strpos", except it catches if failures
1327 * @param $body The string to look for needle in.
1328 * @param $offset Start looking from this position.
1329 * @param $needle The character/string to look for.
1330 * @return location of the next occurance of the needle, or
1331 * strlen($body) if needle wasn't found.
1333 function sq_findnxstr($body, $offset, $needle){
1334 $me = 'sq_findnxstr';
1335 $pos = strpos($body, $needle, $offset);
1336 if ($pos === FALSE){
1337 $pos = strlen($body);
1343 * This function takes a PCRE-style regexp and tries to match it
1344 * within the string.
1346 * @param $body The string to look for needle in.
1347 * @param $offset Start looking from here.
1348 * @param $reg A PCRE-style regex to match.
1349 * @return Returns a false if no matches found, or an array
1350 * with the following members:
1351 * - integer with the location of the match within $body
1352 * - string with whatever content between offset and the match
1353 * - string with whatever it is we matched
1355 function sq_findnxreg($body, $offset, $reg){
1356 $me = 'sq_findnxreg';
1359 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1360 if (!isset($matches{0}) ||
!$matches{0}){
1363 $retarr{0} = $offset +
strlen($matches{1});
1364 $retarr{1} = $matches{1};
1365 $retarr{2} = $matches{2};
1371 * This function looks for the next tag.
1373 * @param $body String where to look for the next tag.
1374 * @param $offset Start looking from here.
1375 * @return false if no more tags exist in the body, or
1376 * an array with the following members:
1377 * - string with the name of the tag
1378 * - array with attributes and their values
1379 * - integer with tag type (1, 2, or 3)
1380 * - integer where the tag starts (starting "<")
1381 * - integer where the tag ends (ending ">")
1382 * first three members will be false, if the tag is invalid.
1384 function sq_getnxtag($body, $offset){
1385 $me = 'sq_getnxtag';
1386 if ($offset > strlen($body)){
1389 $lt = sq_findnxstr($body, $offset, "<");
1390 if ($lt == strlen($body)){
1395 * blah blah <tag attribute="value">
1398 $pos = sq_skipspace($body, $lt+
1);
1399 if ($pos >= strlen($body)){
1400 return Array(false, false, false, $lt, strlen($body));
1403 * There are 3 kinds of tags:
1404 * 1. Opening tag, e.g.:
1406 * 2. Closing tag, e.g.:
1408 * 3. XHTML-style content-less tag, e.g.:
1409 * <img src="blah" />
1412 switch (substr($body, $pos, 1)){
1419 * A comment or an SGML declaration.
1421 if (substr($body, $pos+
1, 2) == "--"){
1422 $gt = strpos($body, "-->", $pos);
1424 $gt = strlen($body);
1428 return Array(false, false, false, $lt, $gt);
1430 $gt = sq_findnxstr($body, $pos, ">");
1431 return Array(false, false, false, $lt, $gt);
1436 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1446 * Look for next [\W-_], which will indicate the end of the tag name.
1448 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1449 if ($regary == false){
1450 return Array(false, false, false, $lt, strlen($body));
1452 list($pos, $tagname, $match) = $regary;
1453 $tagname = strtolower($tagname);
1456 * $match can be either of these:
1457 * '>' indicating the end of the tag entirely.
1458 * '\s' indicating the end of the tag name.
1459 * '/' indicating that this is type-3 xhtml tag.
1461 * Whatever else we find there indicates an invalid tag.
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
1470 if (substr($body, $pos, 2) == "/>"){
1474 $gt = sq_findnxstr($body, $pos, ">");
1475 $retary = Array(false, false, false, $lt, $gt);
1479 return Array($tagname, false, $tagtype, $lt, $pos);
1483 * Check if it's whitespace
1485 if (!preg_match('/\s/', $match)){
1487 * This is an invalid tag! Look for the next closing ">".
1489 $gt = sq_findnxstr($body, $lt, ">");
1490 return Array(false, false, false, $lt, $gt);
1496 * At this point we're here:
1497 * <tagname attribute='blah'>
1500 * At this point we loop in order to find all attributes.
1506 while ($pos <= strlen($body)){
1507 $pos = sq_skipspace($body, $pos);
1508 if ($pos == strlen($body)){
1512 return Array(false, false, false, $lt, $pos);
1515 * See if we arrived at a ">" or "/>", which means that we reached
1516 * the end of the tag.
1519 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1523 $pos +
= strlen($matches{1});
1524 if ($matches{2} == "/>"){
1528 return Array($tagname, $attary, $tagtype, $lt, $pos);
1532 * There are several types of attributes, with optional
1533 * [:space:] between members.
1535 * attrname[:space:]=[:space:]'CDATA'
1537 * attrname[:space:]=[:space:]"CDATA"
1539 * attr[:space:]=[:space:]CDATA
1543 * We leave types 1 and 2 the same, type 3 we check for
1544 * '"' and convert to """ if needed, then wrap in
1545 * double quotes. Type 4 we convert into:
1548 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1549 if ($regary == false){
1551 * Looks like body ended before the end of tag.
1553 return Array(false, false, false, $lt, strlen($body));
1555 list($pos, $attname, $match) = $regary;
1556 $attname = strtolower($attname);
1558 * We arrived at the end of attribute name. Several things possible
1560 * '>' means the end of the tag and this is attribute type 4
1561 * '/' if followed by '>' means the same thing as above
1562 * '\s' means a lot of things -- look what it's followed by.
1563 * anything else means the attribute is invalid.
1568 * This is an xhtml-style tag with a closing / at the
1569 * end, like so: <img src="blah" />. Check if it's followed
1570 * by the closing bracket. If not, then this tag is invalid
1572 if (substr($body, $pos, 2) == "/>"){
1576 $gt = sq_findnxstr($body, $pos, ">");
1577 $retary = Array(false, false, false, $lt, $gt);
1581 $attary{$attname} = '"yes"';
1582 return Array($tagname, $attary, $tagtype, $lt, $pos);
1586 * Skip whitespace and see what we arrive at.
1588 $pos = sq_skipspace($body, $pos);
1589 $char = substr($body, $pos, 1);
1591 * Two things are valid here:
1592 * '=' means this is attribute type 1 2 or 3.
1593 * \w means this was attribute type 4.
1594 * anything else we ignore and re-loop. End of tag and
1595 * invalid stuff will be caught by our checks at the beginning
1600 $pos = sq_skipspace($body, $pos);
1602 * Here are 3 possibilities:
1603 * "'" attribute type 1
1604 * '"' attribute type 2
1605 * everything else is the content of tag type 3
1607 $quot = substr($body, $pos, 1);
1609 $regary = sq_findnxreg($body, $pos+
1, "\'");
1610 if ($regary == false){
1611 return Array(false, false, false, $lt, strlen($body));
1613 list($pos, $attval, $match) = $regary;
1615 $attary{$attname} = "'" . $attval . "'";
1616 } else if ($quot == '"'){
1617 $regary = sq_findnxreg($body, $pos+
1, '\"');
1618 if ($regary == false){
1619 return Array(false, false, false, $lt, strlen($body));
1621 list($pos, $attval, $match) = $regary;
1623 $attary{$attname} = '"' . $attval . '"';
1626 * These are hateful. Look for \s, or >.
1628 $regary = sq_findnxreg($body, $pos, "[\s>]");
1629 if ($regary == false){
1630 return Array(false, false, false, $lt, strlen($body));
1632 list($pos, $attval, $match) = $regary;
1634 * If it's ">" it will be caught at the top.
1636 $attval = preg_replace("/\"/s", """, $attval);
1637 $attary{$attname} = '"' . $attval . '"';
1639 } else if (preg_match("|[\w/>]|", $char)) {
1641 * That was attribute type 4.
1643 $attary{$attname} = '"yes"';
1646 * An illegal character. Find next '>' and return.
1648 $gt = sq_findnxstr($body, $pos, ">");
1649 return Array(false, false, false, $lt, $gt);
1655 * The fact that we got here indicates that the tag end was never
1656 * found. Return invalid tag indication so it gets stripped.
1658 return Array(false, false, false, $lt, strlen($body));
1662 * Translates entities into literal values so they can be checked.
1664 * @param $attvalue the by-ref value to check.
1665 * @param $regex the regular expression to check against.
1666 * @param $hex whether the entites are hexadecimal.
1667 * @return True or False depending on whether there were matches.
1669 function sq_deent(&$attvalue, $regex, $hex=false){
1673 //$attvalue = preg_replace("/(\/\*.*\*\/)/","",$attvalue);
1674 preg_match_all($regex, $attvalue, $matches);
1675 if (is_array($matches) && sizeof($matches[0]) > 0){
1677 for ($i = 0; $i < sizeof($matches[0]); $i++
){
1678 $numval = $matches[1][$i];
1680 $numval = hexdec($numval);
1682 $repl{$matches[0][$i]} = chr($numval);
1684 $attvalue = strtr($attvalue, $repl);
1692 * This function runs various checks against the attributes.
1694 * @param $tagname String with the name of the tag.
1695 * @param $attary Array with all tag attributes.
1696 * @param $rm_attnames See description for sq_sanitize
1697 * @param $bad_attvals See description for sq_sanitize
1698 * @param $add_attr_to_tag See description for sq_sanitize
1699 * @param $message message object
1700 * @param $id message id
1701 * @return Array with modified attributes.
1703 function sq_fixatts($tagname,
1713 while (list($attname, $attvalue) = each($attary)){
1715 * See if this attribute should be removed.
1717 foreach ($rm_attnames as $matchtag=>$matchattrs){
1718 if (preg_match($matchtag, $tagname)){
1719 foreach ($matchattrs as $matchattr){
1720 if (preg_match($matchattr, $attname)){
1721 unset($attary{$attname});
1728 * Workaround for IE quirks
1730 sq_fixIE_idiocy($attvalue);
1733 * Remove any backslashes, entities, and extraneous whitespace.
1736 $oldattvalue = $attvalue;
1737 sq_defang($attvalue);
1738 if ($attname == 'style' && $attvalue !== $oldattvalue) {
1739 // entities are used in the attribute value. In 99% of the cases it's there as XSS
1740 // i.e.<div style="{ left:expʀessioɴ( alert('XSS') ) }">
1741 $attvalue = "idiocy";
1742 $attary{$attname} = $attvalue;
1744 sq_unspace($attvalue);
1747 * Now let's run checks on the attvalues.
1748 * I don't expect anyone to comprehend this. If you do,
1749 * get in touch with me so I can drive to where you live and
1750 * shake your hand personally. :)
1752 foreach ($bad_attvals as $matchtag=>$matchattrs){
1753 if (preg_match($matchtag, $tagname)){
1754 foreach ($matchattrs as $matchattr=>$valary){
1755 if (preg_match($matchattr, $attname)){
1757 * There are two arrays in valary.
1759 * Second one is replacements
1761 list($valmatch, $valrepl) = $valary;
1763 preg_replace($valmatch, $valrepl, $attvalue);
1764 if ($newvalue != $attvalue){
1765 $attary{$attname} = $newvalue;
1766 $attvalue = $newvalue;
1772 if ($attname == 'style') {
1773 if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
1774 // 8bit and control characters in style attribute values can be used for XSS, remove them
1775 $attary{$attname} = '"disallowed character"';
1777 preg_match_all("/url\s*\((.+)\)/si",$attvalue,$aMatch);
1778 if (count($aMatch)) {
1779 foreach($aMatch[1] as $sMatch) {
1781 $urlvalue = $sMatch;
1782 sq_fix_url($attname, $urlvalue, $message, $id, $mailbox,"'");
1783 $attary{$attname} = str_replace($sMatch,$urlvalue,$attvalue);
1788 * Use white list based filtering on attributes which can contain url's
1790 else if ($attname == 'href' ||
$attname == 'src' ||
$attname == 'background') {
1791 sq_fix_url($attname, $attvalue, $message, $id, $mailbox);
1792 $attary{$attname} = $attvalue;
1796 * See if we need to append any attributes to this tag.
1798 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1799 if (preg_match($matchtag, $tagname)){
1800 $attary = array_merge($attary, $addattary);
1807 * This function filters url's
1809 * @param $attvalue String with attribute value to filter
1810 * @param $message message object
1811 * @param $id message id
1812 * @param $mailbox mailbox
1813 * @param $sQuote quoting characters around url's
1815 function sq_fix_url($attname, &$attvalue, $message, $id, $mailbox,$sQuote = '"') {
1816 $attvalue = trim($attvalue);
1817 if ($attvalue && ($attvalue[0] =='"'||
$attvalue[0] == "'")) {
1818 // remove the double quotes
1819 $sQuote = $attvalue[0];
1820 $attvalue = trim(substr($attvalue,1,-1));
1823 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1824 $view_unsafe_images = false;
1826 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1829 * Replace empty src tags with the blank image. src is only used
1830 * for frames, images, and image inputs. Doing a replace should
1831 * not affect them working as should be, however it will stop
1832 * IE from being kicked off when src for img tags are not set
1834 if ($attvalue == '') {
1835 $attvalue = '"' . SM_PATH
. 'images/blank.png"';
1837 // first, disallow 8 bit characters and control characters
1838 if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
1841 $attvalue = $sQuote . 'http://invalid-stuff-detected.example.com' . $sQuote;
1844 $attvalue = $sQuote . SM_PATH
. 'images/blank.png'. $sQuote;
1848 $aUrl = parse_url($attvalue);
1849 if (isset($aUrl['scheme'])) {
1850 switch(strtolower($aUrl['scheme'])) {
1854 if ($attname != 'href') {
1855 if ($view_unsafe_images == false) {
1856 $attvalue = $sQuote . $secremoveimg . $sQuote;
1858 if (isset($aUrl['path'])) {
1859 // validate image extension.
1860 $ext = strtolower(substr($aUrl['path'],strrpos($aUrl['path'],'.')));
1861 if (!in_array($ext,array('.jpeg','.jpg','xjpeg','.gif','.bmp','.jpe','.png','.xbm'))) {
1862 $attvalue = $sQuote . SM_PATH
. 'images/blank.png'. $sQuote;
1865 $attvalue = $sQuote . SM_PATH
. 'images/blank.png'. $sQuote;
1872 * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
1873 * One day MS might actually make it match something useful, for now, falling
1874 * back to using cid2http, so we can grab the blank.png.
1876 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1880 * Turn cid: urls into http-friendly ones.
1882 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
1885 $attvalue = $sQuote . SM_PATH
. 'images/blank.png' . $sQuote;
1889 if (!(isset($aUrl['path']) && $aUrl['path'] == $secremoveimg)) {
1890 // parse_url did not lead to satisfying result
1891 $attvalue = $sQuote . SM_PATH
. 'images/blank.png' . $sQuote;
1899 * This function edits the style definition to make them friendly and
1900 * usable in SquirrelMail.
1902 * @param $message the message object
1903 * @param $id the message id
1904 * @param $content a string with whatever is between <style> and </style>
1905 * @param $mailbox the message mailbox
1906 * @return a string with edited content.
1908 function sq_fixstyle($body, $pos, $message, $id, $mailbox){
1909 global $view_unsafe_images;
1910 $me = 'sq_fixstyle';
1911 // workaround for </style> in between comments
1912 $iCurrentPos = $pos;
1917 for ($i=$pos,$iCount=strlen($body);$i<$iCount;++
$i) {
1924 if ($sToken == '<') {
1934 if (preg_match('/\<\/\s*style\s*\>/i',$sToken,$aMatch)) {
1939 $content .= $sToken;
1947 if ($sToken == '<') {
1949 if (isset($body{$i+
2}) && substr($body,$i,3) == '!--') {
1950 $i = strpos($body,'-->',$i+
3);
1951 if ($i === false) { // no end comment
1969 if ($bSucces == FALSE){
1970 return array(FALSE, strlen($body));
1976 * First look for general BODY style declaration, which would be
1978 * body {background: blah-blah}
1979 * and change it to .bodyclass so we can just assign it to a <div>
1981 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1982 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1984 * Fix url('blah') declarations.
1986 // $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1987 // "url(\\1$secremoveimg\\2)", $content);
1989 // first check for 8bit sequences and disallowed control characters
1990 if (preg_match('/[\16-\37\200-\377]+/',$content)) {
1991 $content = '<!-- style block removed by html filter due to presence of 8bit characters -->';
1992 return array($content, $newpos);
1995 // IE Sucks hard. We have a special function for it.
1996 sq_fixIE_idiocy($content);
1998 // remove @import line
1999 $content = preg_replace("/^\s*(@import.*)$/mi","\n<!-- @import rules forbidden -->\n",$content);
2001 // translate ur\l and variations (IE parses that)
2002 // TODO check if the sq_fixIE_idiocy function already handles this.
2003 $content = preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i", 'url', $content);
2004 preg_match_all("/url\s*\((.+)\)/si",$content,$aMatch);
2005 if (count($aMatch)) {
2006 $aValue = $aReplace = array();
2007 foreach($aMatch[1] as $sMatch) {
2009 $urlvalue = $sMatch;
2010 sq_fix_url('style',$urlvalue, $message, $id, $mailbox,"'");
2011 $aValue[] = $sMatch;
2012 $aReplace[] = $urlvalue;
2014 $content = str_replace($aValue,$aReplace,$content);
2018 * Remove any backslashes, entities, and extraneous whitespace.
2020 $contentTemp = $content;
2021 sq_defang($contentTemp);
2022 sq_unspace($contentTemp);
2025 * Fix stupid css declarations which lead to vulnerabilities
2028 $match = Array('/\/\*.*\*\//',
2032 '/include-source/i',
2035 $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy');
2036 $contentNew = preg_replace($match, $replace, $contentTemp);
2037 if ($contentNew !== $contentTemp) {
2038 // insecure css declarations are used. From now on we don't care
2039 // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
2040 $content = $contentNew;
2042 return array($content, $newpos);
2047 * This function converts cid: url's into the ones that can be viewed in
2050 * @param $message the message object
2051 * @param $id the message id
2052 * @param $cidurl the cid: url.
2053 * @param $mailbox the message mailbox
2054 * @return a string with a http-friendly url
2056 function sq_cid2http($message, $id, $cidurl, $mailbox){
2058 * Get rid of quotes.
2060 $quotchar = substr($cidurl, 0, 1);
2061 if ($quotchar == '"' ||
$quotchar == "'"){
2062 $cidurl = str_replace($quotchar, "", $cidurl);
2066 $cidurl = substr(trim($cidurl), 4);
2068 $match_str = '/\{.*?\}\//';
2070 $cidurl = preg_replace($match_str, $str_rep, $cidurl);
2072 $linkurl = find_ent_id($cidurl, $message);
2073 /* in case of non-save cid links $httpurl should be replaced by a sort of
2074 unsave link image */
2078 * This is part of a fix for Outlook Express 6.x generating
2079 * cid URLs without creating content-id headers. These images are
2080 * not part of the multipart/related html mail. The html contains
2081 * <img src="cid:{some_id}/image_filename.ext"> references to
2082 * attached images with as goal to render them inline although
2083 * the attachment disposition property is not inline.
2086 if (empty($linkurl)) {
2087 if (preg_match('/{.*}\//', $cidurl)) {
2088 $cidurl = preg_replace('/{.*}\//','', $cidurl);
2089 if (!empty($cidurl)) {
2090 $linkurl = find_ent_id($cidurl, $message);
2095 if (!empty($linkurl)) {
2096 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
2097 "passed_id=$id&mailbox=" . urlencode($mailbox) .
2098 '&ent_id=' . $linkurl . $quotchar;
2101 * If we couldn't generate a proper img url, drop in a blank image
2102 * instead of sending back empty, otherwise it causes unusual behaviour
2104 $httpurl = $quotchar . SM_PATH
. 'images/blank.png' . $quotchar;
2111 * This function changes the <body> tag into a <div> tag since we
2112 * can't really have a body-within-body.
2114 * @param $attary an array of attributes and values of <body>
2115 * @param $mailbox mailbox we're currently reading (for cid2http)
2116 * @param $message current message (for cid2http)
2117 * @param $id current message id (for cid2http)
2118 * @return a modified array of attributes to be set for <div>
2120 function sq_body2div($attary, $mailbox, $message, $id){
2121 $me = 'sq_body2div';
2122 $divattary = Array('class' => "'bodyclass'");
2124 $has_bgc_stl = $has_txt_stl = false;
2126 if (is_array($attary) && sizeof($attary) > 0){
2127 foreach ($attary as $attname=>$attvalue){
2128 $quotchar = substr($attvalue, 0, 1);
2129 $attvalue = str_replace($quotchar, "", $attvalue);
2132 $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
2133 $styledef .= "background-image: url('$attvalue'); ";
2136 $has_bgc_stl = true;
2137 $styledef .= "background-color: $attvalue; ";
2140 $has_txt_stl = true;
2141 $styledef .= "color: $attvalue; ";
2145 // Outlook defines a white bgcolor and no text color. This can lead to
2146 // white text on a white bg with certain themes.
2147 if ($has_bgc_stl && !$has_txt_stl) {
2148 $styledef .= "color: $text; ";
2150 if (strlen($styledef) > 0){
2151 $divattary{"style"} = "\"$styledef\"";
2158 * This is the main function and the one you should actually be calling.
2159 * There are several variables you should be aware of an which need
2160 * special description.
2162 * Since the description is quite lengthy, see it here:
2163 * http://linux.duke.edu/projects/mini/htmlfilter/
2165 * @param $body the string with HTML you wish to filter
2166 * @param $tag_list see description above
2167 * @param $rm_tags_with_content see description above
2168 * @param $self_closing_tags see description above
2169 * @param $force_tag_closing see description above
2170 * @param $rm_attnames see description above
2171 * @param $bad_attvals see description above
2172 * @param $add_attr_to_tag see description above
2173 * @param $message message object
2174 * @param $id message id
2175 * @return sanitized html safe to show on your pages.
2177 function sq_sanitize($body,
2179 $rm_tags_with_content,
2189 $me = 'sq_sanitize';
2190 $rm_tags = array_shift($tag_list);
2192 * Normalize rm_tags and rm_tags_with_content.
2194 @array_walk
($tag_list, 'sq_casenormalize');
2195 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
2196 @array_walk
($self_closing_tags, 'sq_casenormalize');
2198 * See if tag_list is of tags to remove or tags to allow.
2199 * false means remove these tags
2200 * true means allow these tags
2203 $open_tags = Array();
2204 $trusted = "\n<!-- begin sanitized html -->\n";
2205 $skip_content = false;
2207 * Take care of netscape's stupid javascript entities like
2210 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
2212 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
2213 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
2214 $free_content = substr($body, $curpos, $lt-$curpos);
2216 * Take care of <style>
2218 if ($tagname == "style" && $tagtype == 1){
2219 list($free_content, $curpos) =
2220 sq_fixstyle($body, $gt+
1, $message, $id, $mailbox);
2221 if ($free_content != FALSE){
2222 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2223 $trusted .= $free_content;
2224 $trusted .= sq_tagprint($tagname, false, 2);
2228 if ($skip_content == false){
2229 $trusted .= $free_content;
2231 if ($tagname != FALSE){
2233 if ($skip_content == $tagname){
2235 * Got to the end of tag we needed to remove.
2238 $skip_content = false;
2240 if ($skip_content == false){
2241 if ($tagname == "body"){
2244 if (isset($open_tags{$tagname}) &&
2245 $open_tags{$tagname} > 0){
2246 $open_tags{$tagname}--;
2254 * $rm_tags_with_content
2256 if ($skip_content == false){
2258 * See if this is a self-closing type and change
2259 * tagtype appropriately.
2262 && in_array($tagname, $self_closing_tags)){
2266 * See if we should skip this tag and any content
2269 if ($tagtype == 1 &&
2270 in_array($tagname, $rm_tags_with_content)){
2271 $skip_content = $tagname;
2273 if (($rm_tags == false
2274 && in_array($tagname, $tag_list)) ||
2275 ($rm_tags == true &&
2276 !in_array($tagname, $tag_list))){
2280 * Convert body into div.
2282 if ($tagname == "body"){
2284 $attary = sq_body2div($attary, $mailbox,
2288 if (isset($open_tags{$tagname})){
2289 $open_tags{$tagname}++
;
2291 $open_tags{$tagname}=1;
2295 * This is where we run other checks.
2297 if (is_array($attary) && sizeof($attary) > 0){
2298 $attary = sq_fixatts($tagname,
2312 if ($tagname != false && $skip_content == false){
2313 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2318 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
2319 if ($force_tag_closing == true){
2320 foreach ($open_tags as $tagname=>$opentimes){
2321 while ($opentimes > 0){
2322 $trusted .= '</' . $tagname . '>';
2328 $trusted .= "<!-- end sanitized html -->\n";
2333 * This is a wrapper function to call html sanitizing routines.
2335 * @param $body the body of the message
2336 * @param $id the id of the message
2340 * @param boolean $take_mailto_links When TRUE, converts mailto: links
2341 * into internal SM compose links
2342 * (optional; default = TRUE)
2343 * @return a string with html safe to display in the browser.
2345 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
2347 // require_once(SM_PATH . 'functions/url_parser.php'); // for $MailTo_PReg_Match
2349 global $attachment_common_show_images, $view_unsafe_images,
2352 * Don't display attached images in HTML mode.
2356 $attachment_common_show_images = false;
2371 $rm_tags_with_content = Array(
2381 $self_closing_tags = Array(
2389 $force_tag_closing = true;
2391 $rm_attnames = Array(
2402 $secremoveimg = "../images/" . _("sec_remove_eng.png");
2403 $bad_attvals = Array(
2406 "/^src|background/i" =>
2409 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2410 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2411 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2414 "\\1$secremoveimg\\2",
2415 "\\1$secremoveimg\\2",
2416 "\\1$secremoveimg\\2",
2419 "/^href|action/i" =>
2422 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2423 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2424 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2439 "/include-source/i",
2440 "/position\s*:\s*absolute/i",
2441 "/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",
2442 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2443 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2444 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2445 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
2463 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
2464 $view_unsafe_images = false;
2466 if (!$view_unsafe_images){
2468 * Remove any references to http/https if view_unsafe_images set
2471 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2472 '/^([\'\"])\s*https*:.*([\'\"])/si');
2473 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2474 "\\1$secremoveimg\\1");
2475 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2476 '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
2477 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2478 "url(\\1$secremoveimg\\1)");
2481 $add_attr_to_tag = Array(
2483 Array('target'=>'"_blank"',
2484 'title'=>'"'._("This external link will open in a new window").'"'
2487 $trusted = sq_sanitize($body,
2489 $rm_tags_with_content,
2499 if (strpos($trusted,$secremoveimg)){
2500 $has_unsafe_images = true;
2503 // we want to parse mailto's in HTML output, change to SM compose links
2504 // this is a modified version of code from url_parser.php... but Marc is
2505 // right: we need a better filtering implementation; adding this randomly
2506 // here is not a great solution
2508 if ($take_mailto_links) {
2509 // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2510 global $MailTo_PReg_Match;
2511 $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1) ;
2512 if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2513 foreach ($regs[0] as $i => $mailto_before) {
2514 $mailto_params = $regs[10][$i];
2515 // get rid of any tailing quote since we have to add send_to to the end
2517 if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2518 $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2519 if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2520 $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2522 if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2523 $to = 'to=' . $regs[1][$i];
2524 if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2525 $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2527 if ($mailto_params) //already some params, append to them
2528 $mailto_params .= '&' . $to;
2530 $mailto_params .= '?' . $to;
2534 $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2536 // we'll already have target=_blank, no need to allow comp_in_new
2537 // here (which would be a lot more work anyway)
2539 global $compose_new_win;
2540 $temp_comp_in_new = $compose_new_win;
2541 $compose_new_win = 0;
2542 $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2543 $compose_new_win = $temp_comp_in_new;
2545 // remove <a href=" and anything after the next quote (we only
2546 // need the uri, not the link HTML) in compose uri
2548 $comp_uri = substr($comp_uri, 9);
2549 $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2550 $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2559 * function SendDownloadHeaders - send file to the browser
2561 * Original Source: SM core src/download.php
2562 * moved here to make it available to other code, and separate
2563 * front end from back end functionality.
2565 * @param string $type0 first half of mime type
2566 * @param string $type1 second half of mime type
2567 * @param string $filename filename to tell the browser for downloaded file
2568 * @param boolean $force whether to force the download dialog to pop
2569 * @param optional integer $filesize send the Content-Header and length to the browser
2572 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2573 global $languages, $squirrelmail_language;
2574 $isIE = $isIE6plus = false;
2576 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER
);
2578 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2579 strstr($HTTP_USER_AGENT, 'Opera') === false) {
2583 if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
2584 ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
2588 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2589 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename')) {
2591 call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_downloadfilename', $filename, $HTTP_USER_AGENT);
2593 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace(' ', ' ', $filename));
2596 // A Pox on Microsoft and it's Internet Explorer!
2598 // IE has lots of bugs with file downloads.
2599 // It also has problems with SSL. Both of these cause problems
2600 // for us in this function.
2602 // See this article on Cache Control headers and SSL
2603 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2605 // The best thing you can do for IE is to upgrade to the latest
2607 //set all the Cache Control Headers for IE
2609 $filename=rawurlencode($filename);
2610 header ("Pragma: public");
2611 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2612 header ("Cache-Control: post-check=0, pre-check=0", false);
2613 header ("Cache-Control: private");
2615 //set the inline header for IE, we'll add the attachment header later if we need it
2616 header ("Content-Disposition: inline; filename=$filename");
2620 // Try to show in browser window
2621 header ("Content-Disposition: inline; filename=\"$filename\"");
2622 header ("Content-Type: $type0/$type1; name=\"$filename\"");
2624 // Try to pop up the "save as" box
2626 // IE makes this hard. It pops up 2 save boxes, or none.
2627 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2628 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2629 // But, according to Microsoft, it is "RFC compliant but doesn't
2630 // take into account some deviations that allowed within the
2631 // specification." Doesn't that mean RFC non-compliant?
2632 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2634 // all browsers need the application/octet-stream header for this
2635 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2637 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2638 // Do not have quotes around filename, but that applied to
2639 // "attachment"... does it apply to inline too?
2640 header ("Content-Disposition: attachment; filename=\"$filename\"");
2642 if ($isIE && !$isIE6plus) {
2643 // This combination seems to work mostly. IE 5.5 SP 1 has
2644 // known issues (see the Microsoft Knowledge Base)
2646 // This works for most types, but doesn't work with Word files
2647 header ("Content-Type: application/download; name=\"$filename\"");
2648 header ("Content-Type: application/force-download; name=\"$filename\"");
2649 // These are spares, just in case. :-)
2650 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2651 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2652 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2654 // This is to prevent IE for MIME sniffing and auto open a file in IE
2655 header ("Content-Type: application/force-download; name=\"$filename\"");
2657 // another application/octet-stream forces download for Netscape
2658 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2662 //send the content-length header if the calling function provides it
2663 if ($filesize > 0) {
2664 header("Content-Length: $filesize");
2667 } // end fn SendDownloadHeaders