/program/lib/Roundcube/rcube_imap_generic.php
PHP | 3908 lines | 2872 code | 408 blank | 628 comment | 601 complexity | 3741b39582fdb8b3b833cad995167338 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
- /**
- +-----------------------------------------------------------------------+
- | This file is part of the Roundcube Webmail client |
- | Copyright (C) 2005-2012, The Roundcube Dev Team |
- | Copyright (C) 2011-2012, 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> |
- +-----------------------------------------------------------------------+
- */
- /**
- * PHP based wrapper class to connect to an IMAP server
- *
- * @package Framework
- * @subpackage Storage
- */
- 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',
- '*' => '\\*',
- );
- public static $mupdate;
- protected $fp;
- protected $host;
- protected $logged = false;
- protected $capability = array();
- protected $capability_readed = false;
- protected $prefs;
- protected $cmd_tag;
- protected $cmd_num = 0;
- protected $resourceid;
- protected $_debug = false;
- protected $_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;
- const COMMAND_ANONYMIZED = 8;
- const DEBUG_LINE_LENGTH = 4098; // 4KB + 2B for \r\n
- /**
- * 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 bool $anonymized Don't write the given data to log but a placeholder
- *
- * @param int Number of bytes sent, False on error
- */
- function putLine($string, $endln=true, $anonymized=false)
- {
- if (!$this->fp)
- return false;
- if ($this->_debug) {
- // anonymize the sent command for logging
- $cut = $endln ? 2 : 0;
- if ($anonymized && preg_match('/^(A\d+ (?:[A-Z]+ )+)(.+)/', $string, $m)) {
- $log = $m[1] . sprintf('****** [%d]', strlen($m[2]) - $cut);
- }
- else if ($anonymized) {
- $log = sprintf('****** [%d]', strlen($string) - $cut);
- }
- else {
- $log = rtrim($string);
- }
- $this->debug('C: ' . $log);
- }
- $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 bool $anonymized Don't write the given data to log but a placeholder
- *
- * @return int|bool Number of bytes sent, False on error
- */
- function putLineC($string, $endln=true, $anonymized=false)
- {
- 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, $anonymized);
- 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, $anonymized);
- 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];
- }
- // parse response for [COPYUID 1204196876 3456:3457 123:124]
- else if (preg_match("/^\[COPYUID [0-9]+ ([0-9,:]+) ([0-9,:]+)\]/i", $str, $m)) {
- $this->data['COPYUID'] = array($m[1], $m[2]);
- }
- }
- $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
- */
- protected 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.
- */
- protected 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;
- }
- protected 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, true, true);
- }
- 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, true, true);
- $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 | self::COMMAND_ANONYMIZED);
- }
- 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, true, true);
- $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 | self::COMMAND_ANONYMIZED);
- // 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)
- {
- // configure
- $this->set_prefs($options);
- $this->host = $host;
- $this->user = $user;
- $this->logged = false;
- $this->selected = null;
- // 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;
- }
- // Connect
- if (!$this->_connect($host)) {
- return false;
- }
- // Send ID info
- if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
- $this->id($this->prefs['ident']);
- }
- $auth_method = $this->prefs['auth_type'];
- $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;
- }
- /**
- * Connects to IMAP server.
- *
- * @param string $host Server hostname or IP
- *
- * @return bool True on success, False on failure
- */
- protected function _connect($host)
- {
- // initialize connection
- $this->error = '';
- $this->errornum = self::ERROR_OK;
- 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'] = max(0, intval(ini_get('default_socket_timeout')));
- }
- if (!empty($this->prefs['socket_options'])) {
- $context = stream_context_create($this->prefs['socket_options']);
- $this->fp = stream_socket_client($host . ':' . $this->prefs['port'], $errno, $errstr,
- $this->prefs['timeout'], STREAM_CLIENT_CONNECT, $context);
- }
- else {
- $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 ?: "Unknown reason"));
- 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')) {
- $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();
- }
- return true;
- }
- /**
- * Initializes environment
- */
- protected function set_prefs($prefs)
- {
- // set preferences
- if (is_array($prefs)) {
- $this->prefs = $prefs;
- }
- // set auth method
- if (!empty($this->prefs['auth_type'])) {
- $this->prefs['auth_type'] = strtoupper($this->prefs['auth_type']);
- }
- else {
- $this->prefs['auth_type'] = 'CHECK';
- }
- // disabled capabilities
- if (!empty($this->prefs['disabled_caps'])) {
- $this->prefs['disabled_caps'] = array_map('strtoupper', (array)$this->prefs['disabled_caps']);
- }
- // additional message flags
- if (!empty($this->prefs['message_flags'])) {
- $this->flags = array_merge($this->flags, $this->prefs['message_flags']);
- unset($this->prefs['message_flags']);
- }
- }
- /**
- * 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->logged && $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|array $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");
- return false;
- }
- // Clear internal status cache
- unset($this->data['STATUS:'.$mailbox]);
- if (!empty($messages) && $messages != '*' && $this->hasCapability('UIDPLUS')) {
- $messages = self::compressMessageSet($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
- * @param array $types Optional folder types (RFC 6154)
- *
- * @return bool True on success, False on error
- */
- function createFolder($mailbox, $types = null)
- {
- $args = array($this->escape($mailbox));
- // RFC 6154: CREATE-SPECIAL-USE
- if (!empty($types) && $this->getCapability('CREATE-SPECIAL-USE')) {
- $args[] = '(USE (' . implode(' ', $types) . '))';
- }
- $result = $this->execute('CREATE', $args, 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 $return_opts (see self::_listMailboxes)
- * @param array $select_opts (see self::_listMailboxes)
- *
- * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
- * is requested, False on error.
- */
- function listMailboxes($ref, $mailbox, $return_opts=array(), $select_opts=array())
- {
- return $this->_listMailboxes($ref, $mailbox, false, $return_opts, $select_opts);
- }
- /**
- * Returns list of subscribed mailboxes
- *
- * @param string $ref Reference name
- * @param string $mailbox Mailbox name
- * @param array $return_opts (see self::_listMailboxes)
- *
- * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
- * is requested, False on error.
- */
- function listSubscribed($ref, $mailbox, $return_opts=array())
- {
- return $this->_listMailboxes($ref, $mailbox, true, $return_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 $return_opts List of RETURN options (RFC5819: LIST-STATUS, RFC5258: LIST-EXTENDED)
- * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN,
- * MYRIGHTS, SUBSCRIBED, CHILDREN
- * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
- * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE,
- * SPECIAL-USE (RFC6154)
- *
- * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
- * is requested, False on error.
- */
- protected function _listMailboxes($ref, $mailbox, $subscribed=false,
- $return_opts=array(), $select_opts=array())
- {
- if (!strlen($mailbox)) {
- $mailbox = '*';
- }
- $args = array();
- $rets = 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($return_opts) && $this->getCapability('LIST-EXTENDED')) {
- $ext_opts = array('SUBSCRIBED', 'CHILDREN');
- $rets = array_intersect($return_opts, $ext_opts);
- $return_opts = array_diff($return_opts, $rets);
- }
- if (!empty($return_opts) && $this->getCapability('LIST-STATUS')) {
- $lstatus = true;
- $status_opts = array('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN');
- $opts = array_diff($return_opts, $status_opts);
- $status_opts = array_diff($return_opts, $opts);
- if (!empty($status_opts)) {
- $rets[] = 'STATUS (' . implode(' ', $status_opts) . ')';
- }
- if (!empty($opts)) {
- $rets = array_merge($rets, $opts);
- }
- }
- if (!empty($rets)) {
- $args[] = 'RETURN (' . implode(' ', $rets) . ')';
- }
- 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|MYRIGHTS) /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);
- // Remove redundant separator at the end of folder name, UW-IMAP bug? (#1488879)
- if ($delim) {
- $mailbox = rtrim($mailbox, $delim);
- }
- // Add to result array
- if (!$lstatus) {
- $folders[] = $mailbox;
- }
- else {
- $folders[$mailbox] = array();
- }
- // store folder options
- if ($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));
- }
- }
- else if ($lstatus) {
- // * STATUS <mailbox> (<result>)
- 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;
- }
- }
- // * MYRIGHTS <mailbox> <acl>
- else if ($cmd == 'MYRIGHTS') {
- list($mailbox, $acl) = $this->tokenizeResponse($line, 2);
- $folders[$mailbox]['MYRIGHTS'] = $acl;
- }
- }
- }
- 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);
- }
- if (!empty(…
Large files files are truncated, but you can click here to view the full file