alecpl
2010-03-24 d8c440c03f3c66b93793c40e54d3c9329d9b5ea9
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:                                                              |
@@ -41,36 +41,40 @@
 */
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 $index_sort = true;
  var $delimiter = NULL;
  var $caching_enabled = FALSE;
  var $default_charset = 'ISO-8859-1';
  var $struct_charset = NULL;
  var $default_folders = 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('auth_method' => '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;
@@ -106,7 +110,7 @@
    else if ($use_ssl) {
      raise_error(array('code' => 403, 'type' => 'imap',
        'file' => __FILE__, 'line' => __LINE__,
        'message' => "Open SSL not available"), TRUE, FALSE);
        'message' => "Open SSL not available"), true, false);
      $port = 143;
    }
@@ -138,22 +142,19 @@
      $this->error_code = $GLOBALS['iil_errornum'];
      raise_error(array('code' => 403, 'type' => 'imap',
        'file' => __FILE__, 'line' => __LINE__,
        'message' => $GLOBALS['iil_error']), TRUE, FALSE);
        'message' => $GLOBALS['iil_error']), true, false);
      }
    // get server properties
    if ($this->conn)
      {
      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;
    }
@@ -303,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;
    }
@@ -323,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,
   );
    }
@@ -349,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;
    }
@@ -440,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,12 +490,12 @@
   * Get message count for a specific mailbox
   *
   * @param   string   Mailbox/folder name
   * @param   string   Mode for count [ALL|UNSEEN|RECENT]
   * @param   string   Mode for count [ALL|THREADS|UNSEEN|RECENT]
   * @param   boolean  Force reading from server and update cache
   * @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);
@@ -478,17 +508,21 @@
   * @access  private
   * @see     rcube_imap::messagecount()
   */
  private function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
  private function _messagecount($mailbox='', $mode='ALL', $force=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
@@ -498,13 +532,16 @@
    if (!is_array($a_mailbox_cache[$mailbox]))
      $a_mailbox_cache[$mailbox] = array();
    if ($mode == 'THREADS') {
      $count = $this->_threadcount($mailbox, $msg_count);
      $_SESSION['maxuid'][$mailbox] = $msg_count ? $this->_id2uid($msg_count) : 0;
      }
    // 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
    else if ($this->skip_deleted)
      {
    else if ($this->skip_deleted) {
      $search_str = "ALL UNDELETED";
      // get message count and store in cache
@@ -513,7 +550,12 @@
      // get message count using SEARCH
      // not very performant but more precise (using UNDELETED)
      // disable THREADS for this request
      $threads = $this->threading;
      $this->threading = false;
      $index = $this->_search_index($mailbox, $search_str);
      $this->threading = $threads;
      $count = is_array($index) ? count($index) : 0;
      if ($mode == 'ALL')
@@ -534,6 +576,26 @@
    $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, &$msg_count)
    {
    if (!empty($this->icache['threads']))
      return count($this->icache['threads']['tree']);
    list ($thread_tree, $msg_depth, $has_children) = $this->_fetch_threads($mailbox);
    $msg_count = count($msg_depth);
//    $this->update_thread_cache($mailbox, $thread_tree, $msg_depth, $has_children);
    return count($thread_tree);
    }
@@ -562,7 +624,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();
@@ -570,6 +632,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);
@@ -591,14 +656,14 @@
    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();
    // use message index sort for sorting by Date (for better performance)
    if ($this->index_sort && $this->sort_field == 'date')
    // use message index sort as default sorting (for better performance)
    if (!$this->sort_field)
      {
        if ($this->skip_deleted) {
          // @TODO: this could be cached
@@ -623,17 +688,19 @@
          $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
      }
    // use SORT command
    else if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
    else if ($this->get_capability('SORT'))
      {
      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 ($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);
        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
        $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))
@@ -675,6 +742,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
@@ -691,6 +892,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;
@@ -698,8 +907,8 @@
    $this->_set_sort_order($sort_field, $sort_order);
    // quickest method
    if ($this->index_sort && $this->search_sort_field == 'date' && $this->sort_field == 'date')
    // quickest method (default sorting)
    if (!$this->search_sort_field && !$this->sort_field)
      {
      if ($sort_order == 'DESC')
        $msgs = array_reverse($msgs);
@@ -720,8 +929,9 @@
      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') && (!$this->index_sort || $this->sort_field != 'date')) // 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)
@@ -749,10 +959,10 @@
      return array_values($a_msg_headers);
      }
    else { // SEARCH searching result, need sorting
    else { // SEARCH result, need sorting
      $cnt = count($msgs);
      // 300: experimantal value for best result
      if (($cnt > 300 && $cnt > $this->page_size) || ($this->index_sort && $this->sort_field == 'date')) {
      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);
        // get messages uids for one page...
@@ -791,6 +1001,40 @@
        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);
    }
@@ -846,25 +1090,25 @@
    // 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);
    if (empty($a_header_index))
      return 0;
      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]);
    // 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
          $this->add_message_cache($cache_key, $headers->id, $headers, NULL,
            !in_array($headers->uid, $cache_index));
        // add message to cache
        $this->add_message_cache($cache_key, $headers->id, $headers, NULL,
          !in_array($headers->uid, $cache_index));
        }
        $a_msg_headers[$headers->uid] = $headers;
        }
      $a_msg_headers[$headers->uid] = $headers;
      }
    return count($a_msg_headers);
@@ -905,18 +1149,22 @@
   */
  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)
    if (!isset($this->cache[$key]) && $this->search_string
      && !$this->search_threads && $mailbox == $this->mailbox)
    {
      $this->cache[$key] = array();
      
      // use message index sort for sorting by Date
      if ($this->index_sort && $this->sort_field == 'date')
      // use message index sort as default sorting
      if (!$this->sort_field)
      {
        $msgs = $this->search_set;
@@ -929,7 +1177,7 @@
          $this->cache[$key] = $msgs;
      }
      // sort with SORT command
      else if ($this->get_capability('sort'))
      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);
@@ -941,7 +1189,8 @@
      }
      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);
@@ -963,12 +1212,12 @@
    // 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);
      }
    // use message index sort for sorting by Date
    if ($this->index_sort && $this->sort_field == 'date')
    // use message index sort as default sorting
    if (!$this->sort_field)
      {
      if ($this->skip_deleted) {
        $a_index = $this->_search_index($mailbox, 'ALL');
@@ -982,17 +1231,16 @@
      $this->cache[$key] = $a_index;
      }
    // fetch complete message index
    else if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
    else if ($this->get_capability('SORT'))
      {
      if ($this->sort_order == 'DESC')
        $a_index = array_reverse($a_index);
      $this->cache[$key] = $a_index;
      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
      {
      $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", $this->sort_field, $this->skip_deleted);
    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")
@@ -1006,9 +1254,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);
@@ -1029,7 +1358,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]);
        }
@@ -1106,7 +1435,7 @@
      $results = $this->search($mbox_name, $res, NULL, $sort_field);
    }
    $this->set_search_set($str, $results, $charset, $sort_field);
    $this->set_search_set($str, $results, $charset, $sort_field, (bool)$this->threading);
    return $results;
    }
@@ -1126,9 +1455,22 @@
    if ($this->skip_deleted && !preg_match('/UNDELETED/', $criteria))
      $criteria = 'UNDELETED '.$criteria;
    if ($sort_field && $this->get_capability('sort') && (!$this->index_sort || $sort_field != 'date')) {
    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 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);
      $a_messages = iil_C_Sort($this->conn, $mailbox, $sort_field, $criteria, false, $charset);
      if (!$a_messages)
   return array();
      }
    else {
      if ($orig_criteria == 'ALL') {
@@ -1137,9 +1479,12 @@
        }
      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->index_sort && $this->sort_field == 'date')
        if (!$this->sort_field)
          sort($a_messages);
        }
      }
@@ -1153,6 +1498,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
@@ -1160,7 +1598,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();
    }
@@ -1189,7 +1628,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);
@@ -1665,41 +2104,41 @@
  /**
   * Set message flag to one or several messages
   *
   * @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 mixed   Message UIDs as array or comma-separated string, or '*'
   * @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
   * @return int    Number of flagged messages, -1 on failure
   */
  function set_flag($uids, $flag, $mbox_name=NULL, $skip_cache=false)
    {
    $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $flag = strtoupper($flag);
    if (!is_array($uids))
      $uids = explode(',',$uids);
    list($uids, $all_mode) = $this->_parse_uids($uids);
    if (strpos($flag, 'UN') === 0)
      $result = iil_C_UnFlag($this->conn, $mailbox, join(',', $uids), substr($flag, 2));
      $result = iil_C_UnFlag($this->conn, $mailbox, $uids, substr($flag, 2));
    else
      $result = iil_C_Flag($this->conn, $mailbox, join(',', $uids), $flag);
      $result = iil_C_Flag($this->conn, $mailbox, $uids, $flag);
    // reload message headers if cached
    if ($this->caching_enabled && !$skip_cache) {
      $cache_key = $mailbox.'.msg';
      $this->remove_message_cache($cache_key, $uids);
    if ($result >= 0) {
      // reload message headers if cached
      if ($this->caching_enabled && !$skip_cache) {
        $cache_key = $mailbox.'.msg';
        if ($all_mode)
          $this->clear_message_cache($cache_key);
        else
          $this->remove_message_cache($cache_key, explode(',', $uids));
        }
      // update counters
      if ($flag=='SEEN')
        $this->_set_messagecount($mailbox, 'UNSEEN', $result*(-1));
      else if ($flag=='UNSEEN')
        $this->_set_messagecount($mailbox, 'UNSEEN', $result);
      else if ($flag=='DELETED')
        $this->_set_messagecount($mailbox, 'ALL', $result*(-1));
      }
    // set nr of messages that were flaged
    $count = count($uids);
    // clear message count cache
    if ($result && $flag=='SEEN')
      $this->_set_messagecount($mailbox, 'UNSEEN', $count*(-1));
    else if ($result && $flag=='UNSEEN')
      $this->_set_messagecount($mailbox, 'UNSEEN', $count);
    else if ($result && $flag=='DELETED')
      $this->_set_messagecount($mailbox, 'ALL', $count*(-1));
    return $result;
    }
@@ -1708,10 +2147,10 @@
  /**
   * Remove message flag for one or several messages
   *
   * @param mixed  Message UIDs as array or as comma-separated string
   * @param mixed  Message UIDs as array or comma-separated string, or '*'
   * @param string Flag to unset: SEEN, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
   * @param string Folder name
   * @return boolean True on success, False on failure
   * @return int   Number of flagged messages, -1 on failure
   * @see set_flag
   */
  function unset_flag($uids, $flag, $mbox_name=NULL)
@@ -1735,7 +2174,7 @@
    $mailbox = $this->mod_mailbox($mbox_name);
    // make sure mailbox exists
    if (($mailbox == 'INBOX') || in_array($mailbox, $this->_list_mailboxes())) {
    if ($this->mailbox_exists($mbox_name, true)) {
      if ($is_file) {
        $separator = rcmail::get_instance()->config->header_delimiter();
        $saved = iil_C_AppendFromFile($this->conn, $mailbox, $message,
@@ -1750,7 +2189,7 @@
      // increase messagecount of the target mailbox
      $this->_set_messagecount($mailbox, 'ALL', 1);
      }
    return $saved;
    }
@@ -1758,33 +2197,32 @@
  /**
   * Move a message from one mailbox to another
   *
   * @param string List of UIDs to move, separated by comma
   * @param mixed  Message UIDs as array or comma-separated string, or '*'
   * @param string Target mailbox
   * @param string Source mailbox
   * @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($tbox, $this->default_folders))
        $this->create_mailbox($tbox, TRUE);
      else
        return FALSE;
      }
    // convert the list of uids to array
    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
    list($uids, $all_mode) = $this->_parse_uids($uids);
    // exit if no message uids are specified
    if (!is_array($a_uids) || empty($a_uids))
    if (empty($uids))
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true))
      {
      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;
@@ -1794,84 +2232,144 @@
      }
    // move messages
    $iil_move = iil_C_Move($this->conn, join(',', $a_uids), $from_mbox, $to_mbox);
    $iil_move = iil_C_Move($this->conn, $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, $uids);
      $this->_clear_messagecount($from_mbox);
      $this->_clear_messagecount($to_mbox);
    }
    // moving failed
    else if ($config->get('delete_always', false) && $tbox == $config->get('trash_mbox')) {
      return $this->delete_message($a_uids, $fbox);
      $moved = $this->delete_message($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']);
    // 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);
      }
      // 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 || $all_mode)
          $this->refresh_search();
        else {
          $uids = explode(',', $uids);
          foreach ($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 ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
        // clear cache from the lowest index on
        $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
       }
    }
    return $moved;
  }
  /**
   * Copy a message from one mailbox to another
   *
   * @param mixed  Message UIDs as array or comma-separated string, or '*'
   * @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;
    list($uids, $all_mode) = $this->_parse_uids($uids);
    // exit if no message uids are specified
    if (empty($uids))
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true))
      {
      if (in_array($tbox, $this->default_folders))
        $this->create_mailbox($tbox, true);
      else
        return false;
      }
    // copy messages
    $iil_copy = iil_C_Copy($this->conn, $uids, $from_mbox, $to_mbox);
    $copied = !($iil_copy === false || $iil_copy < 0);
    if ($copied) {
      $this->_clear_messagecount($to_mbox);
    }
    return $copied;
  }
  /**
   * Mark messages as deleted and expunge mailbox
   *
   * @param string List of UIDs to move, separated by comma
   * @param mixed  Message UIDs as array or comma-separated string, or '*'
   * @param string Source mailbox
   * @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
    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
    list($uids, $all_mode) = $this->_parse_uids($uids);
    // exit if no message uids are specified
    if (!is_array($a_uids) || empty($a_uids))
    if (empty($uids))
      return false;
    $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_uids));
    $deleted = iil_C_Delete($this->conn, $mailbox, $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, $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);
      // 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 || $all_mode)
          $this->refresh_search();
        else {
          $uids = explode(',', $uids);
          foreach ($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 ($all_mode || ($start_index = $this->get_message_cache_index_min($cache_key, $uids))) {
        // clear cache from the lowest index on
        $this->clear_message_cache($cache_key, $all_mode ? 1 : $start_index);
      }
    }
    // 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);
      }
    return $deleted;
    }
  }
  /**
@@ -1912,7 +2410,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);
@@ -1922,14 +2420,14 @@
  /**
   * Send IMAP expunge command and clear cache
   *
   * @see rcube_imap::expunge()
   * @param string    Mailbox name
   * @param boolean    False if cache should not be cleared
   * @param string    List of UIDs to remove, separated by comma
   * @param string     Mailbox name
   * @param boolean  False if cache should not be cleared
   * @param mixed    Message UIDs as array or comma-separated string, or '*'
   * @return boolean True on success
   * @access private
   * @see rcube_imap::expunge()
   */
  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;
@@ -1948,10 +2446,34 @@
    }
  /**
   * Parse message UIDs input
   *
   * @param mixed  UIDs array or comma-separated list or '*' or '1:*'
   * @return array Two elements array with UIDs converted to list and ALL flag
   * @access private
   */
  private function _parse_uids($uids)
    {
    if ($uids === '*' || $uids === '1:*') {
      $uids = '1:*';
      $all = true;
      }
    else {
      if (is_array($uids))
        $uids = join(',', $uids);
      if (preg_match('/[^0-9,]/', $uids))
        $uids = '';
      }
    return array($uids, (bool) $all);
    }
  /* --------------------------------
   *        folder managment
   * --------------------------------*/
  /**
   * Get a list of all folders available on the IMAP server
@@ -1994,7 +2516,7 @@
    if ($this->get_capability('QUOTA'))
      return iil_C_GetQuota($this->conn);
   
    return FALSE;
    return false;
    }
@@ -2037,24 +2559,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;
    }
@@ -2067,7 +2585,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);
@@ -2108,7 +2626,7 @@
    if ($result && $subscribed)
      iil_C_Subscribe($this->conn, $abs_name);
    return $result ? $name : FALSE;
    return $result ? $name : false;
    }
@@ -2120,19 +2638,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(''),
     $mbox_name . $this->delimiter . '*');
        // unsubscribe mailbox before deleting
        iil_C_UnSubscribe($this->conn, $mailbox);
@@ -2140,23 +2658,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))
            {
        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;
              $deleted = true;
             $this->clear_message_cache($c_mbox.'.msg');
              }
       }
            }
          }
        }
@@ -2173,18 +2686,43 @@
   */
  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($abs_name, $a_folders))
        $this->create_mailbox($folder, TRUE);
      else if (!in_array($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;
      if ($subscription) {
        if ($a_folders = iil_C_ListSubscribed($this->conn, $this->mod_mailbox(''), $mbox_name))
          return true;
        }
      else {
        $a_folders = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''), $mbox_mbox);
   if (is_array($a_folders) && in_array($this->mod_mailbox($mbox_name), $a_folders))
          return true;
        }
      }
    return false;
    }
@@ -2199,9 +2737,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;
    }
  /**
@@ -2224,8 +2762,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;
    }
  /**
@@ -2257,13 +2795,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]);
      }
    }
@@ -2288,7 +2826,7 @@
   $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
        $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
   if (!isset($this->cache[$sql_key]))
     $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : FALSE;
     $this->cache[$sql_key] = $sql_arr['data'] ? unserialize($sql_arr['data']) : false;
        }
      }
@@ -2301,7 +2839,7 @@
  private function _write_cache_record($key, $data)
    {
    if (!$this->db)
      return FALSE;
      return false;
    // update existing cache record
    if ($this->cache_keys[$key])
@@ -2426,13 +2964,11 @@
  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');
    
    $config = rcmail::get_instance()->config;
    // use idx sort for sorting by Date with index_sort=true or for unknown field
    if (($sort_field == 'date' && $this->index_sort)
      || !in_array($sort_field, $db_header_fields)) {
    // use idx sort as default sorting
    if (!$sort_field || !in_array($sort_field, $this->db_header_fields)) {
      $sort_field = 'idx';
      }
    
@@ -2469,9 +3005,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
@@ -2486,19 +3022,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();
    
@@ -2509,8 +3045,8 @@
    if (!empty($sa_message_index[$key]) && !$force)
      return $sa_message_index[$key];
    // use idx sort for sorting by Date with index_sort=true
    if ($sort_field == 'date' && $this->index_sort)
    // use idx sort as default
    if (!$sort_field || !in_array($sort_field, $this->db_header_fields))
      $sort_field = 'idx';
    
    $sa_message_index[$key] = array();
@@ -2538,8 +3074,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)
@@ -2583,10 +3119,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
@@ -2635,6 +3171,13 @@
    if (!$this->caching_enabled)
      return;
    
    if (!empty($uids) && !is_array($uids)) {
      if ($uids == '*' || $uids == '1:*')
        $uids = NULL;
      else
        $uids = explode(',', $uids);
      }
    $sql_result = $this->db->query(
      "SELECT MIN(idx) AS minidx
      FROM ".get_table_name('messages')."
@@ -2679,8 +3222,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)
@@ -2691,7 +3238,7 @@
      $out[$j] = array('name' => $name,
                       'mailto' => $address,
                       'string' => $string);
      if ($max && $j==$max)
        break;
      }
@@ -2741,7 +3288,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)
@@ -2925,7 +3472,7 @@
   */
  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)) {
@@ -3052,7 +3599,7 @@
   */
  private function _change_subscription($a_mboxes, $mode)
    {
    $updated = FALSE;
    $updated = false;
    if (is_array($a_mboxes))
      foreach ($a_mboxes as $i => $mbox_name)
@@ -3093,14 +3640,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;
@@ -3112,7 +3659,7 @@
    // write back to cache
    $this->update_cache('messagecount', $a_mailbox_cache);
    
    return TRUE;
    return true;
    }
@@ -3122,7 +3669,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');