From de6876597453e42690070af12e82e1fac0ad1b04 Mon Sep 17 00:00:00 2001
From: Thomas Bruederli <thomas@roundcube.net>
Date: Thu, 31 May 2012 04:42:46 -0400
Subject: [PATCH] Merged CHANGELOG

---
 CHANGELOG                       |    2 
 program/include/rcube_image.php |   87 +++++++++++++
 program/steps/mail/func.inc     |   56 ++++++++-
 program/steps/mail/show.inc     |   31 ++++
 program/blank.tif               |    0 
 program/steps/mail/get.inc      |   40 ++++++
 program/js/app.js               |  137 +++++++++++++++++++---
 7 files changed, 319 insertions(+), 34 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index e55f490..447e4b9 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -2,6 +2,8 @@
 ===========================
 
 - Don't let error message popups cover the login form (#1488500)
+- Display Tiff as Jpeg in browsers without Tiff support (#1488452)
+- Don't display Pdf/Tiff/Flash attachments inline without browser support (#1488452, #1487929)
 - Don't show errors when moving contacts into groups they are already in (#1488493)
 - Make folders with unread messages in subfolders bold again (#1486793)
 - Abbreviate long attachment file names with ellipsis (#1488499)
diff --git a/program/blank.tif b/program/blank.tif
new file mode 100644
index 0000000..2b3f4ec
--- /dev/null
+++ b/program/blank.tif
Binary files differ
diff --git a/program/include/rcube_image.php b/program/include/rcube_image.php
index 21cb5f1..80e8bd4 100644
--- a/program/include/rcube_image.php
+++ b/program/include/rcube_image.php
@@ -13,7 +13,7 @@
  | See the README file for a full license statement.                     |
  |                                                                       |
  | PURPOSE:                                                              |
- |   Image resizer                                                       |
+ |   Image resizer and converter                                         |
  |                                                                       |
  +-----------------------------------------------------------------------+
  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
@@ -24,6 +24,19 @@
 class rcube_image
 {
     private $image_file;
+
+    const TYPE_GIF = 1;
+    const TYPE_JPG = 2;
+    const TYPE_PNG = 3;
+    const TYPE_TIF = 4;
+
+    public static $extensions = array(
+        self::TYPE_GIF => 'gif',
+        self::TYPE_JPG => 'jpg',
+        self::TYPE_PNG => 'png',
+        self::TYPE_TIF => 'tif',
+    );
+
 
     function __construct($filename)
     {
@@ -66,7 +79,7 @@
      * @param int    $size      Max width/height size
      * @param string $filename  Output filename
      *
-     * @return Success of convert as true/false
+     * @return bool True on success, False on failure
      */
     public function resize($size, $filename = null)
     {
@@ -95,10 +108,10 @@
             $p['-opts'] = array('-resize' => $size.'>');
 
             if (in_array($type, explode(',', $p['types']))) { // Valid type?
-                $result = rcube::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p) === '';
+                $result = rcube::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p);
             }
 
-            if ($result) {
+            if ($result === '') {
                 return true;
             }
         }
@@ -148,6 +161,71 @@
             }
         }
 
+        // @TODO: print error to the log?
+        return false;
+    }
+
+    /**
+     * Convert image to a given type
+     *
+     * @param int    $type      Destination file type (see class constants)
+     * @param string $filename  Output filename (if empty, original file will be used
+     *                          and filename extension will be modified)
+     *
+     * @return bool True on success, False on failure
+     */
+    public function convert($type, $filename = null)
+    {
+        $rcube   = rcube::get_instance();
+        $convert = $rcube->config->get('im_convert_path', false);
+
+        if (!$filename) {
+            $filename = $this->image_file;
+
+            // modify extension
+            if ($extension = self::$extensions[$type]) {
+                $filename = preg_replace('/\.[^.]+$/', '', $filename) . '.' . $extension;
+            }
+        }
+
+        // use ImageMagick
+        if ($convert) {
+            $p['in']   = $this->image_file;
+            $p['out']  = $filename;
+            $p['type'] = self::$extensions[$type];
+
+            $result = rcube::exec($convert . ' 2>&1 -colorspace RGB -quality 75 {in} {type}:{out}', $p);
+
+            if ($result === '') {
+                return true;
+            }
+        }
+
+        // use GD extension (TIFF isn't supported)
+        $props    = $this->props();
+        $gd_types = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG);
+
+        if ($props['gd_type'] && in_array($props['gd_type'], $gd_types)) {
+            if ($props['gd_type'] == IMAGETYPE_JPEG) {
+                $image = imagecreatefromjpeg($this->image_file);
+            }
+            else if ($props['gd_type'] == IMAGETYPE_GIF) {
+                $image = imagecreatefromgif($this->image_file);
+            }
+            else if ($props['gd_type'] == IMAGETYPE_PNG) {
+                $image = imagecreatefrompng($this->image_file);
+            }
+
+            if ($type == self::TYPE_JPG) {
+                $result = imagejpeg($image, $filename, 75);
+            }
+            else if ($type == self::TYPE_GIF) {
+                $result = imagegif($image, $filename);
+            }
+            else if ($type == self::TYPE_PNG) {
+                $result = imagepng($image, $filename, 6, PNG_ALL_FILTERS);
+            }
+        }
 
         // @TODO: print error to the log?
         return false;
@@ -169,4 +247,5 @@
             }
         }
     }
+
 }
diff --git a/program/js/app.js b/program/js/app.js
index c4bf5ec..9d6f7e8 100644
--- a/program/js/app.js
+++ b/program/js/app.js
@@ -307,6 +307,10 @@
           this.http_post(postact, postdata);
         }
 
+        // detect browser capabilities
+        if (!this.is_framed())
+          this.browser_capabilities_check();
+
         break;
 
       case 'addressbook':
@@ -627,7 +631,7 @@
           uid = this.get_single_uid();
           if (uid && (!this.env.uid || uid != this.env.uid)) {
             if (this.env.mailbox == this.env.drafts_mailbox)
-              this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
+              this.goto_url('compose', { _draft_uid: uid, _mbox: this.env.mailbox }, true);
             else
               this.show_message(uid);
           }
@@ -649,13 +653,14 @@
         break;
 
       case 'edit':
-        if (this.task=='addressbook' && (cid = this.get_single_cid()))
+        if (this.task == 'addressbook' && (cid = this.get_single_cid()))
           this.load_contact(cid, 'edit');
-        else if (this.task=='settings' && props)
+        else if (this.task == 'settings' && props)
           this.load_identity(props, 'edit-identity');
-        else if (this.task=='mail' && (cid = this.get_single_uid())) {
-          url = (this.env.mailbox == this.env.drafts_mailbox) ? '_draft_uid=' : '_uid=';
-          this.goto_url('compose', url+cid+'&_mbox='+urlencode(this.env.mailbox), true);
+        else if (this.task == 'mail' && (cid = this.get_single_uid())) {
+          url = { _mbox: this.env.mailbox };
+          url[this.env.mailbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid'] = cid;
+          this.goto_url('compose', url, true);
         }
         break;
 
@@ -980,12 +985,12 @@
       case 'reply-list':
       case 'reply':
         if (uid = this.get_single_uid()) {
-          url = '_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
+          url = {_reply_uid: uid, _mbox: this.env.mailbox};
           if (command == 'reply-all')
             // do reply-list, when list is detected and popup menu wasn't used 
-            url += '&_all=' + (!props && this.commands['reply-list'] ? 'list' : 'all');
+            url._all = (!props && this.commands['reply-list'] ? 'list' : 'all');
           else if (command == 'reply-list')
-            url += '&_all=list';
+            url._all = list;
 
           this.goto_url('compose', url, true);
         }
@@ -994,9 +999,9 @@
       case 'forward-attachment':
       case 'forward':
         if (uid = this.get_single_uid()) {
-          url = '_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
+          url = { _forward_uid: uid, _mbox: this.env.mailbox };
           if (command == 'forward-attachment' || (!props && this.env.forward_attachment))
-            url += '&_attachment=1';
+            url._attachment = 1;
           this.goto_url('compose', url, true);
         }
         break;
@@ -1022,7 +1027,7 @@
 
       case 'download':
         if (uid = this.get_single_uid())
-          this.goto_url('viewsource', '&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+'&_save=1');
+          this.goto_url('viewsource', { _uid: uid, _mbox: this.env.mailbox, _save: 1 });
         break;
 
       // quicksearch
@@ -1075,7 +1080,7 @@
 
       case 'export':
         if (this.contact_list.rowcount > 0) {
-          this.goto_url('export', { _source:this.env.source, _gid:this.env.group, _search:this.env.search_request });
+          this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _search: this.env.search_request });
         }
         break;
 
@@ -1576,7 +1581,7 @@
 
     var uid = list.get_single_selection();
     if (uid && this.env.mailbox == this.env.drafts_mailbox)
-      this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
+      this.goto_url('compose', { _draft_uid: uid, _mbox: this.env.mailbox }, true);
     else if (uid)
       this.show_message(uid, false, false);
   };
@@ -1943,13 +1948,16 @@
     if (this.env.search_request)
       url += '&_search='+this.env.search_request;
 
-    if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
+    // add browser capabilities, so we can properly handle attachments
+    url += '&_caps='+urlencode(this.browser_capabilities());
+
+    if (preview && String(target.location.href).indexOf(url) >= 0)
       this.show_contentframe(true);
     else {
       this.location_href(this.env.comm_path+url, target, true);
 
       // mark as read and change mbox unread counter
-      if (action == 'preview' && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
+      if (preview && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
         this.preview_read_timer = setTimeout(function() {
           ref.set_message(id, 'unread', false);
           ref.update_thread_root(id, 'read');
@@ -3796,7 +3804,7 @@
       return;
 
     // ...new search value contains old one and previous search was not finished or its result was empty
-    if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || !ac.num) && this.env.contacts && !this.env.contacts.length)
+    if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || ac.num <= 0) && this.env.contacts && !this.env.contacts.length)
       return;
 
     var i, lock, source, xhr, reqid = new Date().getTime(),
@@ -4918,7 +4926,7 @@
 
     // submit request with appended token
     if (confirm(this.get_label('deleteidentityconfirm')))
-      this.goto_url('delete-identity', '_iid='+id+'&_token='+this.env.request_token, true);
+      this.goto_url('delete-identity', { _iid: id, _token: this.env.request_token }, true);
 
     return true;
   };
@@ -6368,6 +6376,99 @@
       $(elem).click(function() { rcmail.register_protocol_handler(name); return false; });
   };
 
+  // Checks browser capabilities eg. PDF support, TIF support
+  this.browser_capabilities_check = function()
+  {
+    if (!this.env.browser_capabilities)
+      this.env.browser_capabilities = {};
+
+    if (this.env.browser_capabilities.pdf === undefined)
+      this.env.browser_capabilities.pdf = this.pdf_support_check();
+
+    if (this.env.browser_capabilities.flash === undefined)
+      this.env.browser_capabilities.flash = this.flash_support_check();
+
+    if (this.env.browser_capabilities.tif === undefined)
+      this.tif_support_check();
+  };
+
+  // Returns browser capabilities string
+  this.browser_capabilities = function()
+  {
+    if (!this.env.browser_capabilities)
+      return '';
+
+    var n, ret = [];
+
+    for (n in this.env.browser_capabilities)
+      ret.push(n + '=' + this.env.browser_capabilities[n]);
+
+    return ret.join();
+  };
+
+  this.tif_support_check = function()
+  {
+    var img = new Image();
+
+    img.onload = function() { rcmail.env.browser_capabilities.tif = 1; };
+    img.onerror = function() { rcmail.env.browser_capabilities.tif = 0; };
+    img.src = 'program/blank.tif';
+  };
+
+  this.pdf_support_check = function()
+  {
+    var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/pdf"] : {},
+      plugins = navigator.plugins,
+      len = plugins.length,
+      regex = /Adobe Reader|PDF|Acrobat/i;
+
+    if (plugin && plugin.enabledPlugin)
+        return 1;
+
+    if (window.ActiveXObject) {
+      try {
+        if (axObj = new ActiveXObject("AcroPDF.PDF"))
+          return 1;
+      }
+      catch (e) {}
+      try {
+        if (axObj = new ActiveXObject("PDF.PdfCtrl"))
+          return 1;
+      }
+      catch (e) {}
+    }
+
+    for (i=0; i<len; i++) {
+      plugin = plugins[i];
+      if (typeof plugin === 'String') {
+        if (regex.test(plugin))
+          return 1;
+      }
+      else if (plugin.name && regex.test(plugin.name))
+        return 1;
+    }
+
+    return 0;
+  };
+
+  this.flash_support_check = function()
+  {
+    var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/x-shockwave-flash"] : {};
+
+    if (plugin && plugin.enabledPlugin)
+        return 1;
+
+    if (window.ActiveXObject) {
+      try {
+        if (axObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
+          return 1;
+      }
+      catch (e) {}
+    }
+
+    return 0;
+  };
+
 }  // end object rcube_webmail
 
 
diff --git a/program/steps/mail/func.inc b/program/steps/mail/func.inc
index 05d5895..33041d4 100644
--- a/program/steps/mail/func.inc
+++ b/program/steps/mail/func.inc
@@ -81,8 +81,8 @@
       $OUTPUT->set_env('search_request', $search_request);
     }
 
-      $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
-      $OUTPUT->set_env('search_mods', $search_mods);
+    $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
+    $OUTPUT->set_env('search_mods', $search_mods);
   }
 
   $threading = (bool) $RCMAIL->storage->get_threading();
@@ -114,6 +114,9 @@
     $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
   if ($CONFIG['junk_mbox'])
     $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
+
+  if (!empty($_SESSION['browser_caps']))
+    $OUTPUT->set_env('browser_capabilities', $_SESSION['browser_caps']);
 
   if (!$OUTPUT->ajax_call)
     $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
@@ -1103,12 +1106,7 @@
       }
 
       // Content-Type: image/*...
-      if (preg_match('/^image\//i', $attach_prop->mimetype) ||
-        // ...or known file extension: many clients are using application/octet-stream
-        ($attach_prop->filename &&
-          preg_match('/^application\/octet-stream$/i', $attach_prop->mimetype) &&
-          preg_match('/\.(jpg|jpeg|png|gif|bmp)$/i', $attach_prop->filename))
-      ) {
+      if (rcmail_part_image_type($attach_prop)) {
         $out .= html::tag('hr') . html::p(array('align' => "center"),
           html::img(array(
             'src' => $MESSAGE->get_part_url($attach_prop->mime_id, true),
@@ -1126,6 +1124,48 @@
   return html::div($attrib, $out);
 }
 
+function rcmail_part_image_type($part)
+{
+  $rcmail = rcmail::get_instance();
+
+  // Skip TIFF images if browser doesn't support this format...
+  $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
+  // until we can convert them to JPEG
+  $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
+
+  // Content-type regexp
+  $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
+
+  // Content-Type: image/*...
+  if (preg_match($mime_regex, $part->mimetype)) {
+    return $part->mimetype;
+  }
+
+  // Many clients use application/octet-stream, we'll detect mimetype
+  // by checking filename extension
+
+  // Supported image filename extensions to image type map
+  $types = array(
+    'jpg'  => 'image/jpeg',
+    'jpeg' => 'image/jpeg',
+    'png'  => 'image/png',
+    'gif'  => 'image/gif',
+    'bmp'  => 'image/bmp',
+  );
+  if ($tiff_support) {
+    $types['tif']  = 'image/tiff';
+    $types['tiff'] = 'image/tiff';
+  }
+
+  if ($part->filename
+    && preg_match('/^application\/octet-stream$/i', $part->mimetype)
+    && preg_match('/\.([^.])$/i', $part->filename, $m)
+    && ($extension = strtolower($m[1]))
+    && isset($types[$extension])
+  ) {
+    return $types[$extension];
+  }
+}
 
 /**
  * Convert all relative URLs according to a <base> in HTML
diff --git a/program/steps/mail/get.inc b/program/steps/mail/get.inc
index 750011f..658538a 100644
--- a/program/steps/mail/get.inc
+++ b/program/steps/mail/get.inc
@@ -22,7 +22,7 @@
 
 // show loading page
 if (!empty($_GET['_preload'])) {
-  $url = preg_replace('/[&?]+_preload=1/', '', $_SERVER['REQUEST_URI']);
+  $url = preg_replace('/([&?]+)_preload=/', '\\1_embed=', $_SERVER['REQUEST_URI']);
   $message = rcube_label('loadingdata');
 
   header('Content-Type: text/html; charset=' . RCMAIL_CHARSET);
@@ -76,6 +76,17 @@
 
     // overwrite modified vars from plugin
     $mimetype = $plugin['mimetype'];
+
+    // TIFF to JPEG conversion, if needed
+    $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
+    if (!empty($_REQUEST['_embed']) && !$tiff_support
+      && $RCMAIL->config->get('im_convert_path')
+      && rcmail_part_image_type($part) == 'image/tiff'
+    ) {
+      $tiff2jpeg = true;
+      $mimetype = 'image/jpeg';
+    }
+
     list($ctype_primary, $ctype_secondary) = explode('/', $mimetype);
     if ($plugin['body'])
       $part->body = $plugin['body'];
@@ -150,8 +161,33 @@
 
       header("Content-Disposition: $disposition; filename=\"$filename\"");
 
+      // handle tiff to jpeg conversion
+      if (!empty($tiff2jpeg)) {
+        $temp_dir  = unslashify($RCMAIL->config->get('temp_dir'));
+        $file_path = tempnam($temp_dir, 'rcmAttmnt');
+
+        // write content to temp file
+        if ($part->body) {
+          $saved = file_put_contents($file_path, $part->body);
+        }
+        else if ($part->size) {
+          $fd = fopen($file_path, 'w');
+          $saved = $RCMAIL->storage->get_message_part($MESSAGE->uid, $part->mime_id, $part, false, $fd);
+          fclose($fd);
+        }
+
+        // convert image to jpeg and send it to the browser
+        if ($saved) {
+          $image = new rcube_image($file_path);
+          if ($image->convert(rcube_image::TYPE_JPG, $file_path)) {
+            header("Content-Length: " . filesize($file_path));
+            readfile($file_path);
+          }
+          unlink($file_path);
+        }
+      }
       // do content filtering to avoid XSS through fake images
-      if (!empty($_REQUEST['_embed']) && $browser->ie && $browser->ver <= 8) {
+      else if (!empty($_REQUEST['_embed']) && $browser->ie && $browser->ver <= 8) {
         if ($part->body) {
           echo preg_match('/<(script|iframe|object)/i', $part->body) ? '' : $part->body;
           $sent = true;
diff --git a/program/steps/mail/show.inc b/program/steps/mail/show.inc
index 2d4d8e5..158ba31 100644
--- a/program/steps/mail/show.inc
+++ b/program/steps/mail/show.inc
@@ -21,6 +21,16 @@
 
 $PRINT_MODE = $RCMAIL->action=='print' ? TRUE : FALSE;
 
+// Read browser capabilities and store them in session
+if ($caps = get_input_value('_caps', RCUBE_INPUT_GET)) {
+  $browser_caps = array();
+  foreach (explode(',', $caps) as $cap) {
+    $cap = explode('=', $cap);
+    $browser_caps[$cap[0]] = $cap[1];
+  }
+  $_SESSION['browser_caps'] = $browser_caps;
+}
+
 // similar code as in program/steps/mail/get.inc
 if ($uid = get_input_value('_uid', RCUBE_INPUT_GET)) {
   $MESSAGE = new rcube_message($uid);
@@ -51,8 +61,25 @@
   $OUTPUT->set_env('mailbox', $mbox_name);
 
   // mimetypes supported by the browser (default settings)
-  $mimetypes = $RCMAIL->config->get('client_mimetypes', 'text/plain,text/html,text/xml,image/jpeg,image/gif,image/png,application/x-javascript,application/pdf,application/x-shockwave-flash');
-  $OUTPUT->set_env('mimetypes', is_string($mimetypes) ? explode(',', $mimetypes) : (array)$mimetypes);
+  $mimetypes = $RCMAIL->config->get('client_mimetypes', 'text/plain,text/html,text/xml,image/jpeg,image/gif,image/png,image/bmp,image/tiff,application/x-javascript,application/pdf,application/x-shockwave-flash');
+  $mimetypes = is_string($mimetypes) ? explode(',', $mimetypes) : (array)$mimetypes;
+
+  // Remove unsupported types, which makes that attachment which cannot be
+  // displayed in a browser will be downloaded directly without displaying an overlay page
+  if (empty($_SESSION['browser_caps']['pdf']) && ($key = array_search('application/pdf', $mimetypes)) !== false) {
+    unset($mimetypes[$key]);
+  }
+  if (empty($_SESSION['browser_caps']['flash']) && ($key = array_search('application/x-shockwave-flash', $mimetypes)) !== false) {
+    unset($mimetypes[$key]);
+  }
+  if (empty($_SESSION['browser_caps']['tif']) && ($key = array_search('image/tiff', $mimetypes)) !== false) {
+    // we can convert tiff to jpeg
+    if (!$RCMAIL->config->get('im_convert_path')) {
+      unset($mimetypes[$key]);
+    }
+  }
+
+  $OUTPUT->set_env('mimetypes', $mimetypes);
 
   if ($CONFIG['drafts_mbox'])
     $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);

--
Gitblit v1.9.1