alecpl
2010-03-19 9b3fdc25c171d2b2461af42224ea16ad6c032c49
program/include/rcube_imap.php
@@ -5,7 +5,7 @@
 | program/include/rcube_imap.php                                        |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2005-2009, RoundCube Dev. - Switzerland                 |
 | Copyright (C) 2005-2010, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
@@ -36,40 +36,46 @@
 *
 * @package    Mail
 * @author     Thomas Bruederli <roundcube@gmail.com>
 * @version    1.40
 * @version    1.5
 * @link       http://ilohamail.org
 */
class rcube_imap
{
  var $db;
  var $conn;
  var $root_ns = '';
  var $root_dir = '';
  var $mailbox = 'INBOX';
  var $list_page = 1;
  var $page_size = 10;
  var $sort_field = 'date';
  var $sort_order = 'DESC';
  var $delimiter = NULL;
  var $caching_enabled = FALSE;
  var $default_charset = 'ISO-8859-1';
  var $struct_charset = NULL;
  var $default_folders = array('INBOX');
  var $default_folders_lc = array('inbox');
  var $fetch_add_headers = '';
  var $cache = array();
  var $cache_keys = array();
  var $cache_changes = array();
  var $uid_id_map = array();
  var $msg_headers = array();
  var $skip_deleted = FALSE;
  var $search_set = NULL;
  var $search_string = '';
  var $search_charset = '';
  var $search_sort_field = '';
  var $debug_level = 1;
  var $error_code = 0;
  var $options = array('imap' => 'check');
  public $debug_level = 1;
  public $error_code = 0;
  public $skip_deleted = false;
  public $root_dir = '';
  public $page_size = 10;
  public $list_page = 1;
  public $delimiter = NULL;
  public $threading = false;
  public $fetch_add_headers = '';
  public $conn;
  private $db;
  private $root_ns = '';
  private $mailbox = 'INBOX';
  private $sort_field = '';
  private $sort_order = 'DESC';
  private $caching_enabled = false;
  private $default_charset = 'ISO-8859-1';
  private $struct_charset = NULL;
  private $default_folders = array('INBOX');
  private $default_folders_lc = array('inbox');
  private $icache = array();
  private $cache = array();
  private $cache_keys = array();
  private $cache_changes = array();
  private $uid_id_map = array();
  private $msg_headers = array();
  public  $search_set = NULL;
  public  $search_string = '';
  private $search_charset = '';
  private $search_sort_field = '';
  private $search_threads = false;
  private $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
  private $options = array('auth_method' => 'check');
  private $host, $user, $pass, $port, $ssl;
  /**
@@ -101,19 +107,27 @@
    // check for Open-SSL support in PHP build
    if ($use_ssl && extension_loaded('openssl'))
      $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
    else if ($use_ssl)
      {
      raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
                        'message' => 'Open SSL not available;'), TRUE, FALSE);
    else if ($use_ssl) {
      raise_error(array('code' => 403, 'type' => 'imap',
        'file' => __FILE__, 'line' => __LINE__,
        'message' => "Open SSL not available"), true, false);
      $port = 143;
      }
    }
    $ICL_PORT = $port;
    $IMAP_USE_INTERNAL_DATE = false;
    $this->conn = iil_Connect($host, $user, $pass, $this->options);
    $this->host = $host;
    $this->user = $user;
    $attempt = 0;
    do {
      $data = rcmail::get_instance()->plugins->exec_hook('imap_connect', array('host' => $host, 'user' => $user, 'attempt' => ++$attempt));
      if (!empty($data['pass']))
        $pass = $data['pass'];
      $this->conn = iil_Connect($data['host'], $data['user'], $pass, $this->options);
    } while(!$this->conn && $data['retry']);
    $this->host = $data['host'];
    $this->user = $data['user'];
    $this->pass = $pass;
    $this->port = $port;
    $this->ssl = $use_ssl;
@@ -126,24 +140,21 @@
    else if (!$this->conn && $GLOBALS['iil_error'])
      {
      $this->error_code = $GLOBALS['iil_errornum'];
      raise_error(array('code' => 403,
                       'type' => 'imap',
                       'message' => $GLOBALS['iil_error']), TRUE, FALSE);
      raise_error(array('code' => 403, 'type' => 'imap',
        'file' => __FILE__, 'line' => __LINE__,
        'message' => $GLOBALS['iil_error']), true, false);
      }
    // get server properties
    if ($this->conn)
      {
      if (!empty($this->conn->delimiter))
        $this->delimiter = $this->conn->delimiter;
      if (!empty($this->conn->rootdir))
        {
        $this->set_rootdir($this->conn->rootdir);
        $this->root_ns = preg_replace('/[.\/]$/', '', $this->conn->rootdir);
        }
      if (empty($this->delimiter))
   $this->get_hierarchy_delimiter();
      }
    return $this->conn ? TRUE : FALSE;
    return $this->conn ? true : false;
    }
@@ -231,15 +242,10 @@
    if (is_array($arr))
      {
      $this->default_folders = $arr;
      $this->default_folders_lc = array();
      // add inbox if not included
      if (!in_array_nocase('INBOX', $this->default_folders))
      if (!in_array('INBOX', $this->default_folders))
        array_unshift($this->default_folders, 'INBOX');
      // create a second list with lower cased names
      foreach ($this->default_folders as $mbox)
        $this->default_folders_lc[] = strtolower($mbox);
      }
    }
@@ -298,17 +304,18 @@
   * @param  string  Charset of search string
   * @param  string  Sorting field
   */
  function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null)
  function set_search_set($str=null, $msgs=null, $charset=null, $sort_field=null, $threads=false)
    {
    if (is_array($str) && $msgs == null)
      list($str, $msgs, $charset, $sort_field) = $str;
      list($str, $msgs, $charset, $sort_field, $threads) = $str;
    if ($msgs != null && !is_array($msgs))
      $msgs = explode(',', $msgs);
    $this->search_string = $str;
    $this->search_set = $msgs;
    $this->search_charset = $charset;
    $this->search_sort_field = $sort_field;
    $this->search_threads = $threads;
    }
@@ -318,7 +325,12 @@
   */
  function get_search_set()
    {
    return array($this->search_string, $this->search_set, $this->search_charset, $this->search_sort_field);
    return array($this->search_string,
   $this->search_set,
   $this->search_charset,
   $this->search_sort_field,
   $this->search_threads,
   );
    }
@@ -344,6 +356,30 @@
  function get_capability($cap)
    {
    return iil_C_GetCapability($this->conn, strtoupper($cap));
    }
  /**
   * Sets threading flag to the best supported THREAD algorithm
   *
   * @param  boolean  TRUE to enable and FALSE
   * @return string   Algorithm or false if THREAD is not supported
   * @access public
   */
  function set_threading($enable=false)
    {
    $this->threading = false;
    if ($enable) {
      if ($this->get_capability('THREAD=REFS'))
        $this->threading = 'REFS';
      else if ($this->get_capability('THREAD=REFERENCES'))
        $this->threading = 'REFERENCES';
      else if ($this->get_capability('THREAD=ORDEREDSUBJECT'))
        $this->threading = 'ORDEREDSUBJECT';
      }
    return $this->threading;
    }
@@ -404,7 +440,7 @@
      }
    // INBOX should always be available
    if (!in_array_nocase('INBOX', $a_out))
    if (!in_array('INBOX', $a_out))
      array_unshift($a_out, 'INBOX');
    // sort mailboxes
@@ -435,11 +471,10 @@
    if (isset($data['folders'])) {
        $a_folders = $data['folders'];
    }
    else{
    else {
        // retrieve list of folders from IMAP server
        $a_folders = iil_C_ListSubscribed($this->conn, $this->mod_mailbox($root), $filter);
    }
    
    if (!is_array($a_folders) || !sizeof($a_folders))
      $a_folders = array();
@@ -460,7 +495,7 @@
   * @return  int      Number of messages
   * @access  public
   */
  function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
  function messagecount($mbox_name='', $mode='ALL', $force=false)
    {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    return $this->_messagecount($mailbox, $mode, $force);
@@ -473,26 +508,35 @@
   * @access  private
   * @see     rcube_imap::messagecount()
   */
  private function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
  private function _messagecount($mailbox='', $mode='ALL', $force=false)
    {
    $a_mailbox_cache = FALSE;
    $mode = strtoupper($mode);
    if (empty($mailbox))
      $mailbox = $this->mailbox;
    // count search set
    if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force)
      return count((array)$this->search_set);
    // count search set
    if ($this->search_string && $mailbox == $this->mailbox && ($mode == 'ALL' || $mode == 'THREADS') && !$force) {
      if ($this->search_threads)
        return $mode == 'ALL' ? count((array)$this->search_set['depth']) : count((array)$this->search_set['tree']);
      else
        return count((array)$this->search_set);
      }
    $a_mailbox_cache = $this->get_cache('messagecount');
    
    // return cached value
    if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
      return $a_mailbox_cache[$mailbox][$mode];
    if (!is_array($a_mailbox_cache[$mailbox]))
      $a_mailbox_cache[$mailbox] = array();
    if ($mode == 'THREADS')
      $count = $this->_threadcount($mailbox);
    // RECENT count is fetched a bit different
    if ($mode == 'RECENT')
    else if ($mode == 'RECENT')
       $count = iil_C_CheckForRecent($this->conn, $mailbox);
    // use SEARCH for message counting
@@ -508,24 +552,43 @@
      // not very performant but more precise (using UNDELETED)
      $index = $this->_search_index($mailbox, $search_str);
      $count = is_array($index) ? count($index) : 0;
      if ($mode == 'ALL')
        $_SESSION['maxuid'][$mailbox] = $index ? $this->_id2uid(max($index)) : 0;
      }
    else
      {
    else {
      if ($mode == 'UNSEEN')
        $count = iil_C_CountUnseen($this->conn, $mailbox);
      else
      else {
        $count = iil_C_CountMessages($this->conn, $mailbox);
        $_SESSION['maxuid'][$mailbox] = $count ? $this->_id2uid($count) : 0;
      }
    }
    if (!is_array($a_mailbox_cache[$mailbox]))
      $a_mailbox_cache[$mailbox] = array();
    $a_mailbox_cache[$mailbox][$mode] = (int)$count;
    // write back to cache
    $this->update_cache('messagecount', $a_mailbox_cache);
    return (int)$count;
    }
  /**
   * Private method for getting nr of threads
   *
   * @access  private
   * @see     rcube_imap::messagecount()
   */
  private function _threadcount($mailbox)
    {
    if (!empty($this->icache['threads']))
      return count($this->icache['threads']['tree']);
    list ($thread_tree, $msg_depth, $has_children) = $this->_fetch_threads($mailbox);
//    $this->update_thread_cache($mailbox, $thread_tree, $msg_depth, $has_children);
    return count($thread_tree);
    }
@@ -554,7 +617,7 @@
   * @access  private
   * @see     rcube_imap::list_headers
   */
  private function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=FALSE, $slice=0)
  private function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
    {
    if (!strlen($mailbox))
      return array();
@@ -562,6 +625,9 @@
    // use saved message set
    if ($this->search_string && $mailbox == $this->mailbox)
      return $this->_list_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
    if ($this->threading)
      return $this->_list_thread_headers($mailbox, $page, $sort_field, $sort_order, $recursive, $slice);
    $this->_set_sort_order($sort_field, $sort_order);
@@ -583,31 +649,55 @@
    else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
      {
      $this->sync_header_index($mailbox);
      return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, TRUE, $slice);
      return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, true, $slice);
      }
    // retrieve headers from IMAP
    $a_msg_headers = array();
    if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
    // use message index sort as default sorting (for better performance)
    if (!$this->sort_field)
      {
      list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
      $max = max($msg_index);
      $msg_index = array_slice($msg_index, $begin, $end-$begin);
        if ($this->skip_deleted) {
          // @TODO: this could be cached
          if ($msg_index = $this->_search_index($mailbox, 'ALL UNDELETED')) {
            $max = max($msg_index);
            list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
            $msg_index = array_slice($msg_index, $begin, $end-$begin);
          }
        }
        else if ($max = iil_C_CountMessages($this->conn, $mailbox)) {
          list($begin, $end) = $this->_get_message_range($max, $page);
          $msg_index = range($begin+1, $end);
        }
        else
          $msg_index = array();
      if ($slice)
        $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
        if ($slice)
          $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
      // fetch reqested headers from server
      $this->_fetch_headers($mailbox, join(',', $msg_index), $a_msg_headers, $cache_key);
        // fetch reqested headers from server
        if ($msg_index)
          $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
      }
    else
    // use SORT command
    else if ($this->get_capability('SORT'))
      {
      $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted);
      if (empty($a_index))
        return array();
      if ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) {
        list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
        $max = max($msg_index);
        $msg_index = array_slice($msg_index, $begin, $end-$begin);
        if ($slice)
          $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
        // fetch reqested headers from server
        $this->_fetch_headers($mailbox, join(',', $msg_index), $a_msg_headers, $cache_key);
        }
      }
    // fetch specified header for all messages and sort
    else if ($a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted))
      {
      asort($a_index); // ASC
      $msg_index = array_keys($a_index);
      $max = max($msg_index);
@@ -645,6 +735,140 @@
  /**
   * Private method for listing message headers using threads
   *
   * @access  private
   * @see     rcube_imap::list_headers
   */
  private function _list_thread_headers($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=false, $slice=0)
    {
    $this->_set_sort_order($sort_field, $sort_order);
    $page = $page ? $page : $this->list_page;
//    $cache_key = $mailbox.'.msg';
//    $cache_status = $this->check_cache_status($mailbox, $cache_key);
    // get all threads (default sort order)
    list ($thread_tree, $msg_depth, $has_children) = $this->_fetch_threads($mailbox);
    if (empty($thread_tree))
      return array();
    $msg_index = $this->_sort_threads($mailbox, $thread_tree);
    return $this->_fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children,
      $msg_index, $page, $slice);
    }
  /**
   * Private method for fetching threads data
   *
   * @param   string   Mailbox/folder name
   * @return  array    Array with thread data
   * @access  private
   */
  private function _fetch_threads($mailbox)
    {
    if (empty($this->icache['threads'])) {
      // get all threads
      list ($thread_tree, $msg_depth, $has_children) = iil_C_Thread($this->conn,
        $mailbox, $this->threading, $this->skip_deleted ? 'UNDELETED' : '');
      // add to internal (fast) cache
      $this->icache['threads'] = array();
      $this->icache['threads']['tree'] = $thread_tree;
      $this->icache['threads']['depth'] = $msg_depth;
      $this->icache['threads']['has_children'] = $has_children;
      }
    return array(
      $this->icache['threads']['tree'],
      $this->icache['threads']['depth'],
      $this->icache['threads']['has_children'],
      );
    }
  /**
   * Private method for fetching threaded messages headers
   *
   * @access  private
   */
  private function _fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0)
    {
    $cache_key = $mailbox.'.msg';
    // now get IDs for current page
    list($begin, $end) = $this->_get_message_range(count($msg_index), $page);
    $msg_index = array_slice($msg_index, $begin, $end-$begin);
    if ($slice)
      $msg_index = array_slice($msg_index, ($this->sort_order == 'DESC' ? 0 : -$slice), $slice);
    if ($this->sort_order == 'DESC')
      $msg_index = array_reverse($msg_index);
    // flatten threads array
    // @TODO: fetch children only in expanded mode
    $all_ids = array();
    foreach($msg_index as $root) {
      $all_ids[] = $root;
      if (!empty($thread_tree[$root]))
        $all_ids = array_merge($all_ids, array_keys_recursive($thread_tree[$root]));
      }
    // fetch reqested headers from server
    $this->_fetch_headers($mailbox, $all_ids, $a_msg_headers, $cache_key);
    // return empty array if no messages found
    if (!is_array($a_msg_headers) || empty($a_msg_headers))
      return array();
    // use this class for message sorting
    $sorter = new rcube_header_sorter();
    $sorter->set_sequence_numbers($all_ids);
    $sorter->sort_headers($a_msg_headers);
    // Set depth, has_children and unread_children fields in headers
    $this->_set_thread_flags($a_msg_headers, $msg_depth, $has_children);
    return array_values($a_msg_headers);
    }
  /**
   * Private method for setting threaded messages flags:
   * depth, has_children and unread_children
   *
   * @param  array   Reference to headers array indexed by message ID
   * @param  array   Array of messages depth indexed by message ID
   * @param  array   Array of messages children flags indexed by message ID
   * @return array   Message headers array indexed by message ID
   * @access private
   */
  private function _set_thread_flags(&$headers, $msg_depth, $msg_children)
    {
    $parents = array();
    foreach ($headers as $idx => $header) {
      $id = $header->id;
      $depth = $msg_depth[$id];
      $parents = array_slice($parents, 0, $depth);
      if (!empty($parents)) {
        $headers[$idx]->parent_uid = end($parents);
        if (!$header->seen)
          $headers[$parents[0]]->unread_children++;
        }
      array_push($parents, $header->uid);
      $headers[$idx]->depth = $depth;
      $headers[$idx]->has_children = $msg_children[$id];
      }
    }
  /**
   * Private method for listing a set of message headers (search results)
   *
   * @param   string   Mailbox/folder name
@@ -661,6 +885,14 @@
    if (!strlen($mailbox) || empty($this->search_set))
      return array();
    // use saved messages from searching
    if ($this->threading)
      return $this->_list_thread_header_set($mailbox, $page, $sort_field, $sort_order, $slice);
    // search set is threaded, we need a new one
    if ($this->search_threads)
      $this->search('', $this->search_string, $this->search_charset, $sort_field);
    $msgs = $this->search_set;
    $a_msg_headers = array();
    $page = $page ? $page : $this->list_page;
@@ -668,14 +900,35 @@
    $this->_set_sort_order($sort_field, $sort_order);
    // quickest method (default sorting)
    if (!$this->search_sort_field && !$this->sort_field)
      {
      if ($sort_order == 'DESC')
        $msgs = array_reverse($msgs);
      // get messages uids for one page
      $msgs = array_slice(array_values($msgs), $start_msg, min(count($msgs)-$start_msg, $this->page_size));
      if ($slice)
        $msgs = array_slice($msgs, -$slice, $slice);
      // fetch headers
      $this->_fetch_headers($mailbox, join(',',$msgs), $a_msg_headers, NULL);
      // I didn't found in RFC that FETCH always returns messages sorted by index
      $sorter = new rcube_header_sorter();
      $sorter->set_sequence_numbers($msgs);
      $sorter->sort_headers($a_msg_headers);
      return array_values($a_msg_headers);
      }
    // sorted messages, so we can first slice array and then fetch only wanted headers
    if ($this->get_capability('sort')) // SORT searching result
    if ($this->get_capability('SORT')) // SORT searching result
      {
      // reset search set if sorting field has been changed
      if ($this->sort_field && $this->search_sort_field != $this->sort_field)
        {
        $msgs = $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
        }
      // return empty array if no messages found
      if (empty($msgs))
@@ -699,16 +952,17 @@
      return array_values($a_msg_headers);
      }
    else { // SEARCH searching result, need sorting
    else { // SEARCH result, need sorting
      $cnt = count($msgs);
      if ($cnt > 300 && $cnt > $this->page_size) { // experimantal value for best result
      // 300: experimantal value for best result
      if (($cnt > 300 && $cnt > $this->page_size) || !$this->sort_field) {
        // use memory less expensive (and quick) method for big result set
   $a_index = $this->message_index('', $this->sort_field, $this->sort_order);
        $a_index = $this->message_index('', $this->sort_field, $this->sort_order);
        // get messages uids for one page...
        $msgs = array_slice($a_index, $start_msg, min($cnt-$start_msg, $this->page_size));
        if ($slice)
          $msgs = array_slice($msgs, -$slice, $slice);
   // ...and fetch headers
        // ...and fetch headers
        $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
        // return empty array if no messages found
@@ -720,7 +974,7 @@
        $sorter->sort_headers($a_msg_headers);
        return array_values($a_msg_headers);
        }
      }
      else {
        // for small result set we can fetch all messages headers
        $this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
@@ -731,15 +985,49 @@
        // if not already sorted
        $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
        // only return the requested part of the set
   $a_msg_headers = array_slice(array_values($a_msg_headers), $start_msg, min($cnt-$start_msg, $this->page_size));
        $a_msg_headers = array_slice(array_values($a_msg_headers), $start_msg, min($cnt-$start_msg, $this->page_size));
        if ($slice)
          $a_msg_headers = array_slice($a_msg_headers, -$slice, $slice);
        return $a_msg_headers;
        }
      }
    }
  /**
   * Private method for listing a set of threaded message headers (search results)
   *
   * @param   string   Mailbox/folder name
   * @param   int      Current page to list
   * @param   string   Header field to sort by
   * @param   string   Sort order [ASC|DESC]
   * @param   boolean  Number of slice items to extract from result array
   * @return  array    Indexed array with message header objects
   * @access  private
   * @see     rcube_imap::list_header_set()
   */
  private function _list_thread_header_set($mailbox, $page=NULL, $sort_field=NULL, $sort_order=NULL, $slice=0)
    {
    // update search_set if previous data was fetched with disabled threading
    if (!$this->search_threads)
      $this->search('', $this->search_string, $this->search_charset, $sort_field);
    $thread_tree = $this->search_set['tree'];
    $msg_depth = $this->search_set['depth'];
    $has_children = $this->search_set['children'];
    $a_msg_headers = array();
    $page = $page ? $page : $this->list_page;
    $start_msg = ($page-1) * $this->page_size;
    $this->_set_sort_order($sort_field, $sort_order);
    $msg_index = $this->_sort_threads($mailbox, $thread_tree, array_keys($msg_depth));
    return $this->_fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0);
    }
@@ -795,35 +1083,54 @@
    // fetch reqested headers from server
    $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs, false, false, $this->fetch_add_headers);
    if (!empty($a_header_index))
      {
      // cache is incomplete
      $cache_index = $this->get_message_cache_index($cache_key);
      foreach ($a_header_index as $i => $headers)
        {
/*
        if ($headers->deleted && $this->skip_deleted)
          {
          // delete from cache
          if ($cache_index[$headers->id] && $cache_index[$headers->id] == $headers->uid)
            $this->remove_message_cache($cache_key, $headers->uid);
    if (empty($a_header_index))
      return 0;
          continue;
    // cache is incomplete
    $cache_index = $this->get_message_cache_index($cache_key);
    foreach ($a_header_index as $i => $headers) {
      if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid) {
        // prevent index duplicates
        if ($cache_index[$headers->id]) {
          $this->remove_message_cache($cache_key, $headers->id, true);
          unset($cache_index[$headers->id]);
          }
*/
        // add message to cache
        if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid)
          $this->add_message_cache($cache_key, $headers->id, $headers, NULL,
      !in_array((string)$headers->uid, $cache_index, true));
        $a_msg_headers[$headers->uid] = $headers;
        $this->add_message_cache($cache_key, $headers->id, $headers, NULL,
          !in_array($headers->uid, $cache_index));
        }
      $a_msg_headers[$headers->uid] = $headers;
      }
    return count($a_msg_headers);
    }
  /**
   * Fetches IDS of pseudo recent messages.
   *
   * We compare the maximum UID to determine the number of
   * new messages because the RECENT flag is not reliable.
   *
   * @param string  Mailbox/folder name
   * @return array  List of recent message UIDs
   */
  function recent_uids($mbox_name = null, $nofetch = false)
  {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $old_maxuid = intval($_SESSION['maxuid'][$mailbox]);
    
    // refresh message count -> will update $_SESSION['maxuid'][$mailbox]
    $this->_messagecount($mailbox, 'ALL', true);
    if ($_SESSION['maxuid'][$mailbox] > $old_maxuid) {
      $maxuid = max(1, $old_maxuid+1);
      return array_values((array)iil_C_FetchHeaderIndex($this->conn, $mailbox, "$maxuid:*", 'UID', $this->skip_deleted, true));
    }
    return array();
  }
  
  /**
   * Return sorted array of message IDs (not UIDs)
@@ -835,18 +1142,36 @@
   */
  function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
    {
    if ($this->threading)
      return $this->thread_index($mbox_name, $sort_field, $sort_order);
    $this->_set_sort_order($sort_field, $sort_order);
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.msgi";
    // we have a saved search result. get index from there
    if (!isset($this->cache[$key]) && $this->search_string && $mailbox == $this->mailbox)
    // we have a saved search result, get index from there
    if (!isset($this->cache[$key]) && $this->search_string
      && !$this->search_threads && $mailbox == $this->mailbox)
    {
      $this->cache[$key] = array();
      
      if ($this->get_capability('sort'))
        {
      // use message index sort as default sorting
      if (!$this->sort_field)
      {
        $msgs = $this->search_set;
        if ($this->search_sort_field != 'date')
          sort($msgs);
        if ($this->sort_order == 'DESC')
          $this->cache[$key] = array_reverse($msgs);
        else
          $this->cache[$key] = $msgs;
      }
      // sort with SORT command
      else if ($this->get_capability('SORT'))
      {
        if ($this->sort_field && $this->search_sort_field != $this->sort_field)
          $this->search('', $this->search_string, $this->search_charset, $this->sort_field);
@@ -854,10 +1179,11 @@
          $this->cache[$key] = array_reverse($this->search_set);
        else
          $this->cache[$key] = $this->search_set;
        }
      }
      else
        {
        $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
      {
        $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox,
     join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
        if ($this->sort_order=="ASC")
          asort($a_index);
@@ -865,7 +1191,7 @@
          arsort($a_index);
        $this->cache[$key] = array_keys($a_index);
   }
      }
    }
    // have stored it in RAM
@@ -879,22 +1205,35 @@
    // cache is OK
    if ($cache_status>0)
      {
      $a_index = $this->get_message_cache_index($cache_key, TRUE, $this->sort_field, $this->sort_order);
      $a_index = $this->get_message_cache_index($cache_key, true, $this->sort_field, $this->sort_order);
      return array_keys($a_index);
      }
    // fetch complete message index
    if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
    // use message index sort as default sorting
    if (!$this->sort_field)
      {
      if ($this->skip_deleted) {
        $a_index = $this->_search_index($mailbox, 'ALL');
      } else if ($max = $this->_messagecount($mailbox)) {
        $a_index = range(1, $max);
      }
      if ($this->sort_order == 'DESC')
        $a_index = array_reverse($a_index);
      $this->cache[$key] = $a_index;
      }
    else
    // fetch complete message index
    else if ($this->get_capability('SORT'))
      {
      $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted);
      if ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) {
        if ($this->sort_order == 'DESC')
          $a_index = array_reverse($a_index);
        $this->cache[$key] = $a_index;
   }
      }
    else if ($a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
      if ($this->sort_order=="ASC")
        asort($a_index);
      else if ($this->sort_order=="DESC")
@@ -908,9 +1247,90 @@
  /**
   * Return sorted array of threaded message IDs (not UIDs)
   *
   * @param string Mailbox to get index from
   * @param string Sort column
   * @param string Sort order [ASC, DESC]
   * @return array Indexed array with message IDs
   */
  function thread_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
    {
    $this->_set_sort_order($sort_field, $sort_order);
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $key = "{$mailbox}:{$this->sort_field}:{$this->sort_order}:{$this->search_string}.thi";
    // we have a saved search result, get index from there
    if (!isset($this->cache[$key]) && $this->search_string
      && $this->search_threads && $mailbox == $this->mailbox)
    {
      // use message IDs for better performance
      $ids = array_keys_recursive($this->search_set['tree']);
      $this->cache[$key] = $this->_flatten_threads($mailbox, $this->search_set['tree'], $ids);
    }
    // have stored it in RAM
    if (isset($this->cache[$key]))
      return $this->cache[$key];
/*
    // check local cache
    $cache_key = $mailbox.'.msg';
    $cache_status = $this->check_cache_status($mailbox, $cache_key);
    // cache is OK
    if ($cache_status>0)
      {
      $a_index = $this->get_message_cache_index($cache_key, true, $this->sort_field, $this->sort_order);
      return array_keys($a_index);
      }
*/
    // get all threads (default sort order)
    list ($thread_tree) = $this->_fetch_threads($mailbox);
    $this->cache[$key] = $this->_flatten_threads($mailbox, $thread_tree);
    return $this->cache[$key];
    }
  /**
   * Return array of threaded messages (all, not only roots)
   *
   * @param string Mailbox to get index from
   * @param array  Threaded messages array (see _fetch_threads())
   * @param array  Message IDs if we know what we need (e.g. search result)
   *               for better performance
   * @return array Indexed array with message IDs
   *
   * @access private
   */
  function sync_header_index($mailbox)
  private function _flatten_threads($mailbox, $thread_tree, $ids=null)
    {
    if (empty($thread_tree))
      return array();
    $msg_index = $this->_sort_threads($mailbox, $thread_tree, $ids);
    if ($this->sort_order == 'DESC')
      $msg_index = array_reverse($msg_index);
    // flatten threads array
    $all_ids = array();
    foreach($msg_index as $root) {
      $all_ids[] = $root;
      if (!empty($thread_tree[$root]))
        $all_ids = array_merge($all_ids, array_keys_recursive($thread_tree[$root]));
      }
    return $all_ids;
    }
  /**
   * @access private
   */
  private function sync_header_index($mailbox)
    {
    $cache_key = $mailbox.'.msg';
    $cache_index = $this->get_message_cache_index($cache_key);
@@ -931,7 +1351,7 @@
        }
        
      // message in cache but in wrong position
      if (in_array((string)$uid, $cache_index, TRUE))
      if (in_array((string)$uid, $cache_index, true))
        {
        unset($cache_index[$id]);
        }
@@ -939,11 +1359,11 @@
      // other message at this position
      if (isset($cache_index[$id]))
        {
   $for_remove[] = $cache_index[$id];
        $for_remove[] = $cache_index[$id];
        unset($cache_index[$id]);
        }
        
   $for_update[] = $id;
        $for_update[] = $id;
      }
    // clear messages at wrong positions and those deleted that are still in cache_index      
@@ -958,7 +1378,7 @@
      if ($headers = iil_C_FetchHeader($this->conn, $mailbox, join(',', $for_update), false, $this->fetch_add_headers))
        foreach ($headers as $header)
          $this->add_message_cache($cache_key, $header->id, $header, NULL,
      in_array((string)$header->uid, (array)$for_remove, true));
            in_array($header->uid, (array)$for_remove));
      }
    }
@@ -985,30 +1405,30 @@
    // try search with US-ASCII charset (should be supported by server)
    // only if UTF-8 search is not supported
    if (empty($results) && !is_array($results) && !empty($charset) && $charset != 'US-ASCII')
    {
      // convert strings to US_ASCII
      if(preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE))
      {
   // convert strings to US_ASCII
        if(preg_match_all('/\{([0-9]+)\}\r\n/', $str, $matches, PREG_OFFSET_CAPTURE))
     {
     $last = 0; $res = '';
     foreach($matches[1] as $m)
       {
       $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
       $string = substr($str, $string_offset - 1, $m[0]);
       $string = rcube_charset_convert($string, $charset, 'US-ASCII');
       if (!$string) continue;
       $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
       $last = $m[0] + $string_offset - 1;
       }
       if ($last < strlen($str))
         $res .= substr($str, $last, strlen($str)-$last);
     }
   else // strings for conversion not found
     $res = $str;
   $results = $this->search($mbox_name, $res, NULL, $sort_field);
        $last = 0; $res = '';
        foreach($matches[1] as $m)
        {
          $string_offset = $m[1] + strlen($m[0]) + 4; // {}\r\n
          $string = substr($str, $string_offset - 1, $m[0]);
          $string = rcube_charset_convert($string, $charset, 'US-ASCII');
          if (!$string) continue;
          $res .= sprintf("%s{%d}\r\n%s", substr($str, $last, $m[1] - $last - 1), strlen($string), $string);
          $last = $m[0] + $string_offset - 1;
        }
        if ($last < strlen($str))
          $res .= substr($str, $last, strlen($str)-$last);
      }
      else // strings for conversion not found
      $res = $str;
    $this->set_search_set($str, $results, $charset, $sort_field);
      $results = $this->search($mbox_name, $res, NULL, $sort_field);
    }
    $this->set_search_set($str, $results, $charset, $sort_field, (bool)$this->threading);
    return $results;
    }
@@ -1028,14 +1448,39 @@
    if ($this->skip_deleted && !preg_match('/UNDELETED/', $criteria))
      $criteria = 'UNDELETED '.$criteria;
    if ($sort_field && $this->get_capability('sort'))
      {
      $charset = $charset ? $charset : $this->default_charset;
      $a_messages = iil_C_Sort($this->conn, $mailbox, $sort_field, $criteria, FALSE, $charset);
    if ($this->threading) {
      list ($thread_tree, $msg_depth, $has_children) = iil_C_Thread($this->conn,
            $mailbox, $this->threading, $criteria, $charset);
      $a_messages = array(
        'tree'    => $thread_tree,
   'depth'   => $msg_depth,
   'children' => $has_children
        );
      }
    else
      $a_messages = iil_C_Search($this->conn, $mailbox, ($charset ? "CHARSET $charset " : '') . $criteria);
    else if ($sort_field && $this->get_capability('SORT')) {
      $charset = $charset ? $charset : $this->default_charset;
      $a_messages = iil_C_Sort($this->conn, $mailbox, $sort_field, $criteria, false, $charset);
      if (!$a_messages)
   return array();
      }
    else {
      if ($orig_criteria == 'ALL') {
        $max = $this->_messagecount($mailbox);
        $a_messages = $max ? range(1, $max) : array();
        }
      else {
        $a_messages = iil_C_Search($this->conn, $mailbox, ($charset ? "CHARSET $charset " : '') . $criteria);
   if (!$a_messages)
     return array();
        // I didn't found that SEARCH always returns sorted IDs
        if (!$this->sort_field)
          sort($a_messages);
        }
      }
    // update messagecount cache ?
//    $a_mailbox_cache = get_cache('messagecount');
//    $a_mailbox_cache[$mailbox][$criteria] = sizeof($a_messages);
@@ -1046,6 +1491,99 @@
    
  
  /**
   * Sort thread
   *
   * @param string Mailbox name
   * @param  array Unsorted thread tree (iil_C_Thread() result)
   * @param  array Message IDs if we know what we need (e.g. search result)
   * @return array Sorted roots IDs
   * @access private
   */
  private function _sort_threads($mailbox, $thread_tree, $ids=NULL)
    {
    // THREAD=ORDEREDSUBJECT:    sorting by sent date of root message
    // THREAD=REFERENCES:    sorting by sent date of root message
    // THREAD=REFS:       sorting by the most recent date in each thread
    // default sorting
    if (!$this->sort_field || ($this->sort_field == 'date' && $this->threading == 'REFS')) {
        return array_keys((array)$thread_tree);
      }
    // here we'll implement REFS sorting, for performance reason
    else { // ($sort_field == 'date' && $this->threading != 'REFS')
      // use SORT command
      if ($this->get_capability('SORT')) {
        $a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field,
       !empty($ids) ? $ids : ($this->skip_deleted ? 'UNDELETED' : ''));
   // return unsorted tree if we've got no index data
   if (!$a_index)
     return array_keys((array)$thread_tree);
        }
      else {
        // fetch specified headers for all messages and sort them
        $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, !empty($ids) ? $ids : "1:*",
       $this->sort_field, $this->skip_deleted);
   // return unsorted tree if we've got no index data
   if (!$a_index)
     return array_keys((array)$thread_tree);
        asort($a_index); // ASC
   $a_index = array_values($a_index);
        }
   return $this->_sort_thread_refs($thread_tree, $a_index);
      }
    }
  /**
   * THREAD=REFS sorting implementation
   *
   * @param  array   Thread tree array (message identifiers as keys)
   * @param  array   Array of sorted message identifiers
   * @return array   Array of sorted roots messages
   * @access private
   */
  private function _sort_thread_refs($tree, $index)
    {
    if (empty($tree))
      return array();
    $index = array_combine(array_values($index), $index);
    // assign roots
    foreach ($tree as $idx => $val) {
      $index[$idx] = $idx;
      if (!empty($val)) {
        $idx_arr = array_keys_recursive($tree[$idx]);
        foreach ($idx_arr as $subidx)
          $index[$subidx] = $idx;
        }
      }
    $index = array_values($index);
    // create sorted array of roots
    $msg_index = array();
    if ($this->sort_order != 'DESC') {
      foreach ($index as $idx)
        if (!isset($msg_index[$idx]))
          $msg_index[$idx] = $idx;
      $msg_index = array_values($msg_index);
      }
    else {
      for ($x=count($index)-1; $x>=0; $x--)
        if (!isset($msg_index[$index[$x]]))
          $msg_index[$index[$x]] = $index[$x];
      $msg_index = array_reverse($msg_index);
      }
    return $msg_index;
    }
  /**
   * Refresh saved search set
   *
   * @return array Current search set
@@ -1053,7 +1591,8 @@
  function refresh_search()
    {
    if (!empty($this->search_string))
      $this->search_set = $this->search('', $this->search_string, $this->search_charset, $this->search_sort_field);
      $this->search_set = $this->search('', $this->search_string, $this->search_charset,
           $this->search_sort_field, $this->search_threads);
      
    return $this->get_search_set();
    }
@@ -1082,7 +1621,7 @@
   * @param boolean True if we need also BODYSTRUCTURE in headers
   * @return object Message headers representation
   */
  function get_headers($id, $mbox_name=NULL, $is_uid=TRUE, $bodystr=FALSE)
  function get_headers($id, $mbox_name=NULL, $is_uid=true, $bodystr=false)
    {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $uid = $is_uid ? $id : $this->_id2uid($id);
@@ -1141,6 +1680,16 @@
      else
        $this->struct_charset = $this->_structure_charset($structure);
      // Here we can recognize malformed BODYSTRUCTURE and
      // 1. [@TODO] parse the message in other way to create our own message structure
      // 2. or just show the raw message body.
      // Example of structure for malformed MIME message:
      // ("text" "plain" ("charset" "us-ascii") NIL NIL "7bit" 2154 70 NIL NIL NIL)
      if ($headers->ctype && $headers->ctype != 'text/plain'
          && $structure[0] == 'text' && $structure[1] == 'plain') {
        return false;
      }
      $struct = &$this->_structure_part($structure);
      $struct->headers = get_object_vars($headers);
@@ -1166,7 +1715,7 @@
   *
   * @access private
   */
  function &_structure_part($part, $count=0, $parent='', $raw_headers=null)
  function &_structure_part($part, $count=0, $parent='', $mime_headers=null, $raw_headers=null)
    {
    $struct = new rcube_message_part;
    $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
@@ -1188,28 +1737,43 @@
      // build parts list for headers pre-fetching
      for ($i=0, $count=0; $i<count($part); $i++)
        if (is_array($part[$i]) && count($part[$i]) > 3)
     // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
     if (strtolower($part[$i][0]) == 'message' ||
       (in_array('name', (array)$part[$i][2]) && (empty($part[$i][3]) || $part[$i][3]=='NIL'))) {
       $part_headers[] = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
       }
        if (is_array($part[$i]) && count($part[$i]) > 3) {
          // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
          if (!is_array($part[$i][0])) {
            $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
            if (strtolower($part[$i][0]) == 'message' && strtolower($part[$i][1]) == 'rfc822') {
              $raw_part_headers[] = $tmp_part_id;
              $mime_part_headers[] = $tmp_part_id;
            }
            else if (in_array('name', (array)$part[$i][2]) && (empty($part[$i][3]) || $part[$i][3]=='NIL')) {
              $mime_part_headers[] = $tmp_part_id;
            }
          }
        }
      // pre-fetch headers of all parts (in one command for better performance)
      if ($part_headers)
        $part_headers = iil_C_FetchMIMEHeaders($this->conn, $this->mailbox, $this->_msg_id, $part_headers);
      // @TODO: we could do this before _structure_part() call, to fetch
      // headers for parts on all levels
      if ($mime_part_headers)
        $mime_part_headers = iil_C_FetchMIMEHeaders($this->conn, $this->mailbox,
          $this->_msg_id, $mime_part_headers);
      // we'll need a real content-type of message/rfc822 part
      if ($raw_part_headers)
        $raw_part_headers = iil_C_FetchMIMEHeaders($this->conn, $this->mailbox,
          $this->_msg_id, $raw_part_headers, false);
      $struct->parts = array();
      for ($i=0, $count=0; $i<count($part); $i++)
        if (is_array($part[$i]) && count($part[$i]) > 3) {
          $tmp_part_id = $struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1;
          $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id,
      $part_headers[$struct->mime_id ? $struct->mime_id.'.'.($i+1) : $i+1]);
   }
            $mime_part_headers[$tmp_part_id], $raw_part_headers[$tmp_part_id]);
        }
      return $struct;
      }
    // regular part
    $struct->ctype_primary = strtolower($part[0]);
    $struct->ctype_secondary = strtolower($part[1]);
@@ -1270,18 +1834,30 @@
    
    // fetch message headers if message/rfc822 or named part (could contain Content-Location header)
    if ($struct->ctype_primary == 'message' || ($struct->ctype_parameters['name'] && !$struct->content_id)) {
      if (empty($raw_headers))
        $raw_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $struct->mime_id);
      $struct->headers = $this->_parse_headers($raw_headers) + $struct->headers;
    }
      if (empty($mime_headers))
        $mime_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $struct->mime_id);
      $struct->headers = $this->_parse_headers($mime_headers) + $struct->headers;
      // get real headers for message of type 'message/rfc822'
      if ($struct->mimetype == 'message/rfc822') {
        if (empty($raw_headers))
          $raw_headers = iil_C_FetchMIMEHeaders($this->conn, $this->mailbox, $this->_msg_id, (array)$struct->mime_id, false);
        $struct->real_headers = $this->_parse_headers($raw_headers);
        // get real content-type of message/rfc822
        if (preg_match('/^([a-z0-9_\/-]+)/i', $struct->real_headers['content-type'], $matches)) {
          $struct->real_mimetype = strtolower($matches[1]);
          }
        }
      }
    if ($struct->ctype_primary=='message') {
      if (is_array($part[8]) && empty($struct->parts))
      if (is_array($part[8]) && $di != 8 && empty($struct->parts))
        $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
    }
      }
    // normalize filename property
    $this->_set_part_filename($struct, $raw_headers);
    $this->_set_part_filename($struct, $mime_headers);
    return $struct;
    }
@@ -1313,7 +1889,7 @@
      // some servers (eg. dovecot-1.x) have no support for parameter value continuations
      // we must fetch and parse headers "manually"
      if ($i<2) {
   if (!$headers)
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
        $filename_mime = '';
        $i = 0;
@@ -1330,7 +1906,7 @@
        $i++;
      }
      if ($i<2) {
   if (!$headers)
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
        $filename_encoded = '';
        $i = 0; $matches = array();
@@ -1347,7 +1923,7 @@
        $i++;
      }
      if ($i<2) {
   if (!$headers)
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
        $filename_mime = '';
        $i = 0; $matches = array();
@@ -1364,7 +1940,7 @@
        $i++;
      }
      if ($i<2) {
   if (!$headers)
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
        $filename_encoded = '';
        $i = 0; $matches = array();
@@ -1386,8 +1962,8 @@
    // decode filename
    if (!empty($filename_mime)) {
      $part->filename = rcube_imap::decode_mime_string($filename_mime, 
        $part->charset ? $part->charset : $this->struct_charset ? $this->struct_charset :
       rc_detect_encoding($filename_mime, $this->default_charset));
        $part->charset ? $part->charset : ($this->struct_charset ? $this->struct_charset :
          rc_detect_encoding($filename_mime, $this->default_charset)));
      } 
    else if (!empty($filename_encoded)) {
      // decode filename according to RFC 2231, Section 4
@@ -1410,10 +1986,10 @@
  function _structure_charset($structure)
    {
      while (is_array($structure)) {
   if (is_array($structure[2]) && $structure[2][0] == 'charset')
     return $structure[2][1];
   $structure = $structure[0];
   }
        if (is_array($structure[2]) && $structure[2][0] == 'charset')
          return $structure[2][1];
        $structure = $structure[0];
      }
    } 
@@ -1458,7 +2034,7 @@
    // convert charset (if text or message part)
    if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message') {
      // assume default if no charset specified
      if (empty($o_part->charset))
      if (empty($o_part->charset) || strtolower($o_part->charset) == 'us-ascii')
        $o_part->charset = $this->default_charset;
      $body = rcube_charset_convert($body, $o_part->charset);
@@ -1524,9 +2100,10 @@
   * @param mixed  Message UIDs as array or as comma-separated string
   * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
   * @param string Folder name
   * @param boolean True to skip message cache clean up
   * @return boolean True on success, False on failure
   */
  function set_flag($uids, $flag, $mbox_name=NULL)
  function set_flag($uids, $flag, $mbox_name=NULL, $skip_cache=false)
    {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
@@ -1534,24 +2111,15 @@
    if (!is_array($uids))
      $uids = explode(',',$uids);
      
    if ($flag=='UNDELETED')
      $result = iil_C_Undelete($this->conn, $mailbox, join(',', $uids));
    else if ($flag=='UNSEEN')
      $result = iil_C_Unseen($this->conn, $mailbox, join(',', $uids));
    else if ($flag=='UNFLAGGED')
      $result = iil_C_UnFlag($this->conn, $mailbox, join(',', $uids), 'FLAGGED');
    if (strpos($flag, 'UN') === 0)
      $result = iil_C_UnFlag($this->conn, $mailbox, join(',', $uids), substr($flag, 2));
    else
      $result = iil_C_Flag($this->conn, $mailbox, join(',', $uids), $flag);
    // reload message headers if cached
    if ($this->caching_enabled)
      {
    if ($this->caching_enabled && !$skip_cache) {
      $cache_key = $mailbox.'.msg';
      $this->remove_message_cache($cache_key, $uids);
      // close and re-open connection
      // this prevents connection problems with Courier
      $this->reconnect();
      }
    // set nr of messages that were flaged
@@ -1570,26 +2138,51 @@
  /**
   * Remove message flag for one or several messages
   *
   * @param mixed  Message UIDs as array or as comma-separated string
   * @param string Flag to unset: SEEN, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
   * @param string Folder name
   * @return boolean True on success, False on failure
   * @see set_flag
   */
  function unset_flag($uids, $flag, $mbox_name=NULL)
    {
    return $this->set_flag($uids, 'UN'.$flag, $mbox_name);
    }
  /**
   * Append a mail message (source) to a specific mailbox
   *
   * @param string Target mailbox
   * @param string Message source
   * @param string   Target mailbox
   * @param string   The message source string or filename
   * @param string   Headers string if $message contains only the body
   * @param boolean  True if $message is a filename
   *
   * @return boolean True on success, False on error
   */
  function save_message($mbox_name, &$message)
  function save_message($mbox_name, &$message, $headers='', $is_file=false)
    {
    $mailbox = $this->mod_mailbox($mbox_name);
    // make sure mailbox exists
    if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes()))
      $saved = iil_C_Append($this->conn, $mailbox, $message);
    if ($mailbox == 'INBOX' || $this->mailbox_exists($mbox_name)) {
      if ($is_file) {
        $separator = rcmail::get_instance()->config->header_delimiter();
        $saved = iil_C_AppendFromFile($this->conn, $mailbox, $message,
          $headers, $separator.$separator);
        }
      else
        $saved = iil_C_Append($this->conn, $mailbox, $message);
      }
    if ($saved)
      {
      // increase messagecount of the target mailbox
      $this->_set_messagecount($mailbox, 'ALL', 1);
      }
    return $saved;
    }
@@ -1603,56 +2196,120 @@
   * @return boolean True on success, False on error
   */
  function move_message($uids, $to_mbox, $from_mbox='')
    {
  {
    $fbox = $from_mbox;
    $tbox = $to_mbox;
    $to_mbox = $this->mod_mailbox($to_mbox);
    $from_mbox = $from_mbox ? $this->mod_mailbox($from_mbox) : $this->mailbox;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !in_array($to_mbox, $this->_list_mailboxes()))
      {
      if (in_array($to_mbox_in, $this->default_folders))
        $this->create_mailbox($to_mbox_in, TRUE);
      else
        return FALSE;
      }
    // convert the list of uids to array
    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
    // exit if no message uids are specified
    if (!is_array($a_uids) || empty($a_uids))
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox))
      {
      if (in_array($tbox, $this->default_folders))
        $this->create_mailbox($tbox, true);
      else
        return false;
      }
    // flag messages as read before moving them
    $config = rcmail::get_instance()->config;
    if ($config->get('read_when_deleted') && $tbox == $config->get('trash_mbox')) {
      // don't flush cache (4th argument)
      $this->set_flag($uids, 'SEEN', $fbox, true);
      }
    // move messages
    $iil_move = iil_C_Move($this->conn, join(',', $a_uids), $from_mbox, $to_mbox);
    $moved = !($iil_move === false || $iil_move < 0);
    // send expunge command in order to have the moved message
    // really deleted from the source mailbox
    if ($moved) {
      $this->_expunge($from_mbox, FALSE, $a_uids);
      $this->_expunge($from_mbox, false, $a_uids);
      $this->_clear_messagecount($from_mbox);
      $this->_clear_messagecount($to_mbox);
    }
    // moving failed
    else if (rcmail::get_instance()->config->get('delete_always', false)) {
      return iil_C_Delete($this->conn, $from_mbox, join(',', $a_uids));
    else if ($config->get('delete_always', false) && $tbox == $config->get('trash_mbox')) {
      $moved = $this->delete_message($a_uids, $fbox);
    }
    // remove message ids from search set
    if ($moved && $this->search_set && $from_mbox == $this->mailbox) {
      foreach ($a_uids as $uid)
        $a_mids[] = $this->_uid2id($uid, $from_mbox);
      $this->search_set = array_diff($this->search_set, $a_mids);
    if ($moved) {
      // unset threads internal cache
      unset($this->icache['threads']);
      // remove message ids from search set
      if ($this->search_set && $from_mbox == $this->mailbox) {
        // threads are too complicated to just remove messages from set
        if ($this->search_threads)
          $this->refresh_search();
        else {
          foreach ($a_uids as $uid)
            $a_mids[] = $this->_uid2id($uid, $from_mbox);
          $this->search_set = array_diff($this->search_set, $a_mids);
          }
        }
      // update cached message headers
      $cache_key = $from_mbox.'.msg';
      if ($start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
        // clear cache from the lowest index on
        $this->clear_message_cache($cache_key, $start_index);
       }
    }
    // update cached message headers
    $cache_key = $from_mbox.'.msg';
    if ($moved && $start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
      // clear cache from the lowest index on
      $this->clear_message_cache($cache_key, $start_index);
      }
    return $moved;
  }
  /**
   * Copy a message from one mailbox to another
   *
   * @param string List of UIDs to copy, separated by comma
   * @param string Target mailbox
   * @param string Source mailbox
   * @return boolean True on success, False on error
   */
  function copy_message($uids, $to_mbox, $from_mbox='')
  {
    $fbox = $from_mbox;
    $tbox = $to_mbox;
    $to_mbox = $this->mod_mailbox($to_mbox);
    $from_mbox = $from_mbox ? $this->mod_mailbox($from_mbox) : $this->mailbox;
    // convert the list of uids to array
    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
    // exit if no message uids are specified
    if (!is_array($a_uids) || empty($a_uids))
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox))
      {
      if (in_array($tbox, $this->default_folders))
        $this->create_mailbox($tbox, true);
      else
        return false;
      }
    // copy messages
    $iil_copy = iil_C_Copy($this->conn, join(',', $a_uids), $from_mbox, $to_mbox);
    $copied = !($iil_copy === false || $iil_copy < 0);
    if ($copied) {
      $this->_clear_messagecount($to_mbox);
    }
    return $copied;
  }
  /**
@@ -1663,7 +2320,7 @@
   * @return boolean True on success, False on error
   */
  function delete_message($uids, $mbox_name='')
    {
  {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    // convert the list of uids to array
@@ -1674,32 +2331,39 @@
      return false;
    $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_uids));
    // send expunge command in order to have the deleted message
    // really deleted from the mailbox
    if ($deleted)
      {
      $this->_expunge($mailbox, FALSE, $a_uids);
    if ($deleted) {
      // send expunge command in order to have the deleted message
      // really deleted from the mailbox
      $this->_expunge($mailbox, false, $a_uids);
      $this->_clear_messagecount($mailbox);
      unset($this->uid_id_map[$mailbox]);
      }
    // remove message ids from search set
    if ($deleted && $this->search_set && $mailbox == $this->mailbox) {
      foreach ($a_uids as $uid)
        $a_mids[] = $this->_uid2id($uid, $mailbox);
      $this->search_set = array_diff($this->search_set, $a_mids);
    }
    // remove deleted messages from cache
    $cache_key = $mailbox.'.msg';
    if ($deleted && $start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
      // clear cache from the lowest index on
      $this->clear_message_cache($cache_key, $start_index);
      // unset threads internal cache
      unset($this->icache['threads']);
      // remove message ids from search set
      if ($this->search_set && $mailbox == $this->mailbox) {
        // threads are too complicated to just remove messages from set
        if ($this->search_threads)
          $this->refresh_search();
        else {
          foreach ($a_uids as $uid)
            $a_mids[] = $this->_uid2id($uid, $mailbox);
          $this->search_set = array_diff($this->search_set, $a_mids);
          }
        }
      // remove deleted messages from cache
      $cache_key = $mailbox.'.msg';
      if ($start_index = $this->get_message_cache_index_min($cache_key, $a_uids)) {
        // clear cache from the lowest index on
        $this->clear_message_cache($cache_key, $start_index);
      }
    }
    return $deleted;
    }
  }
  /**
@@ -1740,7 +2404,7 @@
   * @param boolean False if cache should not be cleared
   * @return boolean True on success
   */
  function expunge($mbox_name='', $clear_cache=TRUE)
  function expunge($mbox_name='', $clear_cache=true)
    {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    return $this->_expunge($mailbox, $clear_cache);
@@ -1757,7 +2421,7 @@
   * @return boolean True on success
   * @access private
   */
  private function _expunge($mailbox, $clear_cache=TRUE, $uids=NULL)
  private function _expunge($mailbox, $clear_cache=true, $uids=NULL)
    {
    if ($uids && $this->get_capability('UIDPLUS')) 
      $a_uids = is_array($uids) ? join(',', $uids) : $uids;
@@ -1822,7 +2486,7 @@
    if ($this->get_capability('QUOTA'))
      return iil_C_GetQuota($this->conn);
   
    return FALSE;
    return false;
    }
@@ -1865,24 +2529,20 @@
   * @param boolean True if the new mailbox should be subscribed
   * @param string  Name of the created mailbox, false on error
   */
  function create_mailbox($name, $subscribe=FALSE)
  function create_mailbox($name, $subscribe=false)
    {
    $result = FALSE;
    $result = false;
    
    // reduce mailbox name to 100 chars
    $name = substr($name, 0, 100);
    $abs_name = $this->mod_mailbox($name);
    $a_mailbox_cache = $this->get_cache('mailboxes');
    if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
      $result = iil_C_CreateFolder($this->conn, $abs_name);
    $result = iil_C_CreateFolder($this->conn, $abs_name);
    // try to subscribe it
    if ($result && $subscribe)
      $this->subscribe($name);
    return $result ? $name : FALSE;
    return $result ? $name : false;
    }
@@ -1895,7 +2555,7 @@
   */
  function rename_mailbox($mbox_name, $new_name)
    {
    $result = FALSE;
    $result = false;
    // encode mailbox name and reduce it to 100 chars
    $name = substr($new_name, 0, 100);
@@ -1936,7 +2596,7 @@
    if ($result && $subscribed)
      iil_C_Subscribe($this->conn, $abs_name);
    return $result ? $name : FALSE;
    return $result ? $name : false;
    }
@@ -1948,19 +2608,19 @@
   */
  function delete_mailbox($mbox_name)
    {
    $deleted = FALSE;
    $deleted = false;
    if (is_array($mbox_name))
      $a_mboxes = $mbox_name;
    else if (is_string($mbox_name) && strlen($mbox_name))
      $a_mboxes = explode(',', $mbox_name);
    $all_mboxes = iil_C_ListMailboxes($this->conn, $this->mod_mailbox($root), '*');
    if (is_array($a_mboxes))
      foreach ($a_mboxes as $mbox_name)
        {
        $mailbox = $this->mod_mailbox($mbox_name);
        $sub_mboxes = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''),
     $mailbox . $this->delimiter . '*');
        // unsubscribe mailbox before deleting
        iil_C_UnSubscribe($this->conn, $mailbox);
@@ -1968,23 +2628,18 @@
        // send delete command to server
        $result = iil_C_DeleteFolder($this->conn, $mailbox);
        if ($result >= 0) {
          $deleted = TRUE;
          $deleted = true;
          $this->clear_message_cache($mailbox.'.msg');
     }
     
        foreach ($all_mboxes as $c_mbox)
          {
          $regex = preg_quote($mailbox . $this->delimiter, '/');
          $regex = '/^' . $regex . '/';
          if (preg_match($regex, $c_mbox))
            {
            iil_C_UnSubscribe($this->conn, $c_mbox);
            $result = iil_C_DeleteFolder($this->conn, $c_mbox);
            if ($result >= 0) {
              $deleted = TRUE;
             $this->clear_message_cache($c_mbox.'.msg');
              }
       }
        foreach ($sub_mboxes as $c_mbox)
          if ($c_mbox != 'INBOX') {
          iil_C_UnSubscribe($this->conn, $c_mbox);
          $result = iil_C_DeleteFolder($this->conn, $c_mbox);
          if ($result >= 0) {
            $deleted = true;
           $this->clear_message_cache($c_mbox.'.msg');
            }
          }
        }
@@ -2001,18 +2656,45 @@
   */
  function create_default_folders()
    {
    $a_folders = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''), '*');
    $a_subscribed = iil_C_ListSubscribed($this->conn, $this->mod_mailbox(''), '*');
    // create default folders if they do not exist
    foreach ($this->default_folders as $folder)
      {
      $abs_name = $this->mod_mailbox($folder);
      if (!in_array_nocase($abs_name, $a_folders))
        $this->create_mailbox($folder, TRUE);
      else if (!in_array_nocase($abs_name, $a_subscribed))
      if (!$this->mailbox_exists($folder))
        $this->create_mailbox($folder, true);
      else if (!$this->mailbox_exists($folder, true))
        $this->subscribe($folder);
      }
    }
  /**
   * Checks if folder exists and is subscribed
   *
   * @param string   Folder name
   * @param boolean  Enable subscription checking
   * @return boolean TRUE or FALSE
   */
  function mailbox_exists($mbox_name, $subscription=false)
    {
    if ($mbox_name) {
      if ($mbox_name == 'INBOX')
        return true;
      $mbox = $this->mod_mailbox($mbox_name);
      if ($subscription) {
        if ($a_folders = iil_C_ListSubscribed($this->conn, $this->mod_mailbox(''), $mbox))
          return true;
        }
      else {
        $a_folders = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''), $mbox);
   if (is_array($a_folders) && in_array($mbox, $a_folders))
          return true;
        }
      }
    return false;
    }
@@ -2027,9 +2709,9 @@
  function set_caching($set)
    {
    if ($set && is_object($this->db))
      $this->caching_enabled = TRUE;
      $this->caching_enabled = true;
    else
      $this->caching_enabled = FALSE;
      $this->caching_enabled = false;
    }
  /**
@@ -2037,8 +2719,8 @@
   */
  function get_cache($key)
    {
    // read cache
    if (!isset($this->cache[$key]) && $this->caching_enabled)
    // read cache (if it was not read before)
    if (!count($this->cache) && $this->caching_enabled)
      {
      return $this->_read_cache_record($key);
      }
@@ -2052,8 +2734,8 @@
  function update_cache($key, $data)
    {
    $this->cache[$key] = $data;
    $this->cache_changed = TRUE;
    $this->cache_changes[$key] = TRUE;
    $this->cache_changed = true;
    $this->cache_changes[$key] = true;
    }
  /**
@@ -2085,13 +2767,13 @@
        $this->_clear_cache_record($key);
      $this->cache = array();
      $this->cache_changed = FALSE;
      $this->cache_changed = false;
      $this->cache_changes = array();
      }
    else
      {
      $this->_clear_cache_record($key);
      $this->cache_changes[$key] = FALSE;
      $this->cache_changes[$key] = false;
      unset($this->cache[$key]);
      }
    }
@@ -2115,7 +2797,8 @@
        {
   $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
        $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
   $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : FALSE;
   if (!isset($this->cache[$sql_key]))
     $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : false;
        }
      }
@@ -2128,24 +2811,7 @@
  private function _write_cache_record($key, $data)
    {
    if (!$this->db)
      return FALSE;
    // check if we already have a cache entry for this key
    if (!isset($this->cache_keys[$key]))
      {
      $sql_result = $this->db->query(
        "SELECT cache_id
         FROM ".get_table_name('cache')."
         WHERE  user_id=?
         AND    cache_key=?",
        $_SESSION['user_id'],
        'IMAP.'.$key);
      if ($sql_arr = $this->db->fetch_assoc($sql_result))
        $this->cache_keys[$key] = $sql_arr['cache_id'];
      else
        $this->cache_keys[$key] = FALSE;
      }
      return false;
    // update existing cache record
    if ($this->cache_keys[$key])
@@ -2169,6 +2835,18 @@
        $_SESSION['user_id'],
        'IMAP.'.$key,
        $data);
      // get cache entry ID for this key
      $sql_result = $this->db->query(
        "SELECT cache_id
         FROM ".get_table_name('cache')."
         WHERE  user_id=?
         AND    cache_key=?",
        $_SESSION['user_id'],
        'IMAP.'.$key);
        if ($sql_arr = $this->db->fetch_assoc($sql_result))
          $this->cache_keys[$key] = $sql_arr['cache_id'];
      }
    }
@@ -2183,6 +2861,8 @@
       AND    cache_key=?",
      $_SESSION['user_id'],
      'IMAP.'.$key);
    unset($this->cache_keys[$key]);
    }
@@ -2197,18 +2877,26 @@
   *
   * @param string Mailbox name
   * @param string Internal cache key
   * @return int -3 = off, -2 = incomplete, -1 = dirty
   * @return int   Cache status: -3 = off, -2 = incomplete, -1 = dirty
   */
  private function check_cache_status($mailbox, $cache_key)
  {
    if (!$this->caching_enabled)
      return -3;
    $cache_index = $this->get_message_cache_index($cache_key, TRUE);
    $cache_index = $this->get_message_cache_index($cache_key);
    $msg_count = $this->_messagecount($mailbox);
    $cache_count = count($cache_index);
    // console("Cache check: $msg_count !== ".count($cache_index));
    // empty mailbox
    if (!$msg_count)
      return $cache_count ? -2 : 1;
    // @TODO: We've got one big performance problem in cache status checking method
    // E.g. mailbox contains 1000 messages, in cache table we've got first 100
    // of them. Now if we want to display only that 100 (which we've got)
    // check_cache_status returns 'incomplete' and messages are fetched
    // from IMAP instead of DB.
    if ($cache_count==$msg_count) {
      if ($this->skip_deleted) {
@@ -2224,12 +2912,12 @@
   }
   return -2;
      } else {
        // get highest index
        $header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
        // get UID of message with highest index
        $uid = iil_C_ID2UID($this->conn, $mailbox, $msg_count);
        $cache_uid = array_pop($cache_index);
      
        // uids of highest message matches -> cache seems OK
        if ($cache_uid == $header->uid)
        if ($cache_uid == $uid)
          return 1;
      }
      // cache is dirty
@@ -2248,10 +2936,13 @@
  private function get_message_cache($key, $from, $to, $sort_field, $sort_order)
    {
    $cache_key = "$key:$from:$to:$sort_field:$sort_order";
    $db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
    
    if (!in_array($sort_field, $db_header_fields))
    $config = rcmail::get_instance()->config;
    // use idx sort as default sorting
    if (!$sort_field || !in_array($sort_field, $this->db_header_fields)) {
      $sort_field = 'idx';
      }
    
    if ($this->caching_enabled && !isset($this->cache[$cache_key]))
      {
@@ -2286,9 +2977,9 @@
   */
  private function &get_cached_message($key, $uid)
    {
    $internal_key = '__single_msg';
    $internal_key = 'message';
    
    if ($this->caching_enabled && !isset($this->cache[$internal_key][$uid]))
    if ($this->caching_enabled && !isset($this->icache[$internal_key][$uid]))
      {
      $sql_result = $this->db->query(
        "SELECT idx, headers, structure
@@ -2303,19 +2994,19 @@
      if ($sql_arr = $this->db->fetch_assoc($sql_result))
        {
   $this->uid_id_map[preg_replace('/\.msg$/', '', $key)][$uid] = $sql_arr['idx'];
        $this->cache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
        if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
          $this->cache[$internal_key][$uid]->structure = $this->db->decode(unserialize($sql_arr['structure']));
        $this->icache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
        if (is_object($this->icache[$internal_key][$uid]) && !empty($sql_arr['structure']))
          $this->icache[$internal_key][$uid]->structure = $this->db->decode(unserialize($sql_arr['structure']));
        }
      }
    return $this->cache[$internal_key][$uid];
    return $this->icache[$internal_key][$uid];
    }
  /**
   * @access private
   */  
  private function get_message_cache_index($key, $force=FALSE, $sort_field='idx', $sort_order='ASC')
  private function get_message_cache_index($key, $force=false, $sort_field='idx', $sort_order='ASC')
    {
    static $sa_message_index = array();
    
@@ -2325,6 +3016,10 @@
    
    if (!empty($sa_message_index[$key]) && !$force)
      return $sa_message_index[$key];
    // use idx sort as default
    if (!$sort_field || !in_array($sort_field, $this->db_header_fields))
      $sort_field = 'idx';
    
    $sa_message_index[$key] = array();
    $sql_result = $this->db->query(
@@ -2351,8 +3046,8 @@
        return;
    // add to internal (fast) cache
    $this->cache['__single_msg'][$headers->uid] = clone $headers;
    $this->cache['__single_msg'][$headers->uid]->structure = $struct;
    $this->icache['message'][$headers->uid] = clone $headers;
    $this->icache['message'][$headers->uid]->structure = $struct;
    // no further caching
    if (!$this->caching_enabled)
@@ -2365,8 +3060,7 @@
         FROM ".get_table_name('messages')."
         WHERE  user_id=?
         AND    cache_key=?
         AND    uid=?
         AND    del<>1",
         AND    uid=?",
        $_SESSION['user_id'],
        $key,
        $headers->uid);
@@ -2397,10 +3091,10 @@
        $key,
        $index,
        $headers->uid,
        (string)mb_substr($this->db->encode($this->decode_header($headers->subject, TRUE)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->from, TRUE)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->to, TRUE)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->cc, TRUE)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->subject, true)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->from, true)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->to, true)), 0, 128),
        (string)mb_substr($this->db->encode($this->decode_header($headers->cc, true)), 0, 128),
        (int)$headers->size,
        serialize($this->db->encode(clone $headers)),
        is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL
@@ -2411,16 +3105,16 @@
  /**
   * @access private
   */
  private function remove_message_cache($key, $uids)
  private function remove_message_cache($key, $ids, $idx=false)
    {
    if (!$this->caching_enabled)
      return;
    
    $this->db->query(
      "DELETE FROM ".get_table_name('messages')."
      WHERE  user_id=?
      AND    cache_key=?
      AND    uid IN (".$this->db->array2list($uids, 'integer').")",
      WHERE user_id=?
      AND cache_key=?
      AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
      $_SESSION['user_id'],
      $key);
    }
@@ -2435,12 +3129,10 @@
    
    $this->db->query(
      "DELETE FROM ".get_table_name('messages')."
       WHERE  user_id=?
       AND    cache_key=?
       AND    idx>=?",
      $_SESSION['user_id'],
      $key,
      $start_index);
       WHERE user_id=?
       AND cache_key=?
       AND idx>=?",
      $_SESSION['user_id'], $key, $start_index);
    }
  /**
@@ -2495,8 +3187,12 @@
    foreach ($a as $val)
      {
      $j++;
      $address = $val['address'];
      $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
      $address = trim($val['address']);
      $name = trim($val['name']);
      if (preg_match('/^[\'"]/', $name) && preg_match('/[\'"]$/', $name))
        $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', $name);
      if ($name && $address && $name != $address)
        $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
      else if ($address)
@@ -2507,7 +3203,7 @@
      $out[$j] = array('name' => $name,
                       'mailto' => $address,
                       'string' => $string);
      if ($max && $j==$max)
        break;
      }
@@ -2557,7 +3253,7 @@
   * @param boolean Remove quotes if necessary
   * @return string Decoded string
   */
  function decode_header($input, $remove_quotes=FALSE)
  function decode_header($input, $remove_quotes=false)
    {
    $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
    if ($str{0}=='"' && $remove_quotes)
@@ -2741,14 +3437,16 @@
   */
  function mod_mailbox($mbox_name, $mode='in')
    {
    if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
    if ($mbox_name == 'INBOX')
      return $mbox_name;
    if (!empty($this->root_dir) && $mode=='in')
      $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
    else if (strlen($this->root_dir) && $mode=='out')
      $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
    if (!empty($this->root_dir)) {
      if ($mode=='in')
        $mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
      else if (!empty($mbox_name)) // $mode=='out'
        $mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
      }
    return $mbox_name;
    }
@@ -2785,7 +3483,7 @@
      if ($folder{0}=='.')
        continue;
      if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
      if (($p = array_search($folder, $this->default_folders)) !== false && !$a_defaults[$p])
        $a_defaults[$p] = $folder;
      else
        $folders[$folder] = mb_strtolower(rcube_charset_convert($folder, 'UTF7-IMAP'));
@@ -2849,15 +3547,12 @@
    {
    if (!$mbox_name)
      $mbox_name = $this->mailbox;
    $index = array_flip((array)$this->uid_id_map[$mbox_name]);
    if (isset($index[$id]))
      $uid = $index[$id];
    else
      {
      $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
      $this->uid_id_map[$mbox_name][$uid] = $id;
      }
    if ($uid = array_search($id, (array)$this->uid_id_map[$mbox_name]))
      return $uid;
    $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
    $this->uid_id_map[$mbox_name][$uid] = $id;
    
    return $uid;
    }
@@ -2869,8 +3564,8 @@
   */
  private function _change_subscription($a_mboxes, $mode)
    {
    $updated = FALSE;
    $updated = false;
    if (is_array($a_mboxes))
      foreach ($a_mboxes as $i => $mbox_name)
        {
@@ -2878,15 +3573,12 @@
        $a_mboxes[$i] = $mailbox;
        if ($mode=='subscribe')
          $result = iil_C_Subscribe($this->conn, $mailbox);
          $updated = iil_C_Subscribe($this->conn, $mailbox);
        else if ($mode=='unsubscribe')
          $result = iil_C_UnSubscribe($this->conn, $mailbox);
        if ($result>=0)
          $updated = TRUE;
          $updated = iil_C_UnSubscribe($this->conn, $mailbox);
        }
    // get cached mailbox list
    // get cached mailbox list
    if ($updated)
      {
      $a_mailbox_cache = $this->get_cache('mailboxes');
@@ -2898,7 +3590,7 @@
        $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
      else if ($mode=='unsubscribe')
        $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
      // write mailboxlist to cache
      $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
      }
@@ -2913,14 +3605,14 @@
   */
  private function _set_messagecount($mbox_name, $mode, $increment)
    {
    $a_mailbox_cache = FALSE;
    $a_mailbox_cache = false;
    $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
    $mode = strtoupper($mode);
    $a_mailbox_cache = $this->get_cache('messagecount');
    
    if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
      return FALSE;
      return false;
    
    // add incremental value to messagecount
    $a_mailbox_cache[$mailbox][$mode] += $increment;
@@ -2932,7 +3624,7 @@
    // write back to cache
    $this->update_cache('messagecount', $a_mailbox_cache);
    
    return TRUE;
    return true;
    }
@@ -2942,7 +3634,7 @@
   */
  private function _clear_messagecount($mbox_name='')
    {
    $a_mailbox_cache = FALSE;
    $a_mailbox_cache = false;
    $mailbox = $mbox_name ? $mbox_name : $this->mailbox;
    $a_mailbox_cache = $this->get_cache('messagecount');
@@ -2962,6 +3654,7 @@
  private function _parse_headers($headers)
    {
    $a_headers = array();
    $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
    $lines = explode("\n", $headers);
    $c = count($lines);
    for ($i=0; $i<$c; $i++)