From 323fa20bc89edcd683bef1a170445f681305fc5c Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Wed, 23 Mar 2016 11:54:31 -0400
Subject: [PATCH] Message/rfc822 attachment preview (#5054)

---
 program/steps/mail/func.inc                 |    4 +
 program/lib/Roundcube/rcube_message.php     |  108 +++++++++++++++++++++++++-----------
 program/steps/mail/show.inc                 |   14 +++-
 program/steps/mail/get.inc                  |   26 +++++++-
 program/js/app.js                           |    4 
 program/steps/mail/headers.inc              |   11 +++
 skins/classic/templates/messagepreview.html |    4 +
 skins/larry/templates/messagepreview.html   |    4 +
 8 files changed, 127 insertions(+), 48 deletions(-)

diff --git a/program/js/app.js b/program/js/app.js
index 075600c..8fe638c 100644
--- a/program/js/app.js
+++ b/program/js/app.js
@@ -1211,13 +1211,13 @@
             this.open_window(this.env.comm_path + url, true, true);
           }
         }
-        else if (this.env.action == 'get') {
+        else if (this.env.action == 'get' && this.env.mimetype != 'message/rfc822') {
           this.gui_objects.messagepartframe.contentWindow.print();
         }
         else if (uid = this.get_single_uid()) {
           url = this.url('print', this.params_from_uid(uid, {_safe: this.env.safemode ? 1 : 0}));
           if (this.open_window(url, true, true)) {
-            if (this.env.action != 'show')
+            if (this.env.action != 'show' && this.env.action != 'get')
               this.mark_message('read', uid);
           }
         }
diff --git a/program/lib/Roundcube/rcube_message.php b/program/lib/Roundcube/rcube_message.php
index 10ebbf6..c5c436f 100644
--- a/program/lib/Roundcube/rcube_message.php
+++ b/program/lib/Roundcube/rcube_message.php
@@ -54,6 +54,7 @@
     public $folder;
     public $headers;
     public $sender;
+    public $context;
     public $parts        = array();
     public $mime_parts   = array();
     public $inline_parts = array();
@@ -78,11 +79,17 @@
     function __construct($uid, $folder = null, $is_safe = false)
     {
         // decode combined UID-folder identifier
-        if (preg_match('/^\d+-.+/', $uid)) {
+        if (preg_match('/^[0-9.]+-.+/', $uid)) {
             list($uid, $folder) = explode('-', $uid, 2);
         }
 
+        if (preg_match('/^([0-9]+)\.([0-9.]+)$/', $uid, $matches)) {
+            $uid     = $matches[1];
+            $context = $matches[2];
+        }
+
         $this->uid     = $uid;
+        $this->context = $context;
         $this->app     = rcube::get_instance();
         $this->storage = $this->app->get_storage();
         $this->folder  = strlen($folder) ? $folder : $this->storage->get_folder();
@@ -96,10 +103,6 @@
         if (!$this->headers) {
             return;
         }
-
-        $this->mime    = new rcube_mime($this->headers->charset);
-        $this->subject = $this->headers->get('subject');
-        list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
 
         $this->set_safe($is_safe || $_SESSION['safe_messages'][$this->folder.':'.$uid]);
         $this->opt = array(
@@ -116,9 +119,13 @@
             $this->get_mime_numbers($this->headers->structure);
             $this->parse_structure($this->headers->structure);
         }
-        else {
+        else if ($this->context === null) {
             $this->body = $this->storage->get_body($uid);
         }
+
+        $this->mime    = new rcube_mime($this->headers->charset);
+        $this->subject = $this->headers->get('subject');
+        list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));
 
         // notify plugins and let them analyze this structured message object
         $this->app->plugins->exec_hook('message_load', array('object' => $this));
@@ -332,6 +339,10 @@
     {
         // check all message parts
         foreach ($this->mime_parts as $part) {
+            if (!$this->check_context($part)) {
+                continue;
+            }
+
             if ($part->mimetype == 'text/html' || ($enriched && $part->mimetype == 'text/enriched')) {
                 // Skip if part is an attachment, don't use is_attachment() here
                 if ($part->filename) {
@@ -386,6 +397,10 @@
             if ($part->mimetype == 'text/plain') {
                 // Skip if part is an attachment, don't use is_attachment() here
                 if ($part->filename) {
+                    continue;
+                }
+
+                if (!$this->check_context($part)) {
                     continue;
                 }
 
@@ -527,6 +542,10 @@
             if (!isset($structure->headers['subject']) && !isset($structure->headers['from'])) {
                 list($headers, ) = explode("\r\n\r\n", $this->get_part_body($structure->mime_id, false, 32768));
                 $structure->headers = rcube_mime::parse_headers($headers);
+
+                if ($this->context == $structure->mime_id) {
+                    $this->headers = rcube_message_header::from_array($structure->headers);
+                }
             }
         }
         else {
@@ -535,11 +554,12 @@
 
         // show message headers
         if ($recursive && is_array($structure->headers) &&
-                (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])) {
+            (isset($structure->headers['subject']) || $structure->headers['from'] || $structure->headers['to'])
+        ) {
             $c = new stdClass;
             $c->type = 'headers';
             $c->headers = $structure->headers;
-            $this->parts[] = $c;
+            $this->add_part($c);
         }
 
         // Allow plugins to handle message parts
@@ -561,25 +581,25 @@
         if ($message_ctype_primary == 'text' && !$recursive) {
             // parts with unsupported type add to attachments list
             if (!in_array($message_ctype_secondary, array('plain', 'html', 'enriched'))) {
-                $this->attachments[] = $structure;
+                $this->add_part($structure, 'attachment');
                 return;
             }
 
             $structure->type = 'content';
-            $this->parts[] = $structure;
+            $this->add_part($structure);
 
             // Parse simple (plain text) message body
             if ($message_ctype_secondary == 'plain') {
                 foreach ((array)$this->uu_decode($structure) as $uupart) {
                     $this->mime_parts[$uupart->mime_id] = $uupart;
-                    $this->attachments[] = $uupart;
+                    $this->add_part($uupart, 'attachment');
                 }
             }
         }
         // the same for pgp signed messages
         else if ($mimetype == 'application/pgp' && !$recursive) {
             $structure->type = 'content';
-            $this->parts[] = $structure;
+            $this->add_part($structure);
         }
         // message contains (more than one!) alternative parts
         else if ($mimetype == 'multipart/alternative'
@@ -613,7 +633,7 @@
                     $enriched_part = $p;
                 else {
                     // add unsupported/unrecognized parts to attachments list
-                    $this->attachments[] = $sub_part;
+                    $this->add_part($sub_part, 'attachment');
                 }
             }
 
@@ -642,7 +662,7 @@
             // add the right message body
             if (is_object($print_part)) {
                 $print_part->type = 'content';
-                $this->parts[] = $print_part;
+                $this->add_part($print_part);
             }
             // show plaintext warning
             else if ($html_part !== null && empty($this->parts)) {
@@ -653,7 +673,7 @@
                 $c->mimetype        = 'text/plain';
                 $c->realtype        = 'text/html';
 
-                $this->parts[] = $c;
+                $this->add_part($c);
             }
         }
         // this is an ecrypted message -> create a plaintext body with the according message
@@ -666,14 +686,14 @@
             $p->realtype        = 'multipart/encrypted';
             $p->mime_id         = $structure->mime_id;
 
-            $this->parts[] = $p;
+            $this->add_part($p);
 
             // add encrypted payload part as attachment
             if (is_array($structure->parts)) {
                 for ($i=0; $i < count($structure->parts); $i++) {
                     $subpart = $structure->parts[$i];
                     if ($subpart->mimetype == 'application/octet-stream' || !empty($subpart->filename)) {
-                        $this->attachments[] = $subpart;
+                        $this->add_part($subpart, 'attachment');
                     }
                 }
             }
@@ -688,10 +708,10 @@
             $p->realtype        = 'application/pkcs7-mime';
             $p->mime_id         = $structure->mime_id;
 
-            $this->parts[] = $p;
+            $this->add_part($p);
 
             if (!empty($structure->filename)) {
-                $this->attachments[] = $structure;
+                $this->add_part($structure, 'attachment');
             }
         }
         // message contains multiple parts
@@ -709,7 +729,7 @@
 
                     // list message/rfc822 as attachment as well (mostly .eml)
                     if ($primary_type == 'message' && !empty($mail_part->filename)) {
-                        $this->attachments[] = $mail_part;
+                        $this->add_part($mail_part, 'attachment');
                     }
                 }
                 // part text/[plain|html] or delivery status
@@ -738,12 +758,12 @@
                         ($secondary_type == 'plain' && !$this->opt['prefer_html'])
                     ) {
                         $mail_part->type = 'content';
-                        $this->parts[] = $mail_part;
+                        $this->add_part($mail_part);
                     }
 
                     // list as attachment as well
                     if (!empty($mail_part->filename)) {
-                        $this->attachments[] = $mail_part;
+                        $this->add_part($mail_part, 'attachment');
                     }
                 }
                 // ignore "virtual" protocol parts
@@ -755,13 +775,13 @@
                     $tnef_parts = (array) $this->tnef_decode($mail_part);
                     foreach ($tnef_parts as $tpart) {
                         $this->mime_parts[$tpart->mime_id] = $tpart;
-                        $this->attachments[] = $tpart;
+                        $this->add_part($tpart, 'attachment');
                     }
 
                     // add winmail.dat to the list if it's content is unknown
                     if (empty($tnef_parts) && !empty($mail_part->filename)) {
                         $this->mime_parts[$mail_part->mime_id] = $mail_part;
-                        $this->attachments[] = $mail_part;
+                        $this->add_part($mail_part, 'attachment');
                     }
                 }
                 // part is a file/attachment
@@ -783,12 +803,12 @@
                         if ($mail_part->headers['content-location'])
                             $mail_part->content_location = $mail_part->headers['content-base'] . $mail_part->headers['content-location'];
 
-                        $this->inline_parts[] = $mail_part;
+                        $this->add_part($mail_part, 'inline');
                     }
                     // regular attachment with valid content type
                     // (content-type name regexp according to RFC4288.4.2)
                     else if (preg_match('/^[a-z0-9!#$&.+^_-]+\/[a-z0-9!#$&.+^_-]+$/i', $part_mimetype)) {
-                        $this->attachments[] = $mail_part;
+                        $this->add_part($mail_part, 'attachment');
                     }
                     // attachment with invalid content type
                     // replace malformed content type with application/octet-stream (#1487767)
@@ -797,7 +817,7 @@
                         $mail_part->ctype_secondary = 'octet-stream';
                         $mail_part->mimetype        = 'application/octet-stream';
 
-                        $this->attachments[] = $mail_part;
+                        $this->add_part($mail_part, 'attachment');
                     }
                 }
                 // calendar part not marked as attachment (#1490325)
@@ -806,7 +826,7 @@
                         $mail_part->filename = 'calendar.ics';
                     }
 
-                    $this->attachments[] = $mail_part;
+                    $this->add_part($mail_part, 'attachment');
                 }
             }
 
@@ -828,13 +848,13 @@
                         // In this case multipart/related message has only one text part
                         // We'll add all such attachments to the attachments list
                         if (!isset($this->got_html_part)) {
-                            $this->attachments[] = $inline_object;
+                            $this->add_part($inline_object, 'attachment');
                         }
                         // MS Outlook sometimes also adds non-image attachments as related
                         // We'll add all such attachments to the attachments list
                         // Warning: some browsers support pdf in <img/>
                         else if (!preg_match($img_regexp, $inline_object->mimetype)) {
-                            $this->attachments[] = $inline_object;
+                            $this->add_part($inline_object, 'attachment');
                         }
                         // @TODO: we should fetch HTML body and find attachment's content-id
                         // to handle also image attachments without reference in the body
@@ -852,16 +872,16 @@
         }
         // message is a single part non-text
         else if ($structure->filename) {
-            $this->attachments[] = $structure;
+            $this->add_part($structure, $attachment);
         }
         // message is a single part non-text (without filename)
         else if (preg_match('/application\//i', $mimetype)) {
-            $this->attachments[] = $structure;
+            $this->add_part($structure, 'attachment');
         }
     }
 
     /**
-     * Fill aflat array with references to all parts, indexed by part numbers
+     * Fill a flat array with references to all parts, indexed by part numbers
      *
      * @param rcube_message_part $part Message body structure
      */
@@ -876,6 +896,28 @@
     }
 
     /**
+     * Add a part to object parts array(s) (with context check)
+     */
+    private function add_part($part, $type = null)
+    {
+        if ($this->check_context($part)) {
+            switch ($type) {
+                case 'inline': $this->inline_parts[] = $part; break;
+                case 'attachment': $this->attachments[] = $part; break;
+                default: $this->parts[] = $part; break;
+            }
+        }
+    }
+
+    /**
+     * Check if specified part belongs to the current context
+     */
+    private function check_context($part)
+    {
+        return $this->context === null || strpos($part->mime_id, $this->context . '.') === 0;
+    }
+
+    /**
      * Decode a Microsoft Outlook TNEF part (winmail.dat)
      *
      * @param rcube_message_part $part Message part to decode
diff --git a/program/steps/mail/func.inc b/program/steps/mail/func.inc
index 963e696..cb01f94 100644
--- a/program/steps/mail/func.inc
+++ b/program/steps/mail/func.inc
@@ -1985,7 +1985,9 @@
         'image/x-ms-bmp' => 'image/bmp', // #1490282
     );
 
-    if ($alias = $map[strtolower($name)]) {
+    $name = strtolower($name);
+
+    if ($alias = $map[$name]) {
         $name = $alias;
     }
     // Some versions of Outlook create garbage Content-Type:
diff --git a/program/steps/mail/get.inc b/program/steps/mail/get.inc
index f81bdc5..019c063 100644
--- a/program/steps/mail/get.inc
+++ b/program/steps/mail/get.inc
@@ -62,10 +62,17 @@
         'messagepartcontrols' => 'rcmail_message_part_controls',
     ));
 
+    $mimetype = $part ? rcmail_fix_mimetype($part->mimetype) : '';
+    if ($part_id && $mimetype == 'message/rfc822') {
+        $uid = preg_replace('/\.[0-9.]+/', '', $uid);
+        $uid .= '.' . $part_id;
+    }
+
     $OUTPUT->set_env('mailbox', $RCMAIL->storage->get_folder());
     $OUTPUT->set_env('uid', $uid);
     $OUTPUT->set_env('part', $part_id);
     $OUTPUT->set_env('filename', $filename);
+    $OUTPUT->set_env('mimetype', $mimetype);
 
     $OUTPUT->send('messagepart');
     exit;
@@ -449,12 +456,23 @@
  */
 function rcmail_message_part_frame($attrib)
 {
-    global $MESSAGE, $RCMAIL;
+    global $RCMAIL;
 
-    $part = $MESSAGE->mime_parts[asciiwords(rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC))];
-    $ctype_primary = strtolower($part->ctype_primary);
+    $mimetype = $RCMAIL->output->get_env('mimetype');
 
-    $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_embed=' : '_preload='), $_SERVER['QUERY_STRING']);
+    if ($mimetype == 'message/rfc822') {
+        $attrib['src'] = $RCMAIL->url(array(
+                'task'   => 'mail',
+                'action' => 'preview',
+                'uid'    => $RCMAIL->output->get_env('uid'),
+                'mbox'   => $RCMAIL->output->get_env('mailbox'),
+                'framed' => 1,
+        ));
+    }
+    else {
+        $frame_replace = strpos($mimetype, 'text/') === 0 ? '_embed=' : '_preload=';
+        $attrib['src'] = './?' . str_replace('_frame=', $frame_replace, $_SERVER['QUERY_STRING']);
+    }
 
     $RCMAIL->output->add_gui_object('messagepartframe', $attrib['id']);
 
diff --git a/program/steps/mail/headers.inc b/program/steps/mail/headers.inc
index 7fb8d58..174a5e8 100644
--- a/program/steps/mail/headers.inc
+++ b/program/steps/mail/headers.inc
@@ -5,7 +5,7 @@
  | program/steps/mail/headers.inc                                        |
  |                                                                       |
  | This file is part of the Roundcube Webmail client                     |
- | Copyright (C) 2005-2007, The Roundcube Dev Team                       |
+ | Copyright (C) 2005-2016, The Roundcube Dev Team                       |
  |                                                                       |
  | Licensed under the GNU General Public License version 3 or            |
  | any later version with exceptions for skins & plugins.                |
@@ -20,7 +20,14 @@
 */
 
 if ($uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST)) {
-    $source = $RCMAIL->storage->get_raw_headers($uid);
+    if ($pos = strpos($uid, '.')) {
+        $message = new rcube_message($uid);
+        $source  = $message->get_part_content(substr($uid, $pos + 1));
+        $source  = substr($source, 0, strpos($source, "\r\n\r\n"));
+    }
+    else {
+        $source = $RCMAIL->storage->get_raw_headers($uid);
+    }
 
     if ($source !== false) {
         $source = trim(rcube_charset::clean($source));
diff --git a/program/steps/mail/show.inc b/program/steps/mail/show.inc
index 59ae134..221183a 100644
--- a/program/steps/mail/show.inc
+++ b/program/steps/mail/show.inc
@@ -19,7 +19,7 @@
  +-----------------------------------------------------------------------+
 */
 
-$PRINT_MODE = $RCMAIL->action == 'print' ? TRUE : FALSE;
+$PRINT_MODE = $RCMAIL->action == 'print' ? true : false;
 
 // Read browser capabilities and store them in session
 if ($caps = rcube_utils::get_input_value('_caps', rcube_utils::INPUT_GET)) {
@@ -31,7 +31,8 @@
     $_SESSION['browser_caps'] = $browser_caps;
 }
 
-$uid       = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET);
+$msg_id    = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET);
+$uid       = preg_replace('/\.[0-9.]+$/', '', $msg_id);
 $mbox_name = $RCMAIL->storage->get_folder();
 
 // similar code as in program/steps/mail/get.inc
@@ -46,7 +47,7 @@
         $RCMAIL->config->set('prefer_html', $_SESSION['msg_formats'][$mbox_name.':'.$uid]);
     }
 
-    $MESSAGE = new rcube_message($uid, $mbox_name, intval($_GET['_safe']));
+    $MESSAGE = new rcube_message($msg_id, $mbox_name, intval($_GET['_safe']));
 
     // if message not found (wrong UID)...
     if (empty($MESSAGE->headers)) {
@@ -64,8 +65,9 @@
     $OUTPUT->set_pagetitle(abbreviate_string($MESSAGE->subject, 128, '...', true));
 
     // set message environment
-    $OUTPUT->set_env('uid', $MESSAGE->uid);
+    $OUTPUT->set_env('uid', $msg_id);
     $OUTPUT->set_env('safemode', $MESSAGE->is_safe);
+    $OUTPUT->set_env('no_preview_controls', $MESSAGE->context !== null);
     $OUTPUT->set_env('sender', $MESSAGE->sender['string']);
     $OUTPUT->set_env('mailbox', $mbox_name);
     $OUTPUT->set_env('username', $RCMAIL->get_user_name());
@@ -105,6 +107,9 @@
         if (!rcube_image::is_convertable('image/tiff')) {
             unset($mimetypes[$key]);
         }
+    }
+    if (!in_array('message/rfc822', $mimetypes)) {
+        $mimetypes[] = 'message/rfc822';
     }
 
     $OUTPUT->set_env('mimetypes', array_values($mimetypes));
@@ -146,6 +151,7 @@
     }
 
     if (empty($MESSAGE->headers->flags['SEEN'])
+        && $MESSAGE->context === null
         && ($RCMAIL->action == 'show' || ($RCMAIL->action == 'preview' && intval($RCMAIL->config->get('preview_pane_mark_read')) == 0))
     ) {
         $RCMAIL->output->command('set_unread_message', $MESSAGE->uid, $mbox_name);
diff --git a/skins/classic/templates/messagepreview.html b/skins/classic/templates/messagepreview.html
index 869f03f..d74c2d6 100644
--- a/skins/classic/templates/messagepreview.html
+++ b/skins/classic/templates/messagepreview.html
@@ -16,7 +16,9 @@
     <roundcube:if condition="env:optional_format=='html'" />
       <roundcube:button command="change-format" prop="html" image="/images/icons/html.png" width="15" height="15" title="changeformathtml" id="changeformathtml" />
     <roundcube:endif />
-    <roundcube:button command="extwin" image="/images/icons/extwin.png" width="15" height="15" title="openinextwin" id="openextwinlink" />
+    <roundcube:if condition="env:no_preview_controls == false">
+      <roundcube:button command="extwin" image="/images/icons/extwin.png" width="15" height="15" title="openinextwin" id="openextwinlink" />
+    <roundcube:endif />
   </div>
 <roundcube:object name="messageHeaders" class="headers-table" cellspacing="0" cellpadding="2" addicon="/images/icons/silhouette.png" summary="Message headers" />
 <roundcube:object name="messageFullHeaders" id="full-headers" />
diff --git a/skins/larry/templates/messagepreview.html b/skins/larry/templates/messagepreview.html
index 2e3b5ef..e504285 100644
--- a/skins/larry/templates/messagepreview.html
+++ b/skins/larry/templates/messagepreview.html
@@ -22,13 +22,15 @@
 	</span>
 	&nbsp;
 <roundcube:endif />
-<roundcube:if condition="env:mailbox != config:drafts_mbox">
+<roundcube:if condition="env:mailbox != config:drafts_mbox and env:no_preview_controls == false">
 	<roundcube:button command="reply" type="link" class="button reply" classSel="button reply pressed" innerClass="icon" title="replytomessage" label="replytomessage" />
 	<roundcube:button command="reply-all" type="link" class="button replyall" classSel="button replyall pressed" innerClass="icon" title="replytoallmessage" label="replytoallmessage" />
 	<roundcube:button command="forward" type="link" class="button forward" classSel="button forward pressed" innerClass="icon" title="forwardmessage" label="forwardmessage" />
 	&nbsp;
 <roundcube:endif />
+<roundcube:if condition="env:no_preview_controls == false">
 	<roundcube:button command="extwin" type="link" class="button extwin" classSel="button extwin pressed" innerClass="icon" title="openinextwin" label="openinextwin" />
+<roundcube:endif />
 </div>
 
 <h3 class="subject"><span class="voice"><roundcube:label name="subject" />: </span><roundcube:object name="messageHeaders" valueOf="subject" /></h3>

--
Gitblit v1.9.1