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 = $from_o->getAddress(false);
446 $from_name = _("Unknown sender");
448 $from_name = decodeHeader(($from_name));
449 $description = $from_name;
451 $default_page = SM_PATH
. 'src/download.php';
452 if (is_object($header->disposition
)) {
453 $filename = $header->disposition
->getProperty('filename');
454 if (trim($filename) == '') {
455 $name = decodeHeader($header->disposition
->getProperty('name'));
456 if (trim($name) == '') {
457 $name = $header->getParameter('name');
458 if(trim($name) == '') {
459 if (trim( $header->id
) == '') {
460 $filename = 'untitled-[' . $ent . ']' ;
462 $filename = 'cid: ' . $header->id
;
472 $filename = $header->getParameter('name');
473 if (!trim($filename)) {
474 if (trim( $header->id
) == '') {
475 $filename = 'untitled-[' . $ent . ']' ;
477 $filename = 'cid: ' . $header->id
;
481 if ($header->description
) {
482 $description = decodeHeader($header->description
);
488 $display_filename = $filename;
489 if (isset($passed_ent_id)) {
490 $passed_ent_id_link = '&passed_ent_id='.$passed_ent_id;
492 $passed_ent_id_link = '';
494 $defaultlink = $default_page . "?startMessage=$startMessage"
495 . "&passed_id=$id&mailbox=$urlMailbox"
496 . '&ent_id='.$ent.$passed_ent_id_link;
497 if ($where && $what) {
498 $defaultlink .= '&where='. urlencode($where).'&what='.urlencode($what);
500 /* This executes the attachment hook with a specific MIME-type.
501 * If that doesn't have results, it tries if there's a rule
502 * for a more generic type.
504 $hookresults = do_hook("attachment $type0/$type1", $links,
505 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
506 $display_filename, $where, $what);
507 if(count($hookresults[1]) <= 1) {
508 $hookresults = do_hook("attachment $type0/*", $links,
509 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
510 $display_filename, $where, $what);
513 $links = $hookresults[1];
514 $defaultlink = $hookresults[6];
516 $attachments .= '<TR><TD>' .
517 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A> </TD>' .
518 '<TD><SMALL><b>' . show_readable_size($header->size
) .
519 '</b> </small></TD>' .
520 "<TD><SMALL>[ $type0/$type1 ] </SMALL></TD>" .
522 $attachments .= '<b>' . $description . '</b>';
523 $attachments .= '</SMALL></TD><TD><SMALL> ';
526 foreach ($links as $val) {
530 $attachments .= ' | ';
532 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
535 $attachments .= "</TD></TR>\n";
537 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
538 if ($attachmentadd != '')
539 $attachments = $attachmentadd;
543 function sqimap_base64_decode(&$string) {
544 $string = str_replace("\r\n", "\n", $string);
545 $string = base64_decode($string);
548 /* This function decodes the body depending on the encoding type. */
549 function decodeBody($body, $encoding) {
550 global $show_html_default;
552 $body = str_replace("\r\n", "\n", $body);
553 $encoding = strtolower($encoding);
555 if ($encoding == 'quoted-printable' ||
556 $encoding == 'quoted_printable') {
557 $body = quoted_printable_decode($body);
559 while (ereg("=\n", $body)) {
560 $body = ereg_replace ("=\n", '', $body);
563 } else if ($encoding == 'base64') {
564 $body = base64_decode($body);
567 // All other encodings are returned raw.
572 * This functions decode strings that is encoded according to
573 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
574 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
576 function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
577 global $languages, $squirrelmail_language;
578 if (is_array($string)) {
579 $string = implode("\n", $string);
582 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
583 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
584 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
585 // Do we need to return at this point?
592 $aString = explode(' ',$string);
594 foreach ($aString as $chunk) {
595 if ($encoded && !$chunk) {
602 /* if encoded words are not separated by a linear-space-white we still catch them */
604 // if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
605 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
606 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
607 if ($iLastMatch !== $j) {
617 $encoding = ucfirst($res[3]);
621 $replace = base64_decode($res[4]);
622 $ret .= charset_decode($res[2],$replace);
625 $replace = str_replace('_', ' ', $res[4]);
626 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
628 /* Only encode into entities by default. Some places
629 * don't need the encoding, like the compose form.
632 $replace = charset_decode($res[2], $replace);
635 $replace = htmlspecialchars($replace);
655 if (!$encoded && $htmlsave) {
656 $ret .= htmlspecialchars($chunk);
662 /* remove the first added space */
665 $ret = substr($ret,6);
667 $ret = substr($ret,1);
675 * Encode a string according to RFC 1522 for use in headers if it
676 * contains 8-bit characters or anything that looks like it should
679 function encodeHeader ($string) {
680 global $default_charset, $languages, $squirrelmail_language;
682 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
683 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
684 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
686 if (strtolower($default_charset) == 'iso-8859-1') {
687 $string = str_replace("\240",' ',$string);
690 // Encode only if the string contains 8-bit characters or =?
691 $j = strlen($string);
692 $max_l = 75 - strlen($default_charset) - 7;
695 $iEncStart = $enc_init = false;
696 $cur_l = $iOffset = 0;
697 for($i = 0; $i < $j; ++
$i) {
706 if ($iEncStart === false) {
710 if ($cur_l > ($max_l-2)) {
711 /* if there is an stringpart that doesn't need encoding, add it */
712 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
713 $aRet[] = "=?$default_charset?Q?$ret?=";
719 $ret .= sprintf("=%02X",ord($string{$i}));
724 if ($iEncStart !== false) {
725 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
726 $aRet[] = "=?$default_charset?Q?$ret?=";
734 if ($iEncStart !== false) {
736 if ($cur_l > $max_l) {
737 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
738 $aRet[] = "=?$default_charset?Q?$ret?=";
749 $k = ord($string{$i});
751 if ($iEncStart === false) {
752 // do not start encoding in the middle of a string, also take the rest of the word.
753 $sLeadString = substr($string,0,$i);
754 $aLeadString = explode(' ',$sLeadString);
755 $sToBeEncoded = array_pop($aLeadString);
756 $iEncStart = $i - strlen($sToBeEncoded);
757 $ret .= $sToBeEncoded;
758 $cur_l +
= strlen($sToBeEncoded);
761 /* first we add the encoded string that reached it's max size */
762 if ($cur_l > ($max_l-2)) {
763 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
764 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
771 $ret .= sprintf("=%02X", $k);
773 if ($iEncStart !== false) {
775 if ($cur_l > $max_l) {
776 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
777 $aRet[] = "=?$default_charset?Q?$ret?=";
792 if ($iEncStart !== false) {
793 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
794 $aRet[] = "=?$default_charset?Q?$ret?=";
796 $aRet[] = substr($string,$iOffset);
798 $string = implode('',$aRet);
803 /* This function trys to locate the entity_id of a specific mime element */
804 function find_ent_id($id, $message) {
805 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities
); $i++
) {
806 if ($message->entities
[$i]->header
->type0
== 'multipart') {
807 $ret = find_ent_id($id, $message->entities
[$i]);
809 if (strcasecmp($message->entities
[$i]->header
->id
, $id) == 0) {
810 // if (sq_check_save_extension($message->entities[$i])) {
811 return $message->entities
[$i]->entity_id
;
819 function sq_check_save_extension($message) {
820 $filename = $message->getFilename();
821 $ext = substr($filename, strrpos($filename,'.')+
1);
822 $save_extensions = array('jpg','jpeg','gif','png','bmp');
823 return in_array($ext, $save_extensions);
828 ** HTMLFILTER ROUTINES
832 * This function returns the final tag out of the tag name, an array
833 * of attributes, and the type of the tag. This function is called by
834 * sq_sanitize internally.
836 * @param $tagname the name of the tag.
837 * @param $attary the array of attributes and their values
838 * @param $tagtype The type of the tag (see in comments).
839 * @return a string with the final tag representation.
841 function sq_tagprint($tagname, $attary, $tagtype){
845 $fulltag = '</' . $tagname . '>';
847 $fulltag = '<' . $tagname;
848 if (is_array($attary) && sizeof($attary)){
850 while (list($attname, $attvalue) = each($attary)){
851 array_push($atts, "$attname=$attvalue");
853 $fulltag .= ' ' . join(" ", $atts);
864 * A small helper function to use with array_walk. Modifies a by-ref
865 * value and makes it lowercase.
867 * @param $val a value passed by-ref.
868 * @return void since it modifies a by-ref value.
870 function sq_casenormalize(&$val){
871 $val = strtolower($val);
875 * This function skips any whitespace from the current position within
876 * a string and to the next non-whitespace value.
878 * @param $body the string
879 * @param $offset the offset within the string where we should start
880 * looking for the next non-whitespace character.
881 * @return the location within the $body where the next
882 * non-whitespace char is located.
884 function sq_skipspace($body, $offset){
885 $me = 'sq_skipspace';
886 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
887 if (sizeof($matches{1})){
888 $count = strlen($matches{1});
895 * This function looks for the next character within a string. It's
896 * really just a glorified "strpos", except it catches if failures
899 * @param $body The string to look for needle in.
900 * @param $offset Start looking from this position.
901 * @param $needle The character/string to look for.
902 * @return location of the next occurance of the needle, or
903 * strlen($body) if needle wasn't found.
905 function sq_findnxstr($body, $offset, $needle){
906 $me = 'sq_findnxstr';
907 $pos = strpos($body, $needle, $offset);
909 $pos = strlen($body);
915 * This function takes a PCRE-style regexp and tries to match it
918 * @param $body The string to look for needle in.
919 * @param $offset Start looking from here.
920 * @param $reg A PCRE-style regex to match.
921 * @return Returns a false if no matches found, or an array
922 * with the following members:
923 * - integer with the location of the match within $body
924 * - string with whatever content between offset and the match
925 * - string with whatever it is we matched
927 function sq_findnxreg($body, $offset, $reg){
928 $me = 'sq_findnxreg';
931 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
932 if (!isset($matches{0}) ||
!$matches{0}){
935 $retarr{0} = $offset +
strlen($matches{1});
936 $retarr{1} = $matches{1};
937 $retarr{2} = $matches{2};
943 * This function looks for the next tag.
945 * @param $body String where to look for the next tag.
946 * @param $offset Start looking from here.
947 * @return false if no more tags exist in the body, or
948 * an array with the following members:
949 * - string with the name of the tag
950 * - array with attributes and their values
951 * - integer with tag type (1, 2, or 3)
952 * - integer where the tag starts (starting "<")
953 * - integer where the tag ends (ending ">")
954 * first three members will be false, if the tag is invalid.
956 function sq_getnxtag($body, $offset){
958 if ($offset > strlen($body)){
961 $lt = sq_findnxstr($body, $offset, "<");
962 if ($lt == strlen($body)){
967 * blah blah <tag attribute="value">
970 $pos = sq_skipspace($body, $lt+
1);
971 if ($pos >= strlen($body)){
972 return Array(false, false, false, $lt, strlen($body));
975 * There are 3 kinds of tags:
976 * 1. Opening tag, e.g.:
978 * 2. Closing tag, e.g.:
980 * 3. XHTML-style content-less tag, e.g.:
984 switch (substr($body, $pos, 1)){
991 * A comment or an SGML declaration.
993 if (substr($body, $pos+
1, 2) == "--"){
994 $gt = strpos($body, "-->", $pos);
1000 return Array(false, false, false, $lt, $gt);
1002 $gt = sq_findnxstr($body, $pos, ">");
1003 return Array(false, false, false, $lt, $gt);
1008 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1018 * Look for next [\W-_], which will indicate the end of the tag name.
1020 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1021 if ($regary == false){
1022 return Array(false, false, false, $lt, strlen($body));
1024 list($pos, $tagname, $match) = $regary;
1025 $tagname = strtolower($tagname);
1028 * $match can be either of these:
1029 * '>' indicating the end of the tag entirely.
1030 * '\s' indicating the end of the tag name.
1031 * '/' indicating that this is type-3 xhtml tag.
1033 * Whatever else we find there indicates an invalid tag.
1038 * This is an xhtml-style tag with a closing / at the
1039 * end, like so: <img src="blah"/>. Check if it's followed
1040 * by the closing bracket. If not, then this tag is invalid
1042 if (substr($body, $pos, 2) == "/>"){
1046 $gt = sq_findnxstr($body, $pos, ">");
1047 $retary = Array(false, false, false, $lt, $gt);
1051 return Array($tagname, false, $tagtype, $lt, $pos);
1055 * Check if it's whitespace
1057 if (!preg_match('/\s/', $match)){
1059 * This is an invalid tag! Look for the next closing ">".
1061 $gt = sq_findnxstr($body, $lt, ">");
1062 return Array(false, false, false, $lt, $gt);
1068 * At this point we're here:
1069 * <tagname attribute='blah'>
1072 * At this point we loop in order to find all attributes.
1078 while ($pos <= strlen($body)){
1079 $pos = sq_skipspace($body, $pos);
1080 if ($pos == strlen($body)){
1084 return Array(false, false, false, $lt, $pos);
1087 * See if we arrived at a ">" or "/>", which means that we reached
1088 * the end of the tag.
1091 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1095 $pos +
= strlen($matches{1});
1096 if ($matches{2} == "/>"){
1100 return Array($tagname, $attary, $tagtype, $lt, $pos);
1104 * There are several types of attributes, with optional
1105 * [:space:] between members.
1107 * attrname[:space:]=[:space:]'CDATA'
1109 * attrname[:space:]=[:space:]"CDATA"
1111 * attr[:space:]=[:space:]CDATA
1115 * We leave types 1 and 2 the same, type 3 we check for
1116 * '"' and convert to """ if needed, then wrap in
1117 * double quotes. Type 4 we convert into:
1120 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1121 if ($regary == false){
1123 * Looks like body ended before the end of tag.
1125 return Array(false, false, false, $lt, strlen($body));
1127 list($pos, $attname, $match) = $regary;
1128 $attname = strtolower($attname);
1130 * We arrived at the end of attribute name. Several things possible
1132 * '>' means the end of the tag and this is attribute type 4
1133 * '/' if followed by '>' means the same thing as above
1134 * '\s' means a lot of things -- look what it's followed by.
1135 * anything else means the attribute is invalid.
1140 * This is an xhtml-style tag with a closing / at the
1141 * end, like so: <img src="blah"/>. Check if it's followed
1142 * by the closing bracket. If not, then this tag is invalid
1144 if (substr($body, $pos, 2) == "/>"){
1148 $gt = sq_findnxstr($body, $pos, ">");
1149 $retary = Array(false, false, false, $lt, $gt);
1153 $attary{$attname} = '"yes"';
1154 return Array($tagname, $attary, $tagtype, $lt, $pos);
1158 * Skip whitespace and see what we arrive at.
1160 $pos = sq_skipspace($body, $pos);
1161 $char = substr($body, $pos, 1);
1163 * Two things are valid here:
1164 * '=' means this is attribute type 1 2 or 3.
1165 * \w means this was attribute type 4.
1166 * anything else we ignore and re-loop. End of tag and
1167 * invalid stuff will be caught by our checks at the beginning
1172 $pos = sq_skipspace($body, $pos);
1174 * Here are 3 possibilities:
1175 * "'" attribute type 1
1176 * '"' attribute type 2
1177 * everything else is the content of tag type 3
1179 $quot = substr($body, $pos, 1);
1181 $regary = sq_findnxreg($body, $pos+
1, "\'");
1182 if ($regary == false){
1183 return Array(false, false, false, $lt, strlen($body));
1185 list($pos, $attval, $match) = $regary;
1187 $attary{$attname} = "'" . $attval . "'";
1188 } else if ($quot == '"'){
1189 $regary = sq_findnxreg($body, $pos+
1, '\"');
1190 if ($regary == false){
1191 return Array(false, false, false, $lt, strlen($body));
1193 list($pos, $attval, $match) = $regary;
1195 $attary{$attname} = '"' . $attval . '"';
1198 * These are hateful. Look for \s, or >.
1200 $regary = sq_findnxreg($body, $pos, "[\s>]");
1201 if ($regary == false){
1202 return Array(false, false, false, $lt, strlen($body));
1204 list($pos, $attval, $match) = $regary;
1206 * If it's ">" it will be caught at the top.
1208 $attval = preg_replace("/\"/s", """, $attval);
1209 $attary{$attname} = '"' . $attval . '"';
1211 } else if (preg_match("|[\w/>]|", $char)) {
1213 * That was attribute type 4.
1215 $attary{$attname} = '"yes"';
1218 * An illegal character. Find next '>' and return.
1220 $gt = sq_findnxstr($body, $pos, ">");
1221 return Array(false, false, false, $lt, $gt);
1227 * The fact that we got here indicates that the tag end was never
1228 * found. Return invalid tag indication so it gets stripped.
1230 return Array(false, false, false, $lt, strlen($body));
1234 * This function checks attribute values for entity-encoded values
1235 * and returns them translated into 8-bit strings so we can run
1238 * @param $attvalue A string to run entity check against.
1239 * @return Translated value.
1241 function sq_deent($attvalue){
1244 * See if we have to run the checks first. All entities must start
1247 if (strpos($attvalue, "&") === false){
1251 * Check named entities first.
1253 $trans = get_html_translation_table(HTML_ENTITIES
);
1255 * Leave " in, as it can mess us up.
1257 $trans = array_flip($trans);
1258 unset($trans{"""});
1259 while (list($ent, $val) = each($trans)){
1260 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1263 * Now translate numbered entities from 1 to 255 if needed.
1265 if (strpos($attvalue, "#") !== false){
1266 $omit = Array(34, 39);
1267 for ($asc=1; $asc<256; $asc++
){
1268 if (!in_array($asc, $omit)){
1270 $attvalue = preg_replace("/\�*$asc;*(\D)/si", "$chr\\1",
1272 $attvalue = preg_replace("/\�*".dechex($asc).";*(\W)/si",
1273 "$chr\\1", $attvalue);
1281 * This function runs various checks against the attributes.
1283 * @param $tagname String with the name of the tag.
1284 * @param $attary Array with all tag attributes.
1285 * @param $rm_attnames See description for sq_sanitize
1286 * @param $bad_attvals See description for sq_sanitize
1287 * @param $add_attr_to_tag See description for sq_sanitize
1288 * @param $message message object
1289 * @param $id message id
1290 * @return Array with modified attributes.
1292 function sq_fixatts($tagname,
1302 while (list($attname, $attvalue) = each($attary)){
1304 * See if this attribute should be removed.
1306 foreach ($rm_attnames as $matchtag=>$matchattrs){
1307 if (preg_match($matchtag, $tagname)){
1308 foreach ($matchattrs as $matchattr){
1309 if (preg_match($matchattr, $attname)){
1310 unset($attary{$attname});
1317 * Remove any entities.
1319 $attvalue = sq_deent($attvalue);
1322 * Now let's run checks on the attvalues.
1323 * I don't expect anyone to comprehend this. If you do,
1324 * get in touch with me so I can drive to where you live and
1325 * shake your hand personally. :)
1327 foreach ($bad_attvals as $matchtag=>$matchattrs){
1328 if (preg_match($matchtag, $tagname)){
1329 foreach ($matchattrs as $matchattr=>$valary){
1330 if (preg_match($matchattr, $attname)){
1332 * There are two arrays in valary.
1334 * Second one is replacements
1336 list($valmatch, $valrepl) = $valary;
1338 preg_replace($valmatch, $valrepl, $attvalue);
1339 if ($newvalue != $attvalue){
1340 $attary{$attname} = $newvalue;
1347 * Turn cid: urls into http-friendly ones.
1349 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1350 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1354 * See if we need to append any attributes to this tag.
1356 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1357 if (preg_match($matchtag, $tagname)){
1358 $attary = array_merge($attary, $addattary);
1365 * This function edits the style definition to make them friendly and
1366 * usable in squirrelmail.
1368 * @param $message the message object
1369 * @param $id the message id
1370 * @param $content a string with whatever is between <style> and </style>
1371 * @return a string with edited content.
1373 function sq_fixstyle($body, $pos, $message, $id){
1374 global $view_unsafe_images;
1375 $me = 'sq_fixstyle';
1376 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1378 return array(FALSE, strlen($body));
1380 $newpos = $ret[0] +
strlen($ret[2]);
1383 * First look for general BODY style declaration, which would be
1385 * body {background: blah-blah}
1386 * and change it to .bodyclass so we can just assign it to a <div>
1388 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1389 $secremoveimg = '../images/' . _("sec_remove_eng.png");
1391 * Fix url('blah') declarations.
1393 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
1394 "url(\\1$secremoveimg\\2)", $content);
1396 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1399 if (!$view_unsafe_images){
1400 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
1401 "url(\\1$secremoveimg\\2)", $content);
1405 * Fix urls that refer to cid:
1407 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1408 $content, $matches)){
1409 $cidurl = $matches{1};
1410 $httpurl = sq_cid2http($message, $id, $cidurl);
1411 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
1412 "url($httpurl)", $content);
1416 * Fix stupid css declarations which lead to vulnerabilities
1419 $match = Array('/expression/i',
1422 $replace = Array('idiocy', 'idiocy', 'idiocy');
1423 $content = preg_replace($match, $replace, $content);
1424 return array($content, $newpos);
1428 * This function converts cid: url's into the ones that can be viewed in
1431 * @param $message the message object
1432 * @param $id the message id
1433 * @param $cidurl the cid: url.
1434 * @return a string with a http-friendly url
1436 function sq_cid2http($message, $id, $cidurl, $mailbox){
1438 * Get rid of quotes.
1440 $quotchar = substr($cidurl, 0, 1);
1441 $cidurl = str_replace($quotchar, "", $cidurl);
1442 $cidurl = substr(trim($cidurl), 4);
1443 $linkurl = find_ent_id($cidurl, $message);
1444 /* in case of non-save cid links $httpurl should be replaced by a sort of
1445 unsave link image */
1448 $httpurl = $quotchar . SM_PATH
. 'src/download.php?absolute_dl=true&' .
1449 "passed_id=$id&mailbox=" . urlencode($mailbox) .
1450 '&ent_id=' . $linkurl . $quotchar;
1456 * This function changes the <body> tag into a <div> tag since we
1457 * can't really have a body-within-body.
1459 * @param $attary an array of attributes and values of <body>
1460 * @return a modified array of attributes to be set for <div>
1462 function sq_body2div($attary){
1463 $me = 'sq_body2div';
1464 $divattary = Array('class' => "'bodyclass'");
1465 $bgcolor = '#ffffff';
1468 if (is_array($attary) && sizeof($attary) > 0){
1469 foreach ($attary as $attname=>$attvalue){
1470 $quotchar = substr($attvalue, 0, 1);
1471 $attvalue = str_replace($quotchar, "", $attvalue);
1474 $styledef .= "background-image: url('$attvalue'); ";
1477 $styledef .= "background-color: $attvalue; ";
1480 $styledef .= "color: $attvalue; ";
1484 if (strlen($styledef) > 0){
1485 $divattary{"style"} = "\"$styledef\"";
1492 * This is the main function and the one you should actually be calling.
1493 * There are several variables you should be aware of an which need
1494 * special description.
1496 * Since the description is quite lengthy, see it here:
1497 * http://www.mricon.com/html/phpfilter.html
1499 * @param $body the string with HTML you wish to filter
1500 * @param $tag_list see description above
1501 * @param $rm_tags_with_content see description above
1502 * @param $self_closing_tags see description above
1503 * @param $force_tag_closing see description above
1504 * @param $rm_attnames see description above
1505 * @param $bad_attvals see description above
1506 * @param $add_attr_to_tag see description above
1507 * @param $message message object
1508 * @param $id message id
1509 * @return sanitized html safe to show on your pages.
1511 function sq_sanitize($body,
1513 $rm_tags_with_content,
1523 $me = 'sq_sanitize';
1524 $rm_tags = array_shift($tag_list);
1526 * Normalize rm_tags and rm_tags_with_content.
1528 @array_walk
($tag_list, 'sq_casenormalize');
1529 @array_walk
($rm_tags_with_content, 'sq_casenormalize');
1530 @array_walk
($self_closing_tags, 'sq_casenormalize');
1532 * See if tag_list is of tags to remove or tags to allow.
1533 * false means remove these tags
1534 * true means allow these tags
1537 $open_tags = Array();
1538 $trusted = "<!-- begin sanitized html -->\n";
1539 $skip_content = false;
1541 * Take care of netscape's stupid javascript entities like
1544 $body = preg_replace("/&(\{.*?\};)/si", "&\\1", $body);
1546 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
1547 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1548 $free_content = substr($body, $curpos, $lt-$curpos);
1550 * Take care of <style>
1552 if ($tagname == "style" && $tagtype == 1){
1553 list($free_content, $curpos) =
1554 sq_fixstyle($body, $gt+
1, $message, $id);
1555 if ($free_content != FALSE){
1556 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1557 $trusted .= $free_content;
1558 $trusted .= sq_tagprint($tagname, false, 2);
1562 if ($skip_content == false){
1563 $trusted .= $free_content;
1565 if ($tagname != FALSE){
1567 if ($skip_content == $tagname){
1569 * Got to the end of tag we needed to remove.
1572 $skip_content = false;
1574 if ($skip_content == false){
1575 if ($tagname == "body"){
1578 if (isset($open_tags{$tagname}) &&
1579 $open_tags{$tagname} > 0){
1580 $open_tags{$tagname}--;
1589 * $rm_tags_with_content
1591 if ($skip_content == false){
1593 * See if this is a self-closing type and change
1594 * tagtype appropriately.
1597 && in_array($tagname, $self_closing_tags)){
1601 * See if we should skip this tag and any content
1604 if ($tagtype == 1 &&
1605 in_array($tagname, $rm_tags_with_content)){
1606 $skip_content = $tagname;
1608 if (($rm_tags == false
1609 && in_array($tagname, $tag_list)) ||
1610 ($rm_tags == true &&
1611 !in_array($tagname, $tag_list))){
1615 if (isset($open_tags{$tagname})){
1616 $open_tags{$tagname}++
;
1618 $open_tags{$tagname}=1;
1622 * This is where we run other checks.
1624 if (is_array($attary) && sizeof($attary) > 0){
1625 $attary = sq_fixatts($tagname,
1636 * Convert body into div.
1638 if ($tagname == "body"){
1640 $attary = sq_body2div($attary, $message, $id);
1646 if ($tagname != false && $skip_content == false){
1647 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1652 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1653 if ($force_tag_closing == true){
1654 foreach ($open_tags as $tagname=>$opentimes){
1655 while ($opentimes > 0){
1656 $trusted .= '</' . $tagname . '>';
1662 $trusted .= "<!-- end sanitized html -->\n";
1667 * This is a wrapper function to call html sanitizing routines.
1669 * @param $body the body of the message
1670 * @param $id the id of the message
1671 * @return a string with html safe to display in the browser.
1673 function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
1674 global $attachment_common_show_images, $view_unsafe_images,
1677 * Don't display attached images in HTML mode.
1679 $attachment_common_show_images = false;
1692 $rm_tags_with_content = Array(
1699 $self_closing_tags = Array(
1706 $force_tag_closing = false;
1708 $rm_attnames = Array(
1719 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1720 $bad_attvals = Array(
1723 "/^src|background/i" =>
1726 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1727 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1728 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1729 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1732 "\\1$secremoveimg\\2",
1733 "\\1$secremoveimg\\2",
1734 "\\1$secremoveimg\\2",
1735 "\\1$secremoveimg\\2"
1738 "/^href|action/i" =>
1741 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1742 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1743 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1744 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1759 "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
1760 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1761 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1762 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
1776 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET
) ) {
1777 $view_unsafe_images = false;
1779 if (!$view_unsafe_images){
1781 * Remove any references to http/https if view_unsafe_images set
1784 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1785 '/^([\'\"])\s*https*:.*([\'\"])/si');
1786 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1787 "\\1$secremoveimg\\2");
1788 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
1789 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1790 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
1791 "url(\\1$secremoveimg\\2)");
1794 $add_attr_to_tag = Array(
1795 "/^a$/i" => Array('target'=>'"_new"')
1797 $trusted = sq_sanitize($body,
1799 $rm_tags_with_content,
1809 if (preg_match("|$secremoveimg|i", $trusted)){
1810 $has_unsafe_images = true;