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 echo "<BODY TEXT=\"$color[8]\" BGCOLOR=\"$color[4]\" LINK=\"$color[7]\" VLINK=\"$color[7]\" ALINK=\"$color[7]\">\n\n" .
41 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
42 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
43 $errormessage .= '<table><tr><td>' . htmlspecialchars($read) . '</td></tr></table>';
44 plain_error_message( $errormessage, $color );
45 echo '</body></html>';
49 foreach ($flags as $flag) {
50 $char = strtoupper($flag{1});
53 if (strtolower($flag) == '\\seen') {
58 if (strtolower($flag) == '\\answered') {
59 $msg->is_answered
= true;
63 if (strtolower($flag) == '\\deleted') {
64 $msg->is_deleted
= true;
68 if (strtolower($flag) == '\\flagged') {
69 $msg->is_flagged
= true;
73 if (strtolower($flag) == '$mdnsent') {
74 $msg->is_mdnsent
= true;
82 // listEntities($msg);
88 /* This starts the parsing of a particular structure. It is called recursively,
89 * so it can be passed different structures. It returns an object of type
91 * First, it checks to see if it is a multipart message. If it is, then it
92 * handles that as it sees is necessary. If it is just a regular entity,
93 * then it parses it and adds the necessary header information (by calling out
94 * to mime_get_elements()
97 function mime_fetch_body($imap_stream, $id, $ent_id=1) {
99 /* Do a bit of error correction. If we couldn't find the entity id, just guess
100 * that it is the first one. That is usually the case anyway.
104 $cmd = "FETCH $id BODY[]";
106 $cmd = "FETCH $id BODY[$ent_id]";
109 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
111 $topline = trim(array_shift($data));
112 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
114 $wholemessage = implode('', $data);
115 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
116 $ret = substr($wholemessage, 0, $regs[1]);
117 /* There is some information in the content info header that could be important
118 * in order to parse html messages. Let's get them here.
120 // if ($ret{0} == '<') {
121 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
123 } else if (ereg('"([^"]*)"', $topline, $regs)) {
126 global $where, $what, $mailbox, $passed_id, $startMessage;
127 $par = 'mailbox=' . urlencode($mailbox) . '&passed_id=' . $passed_id;
128 if (isset($where) && isset($what)) {
129 $par .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
131 $par .= '&startMessage=' . $startMessage . '&show_more=0';
133 $par .= '&response=' . urlencode($response) .
134 '&message=' . urlencode($message) .
135 '&topline=' . urlencode($topline);
138 '<table width="80%"><tr>' .
139 '<tr><td colspan=2>' .
140 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
142 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
143 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
144 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
145 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
146 "</table><BR></tt></font><hr>";
148 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
150 $wholemessage = implode('', $data);
152 $ret = $wholemessage;
157 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
160 /* Don't kill the connection if the browser is over a dialup
161 * and it would take over 30 seconds to download it.
162 * DonĀ“t call set_time_limit in safe mode.
165 if (!ini_get('safe_mode')) {
168 /* in case of base64 encoded attachments, do not buffer them.
169 Instead, echo the decoded attachment directly to screen */
170 if (strtolower($encoding) == 'base64') {
172 $query = "FETCH $id BODY[]";
174 $query = "FETCH $id BODY[$ent_id]";
176 sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
178 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
179 echo decodeBody($body, $encoding);
183 TODO, use the same method for quoted printable.
184 However, I assume that quoted printable attachments aren't that large
185 so the performancegain / memory usage drop will be minimal.
186 If we decide to add that then we need to adapt sqimap_fread because
187 we need to split te result on \n and fread doesn't stop at \n. That
188 means we also should provide $results from sqimap_fread (by ref) to
189 te function and set $no_return to false. The $filter function for
190 quoted printable should handle unsetting of $results.
193 TODO 2: find out how we write to the output stream php://stdout. fwrite
194 doesn't work because 'php://stdout isn't a stream.
199 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
202 $read = fgets ($imap_stream,8192);
205 // This could be bad -- if the section has sqimap_session_id() . ' OK'
206 // or similar, it will kill the download.
207 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
208 if (trim($read) == ')==') {
210 $read = fgets ($imap_stream,4096);
211 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
214 echo decodeBody($read1, $encoding) .
215 decodeBody($read, $encoding);
218 echo decodeBody($read, $encoding);
220 $read = fgets ($imap_stream,4096);
227 /* -[ END MIME DECODING ]----------------------------------------------------------- */
229 /* This is here for debugging purposes. It will print out a list
230 * of all the entity IDs that are in the $message object.
232 function listEntities ($message) {
234 echo "<tt>" . $message->entity_id
. ' : ' . $message->type0
. '/' . $message->type1
. ' parent = '. $message->parent
->entity_id
. '<br>';
235 for ($i = 0; isset($message->entities
[$i]); $i++
) {
237 $msg = listEntities($message->entities
[$i]);
247 function getPriorityStr($priority) {
248 $priority_level = substr($priority,0,1);
250 switch($priority_level) {
251 /* Check for a higher then normal priority. */
254 $priority_string = _("High");
257 /* Check for a lower then normal priority. */
260 $priority_string = _("Low");
263 /* Check for a normal priority. */
266 $priority_level = '3';
267 $priority_string = _("Normal");
271 return $priority_string;
274 /* returns a $message object for a particular entity id */
275 function getEntity ($message, $ent_id) {
276 return $message->getEntity($ent_id);
280 * Extracted from strings.php 23/03/2002
283 function translateText(&$body, $wrap_at, $charset) {
284 global $where, $what; /* from searching */
285 global $color; /* color theme */
287 require_once(SM_PATH
. 'functions/url_parser.php');
289 $body_ary = explode("\n", $body);
290 for ($i=0; $i < count($body_ary); $i++
) {
291 $line = $body_ary[$i];
292 if (strlen($line) - 2 >= $wrap_at) {
293 sqWordWrap($line, $wrap_at);
295 $line = charset_decode($charset, $line);
296 $line = str_replace("\t", ' ', $line);
305 if ($line[$pos] == ' ') {
307 } else if (strpos($line, '>', $pos) === $pos) {
316 if (!isset($color[13])) {
317 $color[13] = '#800000';
319 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
321 if (!isset($color[14])) {
322 $color[14] = '#FF0000';
324 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
327 $body_ary[$i] = $line;
329 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
332 /* This returns a parsed string called $body. That string can then
333 * be displayed as the actual message in the HTML. It contains
334 * everything needed, including HTML Tags, Attachments at the
337 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
338 /* This if statement checks for the entity to show as the
339 * primary message. To add more of them, just put them in the
340 * order that is their priority.
342 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
343 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
344 global $languages, $squirrelmail_language;
346 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
347 $view_unsafe_images = false;
351 $urlmailbox = urlencode($mailbox);
352 $body_message = getEntity($message, $ent_num);
353 if (($body_message->header
->type0
== 'text') ||
354 ($body_message->header
->type0
== 'rfc822')) {
355 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
356 $body = decodeBody($body, $body_message->header
->encoding
);
358 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
359 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
360 if (mb_detect_encoding($body) != 'ASCII') {
361 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
364 $hookResults = do_hook("message_body", $body);
365 $body = $hookResults[1];
367 /* If there are other types that shouldn't be formatted, add
371 if ($body_message->header
->type1
== 'html') {
372 if ($show_html_default <> 1) {
373 $entity_conv = array(' ' => ' ',
380 $body = strtr($body, $entity_conv);
381 $body = strip_tags($body);
383 translateText($body, $wrap_at,
384 $body_message->header
->getParameter('charset'));
386 $body = magicHTML($body, $id, $message, $mailbox);
389 translateText($body, $wrap_at,
390 $body_message->header
->getParameter('charset'));
392 $link = 'read_body.php?passed_id=' . $id . '&ent_id='.$ent_num.
393 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
394 '&startMessage=' . $startMessage . '&show_more=0';
395 if (isset($passed_ent_id)) {
396 $link .= '&passed_ent_id='.$passed_ent_id;
398 if ($view_unsafe_images) {
399 $text = _("Hide Unsafe Images");
401 if (isset($has_unsafe_images) && $has_unsafe_images) {
402 $link .= '&view_unsafe_images=1';
403 $text = _("View Unsafe Images");
408 $body .= '<center><small><a href="'.$link.'">'.$text.
409 '</a></small></center><br>' . "\n";
415 function formatAttachments($message, $exclude_id, $mailbox, $id) {
416 global $where, $what, $startMessage, $color;
417 static $ShownHTML = 0;
419 $att_ar = $message->getAttachments($exclude_id);
421 if (!count($att_ar)) return '';
425 $urlMailbox = urlencode($mailbox);
427 foreach ($att_ar as $att) {
428 $ent = $att->entity_id
;
429 $header = $att->header
;
430 $type0 = strtolower($header->type0
);
431 $type1 = strtolower($header->type1
);
433 $links['download link']['text'] = _("download");
434 $links['download link']['href'] = SM_PATH
.
435 "src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&ent_id=$ent";
437 if ($type0 =='message' && $type1 == 'rfc822') {
438 $default_page = SM_PATH
. 'src/read_body.php';
439 $rfc822_header = $att->rfc822_header
;
440 $filename = $rfc822_header->subject
;
441 if (trim( $filename ) == '') {
442 $filename = 'untitled-[' . $ent . ']' ;
444 $from_o = $rfc822_header->from
;
445 if (is_object($from_o)) {
446 $from_name = $from_o->getAddress(false);
448 $from_name = _("Unknown sender");
450 $from_name = decodeHeader(($from_name));
451 $description = $from_name;
453 $default_page = SM_PATH
. 'src/download.php';
454 if (is_object($header->disposition
)) {
455 $filename = $header->disposition
->getProperty('filename');
456 if (trim($filename) == '') {
457 $name = decodeHeader($header->disposition
->getProperty('name'));
458 if (trim($name) == '') {
459 $name = $header->getParameter('name');
460 if(trim($name) == '') {
461 if (trim( $header->id
) == '') {
462 $filename = 'untitled-[' . $ent . ']' ;
464 $filename = 'cid: ' . $header->id
;
474 $filename = $header->getParameter('name');
475 if (!trim($filename)) {
476 if (trim( $header->id
) == '') {
477 $filename = 'untitled-[' . $ent . ']' ;
479 $filename = 'cid: ' . $header->id
;
483 if ($header->description
) {
484 $description = decodeHeader($header->description
);
490 $display_filename = $filename;
491 if (isset($passed_ent_id)) {
492 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
494 $passed_ent_id_link = '';
496 $defaultlink = $default_page . "?startMessage=$startMessage"
497 . "&passed_id=$id&mailbox=$urlMailbox"
498 . '&ent_id='.$ent.$passed_ent_id_link;
499 if ($where && $what) {
500 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
502 /* This executes the attachment hook with a specific MIME-type.
503 * If that doesn't have results, it tries if there's a rule
504 * for a more generic type.
506 $hookresults = do_hook("attachment $type0/$type1", $links,
507 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
508 $display_filename, $where, $what);
509 if(count($hookresults[1]) <= 1) {
510 $hookresults = do_hook("attachment $type0/*", $links,
511 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
512 $display_filename, $where, $what);
515 $links = $hookresults[1];
516 $defaultlink = $hookresults[6];
518 $attachments .= '<TR><TD>' .
519 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A> </TD>' .
520 '<TD><SMALL><b>' . show_readable_size($header->size
) .
521 '</b> </small></TD>' .
522 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
524 $attachments .= '<b>' . $description . '</b>';
525 $attachments .= '</SMALL></TD><TD><SMALL> ';
528 foreach ($links as $val) {
532 $attachments .= ' | ';
534 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
537 $attachments .= "</TD></TR>\n";
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 if ($encoding == 'quoted-printable' ||
555 $encoding == 'quoted_printable') {
556 $body = quoted_printable_decode($body);
558 while (ereg("=\n", $body)) {
559 $body = ereg_replace ("=\n", '', $body);
562 } else if ($encoding == 'base64') {
563 $body = base64_decode($body);
566 // All other encodings are returned raw.
571 * This functions decode strings that is encoded according to
572 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
573 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
575 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
576 global $languages, $squirrelmail_language;
577 if (is_array($string)) {
578 $string = implode("\n", $string);
581 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
582 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
583 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
584 // Do we need to return at this point?
591 $aString = explode(' ',$string);
593 foreach ($aString as $chunk) {
594 if ($encoded && !$chunk) {
601 /* if encoded words are not separated by a linear-space-white we still catch them */
603 // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
604 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
605 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
606 if ($iLastMatch !== $j) {
616 $encoding = ucfirst($res[3]);
620 $replace = base64_decode($res[4]);
621 $ret .= charset_decode($res[2],$replace);
624 $replace = str_replace('_', ' ', $res[4]);
625 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
627 /* Only encode into entities by default. Some places
628 * don't need the encoding, like the compose form.
631 $replace = charset_decode($res[2], $replace);
634 $replace = htmlspecialchars($replace);
654 if (!$encoded && $htmlsave) {
655 $ret .= htmlspecialchars($chunk);
661 /* remove the first added space */
664 $ret = substr($ret,6);
666 $ret = substr($ret,1);
674 * Encode a string according to RFC 1522 for use in headers if it
675 * contains 8-bit characters or anything that looks like it should
678 function encodeHeader ($string) {
679 global $default_charset, $languages, $squirrelmail_language;
681 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
682 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
683 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
685 if (strtolower($default_charset) == 'iso-8859-1') {
686 $string = str_replace("\240",' ',$string);
689 // Encode only if the string contains 8-bit characters or =?
690 $j = strlen($string);
691 $max_l = 75 - strlen($default_charset) - 7;
694 $iEncStart = $enc_init = false;
695 $cur_l = $iOffset = 0;
696 for($i = 0; $i < $j; ++
$i) {
705 if ($iEncStart === false) {
709 if ($cur_l > ($max_l-2)) {
710 /* if there is an stringpart that doesn't need encoding, add it */
711 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
712 $aRet[] = "=?$default_charset?Q?$ret?=";
718 $ret .= sprintf("=%02X",ord($string{$i}));
723 if ($iEncStart !== false) {
724 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
725 $aRet[] = "=?$default_charset?Q?$ret?=";
733 if ($iEncStart !== false) {
735 if ($cur_l > $max_l) {
736 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
737 $aRet[] = "=?$default_charset?Q?$ret?=";
748 $k = ord($string{$i});
750 if ($iEncStart === false) {
751 // do not start encoding in the middle of a string, also take the rest of the word.
752 $sLeadString = substr($string,0,$i);
753 $aLeadString = explode(' ',$sLeadString);
754 $sToBeEncoded = array_pop($aLeadString);
755 $iEncStart = $i - strlen($sToBeEncoded);
756 $ret .= $sToBeEncoded;
757 $cur_l +
= strlen($sToBeEncoded);
760 /* first we add the encoded string that reached it's max size */
761 if ($cur_l > ($max_l-2)) {
762 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
763 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
770 $ret .= sprintf("=%02X", $k);
772 if ($iEncStart !== false) {
774 if ($cur_l > $max_l) {
775 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
776 $aRet[] = "=?$default_charset?Q?$ret?=";
791 if ($iEncStart !== false) {
792 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
793 $aRet[] = "=?$default_charset?Q?$ret?=";
795 $aRet[] = substr($string,$iOffset);
797 $string = implode('',$aRet);
802 /* This function trys to locate the entity_id of a specific mime element */
803 function find_ent_id($id, $message) {
804 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
805 if ($message->entities
[$i]->header
->type0
== 'multipart') {
806 $ret = find_ent_id($id, $message->entities
[$i]);
808 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
809 // if (sq_check_save_extension($message->entities[$i])) {
810 return $message->entities
[$i]->entity_id
;
818 function sq_check_save_extension($message) {
819 $filename = $message->getFilename();
820 $ext = substr($filename, strrpos($filename,'.')+
1);
821 $save_extensions = array('jpg','jpeg','gif','png','bmp');
822 return in_array($ext, $save_extensions);
827 ** HTMLFILTER ROUTINES
831 * This function returns the final tag out of the tag name, an array
832 * of attributes, and the type of the tag. This function is called by
833 * sq_sanitize internally.
835 * @param $tagname the name of the tag.
836 * @param $attary the array of attributes and their values
837 * @param $tagtype The type of the tag (see in comments).
838 * @return a string with the final tag representation.
840 function sq_tagprint($tagname, $attary, $tagtype){
844 $fulltag = '</' . $tagname . '>';
846 $fulltag = '<' . $tagname;
847 if (is_array($attary) && sizeof($attary)){
849 while (list($attname, $attvalue) = each($attary)){
850 array_push($atts, "$attname=$attvalue");
852 $fulltag .= ' ' . join(" ", $atts);
863 * A small helper function to use with array_walk. Modifies a by-ref
864 * value and makes it lowercase.
866 * @param $val a value passed by-ref.
867 * @return void since it modifies a by-ref value.
869 function sq_casenormalize(&$val){
870 $val = strtolower($val);
874 * This function skips any whitespace from the current position within
875 * a string and to the next non-whitespace value.
877 * @param $body the string
878 * @param $offset the offset within the string where we should start
879 * looking for the next non-whitespace character.
880 * @return the location within the $body where the next
881 * non-whitespace char is located.
883 function sq_skipspace($body, $offset){
884 $me = 'sq_skipspace';
885 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
886 if (sizeof($matches{1})){
887 $count = strlen($matches{1});
894 * This function looks for the next character within a string. It's
895 * really just a glorified "strpos", except it catches if failures
898 * @param $body The string to look for needle in.
899 * @param $offset Start looking from this position.
900 * @param $needle The character/string to look for.
901 * @return location of the next occurance of the needle, or
902 * strlen($body) if needle wasn't found.
904 function sq_findnxstr($body, $offset, $needle){
905 $me = 'sq_findnxstr';
906 $pos = strpos($body, $needle, $offset);
908 $pos = strlen($body);
914 * This function takes a PCRE-style regexp and tries to match it
917 * @param $body The string to look for needle in.
918 * @param $offset Start looking from here.
919 * @param $reg A PCRE-style regex to match.
920 * @return Returns a false if no matches found, or an array
921 * with the following members:
922 * - integer with the location of the match within $body
923 * - string with whatever content between offset and the match
924 * - string with whatever it is we matched
926 function sq_findnxreg($body, $offset, $reg){
927 $me = 'sq_findnxreg';
930 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
934 $retarr{0} = $offset +
strlen($matches{1});
935 $retarr{1} = $matches{1};
936 $retarr{2} = $matches{2};
942 * This function looks for the next tag.
944 * @param $body String where to look for the next tag.
945 * @param $offset Start looking from here.
946 * @return false if no more tags exist in the body, or
947 * an array with the following members:
948 * - string with the name of the tag
949 * - array with attributes and their values
950 * - integer with tag type (1, 2, or 3)
951 * - integer where the tag starts (starting "<")
952 * - integer where the tag ends (ending ">")
953 * first three members will be false, if the tag is invalid.
955 function sq_getnxtag($body, $offset){
957 if ($offset > strlen($body)){
960 $lt = sq_findnxstr($body, $offset, "<");
961 if ($lt == strlen($body)){
966 * blah blah <tag attribute="value">
969 $pos = sq_skipspace($body, $lt+
1);
970 if ($pos >= strlen($body)){
971 return Array(false, false, false, $lt, strlen($body));
974 * There are 3 kinds of tags:
975 * 1. Opening tag, e.g.:
977 * 2. Closing tag, e.g.:
979 * 3. XHTML-style content-less tag, e.g.:
983 switch (substr($body, $pos, 1)){
990 * A comment or an SGML declaration.
992 if (substr($body, $pos+
1, 2) == "--"){
993 $gt = strpos($body, "-->", $pos);
999 return Array(false, false, false, $lt, $gt);
1001 $gt = sq_findnxstr($body, $pos, ">");
1002 return Array(false, false, false, $lt, $gt);
1007 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1017 * Look for next [\W-_], which will indicate the end of the tag name.
1019 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1020 if ($regary == false){
1021 return Array(false, false, false, $lt, strlen($body));
1023 list($pos, $tagname, $match) = $regary;
1024 $tagname = strtolower($tagname);
1027 * $match can be either of these:
1028 * '>' indicating the end of the tag entirely.
1029 * '\s' indicating the end of the tag name.
1030 * '/' indicating that this is type-3 xhtml tag.
1032 * Whatever else we find there indicates an invalid tag.
1037 * This is an xhtml-style tag with a closing / at the
1038 * end, like so: <img src="blah"/>. Check if it's followed
1039 * by the closing bracket. If not, then this tag is invalid
1041 if (substr($body, $pos, 2) == "/>"){
1045 $gt = sq_findnxstr($body, $pos, ">");
1046 $retary = Array(false, false, false, $lt, $gt);
1050 return Array($tagname, false, $tagtype, $lt, $pos);
1054 * Check if it's whitespace
1056 if (!preg_match('/\s/', $match)){
1058 * This is an invalid tag! Look for the next closing ">".
1060 $gt = sq_findnxstr($body, $offset, ">");
1061 return Array(false, false, false, $lt, $gt);
1067 * At this point we're here:
1068 * <tagname attribute='blah'>
1071 * At this point we loop in order to find all attributes.
1077 while ($pos <= strlen($body)){
1078 $pos = sq_skipspace($body, $pos);
1079 if ($pos == strlen($body)){
1083 return Array(false, false, false, $lt, $pos);
1086 * See if we arrived at a ">" or "/>", which means that we reached
1087 * the end of the tag.
1090 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1094 $pos +
= strlen($matches{1});
1095 if ($matches{2} == "/>"){
1099 return Array($tagname, $attary, $tagtype, $lt, $pos);
1103 * There are several types of attributes, with optional
1104 * [:space:] between members.
1106 * attrname[:space:]=[:space:]'CDATA'
1108 * attrname[:space:]=[:space:]"CDATA"
1110 * attr[:space:]=[:space:]CDATA
1114 * We leave types 1 and 2 the same, type 3 we check for
1115 * '"' and convert to """ if needed, then wrap in
1116 * double quotes. Type 4 we convert into:
1119 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1120 if ($regary == false){
1122 * Looks like body ended before the end of tag.
1124 return Array(false, false, false, $lt, strlen($body));
1126 list($pos, $attname, $match) = $regary;
1127 $attname = strtolower($attname);
1129 * We arrived at the end of attribute name. Several things possible
1131 * '>' means the end of the tag and this is attribute type 4
1132 * '/' if followed by '>' means the same thing as above
1133 * '\s' means a lot of things -- look what it's followed by.
1134 * anything else means the attribute is invalid.
1139 * This is an xhtml-style tag with a closing / at the
1140 * end, like so: <img src="blah"/>. Check if it's followed
1141 * by the closing bracket. If not, then this tag is invalid
1143 if (substr($body, $pos, 2) == "/>"){
1147 $gt = sq_findnxstr($body, $pos, ">");
1148 $retary = Array(false, false, false, $lt, $gt);
1152 $attary{$attname} = '"yes"';
1153 return Array($tagname, $attary, $tagtype, $lt, $pos);
1157 * Skip whitespace and see what we arrive at.
1159 $pos = sq_skipspace($body, $pos);
1160 $char = substr($body, $pos, 1);
1162 * Two things are valid here:
1163 * '=' means this is attribute type 1 2 or 3.
1164 * \w means this was attribute type 4.
1165 * anything else we ignore and re-loop. End of tag and
1166 * invalid stuff will be caught by our checks at the beginning
1171 $pos = sq_skipspace($body, $pos);
1173 * Here are 3 possibilities:
1174 * "'" attribute type 1
1175 * '"' attribute type 2
1176 * everything else is the content of tag type 3
1178 $quot = substr($body, $pos, 1);
1180 $regary = sq_findnxreg($body, $pos+
1, "\'");
1181 if ($regary == false){
1182 return Array(false, false, false, $lt, strlen($body));
1184 list($pos, $attval, $match) = $regary;
1186 $attary{$attname} = "'" . $attval . "'";
1187 } else if ($quot == '"'){
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 . '"';
1197 * These are hateful. Look for \s, or >.
1199 $regary = sq_findnxreg($body, $pos, "[\s>]");
1200 if ($regary == false){
1201 return Array(false, false, false, $lt, strlen($body));
1203 list($pos, $attval, $match) = $regary;
1205 * If it's ">" it will be caught at the top.
1207 $attval = preg_replace("/\"/s", """, $attval);
1208 $attary{$attname} = '"' . $attval . '"';
1210 } else if (preg_match("|[\w/>]|", $char)) {
1212 * That was attribute type 4.
1214 $attary{$attname} = '"yes"';
1217 * An illegal character. Find next '>' and return.
1219 $gt = sq_findnxstr($body, $pos, ">");
1220 return Array(false, false, false, $lt, $gt);
1226 * The fact that we got here indicates that the tag end was never
1227 * found. Return invalid tag indication so it gets stripped.
1229 return Array(false, false, false, $lt, strlen($body));
1233 * This function checks attribute values for entity-encoded values
1234 * and returns them translated into 8-bit strings so we can run
1237 * @param $attvalue A string to run entity check against.
1238 * @return Translated value.
1240 function sq_deent($attvalue){
1243 * See if we have to run the checks first. All entities must start
1246 if (strpos($attvalue, "&") === false){
1250 * Check named entities first.
1252 $trans = get_html_translation_table(HTML_ENTITIES
);
1254 * Leave " in, as it can mess us up.
1256 $trans = array_flip($trans);
1257 unset($trans{"""});
1258 while (list($ent, $val) = each($trans)){
1259 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1262 * Now translate numbered entities from 1 to 255 if needed.
1264 if (strpos($attvalue, "#") !== false){
1265 $omit = Array(34, 39);
1266 for ($asc=1; $asc<256; $asc++
){
1267 if (!in_array($asc, $omit)){
1269 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1271 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1272 "$chr\\1", $attvalue);
1280 * This function runs various checks against the attributes.
1282 * @param $tagname String with the name of the tag.
1283 * @param $attary Array with all tag attributes.
1284 * @param $rm_attnames See description for sq_sanitize
1285 * @param $bad_attvals See description for sq_sanitize
1286 * @param $add_attr_to_tag See description for sq_sanitize
1287 * @param $message message object
1288 * @param $id message id
1289 * @return Array with modified attributes.
1291 function sq_fixatts($tagname,
1301 while (list($attname, $attvalue) = each($attary)){
1303 * See if this attribute should be removed.
1305 foreach ($rm_attnames as $matchtag=>$matchattrs){
1306 if (preg_match($matchtag, $tagname)){
1307 foreach ($matchattrs as $matchattr){
1308 if (preg_match($matchattr, $attname)){
1309 unset($attary{$attname});
1316 * Remove any entities.
1318 $attvalue = sq_deent($attvalue);
1321 * Now let's run checks on the attvalues.
1322 * I don't expect anyone to comprehend this. If you do,
1323 * get in touch with me so I can drive to where you live and
1324 * shake your hand personally. :)
1326 foreach ($bad_attvals as $matchtag=>$matchattrs){
1327 if (preg_match($matchtag, $tagname)){
1328 foreach ($matchattrs as $matchattr=>$valary){
1329 if (preg_match($matchattr, $attname)){
1331 * There are two arrays in valary.
1333 * Second one is replacements
1335 list($valmatch, $valrepl) = $valary;
1337 preg_replace($valmatch, $valrepl, $attvalue);
1338 if ($newvalue != $attvalue){
1339 $attary{$attname} = $newvalue;
1346 * Turn cid: urls into http-friendly ones.
1348 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1349 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1353 * See if we need to append any attributes to this tag.
1355 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1356 if (preg_match($matchtag, $tagname)){
1357 $attary = array_merge($attary, $addattary);
1364 * This function edits the style definition to make them friendly and
1365 * usable in squirrelmail.
1367 * @param $message the message object
1368 * @param $id the message id
1369 * @param $content a string with whatever is between <style> and </style>
1370 * @return a string with edited content.
1372 function sq_fixstyle($message, $id, $content){
1373 global $view_unsafe_images;
1374 $me = 'sq_fixstyle';
1376 * First look for general BODY style declaration, which would be
1378 * body {background: blah-blah}
1379 * and change it to .bodyclass so we can just assign it to a <div>
1381 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1382 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1384 * Fix url('blah') declarations.
1386 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1387 "url(\\1$secremoveimg\\2)", $content);
1389 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1392 if (!$view_unsafe_images){
1393 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1394 "url(\\1$secremoveimg\\2)", $content);
1398 * Fix urls that refer to cid:
1400 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1402 $cidurl = $matches{1};
1403 $httpurl = sq_cid2http($message, $id, $cidurl);
1404 $content = preg_replace("|url\($cidurl\)|si",
1405 "url($httpurl)", $content);
1409 * Fix stupid css declarations which lead to vulnerabilities
1412 $match = Array('/expression/i',
1415 $replace = Array('idiocy', 'idiocy', 'idiocy');
1416 $content = preg_replace($match, $replace, $content);
1421 * This function converts cid: url's into the ones that can be viewed in
1424 * @param $message the message object
1425 * @param $id the message id
1426 * @param $cidurl the cid: url.
1427 * @return a string with a http-friendly url
1429 function sq_cid2http($message, $id, $cidurl, $mailbox){
1431 * Get rid of quotes.
1433 $quotchar = substr($cidurl, 0, 1);
1434 $cidurl = str_replace($quotchar, "", $cidurl);
1435 $cidurl = substr(trim($cidurl), 4);
1436 $linkurl = find_ent_id($cidurl, $message);
1437 /* in case of non-save cid links $httpurl should be replaced by a sort of
1438 unsave link image */
1441 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1442 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1443 '&ent_id=' . $linkurl . $quotchar;
1449 * This function changes the <body> tag into a <div> tag since we
1450 * can't really have a body-within-body.
1452 * @param $attary an array of attributes and values of <body>
1453 * @return a modified array of attributes to be set for <div>
1455 function sq_body2div($attary){
1456 $me = 'sq_body2div';
1457 $divattary = Array('class' => "'bodyclass'");
1458 $bgcolor = '#ffffff';
1461 if (is_array($attary) && sizeof($attary) > 0){
1462 foreach ($attary as $attname=>$attvalue){
1463 $quotchar = substr($attvalue, 0, 1);
1464 $attvalue = str_replace($quotchar, "", $attvalue);
1467 $styledef .= "background-image: url('$attvalue'); ";
1470 $styledef .= "background-color: $attvalue; ";
1473 $styledef .= "color: $attvalue; ";
1477 if (strlen($styledef) > 0){
1478 $divattary{"style"} = "\"$styledef\"";
1485 * This is the main function and the one you should actually be calling.
1486 * There are several variables you should be aware of an which need
1487 * special description.
1489 * Since the description is quite lengthy, see it here:
1490 * http://www.mricon.com/html/phpfilter.html
1492 * @param $body the string with HTML you wish to filter
1493 * @param $tag_list see description above
1494 * @param $rm_tags_with_content see description above
1495 * @param $self_closing_tags see description above
1496 * @param $force_tag_closing see description above
1497 * @param $rm_attnames see description above
1498 * @param $bad_attvals see description above
1499 * @param $add_attr_to_tag see description above
1500 * @param $message message object
1501 * @param $id message id
1502 * @return sanitized html safe to show on your pages.
1504 function sq_sanitize($body,
1506 $rm_tags_with_content,
1516 $me = 'sq_sanitize';
1518 * Normalize rm_tags and rm_tags_with_content.
1520 @array_walk
($rm_tags, 'sq_casenormalize');
1521 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1522 @array_walk
($self_closing_tags, 'sq_casenormalize');
1524 * See if tag_list is of tags to remove or tags to allow.
1525 * false means remove these tags
1526 * true means allow these tags
1528 $rm_tags = array_shift($tag_list);
1530 $open_tags = Array();
1531 $trusted = "<!-- begin sanitized html -->\n";
1532 $skip_content = false;
1534 * Take care of netscape's stupid javascript entities like
1537 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1539 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1540 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1541 $free_content = substr($body, $curpos, $lt-$curpos);
1543 * Take care of <style>
1545 if ($tagname == "style" && $tagtype == 2){
1547 * This is a closing </style>. Edit the
1548 * content before we apply it.
1550 $free_content = sq_fixstyle($message, $id, $free_content);
1552 if ($skip_content == false){
1553 $trusted .= $free_content;
1555 if ($tagname != FALSE){
1557 if ($skip_content == $tagname){
1559 * Got to the end of tag we needed to remove.
1562 $skip_content = false;
1564 if ($skip_content == false){
1565 if ($tagname == "body"){
1568 if (isset($open_tags{$tagname}) &&
1569 $open_tags{$tagname} > 0){
1570 $open_tags{$tagname}--;
1579 * $rm_tags_with_content
1581 if ($skip_content == false){
1583 * See if this is a self-closing type and change
1584 * tagtype appropriately.
1587 && in_array($tagname, $self_closing_tags)){
1591 * See if we should skip this tag and any content
1594 if ($tagtype == 1 &&
1595 in_array($tagname, $rm_tags_with_content)){
1596 $skip_content = $tagname;
1598 if (($rm_tags == false
1599 && in_array($tagname, $tag_list)) ||
1600 ($rm_tags == true &&
1601 !in_array($tagname, $tag_list))){
1605 if (isset($open_tags{$tagname})){
1606 $open_tags{$tagname}++
;
1608 $open_tags{$tagname}=1;
1612 * This is where we run other checks.
1614 if (is_array($attary) && sizeof($attary) > 0){
1615 $attary = sq_fixatts($tagname,
1626 * Convert body into div.
1628 if ($tagname == "body"){
1630 $attary = sq_body2div($attary, $message, $id);
1636 if ($tagname != false && $skip_content == false){
1637 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1642 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1643 if ($force_tag_closing == true){
1644 foreach ($open_tags as $tagname=>$opentimes){
1645 while ($opentimes > 0){
1646 $trusted .= '</' . $tagname . '>';
1652 $trusted .= "<!-- end sanitized html -->\n";
1657 * This is a wrapper function to call html sanitizing routines.
1659 * @param $body the body of the message
1660 * @param $id the id of the message
1661 * @return a string with html safe to display in the browser.
1663 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1664 global $attachment_common_show_images, $view_unsafe_images,
1667 * Don't display attached images in HTML mode.
1669 $attachment_common_show_images = false;
1682 $rm_tags_with_content = Array(
1689 $self_closing_tags = Array(
1696 $force_tag_closing = false;
1698 $rm_attnames = Array(
1709 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1710 $bad_attvals = Array(
1713 "/^src|background/i" =>
1716 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1717 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1718 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1719 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1722 "\\1$secremoveimg\\2",
1723 "\\1$secremoveimg\\2",
1724 "\\1$secremoveimg\\2",
1725 "\\1$secremoveimg\\2"
1728 "/^href|action/i" =>
1731 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1732 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1733 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1734 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1749 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1750 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1751 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1752 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1766 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1767 $view_unsafe_images = false;
1769 if (!$view_unsafe_images){
1771 * Remove any references to http/https if view_unsafe_images set
1774 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1775 '/^([\'\"])\s*https*:.*([\'\"])/si');
1776 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1777 "\\1$secremoveimg\\2");
1778 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1779 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1780 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1781 "url(\\1$secremoveimg\\2)");
1784 $add_attr_to_tag = Array(
1785 "/^a$/i" => Array('target'=>'"_new"')
1787 $trusted = sq_sanitize($body,
1789 $rm_tags_with_content,
1799 if (preg_match("|$secremoveimg|i", $trusted)){
1800 $has_unsafe_images = true;