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 | Copyright (C) 2011, Kolab Systems AG |
10 | Licensed under the GNU GPL |
13 | Provide alternative IMAP library that doesn't rely on the standard |
14 | C-Client based version. This allows to function regardless |
15 | of whether or not the PHP build it's running on has IMAP |
16 | functionality built-in. |
18 | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
20 +-----------------------------------------------------------------------+
21 | Author: Aleksander Machniak <alec@alec.pl> |
22 | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
23 +-----------------------------------------------------------------------+
25 $Id: rcube_imap_generic.php 5970 2012-03-06 19:43:49Z alec $
31 * Struct representing an e-mail message header
34 * @author Aleksander Machniak <alec@alec.pl>
36 class rcube_mail_header
53 public $bodystructure;
58 public $others = array();
59 public $flags = array();
62 // For backward compatibility with cached messages (#1486602)
63 class iilBasicHeader extends rcube_mail_header
68 * PHP based wrapper class to connect to an IMAP server
71 * @author Aleksander Machniak <alec@alec.pl>
73 class rcube_imap_generic
80 public $data = array();
81 public $flags = array(
83 'DELETED' => '\\Deleted',
84 'ANSWERED' => '\\Answered',
86 'FLAGGED' => '\\Flagged',
87 'FORWARDED' => '$Forwarded',
88 'MDNSENT' => '$MDNSent',
94 private $logged = false;
95 private $capability = array();
96 private $capability_readed = false;
101 private $_debug = false;
102 private $_debug_handler = false;
106 const ERROR_BAD = -2;
107 const ERROR_BYE = -3;
108 const ERROR_UNKNOWN = -4;
109 const ERROR_COMMAND = -5;
110 const ERROR_READONLY = -6;
112 const COMMAND_NORESPONSE = 1;
113 const COMMAND_CAPABILITY = 2;
114 const COMMAND_LASTLINE = 4;
119 function __construct()
124 * Send simple (one line) command to the connection stream
126 * @param string $string Command string
127 * @param bool $endln True if CRLF need to be added at the end of command
129 * @param int Number of bytes sent, False on error
131 function putLine($string, $endln=true)
137 $this->debug('C: '. rtrim($string));
140 $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
142 if ($res === false) {
151 * Send command to the connection stream with Command Continuation
152 * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
154 * @param string $string Command string
155 * @param bool $endln True if CRLF need to be added at the end of command
157 * @param int Number of bytes sent, False on error
159 function putLineC($string, $endln=true)
169 if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
170 for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
171 if (preg_match('/^\{([0-9]+)\}\r\n$/', $parts[$i+1], $matches)) {
173 if ($this->prefs['literal+']) {
174 $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
177 $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
178 if ($bytes === false)
182 // don't wait if server supports LITERAL+ capability
183 if (!$this->prefs['literal+']) {
184 $line = $this->readLine(1000);
185 // handle error in command
192 $bytes = $this->putLine($parts[$i], false);
193 if ($bytes === false)
202 function readLine($size=1024)
212 return $line ? $line : NULL;
215 $buffer = fgets($this->fp, $size);
217 if ($buffer === false) {
218 $this->closeSocket();
222 $this->debug('S: '. rtrim($buffer));
225 } while (substr($buffer, -1) != "\n");
230 function multLine($line, $escape = false)
232 $line = rtrim($line);
233 if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
235 $str = substr($line, 0, -strlen($m[0]));
238 while (strlen($out) < $bytes) {
239 $line = $this->readBytes($bytes);
245 $line = $str . ($escape ? $this->escape($out) : $out);
251 function readBytes($bytes)
255 while ($len < $bytes && !$this->eof())
257 $d = fread($this->fp, $bytes-$len);
259 $this->debug('S: '. $d);
262 $data_len = strlen($data);
263 if ($len == $data_len) {
264 break; // nothing was read -> exit to avoid apache lockups
272 function readReply(&$untagged=null)
275 $line = trim($this->readLine(1024));
276 // store untagged response lines
279 } while ($line[0] == '*');
282 $untagged = join("\n", $untagged);
287 function parseResult($string, $err_prefix='')
289 if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
290 $res = strtoupper($matches[1]);
291 $str = trim($matches[2]);
294 $this->errornum = self::ERROR_OK;
295 } else if ($res == 'NO') {
296 $this->errornum = self::ERROR_NO;
297 } else if ($res == 'BAD') {
298 $this->errornum = self::ERROR_BAD;
299 } else if ($res == 'BYE') {
300 $this->closeSocket();
301 $this->errornum = self::ERROR_BYE;
306 // get response string and code (RFC5530)
307 if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
308 $this->resultcode = strtoupper($m[1]);
309 $str = trim(substr($str, strlen($m[1]) + 2));
312 $this->resultcode = null;
313 // parse response for [APPENDUID 1204196876 3456]
314 if (preg_match("/^\[APPENDUID [0-9]+ ([0-9,:*]+)\]/i", $str, $m)) {
315 $this->data['APPENDUID'] = $m[1];
318 $this->result = $str;
320 if ($this->errornum != self::ERROR_OK) {
321 $this->error = $err_prefix ? $err_prefix.$str : $str;
325 return $this->errornum;
327 return self::ERROR_UNKNOWN;
330 private function eof()
332 if (!is_resource($this->fp)) {
336 // If a connection opened by fsockopen() wasn't closed
337 // by the server, feof() will hang.
338 $start = microtime(true);
340 if (feof($this->fp) ||
341 ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
343 $this->closeSocket();
350 private function closeSocket()
356 function setError($code, $msg='')
358 $this->errornum = $code;
362 // check if $string starts with $match (or * BYE/BAD)
363 function startsWith($string, $match, $error=false, $nonempty=false)
365 $len = strlen($match);
372 if (strncmp($string, $match, $len) == 0) {
375 if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
376 if (strtoupper($m[1]) == 'BYE') {
377 $this->closeSocket();
381 if ($nonempty && !strlen($string)) {
387 private function hasCapability($name)
389 if (empty($this->capability) || $name == '') {
393 if (in_array($name, $this->capability)) {
396 else if (strpos($name, '=')) {
401 foreach ($this->capability as $cap) {
402 $entry = explode('=', $cap);
403 if ($entry[0] == $name) {
404 $result[] = $entry[1];
408 return !empty($result) ? $result : false;
412 * Capabilities checker
414 * @param string $name Capability name
416 * @return mixed Capability values array for key=value pairs, true/false for others
418 function getCapability($name)
420 $result = $this->hasCapability($name);
422 if (!empty($result)) {
425 else if ($this->capability_readed) {
429 // get capabilities (only once) because initial
430 // optional CAPABILITY response may differ
431 $result = $this->execute('CAPABILITY');
433 if ($result[0] == self::ERROR_OK) {
434 $this->parseCapability($result[1]);
437 $this->capability_readed = true;
439 return $this->hasCapability($name);
442 function clearCapability()
444 $this->capability = array();
445 $this->capability_readed = false;
449 * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
451 * @param string $user
452 * @param string $pass
453 * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
455 * @return resource Connection resourse on success, error code on error
457 function authenticate($user, $pass, $type='PLAIN')
459 if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
460 if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
461 $this->setError(self::ERROR_BYE,
462 "The Auth_SASL package is required for DIGEST-MD5 authentication");
463 return self::ERROR_BAD;
466 $this->putLine($this->nextTag() . " AUTHENTICATE $type");
467 $line = trim($this->readReply());
469 if ($line[0] == '+') {
470 $challenge = substr($line, 2);
473 return $this->parseResult($line);
476 if ($type == 'CRAM-MD5') {
481 // initialize ipad, opad
482 for ($i=0; $i<64; $i++) {
487 // pad $pass so it's 64 bytes
488 $padLen = 64 - strlen($pass);
489 for ($i=0; $i<$padLen; $i++) {
494 $hash = md5($this->_xor($pass, $opad) . pack("H*",
495 md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
496 $reply = base64_encode($user . ' ' . $hash);
499 $this->putLine($reply);
502 // RFC2831: DIGEST-MD5
503 // proxy authorization
504 if (!empty($this->prefs['auth_cid'])) {
505 $authc = $this->prefs['auth_cid'];
506 $pass = $this->prefs['auth_pw'];
511 $auth_sasl = Auth_SASL::factory('digestmd5');
512 $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
513 base64_decode($challenge), $this->host, 'imap', $user));
516 $this->putLine($reply);
517 $line = trim($this->readReply());
519 if ($line[0] == '+') {
520 $challenge = substr($line, 2);
523 return $this->parseResult($line);
527 $challenge = base64_decode($challenge);
528 if (strpos($challenge, 'rspauth=') === false) {
529 $this->setError(self::ERROR_BAD,
530 "Unexpected response from server to DIGEST-MD5 response");
531 return self::ERROR_BAD;
537 $line = $this->readReply();
538 $result = $this->parseResult($line);
541 // proxy authorization
542 if (!empty($this->prefs['auth_cid'])) {
543 $authc = $this->prefs['auth_cid'];
544 $pass = $this->prefs['auth_pw'];
550 $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
552 // RFC 4959 (SASL-IR): save one round trip
553 if ($this->getCapability('SASL-IR')) {
554 list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
555 self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY);
558 $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
559 $line = trim($this->readReply());
561 if ($line[0] != '+') {
562 return $this->parseResult($line);
565 // send result, get reply and process it
566 $this->putLine($reply);
567 $line = $this->readReply();
568 $result = $this->parseResult($line);
572 if ($result == self::ERROR_OK) {
573 // optional CAPABILITY response
574 if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
575 $this->parseCapability($matches[1], true);
580 $this->setError($result, "AUTHENTICATE $type: $line");
587 * LOGIN Authentication
589 * @param string $user
590 * @param string $pass
592 * @return resource Connection resourse on success, error code on error
594 function login($user, $password)
596 list($code, $response) = $this->execute('LOGIN', array(
597 $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
599 // re-set capabilities list if untagged CAPABILITY response provided
600 if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
601 $this->parseCapability($matches[1], true);
604 if ($code == self::ERROR_OK) {
614 * @return string The delimiter
616 function getHierarchyDelimiter()
618 if ($this->prefs['delimiter']) {
619 return $this->prefs['delimiter'];
622 // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
623 list($code, $response) = $this->execute('LIST',
624 array($this->escape(''), $this->escape('')));
626 if ($code == self::ERROR_OK) {
627 $args = $this->tokenizeResponse($response, 4);
628 $delimiter = $args[3];
630 if (strlen($delimiter) > 0) {
631 return ($this->prefs['delimiter'] = $delimiter);
639 * NAMESPACE handler (RFC 2342)
641 * @return array Namespace data hash (personal, other, shared)
643 function getNamespace()
645 if (array_key_exists('namespace', $this->prefs)) {
646 return $this->prefs['namespace'];
649 if (!$this->getCapability('NAMESPACE')) {
650 return self::ERROR_BAD;
653 list($code, $response) = $this->execute('NAMESPACE');
655 if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
656 $data = $this->tokenizeResponse(substr($response, 11));
659 if (!is_array($data)) {
663 $this->prefs['namespace'] = array(
664 'personal' => $data[0],
666 'shared' => $data[2],
669 return $this->prefs['namespace'];
672 function connect($host, $user, $password, $options=null)
675 if (is_array($options)) {
676 $this->prefs = $options;
679 if (!empty($this->prefs['auth_type'])) {
680 $auth_method = strtoupper($this->prefs['auth_type']);
682 $auth_method = 'CHECK';
687 // initialize connection
689 $this->errornum = self::ERROR_OK;
690 $this->selected = null;
693 $this->logged = false;
697 $this->setError(self::ERROR_BAD, "Empty host");
701 $this->setError(self::ERROR_NO, "Empty user");
704 if (empty($password)) {
705 $this->setError(self::ERROR_NO, "Empty password");
709 if (!$this->prefs['port']) {
710 $this->prefs['port'] = 143;
713 if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
714 $host = $this->prefs['ssl_mode'] . '://' . $host;
717 if ($this->prefs['timeout'] <= 0) {
718 $this->prefs['timeout'] = ini_get('default_socket_timeout');
722 $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
725 $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
729 if ($this->prefs['timeout'] > 0)
730 stream_set_timeout($this->fp, $this->prefs['timeout']);
732 $line = trim(fgets($this->fp, 8192));
735 // set connection identifier for debug output
736 preg_match('/#([0-9]+)/', (string)$this->fp, $m);
737 $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));
740 $this->debug('S: '. $line);
743 // Connected to wrong port or connection error?
744 if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
746 $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
748 $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
750 $this->setError(self::ERROR_BAD, $error);
751 $this->closeConnection();
755 // RFC3501 [7.1] optional CAPABILITY response
756 if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
757 $this->parseCapability($matches[1], true);
761 if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
762 if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
763 $res = $this->execute('STARTTLS');
765 if ($res[0] != self::ERROR_OK) {
766 $this->closeConnection();
770 if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
771 $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
772 $this->closeConnection();
776 // Now we're secure, capabilities need to be reread
777 $this->clearCapability();
782 if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
783 $this->id($this->prefs['ident']);
786 $auth_methods = array();
789 // check for supported auth methods
790 if ($auth_method == 'CHECK') {
791 if ($auth_caps = $this->getCapability('AUTH')) {
792 $auth_methods = $auth_caps;
794 // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
795 $login_disabled = $this->getCapability('LOGINDISABLED');
796 if (($key = array_search('LOGIN', $auth_methods)) !== false) {
797 if ($login_disabled) {
798 unset($auth_methods[$key]);
801 else if (!$login_disabled) {
802 $auth_methods[] = 'LOGIN';
805 // Use best (for security) supported authentication method
806 foreach (array('DIGEST-MD5', 'CRAM-MD5', 'CRAM_MD5', 'PLAIN', 'LOGIN') as $auth_method) {
807 if (in_array($auth_method, $auth_methods)) {
813 // Prevent from sending credentials in plain text when connection is not secure
814 if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
815 $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
816 $this->closeConnection();
819 // replace AUTH with CRAM-MD5 for backward compat.
820 if ($auth_method == 'AUTH') {
821 $auth_method = 'CRAM-MD5';
825 // pre-login capabilities can be not complete
826 $this->capability_readed = false;
829 switch ($auth_method) {
831 $auth_method = 'CRAM-MD5';
835 $result = $this->authenticate($user, $password, $auth_method);
838 $result = $this->login($user, $password);
841 $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
844 // Connected and authenticated
845 if (is_resource($result)) {
846 if ($this->prefs['force_caps']) {
847 $this->clearCapability();
849 $this->logged = true;
854 $this->closeConnection();
861 return ($this->fp && $this->logged) ? true : false;
864 function closeConnection()
866 if ($this->putLine($this->nextTag() . ' LOGOUT')) {
870 $this->closeSocket();
874 * Executes SELECT command (if mailbox is already not in selected state)
876 * @param string $mailbox Mailbox name
877 * @param array $qresync_data QRESYNC data (RFC5162)
879 * @return boolean True on success, false on error
881 function select($mailbox, $qresync_data = null)
883 if (!strlen($mailbox)) {
887 if ($this->selected === $mailbox) {
891 Temporary commented out because Courier returns \Noselect for INBOX
892 Requires more investigation
894 if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
895 if (in_array('\\Noselect', $opts)) {
900 $params = array($this->escape($mailbox));
902 // QRESYNC data items
903 // 0. the last known UIDVALIDITY,
904 // 1. the last known modification sequence,
905 // 2. the optional set of known UIDs, and
906 // 3. an optional parenthesized list of known sequence ranges and their
907 // corresponding UIDs.
908 if (!empty($qresync_data)) {
909 if (!empty($qresync_data[2]))
910 $qresync_data[2] = self::compressMessageSet($qresync_data[2]);
911 $params[] = array('QRESYNC', $qresync_data);
914 list($code, $response) = $this->execute('SELECT', $params);
916 if ($code == self::ERROR_OK) {
917 $response = explode("\r\n", $response);
918 foreach ($response as $line) {
919 if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
920 $this->data[strtoupper($m[2])] = (int) $m[1];
922 else if (preg_match('/^\* OK \[/i', $line, $match)) {
923 $line = substr($line, 6);
924 if (preg_match('/^(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)/i', $line, $match)) {
925 $this->data[strtoupper($match[1])] = (int) $match[2];
927 else if (preg_match('/^(HIGHESTMODSEQ) ([0-9]+)/i', $line, $match)) {
928 $this->data[strtoupper($match[1])] = (string) $match[2];
930 else if (preg_match('/^(NOMODSEQ)/i', $line, $match)) {
931 $this->data[strtoupper($match[1])] = true;
933 else if (preg_match('/^PERMANENTFLAGS \(([^\)]+)\)/iU', $line, $match)) {
934 $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
937 // QRESYNC FETCH response (RFC5162)
938 else if (preg_match('/^\* ([0-9+]) FETCH/i', $line, $match)) {
939 $line = substr($line, strlen($match[0]));
940 $fetch_data = $this->tokenizeResponse($line, 1);
941 $data = array('id' => $match[1]);
943 for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
944 $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
947 $this->data['QRESYNC'][$data['uid']] = $data;
949 // QRESYNC VANISHED response (RFC5162)
950 else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
951 $line = substr($line, strlen($match[0]));
952 $v_data = $this->tokenizeResponse($line, 1);
954 $this->data['VANISHED'] = $v_data;
958 $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
960 $this->selected = $mailbox;
968 * Executes STATUS command
970 * @param string $mailbox Mailbox name
971 * @param array $items Additional requested item names. By default
972 * MESSAGES and UNSEEN are requested. Other defined
973 * in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
975 * @return array Status item-value hash
978 function status($mailbox, $items=array())
980 if (!strlen($mailbox)) {
984 if (!in_array('MESSAGES', $items)) {
985 $items[] = 'MESSAGES';
987 if (!in_array('UNSEEN', $items)) {
991 list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
992 '(' . implode(' ', (array) $items) . ')'));
994 if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
996 $response = substr($response, 9); // remove prefix "* STATUS "
998 list($mbox, $items) = $this->tokenizeResponse($response, 2);
1000 // Fix for #1487859. Some buggy server returns not quoted
1001 // folder name with spaces. Let's try to handle this situation
1002 if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
1003 $response = substr($response, $pos);
1004 $items = $this->tokenizeResponse($response, 1);
1005 if (!is_array($items)) {
1010 for ($i=0, $len=count($items); $i<$len; $i += 2) {
1011 $result[$items[$i]] = $items[$i+1];
1014 $this->data['STATUS:'.$mailbox] = $result;
1023 * Executes EXPUNGE command
1025 * @param string $mailbox Mailbox name
1026 * @param string $messages Message UIDs to expunge
1028 * @return boolean True on success, False on error
1030 function expunge($mailbox, $messages=NULL)
1032 if (!$this->select($mailbox)) {
1036 if (!$this->data['READ-WRITE']) {
1037 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
1041 // Clear internal status cache
1042 unset($this->data['STATUS:'.$mailbox]);
1045 $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
1047 $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
1049 if ($result == self::ERROR_OK) {
1050 $this->selected = null; // state has changed, need to reselect
1058 * Executes CLOSE command
1060 * @return boolean True on success, False on error
1065 $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
1067 if ($result == self::ERROR_OK) {
1068 $this->selected = null;
1076 * Executes SUBSCRIBE command
1078 * @param string $mailbox Mailbox name
1080 * @return boolean True on success, False on error
1082 function subscribe($mailbox)
1084 $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1085 self::COMMAND_NORESPONSE);
1087 return ($result == self::ERROR_OK);
1091 * Executes UNSUBSCRIBE command
1093 * @param string $mailbox Mailbox name
1095 * @return boolean True on success, False on error
1097 function unsubscribe($mailbox)
1099 $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1100 self::COMMAND_NORESPONSE);
1102 return ($result == self::ERROR_OK);
1106 * Executes DELETE command
1108 * @param string $mailbox Mailbox name
1110 * @return boolean True on success, False on error
1112 function deleteFolder($mailbox)
1114 $result = $this->execute('DELETE', array($this->escape($mailbox)),
1115 self::COMMAND_NORESPONSE);
1117 return ($result == self::ERROR_OK);
1121 * Removes all messages in a folder
1123 * @param string $mailbox Mailbox name
1125 * @return boolean True on success, False on error
1127 function clearFolder($mailbox)
1129 $num_in_trash = $this->countMessages($mailbox);
1130 if ($num_in_trash > 0) {
1131 $res = $this->delete($mailbox, '1:*');
1135 if ($this->selected === $mailbox)
1136 $res = $this->close();
1138 $res = $this->expunge($mailbox);
1145 * Returns count of all messages in a folder
1147 * @param string $mailbox Mailbox name
1149 * @return int Number of messages, False on error
1151 function countMessages($mailbox, $refresh = false)
1154 $this->selected = null;
1157 if ($this->selected === $mailbox) {
1158 return $this->data['EXISTS'];
1161 // Check internal cache
1162 $cache = $this->data['STATUS:'.$mailbox];
1163 if (!empty($cache) && isset($cache['MESSAGES'])) {
1164 return (int) $cache['MESSAGES'];
1167 // Try STATUS (should be faster than SELECT)
1168 $counts = $this->status($mailbox);
1169 if (is_array($counts)) {
1170 return (int) $counts['MESSAGES'];
1177 * Returns count of messages with \Recent flag in a folder
1179 * @param string $mailbox Mailbox name
1181 * @return int Number of messages, False on error
1183 function countRecent($mailbox)
1185 if (!strlen($mailbox)) {
1189 $this->select($mailbox);
1191 if ($this->selected === $mailbox) {
1192 return $this->data['RECENT'];
1199 * Returns count of messages without \Seen flag in a specified folder
1201 * @param string $mailbox Mailbox name
1203 * @return int Number of messages, False on error
1205 function countUnseen($mailbox)
1207 // Check internal cache
1208 $cache = $this->data['STATUS:'.$mailbox];
1209 if (!empty($cache) && isset($cache['UNSEEN'])) {
1210 return (int) $cache['UNSEEN'];
1213 // Try STATUS (should be faster than SELECT+SEARCH)
1214 $counts = $this->status($mailbox);
1215 if (is_array($counts)) {
1216 return (int) $counts['UNSEEN'];
1219 // Invoke SEARCH as a fallback
1220 $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1221 if (is_array($index)) {
1222 return (int) $index['COUNT'];
1229 * Executes ID command (RFC2971)
1231 * @param array $items Client identification information key/value hash
1233 * @return array Server identification information key/value hash
1236 function id($items=array())
1238 if (is_array($items) && !empty($items)) {
1239 foreach ($items as $key => $value) {
1240 $args[] = $this->escape($key, true);
1241 $args[] = $this->escape($value, true);
1245 list($code, $response) = $this->execute('ID', array(
1246 !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1250 if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
1251 $response = substr($response, 5); // remove prefix "* ID "
1252 $items = $this->tokenizeResponse($response, 1);
1255 for ($i=0, $len=count($items); $i<$len; $i += 2) {
1256 $result[$items[$i]] = $items[$i+1];
1266 * Executes ENABLE command (RFC5161)
1268 * @param mixed $extension Extension name to enable (or array of names)
1270 * @return array|bool List of enabled extensions, False on error
1273 function enable($extension)
1275 if (empty($extension))
1278 if (!$this->hasCapability('ENABLE'))
1281 if (!is_array($extension))
1282 $extension = array($extension);
1284 list($code, $response) = $this->execute('ENABLE', $extension);
1286 if ($code == self::ERROR_OK && preg_match('/\* ENABLED /i', $response)) {
1287 $response = substr($response, 10); // remove prefix "* ENABLED "
1288 $result = (array) $this->tokenizeResponse($response);
1296 function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1298 $field = strtoupper($field);
1299 if ($field == 'INTERNALDATE') {
1303 $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1304 'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1306 if (!$fields[$field]) {
1310 if (!$this->select($mailbox)) {
1316 $add = $this->compressMessageSet($add);
1318 list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1319 array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1321 if ($code == self::ERROR_OK) {
1322 // remove prefix and unilateral untagged server responses
1323 $response = substr($response, stripos($response, '* SORT') + 7);
1324 if ($pos = strpos($response, '*')) {
1325 $response = substr($response, 0, $pos);
1327 return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1333 function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1335 if (is_array($message_set)) {
1336 if (!($message_set = $this->compressMessageSet($message_set)))
1339 list($from_idx, $to_idx) = explode(':', $message_set);
1340 if (empty($message_set) ||
1341 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1346 $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1348 $fields_a['DATE'] = 1;
1349 $fields_a['INTERNALDATE'] = 4;
1350 $fields_a['ARRIVAL'] = 4;
1351 $fields_a['FROM'] = 1;
1352 $fields_a['REPLY-TO'] = 1;
1353 $fields_a['SENDER'] = 1;
1354 $fields_a['TO'] = 1;
1355 $fields_a['CC'] = 1;
1356 $fields_a['SUBJECT'] = 1;
1357 $fields_a['UID'] = 2;
1358 $fields_a['SIZE'] = 2;
1359 $fields_a['SEEN'] = 3;
1360 $fields_a['RECENT'] = 3;
1361 $fields_a['DELETED'] = 3;
1363 if (!($mode = $fields_a[$index_field])) {
1367 /* Do "SELECT" command */
1368 if (!$this->select($mailbox)) {
1372 // build FETCH command string
1373 $key = $this->nextTag();
1374 $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
1375 $deleted = $skip_deleted ? ' FLAGS' : '';
1377 if ($mode == 1 && $index_field == 'DATE')
1378 $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1379 else if ($mode == 1)
1380 $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1381 else if ($mode == 2) {
1382 if ($index_field == 'SIZE')
1383 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1385 $request = " $cmd $message_set ($index_field$deleted)";
1386 } else if ($mode == 3)
1387 $request = " $cmd $message_set (FLAGS)";
1389 $request = " $cmd $message_set (INTERNALDATE$deleted)";
1391 $request = $key . $request;
1393 if (!$this->putLine($request)) {
1394 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1401 $line = rtrim($this->readLine(200));
1402 $line = $this->multLine($line);
1404 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1408 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1409 $flags = explode(' ', strtoupper($matches[1]));
1410 if (in_array('\\DELETED', $flags)) {
1411 $deleted[$id] = $id;
1416 if ($mode == 1 && $index_field == 'DATE') {
1417 if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1418 $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1419 $value = trim($value);
1420 $result[$id] = $this->strToTime($value);
1422 // non-existent/empty Date: header, use INTERNALDATE
1423 if (empty($result[$id])) {
1424 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1425 $result[$id] = $this->strToTime($matches[1]);
1429 } else if ($mode == 1) {
1430 if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1431 $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1432 $result[$id] = trim($value);
1436 } else if ($mode == 2) {
1437 if (preg_match('/(UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1438 $result[$id] = trim($matches[2]);
1442 } else if ($mode == 3) {
1443 if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1444 $flags = explode(' ', $matches[1]);
1446 $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1447 } else if ($mode == 4) {
1448 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1449 $result[$id] = $this->strToTime($matches[1]);
1455 } while (!$this->startsWith($line, $key, true, true));
1460 static function compressMessageSet($messages, $force=false)
1462 // given a comma delimited list of independent mid's,
1463 // compresses by grouping sequences together
1465 if (!is_array($messages)) {
1466 // if less than 255 bytes long, let's not bother
1467 if (!$force && strlen($messages)<255) {
1471 // see if it's already been compressed
1472 if (strpos($messages, ':') !== false) {
1476 // separate, then sort
1477 $messages = explode(',', $messages);
1483 $start = $prev = $messages[0];
1485 foreach ($messages as $id) {
1486 $incr = $id - $prev;
1487 if ($incr > 1) { // found a gap
1488 if ($start == $prev) {
1489 $result[] = $prev; // push single id
1491 $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1493 $start = $id; // start of new sequence
1498 // handle the last sequence/id
1499 if ($start == $prev) {
1502 $result[] = $start.':'.$prev;
1505 // return as comma separated string
1506 return implode(',', $result);
1509 static function uncompressMessageSet($messages)
1512 $messages = explode(',', $messages);
1514 foreach ($messages as $part) {
1515 $items = explode(':', $part);
1516 $max = max($items[0], $items[1]);
1518 for ($x=$items[0]; $x<=$max; $x++) {
1527 * Returns message sequence identifier
1529 * @param string $mailbox Mailbox name
1530 * @param int $uid Message unique identifier (UID)
1532 * @return int Message sequence identifier
1534 function UID2ID($mailbox, $uid)
1537 $id_a = $this->search($mailbox, "UID $uid");
1538 if (is_array($id_a) && count($id_a) == 1) {
1539 return (int) $id_a[0];
1546 * Returns message unique identifier (UID)
1548 * @param string $mailbox Mailbox name
1549 * @param int $uid Message sequence identifier
1551 * @return int Message unique identifier
1553 function ID2UID($mailbox, $id)
1555 if (empty($id) || $id < 0) {
1559 if (!$this->select($mailbox)) {
1562 // RFC 5957: SORT=DISPLAY
1563 if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
1564 $field = 'DISPLAY' . $field;
1568 list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1570 if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1577 function fetchUIDs($mailbox, $message_set=null)
1579 if (empty($message_set))
1580 $message_set = '1:*';
1582 return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1586 * FETCH command (RFC3501)
1588 * @param string $mailbox Mailbox name
1589 * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
1590 * @param bool $is_uid True if $message_set contains UIDs
1591 * @param array $query_items FETCH command data items
1592 * @param string $mod_seq Modification sequence for CHANGEDSINCE (RFC4551) query
1593 * @param bool $vanished Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
1595 * @return array List of rcube_mail_header elements, False on error
1598 function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
1599 $mod_seq = null, $vanished = false)
1601 if (!$this->select($mailbox)) {
1605 $message_set = $this->compressMessageSet($message_set);
1608 $key = $this->nextTag();
1609 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
1610 $request .= "(" . implode(' ', $query_items) . ")";
1612 if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
1613 $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
1616 if (!$this->putLine($request)) {
1617 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1622 $line = $this->readLine(4096);
1627 // Sample reply line:
1628 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1629 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1630 // BODY[HEADER.FIELDS ...
1632 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1633 $id = intval($m[1]);
1635 $result[$id] = new rcube_mail_header;
1636 $result[$id]->id = $id;
1637 $result[$id]->subject = '';
1638 $result[$id]->messageID = 'mid:' . $id;
1641 $line = substr($line, strlen($m[0]) + 2);
1644 // get complete entry
1645 while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
1649 while (strlen($out) < $bytes) {
1650 $out = $this->readBytes($bytes);
1656 $str = $this->readLine(4096);
1663 // Tokenize response and assign to object properties
1664 while (list($name, $value) = $this->tokenizeResponse($line, 2)) {
1665 if ($name == 'UID') {
1666 $result[$id]->uid = intval($value);
1668 else if ($name == 'RFC822.SIZE') {
1669 $result[$id]->size = intval($value);
1671 else if ($name == 'RFC822.TEXT') {
1672 $result[$id]->body = $value;
1674 else if ($name == 'INTERNALDATE') {
1675 $result[$id]->internaldate = $value;
1676 $result[$id]->date = $value;
1677 $result[$id]->timestamp = $this->StrToTime($value);
1679 else if ($name == 'FLAGS') {
1680 if (!empty($value)) {
1681 foreach ((array)$value as $flag) {
1682 $flag = str_replace(array('$', '\\'), '', $flag);
1683 $flag = strtoupper($flag);
1685 $result[$id]->flags[$flag] = true;
1689 else if ($name == 'MODSEQ') {
1690 $result[$id]->modseq = $value[0];
1692 else if ($name == 'ENVELOPE') {
1693 $result[$id]->envelope = $value;
1695 else if ($name == 'BODYSTRUCTURE' || ($name == 'BODY' && count($value) > 2)) {
1696 if (!is_array($value[0]) && (strtolower($value[0]) == 'message' && strtolower($value[1]) == 'rfc822')) {
1697 $value = array($value);
1699 $result[$id]->bodystructure = $value;
1701 else if ($name == 'RFC822') {
1702 $result[$id]->body = $value;
1704 else if ($name == 'BODY') {
1705 $body = $this->tokenizeResponse($line, 1);
1706 if ($value[0] == 'HEADER.FIELDS')
1708 else if (!empty($value))
1709 $result[$id]->bodypart[$value[0]] = $body;
1711 $result[$id]->body = $body;
1715 // create array with header field:data
1716 if (!empty($headers)) {
1717 $headers = explode("\n", trim($headers));
1718 foreach ($headers as $hid => $resln) {
1719 if (ord($resln[0]) <= 32) {
1720 $lines[$ln] .= (empty($lines[$ln]) ? '' : "\n") . trim($resln);
1722 $lines[++$ln] = trim($resln);
1726 while (list($lines_key, $str) = each($lines)) {
1727 list($field, $string) = explode(':', $str, 2);
1729 $field = strtolower($field);
1730 $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
1734 $result[$id]->date = $string;
1735 $result[$id]->timestamp = $this->strToTime($string);
1738 $result[$id]->from = $string;
1741 $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1744 $result[$id]->subject = $string;
1747 $result[$id]->replyto = $string;
1750 $result[$id]->cc = $string;
1753 $result[$id]->bcc = $string;
1755 case 'content-transfer-encoding':
1756 $result[$id]->encoding = $string;
1758 case 'content-type':
1759 $ctype_parts = preg_split('/[; ]/', $string);
1760 $result[$id]->ctype = strtolower(array_shift($ctype_parts));
1761 if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1762 $result[$id]->charset = $regs[1];
1766 $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1769 $result[$id]->references = $string;
1771 case 'return-receipt-to':
1772 case 'disposition-notification-to':
1773 case 'x-confirm-reading-to':
1774 $result[$id]->mdn_to = $string;
1777 $result[$id]->messageID = $string;
1780 if (preg_match('/^(\d+)/', $string, $matches)) {
1781 $result[$id]->priority = intval($matches[1]);
1785 if (strlen($field) > 2) {
1786 $result[$id]->others[$field] = $string;
1794 // VANISHED response (QRESYNC RFC5162)
1795 // Sample: * VANISHED (EARLIER) 300:310,405,411
1797 else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
1798 $line = substr($line, strlen($match[0]));
1799 $v_data = $this->tokenizeResponse($line, 1);
1801 $this->data['VANISHED'] = $v_data;
1804 } while (!$this->startsWith($line, $key, true));
1809 function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add = '')
1811 $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
1813 $query_items[] = 'BODYSTRUCTURE';
1814 $query_items[] = 'BODY.PEEK[HEADER.FIELDS ('
1815 . 'DATE FROM TO SUBJECT CONTENT-TYPE CC REPLY-TO LIST-POST DISPOSITION-NOTIFICATION-TO X-PRIORITY'
1816 . ($add ? ' ' . trim($add) : '')
1819 $result = $this->fetch($mailbox, $message_set, $is_uid, $query_items);
1824 function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1826 $a = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1828 return array_shift($a);
1833 function sortHeaders($a, $field, $flag)
1835 if (empty($field)) {
1839 $field = strtolower($field);
1842 if ($field == 'date' || $field == 'internaldate') {
1843 $field = 'timestamp';
1849 $flag = strtoupper($flag);
1855 // First, we'll create an "index" array.
1856 // Then, we'll use sort() on that array,
1857 // and use that to sort the main array.
1859 // create "index" array
1862 while (list($key, $val) = each($a)) {
1863 if ($field == 'timestamp') {
1864 $data = $this->strToTime($val->date);
1866 $data = $val->timestamp;
1869 $data = $val->$field;
1870 if (is_string($data)) {
1871 $data = str_replace('"', '', $data);
1872 if ($field == 'subject') {
1873 $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1875 $data = strtoupper($data);
1878 $index[$key] = $data;
1882 if ($flag == 'ASC') {
1888 // form new array based on index
1891 while (list($key, $val) = each($index)) {
1892 $result[$key] = $a[$key];
1900 function modFlag($mailbox, $messages, $flag, $mod)
1902 if ($mod != '+' && $mod != '-') {
1906 if (!$this->select($mailbox)) {
1910 if (!$this->data['READ-WRITE']) {
1911 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1915 // Clear internal status cache
1916 if ($flag == 'SEEN') {
1917 unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1920 $flag = $this->flags[strtoupper($flag)];
1921 $result = $this->execute('UID STORE', array(
1922 $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1923 self::COMMAND_NORESPONSE);
1925 return ($result == self::ERROR_OK);
1928 function flag($mailbox, $messages, $flag) {
1929 return $this->modFlag($mailbox, $messages, $flag, '+');
1932 function unflag($mailbox, $messages, $flag) {
1933 return $this->modFlag($mailbox, $messages, $flag, '-');
1936 function delete($mailbox, $messages) {
1937 return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1940 function copy($messages, $from, $to)
1942 if (!$this->select($from)) {
1946 // Clear internal status cache
1947 unset($this->data['STATUS:'.$to]);
1949 $result = $this->execute('UID COPY', array(
1950 $this->compressMessageSet($messages), $this->escape($to)),
1951 self::COMMAND_NORESPONSE);
1953 return ($result == self::ERROR_OK);
1956 function move($messages, $from, $to)
1958 if (!$this->select($from)) {
1962 if (!$this->data['READ-WRITE']) {
1963 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1967 $r = $this->copy($messages, $from, $to);
1970 // Clear internal status cache
1971 unset($this->data['STATUS:'.$from]);
1973 return $this->delete($from, $messages);
1978 // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1979 // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1980 // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1981 private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1984 if ($str[$begin] != '(') {
1985 $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1986 $msg = substr($str, $begin, $stop - $begin);
1991 $depthmap[$msg] = $depth;
1992 $haschildren[$msg] = false;
1993 if (!is_null($parent))
1994 $haschildren[$parent] = true;
1995 if ($stop + 1 < $end)
1996 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1998 $node[$msg] = array();
2001 while ($off < $end) {
2006 $p = strpos($str, ')', $off);
2008 error_log("Mismatched brackets parsing IMAP THREAD response:");
2009 error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
2010 error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
2013 $p1 = strpos($str, '(', $off);
2014 if ($p1 !== false && $p1 < $p) {
2022 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
2029 function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
2031 $old_sel = $this->selected;
2033 if (!$this->select($mailbox)) {
2037 // return empty result when folder is empty and we're just after SELECT
2038 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2039 return array(array(), array(), array());
2042 $encoding = $encoding ? trim($encoding) : 'US-ASCII';
2043 $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
2044 $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
2047 list($code, $response) = $this->execute('THREAD', array(
2048 $algorithm, $encoding, $criteria));
2050 if ($code == self::ERROR_OK) {
2052 $response = substr($response, stripos($response, '* THREAD') + 9);
2053 // ...unilateral untagged server responses
2054 if ($pos = strpos($response, '*')) {
2055 $response = substr($response, 0, $pos);
2058 $response = str_replace("\r\n", '', $response);
2059 $depthmap = array();
2060 $haschildren = array();
2062 $tree = $this->parseThread($response, 0, strlen($response),
2063 null, null, 0, $depthmap, $haschildren);
2065 return array($tree, $depthmap, $haschildren);
2072 * Executes SEARCH command
2074 * @param string $mailbox Mailbox name
2075 * @param string $criteria Searching criteria
2076 * @param bool $return_uid Enable UID in result instead of sequence ID
2077 * @param array $items Return items (MIN, MAX, COUNT, ALL)
2079 * @return array Message identifiers or item-value hash
2081 function search($mailbox, $criteria, $return_uid=false, $items=array())
2083 $old_sel = $this->selected;
2085 if (!$this->select($mailbox)) {
2089 // return empty result when folder is empty and we're just after SELECT
2090 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2092 return array_combine($items, array_fill(0, count($items), 0));
2097 $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
2098 $criteria = trim($criteria);
2102 if (!empty($items) && $esearch) {
2103 $params .= 'RETURN (' . implode(' ', $items) . ')';
2105 if (!empty($criteria)) {
2106 $modseq = stripos($criteria, 'MODSEQ') !== false;
2107 $params .= ($params ? ' ' : '') . $criteria;
2113 list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2116 if ($code == self::ERROR_OK) {
2118 $response = substr($response, stripos($response,
2119 $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
2120 // ...and unilateral untagged server responses
2121 if ($pos = strpos($response, '*')) {
2122 $response = rtrim(substr($response, 0, $pos));
2125 // remove MODSEQ response
2127 if (preg_match('/\(MODSEQ ([0-9]+)\)$/', $response, $m)) {
2128 $response = substr($response, 0, -strlen($m[0]));
2133 // Skip prefix: ... (TAG "A285") UID ...
2134 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2137 for ($i=0; $i<count($items); $i++) {
2138 // If the SEARCH returns no matches, the server MUST NOT
2139 // include the item result option in the ESEARCH response
2140 if ($ret = $this->tokenizeResponse($response, 2)) {
2141 list ($name, $value) = $ret;
2142 $result[$name] = $value;
2149 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2151 if (!empty($items)) {
2153 if (in_array('COUNT', $items)) {
2154 $result['COUNT'] = count($response);
2156 if (in_array('MIN', $items)) {
2157 $result['MIN'] = !empty($response) ? min($response) : 0;
2159 if (in_array('MAX', $items)) {
2160 $result['MAX'] = !empty($response) ? max($response) : 0;
2162 if (in_array('ALL', $items)) {
2163 $result['ALL'] = $this->compressMessageSet($response, true);
2178 * Returns list of mailboxes
2180 * @param string $ref Reference name
2181 * @param string $mailbox Mailbox name
2182 * @param array $status_opts (see self::_listMailboxes)
2183 * @param array $select_opts (see self::_listMailboxes)
2185 * @return array List of mailboxes or hash of options if $status_opts argument
2188 function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2190 return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2194 * Returns list of subscribed mailboxes
2196 * @param string $ref Reference name
2197 * @param string $mailbox Mailbox name
2198 * @param array $status_opts (see self::_listMailboxes)
2200 * @return array List of mailboxes or hash of options if $status_opts argument
2203 function listSubscribed($ref, $mailbox, $status_opts=array())
2205 return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2209 * IMAP LIST/LSUB command
2211 * @param string $ref Reference name
2212 * @param string $mailbox Mailbox name
2213 * @param bool $subscribed Enables returning subscribed mailboxes only
2214 * @param array $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2215 * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2216 * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2217 * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2219 * @return array List of mailboxes or hash of options if $status_ops argument
2222 private function _listMailboxes($ref, $mailbox, $subscribed=false,
2223 $status_opts=array(), $select_opts=array())
2225 if (!strlen($mailbox)) {
2231 if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2232 $select_opts = (array) $select_opts;
2234 $args[] = '(' . implode(' ', $select_opts) . ')';
2237 $args[] = $this->escape($ref);
2238 $args[] = $this->escape($mailbox);
2240 if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2241 $status_opts = (array) $status_opts;
2244 $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2247 list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2249 if ($code == self::ERROR_OK) {
2253 $response .= "\r\n";
2255 while ($pos = strpos($response, "\r\n", $pos+1)) {
2256 // literal string, not real end-of-command-line
2257 if ($response[$pos-1] == '}') {
2261 $line = substr($response, $last, $pos - $last);
2264 if (!preg_match('/^\* (LIST|LSUB|STATUS) /i', $line, $m)) {
2267 $cmd = strtoupper($m[1]);
2268 $line = substr($line, strlen($m[0]));
2270 // * LIST (<options>) <delimiter> <mailbox>
2271 if ($cmd == 'LIST' || $cmd == 'LSUB') {
2272 list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
2274 // Add to result array
2276 $folders[] = $mailbox;
2279 $folders[$mailbox] = array();
2282 // store LSUB options only if not empty, this way
2283 // we can detect a situation when LIST doesn't return specified folder
2284 if (!empty($opts) || $cmd == 'LIST') {
2285 // Add to options array
2286 if (empty($this->data['LIST'][$mailbox]))
2287 $this->data['LIST'][$mailbox] = $opts;
2288 else if (!empty($opts))
2289 $this->data['LIST'][$mailbox] = array_unique(array_merge(
2290 $this->data['LIST'][$mailbox], $opts));
2293 // * STATUS <mailbox> (<result>)
2294 else if ($cmd == 'STATUS') {
2295 list($mailbox, $status) = $this->tokenizeResponse($line, 2);
2297 for ($i=0, $len=count($status); $i<$len; $i += 2) {
2298 list($name, $value) = $this->tokenizeResponse($status, 2);
2299 $folders[$mailbox][$name] = $value;
2310 function fetchMIMEHeaders($mailbox, $uid, $parts, $mime=true)
2312 if (!$this->select($mailbox)) {
2317 $parts = (array) $parts;
2318 $key = $this->nextTag();
2320 $type = $mime ? 'MIME' : 'HEADER';
2323 foreach ($parts as $part) {
2324 $peeks[] = "BODY.PEEK[$part.$type]";
2327 $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
2330 if (!$this->putLine($request)) {
2331 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2336 $line = $this->readLine(1024);
2338 if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2342 // get complete entry
2343 if (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
2347 while (strlen($out) < $bytes) {
2348 $out = $this->readBytes($bytes);
2355 $result[$idx] = trim($headers);
2357 } while (!$this->startsWith($line, $key, true));
2362 function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2364 $part = empty($part) ? 'HEADER' : $part.'.MIME';
2366 return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2369 function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2371 if (!$this->select($mailbox)) {
2375 switch ($encoding) {
2379 case 'quoted-printable':
2393 $reply_key = '* ' . $id;
2394 $key = $this->nextTag();
2395 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2398 if (!$this->putLine($request)) {
2399 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2403 // receive reply line
2405 $line = rtrim($this->readLine(1024));
2406 $a = explode(' ', $line);
2407 } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2409 $len = strlen($line);
2412 if ($a[2] != 'FETCH') {
2414 // handle empty "* X FETCH ()" response
2415 else if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2416 // one line response, get everything between first and last quotes
2417 if (substr($line, -4, 3) == 'NIL') {
2421 $from = strpos($line, '"') + 1;
2422 $to = strrpos($line, '"');
2424 $result = substr($line, $from, $len);
2428 $result = base64_decode($result);
2430 else if ($mode == 2) {
2431 $result = quoted_printable_decode($result);
2433 else if ($mode == 3) {
2434 $result = convert_uudecode($result);
2437 } else if ($line[$len-1] == '}') {
2438 // multi-line request, find sizes of content and receive that many bytes
2439 $from = strpos($line, '{') + 1;
2440 $to = strrpos($line, '}');
2442 $sizeStr = substr($line, $from, $len);
2443 $bytes = (int)$sizeStr;
2446 while ($bytes > 0) {
2447 $line = $this->readLine(4096);
2449 if ($line === NULL) {
2453 $len = strlen($line);
2455 if ($len > $bytes) {
2456 $line = substr($line, 0, $bytes);
2457 $len = strlen($line);
2463 $line = rtrim($line, "\t\r\n\0\x0B");
2464 // create chunks with proper length for base64 decoding
2465 $line = $prev.$line;
2466 $length = strlen($line);
2468 $length = floor($length / 4) * 4;
2469 $prev = substr($line, $length);
2470 $line = substr($line, 0, $length);
2474 $line = base64_decode($line);
2476 } else if ($mode == 2) {
2477 $line = rtrim($line, "\t\r\0\x0B");
2478 $line = quoted_printable_decode($line);
2480 } else if ($mode == 3) {
2481 $line = rtrim($line, "\t\r\n\0\x0B");
2482 if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2484 $line = convert_uudecode($line);
2487 $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2491 fwrite($file, $line);
2499 // read in anything up until last line
2502 $line = $this->readLine(1024);
2503 } while (!$this->startsWith($line, $key, true));
2505 if ($result !== false) {
2507 fwrite($file, $result);
2508 } else if ($print) {
2518 function createFolder($mailbox)
2520 $result = $this->execute('CREATE', array($this->escape($mailbox)),
2521 self::COMMAND_NORESPONSE);
2523 return ($result == self::ERROR_OK);
2526 function renameFolder($from, $to)
2528 $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2529 self::COMMAND_NORESPONSE);
2531 return ($result == self::ERROR_OK);
2535 * Handler for IMAP APPEND command
2537 * @param string $mailbox Mailbox name
2538 * @param string $message Message content
2540 * @return string|bool On success APPENDUID response (if available) or True, False on failure
2542 function append($mailbox, &$message)
2544 unset($this->data['APPENDUID']);
2550 $message = str_replace("\r", '', $message);
2551 $message = str_replace("\n", "\r\n", $message);
2553 $len = strlen($message);
2558 $key = $this->nextTag();
2559 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2560 $len, ($this->prefs['literal+'] ? '+' : ''));
2562 if ($this->putLine($request)) {
2563 // Don't wait when LITERAL+ is supported
2564 if (!$this->prefs['literal+']) {
2565 $line = $this->readReply();
2567 if ($line[0] != '+') {
2568 $this->parseResult($line, 'APPEND: ');
2573 if (!$this->putLine($message)) {
2578 $line = $this->readLine();
2579 } while (!$this->startsWith($line, $key, true, true));
2581 // Clear internal status cache
2582 unset($this->data['STATUS:'.$mailbox]);
2584 if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2586 else if (!empty($this->data['APPENDUID']))
2587 return $this->data['APPENDUID'];
2592 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2599 * Handler for IMAP APPEND command.
2601 * @param string $mailbox Mailbox name
2602 * @param string $path Path to the file with message body
2603 * @param string $headers Message headers
2605 * @return string|bool On success APPENDUID response (if available) or True, False on failure
2607 function appendFromFile($mailbox, $path, $headers=null)
2609 unset($this->data['APPENDUID']);
2615 // open message file
2617 if (file_exists(realpath($path))) {
2618 $in_fp = fopen($path, 'r');
2621 $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2625 $body_separator = "\r\n\r\n";
2626 $len = filesize($path);
2633 $headers = preg_replace('/[\r\n]+$/', '', $headers);
2634 $len += strlen($headers) + strlen($body_separator);
2637 // send APPEND command
2638 $key = $this->nextTag();
2639 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2640 $len, ($this->prefs['literal+'] ? '+' : ''));
2642 if ($this->putLine($request)) {
2643 // Don't wait when LITERAL+ is supported
2644 if (!$this->prefs['literal+']) {
2645 $line = $this->readReply();
2647 if ($line[0] != '+') {
2648 $this->parseResult($line, 'APPEND: ');
2653 // send headers with body separator
2655 $this->putLine($headers . $body_separator, false);
2659 while (!feof($in_fp) && $this->fp) {
2660 $buffer = fgets($in_fp, 4096);
2661 $this->putLine($buffer, false);
2665 if (!$this->putLine('')) { // \r\n
2671 $line = $this->readLine();
2672 } while (!$this->startsWith($line, $key, true, true));
2674 // Clear internal status cache
2675 unset($this->data['STATUS:'.$mailbox]);
2677 if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2679 else if (!empty($this->data['APPENDUID']))
2680 return $this->data['APPENDUID'];
2685 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2694 * GETQUOTAROOT "INBOX"
2695 * QUOTAROOT INBOX user/rchijiiwa1
2696 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2700 $quota_lines = array();
2701 $key = $this->nextTag();
2702 $command = $key . ' GETQUOTAROOT INBOX';
2704 // get line(s) containing quota info
2705 if ($this->putLine($command)) {
2707 $line = rtrim($this->readLine(5000));
2708 if (preg_match('/^\* QUOTA /', $line)) {
2709 $quota_lines[] = $line;
2711 } while (!$this->startsWith($line, $key, true, true));
2714 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2717 // return false if not found, parse if found
2718 $min_free = PHP_INT_MAX;
2719 foreach ($quota_lines as $key => $quota_line) {
2720 $quota_line = str_replace(array('(', ')'), '', $quota_line);
2721 $parts = explode(' ', $quota_line);
2722 $storage_part = array_search('STORAGE', $parts);
2724 if (!$storage_part) {
2728 $used = intval($parts[$storage_part+1]);
2729 $total = intval($parts[$storage_part+2]);
2730 $free = $total - $used;
2732 // return lowest available space from all quotas
2733 if ($free < $min_free) {
2735 $result['used'] = $used;
2736 $result['total'] = $total;
2737 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2738 $result['free'] = 100 - $result['percent'];
2746 * Send the SETACL command (RFC4314)
2748 * @param string $mailbox Mailbox name
2749 * @param string $user User name
2750 * @param mixed $acl ACL string or array
2752 * @return boolean True on success, False on failure
2756 function setACL($mailbox, $user, $acl)
2758 if (is_array($acl)) {
2759 $acl = implode('', $acl);
2762 $result = $this->execute('SETACL', array(
2763 $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2764 self::COMMAND_NORESPONSE);
2766 return ($result == self::ERROR_OK);
2770 * Send the DELETEACL command (RFC4314)
2772 * @param string $mailbox Mailbox name
2773 * @param string $user User name
2775 * @return boolean True on success, False on failure
2779 function deleteACL($mailbox, $user)
2781 $result = $this->execute('DELETEACL', array(
2782 $this->escape($mailbox), $this->escape($user)),
2783 self::COMMAND_NORESPONSE);
2785 return ($result == self::ERROR_OK);
2789 * Send the GETACL command (RFC4314)
2791 * @param string $mailbox Mailbox name
2793 * @return array User-rights array on success, NULL on error
2796 function getACL($mailbox)
2798 list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2800 if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2801 // Parse server response (remove "* ACL ")
2802 $response = substr($response, 6);
2803 $ret = $this->tokenizeResponse($response);
2804 $mbox = array_shift($ret);
2805 $size = count($ret);
2807 // Create user-rights hash array
2808 // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2809 // so we could return only standard rights defined in RFC4314,
2810 // excluding 'c' and 'd' defined in RFC2086.
2811 if ($size % 2 == 0) {
2812 for ($i=0; $i<$size; $i++) {
2813 $ret[$ret[$i]] = str_split($ret[++$i]);
2820 $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2828 * Send the LISTRIGHTS command (RFC4314)
2830 * @param string $mailbox Mailbox name
2831 * @param string $user User name
2833 * @return array List of user rights
2836 function listRights($mailbox, $user)
2838 list($code, $response) = $this->execute('LISTRIGHTS', array(
2839 $this->escape($mailbox), $this->escape($user)));
2841 if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2842 // Parse server response (remove "* LISTRIGHTS ")
2843 $response = substr($response, 13);
2845 $ret_mbox = $this->tokenizeResponse($response, 1);
2846 $ret_user = $this->tokenizeResponse($response, 1);
2847 $granted = $this->tokenizeResponse($response, 1);
2848 $optional = trim($response);
2851 'granted' => str_split($granted),
2852 'optional' => explode(' ', $optional),
2860 * Send the MYRIGHTS command (RFC4314)
2862 * @param string $mailbox Mailbox name
2864 * @return array MYRIGHTS response on success, NULL on error
2867 function myRights($mailbox)
2869 list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2871 if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2872 // Parse server response (remove "* MYRIGHTS ")
2873 $response = substr($response, 11);
2875 $ret_mbox = $this->tokenizeResponse($response, 1);
2876 $rights = $this->tokenizeResponse($response, 1);
2878 return str_split($rights);
2885 * Send the SETMETADATA command (RFC5464)
2887 * @param string $mailbox Mailbox name
2888 * @param array $entries Entry-value array (use NULL value as NIL)
2890 * @return boolean True on success, False on failure
2893 function setMetadata($mailbox, $entries)
2895 if (!is_array($entries) || empty($entries)) {
2896 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2900 foreach ($entries as $name => $value) {
2901 $entries[$name] = $this->escape($name) . ' ' . $this->escape($value);
2904 $entries = implode(' ', $entries);
2905 $result = $this->execute('SETMETADATA', array(
2906 $this->escape($mailbox), '(' . $entries . ')'),
2907 self::COMMAND_NORESPONSE);
2909 return ($result == self::ERROR_OK);
2913 * Send the SETMETADATA command with NIL values (RFC5464)
2915 * @param string $mailbox Mailbox name
2916 * @param array $entries Entry names array
2918 * @return boolean True on success, False on failure
2922 function deleteMetadata($mailbox, $entries)
2924 if (!is_array($entries) && !empty($entries)) {
2925 $entries = explode(' ', $entries);
2928 if (empty($entries)) {
2929 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2933 foreach ($entries as $entry) {
2934 $data[$entry] = NULL;
2937 return $this->setMetadata($mailbox, $data);
2941 * Send the GETMETADATA command (RFC5464)
2943 * @param string $mailbox Mailbox name
2944 * @param array $entries Entries
2945 * @param array $options Command options (with MAXSIZE and DEPTH keys)
2947 * @return array GETMETADATA result on success, NULL on error
2951 function getMetadata($mailbox, $entries, $options=array())
2953 if (!is_array($entries)) {
2954 $entries = array($entries);
2957 // create entries string
2958 foreach ($entries as $idx => $name) {
2959 $entries[$idx] = $this->escape($name);
2963 $entlist = '(' . implode(' ', $entries) . ')';
2965 // create options string
2966 if (is_array($options)) {
2967 $options = array_change_key_case($options, CASE_UPPER);
2970 if (!empty($options['MAXSIZE'])) {
2971 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2973 if (!empty($options['DEPTH'])) {
2974 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2978 $optlist = '(' . implode(' ', $opts) . ')';
2982 $optlist .= ($optlist ? ' ' : '') . $entlist;
2984 list($code, $response) = $this->execute('GETMETADATA', array(
2985 $this->escape($mailbox), $optlist));
2987 if ($code == self::ERROR_OK) {
2989 $data = $this->tokenizeResponse($response);
2991 // The METADATA response can contain multiple entries in a single
2992 // response or multiple responses for each entry or group of entries
2993 if (!empty($data) && ($size = count($data))) {
2994 for ($i=0; $i<$size; $i++) {
2995 if (isset($mbox) && is_array($data[$i])) {
2996 $size_sub = count($data[$i]);
2997 for ($x=0; $x<$size_sub; $x++) {
2998 $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
3002 else if ($data[$i] == '*') {
3003 if ($data[$i+1] == 'METADATA') {
3004 $mbox = $data[$i+2];
3005 unset($data[$i]); // "*"
3006 unset($data[++$i]); // "METADATA"
3007 unset($data[++$i]); // Mailbox
3009 // get rid of other untagged responses
3015 else if (isset($mbox)) {
3016 $result[$mbox][$data[$i]] = $data[++$i];
3033 * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
3035 * @param string $mailbox Mailbox name
3036 * @param array $data Data array where each item is an array with
3037 * three elements: entry name, attribute name, value
3039 * @return boolean True on success, False on failure
3042 function setAnnotation($mailbox, $data)
3044 if (!is_array($data) || empty($data)) {
3045 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3049 foreach ($data as $entry) {
3050 // ANNOTATEMORE drafts before version 08 require quoted parameters
3051 $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
3052 $this->escape($entry[1], true), $this->escape($entry[2], true));
3055 $entries = implode(' ', $entries);
3056 $result = $this->execute('SETANNOTATION', array(
3057 $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
3059 return ($result == self::ERROR_OK);
3063 * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
3065 * @param string $mailbox Mailbox name
3066 * @param array $data Data array where each item is an array with
3067 * two elements: entry name and attribute name
3069 * @return boolean True on success, False on failure
3073 function deleteAnnotation($mailbox, $data)
3075 if (!is_array($data) || empty($data)) {
3076 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3080 return $this->setAnnotation($mailbox, $data);
3084 * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3086 * @param string $mailbox Mailbox name
3087 * @param array $entries Entries names
3088 * @param array $attribs Attribs names
3090 * @return array Annotations result on success, NULL on error
3094 function getAnnotation($mailbox, $entries, $attribs)
3096 if (!is_array($entries)) {
3097 $entries = array($entries);
3099 // create entries string
3100 // ANNOTATEMORE drafts before version 08 require quoted parameters
3101 foreach ($entries as $idx => $name) {
3102 $entries[$idx] = $this->escape($name, true);
3104 $entries = '(' . implode(' ', $entries) . ')';
3106 if (!is_array($attribs)) {
3107 $attribs = array($attribs);
3109 // create entries string
3110 foreach ($attribs as $idx => $name) {
3111 $attribs[$idx] = $this->escape($name, true);
3113 $attribs = '(' . implode(' ', $attribs) . ')';
3115 list($code, $response) = $this->execute('GETANNOTATION', array(
3116 $this->escape($mailbox), $entries, $attribs));
3118 if ($code == self::ERROR_OK) {
3120 $data = $this->tokenizeResponse($response);
3122 // Here we returns only data compatible with METADATA result format
3123 if (!empty($data) && ($size = count($data))) {
3124 for ($i=0; $i<$size; $i++) {
3126 if (isset($mbox) && is_array($entry)) {
3128 $entry = $last_entry;
3130 else if ($entry == '*') {
3131 if ($data[$i+1] == 'ANNOTATION') {
3132 $mbox = $data[$i+2];
3133 unset($data[$i]); // "*"
3134 unset($data[++$i]); // "ANNOTATION"
3135 unset($data[++$i]); // Mailbox
3137 // get rid of other untagged responses
3144 else if (isset($mbox)) {
3145 $attribs = $data[++$i];
3152 if (!empty($attribs)) {
3153 for ($x=0, $len=count($attribs); $x<$len;) {
3154 $attr = $attribs[$x++];
3155 $value = $attribs[$x++];
3156 if ($attr == 'value.priv') {
3157 $result[$mbox]['/private' . $entry] = $value;
3159 else if ($attr == 'value.shared') {
3160 $result[$mbox]['/shared' . $entry] = $value;
3164 $last_entry = $entry;
3176 * Returns BODYSTRUCTURE for the specified message.
3178 * @param string $mailbox Folder name
3179 * @param int $id Message sequence number or UID
3180 * @param bool $is_uid True if $id is an UID
3182 * @return array/bool Body structure array or False on error.
3185 function getStructure($mailbox, $id, $is_uid = false)
3187 $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
3188 if (is_array($result)) {
3189 $result = array_shift($result);
3190 return $result->bodystructure;
3196 * Returns data of a message part according to specified structure.
3198 * @param array $structure Message structure (getStructure() result)
3199 * @param string $part Message part identifier
3201 * @return array Part data as hash array (type, encoding, charset, size)
3203 static function getStructurePartData($structure, $part)
3205 $part_a = self::getStructurePartArray($structure, $part);
3208 if (empty($part_a)) {
3213 if (is_array($part_a[0])) {
3214 $data['type'] = 'multipart';
3217 $data['type'] = strtolower($part_a[0]);
3220 $data['encoding'] = strtolower($part_a[5]);
3223 if (is_array($part_a[2])) {
3224 while (list($key, $val) = each($part_a[2])) {
3225 if (strcasecmp($val, 'charset') == 0) {
3226 $data['charset'] = $part_a[2][$key+1];
3234 $data['size'] = intval($part_a[6]);
3239 static function getStructurePartArray($a, $part)
3241 if (!is_array($a)) {
3249 $ctype = is_string($a[0]) && is_string($a[1]) ? $a[0] . '/' . $a[1] : '';
3251 if (strcasecmp($ctype, 'message/rfc822') == 0) {
3255 if (strpos($part, '.') > 0) {
3257 $pos = strpos($part, '.');
3258 $rest = substr($orig_part, $pos+1);
3259 $part = substr($orig_part, 0, $pos);
3261 return self::getStructurePartArray($a[$part-1], $rest);
3263 else if ($part > 0) {
3264 if (is_array($a[$part-1]))
3272 * Creates next command identifier (tag)
3274 * @return string Command identifier
3280 $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3282 return $this->cmd_tag;
3286 * Sends IMAP command and parses result
3288 * @param string $command IMAP command
3289 * @param array $arguments Command arguments
3290 * @param int $options Execution options
3292 * @return mixed Response code or list of response code and data
3295 function execute($command, $arguments=array(), $options=0)
3297 $tag = $this->nextTag();
3298 $query = $tag . ' ' . $command;
3299 $noresp = ($options & self::COMMAND_NORESPONSE);
3300 $response = $noresp ? null : '';
3302 if (!empty($arguments)) {
3303 foreach ($arguments as $arg) {
3304 $query .= ' ' . self::r_implode($arg);
3309 if (!$this->putLineC($query)) {
3310 $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3311 return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3316 $line = $this->readLine(4096);
3317 if ($response !== null) {
3320 } while (!$this->startsWith($line, $tag . ' ', true, true));
3322 $code = $this->parseResult($line, $command . ': ');
3324 // Remove last line from response
3326 $line_len = min(strlen($response), strlen($line) + 2);
3327 $response = substr($response, 0, -$line_len);
3330 // optional CAPABILITY response
3331 if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3332 && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3334 $this->parseCapability($matches[1], true);
3337 // return last line only (without command tag, result and response code)
3338 if ($line && ($options & self::COMMAND_LASTLINE)) {
3339 $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3342 return $noresp ? $code : array($code, $response);
3346 * Splits IMAP response into string tokens
3348 * @param string &$str The IMAP's server response
3349 * @param int $num Number of tokens to return
3351 * @return mixed Tokens array or string if $num=1
3354 static function tokenizeResponse(&$str, $num=0)
3358 while (!$num || count($result) < $num) {
3359 // remove spaces from the beginning of the string
3366 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3369 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3372 $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
3373 // Advance the string
3374 $str = substr($str, $epos + 3 + $bytes);
3379 $len = strlen($str);
3381 for ($pos=1; $pos<$len; $pos++) {
3382 if ($str[$pos] == '"') {
3385 if ($str[$pos] == "\\") {
3386 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3391 if ($str[$pos] != '"') {
3394 // we need to strip slashes for a quoted string
3395 $result[] = stripslashes(substr($str, 1, $pos - 1));
3396 $str = substr($str, $pos + 1);
3399 // Parenthesized list
3402 $str = substr($str, 1);
3403 $result[] = self::tokenizeResponse($str);
3407 $str = substr($str, 1);
3411 // String atom, number, NIL, *, %
3414 if ($str === '' || $str === null) {
3418 // excluded chars: SP, CTL, ), [, ]
3419 if (preg_match('/^([^\x00-\x20\x29\x5B\x5D\x7F]+)/', $str, $m)) {
3420 $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3421 $str = substr($str, strlen($m[1]));
3427 return $num == 1 ? $result[0] : $result;
3430 static function r_implode($element)
3434 if (is_array($element)) {
3436 while (list($key, $value) = each($element)) {
3437 $string .= ' ' . self::r_implode($value);
3444 return '(' . trim($string) . ')';
3447 private function _xor($string, $string2)
3450 $size = strlen($string);
3452 for ($i=0; $i<$size; $i++) {
3453 $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3460 * Converts datetime string into unix timestamp
3462 * @param string $date Date string
3464 * @return int Unix timestamp
3466 static function strToTime($date)
3468 // support non-standard "GMTXXXX" literal
3469 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3471 // if date parsing fails, we have a date in non-rfc format
3472 // remove token from the end and try again
3473 while (($ts = intval(@strtotime($date))) <= 0) {
3474 $d = explode(' ', $date);
3479 $date = implode(' ', $d);
3482 return $ts < 0 ? 0 : $ts;
3485 private function parseCapability($str, $trusted=false)
3487 $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3489 $this->capability = explode(' ', strtoupper($str));
3491 if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3492 $this->prefs['literal+'] = true;
3496 $this->capability_readed = true;
3501 * Escapes a string when it contains special characters (RFC3501)
3503 * @param string $string IMAP string
3504 * @param boolean $force_quotes Forces string quoting (for atoms)
3506 * @return string String atom, quoted-string or string literal
3509 static function escape($string, $force_quotes=false)
3511 if ($string === null) {
3515 if ($string === '') {
3519 // atom-string (only safe characters)
3520 if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x25\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
3525 if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
3526 return '"' . addcslashes($string, '\\"') . '"';
3530 return sprintf("{%d}\r\n%s", strlen($string), $string);
3533 static function unEscape($string)
3535 return stripslashes($string);
3539 * Set the value of the debugging flag.
3541 * @param boolean $debug New value for the debugging flag.
3545 function setDebug($debug, $handler = null)
3547 $this->_debug = $debug;
3548 $this->_debug_handler = $handler;
3552 * Write the given debug text to the current debug output handler.
3554 * @param string $message Debug mesage text.
3558 private function debug($message)
3560 if ($this->resourceid) {
3561 $message = sprintf('[%s] %s', $this->resourceid, $message);
3564 if ($this->_debug_handler) {
3565 call_user_func_array($this->_debug_handler, array(&$this, $message));
3567 echo "DEBUG: $message\n";