alecpl
2010-11-05 cb105aa9f12396d1644e87d91c35e8f5c3eefbbd
program/include/rcube_imap_generic.php
@@ -86,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',
@@ -101,8 +99,6 @@
        '*'        => '\\*',
    );
   private $exists;
   private $recent;
    private $selected;
   private $fp;
   private $host;
@@ -121,6 +117,7 @@
    const ERROR_UNKNOWN = -4;
    const COMMAND_NORESPONSE = 1;
    const COMMAND_CAPABILITY = 2;
    /**
     * Object constructor
@@ -129,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)
@@ -148,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)
@@ -372,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:
@@ -471,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)
@@ -487,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;
       }
@@ -511,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)
@@ -545,8 +679,6 @@
       } else {
          $auth_method = 'CHECK';
        }
       $message = "INITIAL: $auth_method\n";
       $result = false;
@@ -603,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')) {
@@ -623,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()
@@ -694,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;
    }
@@ -707,33 +862,81 @@
       if (empty($mailbox)) {
          return false;
       }
       if ($this->selected == $mailbox) {
          return true;
       }
        $key = $this->next_tag();
        $command = "$key SELECT " . $this->escape($mailbox);
       if (!$this->putLine($command)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
            return false;
        if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
            if (in_array('\\Noselect', $opts)) {
                return false;
            }
        }
      do {
         $line = rtrim($this->readLine(512));
        list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
         if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/', $line, $m)) {
             $token = strtolower($m[2]);
             $this->$token = (int) $m[1];
         }
         else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
             $this->permanentflags = explode(' ', $match[1]);
         }
      } while (!$this->startsWith($line, $key, true, true));
        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]);
             }
            }
        if ($this->parseResult($line, 'SELECT: ') == self::ERROR_OK) {
          $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;
@@ -747,7 +950,7 @@
       $this->select($mailbox);
       if ($this->selected == $mailbox) {
          return $this->recent;
          return $this->data['RECENT'];
       }
       return false;
@@ -759,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;
    }
@@ -781,14 +1026,13 @@
           return false;
       }
       /*  Do "SELECT" command */
       if (!$this->select($mailbox)) {
           return false;
       }
       // message IDs
       if (is_array($add))
          $add = $this->compressMessageSet(join(',', $add));
       if (!empty($add))
          $add = $this->compressMessageSet($add);
       list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
           array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
@@ -805,7 +1049,7 @@
    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);
@@ -929,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) {
@@ -965,7 +1212,7 @@
       }
       // handle the last sequence/id
       if ($start==$prev) {
       if ($start == $prev) {
           $result[] = $prev;
       } else {
           $result[] = $start.':'.$prev;
@@ -975,35 +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;
        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)) {
         $result = $m[1];
         return (int) $m[1];
        }
       return $result;
       return null;
    }
    function fetchUIDs($mailbox, $message_set=null)
@@ -1024,9 +1305,6 @@
          return false;
       }
       if (is_array($message_set))
          $message_set = join(',', $message_set);
       $message_set = $this->compressMessageSet($message_set);
       if ($add)
@@ -1046,7 +1324,7 @@
          return false;
       }
       do {
          $line = $this->readLine(1024);
          $line = $this->readLine(4096);
          $line = $this->multLine($line);
            if (!$line)
@@ -1287,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,
@@ -1315,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 {
@@ -1333,8 +1612,7 @@
          $result = array();
          reset($index);
          while (list($key, $val) = each($index)) {
             $result[$key]=$a[$key];
             $i++;
             $result[$key] = $a[$key];
          }
       }
@@ -1346,6 +1624,9 @@
       if (!$this->select($mailbox)) {
            return false;
        }
        // Clear internal status cache
        unset($this->data['STATUS:'.$mailbox]);
      $result = $this->execute($messages ? 'UID EXPUNGE' : 'EXPUNGE',
          array($messages), self::COMMAND_NORESPONSE);
@@ -1361,35 +1642,24 @@
    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;
        $key = $this->next_tag();
        $command = "$key UID STORE $messages {$mod}FLAGS ($flag)";
       if (!$this->putLine($command)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
            return -1;
        // Clear internal status cache
        if ($flag == 'SEEN') {
            unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
        }
       do {
          $line = $this->readLine();
          if ($line[0] == '*') {
              $c++;
            }
       } while (!$this->startsWith($line, $key, 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, 'STORE: ') == self::ERROR_OK) {
          return $c;
       }
       return -1;
       return ($result == self::ERROR_OK);
    }
    function flag($mailbox, $messages, $flag) {
@@ -1407,25 +1677,38 @@
    function copy($messages, $from, $to)
    {
       if (empty($from) || empty($to)) {
           return -1;
           return false;
       }
       if (!$this->select($from)) {
            return -1;
           return false;
       }
        $result = $this->execute('UID COPY', array($messages, $this->escape($to)),
        // 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;
       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
@@ -1479,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());
       }
@@ -1515,96 +1798,212 @@
       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();
       }
        $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($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'];
       }
        $command = $subscribed ? 'LSUB' : 'LIST';
        $key     = $this->next_tag();
        $query   = sprintf("%s %s %s %s", $key, $command,
            $this->escape($ref), $this->escape($mailbox));
        $args = array();
       // send command
       if (!$this->putLine($query)) {
            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $query");
           return false;
       }
        if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
            $select_opts = (array) $select_opts;
       // get folder list
       do {
          $line = $this->readLine(500);
          $line = $this->multLine($line, true);
          $line = trim($line);
            $args[] = '(' . implode(' ', $select_opts) . ')';
        }
          if (preg_match('/^\* '.$command.' \(([^\)]*)\) "*([^"]+)"* (.*)$/', $line, $m)) {
              // folder name
                $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($m[3]));
              // attributes
//              $attrib = explode(' ', $this->unEscape($m[1]));
              // delimiter
//              $delim = $this->unEscape($m[2]);
        $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) == '*') {
                $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, $command.': ') == self::ERROR_OK) {
            return array();
            return $folders;
        }
       return false;
@@ -1811,9 +2210,9 @@
       return false;
    }
    function createFolder($folder)
    function createFolder($mailbox)
    {
        $result = $this->execute('CREATE', array($this->escape($folder)),
        $result = $this->execute('CREATE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
@@ -1827,42 +2226,42 @@
      return ($result == self::ERROR_OK);
    }
    function deleteFolder($folder)
    function deleteFolder($mailbox)
    {
        $result = $this->execute('DELETE', array($this->escape($folder)),
        $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)
    {
       $result = $this->execute('SUBSCRIBE', array($this->escape($folder)),
       $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    function unsubscribe($folder)
    function unsubscribe($mailbox)
    {
       $result = $this->execute('UNSUBSCRIBE', array($this->escape($folder)),
       $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
           self::COMMAND_NORESPONSE);
       return ($result == self::ERROR_OK);
    }
    function append($folder, &$message)
    function append($mailbox, &$message)
    {
       if (!$folder) {
       if (!$mailbox) {
          return false;
       }
@@ -1875,7 +2274,7 @@
       }
        $key = $this->next_tag();
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($folder),
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
            $len, ($this->prefs['literal+'] ? '+' : ''));
       if ($this->putLine($request)) {
@@ -1897,6 +2296,9 @@
             $line = $this->readLine();
          } while (!$this->startsWith($line, $key, true, true));
            // Clear internal status cache
            unset($this->data['STATUS:'.$mailbox]);
          return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
       }
        else {
@@ -1906,9 +2308,9 @@
       return false;
    }
    function appendFromFile($folder, $path, $headers=null)
    function appendFromFile($mailbox, $path, $headers=null)
    {
       if (!$folder) {
       if (!$mailbox) {
           return false;
       }
@@ -1936,7 +2338,7 @@
       // send APPEND command
       $key = $this->next_tag();
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($folder),
       $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
            $len, ($this->prefs['literal+'] ? '+' : ''));
       if ($this->putLine($request)) {
@@ -1971,6 +2373,8 @@
             $line = $this->readLine();
          } while (!$this->startsWith($line, $key, true, true));
            // Clear internal status cache
            unset($this->data['STATUS:'.$mailbox]);
          return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
       }
@@ -1981,9 +2385,9 @@
       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;
        }
@@ -2540,6 +2944,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);
    }
@@ -2678,45 +3089,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);
@@ -2725,6 +3098,10 @@
        if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
            $this->prefs['literal+'] = true;
        }
        if ($trusted) {
            $this->capability_readed = true;
        }
    }
    /**