alecpl
2010-03-26 59c216f3cceaf403ca0a678821eb219b6c41e6ff
program/include/rcube_imap.php
@@ -9,11 +9,11 @@
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |   IMAP wrapper that implements the Iloha IMAP Library (IIL)           |
 |   See http://ilohamail.org/ for details                               |
 |   IMAP Engine                                                         |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
 | Author: Aleksander Machniak <alec@alec.pl>                            |
 +-----------------------------------------------------------------------+
 $Id$
@@ -21,10 +21,6 @@
*/
/*
 * Obtain classes from the Iloha IMAP library
 */
require_once('lib/imap.inc');
require_once('lib/mime.inc');
require_once('lib/tnef_decoder.inc');
@@ -32,12 +28,9 @@
/**
 * Interface class for accessing an IMAP server
 *
 * This is a wrapper that implements the Iloha IMAP Library (IIL)
 *
 * @package    Mail
 * @author     Thomas Bruederli <roundcube@gmail.com>
 * @version    1.5
 * @link       http://ilohamail.org
 * @version    1.6
 */
class rcube_imap
{
@@ -50,7 +43,7 @@
  public $delimiter = NULL;
  public $threading = false;
  public $fetch_add_headers = '';
  public $conn;
    public $conn; // rcube_imap_generic object
  private $db;
  private $root_ns = '';
@@ -61,7 +54,6 @@
  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();  
@@ -86,6 +78,7 @@
  function __construct($db_conn)
    {
    $this->db = $db_conn;
        $this->conn = new rcube_imap_generic();
    }
@@ -102,11 +95,9 @@
   */
  function connect($host, $user, $pass, $port=143, $use_ssl=null)
    {
    global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
    // check for Open-SSL support in PHP build
    if ($use_ssl && extension_loaded('openssl'))
      $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
            $this->options['ssl_mode'] = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
    else if ($use_ssl) {
      raise_error(array('code' => 403, 'type' => 'imap',
        'file' => __FILE__, 'line' => __LINE__,
@@ -114,17 +105,18 @@
      $port = 143;
    }
    $ICL_PORT = $port;
    $IMAP_USE_INTERNAL_DATE = false;
        $this->options['port'] = $port;
    $attempt = 0;
    do {
      $data = rcmail::get_instance()->plugins->exec_hook('imap_connect', array('host' => $host, 'user' => $user, 'attempt' => ++$attempt));
            $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->conn->connect($data['host'], $data['user'], $pass, $this->options);
        } while(!$this->conn->connected() && $data['retry']);
    $this->host = $data['host'];
    $this->user = $data['user'];
@@ -133,25 +125,23 @@
    $this->ssl = $use_ssl;
    
    // print trace messages
    if ($this->conn && ($this->debug_level & 8))
        if ($this->conn->connected()) {
            if ($this->conn->message && ($this->debug_level & 8)) {
      console($this->conn->message);
    // write error log
    else if (!$this->conn && $GLOBALS['iil_error'])
      {
      $this->error_code = $GLOBALS['iil_errornum'];
      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->rootdir))
        $this->set_rootdir($this->conn->rootdir);
      if (empty($this->delimiter))
   $this->get_hierarchy_delimiter();
        }
        // write error log
        else if ($this->conn->error) {
            $this->error_code = $this->conn->errornum;
            raise_error(array('code' => 403, 'type' => 'imap',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => $this->conn->error), true, false);
      }
    return $this->conn ? true : false;
@@ -166,8 +156,9 @@
   */
  function close()
    {    
    if ($this->conn)
      iil_Close($this->conn);
        if ($this->conn && $this->conn->connected())
            $this->conn->close();
        $this->write_cache();
    }
@@ -184,11 +175,11 @@
    
    // issue SELECT command to restore connection status
    if ($this->mailbox)
      iil_C_Select($this->conn, $this->mailbox);
            $this->conn->select($this->mailbox);
    }
  /**
   * Set options to be used in iil_Connect()
     * Set options to be used in rcube_imap_generic::connect()
   */
  function set_options($opt)
  {
@@ -239,8 +230,7 @@
   */
  function set_default_mailboxes($arr)
    {
    if (is_array($arr))
      {
        if (is_array($arr)) {
      $this->default_folders = $arr;
      // add inbox if not included
@@ -342,7 +332,7 @@
   */
  function get_mailbox_name()
    {
    return $this->conn ? $this->mod_mailbox($this->mailbox, 'out') : '';
        return $this->conn->connected() ? $this->mod_mailbox($this->mailbox, 'out') : '';
    }
@@ -355,7 +345,7 @@
   */
  function get_capability($cap)
    {
    return iil_C_GetCapability($this->conn, strtoupper($cap));
        return $this->conn->getCapability(strtoupper($cap));
    }
@@ -394,7 +384,7 @@
  function check_permflag($flag)
    {
    $flag = strtoupper($flag);
    $imap_flag = $GLOBALS['IMAP_FLAGS'][$flag];
        $imap_flag = $this->conn->flags[$flag];
    return (in_array_nocase($imap_flag, $this->conn->permanentflags));
    }
@@ -408,81 +398,12 @@
  function get_hierarchy_delimiter()
    {
    if ($this->conn && empty($this->delimiter))
      $this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
            $this->delimiter = $this->conn->getHierarchyDelimiter();
    if (empty($this->delimiter))
      $this->delimiter = '/';
    return $this->delimiter;
    }
  /**
   * Public method for mailbox listing.
   *
   * Converts mailbox name with root dir first
   *
   * @param   string  Optional root folder
   * @param   string  Optional filter for mailbox listing
   * @return  array   List of mailboxes/folders
   * @access  public
   */
  function list_mailboxes($root='', $filter='*')
    {
    $a_out = array();
    $a_mboxes = $this->_list_mailboxes($root, $filter);
    foreach ($a_mboxes as $mbox_row)
      {
      $name = $this->mod_mailbox($mbox_row, 'out');
      if (strlen($name))
        $a_out[] = $name;
      }
    // INBOX should always be available
    if (!in_array('INBOX', $a_out))
      array_unshift($a_out, 'INBOX');
    // sort mailboxes
    $a_out = $this->_sort_mailbox_list($a_out);
    return $a_out;
    }
  /**
   * Private method for mailbox listing
   *
   * @return  array   List of mailboxes/folders
   * @see     rcube_imap::list_mailboxes()
   * @access  private
   */
  private function _list_mailboxes($root='', $filter='*')
    {
    $a_defaults = $a_out = array();
    // get cached folder list
    $a_mboxes = $this->get_cache('mailboxes');
    if (is_array($a_mboxes))
      return $a_mboxes;
    // Give plugins a chance to provide a list of mailboxes
    $data = rcmail::get_instance()->plugins->exec_hook('list_mailboxes',array('root'=>$root,'filter'=>$filter));
    if (isset($data['folders'])) {
        $a_folders = $data['folders'];
    }
    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();
    // write mailboxlist to cache
    $this->update_cache('mailboxes', $a_folders);
    return $a_folders;
    }
@@ -538,7 +459,7 @@
      }
    // RECENT count is fetched a bit different
    else if ($mode == 'RECENT') {
       $count = iil_C_CheckForRecent($this->conn, $mailbox);
            $count = $this->conn->checkForRecent($mailbox);
      }
    // use SEARCH for message counting
    else if ($this->skip_deleted) {
@@ -563,9 +484,9 @@
      }
    else {
      if ($mode == 'UNSEEN')
        $count = iil_C_CountUnseen($this->conn, $mailbox);
                $count = $this->conn->countUnseen($mailbox);
      else {
        $count = iil_C_CountMessages($this->conn, $mailbox);
                $count = $this->conn->countMessages($mailbox);
        $_SESSION['maxuid'][$mailbox] = $count ? $this->_id2uid($count) : 0;
      }
    }
@@ -643,18 +564,17 @@
    $cache_status = $this->check_cache_status($mailbox, $cache_key);
    // cache is OK, we can get all messages from local cache
    if ($cache_status>0)
      {
        if ($cache_status>0) {
      $start_msg = ($page-1) * $this->page_size;
      $a_msg_headers = $this->get_message_cache($cache_key, $start_msg, $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
            $a_msg_headers = $this->get_message_cache($cache_key, $start_msg,
                $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
      $result = array_values($a_msg_headers);
      if ($slice)
        $result = array_slice($result, -$slice, $slice);
      return $result;
      }
    // cache is dirty, sync it
    else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
      {
        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);
      }
@@ -663,8 +583,7 @@
    $a_msg_headers = array();
    // use message index sort as default sorting (for better performance)
    if (!$this->sort_field)
      {
        if (!$this->sort_field) {
        if ($this->skip_deleted) {
          // @TODO: this could be cached
          if ($msg_index = $this->_search_index($mailbox, 'ALL UNDELETED')) {
@@ -673,7 +592,7 @@
            $msg_index = array_slice($msg_index, $begin, $end-$begin);
          }
        }
        else if ($max = iil_C_CountMessages($this->conn, $mailbox)) {
            else if ($max = $this->conn->countMessages($mailbox)) {
          list($begin, $end) = $this->_get_message_range($max, $page);
          $msg_index = range($begin+1, $end);
        }
@@ -688,9 +607,8 @@
          $this->_fetch_headers($mailbox, join(",", $msg_index), $a_msg_headers, $cache_key);
      }
    // use SORT command
    else if ($this->get_capability('SORT'))
      {
      if ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) {
        else if ($this->get_capability('SORT')) {
            if ($msg_index = $this->conn->sort($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);
@@ -703,8 +621,7 @@
        }
      }
    // 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))
      {
        else if ($a_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
      asort($a_index); // ASC
      $msg_index = array_keys($a_index);
      $max = max($msg_index);
@@ -763,8 +680,8 @@
    $msg_index = $this->_sort_threads($mailbox, $thread_tree);
    return $this->_fetch_thread_headers($mailbox, $thread_tree, $msg_depth, $has_children,
      $msg_index, $page, $slice);
        return $this->_fetch_thread_headers($mailbox,
            $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice);
    }
@@ -779,7 +696,7 @@
    {
    if (empty($this->icache['threads'])) {
      // get all threads
      list ($thread_tree, $msg_depth, $has_children) = iil_C_Thread($this->conn,
            list ($thread_tree, $msg_depth, $has_children) = $this->conn->thread(
        $mailbox, $this->threading, $this->skip_deleted ? 'UNDELETED' : '');
   
      // add to internal (fast) cache
@@ -816,7 +733,7 @@
      $msg_index = array_reverse($msg_index);
    // flatten threads array
    // @TODO: fetch children only in expanded mode
        // @TODO: fetch children only in expanded mode (?)
    $all_ids = array();
    foreach($msg_index as $root) {
      $all_ids[] = $root;
@@ -908,8 +825,7 @@
    $this->_set_sort_order($sort_field, $sort_order);
    // quickest method (default sorting)
    if (!$this->search_sort_field && !$this->sort_field)
      {
        if (!$this->search_sort_field && !$this->sort_field) {
      if ($sort_order == 'DESC')
        $msgs = array_reverse($msgs);
@@ -931,8 +847,7 @@
      }
    // 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);
@@ -991,10 +906,13 @@
          return array();
        // if not already sorted
        $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
                $a_msg_headers = $this->conn->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);
@@ -1034,7 +952,8 @@
    $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);
        return $this->_fetch_thread_headers($mailbox,
            $thread_tree, $msg_depth, $has_children, $msg_index, $page, $slice=0);
    }
@@ -1050,18 +969,15 @@
    {
    $start_msg = ($page-1) * $this->page_size;
    
    if ($page=='all')
      {
        if ($page=='all') {
      $begin = 0;
      $end = $max;
      }
    else if ($this->sort_order=='DESC')
      {
        else if ($this->sort_order=='DESC') {
      $begin = $max - $this->page_size - $start_msg;
      $end =   $max - $start_msg;
      }
    else
      {
        else {
      $begin = $start_msg;
      $end   = $start_msg + $this->page_size;
      }
@@ -1088,7 +1004,8 @@
  private function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
    {
    // fetch reqested headers from server
    $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs, false, false, $this->fetch_add_headers);
        $a_header_index = $this->conn->fetchHeaders(
            $mailbox, $msgs, false, false, $this->fetch_add_headers);
    if (empty($a_header_index))
      return 0;
@@ -1133,7 +1050,8 @@
    
    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_values((array)$this->conn->fetchHeaderIndex(
                $mailbox, "$maxuid:*", 'UID', $this->skip_deleted, true));
    }
    
    return array();
@@ -1159,13 +1077,9 @@
    // 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();
            && !$this->search_threads && $mailbox == $this->mailbox) {
      // use message index sort as default sorting
      if (!$this->sort_field)
      {
            if (!$this->sort_field) {
        $msgs = $this->search_set;
        if ($this->search_sort_field != 'date')
@@ -1177,8 +1091,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);
@@ -1187,17 +1100,21 @@
        else
          $this->cache[$key] = $this->search_set;
      }
      else
      {
        $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox,
            else {
                $a_index = $this->conn->fetchHeaderIndex($mailbox,
     join(',', $this->search_set), $this->sort_field, $this->skip_deleted);
                if (is_array($a_index)) {
        if ($this->sort_order=="ASC")
          asort($a_index);
        else if ($this->sort_order=="DESC")
          arsort($a_index);
        $this->cache[$key] = array_keys($a_index);
                }
                else {
                    $this->cache[$key] = array();
                }
      }
    }
@@ -1210,15 +1127,14 @@
    $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);
        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);
      }
    // use message index sort as default sorting
    if (!$this->sort_field)
      {
        if (!$this->sort_field) {
      if ($this->skip_deleted) {
        $a_index = $this->_search_index($mailbox, 'ALL');
      } else if ($max = $this->_messagecount($mailbox)) {
@@ -1231,16 +1147,17 @@
      $this->cache[$key] = $a_index;
      }
    // fetch complete message index
    else if ($this->get_capability('SORT'))
      {
      if ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')) {
        else if ($this->get_capability('SORT')) {
            if ($a_index = $this->conn->sort($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)) {
        else if ($a_index = $this->conn->fetchHeaderIndex(
            $mailbox, "1:*", $this->sort_field, $this->skip_deleted)) {
      if ($this->sort_order=="ASC")
        asort($a_index);
      else if ($this->sort_order=="DESC")
@@ -1270,8 +1187,7 @@
    // 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->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);
@@ -1286,8 +1202,7 @@
    $cache_status = $this->check_cache_status($mailbox, $cache_key);
    // cache is OK
    if ($cache_status>0)
      {
        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);
      }
@@ -1343,29 +1258,25 @@
    $cache_index = $this->get_message_cache_index($cache_key);
    // fetch complete message index
    $a_message_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", 'UID', $this->skip_deleted);
        $a_message_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", 'UID', $this->skip_deleted);
    
    if ($a_message_index === false)
      return false;
        
    foreach ($a_message_index as $id => $uid)
      {
        foreach ($a_message_index as $id => $uid) {
      // message in cache at correct position
      if ($cache_index[$id] == $uid)
        {
            if ($cache_index[$id] == $uid) {
        unset($cache_index[$id]);
        continue;
        }
        
      // 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]);
        }
      
      // other message at this position
      if (isset($cache_index[$id]))
        {
            if (isset($cache_index[$id])) {
        $for_remove[] = $cache_index[$id];
        unset($cache_index[$id]);
        }
@@ -1382,10 +1293,13 @@
    // fetch complete headers and add to cache
    if (!empty($for_update)) {
      if ($headers = iil_C_FetchHeader($this->conn, $mailbox, join(',', $for_update), false, $this->fetch_add_headers))
        foreach ($headers as $header)
            if ($headers = $this->conn->fetchHeader($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($header->uid, (array)$for_remove));
                }
            }
      }
    }
@@ -1414,15 +1328,15 @@
    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))
      {
            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;
                    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;
        }
@@ -1456,7 +1370,7 @@
      $criteria = 'UNDELETED '.$criteria;
    if ($this->threading) {
      list ($thread_tree, $msg_depth, $has_children) = iil_C_Thread($this->conn,
            list ($thread_tree, $msg_depth, $has_children) = $this->conn->thread(
            $mailbox, $this->threading, $criteria, $charset);
      $a_messages = array(
@@ -1467,7 +1381,7 @@
      }
    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 = $this->conn->sort($mailbox, $sort_field, $criteria, false, $charset);
      if (!$a_messages)
   return array();
@@ -1478,7 +1392,8 @@
        $a_messages = $max ? range(1, $max) : array();
        }
      else {
        $a_messages = iil_C_Search($this->conn, $mailbox, ($charset ? "CHARSET $charset " : '') . $criteria);
                $a_messages = $this->conn->search($mailbox,
                        ($charset ? "CHARSET $charset " : '') . $criteria);
   if (!$a_messages)
     return array();
@@ -1488,6 +1403,7 @@
          sort($a_messages);
        }
      }
    // update messagecount cache ?
//    $a_mailbox_cache = get_cache('messagecount');
//    $a_mailbox_cache[$mailbox][$criteria] = sizeof($a_messages);
@@ -1501,7 +1417,7 @@
   * Sort thread
   *
   * @param string Mailbox name
   * @param  array Unsorted thread tree (iil_C_Thread() result)
     * @param  array Unsorted thread tree (rcube_imap_generic::thread() result)
   * @param  array Message IDs if we know what we need (e.g. search result)
   * @return array Sorted roots IDs
   * @access private
@@ -1519,7 +1435,7 @@
    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,
                $a_index = $this->conn->sort($mailbox, $this->sort_field,
       !empty($ids) ? $ids : ($this->skip_deleted ? 'UNDELETED' : ''));
   // return unsorted tree if we've got no index data
@@ -1528,7 +1444,7 @@
        }
      else {
        // fetch specified headers for all messages and sort them
        $a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, !empty($ids) ? $ids : "1:*",
                $a_index = $this->conn->fetchHeaderIndex($mailbox, !empty($ids) ? $ids : "1:*",
       $this->sort_field, $this->skip_deleted);
   // return unsorted tree if we've got no index data
@@ -1599,6 +1515,7 @@
    {
    if (!empty($this->search_string))
      $this->search_set = $this->search('', $this->search_string, $this->search_charset,
           $this->search_sort_field, $this->search_threads);
      
    return $this->get_search_set();
@@ -1612,8 +1529,12 @@
   */
  function in_searchset($msgid)
  {
    if (!empty($this->search_string))
        if (!empty($this->search_string)) {
            if ($this->search_threads)
                return isset($this->search_set['depth']["$msgid"]);
            else
      return in_array("$msgid", (array)$this->search_set, true);
        }
    else
      return true;
  }
@@ -1637,11 +1558,11 @@
    if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
      return $headers;
    $headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid, $bodystr, $this->fetch_add_headers);
        $headers = $this->conn->fetchHeader(
            $mailbox, $id, $is_uid, $bodystr, $this->fetch_add_headers);
    // write headers cache
    if ($headers)
      {
        if ($headers) {
      if ($headers->uid && $headers->id)
        $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
@@ -1671,13 +1592,12 @@
    }
    if (!$structure_str)
      $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $uid, true);
            $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
    $structure = iml_GetRawStructureArray($structure_str);
    $struct = false;
    // parse structure and add headers
    if (!empty($structure))
      {
        if (!empty($structure)) {
      $headers = $this->get_headers($uid);
      $this->_msg_id = $headers->id;
@@ -1701,8 +1621,7 @@
      $struct->headers = get_object_vars($headers);
      // don't trust given content-type
      if (empty($struct->parts) && !empty($struct->headers['ctype']))
        {
        if (empty($struct->parts) && !empty($struct->headers['ctype'])) {
        $struct->mime_id = '1';
        $struct->mimetype = strtolower($struct->headers['ctype']);
        list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
@@ -1728,24 +1647,24 @@
    $struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
    // multipart
    if (is_array($part[0]))
      {
        if (is_array($part[0])) {
      $struct->ctype_primary = 'multipart';
      
      // find first non-array entry
      for ($i=1; $i<count($part); $i++)
        if (!is_array($part[$i]))
          {
            for ($i=1; $i<count($part); $i++) {
                if (!is_array($part[$i])) {
          $struct->ctype_secondary = strtolower($part[$i]);
          break;
                }
          }
          
      $struct->mimetype = 'multipart/'.$struct->ctype_secondary;
      // build parts list for headers pre-fetching
      for ($i=0, $count=0; $i<count($part); $i++)
            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)
                    // 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') {
@@ -1757,29 +1676,31 @@
            }
          }
        }
            }
        
      // pre-fetch headers of all parts (in one command for better performance)
      // @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,
            if ($mime_part_headers) {
                $mime_part_headers = $this->conn->fetchMIMEHeaders($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,
            if ($raw_part_headers) {
                $raw_part_headers = $this->conn->fetchMIMEHeaders($this->mailbox,
          $this->_msg_id, $raw_part_headers, false);
            }
      $struct->parts = array();
      for ($i=0, $count=0; $i<count($part); $i++)
            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,
            $mime_part_headers[$tmp_part_id], $raw_part_headers[$tmp_part_id]);
        }
            }
      return $struct;
      }
    // regular part
    $struct->ctype_primary = strtolower($part[0]);
@@ -1787,8 +1708,7 @@
    $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
    // read content type parameters
    if (is_array($part[2]))
      {
        if (is_array($part[2])) {
      $struct->ctype_parameters = array();
      for ($i=0; $i<count($part[2]); $i+=2)
        $struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
@@ -1798,8 +1718,7 @@
      }
    
    // read content encoding
    if (!empty($part[5]) && $part[5]!='NIL')
      {
        if (!empty($part[5]) && $part[5]!='NIL') {
      $struct->encoding = strtolower($part[5]);
      $struct->headers['content-transfer-encoding'] = $struct->encoding;
      }
@@ -1811,8 +1730,7 @@
    // read part disposition
    $di = count($part) - 2;
    if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
        (is_array($part[--$di]) && count($part[$di]) == 2))
      {
            (is_array($part[--$di]) && count($part[$di]) == 2)) {
      $struct->disposition = strtolower($part[$di][0]);
      if (is_array($part[$di][1]))
@@ -1821,8 +1739,7 @@
      }
      
    // get child parts
    if (is_array($part[8]) && $di != 8)
      {
        if (is_array($part[8]) && $di != 8) {
      $struct->parts = array();
      for ($i=0, $count=0; $i<count($part[8]); $i++)
        if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
@@ -1830,8 +1747,7 @@
      }
    // get part ID
    if (!empty($part[3]) && $part[3]!='NIL')
      {
        if (!empty($part[3]) && $part[3]!='NIL') {
      $struct->content_id = $part[3];
      $struct->headers['content-id'] = $part[3];
    
@@ -1841,14 +1757,18 @@
    
    // 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($mime_headers))
        $mime_headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $struct->mime_id);
            if (empty($mime_headers)) {
                $mime_headers = $this->conn->fetchPartHeader(
                    $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);
                if (empty($raw_headers)) {
                    $raw_headers = $this->conn->fetchMIMEHeaders(
                        $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
@@ -1896,8 +1816,10 @@
      // 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)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
                if (!$headers) {
                    $headers = $this->conn->fetchPartHeader(
                        $this->mailbox, $this->_msg_id, false, $part->mime_id);
                }
        $filename_mime = '';
        $i = 0;
        while (preg_match('/filename\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
@@ -1913,8 +1835,10 @@
        $i++;
      }
      if ($i<2) {
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
                if (!$headers) {
                    $headers = $this->conn->fetchPartHeader(
                            $this->mailbox, $this->_msg_id, false, $part->mime_id);
                }
        $filename_encoded = '';
        $i = 0; $matches = array();
        while (preg_match('/filename\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
@@ -1930,8 +1854,10 @@
        $i++;
      }
      if ($i<2) {
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
                if (!$headers) {
                    $headers = $this->conn->fetchPartHeader(
                        $this->mailbox, $this->_msg_id, false, $part->mime_id);
                }
        $filename_mime = '';
        $i = 0; $matches = array();
        while (preg_match('/\s+name\*'.$i.'\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
@@ -1947,8 +1873,10 @@
        $i++;
      }
      if ($i<2) {
        if (!$headers)
          $headers = iil_C_FetchPartHeader($this->conn, $this->mailbox, $this->_msg_id, false, $part->mime_id);
                if (!$headers) {
                    $headers = $this->conn->fetchPartHeader(
                        $this->mailbox, $this->_msg_id, false, $part->mime_id);
                }
        $filename_encoded = '';
        $i = 0; $matches = array();
        while (preg_match('/\s+name\*'.$i.'\*\s*=\s*"*([^"\n;]+)[";]*/', $headers, $matches)) {
@@ -2013,9 +1941,8 @@
  function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL, $fp=NULL)
    {
    // get part encoding if not provided
    if (!is_object($o_part))
      {
      $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $uid, true);
        if (!is_object($o_part)) {
            $structure_str = $this->conn->fetchStructureString($this->mailbox, $uid, true);
      $structure = iml_GetRawStructureArray($structure_str);
      // error or message not found
      if (empty($structure))
@@ -2032,7 +1959,7 @@
    if (!$part) $part = 'TEXT';
    $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true, $part,
        $body = $this->conn->handlePartBody($this->mailbox, $uid, true, $part,
        $o_part->encoding, $print, $fp);
    if ($fp || $print)
@@ -2074,7 +2001,7 @@
   */
  function &get_raw_body($uid)
    {
    return iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true);
        return $this->conn->handlePartBody($this->mailbox, $uid, true);
    }
@@ -2086,7 +2013,7 @@
   */
  function &get_raw_headers($uid)
    {
    return iil_C_FetchPartHeader($this->conn, $this->mailbox, $uid, true);
        return $this->conn->fetchPartHeader($this->mailbox, $uid, true);
    }
    
@@ -2097,7 +2024,7 @@
   */ 
  function print_raw_body($uid)
    {
    iil_C_HandlePartBody($this->conn, $this->mailbox, $uid, true, NULL, NULL, true);
        $this->conn->handlePartBody($this->mailbox, $uid, true, NULL, NULL, true);
    }
@@ -2118,9 +2045,9 @@
    list($uids, $all_mode) = $this->_parse_uids($uids, $mailbox);
    if (strpos($flag, 'UN') === 0)
      $result = iil_C_UnFlag($this->conn, $mailbox, $uids, substr($flag, 2));
            $result = $this->conn->unflag($mailbox, $uids, substr($flag, 2));
    else
      $result = iil_C_Flag($this->conn, $mailbox, $uids, $flag);
            $result = $this->conn->flag($mailbox, $uids, $flag);
    if ($result >= 0) {
      // reload message headers if cached
@@ -2177,15 +2104,14 @@
    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,
                $saved = $this->conn->appendFromFile($mailbox, $message,
          $headers, $separator.$separator);
        }
      else
        $saved = iil_C_Append($this->conn, $mailbox, $message);
                $saved = $this->conn->append($mailbox, $message);
      }
    if ($saved)
      {
        if ($saved) {
      // increase messagecount of the target mailbox
      $this->_set_messagecount($mailbox, 'ALL', 1);
      }
@@ -2216,8 +2142,7 @@
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true))
      {
        if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true)) {
      if (in_array($tbox, $this->default_folders))
        $this->create_mailbox($tbox, true);
      else
@@ -2232,8 +2157,8 @@
      }
    // move messages
    $iil_move = iil_C_Move($this->conn, $uids, $from_mbox, $to_mbox);
    $moved = !($iil_move === false || $iil_move < 0);
        $move = $this->conn->move($uids, $from_mbox, $to_mbox);
        $moved = !($move === false || $move < 0);
    // send expunge command in order to have the moved message
    // really deleted from the source mailbox
@@ -2298,8 +2223,7 @@
      return false;
    // make sure mailbox exists
    if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true))
      {
        if ($to_mbox != 'INBOX' && !$this->mailbox_exists($tbox, true)) {
      if (in_array($tbox, $this->default_folders))
        $this->create_mailbox($tbox, true);
      else
@@ -2307,8 +2231,8 @@
      }
    // copy messages
    $iil_copy = iil_C_Copy($this->conn, $uids, $from_mbox, $to_mbox);
    $copied = !($iil_copy === false || $iil_copy < 0);
        $copy = $this->conn->copy($uids, $from_mbox, $to_mbox);
        $copied = !($copy === false || $copy < 0);
    if ($copied) {
      $this->_clear_messagecount($to_mbox);
@@ -2335,7 +2259,7 @@
    if (empty($uids))
      return false;
    $deleted = iil_C_Delete($this->conn, $mailbox, $uids);
        $deleted = $this->conn->delete($mailbox, $uids);
    if ($deleted) {
      // send expunge command in order to have the deleted message
@@ -2383,13 +2307,14 @@
    $mailbox = !empty($mbox_name) ? $this->mod_mailbox($mbox_name) : $this->mailbox;
    $msg_count = $this->_messagecount($mailbox, 'ALL');
    
    if ($msg_count>0)
      {
      $cleared = iil_C_ClearFolder($this->conn, $mailbox);
        if (!$msg_count) {
            return 0;
        }
        $cleared = $this->conn->clearFolder($mailbox);
      
      // make sure the message count cache is cleared as well
      if ($cleared)
        {
        if ($cleared) {
        $this->clear_message_cache($mailbox.'.msg');      
        $a_mailbox_cache = $this->get_cache('messagecount');
        unset($a_mailbox_cache[$mailbox]);
@@ -2397,9 +2322,6 @@
        }
        
      return $cleared;
      }
    else
      return 0;
    }
@@ -2434,10 +2356,9 @@
    else
      $a_uids = NULL;
    $result = iil_C_Expunge($this->conn, $mailbox, $a_uids);
        $result = $this->conn->expunge($mailbox, $a_uids);
    if ($result>=0 && $clear_cache)
      {
        if ($result>=0 && $clear_cache) {
      $this->clear_message_cache($mailbox.'.msg');
      $this->_clear_messagecount($mailbox);
      }
@@ -2462,12 +2383,12 @@
        $all = true;
        }
      // get UIDs from current search set
      // @TODO: skip iil_C_FetchUIDs() and work with IDs instead of UIDs (?)
            // @TODO: skip fetchUIDs() and work with IDs instead of UIDs (?)
      else {
        if ($this->search_threads)
          $uids = iil_C_FetchUIDs($this->conn, $mailbox, array_keys($this->search_set['depth']));
                    $uids = $this->conn->fetchUIDs($mailbox, array_keys($this->search_set['depth']));
        else
          $uids = iil_C_FetchUIDs($this->conn, $mailbox, $this->search_set);
                    $uids = $this->conn->fetchUIDs($mailbox, $this->search_set);
      
        // save ID-to-UID mapping in local cache
        if (is_array($uids))
@@ -2489,9 +2410,108 @@
    }
    
    /**
     * Translate UID to message ID
     *
     * @param int    Message UID
     * @param string Mailbox name
     * @return int   Message ID
     */
    function get_id($uid, $mbox_name=NULL)
    {
        $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
        return $this->_uid2id($uid, $mailbox);
    }
    /**
     * Translate message number to UID
     *
     * @param int    Message ID
     * @param string Mailbox name
     * @return int   Message UID
     */
    function get_uid($id,$mbox_name=NULL)
    {
        $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
        return $this->_id2uid($id, $mailbox);
    }
  /* --------------------------------
   *        folder managment
   * --------------------------------*/
    /**
     * Public method for mailbox listing.
     *
     * Converts mailbox name with root dir first
     *
     * @param   string  Optional root folder
     * @param   string  Optional filter for mailbox listing
     * @return  array   List of mailboxes/folders
     * @access  public
     */
    function list_mailboxes($root='', $filter='*')
    {
        $a_out = array();
        $a_mboxes = $this->_list_mailboxes($root, $filter);
        foreach ($a_mboxes as $mbox_row) {
            $name = $this->mod_mailbox($mbox_row, 'out');
            if (strlen($name))
                $a_out[] = $name;
        }
        // INBOX should always be available
        if (!in_array('INBOX', $a_out))
            array_unshift($a_out, 'INBOX');
        // sort mailboxes
        $a_out = $this->_sort_mailbox_list($a_out);
        return $a_out;
    }
    /**
     * Private method for mailbox listing
     *
     * @return  array   List of mailboxes/folders
     * @see     rcube_imap::list_mailboxes()
     * @access  private
     */
    private function _list_mailboxes($root='', $filter='*')
    {
        $a_defaults = $a_out = array();
        // get cached folder list
        $a_mboxes = $this->get_cache('mailboxes');
        if (is_array($a_mboxes))
            return $a_mboxes;
        // Give plugins a chance to provide a list of mailboxes
        $data = rcmail::get_instance()->plugins->exec_hook('list_mailboxes',
            array('root'=>$root,'filter'=>$filter));
        if (isset($data['folders'])) {
            $a_folders = $data['folders'];
        }
        else {
            // retrieve list of folders from IMAP server
            $a_folders = $this->conn->listSubscribed($this->mod_mailbox($root), $filter);
        }
        if (!is_array($a_folders) || !sizeof($a_folders))
            $a_folders = array();
        // write mailboxlist to cache
        $this->update_cache('mailboxes', $a_folders);
        return $a_folders;
    }
  /**
   * Get a list of all folders available on the IMAP server
@@ -2507,11 +2527,10 @@
      return $sa_unsubscribed;
      
    // retrieve list of folders from IMAP server
    $a_mboxes = iil_C_ListMailboxes($this->conn, $this->mod_mailbox($root), '*');
        $a_mboxes = $this->conn->listMailboxes($this->mod_mailbox($root), '*');
    // modify names with root dir
    foreach ($a_mboxes as $mbox_name)
      {
        foreach ($a_mboxes as $mbox_name) {
      $name = $this->mod_mailbox($mbox_name, 'out');
      if (strlen($name))
        $a_folders[] = $name;
@@ -2532,7 +2551,7 @@
  function get_quota()
    {
    if ($this->get_capability('QUOTA'))
      return iil_C_GetQuota($this->conn);
            return $this->conn->getQuota();
   
    return false;
    }
@@ -2584,7 +2603,7 @@
    // reduce mailbox name to 100 chars
    $name = substr($name, 0, 100);
    $abs_name = $this->mod_mailbox($name);
    $result = iil_C_CreateFolder($this->conn, $abs_name);
        $result = $this->conn->createFolder($abs_name);
    // try to subscribe it
    if ($result && $subscribe)
@@ -2618,21 +2637,20 @@
    
    // unsubscribe folder
    if ($subscribed)
      iil_C_UnSubscribe($this->conn, $mailbox);
            $this->conn->unsubscribe($mailbox);
    if (strlen($abs_name))
      $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
            $result = $this->conn->renameFolder($mailbox, $abs_name);
    if ($result)
      {
        if ($result) {
      $delm = $this->get_hierarchy_delimiter();
      
      // check if mailbox children are subscribed
      foreach ($a_subscribed as $c_subscribed)
        if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed))
          {
          iil_C_UnSubscribe($this->conn, $c_subscribed);
          iil_C_Subscribe($this->conn, preg_replace('/^'.preg_quote($mailbox, '/').'/', $abs_name, $c_subscribed));
                if (preg_match('/^'.preg_quote($mailbox.$delm, '/').'/', $c_subscribed)) {
                    $this->conn->unsubscribe($c_subscribed);
                    $this->conn->subscribe(preg_replace('/^'.preg_quote($mailbox, '/').'/',
                        $abs_name, $c_subscribed));
          }
      // clear cache
@@ -2642,7 +2660,7 @@
    // try to subscribe it
    if ($result && $subscribed)
      iil_C_Subscribe($this->conn, $abs_name);
            $this->conn->subscribe($abs_name);
    return $result ? $name : false;
    }
@@ -2663,30 +2681,31 @@
    else if (is_string($mbox_name) && strlen($mbox_name))
      $a_mboxes = explode(',', $mbox_name);
    if (is_array($a_mboxes))
      foreach ($a_mboxes as $mbox_name)
        {
        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(''),
                $sub_mboxes = $this->conn->listMailboxes($this->mod_mailbox(''),
     $mbox_name . $this->delimiter . '*');
        // unsubscribe mailbox before deleting
        iil_C_UnSubscribe($this->conn, $mailbox);
                $this->conn->unsubscribe($mailbox);
        // send delete command to server
        $result = iil_C_DeleteFolder($this->conn, $mailbox);
                $result = $this->conn->deleteFolder($mailbox);
        if ($result >= 0) {
          $deleted = true;
          $this->clear_message_cache($mailbox.'.msg');
     }
     
        foreach ($sub_mboxes as $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);
                        $this->conn->unsubscribe($c_mbox);
                        $result = $this->conn->deleteFolder($c_mbox);
            if ($result >= 0) {
              $deleted = true;
             $this->clear_message_cache($c_mbox.'.msg');
                        }
                    }
            }
          }
        }
@@ -2705,8 +2724,7 @@
  function create_default_folders()
    {
    // create default folders if they do not exist
    foreach ($this->default_folders as $folder)
      {
        foreach ($this->default_folders as $folder) {
      if (!$this->mailbox_exists($folder))
        $this->create_mailbox($folder, true);
      else if (!$this->mailbox_exists($folder, true))
@@ -2729,11 +2747,11 @@
        return true;
      if ($subscription) {
        if ($a_folders = iil_C_ListSubscribed($this->conn, $this->mod_mailbox(''), $mbox_name))
                if ($a_folders = $this->conn->listSubscribed($this->mod_mailbox(''), $mbox_name))
          return true;
        }
      else {
        $a_folders = iil_C_ListMailboxes($this->conn, $this->mod_mailbox(''), $mbox_mbox);
                $a_folders = $this->conn->listMailboxes($this->mod_mailbox(''), $mbox_mbox);
   
   if (is_array($a_folders) && in_array($this->mod_mailbox($mbox_name), $a_folders))
          return true;
@@ -2744,13 +2762,35 @@
    }
    /**
     * Modify folder name for input/output according to root dir and namespace
     *
     * @param string  Folder name
     * @param string  Mode
     * @return string Folder name
     */
    function mod_mailbox($mbox_name, $mode='in')
    {
        if ($mbox_name == 'INBOX')
            return $mbox_name;
        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;
    }
  /* --------------------------------
   *   internal caching methods
   * --------------------------------*/
  /**
   * @access private
     * @access public
   */
  function set_caching($set)
    {
@@ -2761,13 +2801,12 @@
    }
  /**
   * @access private
     * @access public
   */
  function get_cache($key)
    {
    // read cache (if it was not read before)
    if (!count($this->cache) && $this->caching_enabled)
      {
        if (!count($this->cache) && $this->caching_enabled) {
      return $this->_read_cache_record($key);
      }
    
@@ -2777,7 +2816,7 @@
  /**
   * @access private
   */
  function update_cache($key, $data)
    private function update_cache($key, $data)
    {
    $this->cache[$key] = $data;
    $this->cache_changed = true;
@@ -2787,12 +2826,10 @@
  /**
   * @access private
   */
  function write_cache()
    private function write_cache()
    {
    if ($this->caching_enabled && $this->cache_changed)
      {
      foreach ($this->cache as $key => $data)
        {
        if ($this->caching_enabled && $this->cache_changed) {
            foreach ($this->cache as $key => $data) {
        if ($this->cache_changes[$key])
          $this->_write_cache_record($key, serialize($data));
        }
@@ -2800,15 +2837,14 @@
    }
  /**
   * @access private
     * @access public
   */
  function clear_cache($key=NULL)
    {
    if (!$this->caching_enabled)
      return;
    
    if ($key===NULL)
      {
        if ($key===NULL) {
      foreach ($this->cache as $key => $data)
        $this->_clear_cache_record($key);
@@ -2816,8 +2852,7 @@
      $this->cache_changed = false;
      $this->cache_changes = array();
      }
    else
      {
        else {
      $this->_clear_cache_record($key);
      $this->cache_changes[$key] = false;
      unset($this->cache[$key]);
@@ -2829,18 +2864,16 @@
   */
  private function _read_cache_record($key)
    {
    if ($this->db)
      {
        if ($this->db) {
      // get cached data from DB
      $sql_result = $this->db->query(
        "SELECT cache_id, data, cache_key
         FROM ".get_table_name('cache')."
         WHERE  user_id=?
    AND cache_key LIKE 'IMAP.%'",
                "SELECT cache_id, data, cache_key ".
                "FROM ".get_table_name('cache').
                " WHERE user_id=? ".
               "AND cache_key LIKE 'IMAP.%'",
        $_SESSION['user_id']);
      while ($sql_arr = $this->db->fetch_assoc($sql_result))
        {
            while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
   $sql_key = preg_replace('/^IMAP\./', '', $sql_arr['cache_key']);
        $this->cache_keys[$sql_key] = $sql_arr['cache_id'];
   if (!isset($this->cache[$sql_key]))
@@ -2860,34 +2893,32 @@
      return false;
    // update existing cache record
    if ($this->cache_keys[$key])
      {
        if ($this->cache_keys[$key]) {
      $this->db->query(
        "UPDATE ".get_table_name('cache')."
         SET    created=". $this->db->now().", data=?
         WHERE  user_id=?
         AND    cache_key=?",
                "UPDATE ".get_table_name('cache').
                " SET created=". $this->db->now().", data=? ".
                "WHERE user_id=? ".
                "AND cache_key=?",
        $data,
        $_SESSION['user_id'],
        'IMAP.'.$key);
      }
    // add new cache record
    else
      {
        else {
      $this->db->query(
        "INSERT INTO ".get_table_name('cache')."
         (created, user_id, cache_key, data)
         VALUES (".$this->db->now().", ?, ?, ?)",
                "INSERT INTO ".get_table_name('cache').
                " (created, user_id, cache_key, data) ".
                "VALUES (".$this->db->now().", ?, ?, ?)",
        $_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=?",
                "SELECT cache_id ".
                "FROM ".get_table_name('cache').
                " WHERE user_id=? ".
                "AND cache_key=?",
        $_SESSION['user_id'],
        'IMAP.'.$key);
                                     
@@ -2902,9 +2933,9 @@
  private function _clear_cache_record($key)
    {
    $this->db->query(
      "DELETE FROM ".get_table_name('cache')."
       WHERE  user_id=?
       AND    cache_key=?",
            "DELETE FROM ".get_table_name('cache').
            " WHERE user_id=? ".
            "AND cache_key=?",
      $_SESSION['user_id'],
      'IMAP.'.$key);
      
@@ -2917,13 +2948,12 @@
   *   message caching methods
   * --------------------------------*/
   
  /**
   * Checks if the cache is up-to-date
   *
   * @param string Mailbox name
   * @param string Internal cache key
   * @return int   Cache status: -3 = off, -2 = incomplete, -1 = dirty
     * @return int   Cache status: -3 = off, -2 = incomplete, -1 = dirty, 1 = OK
   */
  private function check_cache_status($mailbox, $cache_key)
  {
@@ -2946,7 +2976,10 @@
    if ($cache_count==$msg_count) {
      if ($this->skip_deleted) {
   $h_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:*", 'UID', $this->skip_deleted);
               $h_index = $this->conn->fetchHeaderIndex($mailbox, "1:*", 'UID', $this->skip_deleted);
                if (empty($h_index))
                    return -2;
   if (sizeof($h_index) == $cache_count) {
     $cache_index = array_flip($cache_index);
@@ -2959,7 +2992,7 @@
   return -2;
      } else {
        // get UID of message with highest index
        $uid = iil_C_ID2UID($this->conn, $mailbox, $msg_count);
                $uid = $this->conn->ID2UID($mailbox, $msg_count);
        $cache_uid = array_pop($cache_index);
      
        // uids of highest message matches -> cache seems OK
@@ -2983,35 +3016,32 @@
    {
    $cache_key = "$key:$from:$to:$sort_field:$sort_order";
    
    $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]))
      {
        if ($this->caching_enabled && !isset($this->cache[$cache_key])) {
      $this->cache[$cache_key] = array();
      $sql_result = $this->db->limitquery(
        "SELECT idx, uid, headers
         FROM ".get_table_name('messages')."
         WHERE  user_id=?
         AND    cache_key=?
         ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".strtoupper($sort_order),
                "SELECT idx, uid, headers".
                " FROM ".get_table_name('messages').
                " WHERE user_id=?".
                " AND cache_key=?".
                " ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".strtoupper($sort_order),
        $from,
        $to-$from,
        $_SESSION['user_id'],
        $key);
      while ($sql_arr = $this->db->fetch_assoc($sql_result))
        {
            while ($sql_arr = $this->db->fetch_assoc($sql_result)) {
        $uid = $sql_arr['uid'];
        $this->cache[$cache_key][$uid] =  $this->db->decode(unserialize($sql_arr['headers']));
        // featch headers if unserialize failed
        if (empty($this->cache[$cache_key][$uid]))
          $this->cache[$cache_key][$uid] = iil_C_FetchHeader($this->conn, preg_replace('/.msg$/', '', $key), $uid, true, $this->fetch_add_headers);
                    $this->cache[$cache_key][$uid] = $this->conn->fetchHeader(
                            preg_replace('/.msg$/', '', $key), $uid, true, $this->fetch_add_headers);
        }
      }
@@ -3025,20 +3055,18 @@
    {
    $internal_key = 'message';
    
    if ($this->caching_enabled && !isset($this->icache[$internal_key][$uid]))
      {
        if ($this->caching_enabled && !isset($this->icache[$internal_key][$uid])) {
      $sql_result = $this->db->query(
        "SELECT idx, headers, structure
         FROM ".get_table_name('messages')."
         WHERE  user_id=?
         AND    cache_key=?
         AND    uid=?",
                "SELECT idx, headers, structure".
                " FROM ".get_table_name('messages').
                " WHERE user_id=?".
                " AND cache_key=?".
                " AND uid=?",
        $_SESSION['user_id'],
        $key,
        $uid);
      if ($sql_arr = $this->db->fetch_assoc($sql_result))
        {
            if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
   $this->uid_id_map[preg_replace('/\.msg$/', '', $key)][$uid] = $sql_arr['idx'];
        $this->icache[$internal_key][$uid] = $this->db->decode(unserialize($sql_arr['headers']));
        if (is_object($this->icache[$internal_key][$uid]) && !empty($sql_arr['structure']))
@@ -3069,11 +3097,11 @@
    
    $sa_message_index[$key] = array();
    $sql_result = $this->db->query(
      "SELECT idx, uid
       FROM ".get_table_name('messages')."
       WHERE  user_id=?
       AND    cache_key=?
       ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
            "SELECT idx, uid".
            " FROM ".get_table_name('messages').
            " WHERE user_id=?".
            " AND cache_key=?".
            " ORDER BY ".$this->db->quote_identifier($sort_field)." ".$sort_order,
      $_SESSION['user_id'],
      $key);
@@ -3102,37 +3130,40 @@
    // check for an existing record (probly headers are cached but structure not)
    if (!$force) {
      $sql_result = $this->db->query(
        "SELECT message_id
         FROM ".get_table_name('messages')."
         WHERE  user_id=?
         AND    cache_key=?
         AND    uid=?",
                "SELECT message_id".
                " FROM ".get_table_name('messages').
                " WHERE user_id=?".
                " AND cache_key=?".
                " AND uid=?",
        $_SESSION['user_id'],
        $key,
        $headers->uid);
      if ($sql_arr = $this->db->fetch_assoc($sql_result))
        $message_id = $sql_arr['message_id'];
      }
    // update cache record
    if ($message_id)
      {
        if ($message_id) {
      $this->db->query(
        "UPDATE ".get_table_name('messages')."
         SET   idx=?, headers=?, structure=?
         WHERE message_id=?",
                "UPDATE ".get_table_name('messages').
                " SET idx=?, headers=?, structure=?".
                " WHERE message_id=?",
        $index,
        serialize($this->db->encode(clone $headers)),
        is_object($struct) ? serialize($this->db->encode(clone $struct)) : NULL,
        $message_id
        );
      }
    else  // insert new record
      {
        else { // insert new record
      $this->db->query(
        "INSERT INTO ".get_table_name('messages')."
         (user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
         VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
                "INSERT INTO ".get_table_name('messages').
                " (user_id, del, cache_key, created, idx, uid, subject, ".
                $this->db->quoteIdentifier('from').", ".
                $this->db->quoteIdentifier('to').", ".
                "cc, date, size, headers, structure)".
                " VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".
                $this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
        $_SESSION['user_id'],
        $key,
        $index,
@@ -3157,10 +3188,10 @@
      return;
    
    $this->db->query(
      "DELETE FROM ".get_table_name('messages')."
      WHERE user_id=?
      AND cache_key=?
      AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
            "DELETE FROM ".get_table_name('messages').
            " WHERE user_id=?".
            " AND cache_key=?".
            " AND ".($idx ? "idx" : "uid")." IN (".$this->db->array2list($ids, 'integer').")",
      $_SESSION['user_id'],
      $key);
    }
@@ -3174,10 +3205,10 @@
      return;
    
    $this->db->query(
      "DELETE FROM ".get_table_name('messages')."
       WHERE user_id=?
       AND cache_key=?
       AND idx>=?",
            "DELETE FROM ".get_table_name('messages').
            " WHERE user_id=?".
            " AND cache_key=?".
            " AND idx>=?",
      $_SESSION['user_id'], $key, $start_index);
    }
@@ -3197,10 +3228,10 @@
      }
    $sql_result = $this->db->query(
      "SELECT MIN(idx) AS minidx
      FROM ".get_table_name('messages')."
      WHERE  user_id=?
      AND    cache_key=?"
            "SELECT MIN(idx) AS minidx".
            " FROM ".get_table_name('messages').
            " WHERE  user_id=?".
            " AND    cache_key=?"
      .(!empty($uids) ? " AND uid IN (".$this->db->array2list($uids, 'integer').")" : ''),
      $_SESSION['user_id'],
      $key);
@@ -3237,8 +3268,7 @@
    $c = count($a);
    $j = 0;
    foreach ($a as $val)
      {
        foreach ($a as $val) {
      $j++;
      $address = trim($val['address']);
      $name = trim($val['name']);
@@ -3255,7 +3285,8 @@
      
      $out[$j] = array('name' => $name,
                       'mailto' => $address,
                       'string' => $string);
                'string' => $string
            );
      if ($max && $j==$max)
        break;
@@ -3280,6 +3311,7 @@
    $pid = 0;
    $tnef_parts = array();
    $tnef_arr = tnef_decode($part->body);
    foreach ($tnef_arr as $winatt) {
      $tpart = new rcube_message_part;
      $tpart->filename = $winatt["name"];
@@ -3383,23 +3415,22 @@
    $count = count($a);
    // should be in format "charset?encoding?base64_string"
    if ($count >= 3)
      {
        if ($count >= 3) {
      for ($i=2; $i<$count; $i++)
        $rest.=$a[$i];
      if (($a[1]=="B")||($a[1]=="b"))
            if (($a[1]=='B') || ($a[1]=='b'))
        $rest = base64_decode($rest);
      else if (($a[1]=="Q")||($a[1]=="q"))
        {
        $rest = str_replace("_", " ", $rest);
            else if (($a[1]=='Q') || ($a[1]=='q')) {
                $rest = str_replace('_', ' ', $rest);
        $rest = quoted_printable_decode($rest);
        }
      return rcube_charset_convert($rest, $a[0]);
      }
    else
      return $str;    // we dont' know what to do with this
        // we dont' know what to do with this
        return $str;
    }
@@ -3412,23 +3443,16 @@
   */
  function mime_decode($input, $encoding='7bit')
    {
    switch (strtolower($encoding))
      {
        switch (strtolower($encoding)) {
      case 'quoted-printable':
        return quoted_printable_decode($input);
        break;
      case 'base64':
        return base64_decode($input);
        break;
      case 'x-uuencode':
      case 'x-uue':
      case 'uue':
      case 'uuencode':
        return convert_uudecode($input);
        break;
      case '7bit':
      default:
        return $input;
@@ -3450,57 +3474,6 @@
    // defaults to what is specified in the class header
    return rcube_charset_convert($body,  $this->default_charset);
    }
  /**
   * Translate UID to message ID
   *
   * @param int    Message UID
   * @param string Mailbox name
   * @return int   Message ID
   */
  function get_id($uid, $mbox_name=NULL)
    {
      $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
      return $this->_uid2id($uid, $mailbox);
    }
  /**
   * Translate message number to UID
   *
   * @param int    Message ID
   * @param string Mailbox name
   * @return int   Message UID
   */
  function get_uid($id,$mbox_name=NULL)
    {
      $mailbox = $mbox_name ? $this->mod_mailbox($mbox_name) : $this->mailbox;
      return $this->_id2uid($id, $mailbox);
    }
  /**
   * Modify folder name for input/output according to root dir and namespace
   *
   * @param string  Folder name
   * @param string  Mode
   * @return string Folder name
   */
  function mod_mailbox($mbox_name, $mode='in')
    {
    if ($mbox_name == 'INBOX')
      return $mbox_name;
    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;
    }
@@ -3531,9 +3504,8 @@
    $delimiter = $this->get_hierarchy_delimiter();
    // find default folders and skip folders starting with '.'
    foreach ($a_folders as $i => $folder)
      {
      if ($folder{0}=='.')
        foreach ($a_folders as $i => $folder) {
            if ($folder[0] == '.')
        continue;
      if (($p = array_search($folder, $this->default_folders)) !== false && !$a_defaults[$p])
@@ -3588,7 +3560,7 @@
      $mbox_name = $this->mailbox;
      
    if (!isset($this->uid_id_map[$mbox_name][$uid]))
      $this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
            $this->uid_id_map[$mbox_name][$uid] = $this->conn->UID2ID($mbox_name, $uid);
    return $this->uid_id_map[$mbox_name][$uid];
    }
@@ -3604,7 +3576,7 @@
    if ($uid = array_search($id, (array)$this->uid_id_map[$mbox_name]))
      return $uid;
    $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
        $uid = $this->conn->ID2UID($mbox_name, $id);
    $this->uid_id_map[$mbox_name][$uid] = $id;
    
    return $uid;
@@ -3620,20 +3592,18 @@
    $updated = false;
    if (is_array($a_mboxes))
      foreach ($a_mboxes as $i => $mbox_name)
        {
            foreach ($a_mboxes as $i => $mbox_name) {
        $mailbox = $this->mod_mailbox($mbox_name);
        $a_mboxes[$i] = $mailbox;
        if ($mode=='subscribe')
          $updated = iil_C_Subscribe($this->conn, $mailbox);
                    $updated = $this->conn->subscribe($mailbox);
        else if ($mode=='unsubscribe')
          $updated = iil_C_UnSubscribe($this->conn, $mailbox);
                    $updated = $this->conn->unsubscribe($mailbox);
        }
    // get cached mailbox list
    if ($updated)
      {
        if ($updated) {
      $a_mailbox_cache = $this->get_cache('mailboxes');
      if (!is_array($a_mailbox_cache))
        return $updated;
@@ -3692,8 +3662,7 @@
    $a_mailbox_cache = $this->get_cache('messagecount');
    if (is_array($a_mailbox_cache[$mailbox]))
      {
        if (is_array($a_mailbox_cache[$mailbox])) {
      unset($a_mailbox_cache[$mailbox]);
      $this->update_cache('messagecount', $a_mailbox_cache);
      }
@@ -3710,10 +3679,9 @@
    $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
    $lines = explode("\n", $headers);
    $c = count($lines);
    for ($i=0; $i<$c; $i++)
      {
      if ($p = strpos($lines[$i], ': '))
        {
        for ($i=0; $i<$c; $i++) {
            if ($p = strpos($lines[$i], ': ')) {
        $field = strtolower(substr($lines[$i], 0, $p));
        $value = trim(substr($lines[$i], $p+1));
        if (!empty($value))
@@ -3734,14 +3702,12 @@
    $a = rcube_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
    $result = array();
    foreach ($a as $key => $val)
      {
        foreach ($a as $key => $val) {
      $val = preg_replace("/([\"\w])</", "$1 <", $val);
      $sub_a = rcube_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
      $result[$key]['name'] = '';
      foreach ($sub_a as $k => $v)
        {
            foreach ($sub_a as $k => $v) {
   // use angle brackets in regexp to not handle names with @ sign
        if (preg_match('/^<\S+@\S+>$/', $v))
          $result[$key]['address'] = trim($v, '<>');
@@ -3792,7 +3758,7 @@
/**
 * Class for sorting an array of iilBasicHeader objects in a predetermined order.
 * Class for sorting an array of rcube_mail_header objects in a predetermined order.
 *
 * @package Mail
 * @author Eric Stadtherr
@@ -3814,7 +3780,7 @@
   /**
    * Sort the array of header objects
    *
    * @param array Array of iilBasicHeader objects indexed by UID
     * @param array Array of rcube_mail_header objects indexed by UID
    */
   function sort_headers(&$headers)
   {