finally managed to solve the bad Junk after literal output from the
[squirrelmail.git] / functions / smtp.php
index 56ca93937e05ebbf324d5d3670a9cca2a1133f12..d6cff03768b056a66e2f58c136d9667f6310c6ae 100644 (file)
@@ -31,20 +31,6 @@ if (!$domain) {
     $domain = getenv('HOSTNAME');
 }
 
-/**
- * Return which separator we should be using.
- * \r\n for SMTP delivery, just \n for Sendmail.
- */
-function sqm_nrn(){
-    global $useSendmail;
-    if ($useSendmail){
-        return "\n";
-    } else {
-        return "\r\n";
-    }
-}
-
-
 /* Returns true only if this message is multipart */
 function isMultipart ($session) {
     global $attachments;
@@ -91,7 +77,6 @@ function expandAddrs ($array) {
     return $array;
 }
 
-
 /* looks up aliases in the addressbook and expands them to
  * the RFC 821 valid RCPT address. ie <user@example.com>
  * Adds @$domain if it wasn't in the address book and if it
@@ -124,11 +109,10 @@ function expandRcptAddrs ($array) {
 
 /* Attach the files that are due to be attached
  */
-function attachFiles ($fp, $session) {
-    global $attachments, $attachment_dir, $username;
+function attachFiles ($fp, $session, $rn="\r\n", $checkdot = false) {
+    global $attachments, $attachment_dir, $username, $languages, $squirrelmail_language;
 
     $length = 0;
-    $rn = sqm_nrn();
 
     $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
     if (isMultipart($session)) {
@@ -144,10 +128,16 @@ function attachFiles ($fp, $session) {
                 $header = '--' . mimeBoundary() . "$rn";
                 if ( isset($info['remotefilename']) 
                      && $info['remotefilename'] != '') {
+                    $remotefilename = $info['remotefilename'];
+                    if (isset($languages[$squirrelmail_language]['XTRA_CODE']) && 
+                      function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
+                        $remotefilename = 
+                            $languages[$squirrelmail_language]['XTRA_CODE']('encode', $remotefilename);
+                    }
                     $header .= "Content-Type: $filetype; name=\"" .
-                        $info['remotefilename'] . "\"$rn";
+                        encodeHeader($remotefilename) . "\"$rn";
                     $header .= "Content-Disposition: attachment; filename=\""
-                        . $info['remotefilename'] . "\"$rn";
+                        . encodeHeader($remotefilename) . "\"$rn";
                 } else {
                     $header .= "Content-Type: $filetype$rn";
                 }
@@ -162,34 +152,61 @@ function attachFiles ($fp, $session) {
                 $file = fopen ($filename, 'rb');
                 if (substr($filetype, 0, 5) == 'text/' ||
                     substr($filetype, 0, 8) == 'message/' ) {
-                    $header .= "$rn";
-                    fputs ($fp, $header);
+                    $header .= $rn;
+                    if ($fp) {
+                       fputs ($fp, $header);
+                   }
                     $length += strlen($header);
+
+                   if ($checkdot) {
+                       $checkdot_begin=true;
+                   } else {
+                       $checkdot_begin=false;
+                   }
+
                     while ($tmp = fgets($file, 4096)) {
                         $tmp = str_replace("\r\n", "\n", $tmp);
                         $tmp = str_replace("\r", "\n", $tmp);
                         if ($rn == "\r\n"){
                             $tmp = str_replace("\n", "\r\n", $tmp);
                         }
-                        /**
-                         * Check if the last line has newline ($rn) in it
-                         * and append if it doesn't.
-                         */
-                        if (feof($fp) && !strstr($tmp, "$rn")){
-                            $tmp .= "$rn";
+                       if ($tmp{0} == '.' && $checkdot_begin) {
+                           $tmp = '.' . $tmp;
+                       }
+                       if ($checkdot) {
+                           $tmp = str_replace("\n.","\n..",$tmp);
+                       }
+                       
+                       $tmp_length = strlen($tmp);
+                       if ($tmp_length && $tmp{$tmp_length-1} == "\n" && $checkdot) {
+                           $checkdot_begin = true;
+                       } else {
+                           $checkdot_begin = false;
+                       }
+                       
+                       
+                        if ($fp) {
+                            fputs($fp, $tmp);
+                        }
+                        $length += $tmp_length;
+                    }
+                    if (substr($tmp, $tmp_length - strlen($rn), strlen($rn)) != $rn) {
+                        if ($fp) {
+                            fputs($fp, $rn);
                         }
-                        fputs($fp, $tmp);
-                        $length += strlen($tmp);
+                       $length += strlen($rn);
                     }
+
+
                 } else {
                     $header .= "Content-Transfer-Encoding: base64" 
                         . "$rn" . "$rn";
-                    fputs ($fp, $header);
+                    if ($fp) fputs ($fp, $header);
                     $length += strlen($header);
                     while ($tmp = fread($file, 570)) {
                         $encoded = chunk_split(base64_encode($tmp));
                         $length += strlen($encoded);
-                        fputs ($fp, $encoded);
+                        if ($fp) fputs ($fp, $encoded);
                     }
                 }
                 fclose ($file);
@@ -202,7 +219,7 @@ function attachFiles ($fp, $session) {
 /* Delete files that are uploaded for attaching
  */
 function deleteAttachments($session) {
-    global $username, $attachments, $attachment_dir;
+    global $username, $attachments, $attachment_dir, $data_dir;
     $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
 
     $rem_attachments = array();
@@ -217,6 +234,7 @@ function deleteAttachments($session) {
         }
     }
     $attachments = $rem_attachments;
+    setPref($data_dir, $username, 'attachments', serialize($attachments));
 }
 
 /* Return a nice MIME-boundary
@@ -260,37 +278,30 @@ function timezone () {
 }
 
 /* Print all the needed RFC822 headers */
-function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session) {
+function write822Header ($fp, $t, $c, $b, $subject, $body, $more_headers, $session, $rn="\r\n") {
     global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
     global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
     global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
     global $REMOTE_HOST, $identity;
-    /**
-     * Get which delimiter we are going to use.
-     */
-    $rn = sqm_nrn();
+
     /* Storing the header to make sure the header is the same
      * everytime the header is printed.
      */
-    static $header, $headerlength;
+    static $header, $headerlength, $headerrn;
     
     if ($header == '') {
+               $headerrn = $rn;
         $to = expandAddrs(parseAddrs($t));
         $cc = expandAddrs(parseAddrs($c));
         $bcc = expandAddrs(parseAddrs($b));
         if (isset($identity) && $identity != 'default') {
             $reply_to = getPref($data_dir, $username, 'reply_to' . $identity);
             $from = getPref($data_dir, $username, 'full_name' . $identity);
-            $from_addr = getPref($data_dir, $username, 
-                                 'email_address' . $identity);
+            $from_addr = getFrom();
         } else {
             $reply_to = getPref($data_dir, $username, 'reply_to');
             $from = getPref($data_dir, $username, 'full_name');
-            $from_addr = getPref($data_dir, $username, 'email_address');
-        }
-        
-        if ($from_addr == '') {
-            $from_addr = $popuser.'@'.$domain;
+            $from_addr = getFrom();
         }
         
         $to_list = getLineOfAddrs($to);
@@ -362,6 +373,9 @@ function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session) {
         if(is_array($more_headers)) {
             reset($more_headers);
             while(list($h_name, $h_val) = each($more_headers)) {
+               if ($h_name == 'References') {
+                   $h_val = str_replace(' ', "$rn        ", $h_val);
+               }    
                 $header .= sprintf("%s: %s%s", $h_name, $h_val, $rn);
             }
         }
@@ -392,28 +406,40 @@ function write822Header ($fp, $t, $c, $b, $subject, $more_headers, $session) {
             $header .= mimeBoundary();
             $header .= "\"$rn";
         } else {
+            if (strtolower($default_charset) == 'iso-2022-jp') {
+                if (mb_detect_encoding($body) == 'ASCII') {
+                    $header .= 'Content-Type: text/plain; US-ASCII' . $rn;
+                    $header .= "Content-Transfer-Encoding: 8bit" . $rn;
+                } else {
+                    $header .= 'Content-Type: '.$contentType . $rn;
+                    $header .= "Content-Transfer-Encoding: 7bit" . $rn;
+                }
+            } else {
             $header .= 'Content-Type: ' . $contentType . $rn;
             $header .= "Content-Transfer-Encoding: 8bit" . $rn;
         }
+        }
         $header .= $rn; // One blank line to separate header and body
         
         $headerlength = strlen($header);
     }     
+
+       if ($headerrn != $rn) {
+               $header = str_replace($headerrn, $rn, $header);
+        $headerlength = strlen($header);
+               $headerrn = $rn;
+       }
     
     /* Write the header */
-    fputs ($fp, $header);
+    if ($fp) fputs ($fp, $header);
     
     return $headerlength;
 }
 
 /* Send the body
  */
-function writeBody ($fp, $passedBody, $session) {
+function writeBody ($fp, $passedBody, $session, $rn="\r\n", $checkdot = false) {
     global $default_charset;
-    /**
-     * Get delimiter.
-     */
-    $rn = sqm_nrn();
 
     $attachmentlength = 0;
     
@@ -427,27 +453,48 @@ function writeBody ($fp, $passedBody, $session) {
             $body .= "Content-Type: text/plain" . $rn;
         }
         
-        $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn;
-        $body .= $passedBody . $rn . $rn;
-        fputs ($fp, $body);
+        if (strtolower($default_charset) == 'iso-2022-jp') {
+            if (mb_detect_encoding($passedBody) == 'ASCII') {
+                $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
+                         $passedBody . $rn . $rn;
+            } else {
+                $body .= "Content-Transfer-Encoding: 7bit\r\n\r\n" .
+                         mb_convert_encoding($passedBody, 'JIS') . "\r\n\r\n";
+            }
+        } else {
+        $body .= "Content-Transfer-Encoding: 8bit" . $rn . $rn .
+                 $passedBody . $rn . $rn;
+        }
+        if ($fp) {
+           fputs ($fp, $body);
+       }
         
-        $attachmentlength = attachFiles($fp, $session);
+        $attachmentlength = attachFiles($fp, $session, $rn, $checkdot);
         
         if (!isset($postbody)) { 
             $postbody = ""; 
         }
         $postbody .= $rn . "--" . mimeBoundary() . "--" . $rn . $rn;
-        fputs ($fp, $postbody);
+        if ($fp) fputs ($fp, $postbody);
     } else {
-        $body = $passedBody . $rn;
-        fputs ($fp, $body);
+        if (strtolower($default_charset) == 'iso-2022-jp') {
+            $body = mb_convert_encoding($passedBody, 'JIS') . $rn;
+        } else {
+            $body = $passedBody . $rn;
+       }
+        if ($fp) {
+           fputs ($fp, $body);
+       }
         $postbody = $rn;
-        fputs ($fp, $postbody);
+        if ($fp) {
+           fputs ($fp, $postbody);
+       }
     }
 
     return (strlen($body) + strlen($postbody) + $attachmentlength);
 }
 
+
 /* Send mail using the sendmail command
  */
 function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
@@ -457,7 +504,7 @@ function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
      * spaces or other "weird" chars that would allow a user to
      * exploit the shell/pipe it is used in.
      */
-    $envelopefrom = "$popuser@$domain";
+    $envelopefrom = getFrom();
     $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
     $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
     $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);
@@ -472,12 +519,12 @@ function sendSendmail($t, $c, $b, $subject, $body, $more_headers, $session) {
         $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
     }
     
-    $headerlength = write822Header ($fp, $t, $c, $b, $subject, 
-                                    $more_headers, $session);
-    $bodylength = writeBody($fp, $body, $session);
+    $headerlength = write822Header ($fp, $t, $c, $b, $subject, $body,  
+                                    $more_headers, $session, "\n");
+    $bodylength = writeBody($fp, $body, $session, "\n", true);
     
     pclose($fp);
-    
+
     return ($headerlength + $bodylength);
 }
 
@@ -630,8 +677,8 @@ function sendSMTP($t, $c, $b, $subject, $body, $more_headers, $session) {
 
     /* Send the message */
     $headerlength = write822Header ($smtpConnection, $t, $c, $b, 
-                                    $subject, $more_headers, $session);
-    $bodylength = writeBody($smtpConnection, $body, $session);
+                                    $subject, $body, $more_headers, $session);
+    $bodylength = writeBody($smtpConnection, $body, $session,"\r\n", true);
     
     fputs($smtpConnection, ".\r\n"); /* end the DATA part */
     $tmp = fgets($smtpConnection, 1024);
@@ -759,14 +806,11 @@ function errorCheck($line, $smtpConnection, $verbose = false) {
 /* create new reference header per rfc2822 */
 
 function calculate_references($refs, $inreplyto, $old_reply_to) {
-    /**
-     * Get the delimiter.
-     */
-    $rn = sqm_nrn();
+
     $refer = "";
     for ($i=1;$i<count($refs[0]);$i++) {
         if (!empty($refs[0][$i])) {
-            if (preg_match("/^References:(.+)$/", $refs[0][$i], $regs)) {
+            if (preg_match("/^References:(.+)$/UAi", $refs[0][$i], $regs)) {
                 $refer = trim($regs[1]);
             }
             else {   
@@ -774,6 +818,14 @@ function calculate_references($refs, $inreplyto, $old_reply_to) {
             }
         }
     }
+    $refer_a = explode(' ', $refer);
+    $refer = '';
+    foreach ($refer_a as $ref) {
+       $ref = trim($ref);
+       if ($ref && $ref{0} == '<' && $ref{(strlen($ref)-1)} == '>') {
+          $refer .= $ref . ' ';
+       }
+    }
     $refer = trim($refer);
     if (strlen($refer) > 2) {
         $refer .= ' ' . $inreplyto;
@@ -787,7 +839,6 @@ function calculate_references($refs, $inreplyto, $old_reply_to) {
         }                        
     }
     trim($refer);
-    $refer = str_replace(' ', "$rn        ", $refer);
     return $refer;
 }
 
@@ -796,12 +847,8 @@ function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
     global $useSendmail, $msg_id, $is_reply, $mailbox, $onetimepad,
         $data_dir, $username, $domain, $key, $version, $sent_folder, 
         $imapServerAddress, $imapPort, $default_use_priority, $more_headers, 
-        $request_mdn, $request_dr;
+        $request_mdn, $request_dr, $uid_support;
 
-    /**
-     * Get the delimiter.
-     */
-    $rn = sqm_nrn();
     $more_headers = Array();
     
     do_hook('smtp_send');
@@ -811,22 +858,38 @@ function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
 
     if (isset($reply_id) && $reply_id) {
         sqimap_mailbox_select ($imap_stream, $mailbox);
-        sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');
+        sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered', true);
 
         /* Insert In-Reply-To and References headers if the
          * message-id of the message we reply to is set (longer than "<>")
          * The References header should really be the old Referenced header
          * with the message ID appended, and now it is (jmunro)
          */
-        $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
-        if(strlen($hdr->message_id) > 2) {
+       $sid = sqimap_session_id($uid_support); 
+       $query = "$sid FETCH $reply_id (BODY.PEEK[HEADER.FIELDS (Message-Id In-Reply-To)])\r\n";
+       fputs ($imap_stream, $query);
+       $read = sqimap_read_data($imap_stream, $sid, true, $response, $message);
+       $message_id = '';
+       $in_reply_to = '';
+
+       foreach ($read as $r) {
+               if (preg_match("/^message-id:(.*)/iA", $r, $regs)) {
+                   $message_id = trim($regs[1]);
+               }
+               if (preg_match("/^in-reply-to:(.*)/iA", $r, $regs)) {
+                   $in_reply_to = trim($regs[1]);
+               }
+       }
+
+        if(strlen($message_id) > 2) {
             $refs = get_reference_header ($imap_stream, $reply_id);
-            $inreplyto = $hdr->message_id;
-            $old_reply_to = $hdr->inrepto;
+            $inreplyto = $message_id;
+            $old_reply_to = $in_reply_to;
             $refer = calculate_references ($refs, $inreplyto, $old_reply_to);
             $more_headers['In-Reply-To'] = $inreplyto;
             $more_headers['References']  = $refer;
         }
+
     }
     if ($default_use_priority) {
         $more_headers = array_merge($more_headers, createPriorityHeaders($prio));
@@ -842,38 +905,42 @@ function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
     if ( $requestRecipt > 0) {
         $more_headers = array_merge($more_headers, createReceiptHeaders($requestRecipt));
     }
-
-    /* In order to remove the problem of users not able to create
-     * messages with "." on a blank line, RFC821 has made provision
-     * in section 4.5.2 (Transparency).
-     */
-    $body = ereg_replace("\n\\.", "\n..", $body);
-    $body = ereg_replace("^\\.", "..", $body);
-
-    /* this is to catch all plain \n instances and
-     * replace them with \r\n.  All newlines were converted
-     * into just \n inside the compose.php file.
-     * But only if delimiter is, in fact, \r\n.
-     */
-    if ($rn == "\r\n"){
-        $body = ereg_replace("\n", "\r\n", $body);
-    }
-    
     if ($MDN) {
         $more_headers["Content-Type"] = "multipart/report; ".
             "report-type=disposition-notification;";
     }
-
+    $imap_body = $body; 
     if ($useSendmail) {
-        $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers, 
+        /* In order to remove the problem of users not able to create
+         * messages with "." on a blank line, RFC821 has made provision
+         * in section 4.5.2 (Transparency).
+         */
+        if (($body && $body{0} == '.')) {
+            $body = '.' . $body;
+        }
+        $body = str_replace("\n.","\n..",$body);
+         $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers, 
                                $session);
     } else {
+       /* In order to remove the problem of users not able to create
+        * messages with "." on a blank line, RFC821 has made provision
+        * in section 4.5.2 (Transparency).
+        */
+       if (($body && $body{0} == '.')) {
+           $body = '.' . $body;
+       }
+       $body = str_replace("\n.","\n..",$body);
         $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers, 
                            $session);
     }
     if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
+        $body = $imap_body;
+        $body = ereg_replace("\n", "\r\n", $body);
+       $headerlength = write822Header (false, $t, $c, $b, $subject, $body, $more_headers, $session, "\r\n");
+       $bodylength = writeBody(false, $body, $session, "\r\n");
+       $length = $headerlength + $bodylength;
         sqimap_append ($imap_stream, $sent_folder, $length);
-        write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers, 
+        write822Header ($imap_stream, $t, $c, $b, $subject, $body, $more_headers, 
                         $session);
         writeBody ($imap_stream, $body, $session);
         sqimap_append_done ($imap_stream);
@@ -885,7 +952,6 @@ function sendMessage($t, $c, $b, $subject, $body, $reply_id, $MDN,
     if ($length) {
         ClearAttachments($session);
     }
-
     return $length;
 }
 
@@ -949,5 +1015,24 @@ function createReceiptHeaders($receipt) {
     return $receipt_headers;
 }
 
+/* Figure out what the 'From:' address is
+ */
+
+function getFrom() {
+    global $username, $popuser, $domain, $data_dir, $identity;
+    if (isset($identity) && $identity != 'default') {
+        $from_addr = getPref($data_dir, $username, 
+                             'email_address' . $identity);
+    }
+    else {
+        $from_addr = getPref($data_dir, $username, 'email_address');
+    }
+    
+    if (!$from_addr) {
+        $from_addr = "$popuser@$domain";
+    }
+    return $from_addr;
+}
+
 
 ?>