alecpl
2010-11-05 cb105aa9f12396d1644e87d91c35e8f5c3eefbbd
program/include/rcube_imap_generic.php
@@ -4,8 +4,8 @@
 +-----------------------------------------------------------------------+
 | program/include/rcube_imap_generic.php                                |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2005-2010, RoundCube Dev. - Switzerland                 |
 | This file is part of the Roundcube Webmail client                     |
 | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
@@ -50,7 +50,6 @@
   public $ctype;
   public $flags;
   public $timestamp;
   public $f;
   public $body_structure;
   public $internaldate;
   public $references;
@@ -87,9 +86,7 @@
    public $error;
    public $errornum;
   public $message;
   public $rootdir;
   public $delimiter;
   public $permanentflags = array();
    public $data = array();
    public $flags = array(
        'SEEN'     => '\\Seen',
        'DELETED'  => '\\Deleted',
@@ -102,8 +99,6 @@
        '*'        => '\\*',
    );
   private $exists;
   private $recent;
    private $selected;
   private $fp;
   private $host;
@@ -111,6 +106,18 @@
   private $capability = array();
   private $capability_readed = false;
    private $prefs;
    private $cmd_tag;
    private $cmd_num = 0;
    const ERROR_OK = 0;
    const ERROR_NO = -1;
    const ERROR_BAD = -2;
    const ERROR_BYE = -3;
    const ERROR_COMMAND = -5;
    const ERROR_UNKNOWN = -4;
    const COMMAND_NORESPONSE = 1;
    const COMMAND_CAPABILITY = 2;
    /**
     * Object constructor
@@ -119,7 +126,15 @@
    {
    }
    private function putLine($string, $endln=true)
    /**
     * Send simple (one line) command to the connection stream
     *
     * @param string $string Command string
     * @param bool   $endln  True if CRLF need to be added at the end of command
     *
     * @param int Number of bytes sent, False on error
     */
    function putLine($string, $endln=true)
    {
        if (!$this->fp)
            return false;
@@ -128,14 +143,29 @@
          write_log('imap', 'C: '. rtrim($string));
       }
        return fputs($this->fp, $string . ($endln ? "\r\n" : ''));
        $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
         if ($res === false) {
              @fclose($this->fp);
              $this->fp = null;
         }
        return $res;
    }
    // $this->putLine replacement with Command Continuation Requests (RFC3501 7.5) support
    private function putLineC($string, $endln=true)
    /**
     * Send command to the connection stream with Command Continuation
     * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
     *
     * @param string $string Command string
     * @param bool   $endln  True if CRLF need to be added at the end of command
     *
     * @param int Number of bytes sent, False on error
     */
    function putLineC($string, $endln=true)
    {
        if (!$this->fp)
            return NULL;
            return false;
       if ($endln)
          $string .= "\r\n";
@@ -144,15 +174,23 @@
       if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
          for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
             if (preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
                    // LITERAL+ support
                    if ($this->prefs['literal+'])
                        $parts[$i+1] = preg_replace('/([0-9]+)/', '\\1+', $parts[$i+1]);
                $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
                    if ($bytes === false)
                        return false;
                    $res += $bytes;
                $line = $this->readLine(1000);
                // handle error in command
                if ($line[0] != '+')
                   return false;
                $i++;
                    // don't wait if server supports LITERAL+ capability
                    if (!$this->prefs['literal+']) {
                    $line = $this->readLine(1000);
                    // handle error in command
                    if ($line[0] != '+')
                       return false;
                }
                    $i++;
             }
             else {
                $bytes = $this->putLine($parts[$i], false);
@@ -166,7 +204,7 @@
       return $res;
    }
    private function readLine($size=1024)
    function readLine($size=1024)
    {
      $line = '';
@@ -191,7 +229,7 @@
              break;
          }
          if (!empty($this->prefs['debug_mode'])) {
             write_log('imap', 'S: '. chop($buffer));
             write_log('imap', 'S: '. rtrim($buffer));
          }
            $line .= $buffer;
       } while ($buffer[strlen($buffer)-1] != "\n");
@@ -199,9 +237,9 @@
       return $line;
    }
    private function multLine($line, $escape=false)
    function multLine($line, $escape=false)
    {
       $line = chop($line);
       $line = rtrim($line);
       if (preg_match('/\{[0-9]+\}$/', $line)) {
          $out = '';
@@ -214,13 +252,13 @@
             $out .= $line;
          }
          $line = $a[1][0] . '"' . ($escape ? $this->Escape($out) : $out) . '"';
          $line = $a[1][0] . ($escape ? $this->escape($out) : $out);
       }
        return $line;
    }
    private function readBytes($bytes)
    function readBytes($bytes)
    {
       $data = '';
       $len  = 0;
@@ -242,7 +280,7 @@
    }
    // don't use it in loops, until you exactly know what you're doing
    private function readReply(&$untagged=null)
    function readReply(&$untagged=null)
    {
       do {
          $line = trim($this->readLine(1024));
@@ -257,28 +295,40 @@
       return $line;
    }
    private function parseResult($string)
    function parseResult($string, $err_prefix='')
    {
       $a = explode(' ', trim($string));
       if (count($a) >= 2) {
          $res = strtoupper($a[1]);
       if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
          $res = strtoupper($matches[1]);
            $str = trim($matches[2]);
          if ($res == 'OK') {
             return 0;
             return $this->errornum = self::ERROR_OK;
          } else if ($res == 'NO') {
             return -1;
                $this->errornum = self::ERROR_NO;
          } else if ($res == 'BAD') {
             return -2;
             $this->errornum = self::ERROR_BAD;
          } else if ($res == 'BYE') {
                @fclose($this->fp);
                $this->fp = null;
             return -3;
             $this->errornum = self::ERROR_BYE;
          }
            if ($str)
                $this->error = $err_prefix ? $err_prefix.$str : $str;
           return $this->errornum;
       }
       return -4;
       return self::ERROR_UNKNOWN;
    }
    private function set_error($code, $msg='')
    {
        $this->errornum = $code;
        $this->error    = $msg;
    }
    // check if $string starts with $match (or * BYE/BAD)
    private function startsWith($string, $match, $error=false, $nonempty=false)
    function startsWith($string, $match, $error=false, $nonempty=false)
    {
       $len = strlen($match);
       if ($len == 0) {
@@ -288,31 +338,6 @@
            return true;
        }
       if (strncmp($string, $match, $len) == 0) {
          return true;
       }
       if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
            if (strtoupper($m[1]) == 'BYE') {
                @fclose($this->fp);
                $this->fp = null;
            }
          return true;
       }
        if ($nonempty && !strlen($string)) {
            return true;
        }
       return false;
    }
    private function startsWithI($string, $match, $error=false, $nonempty=false)
    {
       $len = strlen($match);
       if ($len == 0) {
          return false;
       }
        if (!$this->fp) {
            return true;
        }
       if (strncasecmp($string, $match, $len) == 0) {
          return true;
       }
       if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
@@ -339,21 +364,11 @@
       // get capabilities (only once) because initial
       // optional CAPABILITY response may differ
       $this->capability = array();
        $result = $this->execute('CAPABILITY');
       if (!$this->putLine("cp01 CAPABILITY")) {
            return false;
        if ($result[0] == self::ERROR_OK) {
            $this->parseCapability($result[1]);
        }
       do {
          $line = trim($this->readLine(1024));
          $a = explode(' ', $line);
          if ($line[0] == '*') {
             while (list($k, $w) = each($a)) {
                if ($w != '*' && $w != 'CAPABILITY')
                   $this->capability[] = strtoupper($w);
             }
          }
       } while ($a[0] != 'cp01');
       $this->capability_readed = true;
@@ -370,119 +385,200 @@
       $this->capability_readed = false;
    }
    function authenticate($user, $pass, $encChallenge)
    /**
     * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
     *
     * @param string $user
     * @param string $pass
     * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
     *
     * @return resource Connection resourse on success, error code on error
     */
    function authenticate($user, $pass, $type='PLAIN')
    {
        $ipad = '';
        $opad = '';
        if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
            if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
                $this->set_error(self::ERROR_BYE,
                    "The Auth_SASL package is required for DIGEST-MD5 authentication");
             return self::ERROR_BAD;
            }
        // initialize ipad, opad
        for ($i=0; $i<64; $i++) {
            $ipad .= chr(0x36);
            $opad .= chr(0x5C);
          $this->putLine($this->next_tag() . " AUTHENTICATE $type");
          $line = trim($this->readLine(1024));
          if ($line[0] == '+') {
             $challenge = substr($line, 2);
            }
            else {
                return $this->parseResult($line);
          }
            if ($type == 'CRAM-MD5') {
                // RFC2195: CRAM-MD5
                $ipad = '';
                $opad = '';
                // initialize ipad, opad
                for ($i=0; $i<64; $i++) {
                    $ipad .= chr(0x36);
                    $opad .= chr(0x5C);
                }
                // pad $pass so it's 64 bytes
                $padLen = 64 - strlen($pass);
                for ($i=0; $i<$padLen; $i++) {
                    $pass .= chr(0);
                }
                // generate hash
                $hash  = md5($this->_xor($pass, $opad) . pack("H*",
                    md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
                $reply = base64_encode($user . ' ' . $hash);
                // send result
                $this->putLine($reply);
            }
            else {
                // RFC2831: DIGEST-MD5
                // proxy authorization
                if (!empty($this->prefs['auth_cid'])) {
                    $authc = $this->prefs['auth_cid'];
                    $pass  = $this->prefs['auth_pw'];
                }
                else {
                    $authc = $user;
                }
                $auth_sasl = Auth_SASL::factory('digestmd5');
                $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
                    base64_decode($challenge), $this->host, 'imap', $user));
                // send result
                $this->putLine($reply);
                $line = $this->readLine(1024);
                if ($line[0] == '+') {
                 $challenge = substr($line, 2);
                }
                else {
                    return $this->parseResult($line);
                }
                // check response
                $challenge = base64_decode($challenge);
                if (strpos($challenge, 'rspauth=') === false) {
                    $this->set_error(self::ERROR_BAD,
                        "Unexpected response from server to DIGEST-MD5 response");
                    return self::ERROR_BAD;
                }
                $this->putLine('');
            }
            $line = $this->readLine(1024);
            $result = $this->parseResult($line);
        }
        else { // PLAIN
            // proxy authorization
            if (!empty($this->prefs['auth_cid'])) {
                $authc = $this->prefs['auth_cid'];
                $pass  = $this->prefs['auth_pw'];
            }
            else {
                $authc = $user;
            }
            $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
            // RFC 4959 (SASL-IR): save one round trip
            if ($this->getCapability('SASL-IR')) {
                $result = $this->execute("AUTHENTICATE PLAIN", array($reply),
                    self::COMMAND_NORESPONSE | self::COMMAND_CAPABILITY);
            }
            else {
              $this->putLine($this->next_tag() . " AUTHENTICATE PLAIN");
              $line = trim($this->readLine(1024));
              if ($line[0] != '+') {
                 return $this->parseResult($line);
              }
                // send result, get reply and process it
                $this->putLine($reply);
                $line = $this->readLine(1024);
                $result = $this->parseResult($line);
            }
        }
        // pad $pass so it's 64 bytes
        $padLen = 64 - strlen($pass);
        for ($i=0; $i<$padLen; $i++) {
            $pass .= chr(0);
        }
        // generate hash
        $hash  = md5($this->_xor($pass,$opad) . pack("H*", md5($this->_xor($pass, $ipad) . base64_decode($encChallenge))));
        // generate reply
        $reply = base64_encode($user . ' ' . $hash);
        // send result, get reply
        $this->putLine($reply);
        $line = $this->readLine(1024);
        // process result
        $result = $this->parseResult($line);
        if ($result == 0) {
            $this->errornum = 0;
        if ($result == self::ERROR_OK) {
           // optional CAPABILITY response
           if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
              $this->parseCapability($matches[1], true);
           }
            return $this->fp;
        }
        $this->error    = "Authentication for $user failed (AUTH): $line";
        $this->errornum = $result;
        else {
            $this->set_error($result, "Unable to authenticate user ($type): $line");
        }
        return $result;
    }
    /**
     * LOGIN Authentication
     *
     * @param string $user
     * @param string $pass
     *
     * @return resource Connection resourse on success, error code on error
     */
    function login($user, $password)
    {
        $this->putLine('a001 LOGIN "'.$this->escape($user).'" "'.$this->escape($password).'"');
        $line = $this->readReply($untagged);
        list($code, $response) = $this->execute('LOGIN', array(
            $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
        // re-set capabilities list if untagged CAPABILITY response provided
       if (preg_match('/\* CAPABILITY (.+)/i', $untagged, $matches)) {
          $this->capability = explode(' ', strtoupper($matches[1]));
       if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
          $this->parseCapability($matches[1], true);
       }
        // process result
        $result = $this->parseResult($line);
        if ($result == 0) {
            $this->errornum = 0;
        if ($code == self::ERROR_OK) {
            return $this->fp;
        }
        @fclose($this->fp);
        $this->fp = false;
        $this->error    = "Authentication for $user failed (LOGIN): $line";
        $this->errornum = $result;
        return $result;
        return $code;
    }
    function getNamespace()
    /**
     * Gets the root directory and delimiter (of personal namespace)
     *
     * @return mixed A root directory name, or false.
     */
    function getRootDir()
    {
       if (isset($this->prefs['rootdir']) && is_string($this->prefs['rootdir'])) {
          $this->rootdir = $this->prefs['rootdir'];
          return true;
          return $this->prefs['rootdir'];
       }
        if (!$this->getCapability('NAMESPACE')) {
       if (!is_array($data = $this->getNamespace())) {
           return false;
       }
       if (!$this->putLine("ns1 NAMESPACE")) {
            return false;
        }
       do {
          $line = $this->readLine(1024);
          if ($this->startsWith($line, '* NAMESPACE')) {
             $i    = 0;
             $line = $this->unEscape($line);
             $data = $this->parseNamespace(substr($line,11), $i, 0, 0);
          }
       } while (!$this->startsWith($line, 'ns1', true, true));
       if (!is_array($data)) {
           return false;
       }
       $user_space_data = $data[0];
       $user_space_data = $data['personal'];
       if (!is_array($user_space_data)) {
           return false;
       }
       $first_userspace = $user_space_data[0];
       if (count($first_userspace)!=2) {
       if (count($first_userspace) !=2) {
           return false;
       }
       $this->rootdir            = $first_userspace[0];
       $this->delimiter          = $first_userspace[1];
       $this->prefs['rootdir']   = substr($this->rootdir, 0, -1);
       $this->prefs['delimiter'] = $this->delimiter;
        $rootdir                  = $first_userspace[0];
       $this->prefs['delimiter'] = $first_userspace[1];
       $this->prefs['rootdir']   = $rootdir ? substr($rootdir, 0, -1) : '';
       return true;
       return $this->prefs['rootdir'];
    }
    /**
     * Gets the delimiter, for example:
@@ -495,56 +591,34 @@
     */
    function getHierarchyDelimiter()
    {
       if ($this->delimiter) {
          return $this->delimiter;
       if ($this->prefs['delimiter']) {
          return $this->prefs['delimiter'];
       }
       if (!empty($this->prefs['delimiter'])) {
           return ($this->delimiter = $this->prefs['delimiter']);
           return $this->prefs['delimiter'];
       }
       $delimiter = false;
       // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
       if (!$this->putLine('ghd LIST "" ""')) {
           return false;
       }
       list($code, $response) = $this->execute('LIST',
           array($this->escape(''), $this->escape('')));
       do {
          $line = $this->readLine(500);
          if ($line[0] == '*') {
             $line = rtrim($line);
             $a = rcube_explode_quoted_string(' ', $this->unEscape($line));
             if ($a[0] == '*') {
                 $delimiter = str_replace('"', '', $a[count($a)-2]);
              }
          }
       } while (!$this->startsWith($line, 'ghd', true, true));
        if ($code == self::ERROR_OK) {
            $args = $this->tokenizeResponse($response, 4);
            $delimiter = $args[3];
       if (strlen($delimiter)>0) {
           return $delimiter;
       }
           if (strlen($delimiter) > 0) {
               return ($this->prefs['delimiter'] = $delimiter);
           }
        }
       // if that fails, try namespace extension
       // try to fetch namespace data
       if (!$this->putLine("ns1 NAMESPACE")) {
       if (!is_array($data = $this->getNamespace())) {
            return false;
        }
       do {
          $line = $this->readLine(1024);
          if ($this->startsWith($line, '* NAMESPACE')) {
             $i = 0;
             $line = $this->unEscape($line);
             $data = $this->parseNamespace(substr($line,11), $i, 0, 0);
          }
       } while (!$this->startsWith($line, 'ns1', true, true));
       if (!is_array($data)) {
           return false;
       }
       // extract user space data (opposed to global/shared space)
       $user_space_data = $data[0];
       $user_space_data = $data['personal'];
       if (!is_array($user_space_data)) {
           return false;
       }
@@ -556,9 +630,41 @@
       }
       // extract delimiter
       $delimiter = $first_userspace[1];
       return $this->prefs['delimiter'] = $first_userspace[1];
    }
       return $delimiter;
    /**
     * NAMESPACE handler (RFC 2342)
     *
     * @return array Namespace data hash (personal, other, shared)
     */
    function getNamespace()
    {
        if (array_key_exists('namespace', $this->prefs)) {
            return $this->prefs['namespace'];
        }
        if (!$this->getCapability('NAMESPACE')) {
           return self::ERROR_BAD;
       }
       list($code, $response) = $this->execute('NAMESPACE');
      if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
           $data = $this->tokenizeResponse(substr($response, 11));
      }
       if (!is_array($data)) {
           return $code;
       }
        $this->prefs['namespace'] = array(
            'personal' => $data[0],
            'other'    => $data[1],
            'shared'   => $data[2],
        );
        return $this->prefs['namespace'];
    }
    function connect($host, $user, $password, $options=null)
@@ -574,13 +680,11 @@
          $auth_method = 'CHECK';
        }
       $message = "INITIAL: $auth_method\n";
       $result = false;
       // initialize connection
       $this->error    = '';
       $this->errornum = 0;
       $this->errornum = self::ERROR_OK;
       $this->selected = '';
       $this->user     = $user;
       $this->host     = $host;
@@ -588,18 +692,15 @@
       // check input
       if (empty($host)) {
          $this->error    = "Empty host";
          $this->errornum = -2;
          $this->set_error(self::ERROR_BAD, "Empty host");
          return false;
       }
        if (empty($user)) {
          $this->error    = "Empty user";
          $this->errornum = -1;
          $this->set_error(self::ERROR_NO, "Empty user");
          return false;
       }
       if (empty($password)) {
          $this->error    = "Empty password";
          $this->errornum = -1;
          $this->set_error(self::ERROR_NO, "Empty password");
          return false;
       }
@@ -618,8 +719,7 @@
           $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr);
       if (!$this->fp) {
          $this->error    = sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr);
          $this->errornum = -2;
          $this->set_error(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
          return false;
       }
@@ -635,92 +735,111 @@
       // Connected to wrong port or connection error?
       if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
          if ($line)
             $this->error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
             $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
          else
             $this->error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
           $this->errornum = -2;
             $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
           $this->set_error(self::ERROR_BAD, $error);
            $this->close();
           return false;
       }
       // RFC3501 [7.1] optional CAPABILITY response
       if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
          $this->capability = explode(' ', strtoupper($matches[1]));
          $this->parseCapability($matches[1], true);
       }
       $this->message .= $line;
       $this->message = $line;
       // TLS connection
       if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
           if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
                  $this->putLine("tls0 STARTTLS");
                  $res = $this->execute('STARTTLS');
             $line = $this->readLine(4096);
                if (!$this->startsWith($line, "tls0 OK")) {
                $this->error    = "Server responded to STARTTLS with: $line";
                $this->errornum = -2;
                if ($res[0] != self::ERROR_OK) {
                    $this->close();
                    return false;
                }
             if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                $this->error    = "Unable to negotiate TLS";
                $this->errornum = -2;
                $this->set_error(self::ERROR_BAD, "Unable to negotiate TLS");
                    $this->close();
                return false;
             }
             // Now we're authenticated, capabilities need to be reread
             // Now we're secure, capabilities need to be reread
             $this->clearCapability();
           }
       }
       $orig_method = $auth_method;
       $auth_methods = array();
        $result       = null;
       // check for supported auth methods
       if ($auth_method == 'CHECK') {
          // check for supported auth methods
          if ($this->getCapability('AUTH=DIGEST-MD5')) {
             $auth_methods[] = 'DIGEST-MD5';
          }
          if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
             $auth_method = 'AUTH';
             $auth_methods[] = 'CRAM-MD5';
          }
          else {
             // default to plain text auth
             $auth_method = 'PLAIN';
          if ($this->getCapability('AUTH=PLAIN')) {
             $auth_methods[] = 'PLAIN';
          }
            // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
          if (!$this->getCapability('LOGINDISABLED')) {
             $auth_methods[] = 'LOGIN';
          }
       }
        else {
            // Prevent from sending credentials in plain text when connection is not secure
          if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
             $this->set_error(self::ERROR_BAD, "Login disabled by IMAP server");
                $this->close();
             return false;
            }
            // replace AUTH with CRAM-MD5 for backward compat.
            $auth_methods[] = $auth_method == 'AUTH' ? 'CRAM-MD5' : $auth_method;
        }
        // pre-login capabilities can be not complete
        $this->capability_readed = false;
        // Authenticate
        foreach ($auth_methods as $method) {
            switch ($method) {
            case 'DIGEST-MD5':
            case 'CRAM-MD5':
           case 'PLAIN':
             $result = $this->authenticate($user, $password, $method);
              break;
            case 'LOGIN':
                  $result = $this->login($user, $password);
                break;
            default:
                $this->set_error(self::ERROR_BAD, "Configuration error. Unknown auth method: $method");
            }
          if (is_resource($result)) {
             break;
          }
       }
       if ($auth_method == 'AUTH') {
          // do CRAM-MD5 authentication
          $this->putLine("a000 AUTHENTICATE CRAM-MD5");
          $line = trim($this->readLine(1024));
          if ($line[0] == '+') {
             // got a challenge string, try CRAM-MD5
             $result = $this->authenticate($user, $password, substr($line,2));
             // stop if server sent BYE response
             if ($result == -3) {
                return false;
             }
          }
          if (!is_resource($result) && $orig_method == 'CHECK') {
             $auth_method = 'PLAIN';
          }
       }
       if ($auth_method == 'PLAIN') {
          // do plain text auth
          $result = $this->login($user, $password);
       }
        // Connected and authenticated
       if (is_resource($result)) {
            if ($this->prefs['force_caps']) {
             $this->clearCapability();
            }
          $this->getNamespace();
          $this->getRootDir();
            $this->logged = true;
          return true;
       } else {
          return false;
       }
        }
        // Close connection
        $this->close();
        return false;
    }
    function connected()
@@ -730,10 +849,10 @@
    function close()
    {
       if ($this->putLine("I LOGOUT")) {
          if (!feof($this->fp))
             fgets($this->fp, 1024);
       }
       if ($this->putLine($this->next_tag() . ' LOGOUT')) {
           $this->readReply();
        }
      @fclose($this->fp);
      $this->fp = false;
    }
@@ -743,36 +862,82 @@
       if (empty($mailbox)) {
          return false;
       }
       if ($this->selected == $mailbox) {
          return true;
       }
       if ($this->putLine("sel1 SELECT \"".$this->escape($mailbox).'"')) {
          do {
             $line = chop($this->readLine(300));
             $a = explode(' ', $line);
             if (count($a) == 3) {
                $token = strtoupper($a[2]);
                if ($token == 'EXISTS') {
                   $this->exists = (int) $a[1];
                }
                else if ($token == 'RECENT') {
                   $this->recent = (int) $a[1];
                }
             }
             else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
                $this->permanentflags = explode(' ', $match[1]);
             }
          } while (!$this->startsWith($line, 'sel1', true, true));
          if (strcasecmp($a[1], 'OK') == 0) {
             $this->selected = $mailbox;
             return true;
          }
            else {
                $this->error = "Couldn't select $mailbox";
        if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
            if (in_array('\\Noselect', $opts)) {
                return false;
            }
        }
        list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
        if ($code == self::ERROR_OK) {
            $response = explode("\r\n", $response);
            foreach ($response as $line) {
             if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
                 $this->data[strtoupper($m[2])] = (int) $m[1];
             }
             else if (preg_match('/^\* OK \[(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)\]/i', $line, $match)) {
                 $this->data[strtoupper($match[1])] = (int) $match[2];
             }
             else if (preg_match('/^\* OK \[PERMANENTFLAGS \(([^\)]+)\)\]/iU', $line, $match)) {
                 $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
             }
            }
          $this->selected = $mailbox;
         return true;
      }
        return false;
    }
    /**
     * Executes STATUS comand
     *
     * @param string $mailbox Mailbox name
     * @param array  $items   Additional requested item names. By default
     *                        MESSAGES and UNSEEN are requested. Other defined
     *                        in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
     *
     * @return array Status item-value hash
     * @access public
     * @since 0.5-beta
     */
    function status($mailbox, $items=array())
    {
       if (empty($mailbox)) {
          return false;
       }
        if (!in_array('MESSAGES', $items)) {
            $items[] = 'MESSAGES';
        }
        if (!in_array('UNSEEN', $items)) {
            $items[] = 'UNSEEN';
        }
        list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
            '(' . implode(' ', (array) $items) . ')'));
        if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
            $result   = array();
            $response = substr($response, 9); // remove prefix "* STATUS "
            list($mbox, $items) = $this->tokenizeResponse($response, 2);
            for ($i=0, $len=count($items); $i<$len; $i += 2) {
                $result[$items[$i]] = (int) $items[$i+1];
            }
            $this->data['STATUS:'.$mailbox] = $result;
         return $result;
      }
        return false;
    }
@@ -785,7 +950,7 @@
       $this->select($mailbox);
       if ($this->selected == $mailbox) {
          return $this->recent;
          return $this->data['RECENT'];
       }
       return false;
@@ -797,10 +962,52 @@
          $this->selected = '';
       }
       $this->select($mailbox);
       if ($this->selected == $mailbox) {
          return $this->exists;
          return $this->data['EXISTS'];
       }
        // Check internal cache
        $cache = $this->data['STATUS:'.$mailbox];
        if (!empty($cache) && isset($cache['MESSAGES'])) {
            return (int) $cache['MESSAGES'];
        }
        // Try STATUS (should be faster than SELECT)
        $counts = $this->status($mailbox);
        if (is_array($counts)) {
            return (int) $counts['MESSAGES'];
        }
        return false;
    }
    /**
     * Returns count of messages without \Seen flag in a specified folder
     *
     * @param string $mailbox Mailbox name
     *
     * @return int Number of messages, False on error
     * @access public
     */
    function countUnseen($mailbox)
    {
        // Check internal cache
        $cache = $this->data['STATUS:'.$mailbox];
        if (!empty($cache) && isset($cache['UNSEEN'])) {
            return (int) $cache['UNSEEN'];
        }
        // Try STATUS (should be faster than SELECT+SEARCH)
        $counts = $this->status($mailbox);
        if (is_array($counts)) {
            return (int) $counts['UNSEEN'];
        }
        // Invoke SEARCH as a fallback
        $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
        if (is_array($index)) {
            return (int) $index['COUNT'];
        }
        return false;
    }
@@ -819,48 +1026,30 @@
           return false;
       }
       /*  Do "SELECT" command */
       if (!$this->select($mailbox)) {
           return false;
       }
       $is_uid = $is_uid ? 'UID ' : '';
       // message IDs
       if (is_array($add))
          $add = $this->compressMessageSet(join(',', $add));
       $command  = "s ".$is_uid."SORT ($field) $encoding ALL";
       $line     = $data = '';
       if (!empty($add))
           $command .= ' '.$add;
          $add = $this->compressMessageSet($add);
       if (!$this->putLineC($command)) {
           return false;
       }
       do {
          $line = chop($this->readLine());
          if ($this->startsWith($line, '* SORT')) {
             $data .= substr($line, 7);
          } else if (preg_match('/^[0-9 ]+$/', $line)) {
             $data .= $line;
          }
       } while (!$this->startsWith($line, 's ', true, true));
       list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
           array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
       $result_code = $this->parseResult($line);
       if ($result_code != 0) {
            $this->error = "Sort: $line";
            return false;
       if ($code == self::ERROR_OK) {
           // remove prefix and \r\n from raw response
            $response = str_replace("\r\n", '', substr($response, 7));
           return preg_split('/\s+/', $response, -1, PREG_SPLIT_NO_EMPTY);
       }
       return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
        return false;
    }
    function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
    {
       if (is_array($message_set)) {
          if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
          if (!($message_set = $this->compressMessageSet($message_set)))
             return false;
       } else {
          list($from_idx, $to_idx) = explode(':', $message_set);
@@ -897,7 +1086,7 @@
       }
       // build FETCH command string
       $key     = 'fhi0';
       $key     = $this->next_tag();
       $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
       $deleted = $skip_deleted ? ' FLAGS' : '';
@@ -918,13 +1107,14 @@
       $request = $key . $request;
       if (!$this->putLine($request)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
          return false;
        }
       $result = array();
       do {
          $line = chop($this->readLine(200));
          $line = rtrim($this->readLine(200));
          $line = $this->multLine($line);
          if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
@@ -983,29 +1173,32 @@
       return $result;
    }
    private function compressMessageSet($message_set)
    static function compressMessageSet($messages, $force=false)
    {
       // given a comma delimited list of independent mid's,
       // compresses by grouping sequences together
       // if less than 255 bytes long, let's not bother
       if (strlen($message_set)<255) {
           return $message_set;
       }
        if (!is_array($messages)) {
           // if less than 255 bytes long, let's not bother
           if (!$force && strlen($messages)<255) {
               return $messages;
           }
       // see if it's already been compress
       if (strpos($message_set, ':') !== false) {
           return $message_set;
       }
           // see if it's already been compressed
           if (strpos($messages, ':') !== false) {
               return $messages;
           }
       // separate, then sort
       $ids = explode(',', $message_set);
       sort($ids);
           // separate, then sort
           $messages = explode(',', $messages);
        }
       sort($messages);
       $result = array();
       $start  = $prev = $ids[0];
       $start  = $prev = $messages[0];
       foreach ($ids as $id) {
       foreach ($messages as $id) {
          $incr = $id - $prev;
          if ($incr > 1) {         //found a gap
             if ($start == $prev) {
@@ -1019,7 +1212,7 @@
       }
       // handle the last sequence/id
       if ($start==$prev) {
       if ($start == $prev) {
           $result[] = $prev;
       } else {
           $result[] = $start.':'.$prev;
@@ -1029,38 +1222,69 @@
       return implode(',', $result);
    }
    function UID2ID($folder, $uid)
    static function uncompressMessageSet($messages)
    {
       if ($uid > 0) {
          $id_a = $this->search($folder, "UID $uid");
          if (is_array($id_a) && count($id_a) == 1) {
             return $id_a[0];
          }
       }
       return false;
    }
       $result   = array();
       $messages = explode(',', $messages);
    function ID2UID($folder, $id)
    {
       if (empty($id)) {
           return    -1;
       }
        foreach ($messages as $part) {
            $items = explode(':', $part);
            $max   = max($items[0], $items[1]);
       if (!$this->select($folder)) {
            return -1;
            for ($x=$items[0]; $x<=$max; $x++) {
                $result[] = $x;
            }
        }
       $result = -1;
      if ($this->putLine("fuid FETCH $id (UID)")) {
          do {
             $line = chop($this->readLine(1024));
            if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
               $result = $r[1];
            }
         } while (!$this->startsWith($line, 'fuid', true, true));
      }
        return $result;
    }
       return $result;
    /**
     * Returns message sequence identifier
     *
     * @param string $mailbox Mailbox name
     * @param int    $uid     Message unique identifier (UID)
     *
     * @return int Message sequence identifier
     * @access public
     */
    function UID2ID($mailbox, $uid)
    {
       if ($uid > 0) {
          $id_a = $this->search($mailbox, "UID $uid");
          if (is_array($id_a) && count($id_a) == 1) {
             return (int) $id_a[0];
          }
       }
       return null;
    }
    /**
     * Returns message unique identifier (UID)
     *
     * @param string $mailbox Mailbox name
     * @param int    $uid     Message sequence identifier
     *
     * @return int Message unique identifier
     * @access public
     */
    function ID2UID($mailbox, $id)
    {
       if (empty($id) || $id < 0) {
           return    null;
       }
       if (!$this->select($mailbox)) {
            return null;
        }
        list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
        if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
         return (int) $m[1];
        }
       return null;
    }
    function fetchUIDs($mailbox, $message_set=null)
@@ -1081,40 +1305,33 @@
          return false;
       }
       if (is_array($message_set))
          $message_set = join(',', $message_set);
       $message_set = $this->compressMessageSet($message_set);
       if ($add)
          $add = ' '.strtoupper(trim($add));
          $add = ' '.trim($add);
       /* FETCH uid, size, flags and headers */
       $key       = 'FH12';
       $key       = $this->next_tag();
       $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
       $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
       if ($bodystr)
          $request .= "BODYSTRUCTURE ";
       $request .= "BODY.PEEK[HEADER.FIELDS ";
       $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
       $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
       $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY ";
       $request .= "X-DRAFT-INFO".$add.")])";
       $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
       $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
       if (!$this->putLine($request)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
          return false;
       }
       do {
          $line = $this->readLine(1024);
          $line = $this->readLine(4096);
          $line = $this->multLine($line);
            if (!$line)
                break;
          $a    = explode(' ', $line);
          if (($line[0] == '*') && ($a[2] == 'FETCH')) {
             $id = $a[1];
          if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
             $id = intval($m[1]);
             $result[$id]            = new rcube_mail_header;
             $result[$id]->id        = $id;
@@ -1141,9 +1358,9 @@
                if ($parts_count>=6) {
                   for ($i=0; $i<$parts_count; $i=$i+2) {
                      if ($a[$i] == 'UID')
                         $result[$id]->uid = $a[$i+1];
                         $result[$id]->uid = intval($a[$i+1]);
                      else if ($a[$i] == 'RFC822.SIZE')
                         $result[$id]->size = $a[$i+1];
                         $result[$id]->size = intval($a[$i+1]);
                      else if ($a[$i] == 'INTERNALDATE')
                         $time_str = $a[$i+1];
                      else if ($a[$i] == 'FLAGS')
@@ -1188,7 +1405,7 @@
            // to the next valid header line.
             do {
                $line = chop($this->readLine(300), "\r\n");
                $line = rtrim($this->readLine(300), "\r\n");
                // The preg_match below works around communigate imap, which outputs " UID <number>)".
                // Without this, the while statement continues on and gets the "FH0 OK completed" message.
@@ -1267,7 +1484,7 @@
                      }
                       break;
                   case 'in-reply-to':
                      $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
                      $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
                      break;
                   case 'references':
                      $result[$id]->references = $string;
@@ -1290,8 +1507,6 @@
                      break;
                   } // end switch ()
                } // end while ()
             } else {
                $a = explode(' ', $line);
             }
             // process flags
@@ -1300,7 +1515,6 @@
                $flags_a   = explode(' ', $flags_str);
                if (is_array($flags_a)) {
                //   reset($flags_a);
                   foreach($flags_a as $flag) {
                      $flag = strtoupper($flag);
                      if ($flag == 'SEEN') {
@@ -1351,17 +1565,15 @@
       if ($field == 'date' || $field == 'internaldate') {
           $field = 'timestamp';
       }
       if (empty($flag)) {
           $flag = 'ASC';
       } else {
           $flag = strtoupper($flag);
        }
       $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
       $c = count($a);
       if ($c > 0) {
         // Strategy:
         // First, we'll create an "index" array.
         // Then, we'll use sort() on that array,
@@ -1379,14 +1591,17 @@
             } else {
                $data = $val->$field;
                if (is_string($data)) {
                   $data = strtoupper(str_replace($stripArr, '', $data));
                    $data = str_replace('"', '', $data);
                       if ($field == 'subject') {
                        $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
                        }
                   $data = strtoupper($data);
                  }
             }
             $index[$key]=$data;
             $index[$key] = $data;
          }
          // sort index
          $i = 0;
          if ($flag == 'ASC') {
             asort($index);
          } else {
@@ -1397,8 +1612,7 @@
          $result = array();
          reset($index);
          while (list($key, $val) = each($index)) {
             $result[$key]=$a[$key];
             $i++;
             $result[$key] = $a[$key];
          }
       }
@@ -1408,61 +1622,44 @@
    function expunge($mailbox, $messages=NULL)
    {
       if (!$this->select($mailbox)) {
            return -1;
            return false;
        }
        $c = 0;
      $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
        // Clear internal status cache
        unset($this->data['STATUS:'.$mailbox]);
      if (!$this->putLine("exp1 $command")) {
            return -1;
        }
      $result = $this->execute($messages ? 'UID EXPUNGE' : 'EXPUNGE',
          array($messages), self::COMMAND_NORESPONSE);
      do {
         $line = $this->readLine(100);
         if ($line[0] == '*') {
               $c++;
           }
      } while (!$this->startsWith($line, 'exp1', true, true));
      if ($this->parseResult($line) == 0) {
      if ($result == self::ERROR_OK) {
         $this->selected = ''; // state has changed, need to reselect
         return $c;
         return true;
      }
      $this->error = $line;
       return -1;
       return false;
    }
    function modFlag($mailbox, $messages, $flag, $mod)
    {
       if ($mod != '+' && $mod != '-') {
           return -1;
            $mod = '+';
       }
       $flag = $this->flags[strtoupper($flag)];
       if (!$this->select($mailbox)) {
           return -1;
           return false;
       }
        $c = 0;
       if (!$this->putLine("flg UID STORE $messages {$mod}FLAGS ($flag)")) {
            return false;
        // Clear internal status cache
        if ($flag == 'SEEN') {
            unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
        }
       do {
          $line = $this->readLine(1000);
          if ($line[0] == '*') {
              $c++;
            }
       } while (!$this->startsWith($line, 'flg', true, true));
       $flag   = $this->flags[strtoupper($flag)];
        $result = $this->execute('UID STORE', array(
            $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
            self::COMMAND_NORESPONSE);
       if ($this->parseResult($line) == 0) {
          return $c;
       }
       $this->error = $line;
       return -1;
       return ($result == self::ERROR_OK);
    }
    function flag($mailbox, $messages, $flag) {
@@ -1480,24 +1677,38 @@
    function copy($messages, $from, $to)
    {
       if (empty($from) || empty($to)) {
           return -1;
           return false;
       }
       if (!$this->select($from)) {
            return -1;
           return false;
       }
        $this->putLine("cpy1 UID COPY $messages \"".$this->escape($to)."\"");
       $line = $this->readReply();
       return $this->parseResult($line);
        // Clear internal status cache
        unset($this->data['STATUS:'.$to]);
        $result = $this->execute('UID COPY', array(
            $this->compressMessageSet($messages), $this->escape($to)),
            self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    function countUnseen($folder)
    function move($messages, $from, $to)
    {
        $index = $this->search($folder, 'ALL UNSEEN');
        if (is_array($index))
            return count($index);
        return false;
        if (!$from || !$to) {
            return false;
        }
        $r = $this->copy($messages, $from, $to);
        if ($r) {
            // Clear internal status cache
            unset($this->data['STATUS:'.$from]);
            return $this->delete($from, $messages);
        }
        return $r;
    }
    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
@@ -1551,16 +1762,16 @@
       return $node;
    }
    function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
    function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
    {
        $old_sel = $this->selected;
       if (!$this->select($folder)) {
       if (!$this->select($mailbox)) {
          return false;
       }
        // return empty result when folder is empty and we're just after SELECT
        if ($old_sel != $folder && !$this->exists) {
        if ($old_sel != $mailbox && !$this->data['EXISTS']) {
            return array(array(), array(), array());
       }
@@ -1569,141 +1780,232 @@
       $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
        $data      = '';
       if (!$this->putLineC("thrd1 THREAD $algorithm $encoding $criteria")) {
          return false;
       }
       do {
          $line = trim($this->readLine());
          if ($this->startsWith($line, '* THREAD')) {
             $data .= substr($line, 9);
          } else if (preg_match('/^[0-9() ]+$/', $line)) {
             $data .= $line;
          }
       } while (!$this->startsWith($line, 'thrd1', true, true));
        list($code, $response) = $this->execute('THREAD', array(
            $algorithm, $encoding, $criteria));
       $result_code = $this->parseResult($line);
       if ($result_code == 0) {
       if ($code == self::ERROR_OK && preg_match('/^\* THREAD /i', $response)) {
           // remove prefix and \r\n from raw response
           $response    = str_replace("\r\n", '', substr($response, 9));
            $depthmap    = array();
            $haschildren = array();
            $tree = $this->parseThread($data, 0, strlen($data), null, null, 0, $depthmap, $haschildren);
            $tree = $this->parseThread($response, 0, strlen($response),
                null, null, 0, $depthmap, $haschildren);
            return array($tree, $depthmap, $haschildren);
       }
       $this->error = "Thread: $line";
       return false;
    }
    function search($folder, $criteria, $return_uid=false)
    /**
     * Executes SEARCH command
     *
     * @param string $mailbox    Mailbox name
     * @param string $criteria   Searching criteria
     * @param bool   $return_uid Enable UID in result instead of sequence ID
     * @param array  $items      Return items (MIN, MAX, COUNT, ALL)
     *
     * @return array Message identifiers or item-value hash
     */
    function search($mailbox, $criteria, $return_uid=false, $items=array())
    {
        $old_sel = $this->selected;
       if (!$this->select($folder)) {
       if (!$this->select($mailbox)) {
          return false;
       }
        // return empty result when folder is empty and we're just after SELECT
        if ($old_sel != $folder && !$this->exists) {
            return array();
        if ($old_sel != $mailbox && !$this->data['EXISTS']) {
            if (!empty($items))
                return array_combine($items, array_fill(0, count($items), 0));
            else
                return array();
       }
       $data = '';
       $query = 'srch1 ' . ($return_uid ? 'UID ' : '') . 'SEARCH ' . chop($criteria);
        $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
        $criteria = trim($criteria);
        $params   = '';
       if (!$this->putLineC($query)) {
          return false;
       }
        // RFC4731: ESEARCH
        if (!empty($items) && $esearch) {
            $params .= 'RETURN (' . implode(' ', $items) . ')';
        }
        if (!empty($criteria)) {
            $params .= ($params ? ' ' : '') . $criteria;
        }
        else {
            $params .= 'ALL';
        }
       do {
          $line = trim($this->readLine());
          if ($this->startsWith($line, '* SEARCH')) {
             $data .= substr($line, 8);
          } else if (preg_match('/^[0-9 ]+$/', $line)) {
             $data .= $line;
          }
       } while (!$this->startsWith($line, 'srch1', true, true));
       list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
           array($params));
       $result_code = $this->parseResult($line);
       if ($result_code == 0) {
          return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
       }
       if ($code == self::ERROR_OK) {
           // remove prefix and \r\n from raw response
            $response = substr($response, $esearch ? 10 : 9);
           $response = str_replace("\r\n", '', $response);
       $this->error = "Search: $line";
            if ($esearch) {
                // Skip prefix: ... (TAG "A285") UID ...
                $this->tokenizeResponse($response, $return_uid ? 2 : 1);
                $result = array();
                for ($i=0; $i<count($items); $i++) {
                    // If the SEARCH results in no matches, the server MUST NOT
                    // include the item result option in the ESEARCH response
                    if ($ret = $this->tokenizeResponse($response, 2)) {
                        list ($name, $value) = $ret;
                        $result[$name] = $value;
                    }
                }
                return $result;
            }
           else {
                $response = preg_split('/\s+/', $response, -1, PREG_SPLIT_NO_EMPTY);
                if (!empty($items)) {
                    $result = array();
                    if (in_array('COUNT', $items))
                        $result['COUNT'] = count($response);
                    if (in_array('MIN', $items))
                        $result['MIN'] = !empty($response) ? min($response) : 0;
                    if (in_array('MAX', $items))
                        $result['MAX'] = !empty($response) ? max($response) : 0;
                    if (in_array('ALL', $items))
                        $result['ALL'] = $this->compressMessageSet($response, true);
                    return $result;
                }
                else {
                    return $response;
                }
           }
        }
       return false;
    }
    function move($messages, $from, $to)
    /**
     * Returns list of mailboxes
     *
     * @param string $ref         Reference name
     * @param string $mailbox     Mailbox name
     * @param array  $status_opts (see self::_listMailboxes)
     * @param array  $select_opts (see self::_listMailboxes)
     *
     * @return array List of mailboxes or hash of options if $status_opts argument
     *               is non-empty.
     * @access public
     */
    function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
    {
        if (!$from || !$to) {
            return -1;
        }
        $r = $this->copy($messages, $from, $to);
        if ($r==0) {
            return $this->delete($from, $messages);
        }
        return $r;
        return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
    }
    function listMailboxes($ref, $mailbox)
    /**
     * Returns list of subscribed mailboxes
     *
     * @param string $ref         Reference name
     * @param string $mailbox     Mailbox name
     * @param array  $status_opts (see self::_listMailboxes)
     *
     * @return array List of mailboxes or hash of options if $status_opts argument
     *               is non-empty.
     * @access public
     */
    function listSubscribed($ref, $mailbox, $status_opts=array())
    {
        return $this->_listMailboxes($ref, $mailbox, false);
        return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
    }
    function listSubscribed($ref, $mailbox)
    {
        return $this->_listMailboxes($ref, $mailbox, true);
    }
    private function _listMailboxes($ref, $mailbox, $subscribed=false)
    /**
     * IMAP LIST/LSUB command
     *
     * @param string $ref         Reference name
     * @param string $mailbox     Mailbox name
     * @param bool   $subscribed  Enables returning subscribed mailboxes only
     * @param array  $status_opts List of STATUS options (RFC5819: LIST-STATUS)
     *                            Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
     * @param array  $select_opts List of selection options (RFC5258: LIST-EXTENDED)
     *                            Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
     *
     * @return array List of mailboxes or hash of options if $status_ops argument
     *               is non-empty.
     * @access private
     */
    private function _listMailboxes($ref, $mailbox, $subscribed=false,
        $status_opts=array(), $select_opts=array())
    {
      if (empty($mailbox)) {
           $mailbox = '*';
       }
       if (empty($ref) && $this->rootdir) {
           $ref = $this->rootdir;
       if (empty($ref) && $this->prefs['rootdir']) {
           $ref = $this->prefs['rootdir'];
       }
        if ($subscribed) {
            $key     = 'lsb';
            $command = 'LSUB';
        }
        else {
            $key     = 'lmb';
            $command = 'LIST';
        $args = array();
        if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
            $select_opts = (array) $select_opts;
            $args[] = '(' . implode(' ', $select_opts) . ')';
        }
       // send command
       if (!$this->putLine($key." ".$command." \"". $this->escape($ref) ."\" \"". $this->escape($mailbox) ."\"")) {
          $this->error = "Couldn't send $command command";
           return false;
       }
        $args[] = $this->escape($ref);
        $args[] = $this->escape($mailbox);
       // get folder list
       do {
          $line = $this->readLine(500);
          $line = $this->multLine($line, true);
          $a    = explode(' ', $line);
        if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
            $status_opts = (array) $status_opts;
            $lstatus = true;
          if (($line[0] == '*') && ($a[1] == $command)) {
             $line = rtrim($line);
              // split one line
             $a = rcube_explode_quoted_string(' ', $line);
              // last string is folder name
             $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($a[count($a)-1]));
              // second from last is delimiter
              $delim = trim($a[count($a)-2], '"');
            $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
        }
        list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
        if ($code == self::ERROR_OK) {
            $folders = array();
            while ($this->tokenizeResponse($response, 1) == '*') {
                $cmd = strtoupper($this->tokenizeResponse($response, 1));
                // * LIST (<options>) <delimiter> <mailbox>
                if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
                    list($opts, $delim, $mailbox) = $this->tokenizeResponse($response, 3);
                    // Add to result array
                    if (!$lstatus) {
                        $folders[] = $mailbox;
                    }
                    else {
                        $folders[$mailbox] = array();
                    }
                    // Add to options array
                    if (!empty($opts)) {
                        if (empty($this->data['LIST'][$mailbox]))
                            $this->data['LIST'][$mailbox] = $opts;
                        else
                            $this->data['LIST'][$mailbox] = array_unique(array_merge(
                                $this->data['LIST'][$mailbox], $opts));
                    }
                }
                // * STATUS <mailbox> (<result>)
                else if ($cmd == 'STATUS') {
                    list($mailbox, $status) = $this->tokenizeResponse($response, 2);
                    for ($i=0, $len=count($status); $i<$len; $i += 2) {
                        list($name, $value) = $this->tokenizeResponse($status, 2);
                        $folders[$mailbox][$name] = $value;
                    }
                }
          }
       } while (!$this->startsWith($line, $key, true));
       if (is_array($folders)) {
           return $folders;
       } else if ($this->parseResult($line) == 0) {
            return array();
            return $folders;
        }
       $this->error = $line;
       return false;
    }
@@ -1715,7 +2017,7 @@
       $result = false;
       $parts  = (array) $parts;
       $key    = 'fmh0';
       $key    = $this->next_tag();
       $peeks  = '';
       $idx    = 0;
        $type   = $mime ? 'MIME' : 'HEADER';
@@ -1728,11 +2030,12 @@
       // send request
       if (!$this->putLine($request)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
           return false;
       }
       do {
           $line = $this->readLine(1000);
           $line = $this->readLine(1024);
           $line = $this->multLine($line);
          if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
@@ -1778,17 +2081,18 @@
       // format request
         $reply_key = '* ' . $id;
      $key       = 'ftch0';
      $key       = $this->next_tag();
      $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
       // send request
      if (!$this->putLine($request)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
          return false;
         }
         // receive reply line
         do {
             $line = chop($this->readLine(1000));
             $line = rtrim($this->readLine(1024));
             $a    = explode(' ', $line);
         } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
@@ -1825,7 +2129,11 @@
         $prev     = '';
           while ($bytes > 0) {
              $line = $this->readLine(1024);
              $line = $this->readLine(4096);
              if ($line === NULL)
                  break;
               $len  = strlen($line);
              if ($len > $bytes) {
@@ -1902,69 +2210,58 @@
       return false;
    }
    function createFolder($folder)
    function createFolder($mailbox)
    {
       if ($this->putLine('c CREATE "' . $this->escape($folder) . '"')) {
          do {
             $line = $this->readLine(300);
          } while (!$this->startsWith($line, 'c ', true, true));
          return ($this->parseResult($line) == 0);
       }
       return false;
        $result = $this->execute('CREATE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    function renameFolder($from, $to)
    {
       if ($this->putLine('r RENAME "' . $this->escape($from) . '" "' . $this->escape($to) . '"')) {
          do {
             $line = $this->readLine(300);
          } while (!$this->startsWith($line, 'r ', true, true));
          return ($this->parseResult($line) == 0);
       }
       return false;
        $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
           self::COMMAND_NORESPONSE);
      return ($result == self::ERROR_OK);
    }
    function deleteFolder($folder)
    function deleteFolder($mailbox)
    {
       if ($this->putLine('d DELETE "' . $this->escape($folder). '"')) {
          do {
             $line = $this->readLine(300);
          } while (!$this->startsWith($line, 'd ', true, true));
          return ($this->parseResult($line) == 0);
       }
       return false;
        $result = $this->execute('DELETE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    function clearFolder($folder)
    function clearFolder($mailbox)
    {
       $num_in_trash = $this->countMessages($folder);
       $num_in_trash = $this->countMessages($mailbox);
       if ($num_in_trash > 0) {
          $this->delete($folder, '1:*');
          $this->delete($mailbox, '1:*');
       }
       return ($this->expunge($folder) >= 0);
       return ($this->expunge($mailbox) >= 0);
    }
    function subscribe($folder)
    function subscribe($mailbox)
    {
       $query = 'sub1 SUBSCRIBE "' . $this->escape($folder). '"';
       $this->putLine($query);
       $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       $line = trim($this->readLine(512));
       return ($this->parseResult($line) == 0);
       return ($result == self::ERROR_OK);
    }
    function unsubscribe($folder)
    function unsubscribe($mailbox)
    {
        $query = 'usub1 UNSUBSCRIBE "' . $this->escape($folder) . '"';
       $this->putLine($query);
       $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       $line = trim($this->readLine(512));
       return ($this->parseResult($line) == 0);
       return ($result == self::ERROR_OK);
    }
    function append($folder, &$message)
    function append($mailbox, &$message)
    {
       if (!$folder) {
       if (!$mailbox) {
          return false;
       }
@@ -1976,16 +2273,20 @@
          return false;
       }
       $request = 'a APPEND "' . $this->escape($folder) .'" (\\Seen) {' . $len . '}';
        $key = $this->next_tag();
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
            $len, ($this->prefs['literal+'] ? '+' : ''));
       if ($this->putLine($request)) {
          $line = $this->readLine(512);
            // Don't wait when LITERAL+ is supported
            if (!$this->prefs['literal+']) {
                $line = $this->readLine(512);
          if ($line[0] != '+') {
             // $errornum = $this->parseResult($line);
             $this->error = "Cannot write to folder: $line";
             return false;
          }
              if ($line[0] != '+') {
                 $this->parseResult($line, 'APPEND: ');
                 return false;
              }
            }
          if (!$this->putLine($message)) {
                return false;
@@ -1993,22 +2294,23 @@
          do {
             $line = $this->readLine();
          } while (!$this->startsWith($line, 'a ', true, true));
          } while (!$this->startsWith($line, $key, true, true));
          $result = ($this->parseResult($line) == 0);
          if (!$result) {
              $this->error = $line;
          }
          return $result;
            // Clear internal status cache
            unset($this->data['STATUS:'.$mailbox]);
          return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
       }
        else {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
        }
       $this->error = "Couldn't send command \"$request\"";
       return false;
    }
    function appendFromFile($folder, $path, $headers=null, $separator="\n\n")
    function appendFromFile($mailbox, $path, $headers=null)
    {
       if (!$folder) {
       if (!$mailbox) {
           return false;
       }
@@ -2018,34 +2320,41 @@
          $in_fp = fopen($path, 'r');
       }
       if (!$in_fp) {
          $this->error = "Couldn't open $path for reading";
          $this->set_error(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
          return false;
       }
        $body_separator = "\r\n\r\n";
       $len = filesize($path);
       if (!$len) {
          return false;
       }
        if ($headers) {
            $headers = preg_replace('/[\r\n]+$/', '', $headers);
            $len += strlen($headers) + strlen($separator);
            $len += strlen($headers) + strlen($body_separator);
        }
       // send APPEND command
       $request    = 'a APPEND "' . $this->escape($folder) . '" (\\Seen) {' . $len . '}';
       if ($this->putLine($request)) {
          $line = $this->readLine(512);
       $key = $this->next_tag();
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
            $len, ($this->prefs['literal+'] ? '+' : ''));
          if ($line[0] != '+') {
             //$errornum = $this->parseResult($line);
             $this->error = "Cannot write to folder: $line";
             return false;
          }
       if ($this->putLine($request)) {
            // Don't wait when LITERAL+ is supported
            if (!$this->prefs['literal+']) {
              $line = $this->readLine(512);
              if ($line[0] != '+') {
                 $this->parseResult($line, 'APPEND: ');
                 return false;
              }
            }
            // send headers with body separator
            if ($headers) {
             $this->putLine($headers . $separator, false);
             $this->putLine($headers . $body_separator, false);
            }
          // send file
@@ -2062,39 +2371,43 @@
          // read response
          do {
             $line = $this->readLine();
          } while (!$this->startsWith($line, 'a ', true, true));
          } while (!$this->startsWith($line, $key, true, true));
          $result = ($this->parseResult($line) == 0);
          if (!$result) {
              $this->error = $line;
          }
            // Clear internal status cache
            unset($this->data['STATUS:'.$mailbox]);
          return $result;
          return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
       }
        else {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
        }
       $this->error = "Couldn't send command \"$request\"";
       return false;
    }
    function fetchStructureString($folder, $id, $is_uid=false)
    function fetchStructureString($mailbox, $id, $is_uid=false)
    {
       if (!$this->select($folder)) {
       if (!$this->select($mailbox)) {
            return false;
        }
      $key = 'F1247';
      $key = $this->next_tag();
       $result = false;
        $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
      if ($this->putLine($key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
      if ($this->putLine($command)) {
         do {
            $line = $this->readLine(5000);
            $line = $this->multLine($line, true);
            if (!preg_match("/^$key/", $line))
            if (!preg_match("/^$key /", $line))
               $result .= $line;
         } while (!$this->startsWith($line, $key, true, true));
         $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
      }
        else {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
        }
       return $result;
    }
@@ -2109,21 +2422,26 @@
         */
       $result      = false;
       $quota_lines = array();
       $key         = $this->next_tag();
        $command     = $key . ' GETQUOTAROOT INBOX';
       // get line(s) containing quota info
       if ($this->putLine('QUOT1 GETQUOTAROOT "INBOX"')) {
       if ($this->putLine($command)) {
          do {
             $line = chop($this->readLine(5000));
             if ($this->startsWith($line, '* QUOTA ')) {
             $line = rtrim($this->readLine(5000));
             if (preg_match('/^\* QUOTA /', $line)) {
                $quota_lines[] = $line;
              }
          } while (!$this->startsWith($line, 'QUOT1', true, true));
          } while (!$this->startsWith($line, $key, true, true));
       }
        else {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
        }
       // return false if not found, parse if found
       $min_free = PHP_INT_MAX;
       foreach ($quota_lines as $key => $quota_line) {
          $quota_line   = preg_replace('/[()]/', '', $quota_line);
          $quota_line   = str_replace(array('(', ')'), '', $quota_line);
          $parts        = explode(' ', $quota_line);
          $storage_part = array_search('STORAGE', $parts);
@@ -2147,6 +2465,584 @@
       return $result;
    }
    /**
     * Send the SETACL command (RFC4314)
     *
     * @param string $mailbox Mailbox name
     * @param string $user    User name
     * @param mixed  $acl     ACL string or array
     *
     * @return boolean True on success, False on failure
     *
     * @access public
     * @since 0.5-beta
     */
    function setACL($mailbox, $user, $acl)
    {
        if (is_array($acl)) {
            $acl = implode('', $acl);
        }
        $result = $this->execute('SETACL', array(
            $this->escape($mailbox), $this->escape($user), strtolower($acl)),
            self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    /**
     * Send the DELETEACL command (RFC4314)
     *
     * @param string $mailbox Mailbox name
     * @param string $user    User name
     *
     * @return boolean True on success, False on failure
     *
     * @access public
     * @since 0.5-beta
     */
    function deleteACL($mailbox, $user)
    {
        $result = $this->execute('DELETEACL', array(
            $this->escape($mailbox), $this->escape($user)),
            self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    /**
     * Send the GETACL command (RFC4314)
     *
     * @param string $mailbox Mailbox name
     *
     * @return array User-rights array on success, NULL on error
     * @access public
     * @since 0.5-beta
     */
    function getACL($mailbox)
    {
        list($code, $response) = $this->execute('GETACL', $this->escape($mailbox));
        if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
            // Parse server response (remove "* ACL ")
            $response = substr($response, 6);
            $ret  = $this->tokenizeResponse($response);
            $mbox = array_unshift($ret);
            $size = count($ret);
            // Create user-rights hash array
            // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
            // so we could return only standard rights defined in RFC4314,
            // excluding 'c' and 'd' defined in RFC2086.
            if ($size % 2 == 0) {
                for ($i=0; $i<$size; $i++) {
                    $ret[$ret[$i]] = str_split($ret[++$i]);
                    unset($ret[$i-1]);
                    unset($ret[$i]);
                }
                return $ret;
            }
            $this->set_error(self::ERROR_COMMAND, "Incomplete ACL response");
            return NULL;
        }
        return NULL;
    }
    /**
     * Send the LISTRIGHTS command (RFC4314)
     *
     * @param string $mailbox Mailbox name
     * @param string $user    User name
     *
     * @return array List of user rights
     * @access public
     * @since 0.5-beta
     */
    function listRights($mailbox, $user)
    {
        list($code, $response) = $this->execute('LISTRIGHTS', array(
            $this->escape($mailbox), $this->escape($user)));
        if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
            // Parse server response (remove "* LISTRIGHTS ")
            $response = substr($response, 13);
            $ret_mbox = $this->tokenizeResponse($response, 1);
            $ret_user = $this->tokenizeResponse($response, 1);
            $granted  = $this->tokenizeResponse($response, 1);
            $optional = trim($response);
            return array(
                'granted'  => str_split($granted),
                'optional' => explode(' ', $optional),
            );
        }
        return NULL;
    }
    /**
     * Send the MYRIGHTS command (RFC4314)
     *
     * @param string $mailbox Mailbox name
     *
     * @return array MYRIGHTS response on success, NULL on error
     * @access public
     * @since 0.5-beta
     */
    function myRights($mailbox)
    {
        list($code, $response) = $this->execute('MYRIGHTS', array($this->escape(mailbox)));
        if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
            // Parse server response (remove "* MYRIGHTS ")
            $response = substr($response, 11);
            $ret_mbox = $this->tokenizeResponse($response, 1);
            $rights   = $this->tokenizeResponse($response, 1);
            return str_split($rights);
        }
        return NULL;
    }
    /**
     * Send the SETMETADATA command (RFC5464)
     *
     * @param string $mailbox Mailbox name
     * @param array  $entries Entry-value array (use NULL value as NIL)
     *
     * @return boolean True on success, False on failure
     * @access public
     * @since 0.5-beta
     */
    function setMetadata($mailbox, $entries)
    {
        if (!is_array($entries) || empty($entries)) {
            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
            return false;
        }
        foreach ($entries as $name => $value) {
            if ($value === null)
                $value = 'NIL';
            else
                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
            $entries[$name] = $this->escape($name) . ' ' . $value;
        }
        $entries = implode(' ', $entries);
        $result = $this->execute('SETMETADATA', array(
            $this->escape($mailbox), '(' . $entries . ')'),
            self::COMMAND_NORESPONSE);
        return ($result == self::ERROR_OK);
    }
    /**
     * Send the SETMETADATA command with NIL values (RFC5464)
     *
     * @param string $mailbox Mailbox name
     * @param array  $entries Entry names array
     *
     * @return boolean True on success, False on failure
     *
     * @access public
     * @since 0.5-beta
     */
    function deleteMetadata($mailbox, $entries)
    {
        if (!is_array($entries) && !empty($entries))
            $entries = explode(' ', $entries);
        if (empty($entries)) {
            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
            return false;
        }
        foreach ($entries as $entry)
            $data[$entry] = NULL;
        return $this->setMetadata($mailbox, $data);
    }
    /**
     * Send the GETMETADATA command (RFC5464)
     *
     * @param string $mailbox Mailbox name
     * @param array  $entries Entries
     * @param array  $options Command options (with MAXSIZE and DEPTH keys)
     *
     * @return array GETMETADATA result on success, NULL on error
     *
     * @access public
     * @since 0.5-beta
     */
    function getMetadata($mailbox, $entries, $options=array())
    {
        if (!is_array($entries)) {
            $entries = array($entries);
        }
        // create entries string
        foreach ($entries as $idx => $name) {
            $entries[$idx] = $this->escape($name);
        }
        $optlist = '';
        $entlist = '(' . implode(' ', $entries) . ')';
        // create options string
        if (is_array($options)) {
            $options = array_change_key_case($options, CASE_UPPER);
            $opts = array();
            if (!empty($options['MAXSIZE']))
                $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
            if (!empty($options['DEPTH']))
                $opts[] = 'DEPTH '.intval($options['DEPTH']);
            if ($opts)
                $optlist = '(' . implode(' ', $opts) . ')';
        }
        $optlist .= ($optlist ? ' ' : '') . $entlist;
        list($code, $response) = $this->execute('GETMETADATA', array(
            $this->escape($mailbox), $optlist));
        if ($code == self::ERROR_OK && preg_match('/^\* METADATA /i', $response)) {
            // Parse server response (remove "* METADATA ")
            $response = substr($response, 11);
            $ret_mbox = $this->tokenizeResponse($response, 1);
            $data     = $this->tokenizeResponse($response);
            // The METADATA response can contain multiple entries in a single
            // response or multiple responses for each entry or group of entries
            if (!empty($data) && ($size = count($data))) {
                for ($i=0; $i<$size; $i++) {
                    if (is_array($data[$i])) {
                        $size_sub = count($data[$i]);
                        for ($x=0; $x<$size_sub; $x++) {
                            $data[$data[$i][$x]] = $data[$i][++$x];
                        }
                        unset($data[$i]);
                    }
                    else if ($data[$i] == '*' && $data[$i+1] == 'METADATA') {
                        unset($data[$i]);   // "*"
                        unset($data[++$i]); // "METADATA"
                        unset($data[++$i]); // Mailbox
                    }
                    else {
                        $data[$data[$i]] = $data[++$i];
                        unset($data[$i]);
                        unset($data[$i-1]);
                    }
                }
            }
            return $data;
        }
        return NULL;
    }
    /**
     * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
     *
     * @param string $mailbox Mailbox name
     * @param array  $data    Data array where each item is an array with
     *                        three elements: entry name, attribute name, value
     *
     * @return boolean True on success, False on failure
     * @access public
     * @since 0.5-beta
     */
    function setAnnotation($mailbox, $data)
    {
        if (!is_array($data) || empty($data)) {
            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
            return false;
        }
        foreach ($data as $entry) {
            $name  = $entry[0];
            $attr  = $entry[1];
            $value = $entry[2];
            if ($value === null)
                $value = 'NIL';
            else
                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
            $entries[] = sprintf('%s (%s %s)',
                $this->escape($name), $this->escape($attr), $value);
        }
        $entries = implode(' ', $entries);
        $result  = $this->execute('SETANNOTATION', array(
            $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
        return ($result == self::ERROR_OK);
    }
    /**
     * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
     *
     * @param string $mailbox Mailbox name
     * @param array  $data    Data array where each item is an array with
     *                        two elements: entry name and attribute name
     *
     * @return boolean True on success, False on failure
     *
     * @access public
     * @since 0.5-beta
     */
    function deleteAnnotation($mailbox, $data)
    {
        if (!is_array($data) || empty($data)) {
            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
            return false;
        }
        return $this->setAnnotation($mailbox, $data);
    }
    /**
     * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
     *
     * @param string $mailbox Mailbox name
     * @param array  $entries Entries names
     * @param array  $attribs Attribs names
     *
     * @return array Annotations result on success, NULL on error
     *
     * @access public
     * @since 0.5-beta
     */
    function getAnnotation($mailbox, $entries, $attribs)
    {
        if (!is_array($entries)) {
            $entries = array($entries);
        }
        // create entries string
        foreach ($entries as $idx => $name) {
            $entries[$idx] = $this->escape($name);
        }
        $entries = '(' . implode(' ', $entries) . ')';
        if (!is_array($attribs)) {
            $attribs = array($attribs);
        }
        // create entries string
        foreach ($attribs as $idx => $name) {
            $attribs[$idx] = $this->escape($name);
        }
        $attribs = '(' . implode(' ', $attribs) . ')';
        list($code, $response) = $this->execute('GETANNOTATION', array(
            $this->escape($mailbox), $entries, $attribs));
        if ($code == self::ERROR_OK && preg_match('/^\* ANNOTATION /i', $response)) {
            // Parse server response (remove "* ANNOTATION ")
            $response = substr($response, 13);
            $ret_mbox = $this->tokenizeResponse($response, 1);
            $data     = $this->tokenizeResponse($response);
            $res      = array();
            // Here we returns only data compatible with METADATA result format
            if (!empty($data) && ($size = count($data))) {
                for ($i=0; $i<$size; $i++) {
                    $entry = $data[$i++];
                    if (is_array($entry)) {
                        $attribs = $entry;
                        $entry   = $last_entry;
                    }
                    else
                        $attribs = $data[$i++];
                    if (!empty($attribs)) {
                        for ($x=0, $len=count($attribs); $x<$len;) {
                            $attr  = $attribs[$x++];
                            $value = $attribs[$x++];
                            if ($attr == 'value.priv')
                                $res['/private' . $entry] = $value;
                            else if ($attr == 'value.shared')
                                $res['/shared' . $entry] = $value;
                        }
                    }
                    $last_entry = $entry;
                    unset($data[$i-1]);
                    unset($data[$i-2]);
                }
            }
            return $res;
        }
        return NULL;
    }
    /**
     * Creates next command identifier (tag)
     *
     * @return string Command identifier
     * @access public
     * @since 0.5-beta
     */
    function next_tag()
    {
        $this->cmd_num++;
        $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
        return $this->cmd_tag;
    }
    /**
     * Sends IMAP command and parses result
     *
     * @param string $command   IMAP command
     * @param array  $arguments Command arguments
     * @param int    $options   Execution options
     *
     * @return mixed Response code or list of response code and data
     * @access public
     * @since 0.5-beta
     */
    function execute($command, $arguments=array(), $options=0)
    {
        $tag      = $this->next_tag();
        $query    = $tag . ' ' . $command;
        $noresp   = ($options & self::COMMAND_NORESPONSE);
        $response = $noresp ? null : '';
        if (!empty($arguments))
            $query .= ' ' . implode(' ', $arguments);
        // Send command
       if (!$this->putLineC($query)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $query");
          return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
       }
        // Parse response
       do {
          $line = $this->readLine(4096);
          if ($response !== null)
              $response .= $line;
       } while (!$this->startsWith($line, $tag . ' ', true, true));
       $code = $this->parseResult($line, $command . ': ');
        // Remove last line from response
       if ($response) {
           $line_len = min(strlen($response), strlen($line) + 2);
            $response = substr($response, 0, -$line_len);
        }
          // optional CAPABILITY response
       if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
            && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
        ) {
          $this->parseCapability($matches[1], true);
       }
       return $noresp ? $code : array($code, $response);
    }
    /**
     * Splits IMAP response into string tokens
     *
     * @param string &$str The IMAP's server response
     * @param int    $num  Number of tokens to return
     *
     * @return mixed Tokens array or string if $num=1
     * @access public
     * @since 0.5-beta
     */
    static function tokenizeResponse(&$str, $num=0)
    {
        $result = array();
        while (!$num || count($result) < $num) {
            // remove spaces from the beginning of the string
            $str = ltrim($str);
            switch ($str[0]) {
            // String literal
            case '{':
                if (($epos = strpos($str, "}\r\n", 1)) == false) {
                    // error
                }
                if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
                    // error
                }
                $result[] = substr($str, $epos + 3, $bytes);
                // Advance the string
                $str = substr($str, $epos + 3 + $bytes);
            break;
            // Quoted string
            case '"':
                $len = strlen($str);
                for ($pos=1; $pos<$len; $pos++) {
                    if ($str[$pos] == '"') {
                        break;
                    }
                    if ($str[$pos] == "\\") {
                        if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
                            $pos++;
                        }
                    }
                }
                if ($str[$pos] != '"') {
                    // error
                }
                // we need to strip slashes for a quoted string
                $result[] = stripslashes(substr($str, 1, $pos - 1));
                $str      = substr($str, $pos + 1);
            break;
            // Parenthesized list
            case '(':
                $str = substr($str, 1);
                $result[] = self::tokenizeResponse($str);
            break;
            case ')':
                $str = substr($str, 1);
                return $result;
            break;
            // String atom, number, NIL, *, %
            default:
                // empty or one character
                if ($str === '') {
                    break 2;
                }
                if (strlen($str) < 2) {
                    $result[] = $str;
                    $str = '';
                    break;
                }
                // excluded chars: SP, CTL, (, ), {, ", ], %
                if (preg_match('/^([\x21\x23\x24\x26\x27\x2A-\x5C\x5E-\x7A\x7C-\x7E]+)/', $str, $m)) {
                    $result[] = $m[1] == 'NIL' ? NULL : $m[1];
                    $str = substr($str, strlen($m[1]));
                }
            break;
            }
        }
        return $num == 1 ? $result[0] : $result;
    }
    private function _xor($string, $string2)
    {
       $result = '';
@@ -2157,6 +3053,13 @@
       return $result;
    }
    /**
     * Converts datetime string into unix timestamp
     *
     * @param string $date Date string
     *
     * @return int Unix timestamp
     */
    private function strToTime($date)
    {
       // support non-standard "GMTXXXX" literal
@@ -2186,54 +3089,51 @@
       return $string;
    }
    private function parseNamespace($str, &$i, $len=0, $l)
    private function parseCapability($str, $trusted=false)
    {
       if (!$l) {
           $str = str_replace('NIL', '()', $str);
       }
       if (!$len) {
           $len = strlen($str);
       }
       $data      = array();
       $in_quotes = false;
       $elem      = 0;
        $str = preg_replace('/^\* CAPABILITY /i', '', $str);
        for ($i;$i<$len;$i++) {
          $c = (string)$str[$i];
          if ($c == '(' && !$in_quotes) {
             $i++;
             $data[$elem] = $this->parseNamespace($str, $i, $len, $l++);
             $elem++;
          } else if ($c == ')' && !$in_quotes) {
             return $data;
          } else if ($c == '\\') {
             $i++;
             if ($in_quotes) {
                $data[$elem] .= $c.$str[$i];
              }
          } else if ($c == '"') {
             $in_quotes = !$in_quotes;
             if (!$in_quotes) {
                $elem++;
              }
          } else if ($in_quotes) {
             $data[$elem].=$c;
          }
       }
        $this->capability = explode(' ', strtoupper($str));
        return $data;
        if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
            $this->prefs['literal+'] = true;
        }
        if ($trusted) {
            $this->capability_readed = true;
        }
    }
    private function escape($string)
    /**
     * Escapes a string when it contains special characters (RFC3501)
     *
     * @param string $string IMAP string
     *
     * @return string Escaped string
     * @todo String literals, lists
     */
    static function escape($string)
    {
       return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
        // NIL
        if ($string === null) {
            return 'NIL';
        }
        // empty string
        else if ($string === '') {
            return '""';
        }
        // string: special chars: SP, CTL, (, ), {, %, *, ", \, ]
        else if (preg_match('/([\x00-\x20\x28-\x29\x7B\x25\x2A\x22\x5C\x5D\x7F]+)/', $string)) {
           return '"' . strtr($string, array('"'=>'\\"', '\\' => '\\\\')) . '"';
        }
        // atom
        return $string;
    }
    private function unEscape($string)
    static function unEscape($string)
    {
       return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
    }
}
?>