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 5402 2011-11-09 10:03:54Z 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)) {
1563 list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1565 if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1572 function fetchUIDs($mailbox, $message_set=null)
1574 if (empty($message_set))
1575 $message_set = '1:*';
1577 return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1581 * FETCH command (RFC3501)
1583 * @param string $mailbox Mailbox name
1584 * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
1585 * @param bool $is_uid True if $message_set contains UIDs
1586 * @param array $query_items FETCH command data items
1587 * @param string $mod_seq Modification sequence for CHANGEDSINCE (RFC4551) query
1588 * @param bool $vanished Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
1590 * @return array List of rcube_mail_header elements, False on error
1593 function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
1594 $mod_seq = null, $vanished = false)
1596 if (!$this->select($mailbox)) {
1600 $message_set = $this->compressMessageSet($message_set);
1603 $key = $this->nextTag();
1604 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
1605 $request .= "(" . implode(' ', $query_items) . ")";
1607 if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
1608 $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
1611 if (!$this->putLine($request)) {
1612 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1617 $line = $this->readLine(4096);
1622 // Sample reply line:
1623 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1624 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1625 // BODY[HEADER.FIELDS ...
1627 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1628 $id = intval($m[1]);
1630 $result[$id] = new rcube_mail_header;
1631 $result[$id]->id = $id;
1632 $result[$id]->subject = '';
1633 $result[$id]->messageID = 'mid:' . $id;
1636 $line = substr($line, strlen($m[0]) + 2);
1639 // get complete entry
1640 while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
1644 while (strlen($out) < $bytes) {
1645 $out = $this->readBytes($bytes);
1651 $str = $this->readLine(4096);
1658 // Tokenize response and assign to object properties
1659 while (list($name, $value) = $this->tokenizeResponse($line, 2)) {
1660 if ($name == 'UID') {
1661 $result[$id]->uid = intval($value);
1663 else if ($name == 'RFC822.SIZE') {
1664 $result[$id]->size = intval($value);
1666 else if ($name == 'RFC822.TEXT') {
1667 $result[$id]->body = $value;
1669 else if ($name == 'INTERNALDATE') {
1670 $result[$id]->internaldate = $value;
1671 $result[$id]->date = $value;
1672 $result[$id]->timestamp = $this->StrToTime($value);
1674 else if ($name == 'FLAGS') {
1675 if (!empty($value)) {
1676 foreach ((array)$value as $flag) {
1677 $flag = str_replace(array('$', '\\'), '', $flag);
1678 $flag = strtoupper($flag);
1680 $result[$id]->flags[$flag] = true;
1684 else if ($name == 'MODSEQ') {
1685 $result[$id]->modseq = $value[0];
1687 else if ($name == 'ENVELOPE') {
1688 $result[$id]->envelope = $value;
1690 else if ($name == 'BODYSTRUCTURE' || ($name == 'BODY' && count($value) > 2)) {
1691 if (!is_array($value[0]) && (strtolower($value[0]) == 'message' && strtolower($value[1]) == 'rfc822')) {
1692 $value = array($value);
1694 $result[$id]->bodystructure = $value;
1696 else if ($name == 'RFC822') {
1697 $result[$id]->body = $value;
1699 else if ($name == 'BODY') {
1700 $body = $this->tokenizeResponse($line, 1);
1701 if ($value[0] == 'HEADER.FIELDS')
1703 else if (!empty($value))
1704 $result[$id]->bodypart[$value[0]] = $body;
1706 $result[$id]->body = $body;
1710 // create array with header field:data
1711 if (!empty($headers)) {
1712 $headers = explode("\n", trim($headers));
1713 foreach ($headers as $hid => $resln) {
1714 if (ord($resln[0]) <= 32) {
1715 $lines[$ln] .= (empty($lines[$ln]) ? '' : "\n") . trim($resln);
1717 $lines[++$ln] = trim($resln);
1721 while (list($lines_key, $str) = each($lines)) {
1722 list($field, $string) = explode(':', $str, 2);
1724 $field = strtolower($field);
1725 $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
1729 $result[$id]->date = $string;
1730 $result[$id]->timestamp = $this->strToTime($string);
1733 $result[$id]->from = $string;
1736 $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1739 $result[$id]->subject = $string;
1742 $result[$id]->replyto = $string;
1745 $result[$id]->cc = $string;
1748 $result[$id]->bcc = $string;
1750 case 'content-transfer-encoding':
1751 $result[$id]->encoding = $string;
1753 case 'content-type':
1754 $ctype_parts = preg_split('/[; ]/', $string);
1755 $result[$id]->ctype = strtolower(array_shift($ctype_parts));
1756 if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1757 $result[$id]->charset = $regs[1];
1761 $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1764 $result[$id]->references = $string;
1766 case 'return-receipt-to':
1767 case 'disposition-notification-to':
1768 case 'x-confirm-reading-to':
1769 $result[$id]->mdn_to = $string;
1772 $result[$id]->messageID = $string;
1775 if (preg_match('/^(\d+)/', $string, $matches)) {
1776 $result[$id]->priority = intval($matches[1]);
1780 if (strlen($field) > 2) {
1781 $result[$id]->others[$field] = $string;
1789 // VANISHED response (QRESYNC RFC5162)
1790 // Sample: * VANISHED (EARLIER) 300:310,405,411
1792 else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
1793 $line = substr($line, strlen($match[0]));
1794 $v_data = $this->tokenizeResponse($line, 1);
1796 $this->data['VANISHED'] = $v_data;
1799 } while (!$this->startsWith($line, $key, true));
1804 function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add = '')
1806 $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
1808 $query_items[] = 'BODYSTRUCTURE';
1809 $query_items[] = 'BODY.PEEK[HEADER.FIELDS ('
1810 . 'DATE FROM TO SUBJECT CONTENT-TYPE CC REPLY-TO LIST-POST DISPOSITION-NOTIFICATION-TO X-PRIORITY'
1811 . ($add ? ' ' . trim($add) : '')
1814 $result = $this->fetch($mailbox, $message_set, $is_uid, $query_items);
1819 function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1821 $a = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1823 return array_shift($a);
1828 function sortHeaders($a, $field, $flag)
1830 if (empty($field)) {
1834 $field = strtolower($field);
1837 if ($field == 'date' || $field == 'internaldate') {
1838 $field = 'timestamp';
1844 $flag = strtoupper($flag);
1850 // First, we'll create an "index" array.
1851 // Then, we'll use sort() on that array,
1852 // and use that to sort the main array.
1854 // create "index" array
1857 while (list($key, $val) = each($a)) {
1858 if ($field == 'timestamp') {
1859 $data = $this->strToTime($val->date);
1861 $data = $val->timestamp;
1864 $data = $val->$field;
1865 if (is_string($data)) {
1866 $data = str_replace('"', '', $data);
1867 if ($field == 'subject') {
1868 $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1870 $data = strtoupper($data);
1873 $index[$key] = $data;
1877 if ($flag == 'ASC') {
1883 // form new array based on index
1886 while (list($key, $val) = each($index)) {
1887 $result[$key] = $a[$key];
1895 function modFlag($mailbox, $messages, $flag, $mod)
1897 if ($mod != '+' && $mod != '-') {
1901 if (!$this->select($mailbox)) {
1905 if (!$this->data['READ-WRITE']) {
1906 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1910 // Clear internal status cache
1911 if ($flag == 'SEEN') {
1912 unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1915 $flag = $this->flags[strtoupper($flag)];
1916 $result = $this->execute('UID STORE', array(
1917 $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1918 self::COMMAND_NORESPONSE);
1920 return ($result == self::ERROR_OK);
1923 function flag($mailbox, $messages, $flag) {
1924 return $this->modFlag($mailbox, $messages, $flag, '+');
1927 function unflag($mailbox, $messages, $flag) {
1928 return $this->modFlag($mailbox, $messages, $flag, '-');
1931 function delete($mailbox, $messages) {
1932 return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1935 function copy($messages, $from, $to)
1937 if (!$this->select($from)) {
1941 // Clear internal status cache
1942 unset($this->data['STATUS:'.$to]);
1944 $result = $this->execute('UID COPY', array(
1945 $this->compressMessageSet($messages), $this->escape($to)),
1946 self::COMMAND_NORESPONSE);
1948 return ($result == self::ERROR_OK);
1951 function move($messages, $from, $to)
1953 if (!$this->select($from)) {
1957 if (!$this->data['READ-WRITE']) {
1958 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1962 $r = $this->copy($messages, $from, $to);
1965 // Clear internal status cache
1966 unset($this->data['STATUS:'.$from]);
1968 return $this->delete($from, $messages);
1973 // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1974 // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1975 // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1976 private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1979 if ($str[$begin] != '(') {
1980 $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1981 $msg = substr($str, $begin, $stop - $begin);
1986 $depthmap[$msg] = $depth;
1987 $haschildren[$msg] = false;
1988 if (!is_null($parent))
1989 $haschildren[$parent] = true;
1990 if ($stop + 1 < $end)
1991 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1993 $node[$msg] = array();
1996 while ($off < $end) {
2001 $p = strpos($str, ')', $off);
2003 error_log("Mismatched brackets parsing IMAP THREAD response:");
2004 error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
2005 error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
2008 $p1 = strpos($str, '(', $off);
2009 if ($p1 !== false && $p1 < $p) {
2017 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
2024 function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
2026 $old_sel = $this->selected;
2028 if (!$this->select($mailbox)) {
2032 // return empty result when folder is empty and we're just after SELECT
2033 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2034 return array(array(), array(), array());
2037 $encoding = $encoding ? trim($encoding) : 'US-ASCII';
2038 $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
2039 $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
2042 list($code, $response) = $this->execute('THREAD', array(
2043 $algorithm, $encoding, $criteria));
2045 if ($code == self::ERROR_OK) {
2047 $response = substr($response, stripos($response, '* THREAD') + 9);
2048 // ...unilateral untagged server responses
2049 if ($pos = strpos($response, '*')) {
2050 $response = substr($response, 0, $pos);
2053 $response = str_replace("\r\n", '', $response);
2054 $depthmap = array();
2055 $haschildren = array();
2057 $tree = $this->parseThread($response, 0, strlen($response),
2058 null, null, 0, $depthmap, $haschildren);
2060 return array($tree, $depthmap, $haschildren);
2067 * Executes SEARCH command
2069 * @param string $mailbox Mailbox name
2070 * @param string $criteria Searching criteria
2071 * @param bool $return_uid Enable UID in result instead of sequence ID
2072 * @param array $items Return items (MIN, MAX, COUNT, ALL)
2074 * @return array Message identifiers or item-value hash
2076 function search($mailbox, $criteria, $return_uid=false, $items=array())
2078 $old_sel = $this->selected;
2080 if (!$this->select($mailbox)) {
2084 // return empty result when folder is empty and we're just after SELECT
2085 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2087 return array_combine($items, array_fill(0, count($items), 0));
2092 $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
2093 $criteria = trim($criteria);
2097 if (!empty($items) && $esearch) {
2098 $params .= 'RETURN (' . implode(' ', $items) . ')';
2100 if (!empty($criteria)) {
2101 $modseq = stripos($criteria, 'MODSEQ') !== false;
2102 $params .= ($params ? ' ' : '') . $criteria;
2108 list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2111 if ($code == self::ERROR_OK) {
2113 $response = substr($response, stripos($response,
2114 $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
2115 // ...and unilateral untagged server responses
2116 if ($pos = strpos($response, '*')) {
2117 $response = rtrim(substr($response, 0, $pos));
2120 // remove MODSEQ response
2122 if (preg_match('/\(MODSEQ ([0-9]+)\)$/', $response, $m)) {
2123 $response = substr($response, 0, -strlen($m[0]));
2128 // Skip prefix: ... (TAG "A285") UID ...
2129 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2132 for ($i=0; $i<count($items); $i++) {
2133 // If the SEARCH returns no matches, the server MUST NOT
2134 // include the item result option in the ESEARCH response
2135 if ($ret = $this->tokenizeResponse($response, 2)) {
2136 list ($name, $value) = $ret;
2137 $result[$name] = $value;
2144 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2146 if (!empty($items)) {
2148 if (in_array('COUNT', $items)) {
2149 $result['COUNT'] = count($response);
2151 if (in_array('MIN', $items)) {
2152 $result['MIN'] = !empty($response) ? min($response) : 0;
2154 if (in_array('MAX', $items)) {
2155 $result['MAX'] = !empty($response) ? max($response) : 0;
2157 if (in_array('ALL', $items)) {
2158 $result['ALL'] = $this->compressMessageSet($response, true);
2173 * Returns list of mailboxes
2175 * @param string $ref Reference name
2176 * @param string $mailbox Mailbox name
2177 * @param array $status_opts (see self::_listMailboxes)
2178 * @param array $select_opts (see self::_listMailboxes)
2180 * @return array List of mailboxes or hash of options if $status_opts argument
2183 function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2185 return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2189 * Returns list of subscribed mailboxes
2191 * @param string $ref Reference name
2192 * @param string $mailbox Mailbox name
2193 * @param array $status_opts (see self::_listMailboxes)
2195 * @return array List of mailboxes or hash of options if $status_opts argument
2198 function listSubscribed($ref, $mailbox, $status_opts=array())
2200 return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2204 * IMAP LIST/LSUB command
2206 * @param string $ref Reference name
2207 * @param string $mailbox Mailbox name
2208 * @param bool $subscribed Enables returning subscribed mailboxes only
2209 * @param array $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2210 * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2211 * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2212 * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2214 * @return array List of mailboxes or hash of options if $status_ops argument
2217 private function _listMailboxes($ref, $mailbox, $subscribed=false,
2218 $status_opts=array(), $select_opts=array())
2220 if (!strlen($mailbox)) {
2226 if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2227 $select_opts = (array) $select_opts;
2229 $args[] = '(' . implode(' ', $select_opts) . ')';
2232 $args[] = $this->escape($ref);
2233 $args[] = $this->escape($mailbox);
2235 if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2236 $status_opts = (array) $status_opts;
2239 $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2242 list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2244 if ($code == self::ERROR_OK) {
2248 $response .= "\r\n";
2250 while ($pos = strpos($response, "\r\n", $pos+1)) {
2251 // literal string, not real end-of-command-line
2252 if ($response[$pos-1] == '}') {
2256 $line = substr($response, $last, $pos - $last);
2259 if (!preg_match('/^\* (LIST|LSUB|STATUS) /i', $line, $m)) {
2262 $cmd = strtoupper($m[1]);
2263 $line = substr($line, strlen($m[0]));
2265 // * LIST (<options>) <delimiter> <mailbox>
2266 if ($cmd == 'LIST' || $cmd == 'LSUB') {
2267 list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
2269 // Add to result array
2271 $folders[] = $mailbox;
2274 $folders[$mailbox] = array();
2277 // Add to options array
2278 if (empty($this->data['LIST'][$mailbox]))
2279 $this->data['LIST'][$mailbox] = $opts;
2280 else if (!empty($opts))
2281 $this->data['LIST'][$mailbox] = array_unique(array_merge(
2282 $this->data['LIST'][$mailbox], $opts));
2284 // * STATUS <mailbox> (<result>)
2285 else if ($cmd == 'STATUS') {
2286 list($mailbox, $status) = $this->tokenizeResponse($line, 2);
2288 for ($i=0, $len=count($status); $i<$len; $i += 2) {
2289 list($name, $value) = $this->tokenizeResponse($status, 2);
2290 $folders[$mailbox][$name] = $value;
2301 function fetchMIMEHeaders($mailbox, $uid, $parts, $mime=true)
2303 if (!$this->select($mailbox)) {
2308 $parts = (array) $parts;
2309 $key = $this->nextTag();
2311 $type = $mime ? 'MIME' : 'HEADER';
2314 foreach ($parts as $part) {
2315 $peeks[] = "BODY.PEEK[$part.$type]";
2318 $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
2321 if (!$this->putLine($request)) {
2322 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2327 $line = $this->readLine(1024);
2329 if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2333 // get complete entry
2334 if (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
2338 while (strlen($out) < $bytes) {
2339 $out = $this->readBytes($bytes);
2346 $result[$idx] = trim($headers);
2348 } while (!$this->startsWith($line, $key, true));
2353 function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2355 $part = empty($part) ? 'HEADER' : $part.'.MIME';
2357 return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2360 function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2362 if (!$this->select($mailbox)) {
2366 switch ($encoding) {
2370 case 'quoted-printable':
2384 $reply_key = '* ' . $id;
2385 $key = $this->nextTag();
2386 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2389 if (!$this->putLine($request)) {
2390 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2394 // receive reply line
2396 $line = rtrim($this->readLine(1024));
2397 $a = explode(' ', $line);
2398 } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2400 $len = strlen($line);
2403 if ($a[2] != 'FETCH') {
2405 // handle empty "* X FETCH ()" response
2406 else if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2407 // one line response, get everything between first and last quotes
2408 if (substr($line, -4, 3) == 'NIL') {
2412 $from = strpos($line, '"') + 1;
2413 $to = strrpos($line, '"');
2415 $result = substr($line, $from, $len);
2419 $result = base64_decode($result);
2421 else if ($mode == 2) {
2422 $result = quoted_printable_decode($result);
2424 else if ($mode == 3) {
2425 $result = convert_uudecode($result);
2428 } else if ($line[$len-1] == '}') {
2429 // multi-line request, find sizes of content and receive that many bytes
2430 $from = strpos($line, '{') + 1;
2431 $to = strrpos($line, '}');
2433 $sizeStr = substr($line, $from, $len);
2434 $bytes = (int)$sizeStr;
2437 while ($bytes > 0) {
2438 $line = $this->readLine(4096);
2440 if ($line === NULL) {
2444 $len = strlen($line);
2446 if ($len > $bytes) {
2447 $line = substr($line, 0, $bytes);
2448 $len = strlen($line);
2454 $line = rtrim($line, "\t\r\n\0\x0B");
2455 // create chunks with proper length for base64 decoding
2456 $line = $prev.$line;
2457 $length = strlen($line);
2459 $length = floor($length / 4) * 4;
2460 $prev = substr($line, $length);
2461 $line = substr($line, 0, $length);
2465 $line = base64_decode($line);
2467 } else if ($mode == 2) {
2468 $line = rtrim($line, "\t\r\0\x0B");
2469 $line = quoted_printable_decode($line);
2471 } else if ($mode == 3) {
2472 $line = rtrim($line, "\t\r\n\0\x0B");
2473 if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2475 $line = convert_uudecode($line);
2478 $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2482 fwrite($file, $line);
2490 // read in anything up until last line
2493 $line = $this->readLine(1024);
2494 } while (!$this->startsWith($line, $key, true));
2496 if ($result !== false) {
2498 fwrite($file, $result);
2499 } else if ($print) {
2509 function createFolder($mailbox)
2511 $result = $this->execute('CREATE', array($this->escape($mailbox)),
2512 self::COMMAND_NORESPONSE);
2514 return ($result == self::ERROR_OK);
2517 function renameFolder($from, $to)
2519 $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2520 self::COMMAND_NORESPONSE);
2522 return ($result == self::ERROR_OK);
2526 * Handler for IMAP APPEND command
2528 * @param string $mailbox Mailbox name
2529 * @param string $message Message content
2531 * @return string|bool On success APPENDUID response (if available) or True, False on failure
2533 function append($mailbox, &$message)
2535 unset($this->data['APPENDUID']);
2541 $message = str_replace("\r", '', $message);
2542 $message = str_replace("\n", "\r\n", $message);
2544 $len = strlen($message);
2549 $key = $this->nextTag();
2550 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2551 $len, ($this->prefs['literal+'] ? '+' : ''));
2553 if ($this->putLine($request)) {
2554 // Don't wait when LITERAL+ is supported
2555 if (!$this->prefs['literal+']) {
2556 $line = $this->readReply();
2558 if ($line[0] != '+') {
2559 $this->parseResult($line, 'APPEND: ');
2564 if (!$this->putLine($message)) {
2569 $line = $this->readLine();
2570 } while (!$this->startsWith($line, $key, true, true));
2572 // Clear internal status cache
2573 unset($this->data['STATUS:'.$mailbox]);
2575 if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2577 else if (!empty($this->data['APPENDUID']))
2578 return $this->data['APPENDUID'];
2583 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2590 * Handler for IMAP APPEND command.
2592 * @param string $mailbox Mailbox name
2593 * @param string $path Path to the file with message body
2594 * @param string $headers Message headers
2596 * @return string|bool On success APPENDUID response (if available) or True, False on failure
2598 function appendFromFile($mailbox, $path, $headers=null)
2600 unset($this->data['APPENDUID']);
2606 // open message file
2608 if (file_exists(realpath($path))) {
2609 $in_fp = fopen($path, 'r');
2612 $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2616 $body_separator = "\r\n\r\n";
2617 $len = filesize($path);
2624 $headers = preg_replace('/[\r\n]+$/', '', $headers);
2625 $len += strlen($headers) + strlen($body_separator);
2628 // send APPEND command
2629 $key = $this->nextTag();
2630 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2631 $len, ($this->prefs['literal+'] ? '+' : ''));
2633 if ($this->putLine($request)) {
2634 // Don't wait when LITERAL+ is supported
2635 if (!$this->prefs['literal+']) {
2636 $line = $this->readReply();
2638 if ($line[0] != '+') {
2639 $this->parseResult($line, 'APPEND: ');
2644 // send headers with body separator
2646 $this->putLine($headers . $body_separator, false);
2650 while (!feof($in_fp) && $this->fp) {
2651 $buffer = fgets($in_fp, 4096);
2652 $this->putLine($buffer, false);
2656 if (!$this->putLine('')) { // \r\n
2662 $line = $this->readLine();
2663 } while (!$this->startsWith($line, $key, true, true));
2665 // Clear internal status cache
2666 unset($this->data['STATUS:'.$mailbox]);
2668 if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2670 else if (!empty($this->data['APPENDUID']))
2671 return $this->data['APPENDUID'];
2676 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2685 * GETQUOTAROOT "INBOX"
2686 * QUOTAROOT INBOX user/rchijiiwa1
2687 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2691 $quota_lines = array();
2692 $key = $this->nextTag();
2693 $command = $key . ' GETQUOTAROOT INBOX';
2695 // get line(s) containing quota info
2696 if ($this->putLine($command)) {
2698 $line = rtrim($this->readLine(5000));
2699 if (preg_match('/^\* QUOTA /', $line)) {
2700 $quota_lines[] = $line;
2702 } while (!$this->startsWith($line, $key, true, true));
2705 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2708 // return false if not found, parse if found
2709 $min_free = PHP_INT_MAX;
2710 foreach ($quota_lines as $key => $quota_line) {
2711 $quota_line = str_replace(array('(', ')'), '', $quota_line);
2712 $parts = explode(' ', $quota_line);
2713 $storage_part = array_search('STORAGE', $parts);
2715 if (!$storage_part) {
2719 $used = intval($parts[$storage_part+1]);
2720 $total = intval($parts[$storage_part+2]);
2721 $free = $total - $used;
2723 // return lowest available space from all quotas
2724 if ($free < $min_free) {
2726 $result['used'] = $used;
2727 $result['total'] = $total;
2728 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2729 $result['free'] = 100 - $result['percent'];
2737 * Send the SETACL command (RFC4314)
2739 * @param string $mailbox Mailbox name
2740 * @param string $user User name
2741 * @param mixed $acl ACL string or array
2743 * @return boolean True on success, False on failure
2747 function setACL($mailbox, $user, $acl)
2749 if (is_array($acl)) {
2750 $acl = implode('', $acl);
2753 $result = $this->execute('SETACL', array(
2754 $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2755 self::COMMAND_NORESPONSE);
2757 return ($result == self::ERROR_OK);
2761 * Send the DELETEACL command (RFC4314)
2763 * @param string $mailbox Mailbox name
2764 * @param string $user User name
2766 * @return boolean True on success, False on failure
2770 function deleteACL($mailbox, $user)
2772 $result = $this->execute('DELETEACL', array(
2773 $this->escape($mailbox), $this->escape($user)),
2774 self::COMMAND_NORESPONSE);
2776 return ($result == self::ERROR_OK);
2780 * Send the GETACL command (RFC4314)
2782 * @param string $mailbox Mailbox name
2784 * @return array User-rights array on success, NULL on error
2787 function getACL($mailbox)
2789 list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2791 if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2792 // Parse server response (remove "* ACL ")
2793 $response = substr($response, 6);
2794 $ret = $this->tokenizeResponse($response);
2795 $mbox = array_shift($ret);
2796 $size = count($ret);
2798 // Create user-rights hash array
2799 // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2800 // so we could return only standard rights defined in RFC4314,
2801 // excluding 'c' and 'd' defined in RFC2086.
2802 if ($size % 2 == 0) {
2803 for ($i=0; $i<$size; $i++) {
2804 $ret[$ret[$i]] = str_split($ret[++$i]);
2811 $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2819 * Send the LISTRIGHTS command (RFC4314)
2821 * @param string $mailbox Mailbox name
2822 * @param string $user User name
2824 * @return array List of user rights
2827 function listRights($mailbox, $user)
2829 list($code, $response) = $this->execute('LISTRIGHTS', array(
2830 $this->escape($mailbox), $this->escape($user)));
2832 if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2833 // Parse server response (remove "* LISTRIGHTS ")
2834 $response = substr($response, 13);
2836 $ret_mbox = $this->tokenizeResponse($response, 1);
2837 $ret_user = $this->tokenizeResponse($response, 1);
2838 $granted = $this->tokenizeResponse($response, 1);
2839 $optional = trim($response);
2842 'granted' => str_split($granted),
2843 'optional' => explode(' ', $optional),
2851 * Send the MYRIGHTS command (RFC4314)
2853 * @param string $mailbox Mailbox name
2855 * @return array MYRIGHTS response on success, NULL on error
2858 function myRights($mailbox)
2860 list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2862 if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2863 // Parse server response (remove "* MYRIGHTS ")
2864 $response = substr($response, 11);
2866 $ret_mbox = $this->tokenizeResponse($response, 1);
2867 $rights = $this->tokenizeResponse($response, 1);
2869 return str_split($rights);
2876 * Send the SETMETADATA command (RFC5464)
2878 * @param string $mailbox Mailbox name
2879 * @param array $entries Entry-value array (use NULL value as NIL)
2881 * @return boolean True on success, False on failure
2884 function setMetadata($mailbox, $entries)
2886 if (!is_array($entries) || empty($entries)) {
2887 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2891 foreach ($entries as $name => $value) {
2892 $entries[$name] = $this->escape($name) . ' ' . $this->escape($value);
2895 $entries = implode(' ', $entries);
2896 $result = $this->execute('SETMETADATA', array(
2897 $this->escape($mailbox), '(' . $entries . ')'),
2898 self::COMMAND_NORESPONSE);
2900 return ($result == self::ERROR_OK);
2904 * Send the SETMETADATA command with NIL values (RFC5464)
2906 * @param string $mailbox Mailbox name
2907 * @param array $entries Entry names array
2909 * @return boolean True on success, False on failure
2913 function deleteMetadata($mailbox, $entries)
2915 if (!is_array($entries) && !empty($entries)) {
2916 $entries = explode(' ', $entries);
2919 if (empty($entries)) {
2920 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2924 foreach ($entries as $entry) {
2925 $data[$entry] = NULL;
2928 return $this->setMetadata($mailbox, $data);
2932 * Send the GETMETADATA command (RFC5464)
2934 * @param string $mailbox Mailbox name
2935 * @param array $entries Entries
2936 * @param array $options Command options (with MAXSIZE and DEPTH keys)
2938 * @return array GETMETADATA result on success, NULL on error
2942 function getMetadata($mailbox, $entries, $options=array())
2944 if (!is_array($entries)) {
2945 $entries = array($entries);
2948 // create entries string
2949 foreach ($entries as $idx => $name) {
2950 $entries[$idx] = $this->escape($name);
2954 $entlist = '(' . implode(' ', $entries) . ')';
2956 // create options string
2957 if (is_array($options)) {
2958 $options = array_change_key_case($options, CASE_UPPER);
2961 if (!empty($options['MAXSIZE'])) {
2962 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2964 if (!empty($options['DEPTH'])) {
2965 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2969 $optlist = '(' . implode(' ', $opts) . ')';
2973 $optlist .= ($optlist ? ' ' : '') . $entlist;
2975 list($code, $response) = $this->execute('GETMETADATA', array(
2976 $this->escape($mailbox), $optlist));
2978 if ($code == self::ERROR_OK) {
2980 $data = $this->tokenizeResponse($response);
2982 // The METADATA response can contain multiple entries in a single
2983 // response or multiple responses for each entry or group of entries
2984 if (!empty($data) && ($size = count($data))) {
2985 for ($i=0; $i<$size; $i++) {
2986 if (isset($mbox) && is_array($data[$i])) {
2987 $size_sub = count($data[$i]);
2988 for ($x=0; $x<$size_sub; $x++) {
2989 $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
2993 else if ($data[$i] == '*') {
2994 if ($data[$i+1] == 'METADATA') {
2995 $mbox = $data[$i+2];
2996 unset($data[$i]); // "*"
2997 unset($data[++$i]); // "METADATA"
2998 unset($data[++$i]); // Mailbox
3000 // get rid of other untagged responses
3006 else if (isset($mbox)) {
3007 $result[$mbox][$data[$i]] = $data[++$i];
3024 * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
3026 * @param string $mailbox Mailbox name
3027 * @param array $data Data array where each item is an array with
3028 * three elements: entry name, attribute name, value
3030 * @return boolean True on success, False on failure
3033 function setAnnotation($mailbox, $data)
3035 if (!is_array($data) || empty($data)) {
3036 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3040 foreach ($data as $entry) {
3041 // ANNOTATEMORE drafts before version 08 require quoted parameters
3042 $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
3043 $this->escape($entry[1], true), $this->escape($entry[2], true));
3046 $entries = implode(' ', $entries);
3047 $result = $this->execute('SETANNOTATION', array(
3048 $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
3050 return ($result == self::ERROR_OK);
3054 * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
3056 * @param string $mailbox Mailbox name
3057 * @param array $data Data array where each item is an array with
3058 * two elements: entry name and attribute name
3060 * @return boolean True on success, False on failure
3064 function deleteAnnotation($mailbox, $data)
3066 if (!is_array($data) || empty($data)) {
3067 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3071 return $this->setAnnotation($mailbox, $data);
3075 * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3077 * @param string $mailbox Mailbox name
3078 * @param array $entries Entries names
3079 * @param array $attribs Attribs names
3081 * @return array Annotations result on success, NULL on error
3085 function getAnnotation($mailbox, $entries, $attribs)
3087 if (!is_array($entries)) {
3088 $entries = array($entries);
3090 // create entries string
3091 // ANNOTATEMORE drafts before version 08 require quoted parameters
3092 foreach ($entries as $idx => $name) {
3093 $entries[$idx] = $this->escape($name, true);
3095 $entries = '(' . implode(' ', $entries) . ')';
3097 if (!is_array($attribs)) {
3098 $attribs = array($attribs);
3100 // create entries string
3101 foreach ($attribs as $idx => $name) {
3102 $attribs[$idx] = $this->escape($name, true);
3104 $attribs = '(' . implode(' ', $attribs) . ')';
3106 list($code, $response) = $this->execute('GETANNOTATION', array(
3107 $this->escape($mailbox), $entries, $attribs));
3109 if ($code == self::ERROR_OK) {
3111 $data = $this->tokenizeResponse($response);
3113 // Here we returns only data compatible with METADATA result format
3114 if (!empty($data) && ($size = count($data))) {
3115 for ($i=0; $i<$size; $i++) {
3117 if (isset($mbox) && is_array($entry)) {
3119 $entry = $last_entry;
3121 else if ($entry == '*') {
3122 if ($data[$i+1] == 'ANNOTATION') {
3123 $mbox = $data[$i+2];
3124 unset($data[$i]); // "*"
3125 unset($data[++$i]); // "ANNOTATION"
3126 unset($data[++$i]); // Mailbox
3128 // get rid of other untagged responses
3135 else if (isset($mbox)) {
3136 $attribs = $data[++$i];
3143 if (!empty($attribs)) {
3144 for ($x=0, $len=count($attribs); $x<$len;) {
3145 $attr = $attribs[$x++];
3146 $value = $attribs[$x++];
3147 if ($attr == 'value.priv') {
3148 $result[$mbox]['/private' . $entry] = $value;
3150 else if ($attr == 'value.shared') {
3151 $result[$mbox]['/shared' . $entry] = $value;
3155 $last_entry = $entry;
3167 * Returns BODYSTRUCTURE for the specified message.
3169 * @param string $mailbox Folder name
3170 * @param int $id Message sequence number or UID
3171 * @param bool $is_uid True if $id is an UID
3173 * @return array/bool Body structure array or False on error.
3176 function getStructure($mailbox, $id, $is_uid = false)
3178 $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
3179 if (is_array($result)) {
3180 $result = array_shift($result);
3181 return $result->bodystructure;
3187 * Returns data of a message part according to specified structure.
3189 * @param array $structure Message structure (getStructure() result)
3190 * @param string $part Message part identifier
3192 * @return array Part data as hash array (type, encoding, charset, size)
3194 static function getStructurePartData($structure, $part)
3196 $part_a = self::getStructurePartArray($structure, $part);
3199 if (empty($part_a)) {
3204 if (is_array($part_a[0])) {
3205 $data['type'] = 'multipart';
3208 $data['type'] = strtolower($part_a[0]);
3211 $data['encoding'] = strtolower($part_a[5]);
3214 if (is_array($part_a[2])) {
3215 while (list($key, $val) = each($part_a[2])) {
3216 if (strcasecmp($val, 'charset') == 0) {
3217 $data['charset'] = $part_a[2][$key+1];
3225 $data['size'] = intval($part_a[6]);
3230 static function getStructurePartArray($a, $part)
3232 if (!is_array($a)) {
3235 if (strpos($part, '.') > 0) {
3236 $original_part = $part;
3237 $pos = strpos($part, '.');
3238 $rest = substr($original_part, $pos+1);
3239 $part = substr($original_part, 0, $pos);
3240 if ((strcasecmp($a[0], 'message') == 0) && (strcasecmp($a[1], 'rfc822') == 0)) {
3243 return self::getStructurePartArray($a[$part-1], $rest);
3246 if (!is_array($a[0]) && (strcasecmp($a[0], 'message') == 0)
3247 && (strcasecmp($a[1], 'rfc822') == 0)) {
3250 if (is_array($a[$part-1]))
3255 else if (($part == 0) || (empty($part))) {
3261 * Creates next command identifier (tag)
3263 * @return string Command identifier
3269 $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3271 return $this->cmd_tag;
3275 * Sends IMAP command and parses result
3277 * @param string $command IMAP command
3278 * @param array $arguments Command arguments
3279 * @param int $options Execution options
3281 * @return mixed Response code or list of response code and data
3284 function execute($command, $arguments=array(), $options=0)
3286 $tag = $this->nextTag();
3287 $query = $tag . ' ' . $command;
3288 $noresp = ($options & self::COMMAND_NORESPONSE);
3289 $response = $noresp ? null : '';
3291 if (!empty($arguments)) {
3292 foreach ($arguments as $arg) {
3293 $query .= ' ' . self::r_implode($arg);
3298 if (!$this->putLineC($query)) {
3299 $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3300 return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3305 $line = $this->readLine(4096);
3306 if ($response !== null) {
3309 } while (!$this->startsWith($line, $tag . ' ', true, true));
3311 $code = $this->parseResult($line, $command . ': ');
3313 // Remove last line from response
3315 $line_len = min(strlen($response), strlen($line) + 2);
3316 $response = substr($response, 0, -$line_len);
3319 // optional CAPABILITY response
3320 if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3321 && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3323 $this->parseCapability($matches[1], true);
3326 // return last line only (without command tag, result and response code)
3327 if ($line && ($options & self::COMMAND_LASTLINE)) {
3328 $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3331 return $noresp ? $code : array($code, $response);
3335 * Splits IMAP response into string tokens
3337 * @param string &$str The IMAP's server response
3338 * @param int $num Number of tokens to return
3340 * @return mixed Tokens array or string if $num=1
3343 static function tokenizeResponse(&$str, $num=0)
3347 while (!$num || count($result) < $num) {
3348 // remove spaces from the beginning of the string
3355 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3358 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3361 $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
3362 // Advance the string
3363 $str = substr($str, $epos + 3 + $bytes);
3368 $len = strlen($str);
3370 for ($pos=1; $pos<$len; $pos++) {
3371 if ($str[$pos] == '"') {
3374 if ($str[$pos] == "\\") {
3375 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3380 if ($str[$pos] != '"') {
3383 // we need to strip slashes for a quoted string
3384 $result[] = stripslashes(substr($str, 1, $pos - 1));
3385 $str = substr($str, $pos + 1);
3388 // Parenthesized list
3391 $str = substr($str, 1);
3392 $result[] = self::tokenizeResponse($str);
3396 $str = substr($str, 1);
3400 // String atom, number, NIL, *, %
3403 if ($str === '' || $str === null) {
3407 // excluded chars: SP, CTL, ), [, ]
3408 if (preg_match('/^([^\x00-\x20\x29\x5B\x5D\x7F]+)/', $str, $m)) {
3409 $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3410 $str = substr($str, strlen($m[1]));
3416 return $num == 1 ? $result[0] : $result;
3419 static function r_implode($element)
3423 if (is_array($element)) {
3425 while (list($key, $value) = each($element)) {
3426 $string .= ' ' . self::r_implode($value);
3433 return '(' . trim($string) . ')';
3436 private function _xor($string, $string2)
3439 $size = strlen($string);
3441 for ($i=0; $i<$size; $i++) {
3442 $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3449 * Converts datetime string into unix timestamp
3451 * @param string $date Date string
3453 * @return int Unix timestamp
3455 static function strToTime($date)
3457 // support non-standard "GMTXXXX" literal
3458 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3460 // if date parsing fails, we have a date in non-rfc format
3461 // remove token from the end and try again
3462 while (($ts = intval(@strtotime($date))) <= 0) {
3463 $d = explode(' ', $date);
3468 $date = implode(' ', $d);
3471 return $ts < 0 ? 0 : $ts;
3474 private function parseCapability($str, $trusted=false)
3476 $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3478 $this->capability = explode(' ', strtoupper($str));
3480 if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3481 $this->prefs['literal+'] = true;
3485 $this->capability_readed = true;
3490 * Escapes a string when it contains special characters (RFC3501)
3492 * @param string $string IMAP string
3493 * @param boolean $force_quotes Forces string quoting (for atoms)
3495 * @return string String atom, quoted-string or string literal
3498 static function escape($string, $force_quotes=false)
3500 if ($string === null) {
3503 if ($string === '') {
3506 // atom-string (only safe characters)
3507 if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
3511 if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
3512 return '"' . addcslashes($string, '\\"') . '"';
3516 return sprintf("{%d}\r\n%s", strlen($string), $string);
3519 static function unEscape($string)
3521 return stripslashes($string);
3525 * Set the value of the debugging flag.
3527 * @param boolean $debug New value for the debugging flag.
3531 function setDebug($debug, $handler = null)
3533 $this->_debug = $debug;
3534 $this->_debug_handler = $handler;
3538 * Write the given debug text to the current debug output handler.
3540 * @param string $message Debug mesage text.
3544 private function debug($message)
3546 if ($this->resourceid) {
3547 $message = sprintf('[%s] %s', $this->resourceid, $message);
3550 if ($this->_debug_handler) {
3551 call_user_func_array($this->_debug_handler, array(&$this, $message));
3553 echo "DEBUG: $message\n";