We're living in 2004 now... perl is your friend for these kinds of things :)
[squirrelmail.git] / functions / mime.php
index 1b48a431daeea9b84806d05c7acd4e0aaea33fe5..7433d7c8b49a3c3c7f5e4b14d777e04d72582771 100644 (file)
@@ -3,7 +3,7 @@
 /**
  * mime.php
  *
- * Copyright (c) 1999-2003 The SquirrelMail Project Team
+ * Copyright (c) 1999-2004 The SquirrelMail Project Team
  * Licensed under the GNU GPL. For full terms see the file COPYING.
  *
  * This contains the functions necessary to detect and decode MIME
@@ -23,7 +23,7 @@ require_once(SM_PATH . 'functions/attachment_common.php');
 
 /**
  * Get the MIME structure
- * 
+ *
  * This function gets the structure of a message and stores it in the "message" class.
  * It will return this object for use with all relevant header information and
  * fully parsed into the standard "message" object format.
@@ -393,12 +393,14 @@ function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $ma
             translateText($body, $wrap_at,
                           $body_message->header->getParameter('charset'));
         }
-        $link = 'read_body.php?passed_id=' . $id . '&ent_id='.$ent_num.
+        $link = 'passed_id=' . $id . '&ent_id='.$ent_num.
                 '&mailbox=' . $urlmailbox .'&sort=' . $sort .
                 '&startMessage=' . $startMessage . '&show_more=0';
         if (isset($passed_ent_id)) {
             $link .= '&passed_ent_id='.$passed_ent_id;
         }
+        $body .= '<center><small><a href="download.php?absolute_dl=true&amp;' . 
+                 $link . '">' . _("Download this as a file") .  '</a>';
         if ($view_unsafe_images) {
             $text = _("Hide Unsafe Images");
         } else {
@@ -409,8 +411,10 @@ function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $ma
                 $text = '';
             }
         }
-        $body .= '<center><small><a href="'.$link.'">'.$text.
-                 '</a></small></center><br>' . "\n";
+        if($text != '') {
+            $body .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
+        }
+        $body .= '</small></center><br>' . "\n";
     }
     return $body;
 }
@@ -581,12 +585,20 @@ function decodeBody($body, $encoding) {
     return $body;
 }
 
-/*
+/**
+ * Decodes headers
+ *
  * This functions decode strings that is encoded according to
  * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
  * Patched by Christian Schmidt <christian@ostenfeld.dk>  23/03/2002
+ *
+ * @param string $string header string that has to be made readable
+ * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
+ * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
+ * @param boolean $decide decide if string can be utfencoded. defaults to false
+ * @return string decoded header string
  */
-function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
+function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
     global $languages, $squirrelmail_language;
     if (is_array($string)) {
         $string = implode("\n", $string);
@@ -619,7 +631,7 @@ function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
             /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
             if ($iLastMatch !== $j) {
                 if ($htmlsave) {
-                    $ret .= '&nbsp;';
+                    $ret .= '&#32;';
                 } else {
                     $ret .= ' ';
                 }
@@ -638,6 +650,13 @@ function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
                 $replace = str_replace('_', ' ', $res[4]);
                 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
                                     $replace);
+               /* decide about valid decoding */
+               if ($decide && is_conversion_safe($res[2])) {
+                 $utfencode=true;
+                 $can_be_decoded=true;
+               } else {
+                 $can_be_decoded=false;
+               }
                 /* Only encode into entities by default. Some places
                  * don't need the encoding, like the compose form.
                  */
@@ -656,30 +675,42 @@ function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
             $chunk = $res[5];
             $encoded = true;
         }
-
-        if (!$encoded && $htmlsave) {
-            $ret .= htmlspecialchars($chunk);
-        } else {
-            $ret .= $chunk;
-        }
-
         if (!$encoded) {
             if ($htmlsave) {
-                $ret .= '&nbsp;';
+                $ret .= '&#32;';
             } else {
                 $ret .= ' ';
             }
         }
+
+        if (!$encoded && $htmlsave) {
+            $ret .= htmlspecialchars($chunk);
+        } else {
+            $ret .= $chunk;
+        }
         ++$i;
     }
+    /* remove the first added space */
+    if ($ret) {
+        if ($htmlsave) {
+            $ret = substr($ret,5);
+        } else {
+            $ret = substr($ret,1);
+        }
+    }
 
     return $ret;
 }
 
-/*
+/**
+ * Encodes header as quoted-printable
+ *
  * Encode a string according to RFC 1522 for use in headers if it
  * contains 8-bit characters or anything that looks like it should
  * be encoded.
+ *
+ * @param string $string header string, that has to be encoded
+ * @return string quoted-printable encoded string
  */
 function encodeHeader ($string) {
     global $default_charset, $languages, $squirrelmail_language;
@@ -688,9 +719,10 @@ function encodeHeader ($string) {
         function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
         return  $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
     }
-    if (strtolower($default_charset) == 'iso-8859-1') {
-        $string = str_replace("\240",' ',$string);
-    }
+    // instead of removing nbsp here, we don't add it in decodeHeader
+    //    if (strtolower($default_charset) == 'iso-8859-1') {
+    //    $string = str_replace("\240",' ',$string);
+    //}
 
     // Encode only if the string contains 8-bit characters or =?
     $j = strlen($string);
@@ -846,6 +878,7 @@ function sq_unbackslash($attvalue){
     /**
      * Remove any backslashes. See if there are any first.
      */
+
     if (strstr($attvalue, '\\') !== false){
         $attvalue = stripslashes($attvalue);
     }
@@ -1278,13 +1311,14 @@ function sq_getnxtag($body, $offset){
  * @param  $attvalue A string to run entity check against.
  * @return           Translated value.
  */
+
 function sq_deent($attvalue){
     $me = 'sq_deent';
     /**
      * See if we have to run the checks first. All entities must start
      * with "&".
      */
-    if (strpos($attvalue, "&") === false){
+    if (strpos($attvalue, '&') === false){
         return $attvalue;
     }
     /**
@@ -1295,22 +1329,22 @@ function sq_deent($attvalue){
      * Leave &quot; in, as it can mess us up.
      */
     $trans = array_flip($trans);
-    unset($trans{"&quot;"});
+    unset($trans{'&quot;'});
     while (list($ent, $val) = each($trans)){
-        $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
+        $attvalue = preg_replace('/' . $ent . '*/si', $val, $attvalue);
     }
     /**
      * Now translate numbered entities from 1 to 255 if needed.
      */
-    if (strpos($attvalue, "#") !== false){
+    if (strpos($attvalue, '#') !== false){
         $omit = Array(34, 39);
-        for ($asc=1; $asc<256; $asc++){
+        for ($asc = 256; $asc >= 0; $asc--){
             if (!in_array($asc, $omit)){
                 $chr = chr($asc);
-                $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
-                                         $attvalue);
-                $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
-                                         "$chr\\1", $attvalue);
+                $octrule = '/\&#0*' . $asc . ';*/si';
+                $hexrule = '/\&#x0*' . dechex($asc) . ';*/si';
+                $attvalue = preg_replace($octrule, $chr, $attvalue);
+                $attvalue = preg_replace($hexrule, $chr, $attvalue);
             }
         }
     }
@@ -1360,6 +1394,12 @@ function sq_fixatts($tagname,
         $attvalue = sq_deent($attvalue);
         $attvalue = sq_unspace($attvalue);
 
+        /**
+         * Remove \r \n \t \0 " " "\\"
+         */
+        $attvalue = str_replace(Array("\r", "\n", "\t", "\0", " ", "\\"), 
+                        Array('', '','','','',''), $attvalue);
+
         /**
          * Now let's run checks on the attvalues.
          * I don't expect anyone to comprehend this. If you do,
@@ -1823,7 +1863,8 @@ function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
                                 "/include-source/i",
                                 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
                                 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
-                                "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
+                                "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
+                                "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
                                ),
                           Array(
                                 "idiocy",
@@ -1833,7 +1874,8 @@ function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
                                 "url(\\1#\\1)",
                                 "url(\\1#\\1)",
                                 "url(\\1#\\1)",
-                                "url(\\1#\\1)"
+                                "url(\\1#\\1)",
+                                "\\1:url(\\2#\\3)"
                                )
                           )
                 )
@@ -1891,9 +1933,10 @@ function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
  * @param string $type1 second half of mime type
  * @param string $filename filename to tell the browser for downloaded file
  * @param boolean $force whether to force the download dialog to pop
+ * @param integer $filesize optional, send the Content-Header and length to the browser
  * @return void
  */
- function SendDownloadHeaders($type0, $type1, $filename, $force) {
+ function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
      global $languages, $squirrelmail_language;
      $isIE = $isIE6 = 0;
 
@@ -1954,6 +1997,12 @@ function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
              header("Content-Type: application/octet-stream; name=\"$filename\"");
          }
      }
- }
+
+     //send the content-length header if the calling function provides it
+     if ($filesize > 0) {
+        header("Content-Length: $filesize");
+     }
+
+ }  // end fn SendDownlaodHeaders
 
 ?>