From e70d6ea64e711096af36b1234f8545b870ea5f45 Mon Sep 17 00:00:00 2001
From: thomascube <thomas@roundcube.net>
Date: Sat, 05 Apr 2008 08:49:21 -0400
Subject: [PATCH] Apply changes from trunk to 0.1-stable

---
 program/include/rcube_imap.inc |  727 ++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 498 insertions(+), 229 deletions(-)

diff --git a/program/include/rcube_imap.inc b/program/include/rcube_imap.inc
index f8e9e0a..9a59485 100644
--- a/program/include/rcube_imap.inc
+++ b/program/include/rcube_imap.inc
@@ -5,7 +5,7 @@
  | program/include/rcube_imap.inc                                        |
  |                                                                       |
  | This file is part of the RoundCube Webmail client                     |
- | Copyright (C) 2005-2006, RoundCube Dev. - Switzerland                 |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland                 |
  | Licensed under the GNU GPL                                            |
  |                                                                       |
  | PURPOSE:                                                              |
@@ -21,7 +21,7 @@
 */
 
 
-/**
+/*
  * Obtain classes from the Iloha IMAP library
  */
 require_once('lib/imap.inc');
@@ -33,13 +33,13 @@
  *
  * This is a wrapper that implements the Iloha IMAP Library (IIL)
  *
- * @package    RoundCube Webmail
+ * @package    Mail
  * @author     Thomas Bruederli <roundcube@gmail.com>
- * @version    1.36
+ * @version    1.40
  * @link       http://ilohamail.org
  */
 class rcube_imap
-  {
+{
   var $db;
   var $conn;
   var $root_ns = '';
@@ -51,6 +51,7 @@
   var $sort_order = 'DESC';
   var $delimiter = NULL;
   var $caching_enabled = FALSE;
+  var $default_charset = 'ISO-8859-1';
   var $default_folders = array('INBOX');
   var $default_folders_lc = array('inbox');
   var $cache = array();
@@ -65,12 +66,13 @@
   var $search_string = '';
   var $search_charset = '';
   var $debug_level = 1;
+  var $error_code = 0;
 
 
   /**
    * Object constructor
    *
-   * @param  object  Database connection
+   * @param object DB Database connection
    */
   function __construct($db_conn)
     {
@@ -96,17 +98,17 @@
    * @param  string   Username for IMAP account
    * @param  string   Password for IMAP account
    * @param  number   Port to connect to
-   * @param  boolean  Use SSL connection
+   * @param  string   SSL schema (either ssl or tls) or null if plain connection
    * @return boolean  TRUE on success, FALSE on failure
    * @access public
    */
-  function connect($host, $user, $pass, $port=143, $use_ssl=FALSE)
+  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 && in_array('openssl', get_loaded_extensions()))
-      $ICL_SSL = TRUE;
+      $ICL_SSL = $use_ssl == 'imaps' ? 'ssl' : $use_ssl;
     else if ($use_ssl)
       {
       raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
@@ -131,6 +133,7 @@
     // write error log
     else if (!$this->conn && $GLOBALS['iil_error'])
       {
+      $this->error_code = $GLOBALS['iil_errornum'];
       raise_error(array('code' => 403,
                        'type' => 'imap',
                        'message' => $GLOBALS['iil_error']), TRUE, FALSE);
@@ -198,6 +201,20 @@
     
     if (empty($this->delimiter))
       $this->get_hierarchy_delimiter();
+    }
+
+
+  /**
+   * Set default message charset
+   *
+   * This will be used for message decoding if a charset specification is not available
+   *
+   * @param  string   Charset string
+   * @access public
+   */
+  function set_charset($cs)
+    {
+    $this->default_charset = $ch;
     }
 
 
@@ -287,13 +304,14 @@
       
     $this->search_subject = $subject;
     $this->search_string = $str;
-    $this->search_set = is_array($msgs) ? $msgs : NULL;
+    $this->search_set = (array)$msgs;
     $this->search_charset = $charset;
     }
 
 
   /**
    * Return the saved search set as hash array
+   * @return array Search set
    */
   function get_search_set()
     {
@@ -382,8 +400,8 @@
    * Private method for mailbox listing
    *
    * @return  array   List of mailboxes/folders
+   * @see     rcube_imap::list_mailboxes()
    * @access  private
-   * @see     rcube_imap::list_mailboxes
    */
   function _list_mailboxes($root='', $filter='*')
     {
@@ -413,8 +431,8 @@
    * @param   string   Mailbox/folder name
    * @param   string   Mode for count [ALL|UNSEEN|RECENT]
    * @param   boolean  Force reading from server and update cache
-   * @return  number   Number of messages
-   * @access  public   
+   * @return  int      Number of messages
+   * @access  public
    */
   function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
     {
@@ -427,7 +445,7 @@
    * Private method for getting nr of messages
    *
    * @access  private
-   * @see     rcube_imap::messagecount
+   * @see     rcube_imap::messagecount()
    */
   function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
     {
@@ -438,8 +456,8 @@
       $mailbox = $this->mailbox;
       
     // count search set
-    if ($this->search_set && $mailbox == $this->mailbox && $mode == 'ALL')
-      return count($this->search_set);
+    if ($this->search_string && $mailbox == $this->mailbox && $mode == 'ALL' && !$force)
+      return count((array)$this->search_set);
 
     $a_mailbox_cache = $this->get_cache('messagecount');
     
@@ -496,7 +514,7 @@
    * convert mailbox name with root dir first
    *
    * @param   string   Mailbox/folder name
-   * @param   number   Current page to list
+   * @param   int      Current page to list
    * @param   string   Header field to sort by
    * @param   string   Sort order [ASC|DESC]
    * @return  array    Indexed array with message header objects
@@ -521,13 +539,10 @@
       return array();
 
     // use saved message set
-    if ($this->search_set && $mailbox == $this->mailbox)
+    if ($this->search_string && $mailbox == $this->mailbox)
       return $this->_list_header_set($mailbox, $this->search_set, $page, $sort_field, $sort_order);
 
-    if ($sort_field!=NULL)
-      $this->sort_field = $sort_field;
-    if ($sort_order!=NULL)
-      $this->sort_order = strtoupper($sort_order);
+    $this->_set_sort_order($sort_field, $sort_order);
 
     $max = $this->_messagecount($mailbox);
     $start_msg = ($this->list_page-1) * $this->page_size;
@@ -580,8 +595,9 @@
       $a_msg_headers = array();
       $deleted_count = $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, $cache_key);
 
-      // delete cached messages with a higher index than $max
-      $this->clear_message_cache($cache_key, $max);
+      // delete cached messages with a higher index than $max+1
+      // Changed $max to $max+1 to fix this bug : #1484295
+      $this->clear_message_cache($cache_key, $max + 1);
 
 
       // kick child process to sync cache
@@ -615,7 +631,7 @@
    *
    * @param   string   Mailbox/folder name
    * @param   array    List of message ids to list
-   * @param   number   Current page to list
+   * @param   int      Current page to list
    * @param   string   Header field to sort by
    * @param   string   Sort order [ASC|DESC]
    * @return  array    Indexed array with message header objects
@@ -632,7 +648,7 @@
    * Private method for listing a set of message headers
    *
    * @access  private
-   * @see     rcube_imap::list_header_set
+   * @see     rcube_imap::list_header_set()
    */
   function _list_header_set($mailbox, $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL)
     {
@@ -643,10 +659,7 @@
     if (!strlen($mailbox) || empty($msgs))
       return array();
 
-    if ($sort_field!=NULL)
-      $this->sort_field = $sort_field;
-    if ($sort_order!=NULL)
-      $this->sort_order = strtoupper($sort_order);
+    $this->_set_sort_order($sort_field, $sort_order);
 
     $max = count($msgs);
     $start_msg = ($this->list_page-1) * $this->page_size;
@@ -670,7 +683,7 @@
   /**
    * Helper function to get first and last index of the requested set
    *
-   * @param  number  message count
+   * @param  int     message count
    * @param  mixed   page number to show, or string 'all'
    * @return array   array with two values: first index, last index
    * @access private
@@ -712,7 +725,7 @@
    * @param  string  Message index to fetch
    * @param  array   Reference to message headers array
    * @param  array   Array with cache index
-   * @return number  Number of deleted messages
+   * @return int     Number of deleted messages
    * @access private
    */
   function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
@@ -760,13 +773,20 @@
    */
   function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
     {
-    if ($sort_field!=NULL)
-      $this->sort_field = $sort_field;
-    if ($sort_order!=NULL)
-      $this->sort_order = strtoupper($sort_order);
+    $this->_set_sort_order($sort_field, $sort_order);
 
     $mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
-    $key = "$mbox:".$this->sort_field.":".$this->sort_order.".msgi";
+    $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)
+    {
+      $this->cache[$key] = $a_msg_headers = array();
+      $this->_fetch_headers($mailbox, join(',', $this->search_set), $a_msg_headers, NULL);
+
+      foreach (iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order) as $i => $msg)
+        $this->cache[$key][] = $msg->uid;
+    }
 
     // have stored it in RAM
     if (isset($this->cache[$key]))
@@ -814,6 +834,9 @@
     }
 
 
+  /**
+   * @access private
+   */
   function sync_header_index($mailbox)
     {
     $cache_key = $mailbox.'.msg';
@@ -926,6 +949,8 @@
   
   /**
    * Refresh saved search set
+   *
+   * @return array Current search set
    */
   function refresh_search()
     {
@@ -934,6 +959,20 @@
       
     return $this->get_search_set();
     }
+  
+  
+  /**
+   * Check if the given message ID is part of the current search set
+   *
+   * @return boolean True on match or if no search request is stored
+   */
+  function in_searchset($msgid)
+  {
+    if (!empty($this->search_string))
+      return in_array("$msgid", (array)$this->search_set, true);
+    else
+      return true;
+  }
 
 
   /**
@@ -958,8 +997,8 @@
     // write headers cache
     if ($headers)
       {
-      if ($is_uid)
-        $this->uid_id_map[$mbox_name][$uid] = $headers->id;
+      if ($headers->uid && $headers->id)
+        $this->uid_id_map[$mailbox][$headers->uid] = $headers->id;
 
       $this->add_message_cache($mailbox.'.msg', $headers->id, $headers);
       }
@@ -972,8 +1011,8 @@
    * Fetch body structure from the IMAP server and build
    * an object structure similar to the one generated by PEAR::Mail_mimeDecode
    *
-   * @param Int Message UID to fetch
-   * @return object Standard object tree or False on failure
+   * @param int Message UID to fetch
+   * @return object stdClass Message part tree or False on failure
    */
   function &get_structure($uid)
     {
@@ -988,15 +1027,15 @@
     if (!($msg_id = $this->_uid2id($uid)))
       return FALSE;
 
-	$structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
-	$structure = iml_GetRawStructureArray($structure_str);
-	$struct = false;
-	
+    $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id); 
+    $structure = iml_GetRawStructureArray($structure_str);
+    $struct = false;
+
     // parse structure and add headers
     if (!empty($structure))
       {
       $this->_msg_id = $msg_id;
-      $headers = $this->get_headers($msg_id, NULL, FALSE);
+      $headers = $this->get_headers($uid);
       
       $struct = &$this->_structure_part($structure);
       $struct->headers = get_object_vars($headers);
@@ -1013,9 +1052,9 @@
       if ($this->caching_enabled)
         $this->add_message_cache($cache_key, $msg_id, $headers, $struct);
       }
-	
-	return $struct;
-	}
+      
+    return $struct;
+    }
 
   
   /**
@@ -1047,8 +1086,8 @@
       for ($i=0, $count=0; $i<count($part); $i++)
         if (is_array($part[$i]) && count($part[$i]) > 5)
           $struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id);
-
-      return $struct;      
+          
+      return $struct;
       }
     
     
@@ -1056,30 +1095,30 @@
     $struct->ctype_primary = strtolower($part[0]);
     $struct->ctype_secondary = strtolower($part[1]);
     $struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
-	
+
     // read content type parameters
-	if (is_array($part[2]))
-	  {
-	  $struct->ctype_parameters = array();
+    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];
         
       if (isset($struct->ctype_parameters['charset']))
         $struct->charset = $struct->ctype_parameters['charset'];
-	  }
-	  
-	// read content encoding
-	if (!empty($part[5]) && $part[5]!='NIL')
-	  {
-	  $struct->encoding = strtolower($part[5]);
-	  $struct->headers['content-transfer-encoding'] = $struct->encoding;
-	  }
-	  
-	// get part size
-	if (!empty($part[6]) && $part[6]!='NIL')
-	  $struct->size = intval($part[6]);
+      }
+    
+    // read content encoding
+    if (!empty($part[5]) && $part[5]!='NIL')
+      {
+      $struct->encoding = strtolower($part[5]);
+      $struct->headers['content-transfer-encoding'] = $struct->encoding;
+      }
+    
+    // get part size
+    if (!empty($part[6]) && $part[6]!='NIL')
+      $struct->size = intval($part[6]);
 
-	// read part disposition
+    // 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))
@@ -1099,32 +1138,47 @@
         if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
           $struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
       }
-      
-	// get part ID
-	if (!empty($part[3]) && $part[3]!='NIL')
-	  {
-	  $struct->content_id = $part[3];
-	  $struct->headers['content-id'] = $part[3];
-	  
-	  if (empty($struct->disposition))
-	    $struct->disposition = 'inline';
-	  }
+
+    // get part ID
+    if (!empty($part[3]) && $part[3]!='NIL')
+      {
+      $struct->content_id = $part[3];
+      $struct->headers['content-id'] = $part[3];
+    
+      if (empty($struct->disposition))
+        $struct->disposition = 'inline';
+      }
 
     // fetch message headers if message/rfc822
     if ($struct->ctype_primary=='message')
       {
       $headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER');
       $struct->headers = $this->_parse_headers($headers);
+      
+      if (is_array($part[8]) && empty($struct->parts))
+        $struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
       }
-  
-  	return $struct;
+      
+    // normalize filename property
+    if ($filename_mime = $struct->d_parameters['filename'] ? $struct->d_parameters['filename'] : $struct->ctype_parameters['name'])
+      $struct->filename = rcube_imap::decode_mime_string($filename_mime, $this->default_charset);
+    else if ($filename_encoded = $struct->d_parameters['filename*'] ? $struct->d_parameters['filename*'] : $struct->ctype_parameters['name*'])
+    {
+      // decode filename according to RFC 2231, Section 4
+      list($filename_charset,, $filename_urlencoded) = split('\'', $filename_encoded);
+      $struct->filename = rcube_charset_convert(urldecode($filename_urlencoded), $filename_charset);
+    }
+    else if (!empty($struct->headers['content-description']))
+      $struct->filename = rcube_imap::decode_mime_string($struct->headers['content-description'], $this->default_charset);
+      
+    return $struct;
     }
     
   
   /**
    * Return a flat array with references to all parts, indexed by part numbers
    *
-   * @param object Message body structure
+   * @param object rcube_message_part Message body structure
    * @return Array with part number -> object pairs
    */
   function get_mime_numbers(&$structure)
@@ -1138,7 +1192,7 @@
   /**
    * Helper method for recursive calls
    *
-   * @access 
+   * @access private
    */
   function _get_part_numbers(&$part, &$a_parts)
     {
@@ -1156,9 +1210,9 @@
    *
    * @param  int    Message UID
    * @param  string Part number
-   * @param  object Part object created by get_structure()
+   * @param  object rcube_message_part Part object created by get_structure()
    * @param  mixed  True to print part, ressource to write part contents in
-   * @return Message/part body if not printed
+   * @return string Message/part body if not printed
    */
   function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL)
     {
@@ -1181,23 +1235,30 @@
 
     if ($print)
       {
-      iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, ($o_part->encoding=='base64'?3:2));
-      $body = TRUE;
+      $mode = $o_part->encoding == 'base64' ? 3 : ($o_part->encoding == 'quoted-printable' ? 1 : 2);
+      $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, $mode);
+      
+      // we have to decode the part manually before printing
+      if ($mode == 1)
+        {
+        echo $this->mime_decode($body, $o_part->encoding);
+        $body = true;
+        }
       }
     else
       {
       $body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
 
       // decode part body
-      if ($o_part->encoding=='base64' || $o_part->encoding=='quoted-printable')
+      if ($o_part->encoding)
         $body = $this->mime_decode($body, $o_part->encoding);
 
       // convert charset (if text or message part)
       if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
         {
-        // assume ISO-8859-1 if no charset specified
+        // assume default if no charset specified
         if (empty($o_part->charset))
-          $o_part->charset = 'ISO-8859-1';
+          $o_part->charset = $this->default_charset;
 
         $body = rcube_charset_convert($body, $o_part->charset);
         }
@@ -1211,8 +1272,8 @@
    * Fetch message body of a specific message from the server
    *
    * @param  int    Message UID
-   * @return Message/part body
-   * @see    ::get_message_part()
+   * @return string Message/part body
+   * @see    rcube_imap::get_message_part()
    */
   function &get_body($uid, $part=1)
     {
@@ -1224,15 +1285,15 @@
    * Returns the whole message source as string
    *
    * @param int  Message UID
-   * @return Message source string
+   * @return string Message source string
    */
   function &get_raw_body($uid)
     {
     if (!($msg_id = $this->_uid2id($uid)))
       return FALSE;
 
-	$body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
-	$body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
+    $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
+    $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
 
     return $body;    
     }
@@ -1248,9 +1309,9 @@
     if (!($msg_id = $this->_uid2id($uid)))
       return FALSE;
 
-	print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
-	flush();
-	iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
+    print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
+    flush();
+    iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
     }
 
 
@@ -1258,8 +1319,8 @@
    * 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
-   * @return True on success, False on failure
+   * @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT, MDNSENT
+   * @return boolean True on success, False on failure
    */
   function set_flag($uids, $flag)
     {
@@ -1312,7 +1373,13 @@
     }
 
 
-  // append a mail message (source) to a specific mailbox
+  /**
+   * Append a mail message (source) to a specific mailbox
+   *
+   * @param string Target mailbox
+   * @param string Message source
+   * @return boolean True on success, False on error
+   */
   function save_message($mbox_name, &$message)
     {
     $mbox_name = stripslashes($mbox_name);
@@ -1332,7 +1399,14 @@
     }
 
 
-  // move a message from one mailbox to another
+  /**
+   * Move a message from one mailbox to another
+   *
+   * @param string List of UIDs to move, separated by comma
+   * @param string Target mailbox
+   * @param string Source mailbox
+   * @return boolean True on success, False on error
+   */
   function move_message($uids, $to_mbox, $from_mbox='')
     {
     $to_mbox = stripslashes($to_mbox);
@@ -1343,7 +1417,7 @@
     // make sure mailbox exists
     if (!in_array($to_mbox, $this->_list_mailboxes()))
       {
-      if (in_array(strtolower($to_mbox), $this->default_folders))
+      if (in_array($to_mbox, $this->default_folders))
         $this->create_mailbox($to_mbox, TRUE);
       else
         return FALSE;
@@ -1361,7 +1435,8 @@
     foreach ($a_uids as $uid)
       $a_mids[] = $this->_uid2id($uid, $from_mbox);
 
-    $moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
+    $iil_move = iil_C_Move($this->conn, join(',', $a_mids), $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
@@ -1395,7 +1470,13 @@
     }
 
 
-  // mark messages as deleted and expunge mailbox
+  /**
+   * Mark messages as deleted and expunge mailbox
+   *
+   * @param string List of UIDs to move, separated by comma
+   * @param string Source mailbox
+   * @return boolean True on success, False on error
+   */
   function delete_message($uids, $mbox_name='')
     {
     $mbox_name = stripslashes($mbox_name);
@@ -1447,7 +1528,12 @@
     }
 
 
-  // clear all messages in a specific mailbox
+  /**
+   * Clear all messages in a specific mailbox
+   *
+   * @param string Mailbox name
+   * @return int Above 0 on success
+   */
   function clear_mailbox($mbox_name=NULL)
     {
     $mbox_name = stripslashes($mbox_name);
@@ -1474,7 +1560,13 @@
     }
 
 
-  // send IMAP expunge command and clear cache
+  /**
+   * Send IMAP expunge command and clear cache
+   *
+   * @param string Mailbox name
+   * @param boolean False if cache should not be cleared
+   * @return boolean True on success
+   */
   function expunge($mbox_name='', $clear_cache=TRUE)
     {
     $mbox_name = stripslashes($mbox_name);
@@ -1483,14 +1575,19 @@
     }
 
 
-  // send IMAP expunge command and clear cache
+  /**
+   * Send IMAP expunge command and clear cache
+   *
+   * @see rcube_imap::expunge()
+   * @access private
+   */
   function _expunge($mailbox, $clear_cache=TRUE)
     {
     $result = iil_C_Expunge($this->conn, $mailbox);
 
     if ($result>=0 && $clear_cache)
       {
-      //$this->clear_message_cache($mailbox.'.msg');
+      $this->clear_message_cache($mailbox.'.msg');
       $this->_clear_messagecount($mailbox);
       }
       
@@ -1507,7 +1604,7 @@
    * Get a list of all folders available on the IMAP server
    * 
    * @param string IMAP root dir
-   * @return array Inbdexed array with folder names 
+   * @return array Indexed array with folder names
    */
   function list_unsubscribed($root='')
     {
@@ -1534,8 +1631,10 @@
 
 
   /**
-   * Get quota
+   * Get mailbox quota information
    * added by Nuny
+   * 
+   * @return mixed Quota info or False if not supported
    */
   function get_quota()
     {
@@ -1547,29 +1646,31 @@
 
 
   /**
-   * subscribe to a specific mailbox(es)
+   * Subscribe to a specific mailbox(es)
+   *
+   * @param array Mailbox name(s)
+   * @return boolean True on success
    */ 
-  function subscribe($mbox_name, $mode='subscribe')
+  function subscribe($a_mboxes)
     {
-    if (is_array($mbox_name))
-      $a_mboxes = $mbox_name;
-    else if (is_string($mbox_name) && strlen($mbox_name))
-      $a_mboxes = explode(',', $mbox_name);
-    
+    if (!is_array($a_mboxes))
+      $a_mboxes = array($a_mboxes);
+
     // let this common function do the main work
     return $this->_change_subscription($a_mboxes, 'subscribe');
     }
 
 
   /**
-   * unsubscribe mailboxes
+   * Unsubscribe mailboxes
+   *
+   * @param array Mailbox name(s)
+   * @return boolean True on success
    */
-  function unsubscribe($mbox_name)
+  function unsubscribe($a_mboxes)
     {
-    if (is_array($mbox_name))
-      $a_mboxes = $mbox_name;
-    else if (is_string($mbox_name) && strlen($mbox_name))
-      $a_mboxes = explode(',', $mbox_name);
+    if (!is_array($a_mboxes))
+      $a_mboxes = array($a_mboxes);
 
     // let this common function do the main work
     return $this->_change_subscription($a_mboxes, 'unsubscribe');
@@ -1596,11 +1697,11 @@
     $abs_name = $this->_mod_mailbox($name);
     $a_mailbox_cache = $this->get_cache('mailboxes');
 
-    if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array_nocase($abs_name, $a_mailbox_cache)))
+    if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
       $result = iil_C_CreateFolder($this->conn, $abs_name);
 
     // try to subscribe it
-    if ($subscribe)
+    if ($result && $subscribe)
       $this->subscribe($name);
 
     return $result ? $name : FALSE;
@@ -1612,7 +1713,7 @@
    *
    * @param string Mailbox to rename (as utf-7 string)
    * @param string New mailbox name (as utf-7 string)
-   * @param string Name of the renames mailbox, false on error
+   * @return string Name of the renames mailbox, False on error
    */
   function rename_mailbox($mbox_name, $new_name)
     {
@@ -1639,9 +1740,19 @@
     if (strlen($abs_name))
       $result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
 
-    // clear cache
     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));
+          }
+
+      // clear cache
       $this->clear_message_cache($mailbox.'.msg');
       $this->clear_cache('mailboxes');      
       }
@@ -1655,7 +1766,10 @@
 
 
   /**
-   * remove mailboxes from server
+   * Remove mailboxes from server
+   *
+   * @param string Mailbox name
+   * @return boolean True on success
    */
   function delete_mailbox($mbox_name)
     {
@@ -1665,6 +1779,8 @@
       $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)
@@ -1678,6 +1794,19 @@
         $result = iil_C_DeleteFolder($this->conn, $mailbox);
         if ($result>=0)
           $deleted = TRUE;
+
+        foreach ($all_mboxes as $c_mbox)
+          {
+          $regex = preg_quote($mailbox . $this->delimiter, '/');
+          $regex = '/^' . $regex . '/';
+          if (preg_match($regex, $c_mbox))
+            {
+            iil_C_UnSubscribe($this->conn, $c_mbox);
+            $result = iil_C_DeleteFolder($this->conn, $c_mbox);
+            if ($result>=0)
+              $deleted = TRUE;
+            }
+          }
         }
 
     // clear mailboxlist cache
@@ -1703,13 +1832,10 @@
     foreach ($this->default_folders as $folder)
       {
       $abs_name = $this->_mod_mailbox($folder);
-      if (!in_array_nocase($abs_name, $a_subscribed))
-        {
-        if (!in_array_nocase($abs_name, $a_folders))
-          $this->create_mailbox($folder, TRUE);
-        else
-          $this->subscribe($folder);
-        }
+      if (!in_array_nocase($abs_name, $a_folders))
+        $this->create_mailbox($folder, TRUE);
+      else if (!in_array_nocase($abs_name, $a_subscribed))
+        $this->subscribe($folder);
       }
     }
 
@@ -1719,7 +1845,9 @@
    *   internal caching methods
    * --------------------------------*/
 
-
+  /**
+   * @access private
+   */
   function set_caching($set)
     {
     if ($set && is_object($this->db))
@@ -1728,7 +1856,9 @@
       $this->caching_enabled = FALSE;
     }
 
-
+  /**
+   * @access private
+   */
   function get_cache($key)
     {
     // read cache
@@ -1741,7 +1871,9 @@
     return $this->cache[$key];
     }
 
-
+  /**
+   * @access private
+   */
   function update_cache($key, $data)
     {
     $this->cache[$key] = $data;
@@ -1749,7 +1881,9 @@
     $this->cache_changes[$key] = TRUE;
     }
 
-
+  /**
+   * @access private
+   */
   function write_cache()
     {
     if ($this->caching_enabled && $this->cache_changed)
@@ -1762,7 +1896,9 @@
       }    
     }
 
-
+  /**
+   * @access private
+   */
   function clear_cache($key=NULL)
     {
     if ($key===NULL)
@@ -1782,8 +1918,9 @@
       }
     }
 
-
-
+  /**
+   * @access private
+   */
   function _read_cache_record($key)
     {
     $cache_data = FALSE;
@@ -1806,10 +1943,12 @@
         }
       }
 
-    return $cache_data;    
+    return $cache_data;
     }
-    
 
+  /**
+   * @access private
+   */
   function _write_cache_record($key, $data)
     {
     if (!$this->db)
@@ -1858,7 +1997,9 @@
       }
     }
 
-
+  /**
+   * @access private
+   */
   function _clear_cache_record($key)
     {
     $this->db->query(
@@ -1876,8 +2017,13 @@
    * --------------------------------*/
    
 
-  // checks if the cache is up-to-date
-  // return: -3 = off, -2 = incomplete, -1 = dirty
+  /**
+   * Checks if the cache is up-to-date
+   *
+   * @param string Mailbox name
+   * @param string Internal cache key
+   * @return int -3 = off, -2 = incomplete, -1 = dirty
+   */
   function check_cache_status($mailbox, $cache_key)
     {
     if (!$this->caching_enabled)
@@ -1909,8 +2055,9 @@
       return -2;
     }
 
-
-
+  /**
+   * @access private
+   */
   function get_message_cache($key, $from, $to, $sort_field, $sort_order)
     {
     $cache_key = "$key:$from:$to:$sort_field:$sort_order";
@@ -1938,19 +2085,23 @@
         {
         $uid = $sql_arr['uid'];
         $this->cache[$cache_key][$uid] = 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);
         }
       }
       
     return $this->cache[$cache_key];
     }
 
-
+  /**
+   * @access private
+   */
   function &get_cached_message($key, $uid, $struct=false)
     {
-    if (!$this->caching_enabled)
-      return FALSE;
-
     $internal_key = '__single_msg';
+    
     if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
         ($struct && empty($this->cache[$internal_key][$uid]->structure))))
       {
@@ -1976,13 +2127,15 @@
     return $this->cache[$internal_key][$uid];
     }
 
-   
+  /**
+   * @access private
+   */  
   function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
     {
     static $sa_message_index = array();
     
     // empty key -> empty array
-    if (empty($key))
+    if (!$this->caching_enabled || empty($key))
       return array();
     
     if (!empty($sa_message_index[$key]) && !$force)
@@ -2004,12 +2157,22 @@
     return $sa_message_index[$key];
     }
 
-
+  /**
+   * @access private
+   */
   function add_message_cache($key, $index, $headers, $struct=null)
     {
     if (empty($key) || !is_object($headers) || empty($headers->uid))
+        return;
+    
+    // add to internal (fast) cache
+    $this->cache['__single_msg'][$headers->uid] = $headers;
+    $this->cache['__single_msg'][$headers->uid]->structure = $struct;
+    
+    // no further caching
+    if (!$this->caching_enabled)
       return;
-      
+    
     // check for an existing record (probly headers are cached but structure not)
     $sql_result = $this->db->query(
         "SELECT message_id
@@ -2056,9 +2219,14 @@
       }
     }
     
-    
+  /**
+   * @access private
+   */
   function remove_message_cache($key, $index)
     {
+    if (!$this->caching_enabled)
+      return;
+    
     $this->db->query(
       "DELETE FROM ".get_table_name('messages')."
        WHERE  user_id=?
@@ -2069,9 +2237,14 @@
       $index);
     }
 
-
+  /**
+   * @access private
+   */
   function clear_message_cache($key, $start_index=1)
     {
+    if (!$this->caching_enabled)
+      return;
+    
     $this->db->query(
       "DELETE FROM ".get_table_name('messages')."
        WHERE  user_id=?
@@ -2089,11 +2262,20 @@
    *   encoding/decoding methods
    * --------------------------------*/
 
-  
-  function decode_address_list($input, $max=NULL)
+  /**
+   * Split an address list into a structured array list
+   *
+   * @param string  Input string
+   * @param int     List only this number of addresses
+   * @param boolean Decode address strings
+   * @return array  Indexed list of addresses
+   */
+  function decode_address_list($input, $max=null, $decode=true)
     {
-    $a = $this->_parse_address_list($input);
+    $a = $this->_parse_address_list($input, $decode);
     $out = array();
+    // Special chars as defined by RFC 822 need to in quoted string (or escaped).
+    $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';
     
     if (!is_array($a))
       return $out;
@@ -2106,7 +2288,12 @@
       $j++;
       $address = $val['address'];
       $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
-      $string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address;
+      if ($name && $address && $name != $address)
+        $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
+      else if ($address)
+        $string = $address;
+      else if ($name)
+        $string = $name;
       
       $out[$j] = array('name' => $name,
                        'mailto' => $address,
@@ -2120,13 +2307,18 @@
     }
 
 
+  /**
+   * Decode a message header value
+   *
+   * @param string  Header value
+   * @param boolean Remove quotes if necessary
+   * @return string Decoded string
+   */
   function decode_header($input, $remove_quotes=FALSE)
     {
-    $str = $this->decode_mime_string((string)$input);
+    $str = rcube_imap::decode_mime_string((string)$input, $this->default_charset);
     if ($str{0}=='"' && $remove_quotes)
-      {
       $str = str_replace('"', '', $str);
-      }
     
     return $str;
     }
@@ -2135,15 +2327,22 @@
   /**
    * Decode a mime-encoded string to internal charset
    *
-   * @access static
+   * @param string  Header value
+   * @param string  Fallback charset if none specified
+   * @return string Decoded string
+   * @static
    */
-  function decode_mime_string($input, $recursive=false)
+  function decode_mime_string($input, $fallback=null)
     {
     $out = '';
 
     $pos = strpos($input, '=?');
     if ($pos !== false)
       {
+      // rfc: all line breaks or other characters not found in the Base64 Alphabet must be ignored by decoding software
+      // delete all blanks between MIME-lines, differently we can receive unnecessary blanks and broken utf-8 symbols
+      $input = preg_replace("/\?=\s+=\?/", '?==?', $input);
+
       $out = substr($input, 0, $pos);
   
       $end_cs_pos = strpos($input, "?", $pos+2);
@@ -2154,20 +2353,20 @@
       $rest = substr($input, $end_pos+2);
 
       $out .= rcube_imap::_decode_mime_string_part($encstr);
-      $out .= rcube_imap::decode_mime_string($rest);
+      $out .= rcube_imap::decode_mime_string($rest, $fallback);
 
       return $out;
       }
       
-    // no encoding information, defaults to what is specified in the class header
-    return rcube_charset_convert($input, 'ISO-8859-1');
+    // no encoding information, use fallback
+    return rcube_charset_convert($input, !empty($fallback) ? $fallback : 'ISO-8859-1');
     }
 
 
   /**
    * Decode a part of a mime-encoded string
    *
-   * @access static
+   * @access private
    */
   function _decode_mime_string_part($str)
     {
@@ -2195,6 +2394,14 @@
     }
 
 
+  /**
+   * Decode a mime part
+   *
+   * @param string Input string
+   * @param string Part encoding
+   * @return string Decoded string
+   * @access private
+   */
   function mime_decode($input, $encoding='7bit')
     {
     switch (strtolower($encoding))
@@ -2217,34 +2424,49 @@
     }
 
 
-  function mime_encode($input, $encoding='7bit')
-    {
-    switch ($encoding)
-      {
-      case 'quoted-printable':
-        return quoted_printable_encode($input);
-        break;
-
-      case 'base64':
-        return base64_encode($input);
-        break;
-
-      default:
-        return $input;
-      }
-    }
-
-
-  // convert body chars according to the ctype_parameters
+  /**
+   * Convert body charset to UTF-8 according to the ctype_parameters
+   *
+   * @param string Part body to decode
+   * @param string Charset to convert from
+   * @return string Content converted to internal charset
+   */
   function charset_decode($body, $ctype_param)
     {
     if (is_array($ctype_param) && !empty($ctype_param['charset']))
       return rcube_charset_convert($body, $ctype_param['charset']);
 
     // defaults to what is specified in the class header
-    return rcube_charset_convert($body,  'ISO-8859-1');
+    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);
+    }
 
 
 
@@ -2253,6 +2475,9 @@
    * --------------------------------*/
 
 
+  /**
+   * @access private
+   */
   function _mod_mailbox($mbox_name, $mode='in')
     {
     if ((!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
@@ -2266,8 +2491,22 @@
     return $mbox_name;
     }
 
+  /**
+   * Validate the given input and save to local properties
+   * @access private
+   */
+  function _set_sort_order($sort_field, $sort_order)
+  {
+    if ($sort_field != null)
+      $this->sort_field = asciiwords($sort_field);
+    if ($sort_order != null)
+      $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
+  }
 
-  // sort mailboxes first by default folders and then in alphabethical order
+  /**
+   * Sort mailboxes first by default folders and then in alphabethical order
+   * @access private
+   */
   function _sort_mailbox_list($a_folders)
     {
     $a_out = $a_defaults = array();
@@ -2276,30 +2515,23 @@
     foreach($a_folders as $i => $folder)
       {
       if ($folder{0}=='.')
-      	continue;
+        continue;
 
-      if (($p = array_search(strtolower($folder), $this->default_folders_lc))!==FALSE)
-      	$a_defaults[$p] = $folder;
+      if (($p = array_search(strtolower($folder), $this->default_folders_lc)) !== false && !$a_defaults[$p])
+        $a_defaults[$p] = $folder;
       else
         $a_out[] = $folder;
       }
 
-    sort($a_out);
+    natcasesort($a_out);
     ksort($a_defaults);
     
     return array_merge($a_defaults, $a_out);
     }
 
-  function get_id($uid, $mbox_name=NULL) 
-    {
-      return $this->_uid2id($uid, $mbox_name);
-    }
-  
-  function get_uid($id,$mbox_name=NULL)
-    {
-      return $this->_id2uid($id, $mbox_name);
-    }
-
+  /**
+   * @access private
+   */
   function _uid2id($uid, $mbox_name=NULL)
     {
     if (!$mbox_name)
@@ -2311,16 +2543,31 @@
     return $this->uid_id_map[$mbox_name][$uid];
     }
 
+  /**
+   * @access private
+   */
   function _id2uid($id, $mbox_name=NULL)
     {
     if (!$mbox_name)
       $mbox_name = $this->mailbox;
       
-    return iil_C_ID2UID($this->conn, $mbox_name, $id);
+    $index = array_flip((array)$this->uid_id_map[$mbox_name]);
+    if (isset($index[$id]))
+      $uid = $index[$id];
+    else
+      {
+      $uid = iil_C_ID2UID($this->conn, $mbox_name, $id);
+      $this->uid_id_map[$mbox_name][$uid] = $id;
+      }
+    
+    return $uid;
     }
 
 
-  // parse string or array of server capabilities and put them in internal array
+  /**
+   * Parse string or array of server capabilities and put them in internal array
+   * @access private
+   */
   function _parse_capability($caps)
     {
     if (!is_array($caps))
@@ -2347,7 +2594,10 @@
     }
 
 
-  // subscribe/unsubscribe a list of mailboxes and update local cache
+  /**
+   * Subscribe/unsubscribe a list of mailboxes and update local cache
+   * @access private
+   */
   function _change_subscription($a_mboxes, $mode)
     {
     $updated = FALSE;
@@ -2388,7 +2638,10 @@
     }
 
 
-  // increde/decrese messagecount for a specific mailbox
+  /**
+   * Increde/decrese messagecount for a specific mailbox
+   * @access private
+   */
   function _set_messagecount($mbox_name, $mode, $increment)
     {
     $a_mailbox_cache = FALSE;
@@ -2414,7 +2667,10 @@
     }
 
 
-  // remove messagecount of a specific mailbox from cache
+  /**
+   * Remove messagecount of a specific mailbox from cache
+   * @access private
+   */
   function _clear_messagecount($mbox_name='')
     {
     $a_mailbox_cache = FALSE;
@@ -2430,7 +2686,10 @@
     }
 
 
-  // split RFC822 header string into an associative array
+  /**
+   * Split RFC822 header string into an associative array
+   * @access private
+   */
   function _parse_headers($headers)
     {
     $a_headers = array();
@@ -2451,7 +2710,10 @@
     }
 
 
-  function _parse_address_list($str)
+  /**
+   * @access private
+   */
+  function _parse_address_list($str, $decode=true)
     {
     // remove any newlines and carriage returns before
     $a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
@@ -2460,12 +2722,12 @@
     foreach ($a as $key => $val)
       {
       $val = preg_replace("/([\"\w])</", "$1 <", $val);
-      $sub_a = $this->_explode_quoted_string(' ', $this->decode_header($val));
+      $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
       $result[$key]['name'] = '';
 
       foreach ($sub_a as $k => $v)
         {
-        if ((strpos($v, '@') > 0) && (strpos($v, '.') > 0)) 
+        if (strpos($v, '@') > 0)
           $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
         else
           $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
@@ -2479,6 +2741,9 @@
     }
 
 
+  /**
+   * @access private
+   */
   function _explode_quoted_string($delimiter, $string)
     {
     $result = array();
@@ -2497,11 +2762,14 @@
     $result[] = substr($string, $p);
     return $result;
     }
-  }
+
+}  // end class rcube_imap
 
 
 /**
  * Class representing a message part
+ *
+ * @package Mail
  */
 class rcube_message_part
 {
@@ -2510,6 +2778,7 @@
   var $ctype_secondary = 'plain';
   var $mimetype = 'text/plain';
   var $disposition = '';
+  var $filename = '';
   var $encoding = '8bit';
   var $charset = '';
   var $size = 0;
@@ -2521,10 +2790,9 @@
 
 
 /**
- * rcube_header_sorter
- * 
  * Class for sorting an array of iilBasicHeader objects in a predetermined order.
  *
+ * @package Mail
  * @author Eric Stadtherr
  */
 class rcube_header_sorter
@@ -2532,9 +2800,9 @@
    var $sequence_numbers = array();
    
    /**
-    * set the predetermined sort order.
+    * Set the predetermined sort order.
     *
-    * @param array $seqnums numerically indexed array of IMAP message sequence numbers
+    * @param array Numerically indexed array of IMAP message sequence numbers
     */
    function set_sequence_numbers($seqnums)
    {
@@ -2542,9 +2810,9 @@
    }
  
    /**
-    * sort the array of header objects
+    * Sort the array of header objects
     *
-    * @param array $headers array of iilBasicHeader objects indexed by UID
+    * @param array Array of iilBasicHeader objects indexed by UID
     */
    function sort_headers(&$headers)
    {
@@ -2559,9 +2827,10 @@
    }
  
    /**
-    * get the position of a message sequence number in my sequence_numbers array
+    * Get the position of a message sequence number in my sequence_numbers array
     *
-    * @param integer $seqnum message sequence number contained in sequence_numbers  
+    * @param int Message sequence number contained in sequence_numbers
+    * @return int Position, -1 if not found
     */
    function position_of($seqnum)
    {
@@ -2597,10 +2866,10 @@
 /**
  * Add quoted-printable encoding to a given string
  * 
- * @param string  $input      string to encode
- * @param int     $line_max   add new line after this number of characters
- * @param boolena $space_conf true if spaces should be converted into =20
- * @return encoded string
+ * @param string   String to encode
+ * @param int      Add new line after this number of characters
+ * @param boolean  True if spaces should be converted into =20
+ * @return string Encoded string
  */
 function quoted_printable_encode($input, $line_max=76, $space_conv=false)
   {

--
Gitblit v1.9.1