933523b55a66a179f2c35efcc18eeb737d329351
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This contains the functions necessary to detect and decode MIME
15 require_once(SM_PATH
. 'functions/imap.php');
16 require_once(SM_PATH
. 'functions/attachment_common.php');
18 /* -------------------------------------------------------------------------- */
20 /* -------------------------------------------------------------------------- */
22 /* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
27 function mime_structure ($bodystructure, $flags=array()) {
29 /* Isolate the body structure and remove beginning and end parenthesis. */
30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') +
13));
31 $read = trim(substr ($read, 0, -1));
33 $msg = Message
::parseStructure($read,$i);
34 if (!is_object($msg)) {
35 include_once(SM_PATH
. 'functions/display_messages.php');
36 global $color, $mailbox;
37 /* removed urldecode because $_GET is auto urldecoded ??? */
38 displayPageHeader( $color, $mailbox );
39 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
40 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
41 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
42 plain_error_message( $errormessage, $color );
43 echo '</body></html>';
47 foreach ($flags as $flag) {
48 $char = strtoupper($flag{1});
51 if (strtolower($flag) == '\\seen') {
56 if (strtolower($flag) == '\\answered') {
57 $msg->is_answered
= true;
61 if (strtolower($flag) == '\\deleted') {
62 $msg->is_deleted
= true;
66 if (strtolower($flag) == '\\flagged') {
67 $msg->is_flagged
= true;
71 if (strtolower($flag) == '$mdnsent') {
72 $msg->is_mdnsent
= true;
80 // listEntities($msg);
86 /* This starts the parsing of a particular structure. It is called recursively,
87 * so it can be passed different structures. It returns an object of type
89 * First, it checks to see if it is a multipart message. If it is, then it
90 * handles that as it sees is necessary. If it is just a regular entity,
91 * then it parses it and adds the necessary header information (by calling out
92 * to mime_get_elements()
95 function mime_fetch_body($imap_stream, $id, $ent_id=1) {
97 /* Do a bit of error correction. If we couldn't find the entity id, just guess
98 * that it is the first one. That is usually the case anyway.
102 $cmd = "FETCH $id BODY[]";
104 $cmd = "FETCH $id BODY[$ent_id]";
107 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
109 $topline = trim(array_shift($data));
110 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
112 $wholemessage = implode('', $data);
113 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
114 $ret = substr($wholemessage, 0, $regs[1]);
115 /* There is some information in the content info header that could be important
116 * in order to parse html messages. Let's get them here.
118 // if ($ret{0} == '<') {
119 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
121 } else if (ereg('"([^"]*)"', $topline, $regs)) {
124 global $where, $what, $mailbox, $passed_id, $startMessage;
125 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
126 if (isset($where) && isset($what)) {
127 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
129 $par .= '&startMessage=' . $startMessage . '&show_more=0';
131 $par .= '&response=' . urlencode($response) .
132 '&message=' . urlencode($message) .
133 '&topline=' . urlencode($topline);
136 '<table width="80%"><tr>' .
137 '<tr><td colspan=2>' .
138 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
140 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
141 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
142 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
143 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
144 "</table><BR></tt></font><hr>";
146 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
148 $wholemessage = implode('', $data);
150 $ret = $wholemessage;
155 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
158 /* Don't kill the connection if the browser is over a dialup
159 * and it would take over 30 seconds to download it.
160 * DonĀ“t call set_time_limit in safe mode.
163 if (!ini_get('safe_mode')) {
166 /* in case of base64 encoded attachments, do not buffer them.
167 Instead, echo the decoded attachment directly to screen */
168 if (strtolower($encoding) == 'base64') {
170 $query = "FETCH $id BODY[]";
172 $query = "FETCH $id BODY[$ent_id]";
174 sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
176 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
177 echo decodeBody($body, $encoding);
181 TODO, use the same method for quoted printable.
182 However, I assume that quoted printable attachments aren't that large
183 so the performancegain / memory usage drop will be minimal.
184 If we decide to add that then we need to adapt sqimap_fread because
185 we need to split te result on \n and fread doesn't stop at \n. That
186 means we also should provide $results from sqimap_fread (by ref) to
187 te function and set $no_return to false. The $filter function for
188 quoted printable should handle unsetting of $results.
191 TODO 2: find out how we write to the output stream php://stdout. fwrite
192 doesn't work because 'php://stdout isn't a stream.
197 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
200 $read = fgets ($imap_stream,8192);
203 // This could be bad -- if the section has sqimap_session_id() . ' OK'
204 // or similar, it will kill the download.
205 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
206 if (trim($read) == ')==') {
208 $read = fgets ($imap_stream,4096);
209 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
212 echo decodeBody($read1, $encoding) .
213 decodeBody($read, $encoding);
216 echo decodeBody($read, $encoding);
218 $read = fgets ($imap_stream,4096);
225 /* -[ END MIME DECODING ]----------------------------------------------------------- */
227 /* This is here for debugging purposes. It will print out a list
228 * of all the entity IDs that are in the $message object.
230 function listEntities ($message) {
232 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
233 for ($i = 0; isset($message->entities
[$i]); $i++
) {
235 $msg = listEntities($message->entities
[$i]);
245 function getPriorityStr($priority) {
246 $priority_level = substr($priority,0,1);
248 switch($priority_level) {
249 /* Check for a higher then normal priority. */
252 $priority_string = _("High");
255 /* Check for a lower then normal priority. */
258 $priority_string = _("Low");
261 /* Check for a normal priority. */
264 $priority_level = '3';
265 $priority_string = _("Normal");
269 return $priority_string;
272 /* returns a $message object for a particular entity id */
273 function getEntity ($message, $ent_id) {
274 return $message->getEntity($ent_id);
278 * Extracted from strings.php 23/03/2002
281 function translateText(&$body, $wrap_at, $charset) {
282 global $where, $what; /* from searching */
283 global $color; /* color theme */
285 require_once(SM_PATH
. 'functions/url_parser.php');
287 $body_ary = explode("\n", $body);
288 for ($i=0; $i < count($body_ary); $i++
) {
289 $line = $body_ary[$i];
290 if (strlen($line) - 2 >= $wrap_at) {
291 sqWordWrap($line, $wrap_at);
293 $line = charset_decode($charset, $line);
294 $line = str_replace("\t", ' ', $line);
303 if ($line[$pos] == ' ') {
305 } else if (strpos($line, '>', $pos) === $pos) {
314 if (!isset($color[13])) {
315 $color[13] = '#800000';
317 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
319 if (!isset($color[14])) {
320 $color[14] = '#FF0000';
322 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
325 $body_ary[$i] = $line;
327 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
330 /* This returns a parsed string called $body. That string can then
331 * be displayed as the actual message in the HTML. It contains
332 * everything needed, including HTML Tags, Attachments at the
335 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
336 /* This if statement checks for the entity to show as the
337 * primary message. To add more of them, just put them in the
338 * order that is their priority.
340 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
341 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
342 global $languages, $squirrelmail_language;
344 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
345 $view_unsafe_images = false;
349 $urlmailbox = urlencode($mailbox);
350 $body_message = getEntity($message, $ent_num);
351 if (($body_message->header
->type0
== 'text') ||
352 ($body_message->header
->type0
== 'rfc822')) {
353 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
354 $body = decodeBody($body, $body_message->header
->encoding
);
356 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
357 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
358 if (mb_detect_encoding($body) != 'ASCII') {
359 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
362 $hookResults = do_hook("message_body", $body);
363 $body = $hookResults[1];
365 /* If there are other types that shouldn't be formatted, add
369 if ($body_message->header
->type1
== 'html') {
370 if ($show_html_default <> 1) {
371 $entity_conv = array(' ' => ' ',
378 $body = strtr($body, $entity_conv);
379 $body = strip_tags($body);
381 translateText($body, $wrap_at,
382 $body_message->header
->getParameter('charset'));
384 $body = magicHTML($body, $id, $message, $mailbox);
387 translateText($body, $wrap_at,
388 $body_message->header
->getParameter('charset'));
390 $link = 'read_body.php?passed_id=' . $id . '&ent_id='.$ent_num.
391 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
392 '&startMessage=' . $startMessage . '&show_more=0';
393 if (isset($passed_ent_id)) {
394 $link .= '&passed_ent_id='.$passed_ent_id;
396 if ($view_unsafe_images) {
397 $text = _("Hide Unsafe Images");
399 if (isset($has_unsafe_images) && $has_unsafe_images) {
400 $link .= '&view_unsafe_images=1';
401 $text = _("View Unsafe Images");
406 $body .= '<center><small><a href="'.$link.'">'.$text.
407 '</a></small></center><br>' . "\n";
413 function formatAttachments($message, $exclude_id, $mailbox, $id) {
414 global $where, $what, $startMessage, $color;
415 static $ShownHTML = 0;
417 $att_ar = $message->getAttachments($exclude_id);
419 if (!count($att_ar)) return '';
423 $urlMailbox = urlencode($mailbox);
425 foreach ($att_ar as $att) {
426 $ent = $att->entity_id
;
427 $header = $att->header
;
428 $type0 = strtolower($header->type0
);
429 $type1 = strtolower($header->type1
);
431 $links['download link']['text'] = _("download");
432 $links['download link']['href'] = SM_PATH
.
433 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
435 if ($type0 =='message' && $type1 == 'rfc822') {
436 $default_page = SM_PATH
. 'src/read_body.php';
437 $rfc822_header = $att->rfc822_header
;
438 $filename = $rfc822_header->subject
;
439 if (trim( $filename ) == '') {
440 $filename = 'untitled-[' . $ent . ']' ;
442 $from_o = $rfc822_header->from
;
443 if (is_object($from_o)) {
444 $from_name = decodeHeader($from_o->getAddress(false));
446 $from_name = _("Unknown sender");
448 $description = $from_name;
450 $default_page = SM_PATH
. 'src/download.php';
451 if (is_object($header->disposition
)) {
452 $filename = $header->disposition
->getProperty('filename');
453 if (trim($filename) == '') {
454 $name = decodeHeader($header->disposition
->getProperty('name'));
455 if (trim($name) == '') {
456 $name = $header->getParameter('name');
457 if(trim($name) == '') {
458 if (trim( $header->id
) == '') {
459 $filename = 'untitled-[' . $ent . ']' ;
461 $filename = 'cid: ' . $header->id
;
471 $filename = $header->getParameter('name');
472 if (!trim($filename)) {
473 if (trim( $header->id
) == '') {
474 $filename = 'untitled-[' . $ent . ']' ;
476 $filename = 'cid: ' . $header->id
;
480 if ($header->description
) {
481 $description = decodeHeader($header->description
);
487 $display_filename = $filename;
488 if (isset($passed_ent_id)) {
489 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
491 $passed_ent_id_link = '';
493 $defaultlink = $default_page . "?startMessage=$startMessage"
494 . "&passed_id=$id&mailbox=$urlMailbox"
495 . '&ent_id='.$ent.$passed_ent_id_link;
496 if ($where && $what) {
497 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
499 /* This executes the attachment hook with a specific MIME-type.
500 * If that doesn't have results, it tries if there's a rule
501 * for a more generic type.
503 $hookresults = do_hook("attachment $type0/$type1", $links,
504 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
505 $display_filename, $where, $what);
506 if(count($hookresults[1]) <= 1) {
507 $hookresults = do_hook("attachment $type0/*", $links,
508 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
509 $display_filename, $where, $what);
512 $links = $hookresults[1];
513 $defaultlink = $hookresults[6];
515 $attachments .= '<TR><TD>' .
516 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A> </TD>' .
517 '<TD><SMALL><b>' . show_readable_size($header->size
) .
518 '</b> </small></TD>' .
519 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
521 $attachments .= '<b>' . $description . '</b>';
522 $attachments .= '</SMALL></TD><TD><SMALL> ';
525 foreach ($links as $val) {
529 $attachments .= ' | ';
531 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
534 $attachments .= "</TD></TR>\n";
536 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
537 if ($attachmentadd != '')
538 $attachments = $attachmentadd;
542 function sqimap_base64_decode(&$string) {
543 $string = str_replace("\r\n", "\n", $string);
544 $string = base64_decode($string);
547 /* This function decodes the body depending on the encoding type. */
548 function decodeBody($body, $encoding) {
549 global $show_html_default;
551 $body = str_replace("\r\n", "\n", $body);
552 $encoding = strtolower($encoding);
554 $encoding_handler = do_hook_function('decode_body', $encoding);
557 // plugins get first shot at decoding the body
559 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
560 $body = $encoding_handler('decode', $body);
562 } else if ($encoding == 'quoted-printable' ||
563 $encoding == 'quoted_printable') {
564 $body = quoted_printable_decode($body);
566 while (ereg("=\n", $body)) {
567 $body = ereg_replace ("=\n", '', $body);
570 } else if ($encoding == 'base64') {
571 $body = base64_decode($body);
574 // All other encodings are returned raw.
579 * This functions decode strings that is encoded according to
580 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
581 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
583 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
584 global $languages, $squirrelmail_language;
585 if (is_array($string)) {
586 $string = implode("\n", $string);
589 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
590 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
591 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
592 // Do we need to return at this point?
599 $aString = explode(' ',$string);
601 foreach ($aString as $chunk) {
602 if ($encoded && $chunk === '') {
604 } elseif ($chunk === '') {
609 /* if encoded words are not separated by a linear-space-white we still catch them */
611 // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
612 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
613 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
614 if ($iLastMatch !== $j) {
624 $encoding = ucfirst($res[3]);
628 $replace = base64_decode($res[4]);
629 $ret .= charset_decode($res[2],$replace);
632 $replace = str_replace('_', ' ', $res[4]);
633 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
635 /* Only encode into entities by default. Some places
636 * don't need the encoding, like the compose form.
639 $replace = charset_decode($res[2], $replace);
642 $replace = htmlspecialchars($replace);
662 if (!$encoded && $htmlsave) {
663 $ret .= htmlspecialchars($chunk);
669 /* remove the first added space */
672 $ret = substr($ret,6);
674 $ret = substr($ret,1);
682 * Encode a string according to RFC 1522 for use in headers if it
683 * contains 8-bit characters or anything that looks like it should
686 function encodeHeader ($string) {
687 global $default_charset, $languages, $squirrelmail_language;
689 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
690 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
691 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
693 if (strtolower($default_charset) == 'iso-8859-1') {
694 $string = str_replace("\240",' ',$string);
697 // Encode only if the string contains 8-bit characters or =?
698 $j = strlen($string);
699 $max_l = 75 - strlen($default_charset) - 7;
702 $iEncStart = $enc_init = false;
703 $cur_l = $iOffset = 0;
704 for($i = 0; $i < $j; ++
$i) {
713 if ($iEncStart === false) {
717 if ($cur_l > ($max_l-2)) {
718 /* if there is an stringpart that doesn't need encoding, add it */
719 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
720 $aRet[] = "=?$default_charset?Q?$ret?=";
726 $ret .= sprintf("=%02X",ord($string{$i}));
731 if ($iEncStart !== false) {
732 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
733 $aRet[] = "=?$default_charset?Q?$ret?=";
741 if ($iEncStart !== false) {
743 if ($cur_l > $max_l) {
744 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
745 $aRet[] = "=?$default_charset?Q?$ret?=";
756 $k = ord($string{$i});
758 if ($iEncStart === false) {
759 // do not start encoding in the middle of a string, also take the rest of the word.
760 $sLeadString = substr($string,0,$i);
761 $aLeadString = explode(' ',$sLeadString);
762 $sToBeEncoded = array_pop($aLeadString);
763 $iEncStart = $i - strlen($sToBeEncoded);
764 $ret .= $sToBeEncoded;
765 $cur_l +
= strlen($sToBeEncoded);
768 /* first we add the encoded string that reached it's max size */
769 if ($cur_l > ($max_l-2)) {
770 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
771 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
778 $ret .= sprintf("=%02X", $k);
780 if ($iEncStart !== false) {
782 if ($cur_l > $max_l) {
783 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
784 $aRet[] = "=?$default_charset?Q?$ret?=";
799 if ($iEncStart !== false) {
800 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
801 $aRet[] = "=?$default_charset?Q?$ret?=";
803 $aRet[] = substr($string,$iOffset);
805 $string = implode('',$aRet);
810 /* This function trys to locate the entity_id of a specific mime element */
811 function find_ent_id($id, $message) {
812 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
813 if ($message->entities
[$i]->header
->type0
== 'multipart') {
814 $ret = find_ent_id($id, $message->entities
[$i]);
816 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
817 // if (sq_check_save_extension($message->entities[$i])) {
818 return $message->entities
[$i]->entity_id
;
826 function sq_check_save_extension($message) {
827 $filename = $message->getFilename();
828 $ext = substr($filename, strrpos($filename,'.')+
1);
829 $save_extensions = array('jpg','jpeg','gif','png','bmp');
830 return in_array($ext, $save_extensions);
835 ** HTMLFILTER ROUTINES
839 * This function returns the final tag out of the tag name, an array
840 * of attributes, and the type of the tag. This function is called by
841 * sq_sanitize internally.
843 * @param $tagname the name of the tag.
844 * @param $attary the array of attributes and their values
845 * @param $tagtype The type of the tag (see in comments).
846 * @return a string with the final tag representation.
848 function sq_tagprint($tagname, $attary, $tagtype){
852 $fulltag = '</' . $tagname . '>';
854 $fulltag = '<' . $tagname;
855 if (is_array($attary) && sizeof($attary)){
857 while (list($attname, $attvalue) = each($attary)){
858 array_push($atts, "$attname=$attvalue");
860 $fulltag .= ' ' . join(" ", $atts);
871 * A small helper function to use with array_walk. Modifies a by-ref
872 * value and makes it lowercase.
874 * @param $val a value passed by-ref.
875 * @return void since it modifies a by-ref value.
877 function sq_casenormalize(&$val){
878 $val = strtolower($val);
882 * This function skips any whitespace from the current position within
883 * a string and to the next non-whitespace value.
885 * @param $body the string
886 * @param $offset the offset within the string where we should start
887 * looking for the next non-whitespace character.
888 * @return the location within the $body where the next
889 * non-whitespace char is located.
891 function sq_skipspace($body, $offset){
892 $me = 'sq_skipspace';
893 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
894 if (sizeof($matches{1})){
895 $count = strlen($matches{1});
902 * This function looks for the next character within a string. It's
903 * really just a glorified "strpos", except it catches if failures
906 * @param $body The string to look for needle in.
907 * @param $offset Start looking from this position.
908 * @param $needle The character/string to look for.
909 * @return location of the next occurance of the needle, or
910 * strlen($body) if needle wasn't found.
912 function sq_findnxstr($body, $offset, $needle){
913 $me = 'sq_findnxstr';
914 $pos = strpos($body, $needle, $offset);
916 $pos = strlen($body);
922 * This function takes a PCRE-style regexp and tries to match it
925 * @param $body The string to look for needle in.
926 * @param $offset Start looking from here.
927 * @param $reg A PCRE-style regex to match.
928 * @return Returns a false if no matches found, or an array
929 * with the following members:
930 * - integer with the location of the match within $body
931 * - string with whatever content between offset and the match
932 * - string with whatever it is we matched
934 function sq_findnxreg($body, $offset, $reg){
935 $me = 'sq_findnxreg';
938 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
939 if (!isset($matches{0}) ||
!$matches{0}){
942 $retarr{0} = $offset +
strlen($matches{1});
943 $retarr{1} = $matches{1};
944 $retarr{2} = $matches{2};
950 * This function looks for the next tag.
952 * @param $body String where to look for the next tag.
953 * @param $offset Start looking from here.
954 * @return false if no more tags exist in the body, or
955 * an array with the following members:
956 * - string with the name of the tag
957 * - array with attributes and their values
958 * - integer with tag type (1, 2, or 3)
959 * - integer where the tag starts (starting "<")
960 * - integer where the tag ends (ending ">")
961 * first three members will be false, if the tag is invalid.
963 function sq_getnxtag($body, $offset){
965 if ($offset > strlen($body)){
968 $lt = sq_findnxstr($body, $offset, "<");
969 if ($lt == strlen($body)){
974 * blah blah <tag attribute="value">
977 $pos = sq_skipspace($body, $lt+
1);
978 if ($pos >= strlen($body)){
979 return Array(false, false, false, $lt, strlen($body));
982 * There are 3 kinds of tags:
983 * 1. Opening tag, e.g.:
985 * 2. Closing tag, e.g.:
987 * 3. XHTML-style content-less tag, e.g.:
991 switch (substr($body, $pos, 1)){
998 * A comment or an SGML declaration.
1000 if (substr($body, $pos+
1, 2) == "--"){
1001 $gt = strpos($body, "-->", $pos);
1003 $gt = strlen($body);
1007 return Array(false, false, false, $lt, $gt);
1009 $gt = sq_findnxstr($body, $pos, ">");
1010 return Array(false, false, false, $lt, $gt);
1015 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1025 * Look for next [\W-_], which will indicate the end of the tag name.
1027 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1028 if ($regary == false){
1029 return Array(false, false, false, $lt, strlen($body));
1031 list($pos, $tagname, $match) = $regary;
1032 $tagname = strtolower($tagname);
1035 * $match can be either of these:
1036 * '>' indicating the end of the tag entirely.
1037 * '\s' indicating the end of the tag name.
1038 * '/' indicating that this is type-3 xhtml tag.
1040 * Whatever else we find there indicates an invalid tag.
1045 * This is an xhtml-style tag with a closing / at the
1046 * end, like so: <img src="blah"/>. Check if it's followed
1047 * by the closing bracket. If not, then this tag is invalid
1049 if (substr($body, $pos, 2) == "/>"){
1053 $gt = sq_findnxstr($body, $pos, ">");
1054 $retary = Array(false, false, false, $lt, $gt);
1058 return Array($tagname, false, $tagtype, $lt, $pos);
1062 * Check if it's whitespace
1064 if (!preg_match('/\s/', $match)){
1066 * This is an invalid tag! Look for the next closing ">".
1068 $gt = sq_findnxstr($body, $lt, ">");
1069 return Array(false, false, false, $lt, $gt);
1075 * At this point we're here:
1076 * <tagname attribute='blah'>
1079 * At this point we loop in order to find all attributes.
1085 while ($pos <= strlen($body)){
1086 $pos = sq_skipspace($body, $pos);
1087 if ($pos == strlen($body)){
1091 return Array(false, false, false, $lt, $pos);
1094 * See if we arrived at a ">" or "/>", which means that we reached
1095 * the end of the tag.
1098 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1102 $pos +
= strlen($matches{1});
1103 if ($matches{2} == "/>"){
1107 return Array($tagname, $attary, $tagtype, $lt, $pos);
1111 * There are several types of attributes, with optional
1112 * [:space:] between members.
1114 * attrname[:space:]=[:space:]'CDATA'
1116 * attrname[:space:]=[:space:]"CDATA"
1118 * attr[:space:]=[:space:]CDATA
1122 * We leave types 1 and 2 the same, type 3 we check for
1123 * '"' and convert to """ if needed, then wrap in
1124 * double quotes. Type 4 we convert into:
1127 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1128 if ($regary == false){
1130 * Looks like body ended before the end of tag.
1132 return Array(false, false, false, $lt, strlen($body));
1134 list($pos, $attname, $match) = $regary;
1135 $attname = strtolower($attname);
1137 * We arrived at the end of attribute name. Several things possible
1139 * '>' means the end of the tag and this is attribute type 4
1140 * '/' if followed by '>' means the same thing as above
1141 * '\s' means a lot of things -- look what it's followed by.
1142 * anything else means the attribute is invalid.
1147 * This is an xhtml-style tag with a closing / at the
1148 * end, like so: <img src="blah"/>. Check if it's followed
1149 * by the closing bracket. If not, then this tag is invalid
1151 if (substr($body, $pos, 2) == "/>"){
1155 $gt = sq_findnxstr($body, $pos, ">");
1156 $retary = Array(false, false, false, $lt, $gt);
1160 $attary{$attname} = '"yes"';
1161 return Array($tagname, $attary, $tagtype, $lt, $pos);
1165 * Skip whitespace and see what we arrive at.
1167 $pos = sq_skipspace($body, $pos);
1168 $char = substr($body, $pos, 1);
1170 * Two things are valid here:
1171 * '=' means this is attribute type 1 2 or 3.
1172 * \w means this was attribute type 4.
1173 * anything else we ignore and re-loop. End of tag and
1174 * invalid stuff will be caught by our checks at the beginning
1179 $pos = sq_skipspace($body, $pos);
1181 * Here are 3 possibilities:
1182 * "'" attribute type 1
1183 * '"' attribute type 2
1184 * everything else is the content of tag type 3
1186 $quot = substr($body, $pos, 1);
1188 $regary = sq_findnxreg($body, $pos+
1, "\'");
1189 if ($regary == false){
1190 return Array(false, false, false, $lt, strlen($body));
1192 list($pos, $attval, $match) = $regary;
1194 $attary{$attname} = "'" . $attval . "'";
1195 } else if ($quot == '"'){
1196 $regary = sq_findnxreg($body, $pos+
1, '\"');
1197 if ($regary == false){
1198 return Array(false, false, false, $lt, strlen($body));
1200 list($pos, $attval, $match) = $regary;
1202 $attary{$attname} = '"' . $attval . '"';
1205 * These are hateful. Look for \s, or >.
1207 $regary = sq_findnxreg($body, $pos, "[\s>]");
1208 if ($regary == false){
1209 return Array(false, false, false, $lt, strlen($body));
1211 list($pos, $attval, $match) = $regary;
1213 * If it's ">" it will be caught at the top.
1215 $attval = preg_replace("/\"/s", """, $attval);
1216 $attary{$attname} = '"' . $attval . '"';
1218 } else if (preg_match("|[\w/>]|", $char)) {
1220 * That was attribute type 4.
1222 $attary{$attname} = '"yes"';
1225 * An illegal character. Find next '>' and return.
1227 $gt = sq_findnxstr($body, $pos, ">");
1228 return Array(false, false, false, $lt, $gt);
1234 * The fact that we got here indicates that the tag end was never
1235 * found. Return invalid tag indication so it gets stripped.
1237 return Array(false, false, false, $lt, strlen($body));
1241 * This function checks attribute values for entity-encoded values
1242 * and returns them translated into 8-bit strings so we can run
1245 * @param $attvalue A string to run entity check against.
1246 * @return Translated value.
1248 function sq_deent($attvalue){
1251 * See if we have to run the checks first. All entities must start
1254 if (strpos($attvalue, "&") === false){
1258 * Check named entities first.
1260 $trans = get_html_translation_table(HTML_ENTITIES
);
1262 * Leave " in, as it can mess us up.
1264 $trans = array_flip($trans);
1265 unset($trans{"""});
1266 while (list($ent, $val) = each($trans)){
1267 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1270 * Now translate numbered entities from 1 to 255 if needed.
1272 if (strpos($attvalue, "#") !== false){
1273 $omit = Array(34, 39);
1274 for ($asc=1; $asc<256; $asc++
){
1275 if (!in_array($asc, $omit)){
1277 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1279 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1280 "$chr\\1", $attvalue);
1288 * This function runs various checks against the attributes.
1290 * @param $tagname String with the name of the tag.
1291 * @param $attary Array with all tag attributes.
1292 * @param $rm_attnames See description for sq_sanitize
1293 * @param $bad_attvals See description for sq_sanitize
1294 * @param $add_attr_to_tag See description for sq_sanitize
1295 * @param $message message object
1296 * @param $id message id
1297 * @return Array with modified attributes.
1299 function sq_fixatts($tagname,
1309 while (list($attname, $attvalue) = each($attary)){
1311 * See if this attribute should be removed.
1313 foreach ($rm_attnames as $matchtag=>$matchattrs){
1314 if (preg_match($matchtag, $tagname)){
1315 foreach ($matchattrs as $matchattr){
1316 if (preg_match($matchattr, $attname)){
1317 unset($attary{$attname});
1324 * Remove any entities.
1326 $attvalue = sq_deent($attvalue);
1329 * Now let's run checks on the attvalues.
1330 * I don't expect anyone to comprehend this. If you do,
1331 * get in touch with me so I can drive to where you live and
1332 * shake your hand personally. :)
1334 foreach ($bad_attvals as $matchtag=>$matchattrs){
1335 if (preg_match($matchtag, $tagname)){
1336 foreach ($matchattrs as $matchattr=>$valary){
1337 if (preg_match($matchattr, $attname)){
1339 * There are two arrays in valary.
1341 * Second one is replacements
1343 list($valmatch, $valrepl) = $valary;
1345 preg_replace($valmatch, $valrepl, $attvalue);
1346 if ($newvalue != $attvalue){
1347 $attary{$attname} = $newvalue;
1354 * Turn cid: urls into http-friendly ones.
1356 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1357 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1361 * See if we need to append any attributes to this tag.
1363 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1364 if (preg_match($matchtag, $tagname)){
1365 $attary = array_merge($attary, $addattary);
1372 * This function edits the style definition to make them friendly and
1373 * usable in squirrelmail.
1375 * @param $message the message object
1376 * @param $id the message id
1377 * @param $content a string with whatever is between <style> and </style>
1378 * @return a string with edited content.
1380 function sq_fixstyle($body, $pos, $message, $id){
1381 global $view_unsafe_images;
1382 $me = 'sq_fixstyle';
1383 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1385 return array(FALSE, strlen($body));
1387 $newpos = $ret[0] +
strlen($ret[2]);
1390 * First look for general BODY style declaration, which would be
1392 * body {background: blah-blah}
1393 * and change it to .bodyclass so we can just assign it to a <div>
1395 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1396 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1398 * Fix url('blah') declarations.
1400 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1401 "url(\\1$secremoveimg\\2)", $content);
1403 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1406 if (!$view_unsafe_images){
1407 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1408 "url(\\1$secremoveimg\\2)", $content);
1412 * Fix urls that refer to cid:
1414 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1415 $content, $matches)){
1416 $cidurl = $matches{1};
1417 $httpurl = sq_cid2http($message, $id, $cidurl);
1418 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1419 "url($httpurl)", $content);
1423 * Fix stupid css declarations which lead to vulnerabilities
1426 $match = Array('/expression/i',
1429 $replace = Array('idiocy', 'idiocy', 'idiocy');
1430 $content = preg_replace($match, $replace, $content);
1431 return array($content, $newpos);
1435 * This function converts cid: url's into the ones that can be viewed in
1438 * @param $message the message object
1439 * @param $id the message id
1440 * @param $cidurl the cid: url.
1441 * @return a string with a http-friendly url
1443 function sq_cid2http($message, $id, $cidurl, $mailbox){
1445 * Get rid of quotes.
1447 $quotchar = substr($cidurl, 0, 1);
1448 $cidurl = str_replace($quotchar, "", $cidurl);
1449 $cidurl = substr(trim($cidurl), 4);
1450 $linkurl = find_ent_id($cidurl, $message);
1451 /* in case of non-save cid links $httpurl should be replaced by a sort of
1452 unsave link image */
1455 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1456 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1457 '&ent_id=' . $linkurl . $quotchar;
1463 * This function changes the <body> tag into a <div> tag since we
1464 * can't really have a body-within-body.
1466 * @param $attary an array of attributes and values of <body>
1467 * @return a modified array of attributes to be set for <div>
1469 function sq_body2div($attary){
1470 $me = 'sq_body2div';
1471 $divattary = Array('class' => "'bodyclass'");
1472 $bgcolor = '#ffffff';
1475 if (is_array($attary) && sizeof($attary) > 0){
1476 foreach ($attary as $attname=>$attvalue){
1477 $quotchar = substr($attvalue, 0, 1);
1478 $attvalue = str_replace($quotchar, "", $attvalue);
1481 $styledef .= "background-image: url('$attvalue'); ";
1484 $styledef .= "background-color: $attvalue; ";
1487 $styledef .= "color: $attvalue; ";
1491 if (strlen($styledef) > 0){
1492 $divattary{"style"} = "\"$styledef\"";
1499 * This is the main function and the one you should actually be calling.
1500 * There are several variables you should be aware of an which need
1501 * special description.
1503 * Since the description is quite lengthy, see it here:
1504 * http://www.mricon.com/html/phpfilter.html
1506 * @param $body the string with HTML you wish to filter
1507 * @param $tag_list see description above
1508 * @param $rm_tags_with_content see description above
1509 * @param $self_closing_tags see description above
1510 * @param $force_tag_closing see description above
1511 * @param $rm_attnames see description above
1512 * @param $bad_attvals see description above
1513 * @param $add_attr_to_tag see description above
1514 * @param $message message object
1515 * @param $id message id
1516 * @return sanitized html safe to show on your pages.
1518 function sq_sanitize($body,
1520 $rm_tags_with_content,
1530 $me = 'sq_sanitize';
1531 $rm_tags = array_shift($tag_list);
1533 * Normalize rm_tags and rm_tags_with_content.
1535 @array_walk
($tag_list, 'sq_casenormalize');
1536 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1537 @array_walk
($self_closing_tags, 'sq_casenormalize');
1539 * See if tag_list is of tags to remove or tags to allow.
1540 * false means remove these tags
1541 * true means allow these tags
1544 $open_tags = Array();
1545 $trusted = "<!-- begin sanitized html -->\n";
1546 $skip_content = false;
1548 * Take care of netscape's stupid javascript entities like
1551 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1553 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1554 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1555 $free_content = substr($body, $curpos, $lt-$curpos);
1557 * Take care of <style>
1559 if ($tagname == "style" && $tagtype == 1){
1560 list($free_content, $curpos) =
1561 sq_fixstyle($body, $gt+
1, $message, $id);
1562 if ($free_content != FALSE){
1563 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1564 $trusted .= $free_content;
1565 $trusted .= sq_tagprint($tagname, false, 2);
1569 if ($skip_content == false){
1570 $trusted .= $free_content;
1572 if ($tagname != FALSE){
1574 if ($skip_content == $tagname){
1576 * Got to the end of tag we needed to remove.
1579 $skip_content = false;
1581 if ($skip_content == false){
1582 if ($tagname == "body"){
1585 if (isset($open_tags{$tagname}) &&
1586 $open_tags{$tagname} > 0){
1587 $open_tags{$tagname}--;
1596 * $rm_tags_with_content
1598 if ($skip_content == false){
1600 * See if this is a self-closing type and change
1601 * tagtype appropriately.
1604 && in_array($tagname, $self_closing_tags)){
1608 * See if we should skip this tag and any content
1611 if ($tagtype == 1 &&
1612 in_array($tagname, $rm_tags_with_content)){
1613 $skip_content = $tagname;
1615 if (($rm_tags == false
1616 && in_array($tagname, $tag_list)) ||
1617 ($rm_tags == true &&
1618 !in_array($tagname, $tag_list))){
1622 if (isset($open_tags{$tagname})){
1623 $open_tags{$tagname}++
;
1625 $open_tags{$tagname}=1;
1629 * This is where we run other checks.
1631 if (is_array($attary) && sizeof($attary) > 0){
1632 $attary = sq_fixatts($tagname,
1643 * Convert body into div.
1645 if ($tagname == "body"){
1647 $attary = sq_body2div($attary, $message, $id);
1653 if ($tagname != false && $skip_content == false){
1654 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1659 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1660 if ($force_tag_closing == true){
1661 foreach ($open_tags as $tagname=>$opentimes){
1662 while ($opentimes > 0){
1663 $trusted .= '</' . $tagname . '>';
1669 $trusted .= "<!-- end sanitized html -->\n";
1674 * This is a wrapper function to call html sanitizing routines.
1676 * @param $body the body of the message
1677 * @param $id the id of the message
1678 * @return a string with html safe to display in the browser.
1680 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1681 global $attachment_common_show_images, $view_unsafe_images,
1684 * Don't display attached images in HTML mode.
1686 $attachment_common_show_images = false;
1699 $rm_tags_with_content = Array(
1706 $self_closing_tags = Array(
1713 $force_tag_closing = false;
1715 $rm_attnames = Array(
1726 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1727 $bad_attvals = Array(
1730 "/^src|background/i" =>
1733 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1734 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1735 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1736 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1739 "\\1$secremoveimg\\2",
1740 "\\1$secremoveimg\\2",
1741 "\\1$secremoveimg\\2",
1742 "\\1$secremoveimg\\2"
1745 "/^href|action/i" =>
1748 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1749 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1750 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1751 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1766 "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
1767 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1768 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1769 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
1783 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1784 $view_unsafe_images = false;
1786 if (!$view_unsafe_images){
1788 * Remove any references to http/https if view_unsafe_images set
1791 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1792 '/^([\'\"])\s*https*:.*([\'\"])/si');
1793 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1794 "\\1$secremoveimg\\2");
1795 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1796 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1797 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1798 "url(\\1$secremoveimg\\2)");
1801 $add_attr_to_tag = Array(
1802 "/^a$/i" => Array('target'=>'"_new"')
1804 $trusted = sq_sanitize($body,
1806 $rm_tags_with_content,
1816 if (preg_match("|$secremoveimg|i", $trusted)){
1817 $has_unsafe_images = true;