/mail/program/include/rcube_imap_generic.php
PHP | 3747 lines | 2488 code | 477 blank | 782 comment | 676 complexity | 14fde4e9009387ed7dd32dc89533a2bf MD5 | raw file
Possible License(s): GPL-3.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 General Public License version 3 or |
- | any later version with exceptions for skins & plugins. |
- | See the README file for a full license statement. |
- | |
- | 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$
- */
- /**
- * 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();
- // map header to rcube_mail_header object property
- private $obj_headers = array(
- 'date' => 'date',
- 'from' => 'from',
- 'to' => 'to',
- 'subject' => 'subject',
- 'reply-to' => 'replyto',
- 'cc' => 'cc',
- 'bcc' => 'bcc',
- 'content-transfer-encoding' => 'encoding',
- 'in-reply-to' => 'in_reply_to',
- 'content-type' => 'ctype',
- 'references' => 'references',
- 'return-receipt-to' => 'mdn_to',
- 'disposition-notification-to' => 'mdn_to',
- 'x-confirm-reading-to' => 'mdn_to',
- 'message-id' => 'messageID',
- 'x-priority' => 'priority',
- );
- /**
- * Returns header value
- */
- public function get($name, $decode = true)
- {
- $name = strtolower($name);
- if (isset($this->obj_headers[$name])) {
- $value = $this->{$this->obj_headers[$name]};
- }
- else {
- $value = $this->others[$name];
- }
- return $decode ? rcube_mime::decode_header($value, $this->charset) : $value;
- }
- /**
- * Sets header value
- */
- public function set($name, $value)
- {
- $name = strtolower($name);
- if (isset($this->obj_headers[$name])) {
- $this->{$this->obj_headers[$name]} = $value;
- }
- else {
- $this->others[$name] = $value;
- }
- }
- }
- // For backward compatibility with cached messages (#1486602)
- class iilBasicHeader extends rcube_mail_header
- {
- }
- // Support objects created in git-master (0.9)
- class rcube_message_header 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
- *
- * @return int|bool 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;
- }
- /**
- * Reads line from the connection stream
- *
- * @param int $size Buffer size
- *
- * @return string Line of text response
- */
- 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;
- }
- /**
- * Reads more data from the connection stream when provided
- * data contain string literal
- *
- * @param string $line Response text
- * @param bool $escape Enables escaping
- *
- * @return string Line of text response
- */
- 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;
- }
- /**
- * Reads specified number of bytes from the connection stream
- *
- * @param int $bytes Number of bytes to get
- *
- * @return string Response text
- */
- 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;
- }
- /**
- * Reads complete response to the IMAP command
- *
- * @param array $untagged Will be filled with untagged response lines
- *
- * @return string Response text
- */
- 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;
- }
- /**
- * Response parser.
- *
- * @param string $string Response text
- * @param string $err_prefix Error message prefix
- *
- * @return int Response status
- */
- 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;
- }
- /**
- * Checks connection stream state.
- *
- * @return bool True if connection is closed
- */
- 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;
- }
- /**
- * Closes connection stream.
- */
- private function closeSocket()
- {
- @fclose($this->fp);
- $this->fp = null;
- }
- /**
- * Error code/message setter.
- */
- function setError($code, $msg='')
- {
- $this->errornum = $code;
- $this->error = $msg;
- }
- /**
- * Checks response status.
- * Checks if command response line starts with specified prefix (or * BYE/BAD)
- *
- * @param string $string Response text
- * @param string $match Prefix to match with (case-sensitive)
- * @param bool $error Enables BYE/BAD checking
- * @param bool $nonempty Enables empty response checking
- *
- * @return bool True any check is true or connection is closed.
- */
- function startsWith($string, $match, $error=false, $nonempty=false)
- {
- if (!$this->fp) {
- return true;
- }
- if (strncmp($string, $match, strlen($match)) == 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;
- $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;
- $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;
- }
- /**
- * Detects hierarchy 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'];
- }
- /**
- * Connects to IMAP server and authenticates.
- *
- * @param string $host Server hostname or IP
- * @param string $user User name
- * @param string $password Password
- * @param array $options Connection and class options
- *
- * @return bool True on success, False on failure
- */
- 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;
- }
- /**
- * Checks connection status
- *
- * @return bool True if connection is active and user is logged in, False otherwise.
- */
- function connected()
- {
- return ($this->fp && $this->logged) ? true : false;
- }
- /**
- * Closes connection with logout.
- */
- 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;
- }
- /**
- * Folder subscription (SUBSCRIBE)
- *
- * @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);
- }
- /**
- * Folder unsubscription (UNSUBSCRIBE)
- *
- * @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);
- }
- /**
- * Folder creation (CREATE)
- *
- * @param string $mailbox Mailbox name
- *
- * @return bool True on success, False on error
- */
- function createFolder($mailbox)
- {
- $result = $this->execute('CREATE', array($this->escape($mailbox)),
- self::COMMAND_NORESPONSE);
- return ($result == self::ERROR_OK);
- }
- /**
- * Folder renaming (RENAME)
- *
- * @param string $mailbox Mailbox name
- *
- * @return bool True on success, False on error
- */
- function renameFolder($from, $to)
- {
- $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
- 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->flag($mailbox, '1:*', 'DELETED');
- }
- if ($res) {
- if ($this->selected === $mailbox)
- $res = $this->close();
- else
- $res = $this->expunge($mailbox);
- }
- return $res;
- }
- /**
- * 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.
- */
- function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
- {
- return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
- }
- /**
- * 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.
- */
- function listSubscribed($ref, $mailbox, $status_opts=array())
- {
- return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
- }
- /**
- * 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.
- */
- private function _listMailboxes($ref, $mailbox, $subscribed=false,
- $status_opts=array(), $select_opts=array())
- {
- if (!strlen($mailbox)) {
- $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();
- $last = 0;
- $pos = 0;
- $response .= "\r\n";
- while ($pos = strpos($response, "\r\n", $pos+1)) {
- // literal string, not real end-of-command-line
- if ($response[$pos-1] == '}') {
- continue;
- }
- $line = substr($response, $last, $pos - $last);
- $last = $pos + 2;
- if (!preg_match('/^\* (LIST|LSUB|STATUS) /i', $line, $m)) {
- continue;
- }
- $cmd = strtoupper($m[1]);
- $line = substr($line, strlen($m[0]));
- // * LIST (<options>) <delimiter> <mailbox>
- if ($cmd == 'LIST' || $cmd == 'LSUB') {
- list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
- // Add to result array
- if (!$lstatus) {
- $folders[] = $mailbox;
- }
- else {
- $folders[$mailbox] = array();
- }
- // store LSUB options only if not empty, this way
- // we can detect a situation when LIST doesn't return specified folder
- if (!empty($opts) || $cmd == 'LIST') {
- // Add to options array
- if (empty($this->data['LIST'][$mailbox]))
- $this->data['LIST'][$mailbox] = $opts;
- else if (!empty($opts))
- $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($line, 2);
- for ($i=0, $len=count($status); $i<$len; $i += 2) {
- list($name, $value) = $this->tokenizeResponse($status, 2);
- $folders[$mailbox][$name] = $value;
- }
- }
- }
- return $folders;
- }
- return false;
- }
- /**
- * 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 (!$index->is_error()) {
- return $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;
- }
- /**
- * Executes SORT command
- *
- * @param string $mailbox Mailbox name
- * @param string $field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
- * @param string $add Searching criteria
- * @param bool $return_uid Enables UID SORT usage
- * @param string $encoding Character set
- *
- * @return rcube_result_index Response data
- */
- function sort($mailbox, $field, $add='', $return_uid=false, $encoding = 'US-ASCII')
- {
- require_once dirname(__FILE__) . '/rcube_result_index.php';
- $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 new rcube_result_index($mailbox);
- }
- if (!$this->select($mailbox)) {
- return new rcube_result_index($mailbox);
- }
- // RFC 5957: SORT=DISPLAY
- if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
- $field = 'DISPLAY' . $field;
- }
- // message IDs
- if (!empty($add))
- $add = $this->compressMessageSet($add);
- list($code, $response) = $this->execute($return_uid ? 'UID SORT' : 'SORT',
- array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$ad…
Large files files are truncated, but you can click here to view the full file