Source for file mime.php

Documentation is available at mime.php

  1. <?php
  2.  
  3. /**
  4.  * mime.php
  5.  *
  6.  * This contains the functions necessary to detect and decode MIME
  7.  * messages.
  8.  *
  9.  * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  10.  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  11.  * @version $Id: mime.php,v 1.265.2.68 2006/06/20 06:14:53 jervfors Exp $
  12.  * @package squirrelmail
  13.  */
  14.  
  15. /** The typical includes... */
  16. require_once(SM_PATH 'functions/imap.php');
  17. require_once(SM_PATH 'functions/attachment_common.php');
  18.  
  19. /* -------------------------------------------------------------------------- */
  20. /* MIME DECODING                                                              */
  21. /* -------------------------------------------------------------------------- */
  22.  
  23. /**
  24.  * Get the MIME structure
  25.  *
  26.  * This function gets the structure of a message and stores it in the "message" class.
  27.  * It will return this object for use with all relevant header information and
  28.  * fully parsed into the standard "message" object format.
  29.  */
  30. function mime_structure ($bodystructure$flags=array()) {
  31.  
  32.     /* Isolate the body structure and remove beginning and end parenthesis. */
  33.     $read trim(substr ($bodystructurestrpos(strtolower($bodystructure)'bodystructure'13));
  34.     $read trim(substr ($read0-1));
  35.     $i 0;
  36.     $msg Message::parseStructure($read,$i);
  37.     if (!is_object($msg)) {
  38.         include_once(SM_PATH 'functions/display_messages.php');
  39.         global $color$mailbox;
  40.         /* removed urldecode because $_GET is auto urldecoded ??? */
  41.         displayPageHeader$color$mailbox );
  42.         echo "<body text=\"$color[8]\" bgcolor=\"$color[4]\" link=\"$color[7]\" vlink=\"$color[7]\" alink=\"$color[7]\">\n\n.
  43.          '<center>';
  44.         $errormessage  _("SquirrelMail could not decode the bodystructure of the message");
  45.         $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
  46.         $errormessage .= '<table><tr><td>' htmlspecialchars($read'</td></tr></table>';
  47.         plain_error_message$errormessage$color );
  48.         echo '</body></html>';
  49.         exit;
  50.     }
  51.     if (count($flags)) {
  52.         foreach ($flags as $flag{
  53.             $char strtoupper($flag{1});
  54.             switch ($char{
  55.                 case 'S':
  56.                     if (strtolower($flag== '\\seen'{
  57.                         $msg->is_seen true;
  58.                     }
  59.                     break;
  60.                 case 'A':
  61.                     if (strtolower($flag== '\\answered'{
  62.                         $msg->is_answered true;
  63.                     }
  64.                     break;
  65.                 case 'D':
  66.                     if (strtolower($flag== '\\deleted'{
  67.                         $msg->is_deleted true;
  68.                     }
  69.                     break;
  70.                 case 'F':
  71.                     if (strtolower($flag== '\\flagged'{
  72.                         $msg->is_flagged true;
  73.                     }
  74.                     break;
  75.                 case 'M':
  76.                     if (strtolower($flag== '$mdnsent'{
  77.                         $msg->is_mdnsent true;
  78.                     }
  79.                     break;
  80.                 default:
  81.                     break;
  82.             }
  83.         }
  84.     }
  85.     //    listEntities($msg);
  86.     return $msg;
  87. }
  88.  
  89.  
  90.  
  91. /* This starts the parsing of a particular structure.  It is called recursively,
  92.  * so it can be passed different structures.  It returns an object of type
  93.  * $message.
  94.  * First, it checks to see if it is a multipart message.  If it is, then it
  95.  * handles that as it sees is necessary.  If it is just a regular entity,
  96.  * then it parses it and adds the necessary header information (by calling out
  97.  * to mime_get_elements()
  98.  */
  99.  
  100. function mime_fetch_body($imap_stream$id$ent_id=1$fetch_size=0{
  101.     global $uid_support;
  102.     /* Do a bit of error correction.  If we couldn't find the entity id, just guess
  103.      * that it is the first one.  That is usually the case anyway.
  104.      */
  105.  
  106.     if (!$ent_id{
  107.         $cmd "FETCH $id BODY[]";
  108.     else {
  109.         $cmd "FETCH $id BODY[$ent_id]";
  110.     }
  111.  
  112.     if ($fetch_size!=0$cmd .= "<0.$fetch_size>";
  113.  
  114.     $data sqimap_run_command ($imap_stream$cmdtrue$response$message$uid_support);
  115.     do {
  116.         $topline trim(array_shift($data));
  117.     while($topline && ($topline[0== '*'&& !preg_match('/\* [0-9]+ FETCH.*/i'$topline)) ;
  118.  
  119.     $wholemessage implode(''$data);
  120.     if (ereg('\\{([^\\}]*)\\}'$topline$regs)) {
  121.         $ret substr($wholemessage0$regs[1]);
  122.         /* There is some information in the content info header that could be important
  123.          * in order to parse html messages. Let's get them here.
  124.          */
  125. //        if ($ret{0} == '<') {
  126. //            $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
  127. //        }
  128.     else if (ereg('"([^"]*)"'$topline$regs)) {
  129.         $ret $regs[1];
  130.     else {
  131.         global $where$what$mailbox$passed_id$startMessage;
  132.         $par 'mailbox=' urlencode($mailbox'&amp;passed_id=' $passed_id;
  133.         if (isset($where&& isset($what)) {
  134.             $par .= '&amp;where=' urlencode($where'&amp;what=' urlencode($what);
  135.         else {
  136.             $par .= '&amp;startMessage=' $startMessage '&amp;show_more=0';
  137.         }
  138.         $par .= '&amp;response=' urlencode($response.
  139.             '&amp;message='  urlencode($message)  .
  140.             '&amp;topline='  urlencode($topline);
  141.  
  142.         echo '<tt><br />' .
  143.             '<table width="80%"><tr>' .
  144.             '<tr><td colspan="2">' .
  145.             _("Body retrieval error. The reason for this is most probably that the message is malformed.".
  146.             '</td></tr>' .
  147.             '<tr><td><b>' _("Command:""</td><td>$cmd</td></tr>.
  148.             '<tr><td><b>' _("Response:""</td><td>$response</td></tr>.
  149.             '<tr><td><b>' _("Message:""</td><td>$message</td></tr>.
  150.             '<tr><td><b>' _("FETCH line:""</td><td>$topline</td></tr>.
  151.             "</table><br /></tt></font><hr />";
  152.  
  153.         $data sqimap_run_command ($imap_stream"FETCH $passed_id BODY[]"true$response$message$uid_support);
  154.         array_shift($data);
  155.         $wholemessage implode(''$data);
  156.  
  157.         $ret $wholemessage;
  158.     }
  159.     return $ret;
  160. }
  161.  
  162. function mime_print_body_lines ($imap_stream$id$ent_id=1$encoding{
  163.     global $uid_support;
  164.  
  165.     /* Don't kill the connection if the browser is over a dialup
  166.      * and it would take over 30 seconds to download it.
  167.      * Don't call set_time_limit in safe mode.
  168.      */
  169.  
  170.     if (!ini_get('safe_mode')) {
  171.         set_time_limit(0);
  172.     }
  173.     /* in case of base64 encoded attachments, do not buffer them.
  174.        Instead, echo the decoded attachment directly to screen */
  175.     if (strtolower($encoding== 'base64'{
  176.         if (!$ent_id{
  177.             $query "FETCH $id BODY[]";
  178.         else {
  179.             $query "FETCH $id BODY[$ent_id]";
  180.         }
  181.         sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
  182.     else {
  183.         $body mime_fetch_body ($imap_stream$id$ent_id);
  184.         echo decodeBody($body$encoding);
  185.     }
  186.     return;
  187. }
  188.  
  189. /* -[ END MIME DECODING ]----------------------------------------------------------- */
  190.  
  191. /* This is here for debugging purposes.  It will print out a list
  192.  * of all the entity IDs that are in the $message object.
  193.  */
  194. function listEntities ($message{
  195.     if ($message{
  196.         echo "<tt>" $message->entity_id ' : ' $message->type0 '/' $message->type1 ' parent = '$message->parent->entity_id'<br />';
  197.         for ($i 0isset($message->entities[$i])$i++{
  198.             echo "$i : ";
  199.             $msg listEntities($message->entities[$i]);
  200.  
  201.             if ($msg{
  202.                 echo "return: ";
  203.                 return $msg;
  204.             }
  205.         }
  206.     }
  207. }
  208.  
  209. function getPriorityStr($priority{
  210.     $priority_level substr($priority,0,1);
  211.  
  212.     switch($priority_level{
  213.         /* Check for a higher then normal priority. */
  214.         case '1':
  215.         case '2':
  216.             $priority_string _("High");
  217.             break;
  218.  
  219.         /* Check for a lower then normal priority. */
  220.         case '4':
  221.         case '5':
  222.             $priority_string _("Low");
  223.             break;
  224.  
  225.         /* Check for a normal priority. */
  226.         case '3':
  227.         default:
  228.             $priority_level '3';
  229.             $priority_string _("Normal");
  230.             break;
  231.  
  232.     }
  233.     return $priority_string;
  234. }
  235.  
  236. /* returns a $message object for a particular entity id */
  237. function getEntity ($message$ent_id{
  238.     return $message->getEntity($ent_id);
  239. }
  240.  
  241. /* translateText
  242.  * Extracted from strings.php 23/03/2002
  243.  */
  244.  
  245. function translateText(&$body$wrap_at$charset{
  246.     global $where$what;   /* from searching */
  247.     global $color;          /* color theme */
  248.  
  249.     require_once(SM_PATH 'functions/url_parser.php');
  250.  
  251.     $body_ary explode("\n"$body);
  252.     for ($i=0$i count($body_ary)$i++{
  253.         $line $body_ary[$i];
  254.         if (strlen($line>= $wrap_at{
  255.             sqWordWrap($line$wrap_at$charset);
  256.         }
  257.         $line charset_decode($charset$line);
  258.         $line str_replace("\t"'        '$line);
  259.  
  260.         parseUrl ($line);
  261.  
  262.         $quotes 0;
  263.         $pos 0;
  264.         $j strlen($line);
  265.  
  266.         while ($pos $j{
  267.             if ($line[$pos== ' '{
  268.                 $pos++;
  269.             else if (strpos($line'&gt;'$pos=== $pos{
  270.                 $pos += 4;
  271.                 $quotes++;
  272.             else {
  273.                 break;
  274.             }
  275.         }
  276.  
  277.         if ($quotes 2{
  278.             if (!isset($color[13])) {
  279.                 $color[13'#800000';
  280.             }
  281.             $line '<font color="' $color[13'">' $line '</font>';
  282.         elseif ($quotes{
  283.             if (!isset($color[14])) {
  284.                 $color[14'#FF0000';
  285.             }
  286.             $line '<font color="' $color[14'">' $line '</font>';
  287.         }
  288.  
  289.         $body_ary[$i$line;
  290.     }
  291.     $body '<pre>' implode("\n"$body_ary'</pre>';
  292. }
  293.  
  294. /**
  295.  * This returns a parsed string called $body. That string can then
  296.  * be displayed as the actual message in the HTML. It contains
  297.  * everything needed, including HTML Tags, Attachments at the
  298.  * bottom, etc.
  299.  */
  300. function formatBody($imap_stream$message$color$wrap_at$ent_num$id$mailbox='INBOX',$clean=false{
  301.     /* This if statement checks for the entity to show as the
  302.      * primary message. To add more of them, just put them in the
  303.      * order that is their priority.
  304.      */
  305.     global $startMessage$languages$squirrelmail_language,
  306.            $show_html_default$sort$has_unsafe_images$passed_ent_id,
  307.            $username$key$imapServerAddress$imapPort,
  308.            $download_and_unsafe_link;
  309.  
  310.     if!sqgetGlobalVar('view_unsafe_images'$view_unsafe_imagesSQ_GET) ) {
  311.         $view_unsafe_images false;
  312.     }
  313.  
  314.     $body '';
  315.     $urlmailbox urlencode($mailbox);
  316.     $body_message getEntity($message$ent_num);
  317.     if (($body_message->header->type0 == 'text'||
  318.             ($body_message->header->type0 == 'rfc822')) {
  319.         $body mime_fetch_body ($imap_stream$id$ent_num);
  320.         $body decodeBody($body$body_message->header->encoding);
  321.  
  322.         if (isset($languages[$squirrelmail_language]['XTRA_CODE']&&
  323.                 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  324.             if (mb_detect_encoding($body!= 'ASCII'{
  325.                 $body $languages[$squirrelmail_language]['XTRA_CODE']('decode'$body);
  326.             }
  327.         }
  328.         $hookResults do_hook("message_body"$body);
  329.         $body $hookResults[1];
  330.  
  331.         /* If there are other types that shouldn't be formatted, add
  332.          * them here.
  333.          */
  334.  
  335.         if ($body_message->header->type1 == 'html'{
  336.             if ($show_html_default <> 1{
  337.                 $entity_conv array('&nbsp;' => ' ',
  338.                                      '<p>'    => "\n",
  339.                                      '<P>'    => "\n",
  340.                                      '<br>'   => "\n",
  341.                                      '<BR>'   => "\n",
  342.                                      '<br />' => "\n",
  343.                                      '<BR />' => "\n",
  344.                                      '&gt;'   => '>',
  345.                                      '&lt;'   => '<');
  346.                 $body strtr($body$entity_conv);
  347.                 $body strip_tags($body);
  348.                 $body trim($body);
  349.                 translateText($body$wrap_at,
  350.                         $body_message->header->getParameter('charset'));
  351.             else {
  352.                 $body magicHTML($body$id$message$mailbox);
  353.                 $body charset_decode($body_message->header->getParameter('charset'),$body,false,true);
  354.             }
  355.         else {
  356.             translateText($body$wrap_at,
  357.                     $body_message->header->getParameter('charset'));
  358.         }
  359.  
  360.         // if this is the clean display (i.e. printer friendly), stop here.
  361.         if $clean {
  362.             return $body;
  363.         }
  364.  
  365.         $download_and_unsafe_link '';
  366.  
  367.         $link 'passed_id=' $id '&amp;ent_id='.$ent_num.
  368.             '&amp;mailbox=' $urlmailbox .'&amp;sort=' $sort .
  369.             '&amp;startMessage=' $startMessage '&amp;show_more=0';
  370.         if (isset($passed_ent_id)) {
  371.             $link .= '&amp;passed_ent_id='.$passed_ent_id;
  372.         }
  373.         $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="download.php?absolute_dl=true&amp;' .
  374.             $link '">' _("Download this as a file".  '</a>';
  375.         if ($view_unsafe_images{
  376.             $text _("Hide Unsafe Images");
  377.         else {
  378.             if (isset($has_unsafe_images&& $has_unsafe_images{
  379.                 $link .= '&amp;view_unsafe_images=1';
  380.                 $text _("View Unsafe Images");
  381.             else {
  382.                 $text '';
  383.             }
  384.         }
  385.         if($text != ''{
  386.             $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="read_body.php?' $link '">' $text '</a>';
  387.         }
  388.     }
  389.     return $body;
  390. }
  391.  
  392.  
  393. function formatAttachments($message$exclude_id$mailbox$id{
  394.     global $where$what$startMessage$color$passed_ent_id;
  395.     static $ShownHTML 0;
  396.  
  397.     $att_ar $message->getAttachments($exclude_id);
  398.  
  399.     if (!count($att_ar)) return '';
  400.  
  401.     $attachments '';
  402.  
  403.     $urlMailbox urlencode($mailbox);
  404.  
  405.     foreach ($att_ar as $att{
  406.         $ent $att->entity_id;
  407.         $header $att->header;
  408.         $type0 strtolower($header->type0);
  409.         $type1 strtolower($header->type1);
  410.         $name '';
  411.         $links['download link']['text'_("Download");
  412.         $links['download link']['href'SM_PATH .
  413.             "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
  414.         $ImageURL '';
  415.         if ($type0 =='message' && $type1 == 'rfc822'{
  416.             $default_page SM_PATH 'src/read_body.php';
  417.             $rfc822_header $att->rfc822_header;
  418.             $filename $rfc822_header->subject;
  419.             if (trim$filename == ''{
  420.                 $filename 'untitled-[' $ent ']' ;
  421.             }
  422.             $from_o $rfc822_header->from;
  423.             if (is_object($from_o)) {
  424.                 $from_name $from_o->getAddress(false);
  425.             else {
  426.                 $from_name _("Unknown sender");
  427.             }
  428.             $from_name decodeHeader(($from_name));
  429.             $description $from_name;
  430.         else {
  431.             $default_page SM_PATH 'src/download.php';
  432.             if (is_object($header->disposition)) {
  433.                 $filename $header->disposition->getProperty('filename');
  434.                 if (trim($filename== ''{
  435.                     $name decodeHeader($header->disposition->getProperty('name'));
  436.                     if (trim($name== ''{
  437.                         $name $header->getParameter('name');
  438.                         if(trim($name== ''{
  439.                             if (trim$header->id == ''{
  440.                                 $filename 'untitled-[' $ent ']' ;
  441.                             else {
  442.                                 $filename 'cid: ' $header->id;
  443.                             }
  444.                         else {
  445.                             $filename $name;
  446.                         }
  447.                     else {
  448.                         $filename $name;
  449.                     }
  450.                 }
  451.             else {
  452.                 $filename $header->getParameter('name');
  453.                 if (!trim($filename)) {
  454.                     if (trim$header->id == ''{
  455.                         $filename 'untitled-[' $ent ']' ;
  456.                     else {
  457.                         $filename 'cid: ' $header->id;
  458.                     }
  459.                 }
  460.             }
  461.             if ($header->description{
  462.                 $description decodeHeader($header->description);
  463.             else {
  464.                 $description '';
  465.             }
  466.         }
  467.  
  468.         $display_filename $filename;
  469.         if (isset($passed_ent_id)) {
  470.             $passed_ent_id_link '&amp;passed_ent_id='.$passed_ent_id;
  471.         else {
  472.             $passed_ent_id_link '';
  473.         }
  474.         $defaultlink $default_page "?startMessage=$startMessage"
  475.             . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
  476.             . '&amp;ent_id='.$ent.$passed_ent_id_link;
  477.         if ($where && $what{
  478.            $defaultlink .= '&amp;where='urlencode($where).'&amp;what='.urlencode($what);
  479.         }
  480.  
  481.         /* This executes the attachment hook with a specific MIME-type.
  482.          * If that doesn't have results, it tries if there's a rule
  483.          * for a more generic type.
  484.          */
  485.         $hookresults do_hook("attachment $type0/$type1"$links,
  486.                 $startMessage$id$urlMailbox$ent$defaultlink,
  487.                 $display_filename$where$what);
  488.         if(count($hookresults[1]<= 1{
  489.             $hookresults do_hook("attachment $type0/*"$links,
  490.                     $startMessage$id$urlMailbox$ent$defaultlink,
  491.                     $display_filename$where$what);
  492.         }
  493.  
  494.         $links $hookresults[1];
  495.         $defaultlink $hookresults[6];
  496.  
  497.         $attachments .= '<tr><td>' .
  498.             '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
  499.             '<td><small><b>' show_readable_size($header->size.
  500.             '</b>&nbsp;&nbsp;</small></td>' .
  501.             '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
  502.             '<td><small>';
  503.         $attachments .= '<b>' $description '</b>';
  504.         $attachments .= '</small></td><td><small>&nbsp;';
  505.  
  506.         $skipspaces 1;
  507.         foreach ($links as $val{
  508.             if ($skipspaces{
  509.                 $skipspaces 0;
  510.             else {
  511.                 $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
  512.             }
  513.             $attachments .= '<a href="' $val['href''">' .  $val['text''</a>';
  514.         }
  515.         unset($links);
  516.         $attachments .= "</td></tr>\n";
  517.     }
  518.     return $attachments;
  519. }
  520.  
  521. function sqimap_base64_decode(&$string{
  522.  
  523.     // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
  524.     // fly decoding (to reduce memory usage) you have to check if the
  525.     // data has incomplete pairs
  526.  
  527.     // Remove the noise in order to check if the 4 bytes pairs are complete
  528.     $string str_replace(array("\r\n","\n""\r"" "),array('','','',''),$string);
  529.  
  530.     $sStringRem '';
  531.     $iMod strlen($string4;
  532.     if ($iMod{
  533.         $sStringRem substr($string,-$iMod);
  534.         // Check if $sStringRem contains padding characters
  535.         if (substr($sStringRem,-1!= '='{
  536.             $string substr($string,0,-$iMod);
  537.         else {
  538.             $sStringRem '';
  539.         }
  540.     }
  541.     $string base64_decode($string);
  542.     return $sStringRem;
  543. }
  544.  
  545. /**
  546.  * Decodes encoded message body
  547.  *
  548.  * This function decodes the body depending on the encoding type.
  549.  * Currently quoted-printable and base64 encodings are supported.
  550.  * decode_body hook was added to this function in 1.4.2/1.5.0
  551.  * @param string $body encoded message body
  552.  * @param string $encoding used encoding
  553.  * @return string decoded string
  554.  * @since 1.0
  555.  */
  556. function decodeBody($body$encoding{
  557.  
  558.     $body str_replace("\r\n""\n"$body);
  559.     $encoding strtolower($encoding);
  560.  
  561.     $encoding_handler do_hook_function('decode_body'$encoding);
  562.  
  563.     // plugins get first shot at decoding the body
  564.     if (!empty($encoding_handler&& function_exists($encoding_handler)) {
  565.         $body $encoding_handler('decode'$body);
  566.  
  567.     elseif ($encoding == 'quoted-printable' ||
  568.             $encoding == 'quoted_printable'{
  569.         /**
  570.          * quoted_printable_decode() function is broken in older
  571.          * php versions. Text with \r\n decoding was fixed only
  572.          * in php 4.3.0. Minimal code requirement 4.0.4 +
  573.          * str_replace("\r\n", "\n", $body); call.
  574.          */
  575.         $body quoted_printable_decode($body);
  576.     elseif ($encoding == 'base64'{
  577.         $body base64_decode($body);
  578.     }
  579.  
  580.     // All other encodings are returned raw.
  581.     return $body;
  582. }
  583.  
  584. /**
  585.  * Decodes headers
  586.  *
  587.  * This functions decode strings that is encoded according to
  588.  * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  589.  * Patched by Christian Schmidt <[email protected]>  23/03/2002
  590.  */
  591. function decodeHeader ($string$utfencode=true,$htmlsave=true,$decide=false{
  592.     global $languages$squirrelmail_language,$default_charset;
  593.     if (is_array($string)) {
  594.         $string implode("\n"$string);
  595.     }
  596.  
  597.     if (isset($languages[$squirrelmail_language]['XTRA_CODE']&&
  598.             function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  599.         $string $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader'$string);
  600.         // Do we need to return at this point?
  601.         // return $string;
  602.     }
  603.     $i 0;
  604.     $iLastMatch = -2;
  605.     $encoded false;
  606.  
  607.     $aString explode(' ',$string);
  608.     $ret '';
  609.     foreach ($aString as $chunk{
  610.         if ($encoded && $chunk === ''{
  611.             continue;
  612.         elseif ($chunk === ''{
  613.             $ret .= ' ';
  614.             continue;
  615.         }
  616.         $encoded false;
  617.         /* if encoded words are not separated by a linear-space-white we still catch them */
  618.         $j $i-1;
  619.  
  620.         while ($match preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
  621.             /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
  622.             if ($iLastMatch !== $j{
  623.                 if ($htmlsave{
  624.                     $ret .= '&#32;';
  625.                 else {
  626.                     $ret .= ' ';
  627.                 }
  628.             }
  629.             $iLastMatch $i;
  630.             $j $i;
  631.             if ($htmlsave{
  632.                 $ret .= htmlspecialchars($res[1]);
  633.             else {
  634.                 $ret .= $res[1];
  635.             }
  636.             $encoding ucfirst($res[3]);
  637.  
  638.             /* decide about valid decoding */
  639.             if ($decide && is_conversion_safe($res[2])) {
  640.                 $can_be_encoded=true;
  641.             else {
  642.                 $can_be_encoded=false;
  643.             }
  644.  
  645.             switch ($encoding)
  646.             {
  647.                 case 'B':
  648.                     $replace base64_decode($res[4]);
  649.                     if ($can_be_encoded{
  650.                         // string is converted from one charset to another. sanitizing depends on $htmlsave
  651.                         $replace =  charset_convert($res[2],$replace,$default_charset,$htmlsave);
  652.                     elseif ($utfencode{
  653.                         // string is converted to htmlentities and sanitized
  654.                         $replace charset_decode($res[2],$replace);
  655.                     elseif ($htmlsave{
  656.                         // string is not converted, but still sanitized
  657.                         $replace htmlspecialchars($replace);
  658.                     }
  659.                     $ret.= $replace;
  660.                     break;
  661.                 case 'Q':
  662.                     $replace str_replace('_'' '$res[4]);
  663.                     $replace preg_replace('/=([0-9a-f]{2})/ie''chr(hexdec("\1"))',
  664.                             $replace);
  665.                     if ($can_be_encoded{
  666.                         // string is converted from one charset to another. sanitizing depends on $htmlsave
  667.                         $replace charset_convert($res[2]$replace,$default_charset,$htmlsave);
  668.                     elseif ($utfencode{
  669.                         // string is converted to html entities and sanitized
  670.                         $replace charset_decode($res[2]$replace);
  671.                     elseif ($htmlsave{
  672.                         // string is not converted, but still sanizited
  673.                         $replace htmlspecialchars($replace);
  674.                     }
  675.                     $ret .= $replace;
  676.                     break;
  677.                 default:
  678.                     break;
  679.             }
  680.             $chunk $res[5];
  681.             $encoded true;
  682.         }
  683.         if (!$encoded{
  684.             if ($htmlsave{
  685.                 $ret .= '&#32;';
  686.             else {
  687.                 $ret .= ' ';
  688.             }
  689.         }
  690.  
  691.         if (!$encoded && $htmlsave{
  692.             $ret .= htmlspecialchars($chunk);
  693.         else {
  694.             $ret .= $chunk;
  695.         }
  696.         ++$i;
  697.     }
  698.     /* remove the first added space */
  699.     if ($ret{
  700.         if ($htmlsave{
  701.             $ret substr($ret,5);
  702.         else {
  703.             $ret substr($ret,1);
  704.         }
  705.     }
  706.  
  707.     return $ret;
  708. }
  709.  
  710. /**
  711.  * Encodes header as quoted-printable
  712.  *
  713.  * Encode a string according to RFC 1522 for use in headers if it
  714.  * contains 8-bit characters or anything that looks like it should
  715.  * be encoded.
  716.  */
  717. function encodeHeader ($string{
  718.     global $default_charset$languages$squirrelmail_language;
  719.  
  720.     if (isset($languages[$squirrelmail_language]['XTRA_CODE']&&
  721.             function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  722.         return  $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader'$string);
  723.     }
  724.  
  725.     // Use B encoding for multibyte charsets
  726.     $mb_charsets array('utf-8','big5','gb2313','euc-kr');
  727.     if (in_array($default_charset,$mb_charsets&&
  728.         in_array($default_charset,sq_mb_list_encodings()) &&
  729.         sq_is8bit($string)) {
  730.         return encodeHeaderBase64($string,$default_charset);
  731.     elseif (in_array($default_charset,$mb_charsets&&
  732.               sq_is8bit($string&&
  733.               in_array($default_charset,sq_mb_list_encodings())) {
  734.         // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
  735.         // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
  736.     }
  737.  
  738.     // Encode only if the string contains 8-bit characters or =?
  739.     $j strlen($string);
  740.     $max_l 75 strlen($default_charset7;
  741.     $aRet array();
  742.     $ret '';
  743.     $iEncStart $enc_init false;
  744.     $cur_l $iOffset 0;
  745.     for($i 0$i $j++$i{
  746.         switch($string{$i})
  747.         {
  748.             case '=':
  749.             case '<':
  750.             case '>':
  751.             case ',':
  752.             case '?':
  753.             case '_':
  754.                 if ($iEncStart === false{
  755.                     $iEncStart $i;
  756.                 }
  757.                 $cur_l+=3;
  758.                 if ($cur_l ($max_l-2)) {
  759.                     /* if there is an stringpart that doesn't need encoding, add it */
  760.                     $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  761.                     $aRet["=?$default_charset?Q?$ret?=";
  762.                     $iOffset $i;
  763.                     $cur_l 0;
  764.                     $ret '';
  765.                     $iEncStart false;
  766.                 else {
  767.                     $ret .= sprintf("=%02X",ord($string{$i}));
  768.                 }
  769.                 break;
  770.             case '(':
  771.             case ')':
  772.                 if ($iEncStart !== false{
  773.                     $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  774.                     $aRet["=?$default_charset?Q?$ret?=";
  775.                     $iOffset $i;
  776.                     $cur_l 0;
  777.                     $ret '';
  778.                     $iEncStart false;
  779.                 }
  780.                 break;
  781.             case ' ':
  782.                 if ($iEncStart !== false{
  783.                     $cur_l++;
  784.                     if ($cur_l $max_l{
  785.                         $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  786.                         $aRet["=?$default_charset?Q?$ret?=";
  787.                         $iOffset $i;
  788.                         $cur_l 0;
  789.                         $ret '';
  790.                         $iEncStart false;
  791.                     else {
  792.                         $ret .= '_';
  793.                     }
  794.                 }
  795.                 break;
  796.             default:
  797.                 $k ord($string{$i});
  798.                 if ($k 126{
  799.                     if ($iEncStart === false{
  800.                         // do not start encoding in the middle of a string, also take the rest of the word.
  801.                         $sLeadString substr($string,0,$i);
  802.                         $aLeadString explode(' ',$sLeadString);
  803.                         $sToBeEncoded array_pop($aLeadString);
  804.                         $iEncStart $i strlen($sToBeEncoded);
  805.                         $ret .= $sToBeEncoded;
  806.                         $cur_l += strlen($sToBeEncoded);
  807.                     }
  808.                     $cur_l += 3;
  809.                     /* first we add the encoded string that reached it's max size */
  810.                     if ($cur_l ($max_l-2)) {
  811.                         $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  812.                         $aRet["=?$default_charset?Q?$ret?= "/* the next part is also encoded => separate by space */
  813.                         $cur_l 3;
  814.                         $ret '';
  815.                         $iOffset $i;
  816.                         $iEncStart $i;
  817.                     }
  818.                     $enc_init true;
  819.                     $ret .= sprintf("=%02X"$k);
  820.                 else {
  821.                     if ($iEncStart !== false{
  822.                         $cur_l++;
  823.                         if ($cur_l $max_l{
  824.                             $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  825.                             $aRet["=?$default_charset?Q?$ret?=";
  826.                             $iEncStart false;
  827.                             $iOffset $i;
  828.                             $cur_l 0;
  829.                             $ret '';
  830.                         else {
  831.                             $ret .= $string{$i};
  832.                         }
  833.                     }
  834.                 }
  835.                 break;
  836.         }
  837.     }
  838.  
  839.     if ($enc_init{
  840.         if ($iEncStart !== false{
  841.             $aRet[substr($string,$iOffset,$iEncStart-$iOffset);
  842.             $aRet["=?$default_charset?Q?$ret?=";
  843.         else {
  844.             $aRet[substr($string,$iOffset);
  845.         }
  846.         $string implode('',$aRet);
  847.     }
  848.     return $string;
  849. }
  850.  
  851. /**
  852.  * Encodes string according to rfc2047 B encoding header formating rules
  853.  *
  854.  * It is recommended way to encode headers with character sets that store
  855.  * symbols in more than one byte.
  856.  *
  857.  * Function requires mbstring support. If required mbstring functions are missing,
  858.  * function returns false and sets E_USER_WARNING level error message.
  859.  *
  860.  * Minimal requirements - php 4.0.6 with mbstring extension. Please note,
  861.  * that mbstring functions will generate E_WARNING errors, if unsupported
  862.  * character set is used. mb_encode_mimeheader function provided by php
  863.  * mbstring extension is not used in order to get better control of header
  864.  * encoding.
  865.  *
  866.  * Used php code functions - function_exists(), trigger_error(), strlen()
  867.  * (is used with charset names and base64 strings). Used php mbstring
  868.  * functions - mb_strlen and mb_substr.
  869.  *
  870.  * Related documents: rfc 2045 (BASE64 encoding), rfc 2047 (mime header
  871.  * encoding), rfc 2822 (header folding)
  872.  *
  873.  * @param string $string header string that must be encoded
  874.  * @param string $charset character set. Must be supported by mbstring extension.
  875.  *  Use sq_mb_list_encodings() to detect supported charsets.
  876.  * @return string string encoded according to rfc2047 B encoding formating rules
  877.  * @since 1.5.1 and 1.4.6
  878.  */
  879. function encodeHeaderBase64($string,$charset{
  880.     /**
  881.      * Check mbstring function requirements.
  882.      */
  883.     if (function_exists('mb_strlen'||
  884.         function_exists('mb_substr')) {
  885.         // set E_USER_WARNING
  886.         trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
  887.         // return false
  888.         return false;
  889.     }
  890.  
  891.     // initial return array
  892.     $aRet array();
  893.  
  894.     /**
  895.      * header length = 75 symbols max (same as in encodeHeader)
  896.      * remove $charset length
  897.      * remove =? ? ?= (5 chars)
  898.      * remove 2 more chars (\r\n ?)
  899.      */
  900.     $iMaxLength 75 strlen($charset7;
  901.  
  902.     // set first character position
  903.     $iStartCharNum 0;
  904.  
  905.     // loop through all characters. count characters and not bytes.
  906.     for ($iCharNum=1$iCharNum<=mb_strlen($string,$charset)$iCharNum++{
  907.         // encode string from starting character to current character.
  908.         $encoded_string base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  909.  
  910.         // Check encoded string length
  911.         if(strlen($encoded_string)>$iMaxLength{
  912.             // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
  913.             $aRet[base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
  914.  
  915.             // set new starting character
  916.             $iStartCharNum $iCharNum-1;
  917.  
  918.             // encode last char (in case it is last character in string)
  919.             $encoded_string base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
  920.         // if string is shorter than max length - add next character
  921.     }
  922.  
  923.     // add last encoded string to array
  924.     $aRet[$encoded_string;
  925.  
  926.     // set initial return string
  927.     $sRet '';
  928.  
  929.     // loop through encoded strings
  930.     foreach($aRet as $string{
  931.         // TODO: Do we want to control EOL (end-of-line) marker
  932.         if ($sRet!=''$sRet.= " ";
  933.  
  934.         // add header tags and encoded string to return string
  935.         $sRet.= '=?'.$charset.'?B?'.$string.'?=';
  936.     }
  937.  
  938.     return $sRet;
  939. }
  940.  
  941. /* This function trys to locate the entity_id of a specific mime element */
  942. function find_ent_id($id$message{
  943.     for ($i 0$ret ''$ret == '' && $i count($message->entities)$i++{
  944.         if ($message->entities[$i]->header->type0 == 'multipart')  {
  945.             $ret find_ent_id($id$message->entities[$i]);
  946.         else {
  947.             if (strcasecmp($message->entities[$i]->header->id$id== 0{
  948. //                if (sq_check_save_extension($message->entities[$i])) {
  949.                 return $message->entities[$i]->entity_id;
  950. //                }
  951.             elseif (!empty($message->entities[$i]->header->parameters['name'])) {
  952.                 /**
  953.                  * This is part of a fix for Outlook Express 6.x generating
  954.                  * cid URLs without creating content-id headers
  955.                  * @@JA - 20050207
  956.                  */
  957.                 if (strcasecmp($message->entities[$i]->header->parameters['name']$id== 0{
  958.                     return $message->entities[$i]->entity_id;
  959.                 }
  960.             }
  961.         }
  962.     }
  963.     return $ret;
  964. }
  965.  
  966. function sq_check_save_extension($message{
  967.     $filename $message->getFilename();
  968.     $ext substr($filenamestrrpos($filename,'.')+1);
  969.     $save_extensions array('jpg','jpeg','gif','png','bmp');
  970.     return in_array($ext$save_extensions);
  971. }
  972.  
  973.  
  974. /**
  975.  ** HTMLFILTER ROUTINES
  976.  */
  977.  
  978. /**
  979.  * This function checks attribute values for entity-encoded values
  980.  * and returns them translated into 8-bit strings so we can run
  981.  * checks on them.
  982.  *
  983.  * @param  $attvalue A string to run entity check against.
  984.  * @return           Nothing, modifies a reference value.
  985.  */
  986. function sq_defang(&$attvalue){
  987.     $me 'sq_defang';
  988.     /**
  989.      * Skip this if there aren't ampersands or backslashes.
  990.      */
  991.     if (strpos($attvalue'&'=== false
  992.         && strpos($attvalue'\\'=== false){
  993.         return;
  994.     }
  995.     $m false;
  996.     do {
  997.         $m false;
  998.         $m $m || sq_deent($attvalue'/\&#0*(\d+);*/s');
  999.         $m $m || sq_deent($attvalue'/\&#x0*((\d|[a-f])+);*/si'true);
  1000.         $m $m || sq_deent($attvalue'/\\\\(\d+)/s'true);
  1001.     while ($m == true);
  1002.     $attvalue stripslashes($attvalue);
  1003. }
  1004.  
  1005. /**
  1006.  * Kill any tabs, newlines, or carriage returns. Our friends the
  1007.  * makers of the browser with 95% market value decided that it'd
  1008.  * be funny to make "java[tab]script" be just as good as "javascript".
  1009.  *
  1010.  * @param  attvalue  The attribute value before extraneous spaces removed.
  1011.  * @return attvalue  Nothing, modifies a reference value.
  1012.  */
  1013. function sq_unspace(&$attvalue){
  1014.     $me 'sq_unspace';
  1015.     if (strcspn($attvalue"\t\r\n\0 "!= strlen($attvalue)){
  1016.         $attvalue str_replace(Array("\t""\r""\n""\0"" "),
  1017.                                 Array('',   '',   '',   '',   '')$attvalue);
  1018.     }
  1019. }
  1020.  
  1021. /**
  1022.  * This function returns the final tag out of the tag name, an array
  1023.  * of attributes, and the type of the tag. This function is called by
  1024.  * sq_sanitize internally.
  1025.  *
  1026.  * @param  $tagname  the name of the tag.
  1027.  * @param  $attary   the array of attributes and their values
  1028.  * @param  $tagtype  The type of the tag (see in comments).
  1029.  * @return           string with the final tag representation.
  1030.  */
  1031. function sq_tagprint($tagname$attary$tagtype){
  1032.     $me 'sq_tagprint';
  1033.  
  1034.     if ($tagtype == 2){
  1035.         $fulltag '</' $tagname '>';
  1036.     else {
  1037.         $fulltag '<' $tagname;
  1038.         if (is_array($attary&& sizeof($attary)){
  1039.             $atts Array();
  1040.             while (list($attname$attvalueeach($attary)){
  1041.                 array_push($atts"$attname=$attvalue");
  1042.             }
  1043.             $fulltag .= ' ' join(" "$atts);
  1044.         }
  1045.         if ($tagtype == 3){
  1046.             $fulltag .= ' /';
  1047.         }
  1048.         $fulltag .= '>';
  1049.     }
  1050.     return $fulltag;
  1051. }
  1052.  
  1053. /**
  1054.  * A small helper function to use with array_walk. Modifies a by-ref
  1055.  * value and makes it lowercase.
  1056.  *
  1057.  * @param  $val a value passed by-ref.
  1058.  * @return      void since it modifies a by-ref value.
  1059.  */
  1060. function sq_casenormalize(&$val){
  1061.     $val strtolower($val);
  1062. }
  1063.  
  1064. /**
  1065.  * This function skips any whitespace from the current position within
  1066.  * a string and to the next non-whitespace value.
  1067.  *
  1068.  * @param  $body   the string
  1069.  * @param  $offset the offset within the string where we should start
  1070.  *                  looking for the next non-whitespace character.
  1071.  * @return         the location within the $body where the next
  1072.  *                  non-whitespace char is located.
  1073.  */
  1074. function sq_skipspace($body$offset){
  1075.     $me 'sq_skipspace';
  1076.     preg_match('/^(\s*)/s'substr($body$offset)$matches);
  1077.     if (sizeof($matches{1})){
  1078.         $count strlen($matches{1});
  1079.         $offset += $count;
  1080.     }
  1081.     return $offset;
  1082. }
  1083.  
  1084. /**
  1085.  * This function looks for the next character within a string.  It's
  1086.  * really just a glorified "strpos", except it catches if failures
  1087.  * nicely.
  1088.  *
  1089.  * @param  $body   The string to look for needle in.
  1090.  * @param  $offset Start looking from this position.
  1091.  * @param  $needle The character/string to look for.
  1092.  * @return         location of the next occurance of the needle, or
  1093.  *                  strlen($body) if needle wasn't found.
  1094.  */
  1095. function sq_findnxstr($body$offset$needle){
  1096.     $me  'sq_findnxstr';
  1097.     $pos strpos($body$needle$offset);
  1098.     if ($pos === FALSE){
  1099.         $pos strlen($body);
  1100.     }
  1101.     return $pos;
  1102. }
  1103.  
  1104. /**
  1105.  * This function takes a PCRE-style regexp and tries to match it
  1106.  * within the string.
  1107.  *
  1108.  * @param  $body   The string to look for needle in.
  1109.  * @param  $offset Start looking from here.
  1110.  * @param  $reg    A PCRE-style regex to match.
  1111.  * @return         Returns a false if no matches found, or an array
  1112.  *                  with the following members:
  1113.  *                  - integer with the location of the match within $body
  1114.  *                  - string with whatever content between offset and the match
  1115.  *                  - string with whatever it is we matched
  1116.  */
  1117. function sq_findnxreg($body$offset$reg){
  1118.     $me 'sq_findnxreg';
  1119.     $matches Array();
  1120.     $retarr Array();
  1121.     preg_match("%^(.*?)($reg)%si"substr($body$offset)$matches);
  1122.     if (!isset($matches{0}|| !$matches{0}){
  1123.         $retarr false;
  1124.     else {
  1125.         $retarr{0$offset strlen($matches{1});
  1126.         $retarr{1$matches{1};
  1127.         $retarr{2$matches{2};
  1128.     }
  1129.     return $retarr;
  1130. }
  1131.  
  1132. /**
  1133.  * This function looks for the next tag.
  1134.  *
  1135.  * @param  $body   String where to look for the next tag.
  1136.  * @param  $offset Start looking from here.
  1137.  * @return         false if no more tags exist in the body, or
  1138.  *                  an array with the following members:
  1139.  *                  - string with the name of the tag
  1140.  *                  - array with attributes and their values
  1141.  *                  - integer with tag type (1, 2, or 3)
  1142.  *                  - integer where the tag starts (starting "<")
  1143.  *                  - integer where the tag ends (ending ">")
  1144.  *                  first three members will be false, if the tag is invalid.
  1145.  */
  1146. function sq_getnxtag($body$offset){
  1147.     $me 'sq_getnxtag';
  1148.     if ($offset strlen($body)){
  1149.         return false;
  1150.     }
  1151.     $lt sq_findnxstr($body$offset"<");
  1152.     if ($lt == strlen($body)){
  1153.         return false;
  1154.     }
  1155.     /**
  1156.      * We are here:
  1157.      * blah blah <tag attribute="value">
  1158.      * \---------^
  1159.      */
  1160.     $pos sq_skipspace($body$lt+1);
  1161.     if ($pos >= strlen($body)){
  1162.         return Array(falsefalsefalse$ltstrlen($body));
  1163.     }
  1164.     /**
  1165.      * There are 3 kinds of tags:
  1166.      * 1. Opening tag, e.g.:
  1167.      *    <a href="blah">
  1168.      * 2. Closing tag, e.g.:
  1169.      *    </a>
  1170.      * 3. XHTML-style content-less tag, e.g.:
  1171.      *    <img src="blah" />
  1172.      */
  1173.     $tagtype false;
  1174.     switch (substr($body$pos1)){
  1175.         case '/':
  1176.             $tagtype 2;
  1177.             $pos++;
  1178.             break;
  1179.         case '!':
  1180.             /**
  1181.              * A comment or an SGML declaration.
  1182.              */
  1183.             if (substr($body$pos+12== "--"){
  1184.                 $gt strpos($body"-->"$pos);
  1185.                 if ($gt === false){
  1186.                     $gt strlen($body);
  1187.                 else {
  1188.                     $gt += 2;
  1189.                 }
  1190.                 return Array(falsefalsefalse$lt$gt);
  1191.             else {
  1192.                 $gt sq_findnxstr($body$pos">");
  1193.                 return Array(falsefalsefalse$lt$gt);
  1194.             }
  1195.             break;
  1196.         default:
  1197.             /**
  1198.              * Assume tagtype 1 for now. If it's type 3, we'll switch values
  1199.              * later.
  1200.              */
  1201.             $tagtype 1;
  1202.             break;
  1203.     }
  1204.  
  1205.     $tag_start $pos;
  1206.     $tagname '';
  1207.     /**
  1208.      * Look for next [\W-_], which will indicate the end of the tag name.
  1209.      */
  1210.     $regary sq_findnxreg($body$pos"[^\w\-_]");
  1211.     if ($regary == false){
  1212.         return Array(falsefalsefalse$ltstrlen($body));
  1213.     }
  1214.     list($pos$tagname$match$regary;
  1215.     $tagname strtolower($tagname);
  1216.  
  1217.     /**
  1218.      * $match can be either of these:
  1219.      * '>'  indicating the end of the tag entirely.
  1220.      * '\s' indicating the end of the tag name.
  1221.      * '/'  indicating that this is type-3 xhtml tag.
  1222.      *
  1223.      * Whatever else we find there indicates an invalid tag.
  1224.      */
  1225.     switch ($match){
  1226.         case '/':
  1227.             /**
  1228.              * This is an xhtml-style tag with a closing / at the
  1229.              * end, like so: <img src="blah" />. Check if it's followed
  1230.              * by the closing bracket. If not, then this tag is invalid
  1231.              */
  1232.             if (substr($body$pos2== "/>"){
  1233.                 $pos++;
  1234.                 $tagtype 3;
  1235.             else {
  1236.                 $gt sq_findnxstr($body$pos">");
  1237.                 $retary Array(falsefalsefalse$lt$gt);
  1238.                 return $retary;
  1239.             }
  1240.         case '>':
  1241.             return Array($tagnamefalse$tagtype$lt$pos);
  1242.             break;
  1243.         default:
  1244.             /**
  1245.              * Check if it's whitespace
  1246.              */
  1247.             if (!preg_match('/\s/'$match)){
  1248.                 /**
  1249.                  * This is an invalid tag! Look for the next closing ">".
  1250.                  */
  1251.                 $gt sq_findnxstr($body$lt">");
  1252.                 return Array(falsefalsefalse$lt$gt);
  1253.             }
  1254.             break;
  1255.     }
  1256.  
  1257.     /**
  1258.      * At this point we're here:
  1259.      * <tagname  attribute='blah'>
  1260.      * \-------^
  1261.      *
  1262.      * At this point we loop in order to find all attributes.
  1263.      */
  1264.     $attname '';
  1265.     $atttype false;
  1266.     $attary Array();
  1267.  
  1268.     while ($pos <= strlen($body)){
  1269.         $pos sq_skipspace($body$pos);
  1270.         if ($pos == strlen($body)){
  1271.             /**
  1272.              * Non-closed tag.
  1273.              */
  1274.             return Array(falsefalsefalse$lt$pos);
  1275.         }
  1276.         /**
  1277.          * See if we arrived at a ">" or "/>", which means that we reached
  1278.          * the end of the tag.
  1279.          */
  1280.         $matches Array();
  1281.         if (preg_match("%^(\s*)(>|/>)%s"substr($body$pos)$matches)) {
  1282.             /**
  1283.              * Yep. So we did.
  1284.              */
  1285.             $pos += strlen($matches{1});
  1286.             if ($matches{2== "/>"){
  1287.                 $tagtype 3;
  1288.                 $pos++;
  1289.             }
  1290.             return Array($tagname$attary$tagtype$lt$pos);
  1291.         }
  1292.  
  1293.         /**
  1294.          * There are several types of attributes, with optional
  1295.          * [:space:] between members.
  1296.          * Type 1:
  1297.          *   attrname[:space:]=[:space:]'CDATA'
  1298.          * Type 2:
  1299.          *   attrname[:space:]=[:space:]"CDATA"
  1300.          * Type 3:
  1301.          *   attr[:space:]=[:space:]CDATA
  1302.          * Type 4:
  1303.          *   attrname
  1304.          *
  1305.          * We leave types 1 and 2 the same, type 3 we check for
  1306.          * '"' and convert to "&quot" if needed, then wrap in
  1307.          * double quotes. Type 4 we convert into:
  1308.          * attrname="yes".
  1309.          */
  1310.         $regary sq_findnxreg($body$pos"[^:\w\-_]");
  1311.         if ($regary == false){
  1312.             /**
  1313.              * Looks like body ended before the end of tag.
  1314.              */
  1315.             return Array(falsefalsefalse$ltstrlen($body));
  1316.         }
  1317.         list($pos$attname$match$regary;
  1318.         $attname strtolower($attname);
  1319.         /**
  1320.          * We arrived at the end of attribute name. Several things possible
  1321.          * here:
  1322.          * '>'  means the end of the tag and this is attribute type 4
  1323.          * '/'  if followed by '>' means the same thing as above
  1324.          * '\s' means a lot of things -- look what it's followed by.
  1325.          *      anything else means the attribute is invalid.
  1326.          */
  1327.         switch($match){
  1328.             case '/':
  1329.                 /**
  1330.                  * This is an xhtml-style tag with a closing / at the
  1331.                  * end, like so: <img src="blah" />. Check if it's followed
  1332.                  * by the closing bracket. If not, then this tag is invalid
  1333.                  */
  1334.                 if (substr($body$pos2== "/>"){
  1335.                     $pos++;
  1336.                     $tagtype 3;
  1337.                 else {
  1338.                     $gt sq_findnxstr($body$pos">");
  1339.                     $retary Array(falsefalsefalse$lt$gt);
  1340.                     return $retary;
  1341.                 }
  1342.             case '>':
  1343.                 $attary{$attname'"yes"';
  1344.                 return Array($tagname$attary$tagtype$lt$pos);
  1345.                 break;
  1346.             default:
  1347.                 /**
  1348.                  * Skip whitespace and see what we arrive at.
  1349.                  */
  1350.                 $pos sq_skipspace($body$pos);
  1351.                 $char substr($body$pos1);
  1352.                 /**
  1353.                  * Two things are valid here:
  1354.                  * '=' means this is attribute type 1 2 or 3.
  1355.                  * \w means this was attribute type 4.
  1356.                  * anything else we ignore and re-loop. End of tag and
  1357.                  * invalid stuff will be caught by our checks at the beginning
  1358.                  * of the loop.
  1359.                  */
  1360.                 if ($char == "="){
  1361.                     $pos++;
  1362.                     $pos sq_skipspace($body$pos);
  1363.                     /**
  1364.                      * Here are 3 possibilities:
  1365.                      * "'"  attribute type 1
  1366.                      * '"'  attribute type 2
  1367.                      * everything else is the content of tag type 3
  1368.                      */
  1369.                     $quot substr($body$pos1);
  1370.                     if ($quot == "'"){
  1371.                         $regary sq_findnxreg($body$pos+1"\'");
  1372.                         if ($regary == false){
  1373.                             return Array(falsefalsefalse$ltstrlen($body));
  1374.                         }
  1375.                         list($pos$attval$match$regary;
  1376.                         $pos++;
  1377.                         $attary{$attname"'" $attval "'";
  1378.                     else if ($quot == '"'){
  1379.                         $regary sq_findnxreg($body$pos+1'\"');
  1380.                         if ($regary == false){
  1381.                             return Array(falsefalsefalse$ltstrlen($body));
  1382.                         }
  1383.                         list($pos$attval$match$regary;
  1384.                         $pos++;
  1385.                         $attary{$attname'"' $attval '"';
  1386.                     else {
  1387.                         /**
  1388.                          * These are hateful. Look for \s, or >.
  1389.                          */
  1390.                         $regary sq_findnxreg($body$pos"[\s>]");
  1391.                         if ($regary == false){
  1392.                             return Array(falsefalsefalse$ltstrlen($body));
  1393.                         }
  1394.                         list($pos$attval$match$regary;
  1395.                         /**
  1396.                          * If it's ">" it will be caught at the top.
  1397.                          */
  1398.                         $attval preg_replace("/\"/s""&quot;"$attval);
  1399.                         $attary{$attname'"' $attval '"';
  1400.                     }
  1401.                 else if (preg_match("|[\w/>]|"$char)) {
  1402.                     /**
  1403.                      * That was attribute type 4.
  1404.                      */
  1405.                     $attary{$attname'"yes"';
  1406.                 else {
  1407.                     /**
  1408.                      * An illegal character. Find next '>' and return.
  1409.                      */
  1410.                     $gt sq_findnxstr($body$pos">");
  1411.                     return Array(falsefalsefalse$lt$gt);
  1412.                 }
  1413.                 break;
  1414.         }
  1415.     }
  1416.     /**
  1417.      * The fact that we got here indicates that the tag end was never
  1418.      * found. Return invalid tag indication so it gets stripped.
  1419.      */
  1420.     return Array(falsefalsefalse$ltstrlen($body));
  1421. }
  1422.  
  1423. /**
  1424.  * Translates entities into literal values so they can be checked.
  1425.  *
  1426.  * @param $attvalue the by-ref value to check.
  1427.  * @param $regex    the regular expression to check against.
  1428.  * @param $hex      whether the entites are hexadecimal.
  1429.  * @return          True or False depending on whether there were matches.
  1430.  */
  1431. function sq_deent(&$attvalue$regex$hex=false){
  1432.     $me 'sq_deent';
  1433.     $ret_match false;
  1434.     preg_match_all($regex$attvalue$matches);
  1435.     if (is_array($matches&& sizeof($matches[0]0){
  1436.         $repl Array();
  1437.         for ($i 0$i sizeof($matches[0])$i++){
  1438.             $numval $matches[1][$i];
  1439.             if ($hex){
  1440.                 $numval hexdec($numval);
  1441.             }
  1442.             $repl{$matches[0][$i]chr($numval);
  1443.         }
  1444.         $attvalue strtr($attvalue$repl);
  1445.         return true;
  1446.     else {
  1447.         return false;
  1448.     }
  1449. }
  1450.  
  1451. /**
  1452.  * This function runs various checks against the attributes.
  1453.  *
  1454.  * @param  $tagname         String with the name of the tag.
  1455.  * @param  $attary          Array with all tag attributes.
  1456.  * @param  $rm_attnames     See description for sq_sanitize
  1457.  * @param  $bad_attvals     See description for sq_sanitize
  1458.  * @param  $add_attr_to_tag See description for sq_sanitize
  1459.  * @param  $message         message object
  1460.  * @param  $id              message id
  1461.  * @return                  Array with modified attributes.
  1462.  */
  1463. function sq_fixatts($tagname,
  1464.                     $attary,
  1465.                     $rm_attnames,
  1466.                     $bad_attvals,
  1467.                     $add_attr_to_tag,
  1468.                     $message,
  1469.                     $id,
  1470.                     $mailbox
  1471.                     ){
  1472.     $me 'sq_fixatts';
  1473.     while (list($attname$attvalueeach($attary)){
  1474.         /**
  1475.          * See if this attribute should be removed.
  1476.          */
  1477.         foreach ($rm_attnames as $matchtag=>$matchattrs){
  1478.             if (preg_match($matchtag$tagname)){
  1479.                 foreach ($matchattrs as $matchattr){
  1480.                     if (preg_match($matchattr$attname)){
  1481.                         unset($attary{$attname});
  1482.                         continue;
  1483.                     }
  1484.                 }
  1485.             }
  1486.         }
  1487.         /**
  1488.          * Remove any backslashes, entities, and extraneous whitespace.
  1489.          */
  1490.         sq_defang($attvalue);
  1491.         sq_unspace($attvalue);
  1492.  
  1493.         /**
  1494.          * Now let's run checks on the attvalues.
  1495.          * I don't expect anyone to comprehend this. If you do,
  1496.          * get in touch with me so I can drive to where you live and
  1497.          * shake your hand personally. :)
  1498.          */
  1499.         foreach ($bad_attvals as $matchtag=>$matchattrs){
  1500.             if (preg_match($matchtag$tagname)){
  1501.                 foreach ($matchattrs as $matchattr=>$valary){
  1502.                     if (preg_match($matchattr$attname)){
  1503.                         /**
  1504.                          * There are two arrays in valary.
  1505.                          * First is matches.
  1506.                          * Second one is replacements
  1507.                          */
  1508.                         list($valmatch$valrepl$valary;
  1509.                         $newvalue =
  1510.                             preg_replace($valmatch$valrepl$attvalue);
  1511.                         if ($newvalue != $attvalue){
  1512.                             $attary{$attname$newvalue;
  1513.                         }
  1514.                     }
  1515.                 }
  1516.             }
  1517.         }
  1518.  
  1519.         /**
  1520.          * Replace empty src tags with the blank image.  src is only used
  1521.          * for frames, images, and image inputs.  Doing a replace should
  1522.          * not affect them working as should be, however it will stop
  1523.          * IE from being kicked off when src for img tags are not set
  1524.          */
  1525.         if (($attname == 'src'&& ($attvalue == '""')) {
  1526.             $attary{$attname'"' SM_PATH 'images/blank.png"';
  1527.         }
  1528.  
  1529.         /**
  1530.          * Turn cid: urls into http-friendly ones.
  1531.          */
  1532.         if (preg_match("/^[\'\"]\s*cid:/si"$attvalue)){
  1533.             $attary{$attnamesq_cid2http($message$id$attvalue$mailbox);
  1534.         }
  1535.  
  1536.         /**
  1537.          * "Hack" fix for Outlook using propriatary outbind:// protocol in img tags.
  1538.          * One day MS might actually make it match something useful, for now, falling
  1539.          * back to using cid2http, so we can grab the blank.png.
  1540.          */
  1541.         if (preg_match("/^[\'\"]\s*outbind:\/\//si"$attvalue)) {
  1542.             $attary{$attnamesq_cid2http($message$id$attvalue$mailbox);
  1543.         }
  1544.  
  1545.     }
  1546.     /**
  1547.      * See if we need to append any attributes to this tag.
  1548.      */
  1549.     foreach ($add_attr_to_tag as $matchtag=>$addattary){
  1550.         if (preg_match($matchtag$tagname)){
  1551.             $attary array_merge($attary$addattary);
  1552.         }
  1553.     }
  1554.     return $attary;
  1555. }
  1556.  
  1557. /**
  1558.  * This function edits the style definition to make them friendly and
  1559.  * usable in SquirrelMail.
  1560.  *
  1561.  * @param  $message  the message object
  1562.  * @param  $id       the message id
  1563.  * @param  $content  a string with whatever is between <style> and </style>
  1564.  * @param  $mailbox  the message mailbox
  1565.  * @return           string with edited content.
  1566.  */
  1567. function sq_fixstyle($body$pos$message$id$mailbox){
  1568.     global $view_unsafe_images;
  1569.     $me 'sq_fixstyle';
  1570.     $ret sq_findnxreg($body$pos'</\s*style\s*>');
  1571.     if ($ret == FALSE){
  1572.         return array(FALSEstrlen($body));
  1573.     }
  1574.     $newpos $ret[0strlen($ret[2]);
  1575.     $content $ret[1];
  1576.     /**
  1577.      * First look for general BODY style declaration, which would be
  1578.      * like so:
  1579.      * body {background: blah-blah}
  1580.      * and change it to .bodyclass so we can just assign it to a <div>
  1581.      */
  1582.     $content preg_replace("|body(\s*\{.*?\})|si"".bodyclass\\1"$content);
  1583.     $secremoveimg '../images/' _("sec_remove_eng.png");
  1584.     /**
  1585.      * Fix url('blah') declarations.
  1586.      */
  1587.     // remove NUL
  1588.     $content str_replace("\0"""$content);
  1589.     // translate ur\l and variations into url (IE parses that)
  1590.     $content preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",'url'$content);
  1591.     // NB I insert NUL characters to keep to avoid an infinite loop. They are removed after the loop.
  1592.     while (preg_match("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si"$content$matches)) {
  1593.         $sProto strtolower($matches[1]);
  1594.         switch ($sProto{
  1595.             /**
  1596.              * Fix url('https*://.*) declarations but only if $view_unsafe_images
  1597.              * is false.
  1598.              */
  1599.             case 'https':
  1600.             case 'http':
  1601.                 if (!$view_unsafe_images){
  1602.  
  1603.                     $sExpr "/url\s*\(\s*[\'\"]?\s*$sProto*:.*[\'\"]?\s*\)/si";
  1604.                     $content preg_replace($sExpr"u\0r\0l(\\1$secremoveimg\\2)"$content);
  1605.  
  1606.                 else {
  1607.                     $content preg_replace('/url/i',"u\0r\0l",$content);
  1608.                 }
  1609.                 break;
  1610.  
  1611.             /**
  1612.              * Fix urls that refer to cid:
  1613.              */
  1614.             case 'cid':
  1615.                 $cidurl 'cid:'$matches[2];
  1616.                 $httpurl sq_cid2http($message$id$cidurl$mailbox);
  1617.                 // escape parentheses that can modify the regular expression
  1618.                 $cidurl str_replace(array('(',')'),array('\\(','\\)'),$cidurl);
  1619.                 $content preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
  1620.                                         "u\0r\0l($httpurl)"$content);
  1621.                 break;
  1622.             default:
  1623.                 /**
  1624.                  * replace url with protocol other then the white list
  1625.                  * http,https and cid by an empty string.
  1626.                  */
  1627.                 $content preg_replace("/url\s*\(\s*[\'\"]?([^:]+):(.*)?[\'\"]?\s*\)/si",
  1628.                                  ""$content);
  1629.                 break;
  1630.         }
  1631.         break;
  1632.     }
  1633.     // remove NUL
  1634.     $content str_replace("\0"""$content);
  1635.  
  1636.     /**
  1637.      * Remove any backslashes, entities, and extraneous whitespace.
  1638.      */
  1639.      $contentTemp $content;
  1640.      sq_defang($contentTemp);
  1641.      sq_unspace($contentTemp);
  1642.  
  1643.     /**
  1644.      * Fix stupid css declarations which lead to vulnerabilities
  1645.      * in IE.
  1646.      */
  1647.     $match   Array('/\/\*.*\*\//',
  1648.                      '/expression/i',
  1649.                      '/behaviou*r/i',
  1650.                      '/binding/i',
  1651.                      '/include-source/i');
  1652.     $replace Array('''idiocy''idiocy''idiocy''idiocy');
  1653.     $contentNew preg_replace($match$replace$contentTemp);
  1654.     if ($contentNew !== $contentTemp{
  1655.         // insecure css declarations are used. From now on we don't care
  1656.         // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
  1657.         $content $contentNew;
  1658.     }
  1659.     return array($content$newpos);
  1660. }
  1661.  
  1662.  
  1663. /**
  1664.  * This function converts cid: url's into the ones that can be viewed in
  1665.  * the browser.
  1666.  *
  1667.  * @param  $message  the message object
  1668.  * @param  $id       the message id
  1669.  * @param  $cidurl   the cid: url.
  1670.  * @param  $mailbox  the message mailbox
  1671.  * @return           string with a http-friendly url
  1672.  */
  1673. function sq_cid2http($message$id$cidurl$mailbox){
  1674.     /**
  1675.      * Get rid of quotes.
  1676.      */
  1677.     $quotchar substr($cidurl01);
  1678.     if ($quotchar == '"' || $quotchar == "'"){
  1679.         $cidurl str_replace($quotchar""$cidurl);
  1680.     else {
  1681.         $quotchar '';
  1682.     }
  1683.     $cidurl substr(trim($cidurl)4);
  1684.  
  1685.     $match_str '/\{.*?\}\//';
  1686.     $str_rep '';
  1687.     $cidurl preg_replace($match_str$str_rep$cidurl);
  1688.  
  1689.     $linkurl find_ent_id($cidurl$message);
  1690.     /* in case of non-safe cid links $httpurl should be replaced by a sort of
  1691.        unsafe link image */
  1692.     $httpurl '';
  1693.  
  1694.     /**
  1695.      * This is part of a fix for Outlook Express 6.x generating
  1696.      * cid URLs without creating content-id headers. These images are
  1697.      * not part of the multipart/related html mail. The html contains
  1698.      * <img src="cid:{some_id}/image_filename.ext"> references to
  1699.      * attached images with as goal to render them inline although
  1700.      * the attachment disposition property is not inline.
  1701.      */
  1702.  
  1703.     if (empty($linkurl)) {
  1704.         if (preg_match('/{.*}\//'$cidurl)) {
  1705.             $cidurl preg_replace('/{.*}\//',''$cidurl);
  1706.             if (!empty($cidurl)) {
  1707.                 $linkurl find_ent_id($cidurl$message);
  1708.             }
  1709.         }
  1710.     }
  1711.  
  1712.     if (!empty($linkurl)) {
  1713.         $httpurl $quotchar SM_PATH 'src/download.php?absolute_dl=true&amp;' .
  1714.             "passed_id=$id&amp;mailbox=urlencode($mailbox.
  1715.             '&amp;ent_id=' $linkurl $quotchar;
  1716.     else {
  1717.         /**
  1718.          * If we couldn't generate a proper img url, drop in a blank image
  1719.          * instead of sending back empty, otherwise it causes unusual behaviour
  1720.          */
  1721.         $httpurl $quotchar SM_PATH 'images/blank.png' $quotchar;
  1722.     }
  1723.  
  1724.     return $httpurl;
  1725. }
  1726.  
  1727. /**
  1728.  * This function changes the <body> tag into a <div> tag since we
  1729.  * can't really have a body-within-body.
  1730.  *
  1731.  * @param  $attary   an array of attributes and values of <body>
  1732.  * @param  $mailbox  mailbox we're currently reading (for cid2http)
  1733.  * @param  $message  current message (for cid2http)
  1734.  * @param  $id       current message id (for cid2http)
  1735.  * @return           modified array of attributes to be set for <div>
  1736.  */
  1737. function sq_body2div($attary$mailbox$message$id){
  1738.     $me 'sq_body2div';
  1739.     $divattary Array('class' => "'bodyclass'");
  1740.     $bgcolor '#ffffff';
  1741.     $text '#000000';
  1742.     $styledef '';
  1743.     if (is_array($attary&& sizeof($attary0){
  1744.         foreach ($attary as $attname=>$attvalue){
  1745.             $quotchar substr($attvalue01);
  1746.             $attvalue str_replace($quotchar""$attvalue);
  1747.             switch ($attname){
  1748.                 case 'background':
  1749.                     $attvalue sq_cid2http($message$id$attvalue$mailbox);
  1750.                     $styledef .= "background-imageurl('$attvalue'); ";
  1751.                     break;
  1752.                 case 'bgcolor':
  1753.                     $styledef .= "background-color$attvalue";
  1754.                     break;
  1755.                 case 'text':
  1756.                     $styledef .= "color$attvalue";
  1757.                     break;
  1758.             }
  1759.         }
  1760.         if (strlen($styledef0){
  1761.             $divattary{"style""\"$styledef\"";
  1762.         }
  1763.     }
  1764.     return $divattary;
  1765. }
  1766.  
  1767. /**
  1768.  * This is the main function and the one you should actually be calling.
  1769.  * There are several variables you should be aware of an which need
  1770.  * special description.
  1771.  *
  1772.  * Since the description is quite lengthy, see it here:
  1773.  * http://linux.duke.edu/projects/mini/htmlfilter/
  1774.  *
  1775.  * @param $body                 the string with HTML you wish to filter
  1776.  * @param $tag_list             see description above
  1777.  * @param $rm_tags_with_content see description above
  1778.  * @param $self_closing_tags    see description above
  1779.  * @param $force_tag_closing    see description above
  1780.  * @param $rm_attnames          see description above
  1781.  * @param $bad_attvals          see description above
  1782.  * @param $add_attr_to_tag      see description above
  1783.  * @param $message              message object
  1784.  * @param $id                   message id
  1785.  * @return                      sanitized html safe to show on your pages.
  1786.  */
  1787. function sq_sanitize($body,
  1788.                      $tag_list,
  1789.                      $rm_tags_with_content,
  1790.                      $self_closing_tags,
  1791.                      $force_tag_closing,
  1792.                      $rm_attnames,
  1793.                      $bad_attvals,
  1794.                      $add_attr_to_tag,
  1795.                      $message,
  1796.                      $id,
  1797.                      $mailbox
  1798.                      ){
  1799.     $me 'sq_sanitize';
  1800.     $rm_tags array_shift($tag_list);
  1801.     /**
  1802.      * Normalize rm_tags and rm_tags_with_content.
  1803.      */
  1804.     @array_walk($tag_list'sq_casenormalize');
  1805.     @array_walk($rm_tags_with_content'sq_casenormalize');
  1806.     @array_walk($self_closing_tags'sq_casenormalize');
  1807.     /**
  1808.      * See if tag_list is of tags to remove or tags to allow.
  1809.      * false  means remove these tags
  1810.      * true   means allow these tags
  1811.      */
  1812.     $curpos 0;
  1813.     $open_tags Array();
  1814.     $trusted "\n<!-- begin sanitized html -->\n";
  1815.     $skip_content false;
  1816.     /**
  1817.      * Take care of netscape's stupid javascript entities like
  1818.      * &{alert('boo')};
  1819.      */
  1820.     $body preg_replace("/&(\{.*?\};)/si""&amp;\\1"$body);
  1821.  
  1822.     while (($curtag sq_getnxtag($body$curpos)) != FALSE){
  1823.         list($tagname$attary$tagtype$lt$gt$curtag;
  1824.         $free_content substr($body$curpos$lt-$curpos);
  1825.         /**
  1826.          * Take care of <style>
  1827.          */
  1828.         if ($tagname == "style" && $tagtype == 1){
  1829.             list($free_content$curpos=
  1830.                 sq_fixstyle($body$gt+1$message$id$mailbox);
  1831.             if ($free_content != FALSE){
  1832.                 $trusted .= sq_tagprint($tagname$attary$tagtype);
  1833.                 $trusted .= $free_content;
  1834.                 $trusted .= sq_tagprint($tagnamefalse2);
  1835.             }
  1836.             continue;
  1837.         }
  1838.         if ($skip_content == false){
  1839.             $trusted .= $free_content;
  1840.         }
  1841.         if ($tagname != FALSE){
  1842.             if ($tagtype == 2){
  1843.                 if ($skip_content == $tagname){
  1844.                     /**
  1845.                      * Got to the end of tag we needed to remove.
  1846.                      */
  1847.                     $tagname false;
  1848.                     $skip_content false;
  1849.                 else {
  1850.                     if ($skip_content == false){
  1851.                         if ($tagname == "body"){
  1852.                             $tagname "div";
  1853.                         }
  1854.                         if (isset($open_tags{$tagname}&&
  1855.                                 $open_tags{$tagname0){
  1856.                             $open_tags{$tagname}--;
  1857.                         else {
  1858.                             $tagname false;
  1859.                         }
  1860.                     }
  1861.                 }
  1862.             else {
  1863.                 /**
  1864.                  * $rm_tags_with_content
  1865.                  */
  1866.                 if ($skip_content == false){
  1867.                     /**
  1868.                      * See if this is a self-closing type and change
  1869.                      * tagtype appropriately.
  1870.                      */
  1871.                     if ($tagtype == 1
  1872.                             && in_array($tagname$self_closing_tags)){
  1873.                         $tagtype 3;
  1874.                     }
  1875.                     /**
  1876.                      * See if we should skip this tag and any content
  1877.                      * inside it.
  1878.                      */
  1879.                     if ($tagtype == &&
  1880.                             in_array($tagname$rm_tags_with_content)){
  1881.                         $skip_content $tagname;
  1882.                     else {
  1883.                         if (($rm_tags == false
  1884.                                     && in_array($tagname$tag_list)) ||
  1885.                                 ($rm_tags == true &&
  1886.                                  !in_array($tagname$tag_list))){
  1887.                             $tagname false;
  1888.                         else {
  1889.                             /**
  1890.                              * Convert body into div.
  1891.                              */
  1892.                             if ($tagname == "body"){
  1893.                                 $tagname "div";
  1894.                                 $attary sq_body2div($attary$mailbox,
  1895.                                         $message$id);
  1896.                             }
  1897.                             if ($tagtype == 1){
  1898.                                 if (isset($open_tags{$tagname})){
  1899.                                     $open_tags{$tagname}++;
  1900.                                 else {
  1901.                                     $open_tags{$tagname}=1;
  1902.                                 }
  1903.                             }
  1904.                             /**
  1905.                              * This is where we run other checks.
  1906.                              */
  1907.                             if (is_array($attary&& sizeof($attary0){
  1908.                                 $attary sq_fixatts($tagname,
  1909.                                                      $attary,
  1910.                                                      $rm_attnames,
  1911.                                                      $bad_attvals,
  1912.                                                      $add_attr_to_tag,
  1913.                                                      $message,
  1914.                                                      $id,
  1915.                                                      $mailbox
  1916.                                                      );
  1917.                             }
  1918.                         }
  1919.                     }
  1920.                 }
  1921.             }
  1922.             if ($tagname != false && $skip_content == false){
  1923.                 $trusted .= sq_tagprint($tagname$attary$tagtype);
  1924.             }
  1925.         }
  1926.         $curpos $gt+1;
  1927.     }
  1928.     $trusted .= substr($body$curposstrlen($body)-$curpos);
  1929.     if ($force_tag_closing == true){
  1930.         foreach ($open_tags as $tagname=>$opentimes){
  1931.             while ($opentimes 0){
  1932.                 $trusted .= '</' $tagname '>';
  1933.                 $opentimes--;
  1934.             }
  1935.         }
  1936.         $trusted .= "\n";
  1937.     }
  1938.     $trusted .= "<!-- end sanitized html -->\n";
  1939.     return $trusted;
  1940. }
  1941.  
  1942. /**
  1943.  * This is a wrapper function to call html sanitizing routines.
  1944.  *
  1945.  * @param  $body  the body of the message
  1946.  * @param  $id    the id of the message
  1947.  * @return        string with html safe to display in the browser.
  1948.  */
  1949. function magicHTML($body$id$message$mailbox 'INBOX'{
  1950.     global $attachment_common_show_images$view_unsafe_images,
  1951.            $has_unsafe_images;
  1952.     /**
  1953.      * Don't display attached images in HTML mode.
  1954.      */
  1955.     $attachment_common_show_images false;
  1956.     $tag_list Array(
  1957.             false,
  1958.             "object",
  1959.             "meta",
  1960.             "html",
  1961.             "head",
  1962.             "base",
  1963.             "link",
  1964.             "frame",
  1965.             "iframe",
  1966.             "plaintext",
  1967.             "marquee"
  1968.             );
  1969.  
  1970.     $rm_tags_with_content Array(
  1971.             "script",
  1972.             "applet",
  1973.             "embed",
  1974.             "title",
  1975.             "frameset",
  1976.             "xmp",
  1977.             "xml"
  1978.             );
  1979.  
  1980.     $self_closing_tags =  Array(
  1981.             "img",
  1982.             "br",
  1983.             "hr",
  1984.             "input",
  1985.             "outbind"
  1986.             );
  1987.  
  1988.     $force_tag_closing true;
  1989.  
  1990.     $rm_attnames Array(
  1991.             "/.*/" =>
  1992.             Array(
  1993.                 "/target/i",
  1994.                 "/^on.*/i",
  1995.                 "/^dynsrc/i",
  1996.                 "/^data.*/i",
  1997.                 "/^lowsrc.*/i"
  1998.                 )
  1999.             );
  2000.  
  2001.     $secremoveimg "../images/" _("sec_remove_eng.png");
  2002.     $bad_attvals Array(
  2003.             "/.*/" =>
  2004.             Array(
  2005.                 "/^src|background/i" =>
  2006.                 Array(
  2007.                     Array(
  2008.                         "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  2009.                         "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2010.                         "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2011.                         ),
  2012.                     Array(
  2013.                         "\\1$secremoveimg\\2",
  2014.                         "\\1$secremoveimg\\2",
  2015.                         "\\1$secremoveimg\\2"
  2016.                         )
  2017.                     ),
  2018.                 "/^href|action/i" =>
  2019.                 Array(
  2020.                     Array(
  2021.                         "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
  2022.                         "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
  2023.                         "/^([\'\"])\s*about\s*:.*([\'\"])/si"
  2024.                         ),
  2025.                     Array(
  2026.                         "\\1#\\1",
  2027.                         "\\1#\\1",
  2028.                         "\\1#\\1"
  2029.                         )
  2030.                     ),
  2031.         "/^style/i" =>
  2032.             Array(
  2033.                 Array(
  2034.                     "/\/\*.*\*\//",
  2035.                     "/expression/i",
  2036.                     "/binding/i",
  2037.                     "/behaviou*r/i",
  2038.                     "/include-source/i",
  2039.                     "/position\s*:\s*absolute/i",
  2040.                     "/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",
  2041.                     "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
  2042.                     "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
  2043.                     "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
  2044.                     "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
  2045.                     ),
  2046.                 Array(
  2047.                     "",
  2048.                     "idiocy",
  2049.                     "idiocy",
  2050.                     "idiocy",
  2051.                     "idiocy",
  2052.                     "",
  2053.                     "url",
  2054.                     "url(\\1#\\1)",
  2055.                     "url(\\1#\\1)",
  2056.                     "url(\\1#\\1)",
  2057.                     "\\1:url(\\2#\\3)"
  2058.                     )
  2059.                 )
  2060.             )
  2061.         );
  2062.     if!sqgetGlobalVar('view_unsafe_images'$view_unsafe_imagesSQ_GET) ) {
  2063.         $view_unsafe_images false;
  2064.     }
  2065.     if (!$view_unsafe_images){
  2066.         /**
  2067.          * Remove any references to http/https if view_unsafe_images set
  2068.          * to false.
  2069.          */
  2070.         array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
  2071.                 '/^([\'\"])\s*https*:.*([\'\"])/si');
  2072.         array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
  2073.                 "\\1$secremoveimg\\1");
  2074.         array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
  2075.                 '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
  2076.         array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
  2077.                 "url(\\1$secremoveimg\\1)");
  2078.     }
  2079.  
  2080.     $add_attr_to_tag Array(
  2081.             "/^a$/i=>
  2082.             Array('target'=>'"_blank"',
  2083.                 'title'=>'"'._("This external link will open in a new window").'"'
  2084.                 )
  2085.             );
  2086.     $trusted sq_sanitize($body,
  2087.                            $tag_list,
  2088.                            $rm_tags_with_content,
  2089.                            $self_closing_tags,
  2090.                            $force_tag_closing,
  2091.                            $rm_attnames,
  2092.                            $bad_attvals,
  2093.                            $add_attr_to_tag,
  2094.                            $message,
  2095.                            $id,
  2096.                            $mailbox
  2097.                            );
  2098.     if (preg_match("|$secremoveimg|i"$trusted)){
  2099.         $has_unsafe_images true;
  2100.     }
  2101.     return $trusted;
  2102. }
  2103.  
  2104. /**
  2105.  * function SendDownloadHeaders - send file to the browser
  2106.  *
  2107.  * Original Source: SM core src/download.php
  2108.  * moved here to make it available to other code, and separate
  2109.  * front end from back end functionality.
  2110.  *
  2111.  * @param string $type0 first half of mime type
  2112.  * @param string $type1 second half of mime type
  2113.  * @param string $filename filename to tell the browser for downloaded file
  2114.  * @param boolean $force whether to force the download dialog to pop
  2115.  * @param optional integer $filesize send the Content-Header and length to the browser
  2116.  * @return void 
  2117.  */
  2118. function SendDownloadHeaders($type0$type1$filename$force$filesize=0{
  2119.     global $languages$squirrelmail_language;
  2120.     $isIE $isIE6plus false;
  2121.  
  2122.     sqgetGlobalVar('HTTP_USER_AGENT'$HTTP_USER_AGENTSQ_SERVER);
  2123.  
  2124.     if (strstr($HTTP_USER_AGENT'compatible; MSIE '!== false &&
  2125.             strstr($HTTP_USER_AGENT'Opera'=== false{
  2126.         $isIE true;
  2127.     }
  2128.  
  2129.     if (preg_match('/compatible; MSIE ([0-9]+)/'$HTTP_USER_AGENT$match&&
  2130.         ((int)$match[1]>= && strstr($HTTP_USER_AGENT'Opera'=== false{
  2131.         $isIE6plus true;
  2132.     }
  2133.  
  2134.     if (isset($languages[$squirrelmail_language]['XTRA_CODE']&&
  2135.             function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  2136.         $filename =
  2137.             $languages[$squirrelmail_language]['XTRA_CODE']('downloadfilename'$filename$HTTP_USER_AGENT);
  2138.     else {
  2139.         $filename ereg_replace('[\\/:\*\?"<>\|;]''_'str_replace('&#32;'' '$filename));
  2140.     }
  2141.  
  2142.     // A Pox on Microsoft and it's Internet Explorer!
  2143.     //
  2144.     // IE has lots of bugs with file downloads.
  2145.     // It also has problems with SSL.  Both of these cause problems
  2146.     // for us in this function.
  2147.     //
  2148.     // See this article on Cache Control headers and SSL
  2149.     // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
  2150.     //
  2151.     // The best thing you can do for IE is to upgrade to the latest
  2152.     // version
  2153.     //set all the Cache Control Headers for IE
  2154.     if ($isIE{
  2155.         $filename=rawurlencode($filename);
  2156.         header ("Pragma: public");
  2157.         header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate")// HTTP/1.1
  2158.         header ("Cache-Control: post-check=0, pre-check=0"false);
  2159.         header ("Cache-Control: private");
  2160.  
  2161.         //set the inline header for IE, we'll add the attachment header later if we need it
  2162.         header ("Content-Dispositioninlinefilename=$filename");
  2163.     }
  2164.  
  2165.     if (!$force{
  2166.         // Try to show in browser window
  2167.         header ("Content-Dispositioninlinefilename=\"$filename\"");
  2168.         header ("Content-Type$type0/$type1name=\"$filename\"");
  2169.     else {
  2170.         // Try to pop up the "save as" box
  2171.  
  2172.         // IE makes this hard.  It pops up 2 save boxes, or none.
  2173.         // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
  2174.         // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
  2175.         // But, according to Microsoft, it is "RFC compliant but doesn't
  2176.         // take into account some deviations that allowed within the
  2177.         // specification."  Doesn't that mean RFC non-compliant?
  2178.         // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
  2179.  
  2180.         // all browsers need the application/octet-stream header for this
  2181.         header ("Content-Typeapplication/octet-streamname=\"$filename\"");
  2182.  
  2183.         // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
  2184.         // Do not have quotes around filename, but that applied to
  2185.         // "attachment"... does it apply to inline too?
  2186.         header ("Content-Dispositionattachmentfilename=\"$filename\"");
  2187.  
  2188.         if ($isIE && !$isIE6plus{
  2189.             // This combination seems to work mostly.  IE 5.5 SP 1 has
  2190.             // known issues (see the Microsoft Knowledge Base)
  2191.  
  2192.             // This works for most types, but doesn't work with Word files
  2193.             header ("Content-Typeapplication/downloadname=\"$filename\"");
  2194.  
  2195.             // These are spares, just in case.  :-)
  2196.             //header("Content-Type: $type0/$type1; name=\"$filename\"");
  2197.             //header("Content-Type: application/x-msdownload; name=\"$filename\"");
  2198.             //header("Content-Type: application/octet-stream; name=\"$filename\"");
  2199.         else {
  2200.             // another application/octet-stream forces download for Netscape
  2201.             header ("Content-Typeapplication/octet-streamname=\"$filename\"");
  2202.         }
  2203.     }
  2204.  
  2205.     //send the content-length header if the calling function provides it
  2206.     if ($filesize 0{
  2207.         header("Content-Length$filesize");
  2208.     }
  2209.  
  2210. }  // end fn SendDownloadHeaders
  2211.  
  2212. ?>

Documentation generated on Sat, 07 Oct 2006 16:32:35 +0300 by phpDocumentor 1.3.0RC6