4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap_generic.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Provide alternative IMAP library that doesn't rely on the standard |
13 | C-Client based version. This allows to function regardless |
14 | of whether or not the PHP build it's running on has IMAP |
15 | functionality built-in. |
17 | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
19 +-----------------------------------------------------------------------+
20 | Author: Aleksander Machniak <alec@alec.pl> |
21 | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
22 +-----------------------------------------------------------------------+
24 $Id: rcube_imap_generic.php 4516 2011-02-09 12:46:46Z alec $
30 * Struct representing an e-mail message header
33 * @author Aleksander Machniak <alec@alec.pl>
35 class rcube_mail_header
53 public $body_structure;
58 public $mdn_sent = false;
59 public $is_draft = false;
61 public $deleted = false;
62 public $recent = false;
63 public $answered = false;
64 public $forwarded = false;
66 public $flagged = false;
67 public $has_children = false;
69 public $unread_children = 0;
70 public $others = array();
73 // For backward compatibility with cached messages (#1486602)
74 class iilBasicHeader extends rcube_mail_header
79 * PHP based wrapper class to connect to an IMAP server
82 * @author Aleksander Machniak <alec@alec.pl>
84 class rcube_imap_generic
90 public $data = array();
91 public $flags = array(
93 'DELETED' => '\\Deleted',
94 'RECENT' => '\\Recent',
95 'ANSWERED' => '\\Answered',
97 'FLAGGED' => '\\Flagged',
98 'FORWARDED' => '$Forwarded',
99 'MDNSENT' => '$MDNSent',
106 private $logged = false;
107 private $capability = array();
108 private $capability_readed = false;
111 private $cmd_num = 0;
112 private $_debug = false;
113 private $_debug_handler = false;
117 const ERROR_BAD = -2;
118 const ERROR_BYE = -3;
119 const ERROR_UNKNOWN = -4;
120 const ERROR_COMMAND = -5;
121 const ERROR_READONLY = -6;
123 const COMMAND_NORESPONSE = 1;
124 const COMMAND_CAPABILITY = 2;
125 const COMMAND_LASTLINE = 4;
130 function __construct()
135 * Send simple (one line) command to the connection stream
137 * @param string $string Command string
138 * @param bool $endln True if CRLF need to be added at the end of command
140 * @param int Number of bytes sent, False on error
142 function putLine($string, $endln=true)
148 $this->debug('C: '. rtrim($string));
151 $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
153 if ($res === false) {
162 * Send command to the connection stream with Command Continuation
163 * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
165 * @param string $string Command string
166 * @param bool $endln True if CRLF need to be added at the end of command
168 * @param int Number of bytes sent, False on error
170 function putLineC($string, $endln=true)
179 if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
180 for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
181 if (preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
183 if ($this->prefs['literal+'])
184 $parts[$i+1] = preg_replace('/([0-9]+)/', '\\1+', $parts[$i+1]);
186 $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
187 if ($bytes === false)
191 // don't wait if server supports LITERAL+ capability
192 if (!$this->prefs['literal+']) {
193 $line = $this->readLine(1000);
194 // handle error in command
201 $bytes = $this->putLine($parts[$i], false);
202 if ($bytes === false)
212 function readLine($size=1024)
225 if (feof($this->fp)) {
226 return $line ? $line : NULL;
229 $buffer = fgets($this->fp, $size);
231 if ($buffer === false) {
237 $this->debug('S: '. rtrim($buffer));
240 } while ($buffer[strlen($buffer)-1] != "\n");
245 function multLine($line, $escape=false)
247 $line = rtrim($line);
248 if (preg_match('/\{[0-9]+\}$/', $line)) {
251 preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
253 while (strlen($out) < $bytes) {
254 $line = $this->readBytes($bytes);
260 $line = $a[1][0] . ($escape ? $this->escape($out) : $out);
266 function readBytes($bytes)
270 while ($len < $bytes && !feof($this->fp))
272 $d = fread($this->fp, $bytes-$len);
274 $this->debug('S: '. $d);
277 $data_len = strlen($data);
278 if ($len == $data_len) {
279 break; // nothing was read -> exit to avoid apache lockups
287 function readReply(&$untagged=null)
290 $line = trim($this->readLine(1024));
291 // store untagged response lines
294 } while ($line[0] == '*');
297 $untagged = join("\n", $untagged);
302 function parseResult($string, $err_prefix='')
304 if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
305 $res = strtoupper($matches[1]);
306 $str = trim($matches[2]);
309 $this->errornum = self::ERROR_OK;
310 } else if ($res == 'NO') {
311 $this->errornum = self::ERROR_NO;
312 } else if ($res == 'BAD') {
313 $this->errornum = self::ERROR_BAD;
314 } else if ($res == 'BYE') {
317 $this->errornum = self::ERROR_BYE;
322 // get response string and code (RFC5530)
323 if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
324 $this->resultcode = strtoupper($m[1]);
325 $str = trim(substr($str, strlen($m[1]) + 2));
328 $this->resultcode = null;
330 $this->result = $str;
332 if ($this->errornum != self::ERROR_OK) {
333 $this->error = $err_prefix ? $err_prefix.$str : $str;
337 return $this->errornum;
339 return self::ERROR_UNKNOWN;
342 function setError($code, $msg='')
344 $this->errornum = $code;
348 // check if $string starts with $match (or * BYE/BAD)
349 function startsWith($string, $match, $error=false, $nonempty=false)
351 $len = strlen($match);
358 if (strncmp($string, $match, $len) == 0) {
361 if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
362 if (strtoupper($m[1]) == 'BYE') {
368 if ($nonempty && !strlen($string)) {
374 private function hasCapability($name)
376 if (empty($this->capability) || $name == '') {
380 if (in_array($name, $this->capability)) {
383 else if (strpos($name, '=')) {
388 foreach ($this->capability as $cap) {
389 $entry = explode('=', $cap);
390 if ($entry[0] == $name) {
391 $result[] = $entry[1];
395 return !empty($result) ? $result : false;
399 * Capabilities checker
401 * @param string $name Capability name
403 * @return mixed Capability values array for key=value pairs, true/false for others
405 function getCapability($name)
407 $result = $this->hasCapability($name);
409 if (!empty($result)) {
412 else if ($this->capability_readed) {
416 // get capabilities (only once) because initial
417 // optional CAPABILITY response may differ
418 $result = $this->execute('CAPABILITY');
420 if ($result[0] == self::ERROR_OK) {
421 $this->parseCapability($result[1]);
424 $this->capability_readed = true;
426 return $this->hasCapability($name);
429 function clearCapability()
431 $this->capability = array();
432 $this->capability_readed = false;
436 * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
438 * @param string $user
439 * @param string $pass
440 * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
442 * @return resource Connection resourse on success, error code on error
444 function authenticate($user, $pass, $type='PLAIN')
446 if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
447 if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
448 $this->setError(self::ERROR_BYE,
449 "The Auth_SASL package is required for DIGEST-MD5 authentication");
450 return self::ERROR_BAD;
453 $this->putLine($this->nextTag() . " AUTHENTICATE $type");
454 $line = trim($this->readReply());
456 if ($line[0] == '+') {
457 $challenge = substr($line, 2);
460 return $this->parseResult($line);
463 if ($type == 'CRAM-MD5') {
468 // initialize ipad, opad
469 for ($i=0; $i<64; $i++) {
474 // pad $pass so it's 64 bytes
475 $padLen = 64 - strlen($pass);
476 for ($i=0; $i<$padLen; $i++) {
481 $hash = md5($this->_xor($pass, $opad) . pack("H*",
482 md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
483 $reply = base64_encode($user . ' ' . $hash);
486 $this->putLine($reply);
489 // RFC2831: DIGEST-MD5
490 // proxy authorization
491 if (!empty($this->prefs['auth_cid'])) {
492 $authc = $this->prefs['auth_cid'];
493 $pass = $this->prefs['auth_pw'];
498 $auth_sasl = Auth_SASL::factory('digestmd5');
499 $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
500 base64_decode($challenge), $this->host, 'imap', $user));
503 $this->putLine($reply);
504 $line = trim($this->readReply());
506 if ($line[0] == '+') {
507 $challenge = substr($line, 2);
510 return $this->parseResult($line);
514 $challenge = base64_decode($challenge);
515 if (strpos($challenge, 'rspauth=') === false) {
516 $this->setError(self::ERROR_BAD,
517 "Unexpected response from server to DIGEST-MD5 response");
518 return self::ERROR_BAD;
524 $line = $this->readReply();
525 $result = $this->parseResult($line);
528 // proxy authorization
529 if (!empty($this->prefs['auth_cid'])) {
530 $authc = $this->prefs['auth_cid'];
531 $pass = $this->prefs['auth_pw'];
537 $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
539 // RFC 4959 (SASL-IR): save one round trip
540 if ($this->getCapability('SASL-IR')) {
541 list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
542 self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY);
545 $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
546 $line = trim($this->readReply());
548 if ($line[0] != '+') {
549 return $this->parseResult($line);
552 // send result, get reply and process it
553 $this->putLine($reply);
554 $line = $this->readReply();
555 $result = $this->parseResult($line);
559 if ($result == self::ERROR_OK) {
560 // optional CAPABILITY response
561 if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
562 $this->parseCapability($matches[1], true);
567 $this->setError($result, "AUTHENTICATE $type: $line");
574 * LOGIN Authentication
576 * @param string $user
577 * @param string $pass
579 * @return resource Connection resourse on success, error code on error
581 function login($user, $password)
583 list($code, $response) = $this->execute('LOGIN', array(
584 $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
586 // re-set capabilities list if untagged CAPABILITY response provided
587 if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
588 $this->parseCapability($matches[1], true);
591 if ($code == self::ERROR_OK) {
601 * @return string The delimiter
603 function getHierarchyDelimiter()
605 if ($this->prefs['delimiter']) {
606 return $this->prefs['delimiter'];
609 // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
610 list($code, $response) = $this->execute('LIST',
611 array($this->escape(''), $this->escape('')));
613 if ($code == self::ERROR_OK) {
614 $args = $this->tokenizeResponse($response, 4);
615 $delimiter = $args[3];
617 if (strlen($delimiter) > 0) {
618 return ($this->prefs['delimiter'] = $delimiter);
626 * NAMESPACE handler (RFC 2342)
628 * @return array Namespace data hash (personal, other, shared)
630 function getNamespace()
632 if (array_key_exists('namespace', $this->prefs)) {
633 return $this->prefs['namespace'];
636 if (!$this->getCapability('NAMESPACE')) {
637 return self::ERROR_BAD;
640 list($code, $response) = $this->execute('NAMESPACE');
642 if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
643 $data = $this->tokenizeResponse(substr($response, 11));
646 if (!is_array($data)) {
650 $this->prefs['namespace'] = array(
651 'personal' => $data[0],
653 'shared' => $data[2],
656 return $this->prefs['namespace'];
659 function connect($host, $user, $password, $options=null)
662 if (is_array($options)) {
663 $this->prefs = $options;
666 if (!empty($this->prefs['auth_method'])) {
667 $auth_method = strtoupper($this->prefs['auth_method']);
669 $auth_method = 'CHECK';
674 // initialize connection
676 $this->errornum = self::ERROR_OK;
677 $this->selected = '';
680 $this->logged = false;
684 $this->setError(self::ERROR_BAD, "Empty host");
688 $this->setError(self::ERROR_NO, "Empty user");
691 if (empty($password)) {
692 $this->setError(self::ERROR_NO, "Empty password");
696 if (!$this->prefs['port']) {
697 $this->prefs['port'] = 143;
700 if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
701 $host = $this->prefs['ssl_mode'] . '://' . $host;
705 if ($this->prefs['timeout'] > 0)
706 $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
708 $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr);
711 $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
715 if ($this->prefs['timeout'] > 0)
716 stream_set_timeout($this->fp, $this->prefs['timeout']);
718 $line = trim(fgets($this->fp, 8192));
720 if ($this->_debug && $line) {
721 $this->debug('S: '. $line);
724 // Connected to wrong port or connection error?
725 if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
727 $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
729 $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
731 $this->setError(self::ERROR_BAD, $error);
732 $this->closeConnection();
736 // RFC3501 [7.1] optional CAPABILITY response
737 if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
738 $this->parseCapability($matches[1], true);
742 if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
743 if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
744 $res = $this->execute('STARTTLS');
746 if ($res[0] != self::ERROR_OK) {
747 $this->closeConnection();
751 if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
752 $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
753 $this->closeConnection();
757 // Now we're secure, capabilities need to be reread
758 $this->clearCapability();
763 if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
764 $this->id($this->prefs['ident']);
767 $auth_methods = array();
770 // check for supported auth methods
771 if ($auth_method == 'CHECK') {
772 if ($auth_caps = $this->getCapability('AUTH')) {
773 $auth_methods = $auth_caps;
775 // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
776 $login_disabled = $this->getCapability('LOGINDISABLED');
777 if (($key = array_search('LOGIN', $auth_methods)) !== false) {
778 if ($login_disabled) {
779 unset($auth_methods[$key]);
782 else if (!$login_disabled) {
783 $auth_methods[] = 'LOGIN';
787 // Prevent from sending credentials in plain text when connection is not secure
788 if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
789 $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
790 $this->closeConnection();
793 // replace AUTH with CRAM-MD5 for backward compat.
794 $auth_methods[] = $auth_method == 'AUTH' ? 'CRAM-MD5' : $auth_method;
797 // pre-login capabilities can be not complete
798 $this->capability_readed = false;
801 foreach ($auth_methods as $method) {
804 $method = 'CRAM-MD5';
808 $result = $this->authenticate($user, $password, $method);
811 $result = $this->login($user, $password);
814 $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $method");
817 if (is_resource($result)) {
822 // Connected and authenticated
823 if (is_resource($result)) {
824 if ($this->prefs['force_caps']) {
825 $this->clearCapability();
827 $this->logged = true;
832 $this->closeConnection();
839 return ($this->fp && $this->logged) ? true : false;
842 function closeConnection()
844 if ($this->putLine($this->nextTag() . ' LOGOUT')) {
853 * Executes SELECT command (if mailbox is already not in selected state)
855 * @param string $mailbox Mailbox name
857 * @return boolean True on success, false on error
860 function select($mailbox)
862 if (!strlen($mailbox)) {
866 if ($this->selected == $mailbox) {
870 Temporary commented out because Courier returns \Noselect for INBOX
871 Requires more investigation
873 if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
874 if (in_array('\\Noselect', $opts)) {
879 list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
881 if ($code == self::ERROR_OK) {
882 $response = explode("\r\n", $response);
883 foreach ($response as $line) {
884 if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
885 $this->data[strtoupper($m[2])] = (int) $m[1];
887 else if (preg_match('/^\* OK \[(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)\]/i', $line, $match)) {
888 $this->data[strtoupper($match[1])] = (int) $match[2];
890 else if (preg_match('/^\* OK \[PERMANENTFLAGS \(([^\)]+)\)\]/iU', $line, $match)) {
891 $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
895 $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
897 $this->selected = $mailbox;
905 * Executes STATUS command
907 * @param string $mailbox Mailbox name
908 * @param array $items Additional requested item names. By default
909 * MESSAGES and UNSEEN are requested. Other defined
910 * in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
912 * @return array Status item-value hash
916 function status($mailbox, $items=array())
918 if (!strlen($mailbox)) {
922 if (!in_array('MESSAGES', $items)) {
923 $items[] = 'MESSAGES';
925 if (!in_array('UNSEEN', $items)) {
929 list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
930 '(' . implode(' ', (array) $items) . ')'));
932 if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
934 $response = substr($response, 9); // remove prefix "* STATUS "
936 list($mbox, $items) = $this->tokenizeResponse($response, 2);
938 for ($i=0, $len=count($items); $i<$len; $i += 2) {
939 $result[$items[$i]] = (int) $items[$i+1];
942 $this->data['STATUS:'.$mailbox] = $result;
951 * Executes EXPUNGE command
953 * @param string $mailbox Mailbox name
954 * @param string $messages Message UIDs to expunge
956 * @return boolean True on success, False on error
959 function expunge($mailbox, $messages=NULL)
961 if (!$this->select($mailbox)) {
965 if (!$this->data['READ-WRITE']) {
966 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
970 // Clear internal status cache
971 unset($this->data['STATUS:'.$mailbox]);
974 $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
976 $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
978 if ($result == self::ERROR_OK) {
979 $this->selected = ''; // state has changed, need to reselect
987 * Executes CLOSE command
989 * @return boolean True on success, False on error
995 $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
997 if ($result == self::ERROR_OK) {
998 $this->selected = '';
1006 * Executes SUBSCRIBE command
1008 * @param string $mailbox Mailbox name
1010 * @return boolean True on success, False on error
1013 function subscribe($mailbox)
1015 $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1016 self::COMMAND_NORESPONSE);
1018 return ($result == self::ERROR_OK);
1022 * Executes UNSUBSCRIBE command
1024 * @param string $mailbox Mailbox name
1026 * @return boolean True on success, False on error
1029 function unsubscribe($mailbox)
1031 $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1032 self::COMMAND_NORESPONSE);
1034 return ($result == self::ERROR_OK);
1038 * Executes DELETE command
1040 * @param string $mailbox Mailbox name
1042 * @return boolean True on success, False on error
1045 function deleteFolder($mailbox)
1047 $result = $this->execute('DELETE', array($this->escape($mailbox)),
1048 self::COMMAND_NORESPONSE);
1050 return ($result == self::ERROR_OK);
1054 * Removes all messages in a folder
1056 * @param string $mailbox Mailbox name
1058 * @return boolean True on success, False on error
1061 function clearFolder($mailbox)
1063 $num_in_trash = $this->countMessages($mailbox);
1064 if ($num_in_trash > 0) {
1065 $res = $this->delete($mailbox, '1:*');
1069 if ($this->selected == $mailbox)
1070 $res = $this->close();
1072 $res = $this->expunge($mailbox);
1079 * Returns count of all messages in a folder
1081 * @param string $mailbox Mailbox name
1083 * @return int Number of messages, False on error
1086 function countMessages($mailbox, $refresh = false)
1089 $this->selected = '';
1092 if ($this->selected == $mailbox) {
1093 return $this->data['EXISTS'];
1096 // Check internal cache
1097 $cache = $this->data['STATUS:'.$mailbox];
1098 if (!empty($cache) && isset($cache['MESSAGES'])) {
1099 return (int) $cache['MESSAGES'];
1102 // Try STATUS (should be faster than SELECT)
1103 $counts = $this->status($mailbox);
1104 if (is_array($counts)) {
1105 return (int) $counts['MESSAGES'];
1112 * Returns count of messages with \Recent flag in a folder
1114 * @param string $mailbox Mailbox name
1116 * @return int Number of messages, False on error
1119 function countRecent($mailbox)
1121 if (!strlen($mailbox)) {
1125 $this->select($mailbox);
1127 if ($this->selected == $mailbox) {
1128 return $this->data['RECENT'];
1135 * Returns count of messages without \Seen flag in a specified folder
1137 * @param string $mailbox Mailbox name
1139 * @return int Number of messages, False on error
1142 function countUnseen($mailbox)
1144 // Check internal cache
1145 $cache = $this->data['STATUS:'.$mailbox];
1146 if (!empty($cache) && isset($cache['UNSEEN'])) {
1147 return (int) $cache['UNSEEN'];
1150 // Try STATUS (should be faster than SELECT+SEARCH)
1151 $counts = $this->status($mailbox);
1152 if (is_array($counts)) {
1153 return (int) $counts['UNSEEN'];
1156 // Invoke SEARCH as a fallback
1157 $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1158 if (is_array($index)) {
1159 return (int) $index['COUNT'];
1166 * Executes ID command (RFC2971)
1168 * @param array $items Client identification information key/value hash
1170 * @return array Server identification information key/value hash
1174 function id($items=array())
1176 if (is_array($items) && !empty($items)) {
1177 foreach ($items as $key => $value) {
1178 $args[] = $this->escape($key);
1179 $args[] = $this->escape($value);
1183 list($code, $response) = $this->execute('ID', array(
1184 !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1188 if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
1189 $response = substr($response, 5); // remove prefix "* ID "
1190 $items = $this->tokenizeResponse($response);
1193 for ($i=0, $len=count($items); $i<$len; $i += 2) {
1194 $result[$items[$i]] = $items[$i+1];
1203 function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1205 $field = strtoupper($field);
1206 if ($field == 'INTERNALDATE') {
1210 $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1211 'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1213 if (!$fields[$field]) {
1217 if (!$this->select($mailbox)) {
1223 $add = $this->compressMessageSet($add);
1225 list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1226 array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1228 if ($code == self::ERROR_OK) {
1229 // remove prefix and unilateral untagged server responses
1230 $response = substr($response, stripos($response, '* SORT') + 7);
1231 if ($pos = strpos($response, '*')) {
1232 $response = substr($response, 0, $pos);
1234 return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1240 function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1242 if (is_array($message_set)) {
1243 if (!($message_set = $this->compressMessageSet($message_set)))
1246 list($from_idx, $to_idx) = explode(':', $message_set);
1247 if (empty($message_set) ||
1248 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1253 $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1255 $fields_a['DATE'] = 1;
1256 $fields_a['INTERNALDATE'] = 4;
1257 $fields_a['ARRIVAL'] = 4;
1258 $fields_a['FROM'] = 1;
1259 $fields_a['REPLY-TO'] = 1;
1260 $fields_a['SENDER'] = 1;
1261 $fields_a['TO'] = 1;
1262 $fields_a['CC'] = 1;
1263 $fields_a['SUBJECT'] = 1;
1264 $fields_a['UID'] = 2;
1265 $fields_a['SIZE'] = 2;
1266 $fields_a['SEEN'] = 3;
1267 $fields_a['RECENT'] = 3;
1268 $fields_a['DELETED'] = 3;
1270 if (!($mode = $fields_a[$index_field])) {
1274 /* Do "SELECT" command */
1275 if (!$this->select($mailbox)) {
1279 // build FETCH command string
1280 $key = $this->nextTag();
1281 $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
1282 $deleted = $skip_deleted ? ' FLAGS' : '';
1284 if ($mode == 1 && $index_field == 'DATE')
1285 $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1286 else if ($mode == 1)
1287 $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1288 else if ($mode == 2) {
1289 if ($index_field == 'SIZE')
1290 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1292 $request = " $cmd $message_set ($index_field$deleted)";
1293 } else if ($mode == 3)
1294 $request = " $cmd $message_set (FLAGS)";
1296 $request = " $cmd $message_set (INTERNALDATE$deleted)";
1298 $request = $key . $request;
1300 if (!$this->putLine($request)) {
1301 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1308 $line = rtrim($this->readLine(200));
1309 $line = $this->multLine($line);
1311 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1315 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1316 $flags = explode(' ', strtoupper($matches[1]));
1317 if (in_array('\\DELETED', $flags)) {
1318 $deleted[$id] = $id;
1323 if ($mode == 1 && $index_field == 'DATE') {
1324 if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1325 $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1326 $value = trim($value);
1327 $result[$id] = $this->strToTime($value);
1329 // non-existent/empty Date: header, use INTERNALDATE
1330 if (empty($result[$id])) {
1331 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1332 $result[$id] = $this->strToTime($matches[1]);
1336 } else if ($mode == 1) {
1337 if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1338 $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1339 $result[$id] = trim($value);
1343 } else if ($mode == 2) {
1344 if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1345 $result[$id] = trim($matches[2]);
1349 } else if ($mode == 3) {
1350 if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1351 $flags = explode(' ', $matches[1]);
1353 $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1354 } else if ($mode == 4) {
1355 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1356 $result[$id] = $this->strToTime($matches[1]);
1362 } while (!$this->startsWith($line, $key, true, true));
1367 static function compressMessageSet($messages, $force=false)
1369 // given a comma delimited list of independent mid's,
1370 // compresses by grouping sequences together
1372 if (!is_array($messages)) {
1373 // if less than 255 bytes long, let's not bother
1374 if (!$force && strlen($messages)<255) {
1378 // see if it's already been compressed
1379 if (strpos($messages, ':') !== false) {
1383 // separate, then sort
1384 $messages = explode(',', $messages);
1390 $start = $prev = $messages[0];
1392 foreach ($messages as $id) {
1393 $incr = $id - $prev;
1394 if ($incr > 1) { // found a gap
1395 if ($start == $prev) {
1396 $result[] = $prev; // push single id
1398 $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1400 $start = $id; // start of new sequence
1405 // handle the last sequence/id
1406 if ($start == $prev) {
1409 $result[] = $start.':'.$prev;
1412 // return as comma separated string
1413 return implode(',', $result);
1416 static function uncompressMessageSet($messages)
1419 $messages = explode(',', $messages);
1421 foreach ($messages as $part) {
1422 $items = explode(':', $part);
1423 $max = max($items[0], $items[1]);
1425 for ($x=$items[0]; $x<=$max; $x++) {
1434 * Returns message sequence identifier
1436 * @param string $mailbox Mailbox name
1437 * @param int $uid Message unique identifier (UID)
1439 * @return int Message sequence identifier
1442 function UID2ID($mailbox, $uid)
1445 $id_a = $this->search($mailbox, "UID $uid");
1446 if (is_array($id_a) && count($id_a) == 1) {
1447 return (int) $id_a[0];
1454 * Returns message unique identifier (UID)
1456 * @param string $mailbox Mailbox name
1457 * @param int $uid Message sequence identifier
1459 * @return int Message unique identifier
1462 function ID2UID($mailbox, $id)
1464 if (empty($id) || $id < 0) {
1468 if (!$this->select($mailbox)) {
1472 list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1474 if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1481 function fetchUIDs($mailbox, $message_set=null)
1483 if (is_array($message_set))
1484 $message_set = join(',', $message_set);
1485 else if (empty($message_set))
1486 $message_set = '1:*';
1488 return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1491 function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1495 if (!$this->select($mailbox)) {
1499 $message_set = $this->compressMessageSet($message_set);
1502 $add = ' '.trim($add);
1504 /* FETCH uid, size, flags and headers */
1505 $key = $this->nextTag();
1506 $request = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1507 $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1509 $request .= "BODYSTRUCTURE ";
1510 $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1511 $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1513 if (!$this->putLine($request)) {
1514 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1518 $line = $this->readLine(4096);
1519 $line = $this->multLine($line);
1524 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1525 $id = intval($m[1]);
1527 $result[$id] = new rcube_mail_header;
1528 $result[$id]->id = $id;
1529 $result[$id]->subject = '';
1530 $result[$id]->messageID = 'mid:' . $id;
1535 // Sample reply line:
1536 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1537 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1538 // BODY[HEADER.FIELDS ...
1540 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/sU', $line, $matches)) {
1543 // swap parents with quotes, then explode
1544 $str = preg_replace('/[()]/', '"', $str);
1545 $a = rcube_explode_quoted_string(' ', $str);
1547 // did we get the right number of replies?
1548 $parts_count = count($a);
1549 if ($parts_count>=6) {
1550 for ($i=0; $i<$parts_count; $i=$i+2) {
1551 if ($a[$i] == 'UID') {
1552 $result[$id]->uid = intval($a[$i+1]);
1554 else if ($a[$i] == 'RFC822.SIZE') {
1555 $result[$id]->size = intval($a[$i+1]);
1557 else if ($a[$i] == 'INTERNALDATE') {
1558 $time_str = $a[$i+1];
1560 else if ($a[$i] == 'FLAGS') {
1561 $flags_str = $a[$i+1];
1565 $time_str = str_replace('"', '', $time_str);
1567 // if time is gmt...
1568 $time_str = str_replace('GMT','+0000',$time_str);
1570 $result[$id]->internaldate = $time_str;
1571 $result[$id]->timestamp = $this->StrToTime($time_str);
1572 $result[$id]->date = $time_str;
1577 while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/sU', $line, $m)) {
1578 $line2 = $this->readLine(1024);
1579 $line .= $this->multLine($line2, true);
1581 $result[$id]->body_structure = $m[1];
1584 // the rest of the result
1585 if (preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m)) {
1586 $reslines = explode("\n", trim($m[1], '"'));
1587 // re-parse (see below)
1588 foreach ($reslines as $resln) {
1589 if (ord($resln[0])<=32) {
1590 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1592 $lines[++$ln] = trim($resln);
1598 // Start parsing headers. The problem is, some header "lines" take up multiple lines.
1599 // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1600 // process the previous line. Otherwise, we'll keep adding the strings until we come
1601 // to the next valid header line.
1604 $line = rtrim($this->readLine(300), "\r\n");
1606 // The preg_match below works around communigate imap, which outputs " UID <number>)".
1607 // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1608 // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1609 // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1610 // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1611 // An alternative might be:
1612 // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1613 // however, unsure how well this would work with all imap clients.
1614 if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1618 // handle FLAGS reply after headers (AOL, Zimbra?)
1619 if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1620 $flags_str = $matches[1];
1624 if (ord($line[0])<=32) {
1625 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1627 $lines[++$ln] = trim($line);
1629 // patch from "Maksim Rubis" <siburny@hotmail.com>
1630 } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1632 if (strncmp($line, $key, strlen($key))) {
1633 // process header, fill rcube_mail_header obj.
1635 if (is_array($headers)) {
1637 while (list($k, $bar) = each($headers)) {
1642 // create array with header field:data
1643 while (list($lines_key, $str) = each($lines)) {
1644 list($field, $string) = $this->splitHeaderLine($str);
1646 $field = strtolower($field);
1647 $string = preg_replace('/\n\s*/', ' ', $string);
1651 $result[$id]->date = $string;
1652 $result[$id]->timestamp = $this->strToTime($string);
1655 $result[$id]->from = $string;
1658 $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1661 $result[$id]->subject = $string;
1664 $result[$id]->replyto = $string;
1667 $result[$id]->cc = $string;
1670 $result[$id]->bcc = $string;
1672 case 'content-transfer-encoding':
1673 $result[$id]->encoding = $string;
1675 case 'content-type':
1676 $ctype_parts = preg_split('/[; ]/', $string);
1677 $result[$id]->ctype = strtolower(array_shift($ctype_parts));
1678 if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1679 $result[$id]->charset = $regs[1];
1683 $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1686 $result[$id]->references = $string;
1688 case 'return-receipt-to':
1689 case 'disposition-notification-to':
1690 case 'x-confirm-reading-to':
1691 $result[$id]->mdn_to = $string;
1694 $result[$id]->messageID = $string;
1697 if (preg_match('/^(\d+)/', $string, $matches)) {
1698 $result[$id]->priority = intval($matches[1]);
1702 if (strlen($field) > 2) {
1703 $result[$id]->others[$field] = $string;
1711 if (!empty($flags_str)) {
1712 $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1713 $flags_a = explode(' ', $flags_str);
1715 if (is_array($flags_a)) {
1716 foreach($flags_a as $flag) {
1717 $flag = strtoupper($flag);
1718 if ($flag == 'SEEN') {
1719 $result[$id]->seen = true;
1720 } else if ($flag == 'DELETED') {
1721 $result[$id]->deleted = true;
1722 } else if ($flag == 'RECENT') {
1723 $result[$id]->recent = true;
1724 } else if ($flag == 'ANSWERED') {
1725 $result[$id]->answered = true;
1726 } else if ($flag == '$FORWARDED') {
1727 $result[$id]->forwarded = true;
1728 } else if ($flag == 'DRAFT') {
1729 $result[$id]->is_draft = true;
1730 } else if ($flag == '$MDNSENT') {
1731 $result[$id]->mdn_sent = true;
1732 } else if ($flag == 'FLAGGED') {
1733 $result[$id]->flagged = true;
1736 $result[$id]->flags = $flags_a;
1740 } while (!$this->startsWith($line, $key, true));
1745 function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1747 $a = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1749 return array_shift($a);
1754 function sortHeaders($a, $field, $flag)
1756 if (empty($field)) {
1760 $field = strtolower($field);
1763 if ($field == 'date' || $field == 'internaldate') {
1764 $field = 'timestamp';
1770 $flag = strtoupper($flag);
1776 // First, we'll create an "index" array.
1777 // Then, we'll use sort() on that array,
1778 // and use that to sort the main array.
1780 // create "index" array
1783 while (list($key, $val) = each($a)) {
1784 if ($field == 'timestamp') {
1785 $data = $this->strToTime($val->date);
1787 $data = $val->timestamp;
1790 $data = $val->$field;
1791 if (is_string($data)) {
1792 $data = str_replace('"', '', $data);
1793 if ($field == 'subject') {
1794 $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1796 $data = strtoupper($data);
1799 $index[$key] = $data;
1803 if ($flag == 'ASC') {
1809 // form new array based on index
1812 while (list($key, $val) = each($index)) {
1813 $result[$key] = $a[$key];
1821 function modFlag($mailbox, $messages, $flag, $mod)
1823 if ($mod != '+' && $mod != '-') {
1827 if (!$this->select($mailbox)) {
1831 if (!$this->data['READ-WRITE']) {
1832 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1836 // Clear internal status cache
1837 if ($flag == 'SEEN') {
1838 unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1841 $flag = $this->flags[strtoupper($flag)];
1842 $result = $this->execute('UID STORE', array(
1843 $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1844 self::COMMAND_NORESPONSE);
1846 return ($result == self::ERROR_OK);
1849 function flag($mailbox, $messages, $flag) {
1850 return $this->modFlag($mailbox, $messages, $flag, '+');
1853 function unflag($mailbox, $messages, $flag) {
1854 return $this->modFlag($mailbox, $messages, $flag, '-');
1857 function delete($mailbox, $messages) {
1858 return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1861 function copy($messages, $from, $to)
1863 if (!$this->select($from)) {
1867 // Clear internal status cache
1868 unset($this->data['STATUS:'.$to]);
1870 $result = $this->execute('UID COPY', array(
1871 $this->compressMessageSet($messages), $this->escape($to)),
1872 self::COMMAND_NORESPONSE);
1874 return ($result == self::ERROR_OK);
1877 function move($messages, $from, $to)
1879 if (!$this->select($from)) {
1883 if (!$this->data['READ-WRITE']) {
1884 $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1888 $r = $this->copy($messages, $from, $to);
1891 // Clear internal status cache
1892 unset($this->data['STATUS:'.$from]);
1894 return $this->delete($from, $messages);
1899 // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1900 // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1901 // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1902 private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1905 if ($str[$begin] != '(') {
1906 $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1907 $msg = substr($str, $begin, $stop - $begin);
1912 $depthmap[$msg] = $depth;
1913 $haschildren[$msg] = false;
1914 if (!is_null($parent))
1915 $haschildren[$parent] = true;
1916 if ($stop + 1 < $end)
1917 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1919 $node[$msg] = array();
1922 while ($off < $end) {
1927 $p = strpos($str, ')', $off);
1929 error_log("Mismatched brackets parsing IMAP THREAD response:");
1930 error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1931 error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1934 $p1 = strpos($str, '(', $off);
1935 if ($p1 !== false && $p1 < $p) {
1943 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1950 function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1952 $old_sel = $this->selected;
1954 if (!$this->select($mailbox)) {
1958 // return empty result when folder is empty and we're just after SELECT
1959 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1960 return array(array(), array(), array());
1963 $encoding = $encoding ? trim($encoding) : 'US-ASCII';
1964 $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1965 $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1968 list($code, $response) = $this->execute('THREAD', array(
1969 $algorithm, $encoding, $criteria));
1971 if ($code == self::ERROR_OK) {
1973 $response = substr($response, stripos($response, '* THREAD') + 9);
1974 // ...unilateral untagged server responses
1975 if ($pos = strpos($response, '*')) {
1976 $response = substr($response, 0, $pos);
1979 $response = str_replace("\r\n", '', $response);
1980 $depthmap = array();
1981 $haschildren = array();
1983 $tree = $this->parseThread($response, 0, strlen($response),
1984 null, null, 0, $depthmap, $haschildren);
1986 return array($tree, $depthmap, $haschildren);
1993 * Executes SEARCH command
1995 * @param string $mailbox Mailbox name
1996 * @param string $criteria Searching criteria
1997 * @param bool $return_uid Enable UID in result instead of sequence ID
1998 * @param array $items Return items (MIN, MAX, COUNT, ALL)
2000 * @return array Message identifiers or item-value hash
2002 function search($mailbox, $criteria, $return_uid=false, $items=array())
2004 $old_sel = $this->selected;
2006 if (!$this->select($mailbox)) {
2010 // return empty result when folder is empty and we're just after SELECT
2011 if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2013 return array_combine($items, array_fill(0, count($items), 0));
2018 $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
2019 $criteria = trim($criteria);
2023 if (!empty($items) && $esearch) {
2024 $params .= 'RETURN (' . implode(' ', $items) . ')';
2026 if (!empty($criteria)) {
2027 $params .= ($params ? ' ' : '') . $criteria;
2033 list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2036 if ($code == self::ERROR_OK) {
2038 $response = substr($response, stripos($response,
2039 $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
2040 // ...and unilateral untagged server responses
2041 if ($pos = strpos($response, '*')) {
2042 $response = rtrim(substr($response, 0, $pos));
2046 // Skip prefix: ... (TAG "A285") UID ...
2047 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2050 for ($i=0; $i<count($items); $i++) {
2051 // If the SEARCH results in no matches, the server MUST NOT
2052 // include the item result option in the ESEARCH response
2053 if ($ret = $this->tokenizeResponse($response, 2)) {
2054 list ($name, $value) = $ret;
2055 $result[$name] = $value;
2062 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2064 if (!empty($items)) {
2066 if (in_array('COUNT', $items)) {
2067 $result['COUNT'] = count($response);
2069 if (in_array('MIN', $items)) {
2070 $result['MIN'] = !empty($response) ? min($response) : 0;
2072 if (in_array('MAX', $items)) {
2073 $result['MAX'] = !empty($response) ? max($response) : 0;
2075 if (in_array('ALL', $items)) {
2076 $result['ALL'] = $this->compressMessageSet($response, true);
2091 * Returns list of mailboxes
2093 * @param string $ref Reference name
2094 * @param string $mailbox Mailbox name
2095 * @param array $status_opts (see self::_listMailboxes)
2096 * @param array $select_opts (see self::_listMailboxes)
2098 * @return array List of mailboxes or hash of options if $status_opts argument
2102 function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2104 return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2108 * Returns list of subscribed mailboxes
2110 * @param string $ref Reference name
2111 * @param string $mailbox Mailbox name
2112 * @param array $status_opts (see self::_listMailboxes)
2114 * @return array List of mailboxes or hash of options if $status_opts argument
2118 function listSubscribed($ref, $mailbox, $status_opts=array())
2120 return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2124 * IMAP LIST/LSUB command
2126 * @param string $ref Reference name
2127 * @param string $mailbox Mailbox name
2128 * @param bool $subscribed Enables returning subscribed mailboxes only
2129 * @param array $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2130 * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2131 * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2132 * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2134 * @return array List of mailboxes or hash of options if $status_ops argument
2138 private function _listMailboxes($ref, $mailbox, $subscribed=false,
2139 $status_opts=array(), $select_opts=array())
2141 if (!strlen($mailbox)) {
2147 if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2148 $select_opts = (array) $select_opts;
2150 $args[] = '(' . implode(' ', $select_opts) . ')';
2153 $args[] = $this->escape($ref);
2154 $args[] = $this->escape($mailbox);
2156 if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2157 $status_opts = (array) $status_opts;
2160 $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2163 list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2165 if ($code == self::ERROR_OK) {
2167 while ($this->tokenizeResponse($response, 1) == '*') {
2168 $cmd = strtoupper($this->tokenizeResponse($response, 1));
2169 // * LIST (<options>) <delimiter> <mailbox>
2170 if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
2171 list($opts, $delim, $mailbox) = $this->tokenizeResponse($response, 3);
2173 // Add to result array
2175 $folders[] = $mailbox;
2178 $folders[$mailbox] = array();
2181 // Add to options array
2182 if (!empty($opts)) {
2183 if (empty($this->data['LIST'][$mailbox]))
2184 $this->data['LIST'][$mailbox] = $opts;
2186 $this->data['LIST'][$mailbox] = array_unique(array_merge(
2187 $this->data['LIST'][$mailbox], $opts));
2190 // * STATUS <mailbox> (<result>)
2191 else if ($cmd == 'STATUS') {
2192 list($mailbox, $status) = $this->tokenizeResponse($response, 2);
2194 for ($i=0, $len=count($status); $i<$len; $i += 2) {
2195 list($name, $value) = $this->tokenizeResponse($status, 2);
2196 $folders[$mailbox][$name] = $value;
2207 function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
2209 if (!$this->select($mailbox)) {
2214 $parts = (array) $parts;
2215 $key = $this->nextTag();
2218 $type = $mime ? 'MIME' : 'HEADER';
2221 foreach($parts as $part) {
2222 $peeks[] = "BODY.PEEK[$part.$type]";
2225 $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2228 if (!$this->putLine($request)) {
2229 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2234 $line = $this->readLine(1024);
2235 $line = $this->multLine($line);
2237 if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2239 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
2240 $result[$idx] = trim($result[$idx], '"');
2241 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2243 } while (!$this->startsWith($line, $key, true));
2248 function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2250 $part = empty($part) ? 'HEADER' : $part.'.MIME';
2252 return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2255 function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2257 if (!$this->select($mailbox)) {
2261 switch ($encoding) {
2265 case 'quoted-printable':
2279 $reply_key = '* ' . $id;
2280 $key = $this->nextTag();
2281 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2284 if (!$this->putLine($request)) {
2285 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2289 // receive reply line
2291 $line = rtrim($this->readLine(1024));
2292 $a = explode(' ', $line);
2293 } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2295 $len = strlen($line);
2298 // handle empty "* X FETCH ()" response
2299 if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2300 // one line response, get everything between first and last quotes
2301 if (substr($line, -4, 3) == 'NIL') {
2305 $from = strpos($line, '"') + 1;
2306 $to = strrpos($line, '"');
2308 $result = substr($line, $from, $len);
2312 $result = base64_decode($result);
2314 else if ($mode == 2) {
2315 $result = quoted_printable_decode($result);
2317 else if ($mode == 3) {
2318 $result = convert_uudecode($result);
2321 } else if ($line[$len-1] == '}') {
2322 // multi-line request, find sizes of content and receive that many bytes
2323 $from = strpos($line, '{') + 1;
2324 $to = strrpos($line, '}');
2326 $sizeStr = substr($line, $from, $len);
2327 $bytes = (int)$sizeStr;
2330 while ($bytes > 0) {
2331 $line = $this->readLine(4096);
2333 if ($line === NULL) {
2337 $len = strlen($line);
2339 if ($len > $bytes) {
2340 $line = substr($line, 0, $bytes);
2341 $len = strlen($line);
2347 $line = rtrim($line, "\t\r\n\0\x0B");
2348 // create chunks with proper length for base64 decoding
2349 $line = $prev.$line;
2350 $length = strlen($line);
2352 $length = floor($length / 4) * 4;
2353 $prev = substr($line, $length);
2354 $line = substr($line, 0, $length);
2358 $line = base64_decode($line);
2360 } else if ($mode == 2) {
2361 $line = rtrim($line, "\t\r\0\x0B");
2362 $line = quoted_printable_decode($line);
2363 // Remove NULL characters (#1486189)
2364 $line = str_replace("\x00", '', $line);
2366 } else if ($mode == 3) {
2367 $line = rtrim($line, "\t\r\n\0\x0B");
2368 if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2370 $line = convert_uudecode($line);
2373 $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2377 fwrite($file, $line);
2385 // read in anything up until last line
2388 $line = $this->readLine(1024);
2389 } while (!$this->startsWith($line, $key, true));
2391 if ($result !== false) {
2393 fwrite($file, $result);
2394 } else if ($print) {
2404 function createFolder($mailbox)
2406 $result = $this->execute('CREATE', array($this->escape($mailbox)),
2407 self::COMMAND_NORESPONSE);
2409 return ($result == self::ERROR_OK);
2412 function renameFolder($from, $to)
2414 $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2415 self::COMMAND_NORESPONSE);
2417 return ($result == self::ERROR_OK);
2420 function append($mailbox, &$message)
2426 $message = str_replace("\r", '', $message);
2427 $message = str_replace("\n", "\r\n", $message);
2429 $len = strlen($message);
2434 $key = $this->nextTag();
2435 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2436 $len, ($this->prefs['literal+'] ? '+' : ''));
2438 if ($this->putLine($request)) {
2439 // Don't wait when LITERAL+ is supported
2440 if (!$this->prefs['literal+']) {
2441 $line = $this->readReply();
2443 if ($line[0] != '+') {
2444 $this->parseResult($line, 'APPEND: ');
2449 if (!$this->putLine($message)) {
2454 $line = $this->readLine();
2455 } while (!$this->startsWith($line, $key, true, true));
2457 // Clear internal status cache
2458 unset($this->data['STATUS:'.$mailbox]);
2460 return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2463 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2469 function appendFromFile($mailbox, $path, $headers=null)
2475 // open message file
2477 if (file_exists(realpath($path))) {
2478 $in_fp = fopen($path, 'r');
2481 $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2485 $body_separator = "\r\n\r\n";
2486 $len = filesize($path);
2493 $headers = preg_replace('/[\r\n]+$/', '', $headers);
2494 $len += strlen($headers) + strlen($body_separator);
2497 // send APPEND command
2498 $key = $this->nextTag();
2499 $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2500 $len, ($this->prefs['literal+'] ? '+' : ''));
2502 if ($this->putLine($request)) {
2503 // Don't wait when LITERAL+ is supported
2504 if (!$this->prefs['literal+']) {
2505 $line = $this->readReply();
2507 if ($line[0] != '+') {
2508 $this->parseResult($line, 'APPEND: ');
2513 // send headers with body separator
2515 $this->putLine($headers . $body_separator, false);
2519 while (!feof($in_fp) && $this->fp) {
2520 $buffer = fgets($in_fp, 4096);
2521 $this->putLine($buffer, false);
2525 if (!$this->putLine('')) { // \r\n
2531 $line = $this->readLine();
2532 } while (!$this->startsWith($line, $key, true, true));
2534 // Clear internal status cache
2535 unset($this->data['STATUS:'.$mailbox]);
2537 return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2540 $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2546 function fetchStructureString($mailbox, $id, $is_uid=false)
2548 if (!$this->select($mailbox)) {
2552 $key = $this->nextTag();
2554 $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2556 if ($this->putLine($command)) {
2558 $line = $this->readLine(5000);
2559 $line = $this->multLine($line, true);
2560 if (!preg_match("/^$key /", $line))
2562 } while (!$this->startsWith($line, $key, true, true));
2564 $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2567 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2576 * GETQUOTAROOT "INBOX"
2577 * QUOTAROOT INBOX user/rchijiiwa1
2578 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2582 $quota_lines = array();
2583 $key = $this->nextTag();
2584 $command = $key . ' GETQUOTAROOT INBOX';
2586 // get line(s) containing quota info
2587 if ($this->putLine($command)) {
2589 $line = rtrim($this->readLine(5000));
2590 if (preg_match('/^\* QUOTA /', $line)) {
2591 $quota_lines[] = $line;
2593 } while (!$this->startsWith($line, $key, true, true));
2596 $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2599 // return false if not found, parse if found
2600 $min_free = PHP_INT_MAX;
2601 foreach ($quota_lines as $key => $quota_line) {
2602 $quota_line = str_replace(array('(', ')'), '', $quota_line);
2603 $parts = explode(' ', $quota_line);
2604 $storage_part = array_search('STORAGE', $parts);
2606 if (!$storage_part) {
2610 $used = intval($parts[$storage_part+1]);
2611 $total = intval($parts[$storage_part+2]);
2612 $free = $total - $used;
2614 // return lowest available space from all quotas
2615 if ($free < $min_free) {
2617 $result['used'] = $used;
2618 $result['total'] = $total;
2619 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2620 $result['free'] = 100 - $result['percent'];
2628 * Send the SETACL command (RFC4314)
2630 * @param string $mailbox Mailbox name
2631 * @param string $user User name
2632 * @param mixed $acl ACL string or array
2634 * @return boolean True on success, False on failure
2639 function setACL($mailbox, $user, $acl)
2641 if (is_array($acl)) {
2642 $acl = implode('', $acl);
2645 $result = $this->execute('SETACL', array(
2646 $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2647 self::COMMAND_NORESPONSE);
2649 return ($result == self::ERROR_OK);
2653 * Send the DELETEACL command (RFC4314)
2655 * @param string $mailbox Mailbox name
2656 * @param string $user User name
2658 * @return boolean True on success, False on failure
2663 function deleteACL($mailbox, $user)
2665 $result = $this->execute('DELETEACL', array(
2666 $this->escape($mailbox), $this->escape($user)),
2667 self::COMMAND_NORESPONSE);
2669 return ($result == self::ERROR_OK);
2673 * Send the GETACL command (RFC4314)
2675 * @param string $mailbox Mailbox name
2677 * @return array User-rights array on success, NULL on error
2681 function getACL($mailbox)
2683 list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2685 if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2686 // Parse server response (remove "* ACL ")
2687 $response = substr($response, 6);
2688 $ret = $this->tokenizeResponse($response);
2689 $mbox = array_shift($ret);
2690 $size = count($ret);
2692 // Create user-rights hash array
2693 // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2694 // so we could return only standard rights defined in RFC4314,
2695 // excluding 'c' and 'd' defined in RFC2086.
2696 if ($size % 2 == 0) {
2697 for ($i=0; $i<$size; $i++) {
2698 $ret[$ret[$i]] = str_split($ret[++$i]);
2705 $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2713 * Send the LISTRIGHTS command (RFC4314)
2715 * @param string $mailbox Mailbox name
2716 * @param string $user User name
2718 * @return array List of user rights
2722 function listRights($mailbox, $user)
2724 list($code, $response) = $this->execute('LISTRIGHTS', array(
2725 $this->escape($mailbox), $this->escape($user)));
2727 if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2728 // Parse server response (remove "* LISTRIGHTS ")
2729 $response = substr($response, 13);
2731 $ret_mbox = $this->tokenizeResponse($response, 1);
2732 $ret_user = $this->tokenizeResponse($response, 1);
2733 $granted = $this->tokenizeResponse($response, 1);
2734 $optional = trim($response);
2737 'granted' => str_split($granted),
2738 'optional' => explode(' ', $optional),
2746 * Send the MYRIGHTS command (RFC4314)
2748 * @param string $mailbox Mailbox name
2750 * @return array MYRIGHTS response on success, NULL on error
2754 function myRights($mailbox)
2756 list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2758 if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2759 // Parse server response (remove "* MYRIGHTS ")
2760 $response = substr($response, 11);
2762 $ret_mbox = $this->tokenizeResponse($response, 1);
2763 $rights = $this->tokenizeResponse($response, 1);
2765 return str_split($rights);
2772 * Send the SETMETADATA command (RFC5464)
2774 * @param string $mailbox Mailbox name
2775 * @param array $entries Entry-value array (use NULL value as NIL)
2777 * @return boolean True on success, False on failure
2781 function setMetadata($mailbox, $entries)
2783 if (!is_array($entries) || empty($entries)) {
2784 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2788 foreach ($entries as $name => $value) {
2789 if ($value === null) {
2793 $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2795 $entries[$name] = $this->escape($name) . ' ' . $value;
2798 $entries = implode(' ', $entries);
2799 $result = $this->execute('SETMETADATA', array(
2800 $this->escape($mailbox), '(' . $entries . ')'),
2801 self::COMMAND_NORESPONSE);
2803 return ($result == self::ERROR_OK);
2807 * Send the SETMETADATA command with NIL values (RFC5464)
2809 * @param string $mailbox Mailbox name
2810 * @param array $entries Entry names array
2812 * @return boolean True on success, False on failure
2817 function deleteMetadata($mailbox, $entries)
2819 if (!is_array($entries) && !empty($entries)) {
2820 $entries = explode(' ', $entries);
2823 if (empty($entries)) {
2824 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2828 foreach ($entries as $entry) {
2829 $data[$entry] = NULL;
2832 return $this->setMetadata($mailbox, $data);
2836 * Send the GETMETADATA command (RFC5464)
2838 * @param string $mailbox Mailbox name
2839 * @param array $entries Entries
2840 * @param array $options Command options (with MAXSIZE and DEPTH keys)
2842 * @return array GETMETADATA result on success, NULL on error
2847 function getMetadata($mailbox, $entries, $options=array())
2849 if (!is_array($entries)) {
2850 $entries = array($entries);
2853 // create entries string
2854 foreach ($entries as $idx => $name) {
2855 $entries[$idx] = $this->escape($name);
2859 $entlist = '(' . implode(' ', $entries) . ')';
2861 // create options string
2862 if (is_array($options)) {
2863 $options = array_change_key_case($options, CASE_UPPER);
2866 if (!empty($options['MAXSIZE'])) {
2867 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2869 if (!empty($options['DEPTH'])) {
2870 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2874 $optlist = '(' . implode(' ', $opts) . ')';
2878 $optlist .= ($optlist ? ' ' : '') . $entlist;
2880 list($code, $response) = $this->execute('GETMETADATA', array(
2881 $this->escape($mailbox), $optlist));
2883 if ($code == self::ERROR_OK) {
2885 $data = $this->tokenizeResponse($response);
2887 // The METADATA response can contain multiple entries in a single
2888 // response or multiple responses for each entry or group of entries
2889 if (!empty($data) && ($size = count($data))) {
2890 for ($i=0; $i<$size; $i++) {
2891 if (isset($mbox) && is_array($data[$i])) {
2892 $size_sub = count($data[$i]);
2893 for ($x=0; $x<$size_sub; $x++) {
2894 $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
2898 else if ($data[$i] == '*') {
2899 if ($data[$i+1] == 'METADATA') {
2900 $mbox = $data[$i+2];
2901 unset($data[$i]); // "*"
2902 unset($data[++$i]); // "METADATA"
2903 unset($data[++$i]); // Mailbox
2905 // get rid of other untagged responses
2911 else if (isset($mbox)) {
2912 $result[$mbox][$data[$i]] = $data[++$i];
2929 * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
2931 * @param string $mailbox Mailbox name
2932 * @param array $data Data array where each item is an array with
2933 * three elements: entry name, attribute name, value
2935 * @return boolean True on success, False on failure
2939 function setAnnotation($mailbox, $data)
2941 if (!is_array($data) || empty($data)) {
2942 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2946 foreach ($data as $entry) {
2951 if ($value === null) {
2955 $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2958 // ANNOTATEMORE drafts before version 08 require quoted parameters
2959 $entries[] = sprintf('%s (%s %s)',
2960 $this->escape($name, true), $this->escape($attr, true), $value);
2963 $entries = implode(' ', $entries);
2964 $result = $this->execute('SETANNOTATION', array(
2965 $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
2967 return ($result == self::ERROR_OK);
2971 * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
2973 * @param string $mailbox Mailbox name
2974 * @param array $data Data array where each item is an array with
2975 * two elements: entry name and attribute name
2977 * @return boolean True on success, False on failure
2982 function deleteAnnotation($mailbox, $data)
2984 if (!is_array($data) || empty($data)) {
2985 $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2989 return $this->setAnnotation($mailbox, $data);
2993 * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
2995 * @param string $mailbox Mailbox name
2996 * @param array $entries Entries names
2997 * @param array $attribs Attribs names
2999 * @return array Annotations result on success, NULL on error
3004 function getAnnotation($mailbox, $entries, $attribs)
3006 if (!is_array($entries)) {
3007 $entries = array($entries);
3009 // create entries string
3010 // ANNOTATEMORE drafts before version 08 require quoted parameters
3011 foreach ($entries as $idx => $name) {
3012 $entries[$idx] = $this->escape($name, true);
3014 $entries = '(' . implode(' ', $entries) . ')';
3016 if (!is_array($attribs)) {
3017 $attribs = array($attribs);
3019 // create entries string
3020 foreach ($attribs as $idx => $name) {
3021 $attribs[$idx] = $this->escape($name, true);
3023 $attribs = '(' . implode(' ', $attribs) . ')';
3025 list($code, $response) = $this->execute('GETANNOTATION', array(
3026 $this->escape($mailbox), $entries, $attribs));
3028 if ($code == self::ERROR_OK) {
3030 $data = $this->tokenizeResponse($response);
3032 // Here we returns only data compatible with METADATA result format
3033 if (!empty($data) && ($size = count($data))) {
3034 for ($i=0; $i<$size; $i++) {
3036 if (isset($mbox) && is_array($entry)) {
3038 $entry = $last_entry;
3040 else if ($entry == '*') {
3041 if ($data[$i+1] == 'ANNOTATION') {
3042 $mbox = $data[$i+2];
3043 unset($data[$i]); // "*"
3044 unset($data[++$i]); // "ANNOTATION"
3045 unset($data[++$i]); // Mailbox
3047 // get rid of other untagged responses
3054 else if (isset($mbox)) {
3055 $attribs = $data[++$i];
3062 if (!empty($attribs)) {
3063 for ($x=0, $len=count($attribs); $x<$len;) {
3064 $attr = $attribs[$x++];
3065 $value = $attribs[$x++];
3066 if ($attr == 'value.priv') {
3067 $result[$mbox]['/private' . $entry] = $value;
3069 else if ($attr == 'value.shared') {
3070 $result[$mbox]['/shared' . $entry] = $value;
3074 $last_entry = $entry;
3086 * Creates next command identifier (tag)
3088 * @return string Command identifier
3095 $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3097 return $this->cmd_tag;
3101 * Sends IMAP command and parses result
3103 * @param string $command IMAP command
3104 * @param array $arguments Command arguments
3105 * @param int $options Execution options
3107 * @return mixed Response code or list of response code and data
3111 function execute($command, $arguments=array(), $options=0)
3113 $tag = $this->nextTag();
3114 $query = $tag . ' ' . $command;
3115 $noresp = ($options & self::COMMAND_NORESPONSE);
3116 $response = $noresp ? null : '';
3118 if (!empty($arguments)) {
3119 $query .= ' ' . implode(' ', $arguments);
3123 if (!$this->putLineC($query)) {
3124 $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3125 return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3130 $line = $this->readLine(4096);
3131 if ($response !== null) {
3134 } while (!$this->startsWith($line, $tag . ' ', true, true));
3136 $code = $this->parseResult($line, $command . ': ');
3138 // Remove last line from response
3140 $line_len = min(strlen($response), strlen($line) + 2);
3141 $response = substr($response, 0, -$line_len);
3144 // optional CAPABILITY response
3145 if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3146 && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3148 $this->parseCapability($matches[1], true);
3151 // return last line only (without command tag, result and response code)
3152 if ($line && ($options & self::COMMAND_LASTLINE)) {
3153 $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3156 return $noresp ? $code : array($code, $response);
3160 * Splits IMAP response into string tokens
3162 * @param string &$str The IMAP's server response
3163 * @param int $num Number of tokens to return
3165 * @return mixed Tokens array or string if $num=1
3169 static function tokenizeResponse(&$str, $num=0)
3173 while (!$num || count($result) < $num) {
3174 // remove spaces from the beginning of the string
3181 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3184 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3187 $result[] = substr($str, $epos + 3, $bytes);
3188 // Advance the string
3189 $str = substr($str, $epos + 3 + $bytes);
3194 $len = strlen($str);
3196 for ($pos=1; $pos<$len; $pos++) {
3197 if ($str[$pos] == '"') {
3200 if ($str[$pos] == "\\") {
3201 if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3206 if ($str[$pos] != '"') {
3209 // we need to strip slashes for a quoted string
3210 $result[] = stripslashes(substr($str, 1, $pos - 1));
3211 $str = substr($str, $pos + 1);
3214 // Parenthesized list
3216 $str = substr($str, 1);
3217 $result[] = self::tokenizeResponse($str);
3220 $str = substr($str, 1);
3224 // String atom, number, NIL, *, %
3226 // empty or one character
3230 if (strlen($str) < 2) {
3236 // excluded chars: SP, CTL, (, ), {, ", ], %
3237 if (preg_match('/^([\x21\x23\x24\x26\x27\x2A-\x5C\x5E-\x7A\x7C-\x7E]+)/', $str, $m)) {
3238 $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3239 $str = substr($str, strlen($m[1]));
3245 return $num == 1 ? $result[0] : $result;
3248 private function _xor($string, $string2)
3251 $size = strlen($string);
3253 for ($i=0; $i<$size; $i++) {
3254 $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3261 * Converts datetime string into unix timestamp
3263 * @param string $date Date string
3265 * @return int Unix timestamp
3267 private function strToTime($date)
3269 // support non-standard "GMTXXXX" literal
3270 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3271 // if date parsing fails, we have a date in non-rfc format.
3272 // remove token from the end and try again
3273 while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
3274 $d = explode(' ', $date);
3279 $date = implode(' ', $d);
3284 return $ts < 0 ? 0 : $ts;
3287 private function splitHeaderLine($string)
3289 $pos = strpos($string, ':');
3291 $res[0] = substr($string, 0, $pos);
3292 $res[1] = trim(substr($string, $pos+1));
3298 private function parseCapability($str, $trusted=false)
3300 $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3302 $this->capability = explode(' ', strtoupper($str));
3304 if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3305 $this->prefs['literal+'] = true;
3309 $this->capability_readed = true;
3314 * Escapes a string when it contains special characters (RFC3501)
3316 * @param string $string IMAP string
3317 * @param boolean $force_quotes Forces string quoting
3319 * @return string Escaped string
3320 * @todo String literals, lists
3322 static function escape($string, $force_quotes=false)
3324 if ($string === null) {
3327 else if ($string === '') {
3330 // need quoted-string? find special chars: SP, CTL, (, ), {, %, *, ", \, ]
3331 // plus [ character as a workaround for DBMail's bug (#1487766)
3332 else if ($force_quotes ||
3333 preg_match('/([\x00-\x20\x28-\x29\x7B\x25\x2A\x22\x5B\x5C\x5D\x7F]+)/', $string)
3335 return '"' . strtr($string, array('"'=>'\\"', '\\' => '\\\\')) . '"';
3342 static function unEscape($string)
3344 return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
3348 * Set the value of the debugging flag.
3350 * @param boolean $debug New value for the debugging flag.
3355 function setDebug($debug, $handler = null)
3357 $this->_debug = $debug;
3358 $this->_debug_handler = $handler;
3362 * Write the given debug text to the current debug output handler.
3364 * @param string $message Debug mesage text.
3369 private function debug($message)
3371 if ($this->_debug_handler) {
3372 call_user_func_array($this->_debug_handler, array(&$this, $message));
3374 echo "DEBUG: $message\n";