alecpl
2010-10-29 2cd443315dbd0b3d7fdec78f0042f22d20e57ede
program/include/rcube_imap_generic.php
@@ -86,8 +86,6 @@
    public $error;
    public $errornum;
   public $message;
   public $rootdir;
   public $delimiter;
    public $data = array();
    public $flags = array(
        'SEEN'     => '\\Seen',
@@ -119,6 +117,7 @@
    const ERROR_UNKNOWN = -4;
    const COMMAND_NORESPONSE = 1;
    const COMMAND_CAPABILITY = 2;
    /**
     * Object constructor
@@ -127,6 +126,14 @@
    {
    }
    /**
     * 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)
@@ -146,7 +153,15 @@
        return $res;
    }
    // $this->putLine replacement with Command Continuation Requests (RFC3501 7.5) support
    /**
     * 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)
@@ -370,93 +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 == 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";
        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)
    {
        list($code, $response) = $this->execute('LOGIN', array(
            $this->escape($user), $this->escape($password)));
            $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
        // re-set capabilities list if untagged CAPABILITY response provided
       if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
          $this->parseCapability($matches[1]);
          $this->parseCapability($matches[1], true);
       }
        if ($code == self::ERROR_OK) {
            return $this->fp;
        }
        @fclose($this->fp);
        $this->fp    = false;
        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 (!is_array($data = $this->_namespace())) {
       if (!is_array($data = $this->getNamespace())) {
           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:
@@ -469,11 +591,11 @@
     */
    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'];
       }
       // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
@@ -485,19 +607,18 @@
            $delimiter = $args[3];
           if (strlen($delimiter) > 0) {
               $this->delimiter = $delimiter;
               return $delimiter;
               return ($this->prefs['delimiter'] = $delimiter);
           }
        }
       // if that fails, try namespace extension
       // try to fetch namespace data
       if (!is_array($data = $this->_namespace())) {
       if (!is_array($data = $this->getNamespace())) {
            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;
       }
@@ -509,26 +630,41 @@
       }
       // extract delimiter
       return $this->delimiter = $first_userspace[1];
       return $this->prefs['delimiter'] = $first_userspace[1];
    }
    function _namespace()
    /**
     * 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 false;
           return self::ERROR_BAD;
       }
       list($code, $response) = $this->execute('NAMESPACE');
      if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
           $data = $this->parseNamespace(substr($response, 11), $i, 0, 0);
           $data = $this->tokenizeResponse(substr($response, 11));
      }
       if (!is_array($data)) {
           return false;
           return $code;
       }
        return $data;
        $this->prefs['namespace'] = array(
            'personal' => $data[0],
            'other'    => $data[1],
            'shared'   => $data[2],
        );
        return $this->prefs['namespace'];
    }
    function connect($host, $user, $password, $options=null)
@@ -543,8 +679,6 @@
       } else {
          $auth_method = 'CHECK';
        }
       $message = "INITIAL: $auth_method\n";
       $result = false;
@@ -601,19 +735,21 @@
       // 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 = self::ERROR_BAD;
             $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->parseCapability($matches[1]);
          $this->parseCapability($matches[1], true);
       }
       $this->message .= $line;
       $this->message = $line;
       // TLS connection
       if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
@@ -621,68 +757,89 @@
                  $res = $this->execute('STARTTLS');
                if ($res[0] != self::ERROR_OK) {
                    $this->close();
                    return false;
                }
             if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                $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($this->next_tag() . " 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 == self::ERROR_BYE) {
                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()
@@ -692,10 +849,10 @@
    function close()
    {
       if ($this->logged && $this->putLine($this->next_tag() . ' LOGOUT')) {
          if (!feof($this->fp))
             fgets($this->fp, 1024);
       }
       if ($this->putLine($this->next_tag() . ' LOGOUT')) {
           $this->readReply();
        }
      @fclose($this->fp);
      $this->fp = false;
    }
@@ -709,6 +866,12 @@
       if ($this->selected == $mailbox) {
          return true;
       }
        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)));
@@ -728,6 +891,41 @@
          $this->selected = $mailbox;
         return true;
      }
        return false;
    }
    /**
     * Executes STATUS comand
     *
     * @param string $mailbox Mailbox name
     * @param array  $items   Requested item names
     *
     * @return array Status item-value hash
     * @access public
     * @since 0.5-beta
     */
    function status($mailbox, $items)
    {
       if (empty($mailbox) || empty($items)) {
          return false;
       }
        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];
            }
         return $result;
      }
        return false;
@@ -753,10 +951,40 @@
          $this->selected = '';
       }
       $this->select($mailbox);
       if ($this->selected == $mailbox) {
          return $this->data['EXISTS'];
       }
        // Try STATUS, should be faster
        $counts = $this->status($mailbox, array('MESSAGES'));
        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)
    {
        // Try STATUS, should be faster
        $counts = $this->status($mailbox, array('UNSEEN'));
        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;
    }
@@ -778,6 +1006,11 @@
       if (!$this->select($mailbox)) {
           return false;
       }
        // RFC 5957: SORT=DISPLAY
        if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
            $field = 'DISPLAY' . $field;
        }
       // message IDs
       if (is_array($add))
@@ -922,17 +1155,17 @@
       return $result;
    }
    private function compressMessageSet($message_set)
    private function compressMessageSet($message_set, $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) {
       if (!$force && strlen($message_set)<255) {
           return $message_set;
       }
       // see if it's already been compress
       // see if it's already been compressed
       if (strpos($message_set, ':') !== false) {
           return $message_set;
       }
@@ -1413,14 +1646,6 @@
       return $result;
    }
    function countUnseen($folder)
    {
        $index = $this->search($folder, 'ALL UNSEEN');
        if (is_array($index))
            return count($index);
        return false;
    }
    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
    // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
    // http://derickrethans.nl/files/phparch-php-variables-article.pdf
@@ -1508,27 +1733,92 @@
       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->data['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();
       }
        $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
        $criteria = trim($criteria);
        $params   = '';
        // RFC4731: ESEARCH
        if (!empty($items) && $esearch) {
            $params .= 'RETURN (' . implode(' ', $items) . ')';
        }
        if (!empty($criteria)) {
            $params .= ($params ? ' ' : '') . $criteria;
        }
        else {
            $params .= 'ALL';
        }
       list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
           array(trim($criteria)));
           array($params));
       if ($code == self::ERROR_OK) {
           // remove prefix and \r\n from raw response
           $response = str_replace("\r\n", '', substr($response, 9));
          return preg_split('/\s+/', $response, -1, PREG_SPLIT_NO_EMPTY);
       }
            $response = substr($response, $esearch ? 10 : 9);
           $response = str_replace("\r\n", '', $response);
            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(implode(',', $response), true);
                    return $result;
                }
                else {
                    return $response;
                }
           }
        }
       return false;
    }
@@ -1547,36 +1837,121 @@
        return $r;
    }
    function listMailboxes($ref, $mailbox)
    /**
     * 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())
    {
        return $this->_listMailboxes($ref, $mailbox, false);
        return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
    }
    function listSubscribed($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, true);
        return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
    }
    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'];
       }
        list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST',
            array($this->escape($ref), $this->escape($mailbox)));
        $args = array();
        if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
            $select_opts = (array) $select_opts;
            $args[] = '(' . implode(' ', $select_opts) . ')';
        }
        $args[] = $this->escape($ref);
        $args[] = $this->escape($mailbox);
        if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
            $status_opts = (array) $status_opts;
            $lstatus = true;
            $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) == '*') {
                list (,$opts, $delim, $folder) = $this->tokenizeResponse($response, 4);
              // folder name
                $folders[] = $folder;
                $cmd = strtoupper($this->tokenizeResponse($response, 1));
                // * LIST (<options>) <delimiter> <mailbox>
                if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
                    list($opts, $delim, $folder) = $this->tokenizeResponse($response, 3);
                    // Add to result array
                    if (!$lstatus) {
                        $folders[] = $folder;
                    }
                    else {
                        $folders[$folder] = array();
                    }
                    // Add to options array
                    if (!empty($opts)) {
                        if (empty($this->data['LIST'][$folder]))
                            $this->data['LIST'][$folder] = $opts;
                        else
                            $this->data['LIST'][$folder] = array_unique(array_merge(
                                $this->data['LIST'][$folder], $opts));
                    }
                }
                // * STATUS <mailbox> (<result>)
                else if ($cmd == 'STATUS') {
                    list($folder, $status) = $this->tokenizeResponse($response, 2);
                    for ($i=0, $len=count($status); $i<$len; $i += 2) {
                        list($name, $value) = $this->tokenizeResponse($status, 2);
                        $folders[$folder][$name] = $value;
                    }
                }
          }
            return $folders;
        }
@@ -2513,6 +2888,13 @@
            $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);
    }
@@ -2651,45 +3033,7 @@
       return $string;
    }
    private function parseNamespace($str, &$i, $len=0, $l)
    {
       if (!$l) {
           $str = str_replace('NIL', '()', $str);
       }
       if (!$len) {
           $len = strlen($str);
       }
       $data      = array();
       $in_quotes = false;
       $elem      = 0;
        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] .= $str[$i];
              }
          } else if ($c == '"') {
             $in_quotes = !$in_quotes;
             if (!$in_quotes) {
                $elem++;
              }
          } else if ($in_quotes) {
             $data[$elem].=$c;
          }
       }
        return $data;
    }
    private function parseCapability($str)
    private function parseCapability($str, $trusted=false)
    {
        $str = preg_replace('/^\* CAPABILITY /i', '', $str);
@@ -2698,6 +3042,10 @@
        if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
            $this->prefs['literal+'] = true;
        }
        if ($trusted) {
            $this->capability_readed = true;
        }
    }
    /**