/roundcubemail-0.7.2-dep/program/include/rcube_imap_generic.php
PHP | 3571 lines | 2417 code | 496 blank | 658 comment | 693 complexity | 6513f7c899dba185cf73f2fae234da0e MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- +-----------------------------------------------------------------------+
- | program/include/rcube_imap_generic.php |
- | |
- | This file is part of the Roundcube Webmail client |
- | Copyright (C) 2005-2010, The Roundcube Dev Team |
- | Copyright (C) 2011, Kolab Systems AG |
- | Licensed under the GNU GPL |
- | |
- | PURPOSE: |
- | Provide alternative IMAP library that doesn't rely on the standard |
- | C-Client based version. This allows to function regardless |
- | of whether or not the PHP build it's running on has IMAP |
- | functionality built-in. |
- | |
- | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
- | |
- +-----------------------------------------------------------------------+
- | Author: Aleksander Machniak <alec@alec.pl> |
- | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
- +-----------------------------------------------------------------------+
- $Id: rcube_imap_generic.php 5970 2012-03-06 19:43:49Z alec $
- */
- /**
- * Struct representing an e-mail message header
- *
- * @package Mail
- * @author Aleksander Machniak <alec@alec.pl>
- */
- class rcube_mail_header
- {
- public $id;
- public $uid;
- public $subject;
- public $from;
- public $to;
- public $cc;
- public $replyto;
- public $in_reply_to;
- public $date;
- public $messageID;
- public $size;
- public $encoding;
- public $charset;
- public $ctype;
- public $timestamp;
- public $bodystructure;
- public $internaldate;
- public $references;
- public $priority;
- public $mdn_to;
- public $others = array();
- public $flags = array();
- }
- // For backward compatibility with cached messages (#1486602)
- class iilBasicHeader extends rcube_mail_header
- {
- }
- /**
- * PHP based wrapper class to connect to an IMAP server
- *
- * @package Mail
- * @author Aleksander Machniak <alec@alec.pl>
- */
- class rcube_imap_generic
- {
- public $error;
- public $errornum;
- public $result;
- public $resultcode;
- public $selected;
- public $data = array();
- public $flags = array(
- 'SEEN' => '\\Seen',
- 'DELETED' => '\\Deleted',
- 'ANSWERED' => '\\Answered',
- 'DRAFT' => '\\Draft',
- 'FLAGGED' => '\\Flagged',
- 'FORWARDED' => '$Forwarded',
- 'MDNSENT' => '$MDNSent',
- '*' => '\\*',
- );
- private $fp;
- private $host;
- private $logged = false;
- private $capability = array();
- private $capability_readed = false;
- private $prefs;
- private $cmd_tag;
- private $cmd_num = 0;
- private $resourceid;
- private $_debug = false;
- private $_debug_handler = false;
- const ERROR_OK = 0;
- const ERROR_NO = -1;
- const ERROR_BAD = -2;
- const ERROR_BYE = -3;
- const ERROR_UNKNOWN = -4;
- const ERROR_COMMAND = -5;
- const ERROR_READONLY = -6;
- const COMMAND_NORESPONSE = 1;
- const COMMAND_CAPABILITY = 2;
- const COMMAND_LASTLINE = 4;
- /**
- * Object constructor
- */
- function __construct()
- {
- }
- /**
- * 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;
- if ($this->_debug) {
- $this->debug('C: '. rtrim($string));
- }
- $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
- if ($res === false) {
- @fclose($this->fp);
- $this->fp = null;
- }
- return $res;
- }
- /**
- * 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 false;
- if ($endln)
- $string .= "\r\n";
- $res = 0;
- 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], $matches)) {
- // LITERAL+ support
- if ($this->prefs['literal+']) {
- $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
- }
- $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
- if ($bytes === false)
- return false;
- $res += $bytes;
- // 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);
- if ($bytes === false)
- return false;
- $res += $bytes;
- }
- }
- }
- return $res;
- }
- function readLine($size=1024)
- {
- $line = '';
- if (!$size) {
- $size = 1024;
- }
- do {
- if ($this->eof()) {
- return $line ? $line : NULL;
- }
- $buffer = fgets($this->fp, $size);
- if ($buffer === false) {
- $this->closeSocket();
- break;
- }
- if ($this->_debug) {
- $this->debug('S: '. rtrim($buffer));
- }
- $line .= $buffer;
- } while (substr($buffer, -1) != "\n");
- return $line;
- }
- function multLine($line, $escape = false)
- {
- $line = rtrim($line);
- if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
- $out = '';
- $str = substr($line, 0, -strlen($m[0]));
- $bytes = $m[1];
- while (strlen($out) < $bytes) {
- $line = $this->readBytes($bytes);
- if ($line === NULL)
- break;
- $out .= $line;
- }
- $line = $str . ($escape ? $this->escape($out) : $out);
- }
- return $line;
- }
- function readBytes($bytes)
- {
- $data = '';
- $len = 0;
- while ($len < $bytes && !$this->eof())
- {
- $d = fread($this->fp, $bytes-$len);
- if ($this->_debug) {
- $this->debug('S: '. $d);
- }
- $data .= $d;
- $data_len = strlen($data);
- if ($len == $data_len) {
- break; // nothing was read -> exit to avoid apache lockups
- }
- $len = $data_len;
- }
- return $data;
- }
- function readReply(&$untagged=null)
- {
- do {
- $line = trim($this->readLine(1024));
- // store untagged response lines
- if ($line[0] == '*')
- $untagged[] = $line;
- } while ($line[0] == '*');
- if ($untagged)
- $untagged = join("\n", $untagged);
- return $line;
- }
- function parseResult($string, $err_prefix='')
- {
- 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') {
- $this->errornum = self::ERROR_OK;
- } else if ($res == 'NO') {
- $this->errornum = self::ERROR_NO;
- } else if ($res == 'BAD') {
- $this->errornum = self::ERROR_BAD;
- } else if ($res == 'BYE') {
- $this->closeSocket();
- $this->errornum = self::ERROR_BYE;
- }
- if ($str) {
- $str = trim($str);
- // get response string and code (RFC5530)
- if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
- $this->resultcode = strtoupper($m[1]);
- $str = trim(substr($str, strlen($m[1]) + 2));
- }
- else {
- $this->resultcode = null;
- // parse response for [APPENDUID 1204196876 3456]
- if (preg_match("/^\[APPENDUID [0-9]+ ([0-9,:*]+)\]/i", $str, $m)) {
- $this->data['APPENDUID'] = $m[1];
- }
- }
- $this->result = $str;
- if ($this->errornum != self::ERROR_OK) {
- $this->error = $err_prefix ? $err_prefix.$str : $str;
- }
- }
- return $this->errornum;
- }
- return self::ERROR_UNKNOWN;
- }
- private function eof()
- {
- if (!is_resource($this->fp)) {
- return true;
- }
- // If a connection opened by fsockopen() wasn't closed
- // by the server, feof() will hang.
- $start = microtime(true);
- if (feof($this->fp) ||
- ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
- ) {
- $this->closeSocket();
- return true;
- }
- return false;
- }
- private function closeSocket()
- {
- @fclose($this->fp);
- $this->fp = null;
- }
- function setError($code, $msg='')
- {
- $this->errornum = $code;
- $this->error = $msg;
- }
- // check if $string starts with $match (or * BYE/BAD)
- function startsWith($string, $match, $error=false, $nonempty=false)
- {
- $len = strlen($match);
- if ($len == 0) {
- return false;
- }
- if (!$this->fp) {
- return true;
- }
- if (strncmp($string, $match, $len) == 0) {
- return true;
- }
- if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
- if (strtoupper($m[1]) == 'BYE') {
- $this->closeSocket();
- }
- return true;
- }
- if ($nonempty && !strlen($string)) {
- return true;
- }
- return false;
- }
- private function hasCapability($name)
- {
- if (empty($this->capability) || $name == '') {
- return false;
- }
- if (in_array($name, $this->capability)) {
- return true;
- }
- else if (strpos($name, '=')) {
- return false;
- }
- $result = array();
- foreach ($this->capability as $cap) {
- $entry = explode('=', $cap);
- if ($entry[0] == $name) {
- $result[] = $entry[1];
- }
- }
- return !empty($result) ? $result : false;
- }
- /**
- * Capabilities checker
- *
- * @param string $name Capability name
- *
- * @return mixed Capability values array for key=value pairs, true/false for others
- */
- function getCapability($name)
- {
- $result = $this->hasCapability($name);
- if (!empty($result)) {
- return $result;
- }
- else if ($this->capability_readed) {
- return false;
- }
- // get capabilities (only once) because initial
- // optional CAPABILITY response may differ
- $result = $this->execute('CAPABILITY');
- if ($result[0] == self::ERROR_OK) {
- $this->parseCapability($result[1]);
- }
- $this->capability_readed = true;
- return $this->hasCapability($name);
- }
- function clearCapability()
- {
- $this->capability = array();
- $this->capability_readed = false;
- }
- /**
- * 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')
- {
- if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
- if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
- $this->setError(self::ERROR_BYE,
- "The Auth_SASL package is required for DIGEST-MD5 authentication");
- return self::ERROR_BAD;
- }
- $this->putLine($this->nextTag() . " AUTHENTICATE $type");
- $line = trim($this->readReply());
- 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 = trim($this->readReply());
- if ($line[0] == '+') {
- $challenge = substr($line, 2);
- }
- else {
- return $this->parseResult($line);
- }
- // check response
- $challenge = base64_decode($challenge);
- if (strpos($challenge, 'rspauth=') === false) {
- $this->setError(self::ERROR_BAD,
- "Unexpected response from server to DIGEST-MD5 response");
- return self::ERROR_BAD;
- }
- $this->putLine('');
- }
- $line = $this->readReply();
- $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')) {
- list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
- self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY);
- }
- else {
- $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
- $line = trim($this->readReply());
- if ($line[0] != '+') {
- return $this->parseResult($line);
- }
- // send result, get reply and process it
- $this->putLine($reply);
- $line = $this->readReply();
- $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;
- }
- else {
- $this->setError($result, "AUTHENTICATE $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)), self::COMMAND_CAPABILITY);
- // re-set capabilities list if untagged CAPABILITY response provided
- if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
- $this->parseCapability($matches[1], true);
- }
- if ($code == self::ERROR_OK) {
- return $this->fp;
- }
- return $code;
- }
- /**
- * Gets the delimiter
- *
- * @return string The delimiter
- */
- function getHierarchyDelimiter()
- {
- if ($this->prefs['delimiter']) {
- return $this->prefs['delimiter'];
- }
- // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
- list($code, $response) = $this->execute('LIST',
- array($this->escape(''), $this->escape('')));
- if ($code == self::ERROR_OK) {
- $args = $this->tokenizeResponse($response, 4);
- $delimiter = $args[3];
- if (strlen($delimiter) > 0) {
- return ($this->prefs['delimiter'] = $delimiter);
- }
- }
- return NULL;
- }
- /**
- * 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)
- {
- // set options
- if (is_array($options)) {
- $this->prefs = $options;
- }
- // set auth method
- if (!empty($this->prefs['auth_type'])) {
- $auth_method = strtoupper($this->prefs['auth_type']);
- } else {
- $auth_method = 'CHECK';
- }
- $result = false;
- // initialize connection
- $this->error = '';
- $this->errornum = self::ERROR_OK;
- $this->selected = null;
- $this->user = $user;
- $this->host = $host;
- $this->logged = false;
- // check input
- if (empty($host)) {
- $this->setError(self::ERROR_BAD, "Empty host");
- return false;
- }
- if (empty($user)) {
- $this->setError(self::ERROR_NO, "Empty user");
- return false;
- }
- if (empty($password)) {
- $this->setError(self::ERROR_NO, "Empty password");
- return false;
- }
- if (!$this->prefs['port']) {
- $this->prefs['port'] = 143;
- }
- // check for SSL
- if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
- $host = $this->prefs['ssl_mode'] . '://' . $host;
- }
- if ($this->prefs['timeout'] <= 0) {
- $this->prefs['timeout'] = ini_get('default_socket_timeout');
- }
- // Connect
- $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
- if (!$this->fp) {
- $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
- return false;
- }
- if ($this->prefs['timeout'] > 0)
- stream_set_timeout($this->fp, $this->prefs['timeout']);
- $line = trim(fgets($this->fp, 8192));
- if ($this->_debug) {
- // set connection identifier for debug output
- preg_match('/#([0-9]+)/', (string)$this->fp, $m);
- $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));
- if ($line)
- $this->debug('S: '. $line);
- }
- // Connected to wrong port or connection error?
- if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
- if ($line)
- $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
- else
- $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
- $this->setError(self::ERROR_BAD, $error);
- $this->closeConnection();
- return false;
- }
- // RFC3501 [7.1] optional CAPABILITY response
- if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
- $this->parseCapability($matches[1], true);
- }
- // TLS connection
- if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
- if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
- $res = $this->execute('STARTTLS');
- if ($res[0] != self::ERROR_OK) {
- $this->closeConnection();
- return false;
- }
- if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
- $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
- $this->closeConnection();
- return false;
- }
- // Now we're secure, capabilities need to be reread
- $this->clearCapability();
- }
- }
- // Send ID info
- if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
- $this->id($this->prefs['ident']);
- }
- $auth_methods = array();
- $result = null;
- // check for supported auth methods
- if ($auth_method == 'CHECK') {
- if ($auth_caps = $this->getCapability('AUTH')) {
- $auth_methods = $auth_caps;
- }
- // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
- $login_disabled = $this->getCapability('LOGINDISABLED');
- if (($key = array_search('LOGIN', $auth_methods)) !== false) {
- if ($login_disabled) {
- unset($auth_methods[$key]);
- }
- }
- else if (!$login_disabled) {
- $auth_methods[] = 'LOGIN';
- }
- // Use best (for security) supported authentication method
- foreach (array('DIGEST-MD5', 'CRAM-MD5', 'CRAM_MD5', 'PLAIN', 'LOGIN') as $auth_method) {
- if (in_array($auth_method, $auth_methods)) {
- break;
- }
- }
- }
- else {
- // Prevent from sending credentials in plain text when connection is not secure
- if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
- $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
- $this->closeConnection();
- return false;
- }
- // replace AUTH with CRAM-MD5 for backward compat.
- if ($auth_method == 'AUTH') {
- $auth_method = 'CRAM-MD5';
- }
- }
- // pre-login capabilities can be not complete
- $this->capability_readed = false;
- // Authenticate
- switch ($auth_method) {
- case 'CRAM_MD5':
- $auth_method = 'CRAM-MD5';
- case 'CRAM-MD5':
- case 'DIGEST-MD5':
- case 'PLAIN':
- $result = $this->authenticate($user, $password, $auth_method);
- break;
- case 'LOGIN':
- $result = $this->login($user, $password);
- break;
- default:
- $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
- }
- // Connected and authenticated
- if (is_resource($result)) {
- if ($this->prefs['force_caps']) {
- $this->clearCapability();
- }
- $this->logged = true;
- return true;
- }
- $this->closeConnection();
- return false;
- }
- function connected()
- {
- return ($this->fp && $this->logged) ? true : false;
- }
- function closeConnection()
- {
- if ($this->putLine($this->nextTag() . ' LOGOUT')) {
- $this->readReply();
- }
- $this->closeSocket();
- }
- /**
- * Executes SELECT command (if mailbox is already not in selected state)
- *
- * @param string $mailbox Mailbox name
- * @param array $qresync_data QRESYNC data (RFC5162)
- *
- * @return boolean True on success, false on error
- */
- function select($mailbox, $qresync_data = null)
- {
- if (!strlen($mailbox)) {
- return false;
- }
- if ($this->selected === $mailbox) {
- return true;
- }
- /*
- Temporary commented out because Courier returns \Noselect for INBOX
- Requires more investigation
- if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
- if (in_array('\\Noselect', $opts)) {
- return false;
- }
- }
- */
- $params = array($this->escape($mailbox));
- // QRESYNC data items
- // 0. the last known UIDVALIDITY,
- // 1. the last known modification sequence,
- // 2. the optional set of known UIDs, and
- // 3. an optional parenthesized list of known sequence ranges and their
- // corresponding UIDs.
- if (!empty($qresync_data)) {
- if (!empty($qresync_data[2]))
- $qresync_data[2] = self::compressMessageSet($qresync_data[2]);
- $params[] = array('QRESYNC', $qresync_data);
- }
- list($code, $response) = $this->execute('SELECT', $params);
- 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 \[/i', $line, $match)) {
- $line = substr($line, 6);
- if (preg_match('/^(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)/i', $line, $match)) {
- $this->data[strtoupper($match[1])] = (int) $match[2];
- }
- else if (preg_match('/^(HIGHESTMODSEQ) ([0-9]+)/i', $line, $match)) {
- $this->data[strtoupper($match[1])] = (string) $match[2];
- }
- else if (preg_match('/^(NOMODSEQ)/i', $line, $match)) {
- $this->data[strtoupper($match[1])] = true;
- }
- else if (preg_match('/^PERMANENTFLAGS \(([^\)]+)\)/iU', $line, $match)) {
- $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
- }
- }
- // QRESYNC FETCH response (RFC5162)
- else if (preg_match('/^\* ([0-9+]) FETCH/i', $line, $match)) {
- $line = substr($line, strlen($match[0]));
- $fetch_data = $this->tokenizeResponse($line, 1);
- $data = array('id' => $match[1]);
- for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
- $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
- }
- $this->data['QRESYNC'][$data['uid']] = $data;
- }
- // QRESYNC VANISHED response (RFC5162)
- else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
- $line = substr($line, strlen($match[0]));
- $v_data = $this->tokenizeResponse($line, 1);
- $this->data['VANISHED'] = $v_data;
- }
- }
- $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
- $this->selected = $mailbox;
- return true;
- }
- return false;
- }
- /**
- * Executes STATUS command
- *
- * @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
- * @since 0.5-beta
- */
- function status($mailbox, $items=array())
- {
- if (!strlen($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);
- // Fix for #1487859. Some buggy server returns not quoted
- // folder name with spaces. Let's try to handle this situation
- if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
- $response = substr($response, $pos);
- $items = $this->tokenizeResponse($response, 1);
- if (!is_array($items)) {
- return $result;
- }
- }
- for ($i=0, $len=count($items); $i<$len; $i += 2) {
- $result[$items[$i]] = $items[$i+1];
- }
- $this->data['STATUS:'.$mailbox] = $result;
- return $result;
- }
- return false;
- }
- /**
- * Executes EXPUNGE command
- *
- * @param string $mailbox Mailbox name
- * @param string $messages Message UIDs to expunge
- *
- * @return boolean True on success, False on error
- */
- function expunge($mailbox, $messages=NULL)
- {
- if (!$this->select($mailbox)) {
- return false;
- }
- if (!$this->data['READ-WRITE']) {
- $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
- return false;
- }
- // Clear internal status cache
- unset($this->data['STATUS:'.$mailbox]);
- if ($messages)
- $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
- else
- $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
- if ($result == self::ERROR_OK) {
- $this->selected = null; // state has changed, need to reselect
- return true;
- }
- return false;
- }
- /**
- * Executes CLOSE command
- *
- * @return boolean True on success, False on error
- * @since 0.5
- */
- function close()
- {
- $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
- if ($result == self::ERROR_OK) {
- $this->selected = null;
- return true;
- }
- return false;
- }
- /**
- * Executes SUBSCRIBE command
- *
- * @param string $mailbox Mailbox name
- *
- * @return boolean True on success, False on error
- */
- function subscribe($mailbox)
- {
- $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
- self::COMMAND_NORESPONSE);
- return ($result == self::ERROR_OK);
- }
- /**
- * Executes UNSUBSCRIBE command
- *
- * @param string $mailbox Mailbox name
- *
- * @return boolean True on success, False on error
- */
- function unsubscribe($mailbox)
- {
- $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
- self::COMMAND_NORESPONSE);
- return ($result == self::ERROR_OK);
- }
- /**
- * Executes DELETE command
- *
- * @param string $mailbox Mailbox name
- *
- * @return boolean True on success, False on error
- */
- function deleteFolder($mailbox)
- {
- $result = $this->execute('DELETE', array($this->escape($mailbox)),
- self::COMMAND_NORESPONSE);
- return ($result == self::ERROR_OK);
- }
- /**
- * Removes all messages in a folder
- *
- * @param string $mailbox Mailbox name
- *
- * @return boolean True on success, False on error
- */
- function clearFolder($mailbox)
- {
- $num_in_trash = $this->countMessages($mailbox);
- if ($num_in_trash > 0) {
- $res = $this->delete($mailbox, '1:*');
- }
- if ($res) {
- if ($this->selected === $mailbox)
- $res = $this->close();
- else
- $res = $this->expunge($mailbox);
- }
- return $res;
- }
- /**
- * Returns count of all messages in a folder
- *
- * @param string $mailbox Mailbox name
- *
- * @return int Number of messages, False on error
- */
- function countMessages($mailbox, $refresh = false)
- {
- if ($refresh) {
- $this->selected = null;
- }
- if ($this->selected === $mailbox) {
- 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 with \Recent flag in a folder
- *
- * @param string $mailbox Mailbox name
- *
- * @return int Number of messages, False on error
- */
- function countRecent($mailbox)
- {
- if (!strlen($mailbox)) {
- $mailbox = 'INBOX';
- }
- $this->select($mailbox);
- if ($this->selected === $mailbox) {
- return $this->data['RECENT'];
- }
- 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
- */
- 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;
- }
- /**
- * Executes ID command (RFC2971)
- *
- * @param array $items Client identification information key/value hash
- *
- * @return array Server identification information key/value hash
- * @since 0.6
- */
- function id($items=array())
- {
- if (is_array($items) && !empty($items)) {
- foreach ($items as $key => $value) {
- $args[] = $this->escape($key, true);
- $args[] = $this->escape($value, true);
- }
- }
- list($code, $response) = $this->execute('ID', array(
- !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
- ));
- if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
- $response = substr($response, 5); // remove prefix "* ID "
- $items = $this->tokenizeResponse($response, 1);
- $result = null;
- for ($i=0, $len=count($items); $i<$len; $i += 2) {
- $result[$items[$i]] = $items[$i+1];
- }
- return $result;
- }
- return false;
- }
- /**
- * Executes ENABLE command (RFC5161)
- *
- * @param mixed $extension Extension name to enable (or array of names)
- *
- * @return array|bool List of enabled extensions, False on error
- * @since 0.6
- */
- function enable($extension)
- {
- if (empty($extension))
- return false;
- if (!$this->hasCapability('ENABLE'))
- return false;
- if (!is_array($extension))
- $extension = array($extension);
- list($code, $response) = $this->execute('ENABLE', $extension);
- if ($code == self::ERROR_OK && preg_match('/\* ENABLED /i', $response)) {
- $response = substr($response, 10); // remove prefix "* ENABLED "
- $result = (array) $this->tokenizeResponse($response);
- return $result;
- }
- return false;
- }
- function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
- {
- $field = strtoupper($field);
- if ($field == 'INTERNALDATE') {
- $field = 'ARRIVAL';
- }
- $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
- 'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
- if (!$fields[$field]) {
- return false;
- }
- if (!$this->select($mailbox)) {
- return false;
- }
- // message IDs
- if (!empty($add))
- $add = $this->compressMessageSet($add);
- list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
- array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
- if ($code == self::ERROR_OK) {
- // remove prefix and unilateral untagged server responses
- $response = substr($response, stripos($response, '* SORT') + 7);
- if ($pos = strpos($response, '*')) {
- $response = substr($response, 0, $pos);
- }
- return preg_split('/[\s\r\n]+/', $response, -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($message_set)))
- return false;
- } else {
- list($from_idx, $to_idx) = explode(':', $message_set);
- if (empty($message_set) ||
- (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
- return false;
- }
- }
- $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
- $fields_a['DATE'] = 1;
- $fields_a['INTERNALDATE'] = 4;
- $fields_a['ARRIVAL'] = 4;
- $fields_a['FROM'] = 1;
- $fields_a['REPLY-TO'] = 1;
- $fields_a['SENDER'] = 1;
- $fields_a['TO'] = 1;
- $fields_a['CC'] = 1;
- $fields_a['SUBJECT'] = 1;
- $fields_a['UID'] = 2;
- $fields_a['SIZE'] = 2;
- $fields_a['SEEN'] = 3;
- $fields_a['RECENT'] = 3;
- $fields_a['DELETED'] = 3;
- if (!($mode = $fields_a[$index_field])) {
- return false;
- }
- /* Do "SELECT" command */
- if (!$this->select($mailbox)) {
- return false;
- }
- // build FETCH command string
- $key = $this->nextTag();
- $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
- $deleted = $skip_deleted ? ' FLAGS' : '';
- if ($mode == 1 && $index_field == 'DATE')
- $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
- else if ($mode == 1)
- $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
- else if ($mode == 2) {
- if ($index_field == 'SIZE')
- $request = " $cmd $message_set (RFC822.SIZE$deleted)";
- else
- $request = " $cmd $message_set ($index_field$deleted)";
- } else if ($mode == 3)
- $request = " $cmd $message_set (FLAGS)";
- else // 4
- $request = " $cmd $message_set (INTERNALDATE$deleted)";
- $request = $key . $request;
- if (!$this->putLine($request)) {
- $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
- return false;
- }
- $result = array();
- do {
- $line = rtrim($this->readLine(200));
- $line = $this->multLine($line);
- if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
- $id = $m[1];
- $flags = NULL;
- if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
- $flags = explode(' ', strtoupper($matches[1]));
- if (in_array('\\DELETED', $flags)) {
- $deleted[$id] = $id;
- continue;
- }
- }
- if ($mode == 1 && $index_field == 'DATE') {
- if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
- $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
- $value = trim($value);
- $result[$id] = $this->strToTime($value);
- }
- // non-existent/empty Date: header, use INTERNALDATE
- if (empty($result[$id])) {
- if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
- $result[$id] = $this->strToTime($matches[1]);
- else
- $result[$id] = 0;
- }
- } else if ($mode == 1) {
- if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
- $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
- $result[$id] = trim($value);
- } else {
- $result[$id] = '';
- }
- } else if ($mode == 2) {
- if (preg_match('/(UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
- $result[$id] = trim($matches[2]);
- } else {
- $result[$id] = 0;
- }
- } else if ($mode == 3) {
- if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
- $flags = explode(' ', $matches[1]);
- }
- $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
- } else if ($mode == 4) {
- if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
- $result[$id] = $this->strToTime($matches[1]);
- } else {
- $result[$id] = 0;
- }
- }
- }
- } while (!$this->startsWith($line, $key, true, true));
- return $result;
- }
- static function compressMessageSet($messages, $force=false)
- {
- // given a comma delimited list of independent mid's,
- // compresses by grouping sequences together
- 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 compressed
- if (strpos($messages, ':') !== false) {
- return $messages;
- }
- // separate, then sort
- $messages = explode(',', $messages);
- }
- sort($messages);
- $result = array();
- $start = $prev = $messages[0];
- foreach ($messages as $id) {
- $incr = $id - $prev;
- if ($incr > 1) { // found a gap
- if ($start == $prev) {
- $result[] = $prev; // push single id
- } else {
- $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
- }
- $start = $id; // start of new sequence
- }
- $prev = $id;
- }
- // handle the last sequence/id
- if ($start == $prev) {
- $result[] = $prev;
- } else {
- $result[] = $start.':'.$prev;
- }
- // return as comma separated string
- return implode(',', $result);
- }
- static function uncompressMessageSet($messages)
- {
- $result = array();
- $messages = explode(',', $messages);
- foreach ($messages as $part) {
- $items = explode(':', $part);
- $max = max($items[0], $items[1]);
- for ($x=$items[0]; $x<=$max; $x++) {
- $result[] = $x;
- }
- }
- return $result;
- }
- /**
- * Returns message sequence identifier
- *
- * @param string $mailbox Mailbox name
- * @param int $uid Message unique identifier (UID)
- *
- * @return int Message sequence identifier
- */
- 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
- */
- function ID2UID($mailbox, $id)
- {
- if (empty($id) || $id < 0) {
- return null;
- }
- if (!$this->select($mailbox)) {
- }
- // RFC 5957: SORT=DISPLAY
- if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
- $field = 'DISPLAY' . $field;
- 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)
- {
- if (empty($message_set))
- $message_set = '1:*';
- return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
- }
- /**
- * FETCH command (RFC3501)
- *
- * @param string $mailbox Mailbox name
- * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
- * @param bool $is_uid True if $message_set contains UIDs
- * @param array $query_items FETCH command data items
- * @param string $mod_seq Modification sequence for CHANGEDSINCE (RFC4551) query
- * @param bool $vanished Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
- *
- * @return array List of rcube_mail_header elements, False on error
- * @since 0.6
- */
- function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
- $mod_seq = null, $vanished = false)
- {
- if (!$this->select($mailbox)) {
- return false;
- }
- $message_set = $this->compressMessageSet($message_set);
- $result = array();
- $key = $this->nextTag();
- $request = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
- $request .= "(" . implode(' ', $query_items) . ")";
- if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
- $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
- }
- if (!$this->putLine($request)) {
- $this->setError(self::ERROR_COMMAND…
Large files files are truncated, but you can click here to view the full file