From 8bed5e0151eb375e2d2dc91e4e6c6d5aa62daa5c Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Sun, 19 Jul 2015 05:06:48 -0400
Subject: [PATCH] Fix regression where compose editor mode was set incorrectly

---
 program/lib/Roundcube/rcube_imap.php |  602 ++++++++++++++++++++++++++++++------------------------
 1 files changed, 334 insertions(+), 268 deletions(-)

diff --git a/program/lib/Roundcube/rcube_imap.php b/program/lib/Roundcube/rcube_imap.php
index f60be62..1421563 100644
--- a/program/lib/Roundcube/rcube_imap.php
+++ b/program/lib/Roundcube/rcube_imap.php
@@ -1,6 +1,6 @@
 <?php
 
-/*
+/**
  +-----------------------------------------------------------------------+
  | This file is part of the Roundcube Webmail client                     |
  | Copyright (C) 2005-2012, The Roundcube Dev Team                       |
@@ -56,6 +56,7 @@
      */
     protected $icache = array();
 
+    protected $plugins;
     protected $list_page = 1;
     protected $delimiter;
     protected $namespace;
@@ -82,6 +83,7 @@
     public function __construct()
     {
         $this->conn = new rcube_imap_generic();
+        $this->plugins = rcube::get_instance()->plugins;
 
         // Set namespace and delimiter from session,
         // so some methods would work before connection
@@ -92,7 +94,6 @@
             $this->delimiter = $_SESSION['imap_delimiter'];
         }
     }
-
 
     /**
      * Magic getter for backward compat.
@@ -106,17 +107,16 @@
         }
     }
 
-
     /**
      * Connect to an IMAP server
      *
-     * @param  string   $host    Host to connect
-     * @param  string   $user    Username for IMAP account
-     * @param  string   $pass    Password for IMAP account
-     * @param  integer  $port    Port to connect to
-     * @param  string   $use_ssl SSL schema (either ssl or tls) or null if plain connection
+     * @param string  $host    Host to connect
+     * @param string  $user    Username for IMAP account
+     * @param string  $pass    Password for IMAP account
+     * @param integer $port    Port to connect to
+     * @param string  $use_ssl SSL schema (either ssl or tls) or null if plain connection
      *
-     * @return boolean  TRUE on success, FALSE on failure
+     * @return boolean True on success, False on failure
      */
     public function connect($host, $user, $pass, $port=143, $use_ssl=null)
     {
@@ -147,7 +147,7 @@
 
         $attempt = 0;
         do {
-            $data = rcube::get_instance()->plugins->exec_hook('storage_connect',
+            $data = $this->plugins->exec_hook('storage_connect',
                 array_merge($this->options, array('host' => $host, 'user' => $user,
                     'attempt' => ++$attempt)));
 
@@ -170,8 +170,20 @@
         $this->connect_done = true;
 
         if ($this->conn->connected()) {
+            // check for session identifier
+            $session = null;
+            if (preg_match('/\s+SESSIONID=([^=\s]+)/', $this->conn->result, $m)) {
+                $session = $m[1];
+            }
+
             // get namespace and delimiter
             $this->set_env();
+
+            // trigger post-connect hook
+            $this->plugins->exec_hook('storage_connected', array(
+                'host' => $host, 'user' => $user, 'session' => $session
+            ));
+
             return true;
         }
         // write error log
@@ -189,7 +201,6 @@
         return false;
     }
 
-
     /**
      * Close IMAP connection.
      * Usually done on script shutdown
@@ -201,7 +212,6 @@
             $this->mcache->close();
         }
     }
-
 
     /**
      * Check connection state, connect if not connected.
@@ -224,7 +234,6 @@
         return $this->is_connected();
     }
 
-
     /**
      * Checks IMAP connection.
      *
@@ -234,7 +243,6 @@
     {
         return $this->conn->connected();
     }
-
 
     /**
      * Returns code of last error
@@ -246,7 +254,6 @@
         return $this->conn->errornum;
     }
 
-
     /**
      * Returns text of last error
      *
@@ -256,7 +263,6 @@
     {
         return $this->conn->error;
     }
-
 
     /**
      * Returns code of last command response
@@ -287,7 +293,6 @@
         }
     }
 
-
     /**
      * Activate/deactivate debug mode
      *
@@ -299,23 +304,21 @@
         $this->conn->setDebug($dbg, array($this, 'debug_handler'));
     }
 
-
     /**
      * Set internal folder reference.
      * All operations will be perfomed on this folder.
      *
-     * @param  string $folder Folder name
+     * @param string $folder Folder name
      */
     public function set_folder($folder)
     {
         $this->folder = $folder;
     }
 
-
     /**
      * Save a search result for future message listing methods
      *
-     * @param  array  $set  Search set, result from rcube_imap::get_search_set():
+     * @param array $set Search set, result from rcube_imap::get_search_set():
      *                      0 - searching criteria, string
      *                      1 - search result, rcube_result_index|rcube_result_thread
      *                      2 - searching character set, string
@@ -338,7 +341,6 @@
         }
     }
 
-
     /**
      * Return the saved search set as hash array
      *
@@ -358,7 +360,6 @@
             $this->search_sorted,
         );
     }
-
 
     /**
      * Returns the IMAP server's capability.
@@ -383,14 +384,13 @@
         return $_SESSION[$sess_key];
     }
 
-
     /**
      * Checks the PERMANENTFLAGS capability of the current folder
      * and returns true if the given flag is supported by the IMAP server
      *
-     * @param   string  $flag Permanentflag name
+     * @param string $flag Permanentflag name
      *
-     * @return  boolean True if this flag is supported
+     * @return boolean True if this flag is supported
      */
     public function check_permflag($flag)
     {
@@ -401,11 +401,10 @@
         return $imap_flag && !empty($perm_flags) && in_array_nocase($imap_flag, $perm_flags);
     }
 
-
     /**
      * Returns PERMANENTFLAGS of the specified folder
      *
-     * @param  string $folder Folder name
+     * @param string $folder Folder name
      *
      * @return array Flags
      */
@@ -433,25 +432,22 @@
         return $permflags;
     }
 
-
     /**
      * Returns the delimiter that is used by the IMAP server for folder separation
      *
-     * @return  string  Delimiter string
-     * @access  public
+     * @return string Delimiter string
      */
     public function get_hierarchy_delimiter()
     {
         return $this->delimiter;
     }
 
-
     /**
      * Get namespace
      *
      * @param string $name Namespace array index: personal, other, shared, prefix
      *
-     * @return  array  Namespace data
+     * @return array Namespace data
      */
     public function get_namespace($name = null)
     {
@@ -464,7 +460,6 @@
         unset($ns['prefix']);
         return $ns;
     }
-
 
     /**
      * Sets delimiter and namespaces
@@ -546,7 +541,6 @@
         $_SESSION['imap_delimiter'] = $this->delimiter;
     }
 
-
     /**
      * Get message count for a specific folder
      *
@@ -556,7 +550,7 @@
      * @param  boolean $status  Enables storing folder status info (max UID/count),
      *                          required for folder_status()
      *
-     * @return int     Number of messages
+     * @return int Number of messages
      */
     public function count($folder='', $mode='ALL', $force=false, $status=true)
     {
@@ -566,7 +560,6 @@
 
         return $this->countmessages($folder, $mode, $force, $status);
     }
-
 
     /**
      * protected method for getting nr of messages
@@ -682,7 +675,6 @@
         return (int)$count;
     }
 
-
     /**
      * Public method for listing message flags
      *
@@ -717,7 +709,6 @@
         return $result;
     }
 
-
     /**
      * Public method for listing headers
      *
@@ -727,7 +718,7 @@
      * @param   string   $sort_order Sort order [ASC|DESC]
      * @param   int      $slice      Number of slice items to extract from result array
      *
-     * @return  array    Indexed array with message header objects
+     * @return array Indexed array with message header objects
      */
     public function list_messages($folder='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
     {
@@ -738,7 +729,6 @@
         return $this->_list_messages($folder, $page, $sort_field, $sort_order, $slice);
     }
 
-
     /**
      * protected method for listing message headers
      *
@@ -748,8 +738,8 @@
      * @param   string   $sort_order Sort order [ASC|DESC]
      * @param   int      $slice      Number of slice items to extract from result array
      *
-     * @return  array    Indexed array with message header objects
-     * @see     rcube_imap::list_messages
+     * @return array Indexed array with message header objects
+     * @see rcube_imap::list_messages
      */
     protected function _list_messages($folder='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
     {
@@ -761,7 +751,7 @@
         $page = $page ? $page : $this->list_page;
 
         // use saved message set
-        if ($this->search_string && $folder == $this->folder) {
+        if ($this->search_string) {
             return $this->list_search_messages($folder, $page, $slice);
         }
 
@@ -792,16 +782,15 @@
         return array_values($a_msg_headers);
     }
 
-
     /**
      * protected method for listing message headers using threads
      *
-     * @param   string   $folder     Folder name
-     * @param   int      $page       Current page to list
-     * @param   int      $slice      Number of slice items to extract from result array
+     * @param string $folder Folder name
+     * @param int    $page   Current page to list
+     * @param int    $slice  Number of slice items to extract from result array
      *
-     * @return  array    Indexed array with message header objects
-     * @see     rcube_imap::list_messages
+     * @return array Indexed array with message header objects
+     * @see rcube_imap::list_messages
      */
     protected function list_thread_messages($folder, $page, $slice=0)
     {
@@ -819,7 +808,7 @@
     /**
      * Method for fetching threads data
      *
-     * @param  string $folder Folder name
+     * @param string $folder Folder name
      *
      * @return rcube_imap_thread Thread data object
      */
@@ -843,11 +832,10 @@
         return $this->icache['threads'] = $result;
     }
 
-
     /**
      * Method for direct fetching of threads data
      *
-     * @param  string $folder Folder name
+     * @param string $folder Folder name
      *
      * @return rcube_imap_thread Thread data object
      */
@@ -862,7 +850,6 @@
             $this->options['skip_deleted'] ? 'UNDELETED' : '', true);
     }
 
-
     /**
      * protected method for fetching threaded messages headers
      *
@@ -871,7 +858,7 @@
      * @param int                 $page       List page number
      * @param int                 $slice      Number of threads to slice
      *
-     * @return array  Messages headers
+     * @return array Messages headers
      */
     protected function fetch_thread_headers($folder, $threads, $page, $slice=0)
     {
@@ -901,13 +888,12 @@
         return array_values($a_msg_headers);
     }
 
-
     /**
      * protected method for setting threaded messages flags:
      * depth, has_children and unread_children
      *
-     * @param  array               $headers  Reference to headers array indexed by message UID
-     * @param  rcube_result_thread $threads  Threads data object
+     * @param array               $headers  Reference to headers array indexed by message UID
+     * @param rcube_result_thread $threads  Threads data object
      *
      * @return array Message headers array indexed by message UID
      */
@@ -933,7 +919,6 @@
         }
     }
 
-
     /**
      * protected method for listing a set of message headers (search results)
      *
@@ -941,7 +926,7 @@
      * @param   int      $page     Current page to list
      * @param   int      $slice    Number of slice items to extract from result array
      *
-     * @return  array    Indexed array with message header objects
+     * @return array Indexed array with message header objects
      */
     protected function list_search_messages($folder, $page, $slice=0)
     {
@@ -955,35 +940,56 @@
             $sort_field = $this->sort_field;
             $search_set = $this->search_set;
 
-            $this->sort_field = null;
-            $this->page_size = 1000;  // fetch up to 1000 matching messages per folder
-            $this->threading = false;
-
-            $a_msg_headers = array();
-            foreach ($search_set->sets as $resultset) {
-                if (!$resultset->is_empty()) {
-                    $this->search_set = $resultset;
-                    $this->search_threads = $resultset instanceof rcube_result_thread;
-                    $a_msg_headers = array_merge($a_msg_headers, $this->list_search_messages($resultset->get_parameters('MAILBOX'), 1));
-                }
-            }
-
-            // do sorting and paging
+            // prepare paging
             $cnt   = $search_set->count();
             $from  = ($page-1) * $page_size;
             $to    = $from + $page_size;
+            $slice_length = min($page_size, $cnt - $from);
 
-            // sort headers
-            if (!$this->threading && !empty($a_msg_headers)) {
-                $a_msg_headers = $this->conn->sortHeaders($a_msg_headers, $sort_field, $this->sort_order);
+            // fetch resultset headers, sort and slice them
+            if (!empty($sort_field)) {
+                $this->sort_field = null;
+                $this->page_size = 1000;  // fetch up to 1000 matching messages per folder
+                $this->threading = false;
+
+                $a_msg_headers = array();
+                foreach ($search_set->sets as $resultset) {
+                    if (!$resultset->is_empty()) {
+                        $this->search_set = $resultset;
+                        $this->search_threads = $resultset instanceof rcube_result_thread;
+                        $a_msg_headers = array_merge($a_msg_headers, $this->list_search_messages($resultset->get_parameters('MAILBOX'), 1));
+                    }
+                }
+
+                // sort headers
+                if (!empty($a_msg_headers)) {
+                    $a_msg_headers = $this->conn->sortHeaders($a_msg_headers, $sort_field, $this->sort_order);
+                }
+
+                // store (sorted) message index
+                $search_set->set_message_index($a_msg_headers, $sort_field, $this->sort_order);
+
+                // only return the requested part of the set
+                $a_msg_headers = array_slice(array_values($a_msg_headers), $from, $slice_length);
             }
+            else {
+                if ($this->sort_order != $search_set->get_parameters('ORDER')) {
+                    $search_set->revert();
+                }
 
-            // store (sorted) message index
-            $search_set->set_message_index($a_msg_headers, $sort_field, $this->sort_order);
+                // slice resultset first...
+                $fetch = array();
+                foreach (array_slice($search_set->get(), $from, $slice_length) as $msg_id) {
+                    list($uid, $folder) = explode('-', $msg_id, 2);
+                    $fetch[$folder][] = $uid;
+                }
 
-            // only return the requested part of the set
-            $slice_length  = min($page_size, $cnt - $from);
-            $a_msg_headers = array_slice(array_values($a_msg_headers), $from, $slice_length);
+                // ... and fetch the requested set of headers
+                $a_msg_headers = array();
+                foreach ($fetch as $folder => $a_index) {
+                    $a_msg_headers = array_merge($a_msg_headers, array_values($this->fetch_headers($folder, $a_index)));
+                }
+            }
 
             if ($slice) {
                 $a_msg_headers = array_slice($a_msg_headers, -$slice, $slice);
@@ -1105,7 +1111,6 @@
         }
     }
 
-
     /**
      * protected method for listing a set of threaded message headers (search results)
      *
@@ -1113,7 +1118,7 @@
      * @param   int      $page       Current page to list
      * @param   int      $slice      Number of slice items to extract from result array
      *
-     * @return  array    Indexed array with message header objects
+     * @return array Indexed array with message header objects
      * @see rcube_imap::list_search_messages()
      */
     protected function list_search_thread_messages($folder, $page, $slice=0)
@@ -1128,7 +1133,6 @@
 
         return $this->fetch_thread_headers($folder, clone $this->search_set, $page, $slice);
     }
-
 
     /**
      * Fetches messages headers (by UID)
@@ -1177,7 +1181,6 @@
         return $a_msg_headers;
     }
 
-
     /**
      * Returns current status of a folder (compared to the last time use)
      *
@@ -1225,7 +1228,6 @@
         return $result;
     }
 
-
     /**
      * Stores folder statistic data in session
      * @TODO: move to separate DB table (cache?)
@@ -1238,7 +1240,6 @@
     {
         $_SESSION['folders'][$folder][$name] = $data;
     }
-
 
     /**
      * Gets folder statistic data
@@ -1255,7 +1256,6 @@
 
         return array();
     }
-
 
     /**
      * Return sorted list of message UIDs
@@ -1334,7 +1334,6 @@
         return $this->index_direct($folder, $this->sort_field, $this->sort_order);
     }
 
-
     /**
      * Return sorted list of message UIDs ignoring current search settings.
      * Doesn't uses cache by default.
@@ -1349,7 +1348,7 @@
     public function index_direct($folder, $sort_field = null, $sort_order = null, $search = null)
     {
         if (!empty($search)) {
-            $search = $this->search_set->get_compressed();
+            $search = $search->get_compressed();
         }
 
         // use message index sort as default sorting
@@ -1402,7 +1401,6 @@
         return $index;
     }
 
-
     /**
      * Return index of threaded message UIDs
      *
@@ -1433,7 +1431,6 @@
         return $threads;
     }
 
-
     /**
      * Sort threaded result, using THREAD=REFS method if available.
      * If not, use any method and re-sort the result in THREAD=REFS way.
@@ -1463,32 +1460,43 @@
         }
     }
 
-
     /**
      * Invoke search request to IMAP server
      *
      * @param  string  $folder     Folder name to search in
-     * @param  string  $str        Search criteria
+     * @param  string  $search     Search criteria
      * @param  string  $charset    Search charset
      * @param  string  $sort_field Header field to sort by
      *
+     * @return rcube_result_index  Search result object
      * @todo: Search criteria should be provided in non-IMAP format, eg. array
      */
-    public function search($folder='', $str='ALL', $charset=NULL, $sort_field=NULL)
+    public function search($folder = '', $search = 'ALL', $charset = null, $sort_field = null)
     {
-        if (!$str) {
-            $str = 'ALL';
+        if (!$search) {
+            $search = 'ALL';
         }
 
-        if (empty($folder)) {
+        if ((is_array($folder) && empty($folder)) || (!is_array($folder) && !strlen($folder))) {
             $folder = $this->folder;
         }
 
-        // multi-folder search
-        if (is_array($folder) && count($folder) > 1 && $str != 'ALL') {
-            new rcube_result_index; // trigger autoloader and make these classes available for threaded context
-            new rcube_result_thread;
+        $plugin = $this->plugins->exec_hook('imap_search_before', array(
+            'folder'     => $folder,
+            'search'     => $search,
+            'charset'    => $charset,
+            'sort_field' => $sort_field,
+            'threading'  => $this->threading,
+        ));
 
+        $folder     = $plugin['folder'];
+        $search     = $plugin['search'];
+        $charset    = $plugin['charset'];
+        $sort_field = $plugin['sort_field'];
+        $results    = $plugin['result'];
+
+        // multi-folder search
+        if (!$results && is_array($folder) && count($folder) > 1 && $search != 'ALL') {
             // connect IMAP to have all the required classes and settings loaded
             $this->check_connection();
 
@@ -1496,23 +1504,36 @@
             $this->threading = false;
 
             $searcher = new rcube_imap_search($this->options, $this->conn);
+
+            // set limit to not exceed the client's request timeout
+            $searcher->set_timelimit(60);
+
+            // continue existing incomplete search
+            if (!empty($this->search_set) && $this->search_set->incomplete && $search == $this->search_string) {
+                $searcher->set_results($this->search_set);
+            }
+
+            // execute the search
             $results = $searcher->exec(
                 $folder,
-                $str,
+                $search,
                 $charset ? $charset : $this->default_charset,
                 $sort_field && $this->get_capability('SORT') ? $sort_field : null,
                 $this->threading
             );
         }
-        else {
-            $folder = is_array($folder) ? $folder[0] : $folder;
-            $results = $this->search_index($folder, $str, $charset, $sort_field);
+        else if (!$results) {
+            $folder  = is_array($folder) ? $folder[0] : $folder;
+            $search  = is_array($search) ? $search[$folder] : $search;
+            $results = $this->search_index($folder, $search, $charset, $sort_field);
         }
 
-        $this->set_search_set(array($str, $results, $charset, $sort_field,
-            $this->threading || $this->search_sorted ? true : false));
-    }
+        $sorted = $this->threading || $this->search_sorted || $plugin['search_sorted'] ? true : false;
 
+        $this->set_search_set(array($search, $results, $charset, $sort_field, $sorted));
+
+        return $results;
+    }
 
     /**
      * Direct (real and simple) SEARCH request (without result sorting and caching).
@@ -1524,23 +1545,29 @@
      */
     public function search_once($folder = null, $str = 'ALL')
     {
-        if (!$str) {
-            $str = 'ALL';
-        }
-
-        if (!strlen($folder)) {
-            $folder = $this->folder;
-        }
-
         if (!$this->check_connection()) {
             return new rcube_result_index();
         }
 
-        $index = $this->conn->search($folder, $str, true);
+        if (!$str) {
+            $str = 'ALL';
+        }
+
+        // multi-folder search
+        if (is_array($folder) && count($folder) > 1) {
+            $searcher = new rcube_imap_search($this->options, $this->conn);
+            $index = $searcher->exec($folder, $str, $this->default_charset);
+        }
+        else {
+            $folder = is_array($folder) ? $folder[0] : $folder;
+            if (!strlen($folder)) {
+                $folder = $this->folder;
+            }
+            $index = $this->conn->search($folder, $str, true);
+        }
 
         return $index;
     }
-
 
     /**
      * protected search method
@@ -1618,7 +1645,6 @@
         return $messages;
     }
 
-
     /**
      * Converts charset of search criteria string
      *
@@ -1637,12 +1663,15 @@
                 $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
                 $string = substr($str, $string_offset - 1, $m[0]);
                 $string = rcube_charset::convert($string, $charset, $dest_charset);
-                if ($string === false) {
+
+                if ($string === false || !strlen($string)) {
                     continue;
                 }
+
                 $res .= substr($str, $last, $m[1] - $last - 1) . rcube_imap_generic::escape($string);
                 $last = $m[0] + $string_offset - 1;
             }
+
             if ($last < strlen($str)) {
                 $res .= substr($str, $last, strlen($str)-$last);
             }
@@ -1655,7 +1684,6 @@
         return $res;
     }
 
-
     /**
      * Refresh saved search set
      *
@@ -1664,13 +1692,29 @@
     public function refresh_search()
     {
         if (!empty($this->search_string)) {
-            // FIXME: make this work with saved multi-folder searches
-            $this->search('', $this->search_string, $this->search_charset, $this->search_sort_field);
+            $this->search(
+                is_object($this->search_set) ? $this->search_set->get_parameters('MAILBOX') : '',
+                $this->search_string,
+                $this->search_charset,
+                $this->search_sort_field
+            );
         }
 
         return $this->get_search_set();
     }
 
+    /**
+     * Flag certain result subsets as 'incomplete'.
+     * For subsequent refresh_search() calls to only refresh the updated parts.
+     */
+    protected function set_search_dirty($folder)
+    {
+        if ($this->search_set && is_a($this->search_set, 'rcube_result_multifolder')) {
+            if ($subset = $this->search_set->get_set($folder)) {
+                $subset->incomplete = $this->search_set->incomplete = true;
+            }
+        }
+    }
 
     /**
      * Return message headers object of a specific message
@@ -1683,13 +1727,13 @@
      */
     public function get_message_headers($uid, $folder = null, $force = false)
     {
-        if (!strlen($folder)) {
-            $folder = $this->folder;
+        // decode combined UID-folder identifier
+        if (preg_match('/^\d+-.+/', $uid)) {
+            list($uid, $folder) = explode('-', $uid, 2);
         }
 
-        // decode combined UID-folder identifier
-        if (preg_match('/^\d+-[^,]+$/', $uid)) {
-            list($uid, $folder) = explode('-', $uid);
+        if (!strlen($folder)) {
+            $folder = $this->folder;
         }
 
         // get cached headers
@@ -1702,18 +1746,20 @@
         else {
             $headers = $this->conn->fetchHeader(
                 $folder, $uid, true, true, $this->get_fetch_headers());
+
+            if (is_object($headers))
+                $headers->folder = $folder;
         }
 
         return $headers;
     }
 
-
     /**
      * Fetch message headers and body structure from the IMAP server and build
-     * an object structure similar to the one generated by PEAR::Mail_mimeDecode
+     * an object structure.
      *
-     * @param int     $uid      Message UID to fetch
-     * @param string  $folder   Folder to read from
+     * @param int    $uid    Message UID to fetch
+     * @param string $folder Folder to read from
      *
      * @return object rcube_message_header Message data
      */
@@ -1724,8 +1770,8 @@
         }
 
         // decode combined UID-folder identifier
-        if (preg_match('/^\d+-[^,]+$/', $uid)) {
-            list($uid, $folder) = explode('-', $uid);
+        if (preg_match('/^\d+-.+/', $uid)) {
+            list($uid, $folder) = explode('-', $uid, 2);
         }
 
         // Check internal cache
@@ -1771,7 +1817,7 @@
             $this->struct_charset = $this->structure_charset($structure);
         }
 
-        $headers->ctype = strtolower($headers->ctype);
+        $headers->ctype = @strtolower($headers->ctype);
 
         // Here we can recognize malformed BODYSTRUCTURE and
         // 1. [@TODO] parse the message in other way to create our own message structure
@@ -1792,8 +1838,8 @@
                 $structure[1] = $m[2];
             }
             else {
-                // Try to parse the message using Mail_mimeDecode package
-                // We need a better solution, Mail_mimeDecode parses message
+                // Try to parse the message using rcube_mime_decode.
+                // We need a better solution, it parses message
                 // in memory, which wouldn't work for very big messages,
                 // (it uses up to 10x more memory than the message size)
                 // it's also buggy and not actively developed
@@ -1833,7 +1879,6 @@
         return $this->icache['message'] = $headers;
     }
 
-
     /**
      * Build message part object
      *
@@ -1841,7 +1886,7 @@
      * @param int    $count
      * @param string $parent
      */
-    protected function structure_part($part, $count=0, $parent='', $mime_headers=null)
+    protected function structure_part($part, $count = 0, $parent = '', $mime_headers = null)
     {
         $struct = new rcube_message_part;
         $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
@@ -1866,6 +1911,16 @@
             for ($i=1; $i<count($part); $i++) {
                 if (!is_array($part[$i])) {
                     $struct->ctype_secondary = strtolower($part[$i]);
+
+                    // read content type parameters
+                    if (is_array($part[$i+1])) {
+                        $struct->ctype_parameters = array();
+                        for ($j=0; $j<count($part[$i+1]); $j+=2) {
+                            $param = strtolower($part[$i+1][$j]);
+                            $struct->ctype_parameters[$param] = $part[$i+1][$j+1];
+                        }
+                    }
+
                     break;
                 }
             }
@@ -2049,14 +2104,13 @@
         return $struct;
     }
 
-
     /**
      * Set attachment filename from message part structure
      *
-     * @param  rcube_message_part $part    Part object
-     * @param  string             $headers Part's raw headers
+     * @param rcube_message_part $part    Part object
+     * @param string             $headers Part's raw headers
      */
-    protected function set_part_filename(&$part, $headers=null)
+    protected function set_part_filename(&$part, $headers = null)
     {
         if (!empty($part->d_parameters['filename'])) {
             $filename_mime = $part->d_parameters['filename'];
@@ -2184,11 +2238,10 @@
         }
     }
 
-
     /**
      * Get charset name from message structure (first part)
      *
-     * @param  array $structure Message structure
+     * @param array $structure Message structure
      *
      * @return string Charset name
      */
@@ -2217,7 +2270,8 @@
      *
      * @return string Message/part body if not printed
      */
-    public function get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL, $skip_charset_conv=false, $max_bytes=0, $formatted=true)
+    public function get_message_part($uid, $part = 1, $o_part = null, $print = null, $fp = null,
+        $skip_charset_conv = false, $max_bytes = 0, $formatted = true)
     {
         if (!$this->check_connection()) {
             return null;
@@ -2269,42 +2323,41 @@
         return $body;
     }
 
-
     /**
      * Returns the whole message source as string (or saves to a file)
      *
-     * @param int      $uid Message UID
-     * @param resource $fp  File pointer to save the message
+     * @param int      $uid  Message UID
+     * @param resource $fp   File pointer to save the message
+     * @param string   $part Optional message part ID
      *
      * @return string Message source string
      */
-    public function get_raw_body($uid, $fp=null)
+    public function get_raw_body($uid, $fp=null, $part = null)
     {
         if (!$this->check_connection()) {
             return null;
         }
 
         return $this->conn->handlePartBody($this->folder, $uid,
-            true, null, null, false, $fp);
+            true, $part, null, false, $fp);
     }
-
 
     /**
      * Returns the message headers as string
      *
-     * @param int $uid  Message UID
+     * @param int    $uid  Message UID
+     * @param string $part Optional message part ID
      *
      * @return string Message headers string
      */
-    public function get_raw_headers($uid)
+    public function get_raw_headers($uid, $part = null)
     {
         if (!$this->check_connection()) {
             return null;
         }
 
-        return $this->conn->fetchPartHeader($this->folder, $uid, true);
+        return $this->conn->fetchPartHeader($this->folder, $uid, true, $part);
     }
-
 
     /**
      * Sends the whole message source to stdout
@@ -2320,7 +2373,6 @@
 
         $this->conn->handlePartBody($this->folder, $uid, true, null, null, true, null, $formatted);
     }
-
 
     /**
      * Set message flag to one or several messages
@@ -2374,11 +2426,12 @@
                     $this->clear_message_cache($folder, $all_mode ? null : explode(',', $uids));
                 }
             }
+
+            $this->set_search_dirty($folder);
         }
 
         return $result;
     }
-
 
     /**
      * Append a mail message (source) to a specific folder
@@ -2421,11 +2474,21 @@
         if ($saved) {
             // increase messagecount of the target folder
             $this->set_messagecount($folder, 'ALL', 1);
+
+            $this->plugins->exec_hook('message_saved', array(
+                    'folder'  => $folder,
+                    'message' => $message,
+                    'headers' => $headers,
+                    'is_file' => $is_file,
+                    'flags'   => $flags,
+                    'date'    => $date,
+                    'binary'  => $binary,
+                    'result'  => $saved,
+            ));
         }
 
         return $saved;
     }
-
 
     /**
      * Move a message from one folder to another
@@ -2472,6 +2535,9 @@
         if ($moved) {
             $this->clear_messagecount($from_mbox);
             $this->clear_messagecount($to_mbox);
+
+            $this->set_search_dirty($from_mbox);
+            $this->set_search_dirty($to_mbox);
         }
         // moving failed
         else if ($to_trash && $config->get('delete_always', false)) {
@@ -2488,7 +2554,7 @@
                 if ($this->search_threads || $all_mode) {
                     $this->refresh_search();
                 }
-                else {
+                else if (!$this->search_set->incomplete) {
                     $this->search_set->filter(explode(',', $uids), $this->folder);
                 }
             }
@@ -2500,7 +2566,6 @@
 
         return $moved;
     }
-
 
     /**
      * Copy a message from one folder to another
@@ -2537,7 +2602,6 @@
 
         return $copied;
     }
-
 
     /**
      * Mark messages as deleted and expunge them
@@ -2576,13 +2640,15 @@
             // unset threads internal cache
             unset($this->icache['threads']);
 
+            $this->set_search_dirty($folder);
+
             // remove message ids from search set
             if ($this->search_set && $folder == $this->folder) {
                 // threads are too complicated to just remove messages from set
                 if ($this->search_threads || $all_mode) {
                     $this->refresh_search();
                 }
-                else {
+                else if (!$this->search_set->incomplete) {
                     $this->search_set->filter(explode(',', $uids));
                 }
             }
@@ -2593,7 +2659,6 @@
 
         return $deleted;
     }
-
 
     /**
      * Send IMAP expunge command and clear cache
@@ -2682,7 +2747,7 @@
         }
 
         // Give plugins a chance to provide a list of folders
-        $data = rcube::get_instance()->plugins->exec_hook('storage_folders',
+        $data = $this->plugins->exec_hook('storage_folders',
             array('root' => $root, 'name' => $name, 'filter' => $filter, 'mode' => 'LSUB'));
 
         if (isset($data['folders'])) {
@@ -2717,15 +2782,14 @@
         return $a_mboxes;
     }
 
-
     /**
      * Method for direct folders listing (LSUB)
      *
-     * @param   string  $root   Optional root folder
-     * @param   string  $name   Optional name pattern
+     * @param string $root Optional root folder
+     * @param string $name Optional name pattern
      *
-     * @return  array   List of subscribed folders
-     * @see     rcube_imap::list_folders_subscribed()
+     * @return array List of subscribed folders
+     * @see rcube_imap::list_folders_subscribed()
      */
     public function list_folders_subscribed_direct($root='', $name='*')
     {
@@ -2786,7 +2850,6 @@
         return $a_folders;
     }
 
-
     /**
      * Get a list of all folders available on the server
      *
@@ -2814,7 +2877,7 @@
         }
 
         // Give plugins a chance to provide a list of folders
-        $data = rcube::get_instance()->plugins->exec_hook('storage_folders',
+        $data = $this->plugins->exec_hook('storage_folders',
             array('root' => $root, 'name' => $name, 'filter' => $filter, 'mode' => 'LIST'));
 
         if (isset($data['folders'])) {
@@ -2855,15 +2918,14 @@
         return $a_mboxes;
     }
 
-
     /**
      * Method for direct folders listing (LIST)
      *
-     * @param   string  $root   Optional root folder
-     * @param   string  $name   Optional name pattern
+     * @param string $root Optional root folder
+     * @param string $name Optional name pattern
      *
-     * @return  array   List of folders
-     * @see     rcube_imap::list_folders()
+     * @return array List of folders
+     * @see rcube_imap::list_folders()
      */
     public function list_folders_direct($root='', $name='*')
     {
@@ -2887,15 +2949,14 @@
         return $result;
     }
 
-
     /**
      * Fix folders list by adding folders from other namespaces.
      * Needed on some servers eg. Courier IMAP
      *
-     * @param array  $result  Reference to folders list
-     * @param string $type    Listing type (ext-subscribed, subscribed or all)
+     * @param array  $result Reference to folders list
+     * @param string $type   Listing type (ext-subscribed, subscribed or all)
      */
-    private function list_folders_update(&$result, $type = null)
+    protected function list_folders_update(&$result, $type = null)
     {
         $namespace = $this->get_namespace();
         $search    = array();
@@ -2943,7 +3004,6 @@
         }
     }
 
-
     /**
      * Filter the given list of folders according to access rights
      *
@@ -2969,22 +3029,21 @@
         return $a_folders;
     }
 
-
     /**
      * Get mailbox quota information
-     * added by Nuny
+     *
+     * @param string $folder Folder name
      *
      * @return mixed Quota info or False if not supported
      */
-    public function get_quota()
+    public function get_quota($folder = null)
     {
         if ($this->get_capability('QUOTA') && $this->check_connection()) {
-            return $this->conn->getQuota();
+            return $this->conn->getQuota($folder);
         }
 
         return false;
     }
-
 
     /**
      * Get folder size (size of all messages in a folder)
@@ -3009,7 +3068,6 @@
         return $result;
     }
 
-
     /**
      * Subscribe to a specific folder(s)
      *
@@ -3023,7 +3081,6 @@
         return $this->change_subscription($folders, 'subscribe');
     }
 
-
     /**
      * Unsubscribe folder(s)
      *
@@ -3036,7 +3093,6 @@
         // let this common function do the main work
         return $this->change_subscription($folders, 'unsubscribe');
     }
-
 
     /**
      * Create a new folder on the server and register it in local cache
@@ -3055,6 +3111,16 @@
 
         $result = $this->conn->createFolder($folder, $type ? array("\\" . ucfirst($type)) : null);
 
+        // it's quite often situation that we're trying to create and subscribe
+        // a folder that already exist, but is unsubscribed
+        if (!$result) {
+            if ($this->get_response_code() == rcube_storage::ALREADYEXISTS
+                || preg_match('/already exists/i', $this->get_error_str())
+            ) {
+                $result = true;
+            }
+        }
+
         // try to subscribe it
         if ($result) {
             // clear cache
@@ -3067,7 +3133,6 @@
 
         return $result;
     }
-
 
     /**
      * Set a new name to an existing folder
@@ -3128,7 +3193,6 @@
         return $result;
     }
 
-
     /**
      * Remove folder from server
      *
@@ -3176,7 +3240,6 @@
         return $result;
     }
 
-
     /**
      * Detect special folder associations stored in storage backend
      */
@@ -3202,12 +3265,14 @@
         // request \Subscribed flag in LIST response as performance improvement for folder_exists()
         $folders = $this->conn->listMailboxes('', '*', array('SUBSCRIBED'), array('SPECIAL-USE'));
 
-        foreach ($folders as $folder) {
-            if ($flags = $this->conn->data['LIST'][$folder]) {
-                foreach ($types as $type) {
-                    if (in_array($type, $flags)) {
-                        $type           = strtolower(substr($type, 1));
-                        $special[$type] = $folder;
+        if (!empty($folders)) {
+            foreach ($folders as $folder) {
+                if ($flags = $this->conn->data['LIST'][$folder]) {
+                    foreach ($types as $type) {
+                        if (in_array($type, $flags)) {
+                            $type           = strtolower(substr($type, 1));
+                            $special[$type] = $folder;
+                        }
                     }
                 }
             }
@@ -3218,7 +3283,6 @@
 
         return array_merge($result, $special);
     }
-
 
     /**
      * Set special folder associations stored in storage backend
@@ -3257,7 +3321,6 @@
 
         return true;
     }
-
 
     /**
      * Checks if folder exists and is subscribed
@@ -3312,7 +3375,6 @@
         return false;
     }
 
-
     /**
      * Returns the namespace where the folder is in
      *
@@ -3342,7 +3404,6 @@
 
         return 'personal';
     }
-
 
     /**
      * Modify folder name according to namespace.
@@ -3382,7 +3443,6 @@
         return $folder;
     }
 
-
     /**
      * Gets folder attributes from LIST response, e.g. \Noselect, \Noinferiors
      *
@@ -3414,7 +3474,6 @@
 
         return is_array($opts) ? $opts : array();
     }
-
 
     /**
      * Gets connection (and current folder) data: UIDVALIDITY, EXISTS, RECENT,
@@ -3454,7 +3513,6 @@
 
         return $data;
     }
-
 
     /**
      * Returns extended information about the folder
@@ -3551,7 +3609,6 @@
         return $options;
     }
 
-
     /**
      * Synchronizes messages cache.
      *
@@ -3563,7 +3620,6 @@
             $mcache->synchronize($folder);
         }
     }
-
 
     /**
      * Get message header names for rcube_imap_generic::fetchHeader(s)
@@ -3616,7 +3672,6 @@
         return $this->conn->setACL($folder, $user, $acl);
     }
 
-
     /**
      * Removes any <identifier,rights> pair for the
      * specified user from the ACL for the specified
@@ -3641,7 +3696,6 @@
         return $this->conn->deleteACL($folder, $user);
     }
 
-
     /**
      * Returns the access control list for folder (GETACL)
      *
@@ -3662,7 +3716,6 @@
 
         return $this->conn->getACL($folder);
     }
-
 
     /**
      * Returns information about what rights can be granted to the
@@ -3687,7 +3740,6 @@
         return $this->conn->listRights($folder, $user);
     }
 
-
     /**
      * Returns the set of rights that the current user has to
      * folder (MYRIGHTS)
@@ -3709,7 +3761,6 @@
 
         return $this->conn->myRights($folder);
     }
-
 
     /**
      * Sets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
@@ -3744,7 +3795,6 @@
         return false;
     }
 
-
     /**
      * Unsets IMAP metadata/annotations (SETMETADATA/SETANNOTATION)
      *
@@ -3777,7 +3827,6 @@
 
         return false;
     }
-
 
     /**
      * Returns IMAP metadata/annotations (GETMETADATA/GETANNOTATION)
@@ -3829,8 +3878,16 @@
 
             // @TODO: Honor MAXSIZE and DEPTH options
             foreach ($queries as $attrib => $entry) {
-                if ($result = $this->conn->getAnnotation($folder, $entry, $attrib)) {
-                    $res = array_merge_recursive($res, $result);
+                $result = $this->conn->getAnnotation($folder, $entry, $attrib);
+
+                // an error, invalidate any previous getAnnotation() results
+                if (!is_array($result)) {
+                    return null;
+                }
+                else {
+                    foreach ($result as $fldr => $data) {
+                        $res[$fldr] = array_merge((array) $res[$fldr], $data);
+                    }
                 }
             }
         }
@@ -3842,7 +3899,6 @@
 
         return null;
     }
-
 
     /**
      * Converts the METADATA extension entry name into the correct
@@ -3973,7 +4029,6 @@
         }
     }
 
-
     /**
      * Getter for messages cache object
      */
@@ -3992,7 +4047,6 @@
         return $this->mcache;
     }
 
-
     /**
      * Clears the messages cache.
      *
@@ -4005,7 +4059,6 @@
             $mcache->clear($folder, $uids);
         }
     }
-
 
     /**
      * Delete outdated cache entries
@@ -4036,7 +4089,6 @@
         }
     }
 
-
     /**
      * Sort folders first by default folders and then in alphabethical order
      *
@@ -4047,67 +4099,87 @@
      */
     public function sort_folder_list($a_folders, $skip_default = false)
     {
-        $a_out = $a_defaults = $folders = array();
-
-        $delimiter = $this->get_hierarchy_delimiter();
         $specials  = array_merge(array('INBOX'), array_values($this->get_special_folders()));
+        $folders   = array();
 
-        // find default folders and skip folders starting with '.'
+        // convert names to UTF-8 and skip folders starting with '.'
         foreach ($a_folders as $folder) {
-            if ($folder[0] == '.') {
-                continue;
-            }
-
-            if (!$skip_default && ($p = array_search($folder, $specials)) !== false && !$a_defaults[$p]) {
-                $a_defaults[$p] = $folder;
-            }
-            else {
-                $folders[$folder] = rcube_charset::convert($folder, 'UTF7-IMAP');
+            if ($folder[0] != '.') {
+                // for better performance skip encoding conversion
+                // if the string does not look like UTF7-IMAP
+                $folders[$folder] = strpos($folder, '&') === false ? $folder : rcube_charset::convert($folder, 'UTF7-IMAP');
             }
         }
 
-        // sort folders and place defaults on the top
-        asort($folders, SORT_LOCALE_STRING);
-        ksort($a_defaults);
-        $folders = array_merge($a_defaults, array_keys($folders));
+        // sort folders
+        // asort($folders, SORT_LOCALE_STRING) is not properly sorting case sensitive names
+        uasort($folders, array($this, 'sort_folder_comparator'));
 
-        // finally we must rebuild the list to move
-        // subfolders of default folders to their place...
-        // ...also do this for the rest of folders because
-        // asort() is not properly sorting case sensitive names
-        while (list($key, $folder) = each($folders)) {
-            // set the type of folder name variable (#1485527)
-            $a_out[] = (string) $folder;
-            unset($folders[$key]);
-            $this->rsort($folder, $delimiter, $folders, $a_out);
+        $folders = array_keys($folders);
+
+        if ($skip_default) {
+            return $folders;
         }
 
-        return $a_out;
+        // force the type of folder name variable (#1485527)
+        $folders  = array_map('strval', $folders);
+        $out      = array();
+
+        // finally we must put special folders on top and rebuild the list
+        // to move their subfolders where they belong...
+        $specials = array_unique(array_intersect($specials, $folders));
+        $folders  = array_merge($specials, array_diff($folders, $specials));
+
+        $this->sort_folder_specials(null, $folders, $specials, $out);
+
+        return $out;
     }
 
-
     /**
-     * Recursive method for sorting folders
+     * Recursive function to put subfolders of special folders in place
      */
-    protected function rsort($folder, $delimiter, &$list, &$out)
+    protected function sort_folder_specials($folder, &$list, &$specials, &$out)
     {
         while (list($key, $name) = each($list)) {
-            if (strpos($name, $folder.$delimiter) === 0) {
-                // set the type of folder name variable (#1485527)
-                $out[] = (string) $name;
+            if ($folder === null || strpos($name, $folder.$this->delimiter) === 0) {
+                $out[] = $name;
                 unset($list[$key]);
-                $this->rsort($name, $delimiter, $list, $out);
+
+                if (!empty($specials) && ($found = array_search($name, $specials)) !== false) {
+                    unset($specials[$found]);
+                    $this->sort_folder_specials($name, $list, $specials, $out);
+                }
             }
         }
+
         reset($list);
     }
 
+    /**
+     * Callback for uasort() that implements correct
+     * locale-aware case-sensitive sorting
+     */
+    protected function sort_folder_comparator($str1, $str2)
+    {
+        $path1 = explode($this->delimiter, $str1);
+        $path2 = explode($this->delimiter, $str2);
+
+        foreach ($path1 as $idx => $folder1) {
+            $folder2 = $path2[$idx];
+
+            if ($folder1 === $folder2) {
+                continue;
+            }
+
+            return strcoll($folder1, $folder2);
+        }
+    }
 
     /**
      * Find UID of the specified message sequence ID
      *
-     * @param int    $id       Message (sequence) ID
-     * @param string $folder   Folder name
+     * @param int    $id     Message (sequence) ID
+     * @param string $folder Folder name
      *
      * @return int Message UID
      */
@@ -4131,7 +4203,6 @@
 
         return $uid;
     }
-
 
     /**
      * Subscribe/unsubscribe a list of folders and update local cache
@@ -4165,7 +4236,6 @@
         return $updated;
     }
 
-
     /**
      * Increde/decrese messagecount for a specific folder
      */
@@ -4196,7 +4266,6 @@
         return true;
     }
 
-
     /**
      * Remove messagecount of a specific folder from cache
      */
@@ -4214,7 +4283,6 @@
             $this->update_cache('messagecount', $a_folder_cache);
         }
     }
-
 
     /**
      * Converts date string/object into IMAP date/time format
@@ -4237,7 +4305,6 @@
 
         return $date->format('d-M-Y H:i:s O');
     }
-
 
     /**
      * This is our own debug handler for the IMAP connection
@@ -4368,7 +4435,7 @@
         return $this->mod_folder($folder, $mode);
     }
 
-    public function mailbox_attributes($folder, $force=false)
+    public function mailbox_attributes($folder, $force = false)
     {
         return $this->folder_attributes($folder, $force);
     }
@@ -4388,9 +4455,8 @@
         return $this->folder_sync($folder);
     }
 
-    public function expunge($folder='', $clear_cache=true)
+    public function expunge($folder = '', $clear_cache = true)
     {
         return $this->expunge_folder($folder, $clear_cache);
     }
-
 }

--
Gitblit v1.9.1