From 14f4633b0bf3b60047a169b73f16b33372d5378c Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Wed, 04 Mar 2015 12:32:49 -0500
Subject: [PATCH] Remove redundant encoding of message subject with mb_encode_mimeheader() (#1490295)

---
 program/steps/mail/sendmail.inc |  619 ++++++++++++++++++++++++++++++--------------------------
 1 files changed, 331 insertions(+), 288 deletions(-)

diff --git a/program/steps/mail/sendmail.inc b/program/steps/mail/sendmail.inc
index a0c55d2..5326d64 100644
--- a/program/steps/mail/sendmail.inc
+++ b/program/steps/mail/sendmail.inc
@@ -24,7 +24,8 @@
 $OUTPUT->reset();
 $OUTPUT->framed = TRUE;
 
-$savedraft      = !empty($_POST['_draft']) ? true : false;
+$saveonly       = !empty($_GET['_saveonly']);
+$savedraft      = !empty($_POST['_draft']) && !$saveonly;
 $sendmail_delay = (int) $RCMAIL->config->get('sendmail_delay');
 $drafts_mbox    = $RCMAIL->config->get('drafts_mbox');
 
@@ -60,236 +61,6 @@
 }
 
 
-/****** message sending functions ********/
-
-// encrypt parts of the header
-function rcmail_encrypt_header($what)
-{
-    global $RCMAIL;
-
-    if (!$RCMAIL->config->get('http_received_header_encrypt')) {
-        return $what;
-    }
-
-    return $RCMAIL->encrypt($what);
-}
-
-// get identity record
-function rcmail_get_identity($id)
-{
-    global $RCMAIL, $message_charset;
-
-    if ($sql_arr = $RCMAIL->user->get_identity($id)) {
-        $out = $sql_arr;
-
-        if ($message_charset != RCUBE_CHARSET) {
-            foreach ($out as $k => $v) {
-                $out[$k] = rcube_charset::convert($v, RCUBE_CHARSET, $message_charset);
-            }
-        }
-
-        $out['mailto'] = $sql_arr['email'];
-        $out['string'] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
-
-        return $out;
-    }
-
-    return false;
-}
-
-/**
- * go from this:
- * <img src="http[s]://.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
- *
- * to this:
- *
- * <img src="/path/on/server/.../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
- */
-function rcmail_fix_emoticon_paths($mime_message)
-{
-    global $RCMAIL;
-
-    $body = $mime_message->getHTMLBody();
-
-    // remove any null-byte characters before parsing
-    $body = preg_replace('/\x00/', '', $body);
-
-    $searchstr = 'program/js/tiny_mce/plugins/emotions/img/';
-    $offset = 0;
-
-    // keep track of added images, so they're only added once
-    $included_images = array();
-
-    if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
-        foreach ($matches[1] as $m) {
-            // find emoticon image tags
-            if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
-                $image_name = $imatches[1];
-
-                // sanitize image name so resulting attachment doesn't leave images dir
-                $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
-                $img_file   = INSTALL_PATH . '/' . $searchstr . $image_name;
-
-                if (! in_array($image_name, $included_images)) {
-                    // add the image to the MIME message
-                    if (!$mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name)) {
-                        $RCMAIL->output->show_message("emoticonerror", 'error');
-                    }
-
-                    array_push($included_images, $image_name);
-                }
-
-                $body    = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
-                $offset += strlen($img_file) - strlen($m[0]);
-            }
-        }
-    }
-
-    $mime_message->setHTMLBody($body);
-}
-
-/**
- * Extract image attachments from HTML content (data URIs)
- */
-function rcmail_extract_inline_images($mime_message, $from)
-{
-    $body   = $mime_message->getHTMLBody();
-    $offset = 0;
-    $list   = array();
-    $regexp = '# src=[\'"](data:(image/[a-z]+);base64,([a-z0-9+/=\r\n]+))([\'"])#i';
-
-    // get domain for the Content-ID, must be the same as in Mail_Mime::get()
-    if (preg_match('#@([0-9a-zA-Z\-\.]+)#', $from, $matches)) {
-        $domain = $matches[1];
-    } else {
-        $domain = 'localhost';
-    }
-
-    if (preg_match_all($regexp, $body, $matches, PREG_OFFSET_CAPTURE)) {
-        foreach ($matches[1] as $idx => $m) {
-            $data = preg_replace('/\r\n/', '', $matches[3][$idx][0]);
-            $data = base64_decode($data);
-
-            if (empty($data)) {
-                continue;
-            }
-
-            $hash      = md5($data) . '@' . $domain;
-            $mime_type = $matches[2][$idx][0];
-            $name      = $list[$hash];
-
-            // add the image to the MIME message
-            if (!$name) {
-                $ext         = preg_replace('#^[^/]+/#', '', $mime_type);
-                $name        = substr($hash, 0, 8) . '.' . $ext;
-                $list[$hash] = $name;
-
-                $mime_message->addHTMLImage($data, $mime_type, $name, false, $hash);
-            }
-
-            $body = substr_replace($body, $name, $m[1] + $offset, strlen($m[0]));
-            $offset += strlen($name) - strlen($m[0]);
-        }
-    }
-
-    $mime_message->setHTMLBody($body);
-}
-
-/**
- * Parse and cleanup email address input (and count addresses)
- *
- * @param string  Address input
- * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
- * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
- * @return string Canonical recipients string separated by comma
- */
-function rcmail_email_input_format($mailto, $count=false, $check=true)
-{
-    global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
-
-    // simplified email regexp, supporting quoted local part
-    $email_regexp = '(\S+|("[^"]+"))@\S+';
-
-    $delim   = trim($RCMAIL->config->get('recipients_separator', ','));
-    $regexp  = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
-    $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
-
-    // replace new lines and strip ending ', ', make address input more valid
-    $mailto = trim(preg_replace($regexp, $replace, $mailto));
-    $items  = rcube_utils::explode_quoted_string($delim, $mailto);
-    $result = array();
-
-    foreach ($items as $item) {
-        $item = trim($item);
-        // address in brackets without name (do nothing)
-        if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
-            $item     = rcube_utils::idn_to_ascii(trim($item, '<>'));
-            $result[] = $item;
-        }
-        // address without brackets and without name (add brackets)
-        else if (preg_match('/^'.$email_regexp.'$/', $item)) {
-            $item     = rcube_utils::idn_to_ascii($item);
-            $result[] = $item;
-        }
-        // address with name (handle name)
-        else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
-            $address = $matches[0];
-            $name    = trim(str_replace($address, '', $item));
-            if ($name[0] == '"' && $name[count($name)-1] == '"') {
-                $name = substr($name, 1, -1);
-            }
-            $name     = stripcslashes($name);
-            $address  = rcube_utils::idn_to_ascii(trim($address, '<>'));
-            $result[] = format_email_recipient($address, $name);
-            $item     = $address;
-        }
-        else if (trim($item)) {
-            continue;
-        }
-
-        // check address format
-        $item = trim($item, '<>');
-        if ($item && $check && !rcube_utils::check_email($item)) {
-            $EMAIL_FORMAT_ERROR = $item;
-            return;
-        }
-    }
-
-    if ($count) {
-        $RECIPIENT_COUNT += count($result);
-    }
-
-    return implode(', ', $result);
-}
-
-
-function rcmail_generic_message_footer($isHtml)
-{
-    global $RCMAIL;
-
-    if ($isHtml && ($file = $RCMAIL->config->get('generic_message_footer_html'))) {
-        $html_footer = true;
-    }
-    else {
-        $file = $RCMAIL->config->get('generic_message_footer');
-        $html_footer = false;
-    }
-
-    if ($file && realpath($file)) {
-        // sanity check
-        if (!preg_match('/\.(php|ini|conf)$/', $file) && strpos($file, '/etc/') === false) {
-            $footer = file_get_contents($file);
-            if ($isHtml && !$html_footer) {
-                $footer = '<pre>' . $footer . '</pre>';
-            }
-            return $footer;
-        }
-    }
-
-    return false;
-}
-
-
 /****** compose message ********/
 
 if (empty($COMPOSE['param']['message-id'])) {
@@ -307,7 +78,7 @@
 $mailcc  = rcmail_email_input_format(rcube_utils::get_input_value('_cc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
 $mailbcc = rcmail_email_input_format(rcube_utils::get_input_value('_bcc', rcube_utils::INPUT_POST, TRUE, $message_charset), true);
 
-if ($EMAIL_FORMAT_ERROR) {
+if ($EMAIL_FORMAT_ERROR && !$savedraft) {
     $OUTPUT->show_message('emailformaterror', 'error', array('email' => $EMAIL_FORMAT_ERROR));
     $OUTPUT->send('iframe');
 }
@@ -374,7 +145,7 @@
         $http_header .= $nldlm . ' via ';
     }
 
-    $host = $_SERVER['REMOTE_ADDR'];
+    $host     = $_SERVER['REMOTE_ADDR'];
     $hostname = gethostbyaddr($host);
 
     if ($encrypt) {
@@ -401,7 +172,7 @@
 
 $headers['Date'] = $RCMAIL->user_date();
 $headers['From'] = rcube_charset::convert($from_string, RCUBE_CHARSET, $message_charset);
-$headers['To'] = $mailto;
+$headers['To']   = $mailto;
 
 // additional recipients
 if (!empty($mailcc)) {
@@ -418,6 +189,10 @@
     }
 }
 
+$dont_override = (array) $RCMAIL->config->get('dont_override');
+$mdn_enabled   = in_array('mdn_default', $dont_override) ? $RCMAIL->config->get('mdn_default') : !empty($_POST['_mdn']);
+$dsn_enabled   = in_array('dsn_default', $dont_override) ? $RCMAIL->config->get('dsn_default') : !empty($_POST['_dsn']);
+
 // add subject
 $headers['Subject'] = trim(rcube_utils::get_input_value('_subject', rcube_utils::INPUT_POST, TRUE, $message_charset));
 
@@ -431,7 +206,7 @@
     $headers['Mail-Reply-To'] = $headers['Reply-To'];
 }
 if ($hdr = rcube_utils::get_input_value('_followupto', rcube_utils::INPUT_POST, TRUE, $message_charset)) {
-    $headers['Mail-Followup-To'] = rcmail_email_input_format();
+    $headers['Mail-Followup-To'] = rcmail_email_input_format($hdr);
 }
 
 // remember reply/forward UIDs in special headers
@@ -439,7 +214,7 @@
     $headers['X-Draft-Info'] = array('type' => 'reply', 'uid' => $COMPOSE['reply_uid']);
 }
 else if (!empty($COMPOSE['forward_uid']) && $savedraft) {
-    $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => $COMPOSE['forward_uid']);
+    $headers['X-Draft-Info'] = array('type' => 'forward', 'uid' => rcube_imap_generic::compressMessageSet($COMPOSE['forward_uid']));
 }
 
 if (!empty($COMPOSE['reply_msgid'])) {
@@ -458,7 +233,7 @@
     }
 }
 
-if (!empty($_POST['_receipt'])) {
+if ($mdn_enabled) {
     $headers['Return-Receipt-To']           = $from_string;
     $headers['Disposition-Notification-To'] = $from_string;
 }
@@ -503,20 +278,31 @@
     }
 
     // append doctype and html/body wrappers
-    $message_body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">'
-        . "\r\n<html><body" . (!empty($bstyle) ? " style='" . implode($bstyle, '; ') . "'" : '') . ">\r\n"
-        . $message_body;
+    $bstyle       = !empty($bstyle) ? (" style='" . implode($bstyle, '; ') . "'") : '';
+    $message_body = '<html><head>'
+        . '<meta http-equiv="Content-Type" content="text/html; charset=' . $message_charset . '" /></head>'
+        . "<body" . $bstyle . ">\r\n" . $message_body;
 }
 
 if (!$savedraft) {
     if ($isHtml) {
-        // remove signature's div ID
-        $message_body = preg_replace('/\s*id="_rc_sig"/', '', $message_body);
+        $b_style   = 'padding: 0 0.4em; border-left: #1010ff 2px solid; margin: 0';
+        $pre_style = 'margin: 0; padding: 0; font-family: monospace';
 
-        // add inline css for blockquotes
-        $bstyle       = 'padding-left:5px; border-left:#1010ff 2px solid; margin-left:5px';
-        $message_body = preg_replace('/<blockquote>/',
-            '<blockquote type="cite" style="'.$bstyle.'">', $message_body);
+        $message_body = preg_replace(
+            array(
+                // remove signature's div ID
+                '/\s*id="_rc_sig"/',
+                // add inline css for blockquotes and container
+                '/<blockquote>/',
+                '/<div class="pre">/'
+            ),
+            array(
+                '',
+                '<blockquote type="cite" style="'.$b_style.'">',
+                '<div class="pre" style="'.$pre_style.'">'
+            ),
+            $message_body);
     }
 
     // Check spelling before send
@@ -530,10 +316,16 @@
         $COMPOSE['spell_checked'] = true;
 
         if (!$spell_result) {
-            $result = $isHtml ? $spellchecker->get_words() : $spellchecker->get_xml();
+            if ($isHtml) {
+                $result['words']      = $spellchecker->get();
+                $result['dictionary'] = (bool) $RCMAIL->config->get('spellcheck_dictionary');
+            }
+            else {
+                $result = $spellchecker->get_xml();
+            }
 
             $OUTPUT->show_message('mispellingsfound', 'error');
-            $OUTPUT->command('spellcheck_resume', $isHtml, $result);
+            $OUTPUT->command('spellcheck_resume', $result);
             $OUTPUT->send('iframe');
         }
     }
@@ -641,8 +433,7 @@
         $attachment = $RCMAIL->plugins->exec_hook('attachment_get', $attachment);
 
         if ($isHtml) {
-            $dispurl      = '/\ssrc\s*=\s*[\'"]*\S+display-attachment\S+file=rcmfile'
-                . preg_quote($attachment['id']) . '[\s\'"]*/';
+            $dispurl      = '/[\'"]\S+display-attachment\S+file=rcmfile' . preg_quote($attachment['id']) . '[\'"]/';
             $message_body = $MAIL_MIME->getHTMLBody();
             $is_inline    = preg_match($dispurl, $message_body);
         }
@@ -662,7 +453,7 @@
                 $cid .= '@localhost';
             }
 
-            $message_body = preg_replace($dispurl, ' src="cid:' . $cid . '" ', $message_body);
+            $message_body = preg_replace($dispurl, '"cid:' . $cid . '"', $message_body);
 
             $MAIL_MIME->setHTMLBody($message_body);
 
@@ -682,7 +473,8 @@
                 $attachment['data'] ? false : true,
                 $ctype == 'message/rfc822' ? '8bit' : 'base64',
                 'attachment',
-                '', '', '',
+                $attachment['charset'],
+                '', '',
                 $folding ? 'quoted-printable' : NULL,
                 $folding == 2 ? 'quoted-printable' : NULL,
                 '', RCUBE_CHARSET
@@ -697,15 +489,11 @@
     $transfer_encoding = $RCMAIL->config->get('force_7bit') ? 'quoted-printable' : '8bit';
 }
 else {
-    $text_charset      = '';
+    $text_charset      = 'US-ASCII';
     $transfer_encoding = '7bit';
 }
 
 if ($flowed) {
-    if (!$text_charset) {
-        $text_charset = 'US-ASCII';
-    }
-
     $text_charset .= ";\r\n format=flowed";
 }
 
@@ -717,19 +505,11 @@
 $MAIL_MIME->setParam('html_charset', $message_charset);
 $MAIL_MIME->setParam('text_charset', $text_charset);
 
-// encoding subject header with mb_encode provides better results with asian characters
-if (function_exists('mb_encode_mimeheader')) {
-    mb_internal_encoding($message_charset);
-    $headers['Subject'] = mb_encode_mimeheader($headers['Subject'],
-        $message_charset, 'Q', "\r\n", 8);
-    mb_internal_encoding(RCUBE_CHARSET);
-}
-
 // pass headers to message object
 $MAIL_MIME->headers($headers);
 
 // Begin SMTP Delivery Block
-if (!$savedraft) {
+if (!$savedraft && !$saveonly) {
     // check 'From' address (identity may be incomplete)
     if (empty($from)) {
         $OUTPUT->show_message('nofromaddress', 'error');
@@ -737,9 +517,7 @@
     }
 
     // Handle Delivery Status Notification request
-    if (!empty($_POST['_dsn'])) {
-        $smtp_opts['dsn'] = true;
-    }
+    $smtp_opts['dsn'] = $dsn_enabled;
 
     $sent = $RCMAIL->deliver_message($MAIL_MIME, $from, $mailto,
         $smtp_error, $mailbody_file, $smtp_opts);
@@ -764,10 +542,16 @@
     }
 
     // set replied/forwarded flag
-    if ($COMPOSE['reply_uid'])
-        $RCMAIL->storage->set_flag($COMPOSE['reply_uid'], 'ANSWERED', $COMPOSE['mailbox']);
-    else if ($COMPOSE['forward_uid'])
-        $RCMAIL->storage->set_flag($COMPOSE['forward_uid'], 'FORWARDED', $COMPOSE['mailbox']);
+    if ($COMPOSE['reply_uid']) {
+        foreach (rcmail::get_uids($COMPOSE['reply_uid'], $COMPOSE['mailbox']) as $mbox => $uids) {
+            $RCMAIL->storage->set_flag($uids, 'ANSWERED', $mbox);
+        }
+    }
+    else if ($COMPOSE['forward_uid']) {
+        foreach (rcmail::get_uids($COMPOSE['forward_uid'], $COMPOSE['mailbox']) as $mbox => $uids) {
+            $RCMAIL->storage->set_flag($uids, 'FORWARDED', $mbox);
+        }
+    }
 }
 
 // Determine which folder to save message
@@ -775,9 +559,11 @@
     $store_target = $drafts_mbox;
 }
 else if (!$RCMAIL->config->get('no_save_sent_messages')) {
-    $store_target = rcube_utils::get_input_value('_store_target', rcube_utils::INPUT_POST);
-    if (!strlen($store_target)) {
-        $sore_target = $RCMAIL->config->get('sent_mbox');
+    if (isset($_POST['_store_target'])) {
+        $store_target = rcube_utils::get_input_value('_store_target', rcube_utils::INPUT_POST);
+    }
+    else {
+        $store_target = $RCMAIL->config->get('sent_mbox');
     }
 }
 
@@ -807,8 +593,9 @@
             else {
                 $temp_dir      = $RCMAIL->config->get('temp_dir');
                 $mailbody_file = tempnam($temp_dir, 'rcmMsg');
+                $msg           = $MAIL_MIME->saveMessageBody($mailbody_file);
 
-                if (!PEAR::isError($msg = $MAIL_MIME->saveMessageBody($mailbody_file))) {
+                if (!is_a($msg, 'PEAR_Error')) {
                     $msg = $mailbody_file;
                 }
             }
@@ -818,7 +605,7 @@
             $headers = '';
         }
 
-        if (PEAR::isError($msg)) {
+        if (is_a($msg, 'PEAR_Error')) {
             rcube::raise_error(array('code' => 650, 'type' => 'php',
                 'file' => __FILE__, 'line' => __LINE__,
                 'message' => "Could not create message: ".$msg->getMessage()),
@@ -842,7 +629,8 @@
             'message' => "Could not save message in $store_target"), true, false);
 
         if ($savedraft) {
-            $OUTPUT->show_message('errorsaving', 'error');
+            $RCMAIL->display_server_error('errorsaving');
+
             // start the auto-save timer again
             $OUTPUT->command('auto_save_start');
             $OUTPUT->send('iframe');
@@ -891,23 +679,278 @@
     $OUTPUT->command('auto_save_start');
 }
 else {
+    // Collect folders which could contain the composed message,
+    // we'll refresh the list if currently opened folder is one of them (#1490238)
     $folders = array();
 
-    if ($COMPOSE['mode'] == 'reply' || $COMPOSE['mode'] == 'forward') {
-        $folders[] = $COMPOSE['mailbox'];
+    if (!$saveonly) {
+        if (in_array($COMPOSE['mode'], array('reply', 'forward', 'draft'))) {
+            $folders[] = $COMPOSE['mailbox'];
+        }
+        if (!empty($COMPOSE['param']['draft_uid']) && $drafts_mbox) {
+            $folders[] = $drafts_mbox;
+        }
     }
-
-    rcmail_compose_cleanup($COMPOSE_ID);
-    $OUTPUT->command('remove_compose_data', $COMPOSE_ID);
 
     if ($store_folder && !$saved) {
-        $OUTPUT->command('sent_successfully', 'error', $RCMAIL->gettext('errorsavingsent'), $folders);
+        $params = $saveonly ? null : array('prefix' => true);
+        $RCMAIL->display_server_error('errorsavingsent', null, null, $params);
+        if ($saveonly) {
+            $OUTPUT->send('iframe');
+        }
+
+        $save_error = true;
     }
-    else if ($store_folder) {
-        $folders[] = $store_target;
+    else {
+        rcmail_compose_cleanup($COMPOSE_ID);
+        $OUTPUT->command('remove_compose_data', $COMPOSE_ID);
+
+        if ($store_folder) {
+            $folders[] = $store_target;
+        }
     }
 
-    $OUTPUT->command('sent_successfully', 'confirmation', $RCMAIL->gettext('messagesent'), $folders);
+    $msg = $RCMAIL->gettext($saveonly ? 'successfullysaved' : 'messagesent');
+
+    $OUTPUT->command('sent_successfully', 'confirmation', $msg, $folders, $save_error);
 }
 
 $OUTPUT->send('iframe');
+
+
+/****** message sending functions ********/
+
+// encrypt parts of the header
+function rcmail_encrypt_header($what)
+{
+    global $RCMAIL;
+
+    if (!$RCMAIL->config->get('http_received_header_encrypt')) {
+        return $what;
+    }
+
+    return $RCMAIL->encrypt($what);
+}
+
+// get identity record
+function rcmail_get_identity($id)
+{
+    global $RCMAIL, $message_charset;
+
+    if ($sql_arr = $RCMAIL->user->get_identity($id)) {
+        $out = $sql_arr;
+
+        if ($message_charset != RCUBE_CHARSET) {
+            foreach ($out as $k => $v) {
+                $out[$k] = rcube_charset::convert($v, RCUBE_CHARSET, $message_charset);
+            }
+        }
+
+        $out['mailto'] = $sql_arr['email'];
+        $out['string'] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
+
+        return $out;
+    }
+
+    return false;
+}
+
+/**
+ * go from this:
+ * <img src="http[s]://.../tinymce/plugins/emoticons/img/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
+ *
+ * to this:
+ *
+ * <img src="/path/on/server/.../tinymce/plugins/emoticons/img/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
+ */
+function rcmail_fix_emoticon_paths($mime_message)
+{
+    global $RCMAIL;
+
+    $body = $mime_message->getHTMLBody();
+
+    // remove any null-byte characters before parsing
+    $body = preg_replace('/\x00/', '', $body);
+
+    $searchstr  = 'program/js/tinymce/plugins/emoticons/img/';
+    $assets_dir = $RCMAIL->config->get('assets_dir');
+    $path       = ($assets_dir ?: INSTALL_PATH) . '/' . $searchstr;
+    $offset     = 0;
+
+    // keep track of added images, so they're only added once
+    $included_images = array();
+
+    if (preg_match_all('# src=[\'"]([^\'"]+)#', $body, $matches, PREG_OFFSET_CAPTURE)) {
+        foreach ($matches[1] as $m) {
+            // find emoticon image tags
+            if (preg_match('#'.$searchstr.'(.*)$#', $m[0], $imatches)) {
+                $image_name = $imatches[1];
+
+                // sanitize image name so resulting attachment doesn't leave images dir
+                $image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i', '', $image_name);
+                $img_file   = $path . $image_name;
+
+                if (!in_array($image_name, $included_images)) {
+                    // add the image to the MIME message
+                    $res = $mime_message->addHTMLImage($img_file, 'image/gif', '', true, $image_name);
+                    if (is_a($res, 'PEAR_Error')) {
+                        $RCMAIL->output->show_message("emoticonerror", 'error');
+                        continue;
+                    }
+
+                    array_push($included_images, $image_name);
+                }
+
+                $body    = substr_replace($body, $img_file, $m[1] + $offset, strlen($m[0]));
+                $offset += strlen($img_file) - strlen($m[0]);
+            }
+        }
+    }
+
+    $mime_message->setHTMLBody($body);
+}
+
+/**
+ * Extract image attachments from HTML content (data URIs)
+ */
+function rcmail_extract_inline_images($mime_message, $from)
+{
+    $body   = $mime_message->getHTMLBody();
+    $offset = 0;
+    $list   = array();
+    $domain = 'localhost';
+    $regexp = '#img[^>]+src=[\'"](data:([^;]*);base64,([a-z0-9+/=\r\n]+))([\'"])#i';
+
+    if (preg_match_all($regexp, $body, $matches, PREG_OFFSET_CAPTURE)) {
+        // get domain for the Content-ID, must be the same as in Mail_Mime::get()
+        if (preg_match('#@([0-9a-zA-Z\-\.]+)#', $from, $m)) {
+            $domain = $m[1];
+        }
+
+        foreach ($matches[1] as $idx => $m) {
+            $data = preg_replace('/\r\n/', '', $matches[3][$idx][0]);
+            $data = base64_decode($data);
+
+            if (empty($data)) {
+                continue;
+            }
+
+            $hash      = md5($data) . '@' . $domain;
+            $mime_type = $matches[2][$idx][0];
+            $name      = $list[$hash];
+
+            if (empty($mime_type)) {
+                $mime_type = rcube_mime::image_content_type($data);
+            }
+
+            // add the image to the MIME message
+            if (!$name) {
+                $ext         = preg_replace('#^[^/]+/#', '', $mime_type);
+                $name        = substr($hash, 0, 8) . '.' . $ext;
+                $list[$hash] = $name;
+
+                $mime_message->addHTMLImage($data, $mime_type, $name, false, $hash);
+            }
+
+            $body = substr_replace($body, $name, $m[1] + $offset, strlen($m[0]));
+            $offset += strlen($name) - strlen($m[0]);
+        }
+    }
+
+    $mime_message->setHTMLBody($body);
+}
+
+/**
+ * Parse and cleanup email address input (and count addresses)
+ *
+ * @param string  Address input
+ * @param boolean Do count recipients (saved in global $RECIPIENT_COUNT)
+ * @param boolean Validate addresses (errors saved in global $EMAIL_FORMAT_ERROR)
+ * @return string Canonical recipients string separated by comma
+ */
+function rcmail_email_input_format($mailto, $count=false, $check=true)
+{
+    global $RCMAIL, $EMAIL_FORMAT_ERROR, $RECIPIENT_COUNT;
+
+    // simplified email regexp, supporting quoted local part
+    $email_regexp = '(\S+|("[^"]+"))@\S+';
+
+    $delim   = trim($RCMAIL->config->get('recipients_separator', ','));
+    $regexp  = array("/[,;$delim]\s*[\r\n]+/", '/[\r\n]+/', "/[,;$delim]\s*\$/m", '/;/', '/(\S{1})(<'.$email_regexp.'>)/U');
+    $replace = array($delim.' ', ', ', '', $delim, '\\1 \\2');
+
+    // replace new lines and strip ending ', ', make address input more valid
+    $mailto = trim(preg_replace($regexp, $replace, $mailto));
+    $items  = rcube_utils::explode_quoted_string($delim, $mailto);
+    $result = array();
+
+    foreach ($items as $item) {
+        $item = trim($item);
+        // address in brackets without name (do nothing)
+        if (preg_match('/^<'.$email_regexp.'>$/', $item)) {
+            $item     = rcube_utils::idn_to_ascii(trim($item, '<>'));
+            $result[] = $item;
+        }
+        // address without brackets and without name (add brackets)
+        else if (preg_match('/^'.$email_regexp.'$/', $item)) {
+            $item     = rcube_utils::idn_to_ascii($item);
+            $result[] = $item;
+        }
+        // address with name (handle name)
+        else if (preg_match('/<*'.$email_regexp.'>*$/', $item, $matches)) {
+            $address = $matches[0];
+            $name    = trim(str_replace($address, '', $item));
+            if ($name[0] == '"' && $name[count($name)-1] == '"') {
+                $name = substr($name, 1, -1);
+            }
+            $name     = stripcslashes($name);
+            $address  = rcube_utils::idn_to_ascii(trim($address, '<>'));
+            $result[] = format_email_recipient($address, $name);
+            $item     = $address;
+        }
+        else if (trim($item)) {
+            continue;
+        }
+
+        // check address format
+        $item = trim($item, '<>');
+        if ($item && $check && !rcube_utils::check_email($item)) {
+            $EMAIL_FORMAT_ERROR = $item;
+            return;
+        }
+    }
+
+    if ($count) {
+        $RECIPIENT_COUNT += count($result);
+    }
+
+    return implode(', ', $result);
+}
+
+
+function rcmail_generic_message_footer($isHtml)
+{
+    global $RCMAIL;
+
+    if ($isHtml && ($file = $RCMAIL->config->get('generic_message_footer_html'))) {
+        $html_footer = true;
+    }
+    else {
+        $file = $RCMAIL->config->get('generic_message_footer');
+        $html_footer = false;
+    }
+
+    if ($file && realpath($file)) {
+        // sanity check
+        if (!preg_match('/\.(php|ini|conf)$/', $file) && strpos($file, '/etc/') === false) {
+            $footer = file_get_contents($file);
+            if ($isHtml && !$html_footer) {
+                $t2h    = new rcube_text2html($footer, false);
+                $footer = $t2h->get_html();
+            }
+            return $footer;
+        }
+    }
+
+    return false;
+}

--
Gitblit v1.9.1