4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap_generic.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Provide alternative IMAP library that doesn't rely on the standard |
13 | C-Client based version. This allows to function regardless |
14 | of whether or not the PHP build it's running on has IMAP |
15 | functionality built-in. |
17 | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
19 +-----------------------------------------------------------------------+
20 | Author: Aleksander Machniak <alec@alec.pl> |
21 | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
22 +-----------------------------------------------------------------------+
24 $Id: rcube_imap_generic.php 5213 2011-09-13 08:09:50Z alec $
30 * Struct representing an e-mail message header
33 * @author Aleksander Machniak <alec@alec.pl>
35 class rcube_mail_header
53 public $body_structure;
58 public $mdn_sent = false;
60 public $deleted = false;
61 public $answered = false;
62 public $forwarded = false;
63 public $flagged = false;
64 public $has_children = false;
66 public $unread_children = 0;
67 public $others = array();
70 // For backward compatibility with cached messages (#1486602)
71 class iilBasicHeader extends rcube_mail_header
76 * PHP based wrapper class to connect to an IMAP server
79 * @author Aleksander Machniak <alec@alec.pl>
81 class rcube_imap_generic
87 public $data = array();
88 public $flags = array(
90 'DELETED' => '\\Deleted',
91 'ANSWERED' => '\\Answered',
93 'FLAGGED' => '\\Flagged',
94 'FORWARDED' => '$Forwarded',
95 'MDNSENT' => '$MDNSent',
102 private $logged = false;
103 private $capability = array();
104 private $capability_readed = false;
107 private $cmd_num = 0;
109 private $_debug = false;
110 private $_debug_handler = false;
114 const ERROR_BAD = -2;
115 const ERROR_BYE = -3;
116 const ERROR_UNKNOWN = -4;
117 const ERROR_COMMAND = -5;
118 const ERROR_READONLY = -6;
120 const COMMAND_NORESPONSE = 1;
121 const COMMAND_CAPABILITY = 2;
122 const COMMAND_LASTLINE = 4;
127 function __construct()
132 * Send simple (one line) command to the connection stream
134 * @param string $string Command string
135 * @param bool $endln True if CRLF need to be added at the end of command
137 * @param int Number of bytes sent, False on error
139 function putLine($string, $endln=true)
145 $this->debug('C: '. rtrim($string));
148 $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
150 if ($res === false) {
159 * Send command to the connection stream with Command Continuation
160 * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
162 * @param string $string Command string
163 * @param bool $endln True if CRLF need to be added at the end of command
165 * @param int Number of bytes sent, False on error
167 function putLineC($string, $endln=true)
177 if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
178 for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
179 if (preg_match('/^\{([0-9]+)\}\r\n$/', $parts[$i+1], $matches)) {
181 if ($this->prefs['literal+']) {
182 $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
185 $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
186 if ($bytes === false)
190 // don't wait if server supports LITERAL+ capability
191 if (!$this->prefs['literal+']) {
192 $line = $this->readLine(1000);
193 // handle error in command
200 $bytes = $this->putLine($parts[$i], false);
201 if ($bytes === false)
210 function readLine($size=1024)
220 return $line ? $line : NULL;
223 $buffer = fgets($this->fp, $size);
225 if ($buffer === false) {
226 $this->closeSocket();
230 $this->debug('S: '. rtrim($buffer));
233 } while (substr($buffer, -1) != "\n");
238 function multLine($line, $escape=false)
240 $line = rtrim($line);
241 if (preg_match('/\{[0-9]+\}$/', $line)) {
244 preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
246 while (strlen($out) < $bytes) {
247 $line = $this->readBytes($bytes);
253 $line = $a[1][0] . ($escape ? $this->escape($out) : $out);
259 function readBytes($bytes)
263 while ($len < $bytes && !$this->eof())
265 $d = fread($this->fp, $bytes-$len);
267 $this->debug('S: '. $d);
270 $data_len = strlen($data);
271 if ($len == $data_len) {
272 break; // nothing was read -> exit to avoid apache lockups
280 function readReply(&$untagged=null)
283 $line = trim($this->readLine(1024));
284 // store untagged response lines
287 } while ($line[0] == '*');
290 $untagged = join("\n", $untagged);
295 function parseResult($string, $err_prefix='')
297 if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
298 $res = strtoupper($matches[1]);
299 $str = trim($matches[2]);
302 $this->errornum = self::ERROR_OK;
303 } else if ($res == 'NO') {
304 $this->errornum = self::ERROR_NO;
305 } else if ($res == 'BAD') {
306 $this->errornum = self::ERROR_BAD;
307 } else if ($res == 'BYE') {
308 $this->closeSocket();
309 $this->errornum = self::ERROR_BYE;
314 // get response string and code (RFC5530)
315 if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
316 $this->resultcode = strtoupper($m[1]);
317 $str = trim(substr($str, strlen($m[1]) + 2));
320 $this->resultcode = null;
322 $this->result = $str;
324 if ($this->errornum != self::ERROR_OK) {
325 $this->error = $err_prefix ? $err_prefix.$str : $str;
329 return $this->errornum;
331 return self::ERROR_UNKNOWN;
334 private function eof()
336 if (!is_resource($this->fp)) {
340 // If a connection opened by fsockopen() wasn't closed
341 // by the server, feof() will hang.
342 $start = microtime(true);
344 if (feof($this->fp) ||
345 ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
347 $this->closeSocket();
354 private function closeSocket()
360 function setError($code, $msg='')
362 $this->errornum = $code;
366 // check if $string starts with $match (or * BYE/BAD)
367 function startsWith($string, $match, $error=false, $nonempty=false)
369 $len = strlen($match);
376 if (strncmp($string, $match, $len) == 0) {
379 if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
380 if (strtoupper($m[1]) == 'BYE') {
381 $this->closeSocket();
385 if ($nonempty && !strlen($string)) {
391 private function hasCapability($name)
393 if (empty($this->capability) || $name == '') {
397 if (in_array($name, $this->capability)) {
400 else if (strpos($name, '=')) {
405 foreach ($this->capability as $cap) {
406 $entry = explode('=', $cap);
407 if ($entry[0] == $name) {
408 $result[] = $entry[1];
412 return !empty($result) ? $result : false;
416 * Capabilities checker
418 * @param string $name Capability name
420 * @return mixed Capability values array for key=value pairs, true/false for others
422 function getCapability($name)
424 $result = $this->hasCapability($name);
426 if (!empty($result)) {
429 else if ($this->capability_readed) {
433 // get capabilities (only once) because initial
434 // optional CAPABILITY response may differ
435 $result = $this->execute('CAPABILITY');
437 if ($result[0] == self::ERROR_OK) {
438 $this->parseCapability($result[1]);
441 $this->capability_readed = true;
443 return $this->hasCapability($name);
446 function clearCapability()
448 $this->capability = array();
449 $this->capability_readed = false;
453 * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
455 * @param string $user
456 * @param string $pass
457 * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
459 * @return resource Connection resourse on success, error code on error
461 function authenticate($user, $pass, $type='PLAIN')
463 if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
464 if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
465 $this->setError(self::ERROR_BYE,
466 "The Auth_SASL package is required for DIGEST-MD5 authentication");
467 return self::ERROR_BAD;
470 $this->putLine($this->nextTag() . " AUTHENTICATE $type");
471 $line = trim($this->readReply());
473 if ($line[0] == '+') {
474 $challenge = substr($line, 2);
477 return $this->parseResult($line);
480 if ($type == 'CRAM-MD5') {
485 // initialize ipad, opad
486 for ($i=0; $i<64; $i++) {
491 // pad $pass so it's 64 bytes
492 $padLen = 64 - strlen($pass);
493 for ($i=0; $i<$padLen; $i++) {
498 $hash = md5($this->_xor($pass, $opad) . pack("H*",
499 md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
500 $reply = base64_encode($user . ' ' . $hash);
503 $this->putLine($reply);
506 // RFC2831: DIGEST-MD5
507 // proxy authorization
508 if (!empty($this->prefs['auth_cid'])) {
509 $authc = $this->prefs['auth_cid'];
510 $pass = $this->prefs['auth_pw'];
515 $auth_sasl = Auth_SASL::factory('digestmd5');
516 $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
517 base64_decode($challenge), $this->host, 'imap', $user));
520 $this->putLine($reply);
521 $line = trim($this->readReply());
523 if ($line[0] == '+') {
524 $challenge = substr($line, 2);
527 return $this->parseResult($line);
531 $challenge = base64_decode($challenge);
532 if (strpos($challenge, 'rspauth=') === false) {
533 $this->setError(self::ERROR_BAD,
534 "Unexpected response from server to DIGEST-MD5 response");
535 return self::ERROR_BAD;
541 $line = $this->readReply();
542 $result = $this->parseResult($line);
545 // proxy authorization
546 if (!empty($this->prefs['auth_cid'])) {
547 $authc = $this->prefs['auth_cid'];
548 $pass = $this->prefs['auth_pw'];
554 $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
556 // RFC 4959 (SASL-IR): save one round trip
557 if ($this->getCapability('SASL-IR')) {
558 list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
559 self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY);
562 $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
563 $line = trim($this->readReply());
565 if ($line[0] != '+') {
566 return $this->parseResult($line);
569 // send result, get reply and process it
570 $this->putLine($reply);
571 $line = $this->readReply();
572 $result = $this->parseResult($line);
576 if ($result == self::ERROR_OK) {
577 // optional CAPABILITY response
578 if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
579 $this->parseCapability($matches[1], true);
584 $this->setError($result, "AUTHENTICATE $type: $line");
591 * LOGIN Authentication
593 * @param string $user
594 * @param string $pass
596 * @return resource Connection resourse on success, error code on error
598 function login($user, $password)
600 list($code, $response) = $this->execute('LOGIN', array(
601 $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
603 // re-set capabilities list if untagged CAPABILITY response provided
604 if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
605 $this->parseCapability($matches[1], true);
608 if ($code == self::ERROR_OK) {
618 * @return string The delimiter
620 function getHierarchyDelimiter()
622 if ($this->prefs['delimiter']) {
623 return $this->prefs['delimiter'];
626 // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
627 list($code, $response) = $this->execute('LIST',
628 array($this->escape(''), $this->escape('')));
630 if ($code == self::ERROR_OK) {
631 $args = $this->tokenizeResponse($response, 4);
632 $delimiter = $args[3];
634 if (strlen($delimiter) > 0) {
635 return ($this->prefs['delimiter'] = $delimiter);
643 * NAMESPACE handler (RFC 2342)
645 * @return array Namespace data hash (personal, other, shared)
647 function getNamespace()
649 if (array_key_exists('namespace', $this->prefs)) {
650 return $this->prefs['namespace'];
653 if (!$this->getCapability('NAMESPACE')) {
654 return self::ERROR_BAD;
657 list($code, $response) = $this->execute('NAMESPACE');
659 if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
660 $data = $this->tokenizeResponse(substr($response, 11));
663 if (!is_array($data)) {
667 $this->prefs['namespace'] = array(
668 'personal' => $data[0],
670 'shared' => $data[2],
673 return $this->prefs['namespace'];
676 function connect($host, $user, $password, $options=null)
679 if (is_array($options)) {
680 $this->prefs = $options;
683 if (!empty($this->prefs['auth_method'])) {
684 $auth_method = strtoupper($this->prefs['auth_method']);
686 $auth_method = 'CHECK';
691 // initialize connection
693 $this->errornum = self::ERROR_OK;
694 $this->selected = '';
697 $this->logged = false;
701 $this->setError(self::ERROR_BAD, "Empty host");
705 $this->setError(self::ERROR_NO, "Empty user");
708 if (empty($password)) {
709 $this->setError(self::ERROR_NO, "Empty password");
713 if (!$this->prefs['port']) {
714 $this->prefs['port'] = 143;
717 if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
718 $host = $this->prefs['ssl_mode'] . '://' . $host;
721 if ($this->prefs['timeout'] <= 0) {
722 $this->prefs['timeout'] = ini_get('default_socket_timeout');
726 $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
729 $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
733 if ($this->prefs['timeout'] > 0)
734 stream_set_timeout($this->fp, $this->prefs['timeout']);
736 $line = trim(fgets($this->fp, 8192));
739 // set connection identifier for debug output
740 preg_match('/#([0-9]+)/', (string)$this->fp, $m);
741 $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));
744 $this->debug('S: '. $line);
747 // Connected to wrong port or connection error?
748 if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
750 $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
752 $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
754 $this->setError(self::ERROR_BAD, $error);
755 $this->closeConnection();
759 // RFC3501 [7.1] optional CAPABILITY response
760 if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
761 $this->parseCapability($matches[1], true);
765 if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
766 if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
767 $res = $this->execute('STARTTLS');
769 if ($res[0] != self::ERROR_OK) {
770 $this->closeConnection();
774 if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
775 $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
776 $this->closeConnection();
780 // Now we're secure, capabilities need to be reread
781 $this->clearCapability();
786 if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
787 $this->id($this->prefs['ident']);
790 $auth_methods = array();
793 // check for supported auth methods
794 if ($auth_method == 'CHECK') {
795 if ($auth_caps = $this->getCapability('AUTH')) {
796 $auth_methods = $auth_caps;
798 // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
799 $login_disabled = $this->getCapability('LOGINDISABLED');
800 if (($key = array_search('LOGIN', $auth_methods)) !== false) {
801 if ($login_disabled) {
802 unset($auth_methods[$key]);
805 else if (!$login_disabled) {
806 $auth_methods[] = 'LOGIN';
809 // Use best (for security) supported authentication method
810 foreach (array('DIGEST-MD5', 'CRAM-MD5', 'CRAM_MD5', 'PLAIN', 'LOGIN') as $auth_method) {
811 if (in_array($auth_method, $auth_methods)) {
817 // Prevent from sending credentials in plain text when connection is not secure
818 if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
819 $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
820 $this->closeConnection();
823 // replace AUTH with CRAM-MD5 for backward compat.
824 if ($auth_method == 'AUTH') {
825 $auth_method = 'CRAM-MD5';
829 // pre-login capabilities can be not complete
830 $this->capability_readed = false;
833 switch ($auth_method) {
835 $auth_method = 'CRAM-MD5';
839 $result = $this->authenticate($user, $password, $auth_method);
842 $result = $this->login($user, $password);
845 $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
848 // Connected and authenticated
849 if (is_resource($result)) {
850 if ($this->prefs['force_caps']) {
851 $this->clearCapability();
853 $this->logged = true;
858 $this->closeConnection();
865 return ($this->fp && $this->logged) ? true : false;
868 function closeConnection()
870 if ($this->putLine($this->nextTag() . ' LOGOUT')) {
874 $this->closeSocket();
878 * Executes SELECT command (if mailbox is already not in selected state)
880 * @param string $mailbox Mailbox name
882 * @return boolean True on success, false on error
885 function select($mailbox)
887 if (!strlen($mailbox)) {
891 if ($this->selected == $mailbox) {
895 Temporary commented out because Courier returns \Noselect for INBOX
896 Requires more investigation
898 if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
899 if (in_array('\\Noselect', $opts)) {
904 list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
906 if ($code == self::ERROR_OK) {
907 $response = explode("\r\n", $response);
908 foreach ($response as $line) {
909 if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
910 $this->data[strtoupper($m[2])] = (int) $m[1];
912 else if (preg_match('/^\* OK \[(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)\]/i', $line, $match)) {
913 $this->data[strtoupper($match[1])] = (int) $match[2];
915 else if (preg_match('/^\* OK \[PERMANENTFLAGS \(([^\)]+)\)\]/iU', $line, $match)) {
916 $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
920 $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
922 $this->selected = $mailbox;
930 * Executes STATUS command
932 * @param string $mailbox Mailbox name
933 * @param array $items Additional requested item names. By default
934 * MESSAGES and UNSEEN are requested. Other defined
935 * in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
937 * @return array Status item-value hash
941 function status($mailbox, $items=array())
943 if (!strlen($mailbox)) {
947 if (!in_array('MESSAGES', $items)) {
948 $items[] = 'MESSAGES';
950 if (!in_array('UNSEEN', $items)) {
954 list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
955 '(' . implode(' ', (array) $items) . ')'));
957 if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
959 $response = substr($response, 9); // remove prefix "* STATUS "
961 list($mbox, $items) = $this->tokenizeResponse($response, 2);
963 // Fix for #1487859. Some buggy server returns not quoted
964 // folder name with spaces. Let's try to handle this situation
965 if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
966 $response = substr($response, $pos);
967 $items = $this->tokenizeResponse($response, 1);
968 if (!is_array($items)) {
973 for ($i=0, $len=count($items); $i<$len; $i += 2) {
974 $result[$items[$i]] = (int) $items[$i+1];
977 $this->data['STATUS:'.$mailbox] = $result;
986 * Executes EXPUNGE command
988 * @param string $mailbox Mailbox name
989 * @param string $messages Message UIDs to expunge
991 * @return boolean True on success, False on error
994 function expunge($mailbox, $messages=NULL)
996 if (!$this->select($mailbox)) {
1000 if (!$this->data['READ-WRITE']) {
1001 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
1005 // Clear internal status cache
1006 unset($this->data['STATUS:'.$mailbox]);
1009 $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
1011 $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
1013 if ($result == self::ERROR_OK) {
1014 $this->selected = ''; // state has changed, need to reselect
1022 * Executes CLOSE command
1024 * @return boolean True on success, False on error
1030 $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
1032 if ($result == self::ERROR_OK) {
1033 $this->selected = '';
1041 * Executes SUBSCRIBE command
1043 * @param string $mailbox Mailbox name
1045 * @return boolean True on success, False on error
1048 function subscribe($mailbox)
1050 $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1051 self::COMMAND_NORESPONSE);
1053 return ($result == self::ERROR_OK);
1057 * Executes UNSUBSCRIBE command
1059 * @param string $mailbox Mailbox name
1061 * @return boolean True on success, False on error
1064 function unsubscribe($mailbox)
1066 $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1067 self::COMMAND_NORESPONSE);
1069 return ($result == self::ERROR_OK);
1073 * Executes DELETE command
1075 * @param string $mailbox Mailbox name
1077 * @return boolean True on success, False on error
1080 function deleteFolder($mailbox)
1082 $result = $this->execute('DELETE', array($this->escape($mailbox)),
1083 self::COMMAND_NORESPONSE);
1085 return ($result == self::ERROR_OK);
1089 * Removes all messages in a folder
1091 * @param string $mailbox Mailbox name
1093 * @return boolean True on success, False on error
1096 function clearFolder($mailbox)
1098 $num_in_trash = $this->countMessages($mailbox);
1099 if ($num_in_trash > 0) {
1100 $res = $this->delete($mailbox, '1:*');
1104 if ($this->selected == $mailbox)
1105 $res = $this->close();
1107 $res = $this->expunge($mailbox);
1114 * Returns count of all messages in a folder
1116 * @param string $mailbox Mailbox name
1118 * @return int Number of messages, False on error
1121 function countMessages($mailbox, $refresh = false)
1124 $this->selected = '';
1127 if ($this->selected == $mailbox) {
1128 return $this->data['EXISTS'];
1131 // Check internal cache
1132 $cache = $this->data['STATUS:'.$mailbox];
1133 if (!empty($cache) && isset($cache['MESSAGES'])) {
1134 return (int) $cache['MESSAGES'];
1137 // Try STATUS (should be faster than SELECT)
1138 $counts = $this->status($mailbox);
1139 if (is_array($counts)) {
1140 return (int) $counts['MESSAGES'];
1147 * Returns count of messages with \Recent flag in a folder
1149 * @param string $mailbox Mailbox name
1151 * @return int Number of messages, False on error
1154 function countRecent($mailbox)
1156 if (!strlen($mailbox)) {
1160 $this->select($mailbox);
1162 if ($this->selected == $mailbox) {
1163 return $this->data['RECENT'];
1170 * Returns count of messages without \Seen flag in a specified folder
1172 * @param string $mailbox Mailbox name
1174 * @return int Number of messages, False on error
1177 function countUnseen($mailbox)
1179 // Check internal cache
1180 $cache = $this->data['STATUS:'.$mailbox];
1181 if (!empty($cache) && isset($cache['UNSEEN'])) {
1182 return (int) $cache['UNSEEN'];
1185 // Try STATUS (should be faster than SELECT+SEARCH)
1186 $counts = $this->status($mailbox);
1187 if (is_array($counts)) {
1188 return (int) $counts['UNSEEN'];
1191 // Invoke SEARCH as a fallback
1192 $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1193 if (is_array($index)) {
1194 return (int) $index['COUNT'];
1201 * Executes ID command (RFC2971)
1203 * @param array $items Client identification information key/value hash
1205 * @return array Server identification information key/value hash
1209 function id($items=array())
1211 if (is_array($items) && !empty($items)) {
1212 foreach ($items as $key => $value) {
1213 $args[] = $this->escape($key, true);
1214 $args[] = $this->escape($value, true);
1218 list($code, $response) = $this->execute('ID', array(
1219 !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1223 if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
1224 $response = substr($response, 5); // remove prefix "* ID "
1225 $items = $this->tokenizeResponse($response, 1);
1228 for ($i=0, $len=count($items); $i<$len; $i += 2) {
1229 $result[$items[$i]] = $items[$i+1];
1238 function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1240 $field = strtoupper($field);
1241 if ($field == 'INTERNALDATE') {
1245 $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1246 'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1248 if (!$fields[$field]) {
1252 if (!$this->select($mailbox)) {
1258 $add = $this->compressMessageSet($add);
1260 list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1261 array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1263 if ($code == self::ERROR_OK) {
1264 // remove prefix and unilateral untagged server responses
1265 $response = substr($response, stripos($response, '* SORT') + 7);
1266 if ($pos = strpos($response, '*')) {
1267 $response = substr($response, 0, $pos);
1269 return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1275 function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1277 if (is_array($message_set)) {
1278 if (!($message_set = $this->compressMessageSet($message_set)))
1281 list($from_idx, $to_idx) = explode(':', $message_set);
1282 if (empty($message_set) ||
1283 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1288 $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1290 $fields_a['DATE'] = 1;
1291 $fields_a['INTERNALDATE'] = 4;
1292 $fields_a['ARRIVAL'] = 4;
1293 $fields_a['FROM'] = 1;
1294 $fields_a['REPLY-TO'] = 1;
1295 $fields_a['SENDER'] = 1;
1296 $fields_a['TO'] = 1;
1297 $fields_a['CC'] = 1;
1298 $fields_a['SUBJECT'] = 1;
1299 $fields_a['UID'] = 2;
1300 $fields_a['SIZE'] = 2;
1301 $fields_a['SEEN'] = 3;
1302 $fields_a['RECENT'] = 3;
1303 $fields_a['DELETED'] = 3;
1305 if (!($mode = $fields_a[$index_field])) {
1309 /* Do "SELECT" command */
1310 if (!$this->select($mailbox)) {
1314 // build FETCH command string
1315 $key = $this->nextTag();
1316 $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
1317 $deleted = $skip_deleted ? ' FLAGS' : '';
1319 if ($mode == 1 && $index_field == 'DATE')
1320 $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1321 else if ($mode == 1)
1322 $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1323 else if ($mode == 2) {
1324 if ($index_field == 'SIZE')
1325 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1327 $request = " $cmd $message_set ($index_field$deleted)";
1328 } else if ($mode == 3)
1329 $request = " $cmd $message_set (FLAGS)";
1331 $request = " $cmd $message_set (INTERNALDATE$deleted)";
1333 $request = $key . $request;
1335 if (!$this->putLine($request)) {
1336 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1343 $line = rtrim($this->readLine(200));
1344 $line = $this->multLine($line);
1346 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1350 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1351 $flags = explode(' ', strtoupper($matches[1]));
1352 if (in_array('\\DELETED', $flags)) {
1353 $deleted[$id] = $id;
1358 if ($mode == 1 && $index_field == 'DATE') {
1359 if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1360 $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1361 $value = trim($value);
1362 $result[$id] = $this->strToTime($value);
1364 // non-existent/empty Date: header, use INTERNALDATE
1365 if (empty($result[$id])) {
1366 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1367 $result[$id] = $this->strToTime($matches[1]);
1371 } else if ($mode == 1) {
1372 if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1373 $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1374 $result[$id] = trim($value);
1378 } else if ($mode == 2) {
1379 if (preg_match('/(UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1380 $result[$id] = trim($matches[2]);
1384 } else if ($mode == 3) {
1385 if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1386 $flags = explode(' ', $matches[1]);
1388 $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1389 } else if ($mode == 4) {
1390 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1391 $result[$id] = $this->strToTime($matches[1]);
1397 } while (!$this->startsWith($line, $key, true, true));
1402 static function compressMessageSet($messages, $force=false)
1404 // given a comma delimited list of independent mid's,
1405 // compresses by grouping sequences together
1407 if (!is_array($messages)) {
1408 // if less than 255 bytes long, let's not bother
1409 if (!$force && strlen($messages)<255) {
1413 // see if it's already been compressed
1414 if (strpos($messages, ':') !== false) {
1418 // separate, then sort
1419 $messages = explode(',', $messages);
1425 $start = $prev = $messages[0];
1427 foreach ($messages as $id) {
1428 $incr = $id - $prev;
1429 if ($incr > 1) { // found a gap
1430 if ($start == $prev) {
1431 $result[] = $prev; // push single id
1433 $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1435 $start = $id; // start of new sequence
1440 // handle the last sequence/id
1441 if ($start == $prev) {
1444 $result[] = $start.':'.$prev;
1447 // return as comma separated string
1448 return implode(',', $result);
1451 static function uncompressMessageSet($messages)
1454 $messages = explode(',', $messages);
1456 foreach ($messages as $part) {
1457 $items = explode(':', $part);
1458 $max = max($items[0], $items[1]);
1460 for ($x=$items[0]; $x<=$max; $x++) {
1469 * Returns message sequence identifier
1471 * @param string $mailbox Mailbox name
1472 * @param int $uid Message unique identifier (UID)
1474 * @return int Message sequence identifier
1477 function UID2ID($mailbox, $uid)
1480 $id_a = $this->search($mailbox, "UID $uid");
1481 if (is_array($id_a) && count($id_a) == 1) {
1482 return (int) $id_a[0];
1489 * Returns message unique identifier (UID)
1491 * @param string $mailbox Mailbox name
1492 * @param int $uid Message sequence identifier
1494 * @return int Message unique identifier
1497 function ID2UID($mailbox, $id)
1499 if (empty($id) || $id < 0) {
1503 if (!$this->select($mailbox)) {
1507 list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1509 if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1516 function fetchUIDs($mailbox, $message_set=null)
1518 if (is_array($message_set))
1519 $message_set = join(',', $message_set);
1520 else if (empty($message_set))
1521 $message_set = '1:*';
1523 return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1526 function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1530 if (!$this->select($mailbox)) {
1534 $message_set = $this->compressMessageSet($message_set);
1537 $add = ' '.trim($add);
1539 /* FETCH uid, size, flags and headers */
1540 $key = $this->nextTag();
1541 $request = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1542 $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1544 $request .= "BODYSTRUCTURE ";
1545 $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1546 $request .= "CC REPLY-TO LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1548 if (!$this->putLine($request)) {
1549 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1553 $line = $this->readLine(4096);
1554 $line = $this->multLine($line);
1559 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1560 $id = intval($m[1]);
1562 $result[$id] = new rcube_mail_header;
1563 $result[$id]->id = $id;
1564 $result[$id]->subject = '';
1565 $result[$id]->messageID = 'mid:' . $id;
1570 // Sample reply line:
1571 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1572 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1573 // BODY[HEADER.FIELDS ...
1575 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/sU', $line, $matches)) {
1578 while (list($name, $value) = $this->tokenizeResponse($str, 2)) {
1579 if ($name == 'UID') {
1580 $result[$id]->uid = intval($value);
1582 else if ($name == 'RFC822.SIZE') {
1583 $result[$id]->size = intval($value);
1585 else if ($name == 'INTERNALDATE') {
1586 $result[$id]->internaldate = $value;
1587 $result[$id]->date = $value;
1588 $result[$id]->timestamp = $this->StrToTime($value);
1590 else if ($name == 'FLAGS') {
1597 while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/sU', $line, $m)) {
1598 $line2 = $this->readLine(1024);
1599 $line .= $this->multLine($line2, true);
1601 $result[$id]->body_structure = $m[1];
1604 // the rest of the result
1605 if (preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m)) {
1606 $reslines = explode("\n", trim($m[1], '"'));
1607 // re-parse (see below)
1608 foreach ($reslines as $resln) {
1609 if (ord($resln[0])<=32) {
1610 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1612 $lines[++$ln] = trim($resln);
1618 // Start parsing headers. The problem is, some header "lines" take up multiple lines.
1619 // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1620 // process the previous line. Otherwise, we'll keep adding the strings until we come
1621 // to the next valid header line.
1624 $line = rtrim($this->readLine(300), "\r\n");
1626 // The preg_match below works around communigate imap, which outputs " UID <number>)".
1627 // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1628 // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1629 // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1630 // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1631 // An alternative might be:
1632 // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1633 // however, unsure how well this would work with all imap clients.
1634 if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1638 // handle FLAGS reply after headers (AOL, Zimbra?)
1639 if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1640 $flags_a = $this->tokenizeResponse($matches[1]);
1644 if (ord($line[0])<=32) {
1645 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1647 $lines[++$ln] = trim($line);
1649 // patch from "Maksim Rubis" <siburny@hotmail.com>
1650 } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1652 if (strncmp($line, $key, strlen($key))) {
1653 // process header, fill rcube_mail_header obj.
1655 if (is_array($headers)) {
1657 while (list($k, $bar) = each($headers)) {
1662 // create array with header field:data
1663 while (list($lines_key, $str) = each($lines)) {
1664 list($field, $string) = explode(':', $str, 2);
1666 $field = strtolower($field);
1667 $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
1671 $result[$id]->date = $string;
1672 $result[$id]->timestamp = $this->strToTime($string);
1675 $result[$id]->from = $string;
1678 $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1681 $result[$id]->subject = $string;
1684 $result[$id]->replyto = $string;
1687 $result[$id]->cc = $string;
1690 $result[$id]->bcc = $string;
1692 case 'content-transfer-encoding':
1693 $result[$id]->encoding = $string;
1695 case 'content-type':
1696 $ctype_parts = preg_split('/[; ]/', $string);
1697 $result[$id]->ctype = strtolower(array_shift($ctype_parts));
1698 if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1699 $result[$id]->charset = $regs[1];
1703 $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1706 $result[$id]->references = $string;
1708 case 'return-receipt-to':
1709 case 'disposition-notification-to':
1710 case 'x-confirm-reading-to':
1711 $result[$id]->mdn_to = $string;
1714 $result[$id]->messageID = $string;
1717 if (preg_match('/^(\d+)/', $string, $matches)) {
1718 $result[$id]->priority = intval($matches[1]);
1722 if (strlen($field) > 2) {
1723 $result[$id]->others[$field] = $string;
1731 if (!empty($flags_a)) {
1732 foreach ($flags_a as $flag) {
1733 $flag = str_replace('\\', '', $flag);
1734 $result[$id]->flags[] = $flag;
1736 switch (strtoupper($flag)) {
1738 $result[$id]->seen = true;
1741 $result[$id]->deleted = true;
1744 $result[$id]->answered = true;
1747 $result[$id]->forwarded = true;
1750 $result[$id]->mdn_sent = true;
1753 $result[$id]->flagged = true;
1759 } while (!$this->startsWith($line, $key, true));
1764 function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1766 $a = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1768 return array_shift($a);
1773 function sortHeaders($a, $field, $flag)
1775 if (empty($field)) {
1779 $field = strtolower($field);
1782 if ($field == 'date' || $field == 'internaldate') {
1783 $field = 'timestamp';
1789 $flag = strtoupper($flag);
1795 // First, we'll create an "index" array.
1796 // Then, we'll use sort() on that array,
1797 // and use that to sort the main array.
1799 // create "index" array
1802 while (list($key, $val) = each($a)) {
1803 if ($field == 'timestamp') {
1804 $data = $this->strToTime($val->date);
1806 $data = $val->timestamp;
1809 $data = $val->$field;
1810 if (is_string($data)) {
1811 $data = str_replace('"', '', $data);
1812 if ($field == 'subject') {
1813 $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1815 $data = strtoupper($data);
1818 $index[$key] = $data;
1822 if ($flag == 'ASC') {
1828 // form new array based on index
1831 while (list($key, $val) = each($index)) {
1832 $result[$key] = $a[$key];
1840 function modFlag($mailbox, $messages, $flag, $mod)
1842 if ($mod != '+' && $mod != '-') {
1846 if (!$this->select($mailbox)) {
1850 if (!$this->data['READ-WRITE']) {
1851 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1855 // Clear internal status cache
1856 if ($flag == 'SEEN') {
1857 unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1860 $flag = $this->flags[strtoupper($flag)];
1861 $result = $this->execute('UID STORE', array(
1862 $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1863 self::COMMAND_NORESPONSE);
1865 return ($result == self::ERROR_OK);
1868 function flag($mailbox, $messages, $flag) {
1869 return $this->modFlag($mailbox, $messages, $flag, '+');
1872 function unflag($mailbox, $messages, $flag) {
1873 return $this->modFlag($mailbox, $messages, $flag, '-');
1876 function delete($mailbox, $messages) {
1877 return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1880 function copy($messages, $from, $to)
1882 if (!$this->select($from)) {
1886 // Clear internal status cache
1887 unset($this->data['STATUS:'.$to]);
1889 $result = $this->execute('UID COPY', array(
1890 $this->compressMessageSet($messages), $this->escape($to)),
1891 self::COMMAND_NORESPONSE);
1893 return ($result == self::ERROR_OK);
1896 function move($messages, $from, $to)
1898 if (!$this->select($from)) {
1902 if (!$this->data['READ-WRITE']) {
1903 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1907 $r = $this->copy($messages, $from, $to);
1910 // Clear internal status cache
1911 unset($this->data['STATUS:'.$from]);
1913 return $this->delete($from, $messages);
1918 // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1919 // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1920 // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1921 private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1924 if ($str[$begin] != '(') {
1925 $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1926 $msg = substr($str, $begin, $stop - $begin);
1931 $depthmap[$msg] = $depth;
1932 $haschildren[$msg] = false;
1933 if (!is_null($parent))
1934 $haschildren[$parent] = true;
1935 if ($stop + 1 < $end)
1936 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1938 $node[$msg] = array();
1941 while ($off < $end) {
1946 $p = strpos($str, ')', $off);
1948 error_log("Mismatched brackets parsing IMAP THREAD response:");
1949 error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1950 error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1953 $p1 = strpos($str, '(', $off);
1954 if ($p1 !== false && $p1 < $p) {
1962 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1969 function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1971 $old_sel = $this->selected;
1973 if (!$this->select($mailbox)) {
1977 // return empty result when folder is empty and we're just after SELECT
1978 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1979 return array(array(), array(), array());
1982 $encoding = $encoding ? trim($encoding) : 'US-ASCII';
1983 $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1984 $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1987 list($code, $response) = $this->execute('THREAD', array(
1988 $algorithm, $encoding, $criteria));
1990 if ($code == self::ERROR_OK) {
1992 $response = substr($response, stripos($response, '* THREAD') + 9);
1993 // ...unilateral untagged server responses
1994 if ($pos = strpos($response, '*')) {
1995 $response = substr($response, 0, $pos);
1998 $response = str_replace("\r\n", '', $response);
1999 $depthmap = array();
2000 $haschildren = array();
2002 $tree = $this->parseThread($response, 0, strlen($response),
2003 null, null, 0, $depthmap, $haschildren);
2005 return array($tree, $depthmap, $haschildren);
2012 * Executes SEARCH command
2014 * @param string $mailbox Mailbox name
2015 * @param string $criteria Searching criteria
2016 * @param bool $return_uid Enable UID in result instead of sequence ID
2017 * @param array $items Return items (MIN, MAX, COUNT, ALL)
2019 * @return array Message identifiers or item-value hash
2021 function search($mailbox, $criteria, $return_uid=false, $items=array())
2023 $old_sel = $this->selected;
2025 if (!$this->select($mailbox)) {
2029 // return empty result when folder is empty and we're just after SELECT
2030 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2032 return array_combine($items, array_fill(0, count($items), 0));
2037 $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
2038 $criteria = trim($criteria);
2042 if (!empty($items) && $esearch) {
2043 $params .= 'RETURN (' . implode(' ', $items) . ')';
2045 if (!empty($criteria)) {
2046 $params .= ($params ? ' ' : '') . $criteria;
2052 list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2055 if ($code == self::ERROR_OK) {
2057 $response = substr($response, stripos($response,
2058 $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
2059 // ...and unilateral untagged server responses
2060 if ($pos = strpos($response, '*')) {
2061 $response = rtrim(substr($response, 0, $pos));
2065 // Skip prefix: ... (TAG "A285") UID ...
2066 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2069 for ($i=0; $i<count($items); $i++) {
2070 // If the SEARCH results in no matches, the server MUST NOT
2071 // include the item result option in the ESEARCH response
2072 if ($ret = $this->tokenizeResponse($response, 2)) {
2073 list ($name, $value) = $ret;
2074 $result[$name] = $value;
2081 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2083 if (!empty($items)) {
2085 if (in_array('COUNT', $items)) {
2086 $result['COUNT'] = count($response);
2088 if (in_array('MIN', $items)) {
2089 $result['MIN'] = !empty($response) ? min($response) : 0;
2091 if (in_array('MAX', $items)) {
2092 $result['MAX'] = !empty($response) ? max($response) : 0;
2094 if (in_array('ALL', $items)) {
2095 $result['ALL'] = $this->compressMessageSet($response, true);
2110 * Returns list of mailboxes
2112 * @param string $ref Reference name
2113 * @param string $mailbox Mailbox name
2114 * @param array $status_opts (see self::_listMailboxes)
2115 * @param array $select_opts (see self::_listMailboxes)
2117 * @return array List of mailboxes or hash of options if $status_opts argument
2121 function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2123 return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2127 * Returns list of subscribed mailboxes
2129 * @param string $ref Reference name
2130 * @param string $mailbox Mailbox name
2131 * @param array $status_opts (see self::_listMailboxes)
2133 * @return array List of mailboxes or hash of options if $status_opts argument
2137 function listSubscribed($ref, $mailbox, $status_opts=array())
2139 return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2143 * IMAP LIST/LSUB command
2145 * @param string $ref Reference name
2146 * @param string $mailbox Mailbox name
2147 * @param bool $subscribed Enables returning subscribed mailboxes only
2148 * @param array $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2149 * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2150 * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2151 * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2153 * @return array List of mailboxes or hash of options if $status_ops argument
2157 private function _listMailboxes($ref, $mailbox, $subscribed=false,
2158 $status_opts=array(), $select_opts=array())
2160 if (!strlen($mailbox)) {
2166 if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2167 $select_opts = (array) $select_opts;
2169 $args[] = '(' . implode(' ', $select_opts) . ')';
2172 $args[] = $this->escape($ref);
2173 $args[] = $this->escape($mailbox);
2175 if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2176 $status_opts = (array) $status_opts;
2179 $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2182 list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2184 if ($code == self::ERROR_OK) {
2186 while ($this->tokenizeResponse($response, 1) == '*') {
2187 $cmd = strtoupper($this->tokenizeResponse($response, 1));
2188 // * LIST (<options>) <delimiter> <mailbox>
2189 if ($cmd == 'LIST' || $cmd == 'LSUB') {
2190 list($opts, $delim, $mailbox) = $this->tokenizeResponse($response, 3);
2192 // Add to result array
2194 $folders[] = $mailbox;
2197 $folders[$mailbox] = array();
2200 // Add to options array
2201 if (!empty($opts)) {
2202 if (empty($this->data['LIST'][$mailbox]))
2203 $this->data['LIST'][$mailbox] = $opts;
2205 $this->data['LIST'][$mailbox] = array_unique(array_merge(
2206 $this->data['LIST'][$mailbox], $opts));
2209 // * STATUS <mailbox> (<result>)
2210 else if ($cmd == 'STATUS') {
2211 list($mailbox, $status) = $this->tokenizeResponse($response, 2);
2213 for ($i=0, $len=count($status); $i<$len; $i += 2) {
2214 list($name, $value) = $this->tokenizeResponse($status, 2);
2215 $folders[$mailbox][$name] = $value;
2218 // other untagged response line, skip it
2220 $response = ltrim($response);
2221 if (($position = strpos($response, "\n")) !== false)
2222 $response = substr($response, $position+1);
2234 function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
2236 if (!$this->select($mailbox)) {
2241 $parts = (array) $parts;
2242 $key = $this->nextTag();
2245 $type = $mime ? 'MIME' : 'HEADER';
2248 foreach($parts as $part) {
2249 $peeks[] = "BODY.PEEK[$part.$type]";
2252 $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2255 if (!$this->putLine($request)) {
2256 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2261 $line = $this->readLine(1024);
2262 $line = $this->multLine($line);
2264 if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2266 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
2267 $result[$idx] = trim($result[$idx], '"');
2268 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2270 } while (!$this->startsWith($line, $key, true));
2275 function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2277 $part = empty($part) ? 'HEADER' : $part.'.MIME';
2279 return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2282 function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2284 if (!$this->select($mailbox)) {
2288 switch ($encoding) {
2292 case 'quoted-printable':
2306 $reply_key = '* ' . $id;
2307 $key = $this->nextTag();
2308 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2311 if (!$this->putLine($request)) {
2312 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2316 // receive reply line
2318 $line = rtrim($this->readLine(1024));
2319 $a = explode(' ', $line);
2320 } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2322 $len = strlen($line);
2325 // handle empty "* X FETCH ()" response
2326 if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2327 // one line response, get everything between first and last quotes
2328 if (substr($line, -4, 3) == 'NIL') {
2332 $from = strpos($line, '"') + 1;
2333 $to = strrpos($line, '"');
2335 $result = substr($line, $from, $len);
2339 $result = base64_decode($result);
2341 else if ($mode == 2) {
2342 $result = quoted_printable_decode($result);
2344 else if ($mode == 3) {
2345 $result = convert_uudecode($result);
2348 } else if ($line[$len-1] == '}') {
2349 // multi-line request, find sizes of content and receive that many bytes
2350 $from = strpos($line, '{') + 1;
2351 $to = strrpos($line, '}');
2353 $sizeStr = substr($line, $from, $len);
2354 $bytes = (int)$sizeStr;
2357 while ($bytes > 0) {
2358 $line = $this->readLine(4096);
2360 if ($line === NULL) {
2364 $len = strlen($line);
2366 if ($len > $bytes) {
2367 $line = substr($line, 0, $bytes);
2368 $len = strlen($line);
2374 $line = rtrim($line, "\t\r\n\0\x0B");
2375 // create chunks with proper length for base64 decoding
2376 $line = $prev.$line;
2377 $length = strlen($line);
2379 $length = floor($length / 4) * 4;
2380 $prev = substr($line, $length);
2381 $line = substr($line, 0, $length);
2385 $line = base64_decode($line);
2387 } else if ($mode == 2) {
2388 $line = rtrim($line, "\t\r\0\x0B");
2389 $line = quoted_printable_decode($line);
2391 } else if ($mode == 3) {
2392 $line = rtrim($line, "\t\r\n\0\x0B");
2393 if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2395 $line = convert_uudecode($line);
2398 $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2402 fwrite($file, $line);
2410 // read in anything up until last line
2413 $line = $this->readLine(1024);
2414 } while (!$this->startsWith($line, $key, true));
2416 if ($result !== false) {
2418 fwrite($file, $result);
2419 } else if ($print) {
2429 function createFolder($mailbox)
2431 $result = $this->execute('CREATE', array($this->escape($mailbox)),
2432 self::COMMAND_NORESPONSE);
2434 return ($result == self::ERROR_OK);
2437 function renameFolder($from, $to)
2439 $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2440 self::COMMAND_NORESPONSE);
2442 return ($result == self::ERROR_OK);
2445 function append($mailbox, &$message)
2451 $message = str_replace("\r", '', $message);
2452 $message = str_replace("\n", "\r\n", $message);
2454 $len = strlen($message);
2459 $key = $this->nextTag();
2460 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2461 $len, ($this->prefs['literal+'] ? '+' : ''));
2463 if ($this->putLine($request)) {
2464 // Don't wait when LITERAL+ is supported
2465 if (!$this->prefs['literal+']) {
2466 $line = $this->readReply();
2468 if ($line[0] != '+') {
2469 $this->parseResult($line, 'APPEND: ');
2474 if (!$this->putLine($message)) {
2479 $line = $this->readLine();
2480 } while (!$this->startsWith($line, $key, true, true));
2482 // Clear internal status cache
2483 unset($this->data['STATUS:'.$mailbox]);
2485 return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2488 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2494 function appendFromFile($mailbox, $path, $headers=null)
2500 // open message file
2502 if (file_exists(realpath($path))) {
2503 $in_fp = fopen($path, 'r');
2506 $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2510 $body_separator = "\r\n\r\n";
2511 $len = filesize($path);
2518 $headers = preg_replace('/[\r\n]+$/', '', $headers);
2519 $len += strlen($headers) + strlen($body_separator);
2522 // send APPEND command
2523 $key = $this->nextTag();
2524 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2525 $len, ($this->prefs['literal+'] ? '+' : ''));
2527 if ($this->putLine($request)) {
2528 // Don't wait when LITERAL+ is supported
2529 if (!$this->prefs['literal+']) {
2530 $line = $this->readReply();
2532 if ($line[0] != '+') {
2533 $this->parseResult($line, 'APPEND: ');
2538 // send headers with body separator
2540 $this->putLine($headers . $body_separator, false);
2544 while (!feof($in_fp) && $this->fp) {
2545 $buffer = fgets($in_fp, 4096);
2546 $this->putLine($buffer, false);
2550 if (!$this->putLine('')) { // \r\n
2556 $line = $this->readLine();
2557 } while (!$this->startsWith($line, $key, true, true));
2559 // Clear internal status cache
2560 unset($this->data['STATUS:'.$mailbox]);
2562 return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2565 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2571 function fetchStructureString($mailbox, $id, $is_uid=false)
2573 if (!$this->select($mailbox)) {
2577 $key = $this->nextTag();
2579 $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2581 if ($this->putLine($command)) {
2583 $line = $this->readLine(5000);
2584 $line = $this->multLine($line, true);
2585 if (!preg_match("/^$key /", $line))
2587 } while (!$this->startsWith($line, $key, true, true));
2589 $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2592 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2601 * GETQUOTAROOT "INBOX"
2602 * QUOTAROOT INBOX user/rchijiiwa1
2603 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2607 $quota_lines = array();
2608 $key = $this->nextTag();
2609 $command = $key . ' GETQUOTAROOT INBOX';
2611 // get line(s) containing quota info
2612 if ($this->putLine($command)) {
2614 $line = rtrim($this->readLine(5000));
2615 if (preg_match('/^\* QUOTA /', $line)) {
2616 $quota_lines[] = $line;
2618 } while (!$this->startsWith($line, $key, true, true));
2621 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2624 // return false if not found, parse if found
2625 $min_free = PHP_INT_MAX;
2626 foreach ($quota_lines as $key => $quota_line) {
2627 $quota_line = str_replace(array('(', ')'), '', $quota_line);
2628 $parts = explode(' ', $quota_line);
2629 $storage_part = array_search('STORAGE', $parts);
2631 if (!$storage_part) {
2635 $used = intval($parts[$storage_part+1]);
2636 $total = intval($parts[$storage_part+2]);
2637 $free = $total - $used;
2639 // return lowest available space from all quotas
2640 if ($free < $min_free) {
2642 $result['used'] = $used;
2643 $result['total'] = $total;
2644 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2645 $result['free'] = 100 - $result['percent'];
2653 * Send the SETACL command (RFC4314)
2655 * @param string $mailbox Mailbox name
2656 * @param string $user User name
2657 * @param mixed $acl ACL string or array
2659 * @return boolean True on success, False on failure
2664 function setACL($mailbox, $user, $acl)
2666 if (is_array($acl)) {
2667 $acl = implode('', $acl);
2670 $result = $this->execute('SETACL', array(
2671 $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2672 self::COMMAND_NORESPONSE);
2674 return ($result == self::ERROR_OK);
2678 * Send the DELETEACL command (RFC4314)
2680 * @param string $mailbox Mailbox name
2681 * @param string $user User name
2683 * @return boolean True on success, False on failure
2688 function deleteACL($mailbox, $user)
2690 $result = $this->execute('DELETEACL', array(
2691 $this->escape($mailbox), $this->escape($user)),
2692 self::COMMAND_NORESPONSE);
2694 return ($result == self::ERROR_OK);
2698 * Send the GETACL command (RFC4314)
2700 * @param string $mailbox Mailbox name
2702 * @return array User-rights array on success, NULL on error
2706 function getACL($mailbox)
2708 list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2710 if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2711 // Parse server response (remove "* ACL ")
2712 $response = substr($response, 6);
2713 $ret = $this->tokenizeResponse($response);
2714 $mbox = array_shift($ret);
2715 $size = count($ret);
2717 // Create user-rights hash array
2718 // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2719 // so we could return only standard rights defined in RFC4314,
2720 // excluding 'c' and 'd' defined in RFC2086.
2721 if ($size % 2 == 0) {
2722 for ($i=0; $i<$size; $i++) {
2723 $ret[$ret[$i]] = str_split($ret[++$i]);
2730 $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2738 * Send the LISTRIGHTS command (RFC4314)
2740 * @param string $mailbox Mailbox name
2741 * @param string $user User name
2743 * @return array List of user rights
2747 function listRights($mailbox, $user)
2749 list($code, $response) = $this->execute('LISTRIGHTS', array(
2750 $this->escape($mailbox), $this->escape($user)));
2752 if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2753 // Parse server response (remove "* LISTRIGHTS ")
2754 $response = substr($response, 13);
2756 $ret_mbox = $this->tokenizeResponse($response, 1);
2757 $ret_user = $this->tokenizeResponse($response, 1);
2758 $granted = $this->tokenizeResponse($response, 1);
2759 $optional = trim($response);
2762 'granted' => str_split($granted),
2763 'optional' => explode(' ', $optional),
2771 * Send the MYRIGHTS command (RFC4314)
2773 * @param string $mailbox Mailbox name
2775 * @return array MYRIGHTS response on success, NULL on error
2779 function myRights($mailbox)
2781 list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2783 if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2784 // Parse server response (remove "* MYRIGHTS ")
2785 $response = substr($response, 11);
2787 $ret_mbox = $this->tokenizeResponse($response, 1);
2788 $rights = $this->tokenizeResponse($response, 1);
2790 return str_split($rights);
2797 * Send the SETMETADATA command (RFC5464)
2799 * @param string $mailbox Mailbox name
2800 * @param array $entries Entry-value array (use NULL value as NIL)
2802 * @return boolean True on success, False on failure
2806 function setMetadata($mailbox, $entries)
2808 if (!is_array($entries) || empty($entries)) {
2809 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2813 foreach ($entries as $name => $value) {
2814 $entries[$name] = $this->escape($name) . ' ' . $this->escape($value);
2817 $entries = implode(' ', $entries);
2818 $result = $this->execute('SETMETADATA', array(
2819 $this->escape($mailbox), '(' . $entries . ')'),
2820 self::COMMAND_NORESPONSE);
2822 return ($result == self::ERROR_OK);
2826 * Send the SETMETADATA command with NIL values (RFC5464)
2828 * @param string $mailbox Mailbox name
2829 * @param array $entries Entry names array
2831 * @return boolean True on success, False on failure
2836 function deleteMetadata($mailbox, $entries)
2838 if (!is_array($entries) && !empty($entries)) {
2839 $entries = explode(' ', $entries);
2842 if (empty($entries)) {
2843 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2847 foreach ($entries as $entry) {
2848 $data[$entry] = NULL;
2851 return $this->setMetadata($mailbox, $data);
2855 * Send the GETMETADATA command (RFC5464)
2857 * @param string $mailbox Mailbox name
2858 * @param array $entries Entries
2859 * @param array $options Command options (with MAXSIZE and DEPTH keys)
2861 * @return array GETMETADATA result on success, NULL on error
2866 function getMetadata($mailbox, $entries, $options=array())
2868 if (!is_array($entries)) {
2869 $entries = array($entries);
2872 // create entries string
2873 foreach ($entries as $idx => $name) {
2874 $entries[$idx] = $this->escape($name);
2878 $entlist = '(' . implode(' ', $entries) . ')';
2880 // create options string
2881 if (is_array($options)) {
2882 $options = array_change_key_case($options, CASE_UPPER);
2885 if (!empty($options['MAXSIZE'])) {
2886 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2888 if (!empty($options['DEPTH'])) {
2889 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2893 $optlist = '(' . implode(' ', $opts) . ')';
2897 $optlist .= ($optlist ? ' ' : '') . $entlist;
2899 list($code, $response) = $this->execute('GETMETADATA', array(
2900 $this->escape($mailbox), $optlist));
2902 if ($code == self::ERROR_OK) {
2904 $data = $this->tokenizeResponse($response);
2906 // The METADATA response can contain multiple entries in a single
2907 // response or multiple responses for each entry or group of entries
2908 if (!empty($data) && ($size = count($data))) {
2909 for ($i=0; $i<$size; $i++) {
2910 if (isset($mbox) && is_array($data[$i])) {
2911 $size_sub = count($data[$i]);
2912 for ($x=0; $x<$size_sub; $x++) {
2913 $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
2917 else if ($data[$i] == '*') {
2918 if ($data[$i+1] == 'METADATA') {
2919 $mbox = $data[$i+2];
2920 unset($data[$i]); // "*"
2921 unset($data[++$i]); // "METADATA"
2922 unset($data[++$i]); // Mailbox
2924 // get rid of other untagged responses
2930 else if (isset($mbox)) {
2931 $result[$mbox][$data[$i]] = $data[++$i];
2948 * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
2950 * @param string $mailbox Mailbox name
2951 * @param array $data Data array where each item is an array with
2952 * three elements: entry name, attribute name, value
2954 * @return boolean True on success, False on failure
2958 function setAnnotation($mailbox, $data)
2960 if (!is_array($data) || empty($data)) {
2961 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2965 foreach ($data as $entry) {
2966 // ANNOTATEMORE drafts before version 08 require quoted parameters
2967 $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
2968 $this->escape($entry[1], true), $this->escape($entry[2], true));
2971 $entries = implode(' ', $entries);
2972 $result = $this->execute('SETANNOTATION', array(
2973 $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
2975 return ($result == self::ERROR_OK);
2979 * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
2981 * @param string $mailbox Mailbox name
2982 * @param array $data Data array where each item is an array with
2983 * two elements: entry name and attribute name
2985 * @return boolean True on success, False on failure
2990 function deleteAnnotation($mailbox, $data)
2992 if (!is_array($data) || empty($data)) {
2993 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2997 return $this->setAnnotation($mailbox, $data);
3001 * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3003 * @param string $mailbox Mailbox name
3004 * @param array $entries Entries names
3005 * @param array $attribs Attribs names
3007 * @return array Annotations result on success, NULL on error
3012 function getAnnotation($mailbox, $entries, $attribs)
3014 if (!is_array($entries)) {
3015 $entries = array($entries);
3017 // create entries string
3018 // ANNOTATEMORE drafts before version 08 require quoted parameters
3019 foreach ($entries as $idx => $name) {
3020 $entries[$idx] = $this->escape($name, true);
3022 $entries = '(' . implode(' ', $entries) . ')';
3024 if (!is_array($attribs)) {
3025 $attribs = array($attribs);
3027 // create entries string
3028 foreach ($attribs as $idx => $name) {
3029 $attribs[$idx] = $this->escape($name, true);
3031 $attribs = '(' . implode(' ', $attribs) . ')';
3033 list($code, $response) = $this->execute('GETANNOTATION', array(
3034 $this->escape($mailbox), $entries, $attribs));
3036 if ($code == self::ERROR_OK) {
3038 $data = $this->tokenizeResponse($response);
3040 // Here we returns only data compatible with METADATA result format
3041 if (!empty($data) && ($size = count($data))) {
3042 for ($i=0; $i<$size; $i++) {
3044 if (isset($mbox) && is_array($entry)) {
3046 $entry = $last_entry;
3048 else if ($entry == '*') {
3049 if ($data[$i+1] == 'ANNOTATION') {
3050 $mbox = $data[$i+2];
3051 unset($data[$i]); // "*"
3052 unset($data[++$i]); // "ANNOTATION"
3053 unset($data[++$i]); // Mailbox
3055 // get rid of other untagged responses
3062 else if (isset($mbox)) {
3063 $attribs = $data[++$i];
3070 if (!empty($attribs)) {
3071 for ($x=0, $len=count($attribs); $x<$len;) {
3072 $attr = $attribs[$x++];
3073 $value = $attribs[$x++];
3074 if ($attr == 'value.priv') {
3075 $result[$mbox]['/private' . $entry] = $value;
3077 else if ($attr == 'value.shared') {
3078 $result[$mbox]['/shared' . $entry] = $value;
3082 $last_entry = $entry;
3094 * Creates next command identifier (tag)
3096 * @return string Command identifier
3103 $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3105 return $this->cmd_tag;
3109 * Sends IMAP command and parses result
3111 * @param string $command IMAP command
3112 * @param array $arguments Command arguments
3113 * @param int $options Execution options
3115 * @return mixed Response code or list of response code and data
3119 function execute($command, $arguments=array(), $options=0)
3121 $tag = $this->nextTag();
3122 $query = $tag . ' ' . $command;
3123 $noresp = ($options & self::COMMAND_NORESPONSE);
3124 $response = $noresp ? null : '';
3126 if (!empty($arguments)) {
3127 $query .= ' ' . implode(' ', $arguments);
3131 if (!$this->putLineC($query)) {
3132 $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3133 return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3138 $line = $this->readLine(4096);
3139 if ($response !== null) {
3142 } while (!$this->startsWith($line, $tag . ' ', true, true));
3144 $code = $this->parseResult($line, $command . ': ');
3146 // Remove last line from response
3148 $line_len = min(strlen($response), strlen($line) + 2);
3149 $response = substr($response, 0, -$line_len);
3152 // optional CAPABILITY response
3153 if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3154 && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3156 $this->parseCapability($matches[1], true);
3159 // return last line only (without command tag, result and response code)
3160 if ($line && ($options & self::COMMAND_LASTLINE)) {
3161 $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3164 return $noresp ? $code : array($code, $response);
3168 * Splits IMAP response into string tokens
3170 * @param string &$str The IMAP's server response
3171 * @param int $num Number of tokens to return
3173 * @return mixed Tokens array or string if $num=1
3177 static function tokenizeResponse(&$str, $num=0)
3181 while (!$num || count($result) < $num) {
3182 // remove spaces from the beginning of the string
3189 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3192 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3195 $result[] = substr($str, $epos + 3, $bytes);
3196 // Advance the string
3197 $str = substr($str, $epos + 3 + $bytes);
3202 $len = strlen($str);
3204 for ($pos=1; $pos<$len; $pos++) {
3205 if ($str[$pos] == '"') {
3208 if ($str[$pos] == "\\") {
3209 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3214 if ($str[$pos] != '"') {
3217 // we need to strip slashes for a quoted string
3218 $result[] = stripslashes(substr($str, 1, $pos - 1));
3219 $str = substr($str, $pos + 1);
3222 // Parenthesized list
3224 $str = substr($str, 1);
3225 $result[] = self::tokenizeResponse($str);
3228 $str = substr($str, 1);
3232 // String atom, number, NIL, *, %
3234 // empty or one character
3238 if (strlen($str) < 2) {
3244 // excluded chars: SP, CTL, )
3245 if (preg_match('/^([^\x00-\x20\x29\x7F]+)/', $str, $m)) {
3246 $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3247 $str = substr($str, strlen($m[1]));
3253 return $num == 1 ? $result[0] : $result;
3256 private function _xor($string, $string2)
3259 $size = strlen($string);
3261 for ($i=0; $i<$size; $i++) {
3262 $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3269 * Converts datetime string into unix timestamp
3271 * @param string $date Date string
3273 * @return int Unix timestamp
3275 static function strToTime($date)
3277 // support non-standard "GMTXXXX" literal
3278 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3280 // if date parsing fails, we have a date in non-rfc format
3281 // remove token from the end and try again
3282 while (($ts = intval(@strtotime($date))) <= 0) {
3283 $d = explode(' ', $date);
3288 $date = implode(' ', $d);
3291 return $ts < 0 ? 0 : $ts;
3294 private function parseCapability($str, $trusted=false)
3296 $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3298 $this->capability = explode(' ', strtoupper($str));
3300 if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3301 $this->prefs['literal+'] = true;
3305 $this->capability_readed = true;
3310 * Escapes a string when it contains special characters (RFC3501)
3312 * @param string $string IMAP string
3313 * @param boolean $force_quotes Forces string quoting (for atoms)
3315 * @return string String atom, quoted-string or string literal
3318 static function escape($string, $force_quotes=false)
3320 if ($string === null) {
3323 if ($string === '') {
3326 // atom-string (only safe characters)
3327 if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
3331 if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
3332 return '"' . addcslashes($string, '\\"') . '"';
3336 return sprintf("{%d}\r\n%s", strlen($string), $string);
3339 static function unEscape($string)
3341 return stripslashes($string);
3345 * Set the value of the debugging flag.
3347 * @param boolean $debug New value for the debugging flag.
3352 function setDebug($debug, $handler = null)
3354 $this->_debug = $debug;
3355 $this->_debug_handler = $handler;
3359 * Write the given debug text to the current debug output handler.
3361 * @param string $message Debug mesage text.
3366 private function debug($message)
3368 if ($this->resourceid) {
3369 $message = sprintf('[%s] %s', $this->resourceid, $message);
3372 if ($this->_debug_handler) {
3373 call_user_func_array($this->_debug_handler, array(&$this, $message));
3375 echo "DEBUG: $message\n";