]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_imap_generic.php
Imported Upstream version 0.7
[roundcube.git] / program / include / rcube_imap_generic.php
1 <?php
2
3 /**
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_imap_generic.php                                |
6  |                                                                       |
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                                            |
11  |                                                                       |
12  | PURPOSE:                                                              |
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.                                             |
17  |                                                                       |
18  |   Based on Iloha IMAP Library. See http://ilohamail.org/ for details  |
19  |                                                                       |
20  +-----------------------------------------------------------------------+
21  | Author: Aleksander Machniak <alec@alec.pl>                            |
22  | Author: Ryo Chijiiwa <Ryo@IlohaMail.org>                              |
23  +-----------------------------------------------------------------------+
24
25  $Id: rcube_imap_generic.php 5402 2011-11-09 10:03:54Z alec $
26
27 */
28
29
30 /**
31  * Struct representing an e-mail message header
32  *
33  * @package Mail
34  * @author  Aleksander Machniak <alec@alec.pl>
35  */
36 class rcube_mail_header
37 {
38     public $id;
39     public $uid;
40     public $subject;
41     public $from;
42     public $to;
43     public $cc;
44     public $replyto;
45     public $in_reply_to;
46     public $date;
47     public $messageID;
48     public $size;
49     public $encoding;
50     public $charset;
51     public $ctype;
52     public $timestamp;
53     public $bodystructure;
54     public $internaldate;
55     public $references;
56     public $priority;
57     public $mdn_to;
58     public $others = array();
59     public $flags = array();
60 }
61
62 // For backward compatibility with cached messages (#1486602)
63 class iilBasicHeader extends rcube_mail_header
64 {
65 }
66
67 /**
68  * PHP based wrapper class to connect to an IMAP server
69  *
70  * @package Mail
71  * @author  Aleksander Machniak <alec@alec.pl>
72  */
73 class rcube_imap_generic
74 {
75     public $error;
76     public $errornum;
77     public $result;
78     public $resultcode;
79     public $selected;
80     public $data = array();
81     public $flags = array(
82         'SEEN'     => '\\Seen',
83         'DELETED'  => '\\Deleted',
84         'ANSWERED' => '\\Answered',
85         'DRAFT'    => '\\Draft',
86         'FLAGGED'  => '\\Flagged',
87         'FORWARDED' => '$Forwarded',
88         'MDNSENT'  => '$MDNSent',
89         '*'        => '\\*',
90     );
91
92     private $fp;
93     private $host;
94     private $logged = false;
95     private $capability = array();
96     private $capability_readed = false;
97     private $prefs;
98     private $cmd_tag;
99     private $cmd_num = 0;
100     private $resourceid;
101     private $_debug = false;
102     private $_debug_handler = false;
103
104     const ERROR_OK = 0;
105     const ERROR_NO = -1;
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;
111
112     const COMMAND_NORESPONSE = 1;
113     const COMMAND_CAPABILITY = 2;
114     const COMMAND_LASTLINE   = 4;
115
116     /**
117      * Object constructor
118      */
119     function __construct()
120     {
121     }
122
123     /**
124      * Send simple (one line) command to the connection stream
125      *
126      * @param string $string Command string
127      * @param bool   $endln  True if CRLF need to be added at the end of command
128      *
129      * @param int Number of bytes sent, False on error
130      */
131     function putLine($string, $endln=true)
132     {
133         if (!$this->fp)
134             return false;
135
136         if ($this->_debug) {
137             $this->debug('C: '. rtrim($string));
138         }
139
140         $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
141
142         if ($res === false) {
143             @fclose($this->fp);
144             $this->fp = null;
145         }
146
147         return $res;
148     }
149
150     /**
151      * Send command to the connection stream with Command Continuation
152      * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
153      *
154      * @param string $string Command string
155      * @param bool   $endln  True if CRLF need to be added at the end of command
156      *
157      * @param int Number of bytes sent, False on error
158      */
159     function putLineC($string, $endln=true)
160     {
161         if (!$this->fp)
162             return false;
163
164         if ($endln)
165             $string .= "\r\n";
166
167
168         $res = 0;
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)) {
172                     // LITERAL+ support
173                     if ($this->prefs['literal+']) {
174                         $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
175                     }
176
177                     $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
178                     if ($bytes === false)
179                         return false;
180                     $res += $bytes;
181
182                     // don't wait if server supports LITERAL+ capability
183                     if (!$this->prefs['literal+']) {
184                         $line = $this->readLine(1000);
185                         // handle error in command
186                         if ($line[0] != '+')
187                             return false;
188                     }
189                     $i++;
190                 }
191                 else {
192                     $bytes = $this->putLine($parts[$i], false);
193                     if ($bytes === false)
194                         return false;
195                     $res += $bytes;
196                 }
197             }
198         }
199         return $res;
200     }
201
202     function readLine($size=1024)
203     {
204         $line = '';
205
206         if (!$size) {
207             $size = 1024;
208         }
209
210         do {
211             if ($this->eof()) {
212                 return $line ? $line : NULL;
213             }
214
215             $buffer = fgets($this->fp, $size);
216
217             if ($buffer === false) {
218                 $this->closeSocket();
219                 break;
220             }
221             if ($this->_debug) {
222                 $this->debug('S: '. rtrim($buffer));
223             }
224             $line .= $buffer;
225         } while (substr($buffer, -1) != "\n");
226
227         return $line;
228     }
229
230     function multLine($line, $escape = false)
231     {
232         $line = rtrim($line);
233         if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
234             $out   = '';
235             $str   = substr($line, 0, -strlen($m[0]));
236             $bytes = $m[1];
237
238             while (strlen($out) < $bytes) {
239                 $line = $this->readBytes($bytes);
240                 if ($line === NULL)
241                     break;
242                 $out .= $line;
243             }
244
245             $line = $str . ($escape ? $this->escape($out) : $out);
246         }
247
248         return $line;
249     }
250
251     function readBytes($bytes)
252     {
253         $data = '';
254         $len  = 0;
255         while ($len < $bytes && !$this->eof())
256         {
257             $d = fread($this->fp, $bytes-$len);
258             if ($this->_debug) {
259                 $this->debug('S: '. $d);
260             }
261             $data .= $d;
262             $data_len = strlen($data);
263             if ($len == $data_len) {
264                 break; // nothing was read -> exit to avoid apache lockups
265             }
266             $len = $data_len;
267         }
268
269         return $data;
270     }
271
272     function readReply(&$untagged=null)
273     {
274         do {
275             $line = trim($this->readLine(1024));
276             // store untagged response lines
277             if ($line[0] == '*')
278                 $untagged[] = $line;
279         } while ($line[0] == '*');
280
281         if ($untagged)
282             $untagged = join("\n", $untagged);
283
284         return $line;
285     }
286
287     function parseResult($string, $err_prefix='')
288     {
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]);
292
293             if ($res == 'OK') {
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;
302             }
303
304             if ($str) {
305                 $str = trim($str);
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));
310                 }
311                 else {
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];
316                     }
317                 }
318                 $this->result = $str;
319
320                 if ($this->errornum != self::ERROR_OK) {
321                     $this->error = $err_prefix ? $err_prefix.$str : $str;
322                 }
323             }
324
325             return $this->errornum;
326         }
327         return self::ERROR_UNKNOWN;
328     }
329
330     private function eof()
331     {
332         if (!is_resource($this->fp)) {
333             return true;
334         }
335
336         // If a connection opened by fsockopen() wasn't closed
337         // by the server, feof() will hang.
338         $start = microtime(true);
339
340         if (feof($this->fp) || 
341             ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
342         ) {
343             $this->closeSocket();
344             return true;
345         }
346
347         return false;
348     }
349
350     private function closeSocket()
351     {
352         @fclose($this->fp);
353         $this->fp = null;
354     }
355
356     function setError($code, $msg='')
357     {
358         $this->errornum = $code;
359         $this->error    = $msg;
360     }
361
362     // check if $string starts with $match (or * BYE/BAD)
363     function startsWith($string, $match, $error=false, $nonempty=false)
364     {
365         $len = strlen($match);
366         if ($len == 0) {
367             return false;
368         }
369         if (!$this->fp) {
370             return true;
371         }
372         if (strncmp($string, $match, $len) == 0) {
373             return true;
374         }
375         if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
376             if (strtoupper($m[1]) == 'BYE') {
377                 $this->closeSocket();
378             }
379             return true;
380         }
381         if ($nonempty && !strlen($string)) {
382             return true;
383         }
384         return false;
385     }
386
387     private function hasCapability($name)
388     {
389         if (empty($this->capability) || $name == '') {
390             return false;
391         }
392
393         if (in_array($name, $this->capability)) {
394             return true;
395         }
396         else if (strpos($name, '=')) {
397             return false;
398         }
399
400         $result = array();
401         foreach ($this->capability as $cap) {
402             $entry = explode('=', $cap);
403             if ($entry[0] == $name) {
404                 $result[] = $entry[1];
405             }
406         }
407
408         return !empty($result) ? $result : false;
409     }
410
411     /**
412      * Capabilities checker
413      *
414      * @param string $name Capability name
415      *
416      * @return mixed Capability values array for key=value pairs, true/false for others
417      */
418     function getCapability($name)
419     {
420         $result = $this->hasCapability($name);
421
422         if (!empty($result)) {
423             return $result;
424         }
425         else if ($this->capability_readed) {
426             return false;
427         }
428
429         // get capabilities (only once) because initial
430         // optional CAPABILITY response may differ
431         $result = $this->execute('CAPABILITY');
432
433         if ($result[0] == self::ERROR_OK) {
434             $this->parseCapability($result[1]);
435         }
436
437         $this->capability_readed = true;
438
439         return $this->hasCapability($name);
440     }
441
442     function clearCapability()
443     {
444         $this->capability = array();
445         $this->capability_readed = false;
446     }
447
448     /**
449      * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
450      *
451      * @param string $user
452      * @param string $pass
453      * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
454      *
455      * @return resource Connection resourse on success, error code on error
456      */
457     function authenticate($user, $pass, $type='PLAIN')
458     {
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;
464             }
465
466             $this->putLine($this->nextTag() . " AUTHENTICATE $type");
467             $line = trim($this->readReply());
468
469             if ($line[0] == '+') {
470                 $challenge = substr($line, 2);
471             }
472             else {
473                 return $this->parseResult($line);
474             }
475
476             if ($type == 'CRAM-MD5') {
477                 // RFC2195: CRAM-MD5
478                 $ipad = '';
479                 $opad = '';
480
481                 // initialize ipad, opad
482                 for ($i=0; $i<64; $i++) {
483                     $ipad .= chr(0x36);
484                     $opad .= chr(0x5C);
485                 }
486
487                 // pad $pass so it's 64 bytes
488                 $padLen = 64 - strlen($pass);
489                 for ($i=0; $i<$padLen; $i++) {
490                     $pass .= chr(0);
491                 }
492
493                 // generate hash
494                 $hash  = md5($this->_xor($pass, $opad) . pack("H*",
495                     md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
496                 $reply = base64_encode($user . ' ' . $hash);
497
498                 // send result
499                 $this->putLine($reply);
500             }
501             else {
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'];
507                 }
508                 else {
509                     $authc = $user;
510                 }
511                 $auth_sasl = Auth_SASL::factory('digestmd5');
512                 $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
513                     base64_decode($challenge), $this->host, 'imap', $user));
514
515                 // send result
516                 $this->putLine($reply);
517                 $line = trim($this->readReply());
518
519                 if ($line[0] == '+') {
520                     $challenge = substr($line, 2);
521                 }
522                 else {
523                     return $this->parseResult($line);
524                 }
525
526                 // check response
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;
532                 }
533
534                 $this->putLine('');
535             }
536
537             $line = $this->readReply();
538             $result = $this->parseResult($line);
539         }
540         else { // PLAIN
541             // proxy authorization
542             if (!empty($this->prefs['auth_cid'])) {
543                 $authc = $this->prefs['auth_cid'];
544                 $pass  = $this->prefs['auth_pw'];
545             }
546             else {
547                 $authc = $user;
548             }
549
550             $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
551
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);
556             }
557             else {
558                 $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
559                 $line = trim($this->readReply());
560
561                 if ($line[0] != '+') {
562                     return $this->parseResult($line);
563                 }
564
565                 // send result, get reply and process it
566                 $this->putLine($reply);
567                 $line = $this->readReply();
568                 $result = $this->parseResult($line);
569             }
570         }
571
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);
576             }
577             return $this->fp;
578         }
579         else {
580             $this->setError($result, "AUTHENTICATE $type: $line");
581         }
582
583         return $result;
584     }
585
586     /**
587      * LOGIN Authentication
588      *
589      * @param string $user
590      * @param string $pass
591      *
592      * @return resource Connection resourse on success, error code on error
593      */
594     function login($user, $password)
595     {
596         list($code, $response) = $this->execute('LOGIN', array(
597             $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY);
598
599         // re-set capabilities list if untagged CAPABILITY response provided
600         if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
601             $this->parseCapability($matches[1], true);
602         }
603
604         if ($code == self::ERROR_OK) {
605             return $this->fp;
606         }
607
608         return $code;
609     }
610
611     /**
612      * Gets the delimiter
613      *
614      * @return string The delimiter
615      */
616     function getHierarchyDelimiter()
617     {
618         if ($this->prefs['delimiter']) {
619             return $this->prefs['delimiter'];
620         }
621
622         // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
623         list($code, $response) = $this->execute('LIST',
624             array($this->escape(''), $this->escape('')));
625
626         if ($code == self::ERROR_OK) {
627             $args = $this->tokenizeResponse($response, 4);
628             $delimiter = $args[3];
629
630             if (strlen($delimiter) > 0) {
631                 return ($this->prefs['delimiter'] = $delimiter);
632             }
633         }
634
635         return NULL;
636     }
637
638     /**
639      * NAMESPACE handler (RFC 2342)
640      *
641      * @return array Namespace data hash (personal, other, shared)
642      */
643     function getNamespace()
644     {
645         if (array_key_exists('namespace', $this->prefs)) {
646             return $this->prefs['namespace'];
647         }
648
649         if (!$this->getCapability('NAMESPACE')) {
650             return self::ERROR_BAD;
651         }
652
653         list($code, $response) = $this->execute('NAMESPACE');
654
655         if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
656             $data = $this->tokenizeResponse(substr($response, 11));
657         }
658
659         if (!is_array($data)) {
660             return $code;
661         }
662
663         $this->prefs['namespace'] = array(
664             'personal' => $data[0],
665             'other'    => $data[1],
666             'shared'   => $data[2],
667         );
668
669         return $this->prefs['namespace'];
670     }
671
672     function connect($host, $user, $password, $options=null)
673     {
674         // set options
675         if (is_array($options)) {
676             $this->prefs = $options;
677         }
678         // set auth method
679         if (!empty($this->prefs['auth_type'])) {
680             $auth_method = strtoupper($this->prefs['auth_type']);
681         } else {
682             $auth_method = 'CHECK';
683         }
684
685         $result = false;
686
687         // initialize connection
688         $this->error    = '';
689         $this->errornum = self::ERROR_OK;
690         $this->selected = null;
691         $this->user     = $user;
692         $this->host     = $host;
693         $this->logged   = false;
694
695         // check input
696         if (empty($host)) {
697             $this->setError(self::ERROR_BAD, "Empty host");
698             return false;
699         }
700         if (empty($user)) {
701             $this->setError(self::ERROR_NO, "Empty user");
702             return false;
703         }
704         if (empty($password)) {
705             $this->setError(self::ERROR_NO, "Empty password");
706             return false;
707         }
708
709         if (!$this->prefs['port']) {
710             $this->prefs['port'] = 143;
711         }
712         // check for SSL
713         if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
714             $host = $this->prefs['ssl_mode'] . '://' . $host;
715         }
716
717         if ($this->prefs['timeout'] <= 0) {
718             $this->prefs['timeout'] = ini_get('default_socket_timeout');
719         }
720
721         // Connect
722         $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
723
724         if (!$this->fp) {
725             $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
726             return false;
727         }
728
729         if ($this->prefs['timeout'] > 0)
730             stream_set_timeout($this->fp, $this->prefs['timeout']);
731
732         $line = trim(fgets($this->fp, 8192));
733
734         if ($this->_debug) {
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));
738
739             if ($line)
740                 $this->debug('S: '. $line);
741         }
742
743         // Connected to wrong port or connection error?
744         if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
745             if ($line)
746                 $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
747             else
748                 $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
749
750             $this->setError(self::ERROR_BAD, $error);
751             $this->closeConnection();
752             return false;
753         }
754
755         // RFC3501 [7.1] optional CAPABILITY response
756         if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
757             $this->parseCapability($matches[1], true);
758         }
759
760         // TLS connection
761         if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
762             if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
763                 $res = $this->execute('STARTTLS');
764
765                 if ($res[0] != self::ERROR_OK) {
766                     $this->closeConnection();
767                     return false;
768                 }
769
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();
773                     return false;
774                 }
775
776                 // Now we're secure, capabilities need to be reread
777                 $this->clearCapability();
778             }
779         }
780
781         // Send ID info
782         if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
783             $this->id($this->prefs['ident']);
784         }
785
786         $auth_methods = array();
787         $result       = null;
788
789         // check for supported auth methods
790         if ($auth_method == 'CHECK') {
791             if ($auth_caps = $this->getCapability('AUTH')) {
792                 $auth_methods = $auth_caps;
793             }
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]);
799                 }
800             }
801             else if (!$login_disabled) {
802                 $auth_methods[] = 'LOGIN';
803             }
804
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)) {
808                     break;
809                 }
810             }
811         }
812         else {
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();
817                 return false;
818             }
819             // replace AUTH with CRAM-MD5 for backward compat.
820             if ($auth_method == 'AUTH') {
821                 $auth_method = 'CRAM-MD5';
822             }
823         }
824
825         // pre-login capabilities can be not complete
826         $this->capability_readed = false;
827
828         // Authenticate
829         switch ($auth_method) {
830             case 'CRAM_MD5':
831                 $auth_method = 'CRAM-MD5';
832             case 'CRAM-MD5':
833             case 'DIGEST-MD5':
834             case 'PLAIN':
835                 $result = $this->authenticate($user, $password, $auth_method);
836                 break;
837             case 'LOGIN':
838                 $result = $this->login($user, $password);
839                 break;
840             default:
841                 $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
842         }
843
844         // Connected and authenticated
845         if (is_resource($result)) {
846             if ($this->prefs['force_caps']) {
847                 $this->clearCapability();
848             }
849             $this->logged = true;
850
851             return true;
852         }
853
854         $this->closeConnection();
855
856         return false;
857     }
858
859     function connected()
860     {
861         return ($this->fp && $this->logged) ? true : false;
862     }
863
864     function closeConnection()
865     {
866         if ($this->putLine($this->nextTag() . ' LOGOUT')) {
867             $this->readReply();
868         }
869
870         $this->closeSocket();
871     }
872
873     /**
874      * Executes SELECT command (if mailbox is already not in selected state)
875      *
876      * @param string $mailbox      Mailbox name
877      * @param array  $qresync_data QRESYNC data (RFC5162)
878      *
879      * @return boolean True on success, false on error
880      */
881     function select($mailbox, $qresync_data = null)
882     {
883         if (!strlen($mailbox)) {
884             return false;
885         }
886
887         if ($this->selected === $mailbox) {
888             return true;
889         }
890 /*
891     Temporary commented out because Courier returns \Noselect for INBOX
892     Requires more investigation
893
894         if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
895             if (in_array('\\Noselect', $opts)) {
896                 return false;
897             }
898         }
899 */
900         $params = array($this->escape($mailbox));
901
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);
912         }
913
914         list($code, $response) = $this->execute('SELECT', $params);
915
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];
921                 }
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];
926                     }
927                     else if (preg_match('/^(HIGHESTMODSEQ) ([0-9]+)/i', $line, $match)) {
928                         $this->data[strtoupper($match[1])] = (string) $match[2];
929                     }
930                     else if (preg_match('/^(NOMODSEQ)/i', $line, $match)) {
931                         $this->data[strtoupper($match[1])] = true;
932                     }
933                     else if (preg_match('/^PERMANENTFLAGS \(([^\)]+)\)/iU', $line, $match)) {
934                         $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
935                     }
936                 }
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]);
942
943                     for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
944                         $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
945                     }
946
947                     $this->data['QRESYNC'][$data['uid']] = $data;
948                 }
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);
953
954                     $this->data['VANISHED'] = $v_data;
955                 }
956             }
957
958             $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
959
960             $this->selected = $mailbox;
961             return true;
962         }
963
964         return false;
965     }
966
967     /**
968      * Executes STATUS command
969      *
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
974      *
975      * @return array Status item-value hash
976      * @since 0.5-beta
977      */
978     function status($mailbox, $items=array())
979     {
980         if (!strlen($mailbox)) {
981             return false;
982         }
983
984         if (!in_array('MESSAGES', $items)) {
985             $items[] = 'MESSAGES';
986         }
987         if (!in_array('UNSEEN', $items)) {
988             $items[] = 'UNSEEN';
989         }
990
991         list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
992             '(' . implode(' ', (array) $items) . ')'));
993
994         if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
995             $result   = array();
996             $response = substr($response, 9); // remove prefix "* STATUS "
997
998             list($mbox, $items) = $this->tokenizeResponse($response, 2);
999
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)) {
1006                     return $result;
1007                 }
1008             }
1009
1010             for ($i=0, $len=count($items); $i<$len; $i += 2) {
1011                 $result[$items[$i]] = $items[$i+1];
1012             }
1013
1014             $this->data['STATUS:'.$mailbox] = $result;
1015
1016             return $result;
1017         }
1018
1019         return false;
1020     }
1021
1022     /**
1023      * Executes EXPUNGE command
1024      *
1025      * @param string $mailbox  Mailbox name
1026      * @param string $messages Message UIDs to expunge
1027      *
1028      * @return boolean True on success, False on error
1029      */
1030     function expunge($mailbox, $messages=NULL)
1031     {
1032         if (!$this->select($mailbox)) {
1033             return false;
1034         }
1035
1036         if (!$this->data['READ-WRITE']) {
1037             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
1038             return false;
1039         }
1040
1041         // Clear internal status cache
1042         unset($this->data['STATUS:'.$mailbox]);
1043
1044         if ($messages)
1045             $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
1046         else
1047             $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
1048
1049         if ($result == self::ERROR_OK) {
1050             $this->selected = null; // state has changed, need to reselect
1051             return true;
1052         }
1053
1054         return false;
1055     }
1056
1057     /**
1058      * Executes CLOSE command
1059      *
1060      * @return boolean True on success, False on error
1061      * @since 0.5
1062      */
1063     function close()
1064     {
1065         $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
1066
1067         if ($result == self::ERROR_OK) {
1068             $this->selected = null;
1069             return true;
1070         }
1071
1072         return false;
1073     }
1074
1075     /**
1076      * Executes SUBSCRIBE command
1077      *
1078      * @param string $mailbox Mailbox name
1079      *
1080      * @return boolean True on success, False on error
1081      */
1082     function subscribe($mailbox)
1083     {
1084         $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1085             self::COMMAND_NORESPONSE);
1086
1087         return ($result == self::ERROR_OK);
1088     }
1089
1090     /**
1091      * Executes UNSUBSCRIBE command
1092      *
1093      * @param string $mailbox Mailbox name
1094      *
1095      * @return boolean True on success, False on error
1096      */
1097     function unsubscribe($mailbox)
1098     {
1099         $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1100             self::COMMAND_NORESPONSE);
1101
1102         return ($result == self::ERROR_OK);
1103     }
1104
1105     /**
1106      * Executes DELETE command
1107      *
1108      * @param string $mailbox Mailbox name
1109      *
1110      * @return boolean True on success, False on error
1111      */
1112     function deleteFolder($mailbox)
1113     {
1114         $result = $this->execute('DELETE', array($this->escape($mailbox)),
1115             self::COMMAND_NORESPONSE);
1116
1117         return ($result == self::ERROR_OK);
1118     }
1119
1120     /**
1121      * Removes all messages in a folder
1122      *
1123      * @param string $mailbox Mailbox name
1124      *
1125      * @return boolean True on success, False on error
1126      */
1127     function clearFolder($mailbox)
1128     {
1129         $num_in_trash = $this->countMessages($mailbox);
1130         if ($num_in_trash > 0) {
1131             $res = $this->delete($mailbox, '1:*');
1132         }
1133
1134         if ($res) {
1135             if ($this->selected === $mailbox)
1136                 $res = $this->close();
1137             else
1138                 $res = $this->expunge($mailbox);
1139         }
1140
1141         return $res;
1142     }
1143
1144     /**
1145      * Returns count of all messages in a folder
1146      *
1147      * @param string $mailbox Mailbox name
1148      *
1149      * @return int Number of messages, False on error
1150      */
1151     function countMessages($mailbox, $refresh = false)
1152     {
1153         if ($refresh) {
1154             $this->selected = null;
1155         }
1156
1157         if ($this->selected === $mailbox) {
1158             return $this->data['EXISTS'];
1159         }
1160
1161         // Check internal cache
1162         $cache = $this->data['STATUS:'.$mailbox];
1163         if (!empty($cache) && isset($cache['MESSAGES'])) {
1164             return (int) $cache['MESSAGES'];
1165         }
1166
1167         // Try STATUS (should be faster than SELECT)
1168         $counts = $this->status($mailbox);
1169         if (is_array($counts)) {
1170             return (int) $counts['MESSAGES'];
1171         }
1172
1173         return false;
1174     }
1175
1176     /**
1177      * Returns count of messages with \Recent flag in a folder
1178      *
1179      * @param string $mailbox Mailbox name
1180      *
1181      * @return int Number of messages, False on error
1182      */
1183     function countRecent($mailbox)
1184     {
1185         if (!strlen($mailbox)) {
1186             $mailbox = 'INBOX';
1187         }
1188
1189         $this->select($mailbox);
1190
1191         if ($this->selected === $mailbox) {
1192             return $this->data['RECENT'];
1193         }
1194
1195         return false;
1196     }
1197
1198     /**
1199      * Returns count of messages without \Seen flag in a specified folder
1200      *
1201      * @param string $mailbox Mailbox name
1202      *
1203      * @return int Number of messages, False on error
1204      */
1205     function countUnseen($mailbox)
1206     {
1207         // Check internal cache
1208         $cache = $this->data['STATUS:'.$mailbox];
1209         if (!empty($cache) && isset($cache['UNSEEN'])) {
1210             return (int) $cache['UNSEEN'];
1211         }
1212
1213         // Try STATUS (should be faster than SELECT+SEARCH)
1214         $counts = $this->status($mailbox);
1215         if (is_array($counts)) {
1216             return (int) $counts['UNSEEN'];
1217         }
1218
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'];
1223         }
1224
1225         return false;
1226     }
1227
1228     /**
1229      * Executes ID command (RFC2971)
1230      *
1231      * @param array $items Client identification information key/value hash
1232      *
1233      * @return array Server identification information key/value hash
1234      * @since 0.6
1235      */
1236     function id($items=array())
1237     {
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);
1242             }
1243         }
1244
1245         list($code, $response) = $this->execute('ID', array(
1246             !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1247         ));
1248
1249
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);
1253             $result   = null;
1254
1255             for ($i=0, $len=count($items); $i<$len; $i += 2) {
1256                 $result[$items[$i]] = $items[$i+1];
1257             }
1258
1259             return $result;
1260         }
1261
1262         return false;
1263     }
1264
1265     /**
1266      * Executes ENABLE command (RFC5161)
1267      *
1268      * @param mixed $extension Extension name to enable (or array of names)
1269      *
1270      * @return array|bool List of enabled extensions, False on error
1271      * @since 0.6
1272      */
1273     function enable($extension)
1274     {
1275         if (empty($extension))
1276             return false;
1277
1278         if (!$this->hasCapability('ENABLE'))
1279             return false;
1280
1281         if (!is_array($extension))
1282             $extension = array($extension);
1283
1284         list($code, $response) = $this->execute('ENABLE', $extension);
1285
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);
1289
1290             return $result;
1291         }
1292
1293         return false;
1294     }
1295
1296     function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1297     {
1298         $field = strtoupper($field);
1299         if ($field == 'INTERNALDATE') {
1300             $field = 'ARRIVAL';
1301         }
1302
1303         $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1304             'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1305
1306         if (!$fields[$field]) {
1307             return false;
1308         }
1309
1310         if (!$this->select($mailbox)) {
1311             return false;
1312         }
1313
1314         // message IDs
1315         if (!empty($add))
1316             $add = $this->compressMessageSet($add);
1317
1318         list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1319             array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1320
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);
1326             }
1327             return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1328         }
1329
1330         return false;
1331     }
1332
1333     function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1334     {
1335         if (is_array($message_set)) {
1336             if (!($message_set = $this->compressMessageSet($message_set)))
1337                 return false;
1338         } else {
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)) {
1342                 return false;
1343             }
1344         }
1345
1346         $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1347
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;
1362
1363         if (!($mode = $fields_a[$index_field])) {
1364             return false;
1365         }
1366
1367         /*  Do "SELECT" command */
1368         if (!$this->select($mailbox)) {
1369             return false;
1370         }
1371
1372         // build FETCH command string
1373         $key     = $this->nextTag();
1374         $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
1375         $deleted = $skip_deleted ? ' FLAGS' : '';
1376
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)";
1384             else
1385                 $request = " $cmd $message_set ($index_field$deleted)";
1386         } else if ($mode == 3)
1387             $request = " $cmd $message_set (FLAGS)";
1388         else // 4
1389             $request = " $cmd $message_set (INTERNALDATE$deleted)";
1390
1391         $request = $key . $request;
1392
1393         if (!$this->putLine($request)) {
1394             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1395             return false;
1396         }
1397
1398         $result = array();
1399
1400         do {
1401             $line = rtrim($this->readLine(200));
1402             $line = $this->multLine($line);
1403
1404             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1405                 $id     = $m[1];
1406                 $flags  = NULL;
1407
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;
1412                         continue;
1413                     }
1414                 }
1415
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);
1421                     }
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]);
1426                         else
1427                             $result[$id] = 0;
1428                     }
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);
1433                     } else {
1434                         $result[$id] = '';
1435                     }
1436                 } else if ($mode == 2) {
1437                     if (preg_match('/(UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1438                         $result[$id] = trim($matches[2]);
1439                     } else {
1440                         $result[$id] = 0;
1441                     }
1442                 } else if ($mode == 3) {
1443                     if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1444                         $flags = explode(' ', $matches[1]);
1445                     }
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]);
1450                     } else {
1451                         $result[$id] = 0;
1452                     }
1453                 }
1454             }
1455         } while (!$this->startsWith($line, $key, true, true));
1456
1457         return $result;
1458     }
1459
1460     static function compressMessageSet($messages, $force=false)
1461     {
1462         // given a comma delimited list of independent mid's,
1463         // compresses by grouping sequences together
1464
1465         if (!is_array($messages)) {
1466             // if less than 255 bytes long, let's not bother
1467             if (!$force && strlen($messages)<255) {
1468                 return $messages;
1469            }
1470
1471             // see if it's already been compressed
1472             if (strpos($messages, ':') !== false) {
1473                 return $messages;
1474             }
1475
1476             // separate, then sort
1477             $messages = explode(',', $messages);
1478         }
1479
1480         sort($messages);
1481
1482         $result = array();
1483         $start  = $prev = $messages[0];
1484
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
1490                 } else {
1491                     $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1492                 }
1493                 $start = $id; // start of new sequence
1494             }
1495             $prev = $id;
1496         }
1497
1498         // handle the last sequence/id
1499         if ($start == $prev) {
1500             $result[] = $prev;
1501         } else {
1502             $result[] = $start.':'.$prev;
1503         }
1504
1505         // return as comma separated string
1506         return implode(',', $result);
1507     }
1508
1509     static function uncompressMessageSet($messages)
1510     {
1511         $result   = array();
1512         $messages = explode(',', $messages);
1513
1514         foreach ($messages as $part) {
1515             $items = explode(':', $part);
1516             $max   = max($items[0], $items[1]);
1517
1518             for ($x=$items[0]; $x<=$max; $x++) {
1519                 $result[] = $x;
1520             }
1521         }
1522
1523         return $result;
1524     }
1525
1526     /**
1527      * Returns message sequence identifier
1528      *
1529      * @param string $mailbox Mailbox name
1530      * @param int    $uid     Message unique identifier (UID)
1531      *
1532      * @return int Message sequence identifier
1533      */
1534     function UID2ID($mailbox, $uid)
1535     {
1536         if ($uid > 0) {
1537             $id_a = $this->search($mailbox, "UID $uid");
1538             if (is_array($id_a) && count($id_a) == 1) {
1539                 return (int) $id_a[0];
1540             }
1541         }
1542         return null;
1543     }
1544
1545     /**
1546      * Returns message unique identifier (UID)
1547      *
1548      * @param string $mailbox Mailbox name
1549      * @param int    $uid     Message sequence identifier
1550      *
1551      * @return int Message unique identifier
1552      */
1553     function ID2UID($mailbox, $id)
1554     {
1555         if (empty($id) || $id < 0) {
1556             return null;
1557         }
1558
1559         if (!$this->select($mailbox)) {
1560             return null;
1561         }
1562
1563         list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1564
1565         if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1566             return (int) $m[1];
1567         }
1568
1569         return null;
1570     }
1571
1572     function fetchUIDs($mailbox, $message_set=null)
1573     {
1574         if (empty($message_set))
1575             $message_set = '1:*';
1576
1577         return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1578     }
1579
1580     /**
1581      * FETCH command (RFC3501)
1582      *
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
1589      *
1590      * @return array List of rcube_mail_header elements, False on error
1591      * @since 0.6
1592      */
1593     function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
1594         $mod_seq = null, $vanished = false)
1595     {
1596         if (!$this->select($mailbox)) {
1597             return false;
1598         }
1599
1600         $message_set = $this->compressMessageSet($message_set);
1601         $result      = array();
1602
1603         $key      = $this->nextTag();
1604         $request  = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
1605         $request .= "(" . implode(' ', $query_items) . ")";
1606
1607         if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
1608             $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
1609         }
1610
1611         if (!$this->putLine($request)) {
1612             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1613             return false;
1614         }
1615
1616         do {
1617             $line = $this->readLine(4096);
1618
1619             if (!$line)
1620                 break;
1621
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 ...
1626
1627             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1628                 $id = intval($m[1]);
1629
1630                 $result[$id]            = new rcube_mail_header;
1631                 $result[$id]->id        = $id;
1632                 $result[$id]->subject   = '';
1633                 $result[$id]->messageID = 'mid:' . $id;
1634
1635                 $lines = array();
1636                 $line  = substr($line, strlen($m[0]) + 2);
1637                 $ln    = 0;
1638
1639                 // get complete entry
1640                 while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
1641                     $bytes = $m[1];
1642                     $out   = '';
1643
1644                     while (strlen($out) < $bytes) {
1645                         $out = $this->readBytes($bytes);
1646                         if ($out === NULL)
1647                             break;
1648                         $line .= $out;
1649                     }
1650
1651                     $str = $this->readLine(4096);
1652                     if ($str === false)
1653                         break;
1654
1655                     $line .= $str;
1656                 }
1657
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);
1662                     }
1663                     else if ($name == 'RFC822.SIZE') {
1664                         $result[$id]->size = intval($value);
1665                     }
1666                     else if ($name == 'RFC822.TEXT') {
1667                         $result[$id]->body = $value;
1668                     }
1669                     else if ($name == 'INTERNALDATE') {
1670                         $result[$id]->internaldate = $value;
1671                         $result[$id]->date         = $value;
1672                         $result[$id]->timestamp    = $this->StrToTime($value);
1673                     }
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);
1679
1680                                 $result[$id]->flags[$flag] = true;
1681                             }
1682                         }
1683                     }
1684                     else if ($name == 'MODSEQ') {
1685                         $result[$id]->modseq = $value[0];
1686                     }
1687                     else if ($name == 'ENVELOPE') {
1688                         $result[$id]->envelope = $value;
1689                     }
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);
1693                         }
1694                         $result[$id]->bodystructure = $value;
1695                     }
1696                     else if ($name == 'RFC822') {
1697                         $result[$id]->body = $value;
1698                     }
1699                     else if ($name == 'BODY') {
1700                         $body = $this->tokenizeResponse($line, 1);
1701                         if ($value[0] == 'HEADER.FIELDS')
1702                             $headers = $body;
1703                         else if (!empty($value))
1704                             $result[$id]->bodypart[$value[0]] = $body;
1705                         else
1706                             $result[$id]->body = $body;
1707                     }
1708                 }
1709
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);
1716                         } else {
1717                             $lines[++$ln] = trim($resln);
1718                         }
1719                     }
1720
1721                     while (list($lines_key, $str) = each($lines)) {
1722                         list($field, $string) = explode(':', $str, 2);
1723
1724                         $field  = strtolower($field);
1725                         $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
1726
1727                         switch ($field) {
1728                         case 'date';
1729                             $result[$id]->date = $string;
1730                             $result[$id]->timestamp = $this->strToTime($string);
1731                             break;
1732                         case 'from':
1733                             $result[$id]->from = $string;
1734                             break;
1735                         case 'to':
1736                             $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1737                             break;
1738                         case 'subject':
1739                             $result[$id]->subject = $string;
1740                             break;
1741                         case 'reply-to':
1742                             $result[$id]->replyto = $string;
1743                             break;
1744                         case 'cc':
1745                             $result[$id]->cc = $string;
1746                             break;
1747                         case 'bcc':
1748                             $result[$id]->bcc = $string;
1749                             break;
1750                         case 'content-transfer-encoding':
1751                             $result[$id]->encoding = $string;
1752                         break;
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];
1758                             }
1759                             break;
1760                         case 'in-reply-to':
1761                             $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1762                             break;
1763                         case 'references':
1764                             $result[$id]->references = $string;
1765                             break;
1766                         case 'return-receipt-to':
1767                         case 'disposition-notification-to':
1768                         case 'x-confirm-reading-to':
1769                             $result[$id]->mdn_to = $string;
1770                             break;
1771                         case 'message-id':
1772                             $result[$id]->messageID = $string;
1773                             break;
1774                         case 'x-priority':
1775                             if (preg_match('/^(\d+)/', $string, $matches)) {
1776                                 $result[$id]->priority = intval($matches[1]);
1777                             }
1778                             break;
1779                         default:
1780                             if (strlen($field) > 2) {
1781                                 $result[$id]->others[$field] = $string;
1782                             }
1783                             break;
1784                         }
1785                     }
1786                 }
1787             }
1788
1789             // VANISHED response (QRESYNC RFC5162)
1790             // Sample: * VANISHED (EARLIER) 300:310,405,411
1791
1792             else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
1793                 $line   = substr($line, strlen($match[0]));
1794                 $v_data = $this->tokenizeResponse($line, 1);
1795
1796                 $this->data['VANISHED'] = $v_data;
1797             }
1798
1799         } while (!$this->startsWith($line, $key, true));
1800
1801         return $result;
1802     }
1803
1804     function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add = '')
1805     {
1806         $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
1807         if ($bodystr)
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) : '')
1812             . ')]';
1813
1814         $result = $this->fetch($mailbox, $message_set, $is_uid, $query_items);
1815
1816         return $result;
1817     }
1818
1819     function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1820     {
1821         $a = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1822         if (is_array($a)) {
1823             return array_shift($a);
1824         }
1825         return false;
1826     }
1827
1828     function sortHeaders($a, $field, $flag)
1829     {
1830         if (empty($field)) {
1831             $field = 'uid';
1832         }
1833         else {
1834             $field = strtolower($field);
1835         }
1836
1837         if ($field == 'date' || $field == 'internaldate') {
1838             $field = 'timestamp';
1839         }
1840
1841         if (empty($flag)) {
1842             $flag = 'ASC';
1843         } else {
1844             $flag = strtoupper($flag);
1845         }
1846
1847         $c = count($a);
1848         if ($c > 0) {
1849             // Strategy:
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.
1853
1854             // create "index" array
1855             $index = array();
1856             reset($a);
1857             while (list($key, $val) = each($a)) {
1858                 if ($field == 'timestamp') {
1859                     $data = $this->strToTime($val->date);
1860                     if (!$data) {
1861                         $data = $val->timestamp;
1862                     }
1863                 } else {
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);
1869                         }
1870                         $data = strtoupper($data);
1871                     }
1872                 }
1873                 $index[$key] = $data;
1874             }
1875
1876             // sort index
1877             if ($flag == 'ASC') {
1878                 asort($index);
1879             } else {
1880                 arsort($index);
1881             }
1882
1883             // form new array based on index
1884             $result = array();
1885             reset($index);
1886             while (list($key, $val) = each($index)) {
1887                 $result[$key] = $a[$key];
1888             }
1889         }
1890
1891         return $result;
1892     }
1893
1894
1895     function modFlag($mailbox, $messages, $flag, $mod)
1896     {
1897         if ($mod != '+' && $mod != '-') {
1898             $mod = '+';
1899         }
1900
1901         if (!$this->select($mailbox)) {
1902             return false;
1903         }
1904
1905         if (!$this->data['READ-WRITE']) {
1906             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1907             return false;
1908         }
1909
1910         // Clear internal status cache
1911         if ($flag == 'SEEN') {
1912             unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1913         }
1914
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);
1919
1920         return ($result == self::ERROR_OK);
1921     }
1922
1923     function flag($mailbox, $messages, $flag) {
1924         return $this->modFlag($mailbox, $messages, $flag, '+');
1925     }
1926
1927     function unflag($mailbox, $messages, $flag) {
1928         return $this->modFlag($mailbox, $messages, $flag, '-');
1929     }
1930
1931     function delete($mailbox, $messages) {
1932         return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1933     }
1934
1935     function copy($messages, $from, $to)
1936     {
1937         if (!$this->select($from)) {
1938             return false;
1939         }
1940
1941         // Clear internal status cache
1942         unset($this->data['STATUS:'.$to]);
1943
1944         $result = $this->execute('UID COPY', array(
1945             $this->compressMessageSet($messages), $this->escape($to)),
1946             self::COMMAND_NORESPONSE);
1947
1948         return ($result == self::ERROR_OK);
1949     }
1950
1951     function move($messages, $from, $to)
1952     {
1953         if (!$this->select($from)) {
1954             return false;
1955         }
1956
1957         if (!$this->data['READ-WRITE']) {
1958             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1959             return false;
1960         }
1961
1962         $r = $this->copy($messages, $from, $to);
1963
1964         if ($r) {
1965             // Clear internal status cache
1966             unset($this->data['STATUS:'.$from]);
1967
1968             return $this->delete($from, $messages);
1969         }
1970         return $r;
1971     }
1972
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)
1977     {
1978         $node = array();
1979         if ($str[$begin] != '(') {
1980             $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1981             $msg = substr($str, $begin, $stop - $begin);
1982             if ($msg == 0)
1983                 return $node;
1984             if (is_null($root))
1985                 $root = $msg;
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);
1992             else
1993                 $node[$msg] = array();
1994         } else {
1995             $off = $begin;
1996             while ($off < $end) {
1997                 $start = $off;
1998                 $off++;
1999                 $n = 1;
2000                 while ($n > 0) {
2001                     $p = strpos($str, ')', $off);
2002                     if ($p === false) {
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))));
2006                         return $node;
2007                     }
2008                     $p1 = strpos($str, '(', $off);
2009                     if ($p1 !== false && $p1 < $p) {
2010                         $off = $p1 + 1;
2011                         $n++;
2012                     } else {
2013                         $off = $p + 1;
2014                         $n--;
2015                     }
2016                 }
2017                 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
2018             }
2019         }
2020
2021         return $node;
2022     }
2023
2024     function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
2025     {
2026         $old_sel = $this->selected;
2027
2028         if (!$this->select($mailbox)) {
2029             return false;
2030         }
2031
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());
2035         }
2036
2037         $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
2038         $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
2039         $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
2040         $data      = '';
2041
2042         list($code, $response) = $this->execute('THREAD', array(
2043             $algorithm, $encoding, $criteria));
2044
2045         if ($code == self::ERROR_OK) {
2046             // remove prefix...
2047             $response = substr($response, stripos($response, '* THREAD') + 9);
2048             // ...unilateral untagged server responses
2049             if ($pos = strpos($response, '*')) {
2050                 $response = substr($response, 0, $pos);
2051             }
2052
2053             $response    = str_replace("\r\n", '', $response);
2054             $depthmap    = array();
2055             $haschildren = array();
2056
2057             $tree = $this->parseThread($response, 0, strlen($response),
2058                 null, null, 0, $depthmap, $haschildren);
2059
2060             return array($tree, $depthmap, $haschildren);
2061         }
2062
2063         return false;
2064     }
2065
2066     /**
2067      * Executes SEARCH command
2068      *
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)
2073      *
2074      * @return array Message identifiers or item-value hash 
2075      */
2076     function search($mailbox, $criteria, $return_uid=false, $items=array())
2077     {
2078         $old_sel = $this->selected;
2079
2080         if (!$this->select($mailbox)) {
2081             return false;
2082         }
2083
2084         // return empty result when folder is empty and we're just after SELECT
2085         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2086             if (!empty($items))
2087                 return array_combine($items, array_fill(0, count($items), 0));
2088             else
2089                 return array();
2090         }
2091
2092         $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
2093         $criteria = trim($criteria);
2094         $params   = '';
2095
2096         // RFC4731: ESEARCH
2097         if (!empty($items) && $esearch) {
2098             $params .= 'RETURN (' . implode(' ', $items) . ')';
2099         }
2100         if (!empty($criteria)) {
2101             $modseq = stripos($criteria, 'MODSEQ') !== false;
2102             $params .= ($params ? ' ' : '') . $criteria;
2103         }
2104         else {
2105             $params .= 'ALL';
2106         }
2107
2108         list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2109             array($params));
2110
2111         if ($code == self::ERROR_OK) {
2112             // remove prefix...
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));
2118             }
2119
2120             // remove MODSEQ response
2121             if ($modseq) {
2122                 if (preg_match('/\(MODSEQ ([0-9]+)\)$/', $response, $m)) {
2123                     $response = substr($response, 0, -strlen($m[0]));
2124                 }
2125             }
2126
2127             if ($esearch) {
2128                 // Skip prefix: ... (TAG "A285") UID ...
2129                 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2130
2131                 $result = array();
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;
2138                     }
2139                 }
2140
2141                 return $result;
2142             }
2143             else {
2144                 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2145
2146                 if (!empty($items)) {
2147                     $result = array();
2148                     if (in_array('COUNT', $items)) {
2149                         $result['COUNT'] = count($response);
2150                     }
2151                     if (in_array('MIN', $items)) {
2152                         $result['MIN'] = !empty($response) ? min($response) : 0;
2153                     }
2154                     if (in_array('MAX', $items)) {
2155                         $result['MAX'] = !empty($response) ? max($response) : 0;
2156                     }
2157                     if (in_array('ALL', $items)) {
2158                         $result['ALL'] = $this->compressMessageSet($response, true);
2159                     }
2160
2161                     return $result;
2162                 }
2163                 else {
2164                     return $response;
2165                 }
2166             }
2167         }
2168
2169         return false;
2170     }
2171
2172     /**
2173      * Returns list of mailboxes
2174      *
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)
2179      *
2180      * @return array List of mailboxes or hash of options if $status_opts argument
2181      *               is non-empty.
2182      */
2183     function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2184     {
2185         return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2186     }
2187
2188     /**
2189      * Returns list of subscribed mailboxes
2190      *
2191      * @param string $ref         Reference name
2192      * @param string $mailbox     Mailbox name
2193      * @param array  $status_opts (see self::_listMailboxes)
2194      *
2195      * @return array List of mailboxes or hash of options if $status_opts argument
2196      *               is non-empty.
2197      */
2198     function listSubscribed($ref, $mailbox, $status_opts=array())
2199     {
2200         return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2201     }
2202
2203     /**
2204      * IMAP LIST/LSUB command
2205      *
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
2213      *
2214      * @return array List of mailboxes or hash of options if $status_ops argument
2215      *               is non-empty.
2216      */
2217     private function _listMailboxes($ref, $mailbox, $subscribed=false,
2218         $status_opts=array(), $select_opts=array())
2219     {
2220         if (!strlen($mailbox)) {
2221             $mailbox = '*';
2222         }
2223
2224         $args = array();
2225
2226         if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2227             $select_opts = (array) $select_opts;
2228
2229             $args[] = '(' . implode(' ', $select_opts) . ')';
2230         }
2231
2232         $args[] = $this->escape($ref);
2233         $args[] = $this->escape($mailbox);
2234
2235         if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2236             $status_opts = (array) $status_opts;
2237             $lstatus = true;
2238
2239             $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2240         }
2241
2242         list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2243
2244         if ($code == self::ERROR_OK) {
2245             $folders  = array();
2246             $last     = 0;
2247             $pos      = 0;
2248             $response .= "\r\n";
2249
2250             while ($pos = strpos($response, "\r\n", $pos+1)) {
2251                 // literal string, not real end-of-command-line
2252                 if ($response[$pos-1] == '}') {
2253                     continue;
2254                 }
2255
2256                 $line = substr($response, $last, $pos - $last);
2257                 $last = $pos + 2;
2258
2259                 if (!preg_match('/^\* (LIST|LSUB|STATUS) /i', $line, $m)) {
2260                     continue;
2261                 }
2262                 $cmd  = strtoupper($m[1]);
2263                 $line = substr($line, strlen($m[0]));
2264
2265                 // * LIST (<options>) <delimiter> <mailbox>
2266                 if ($cmd == 'LIST' || $cmd == 'LSUB') {
2267                     list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
2268
2269                     // Add to result array
2270                     if (!$lstatus) {
2271                         $folders[] = $mailbox;
2272                     }
2273                     else {
2274                         $folders[$mailbox] = array();
2275                     }
2276
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));
2283                 }
2284                 // * STATUS <mailbox> (<result>)
2285                 else if ($cmd == 'STATUS') {
2286                     list($mailbox, $status) = $this->tokenizeResponse($line, 2);
2287
2288                     for ($i=0, $len=count($status); $i<$len; $i += 2) {
2289                         list($name, $value) = $this->tokenizeResponse($status, 2);
2290                         $folders[$mailbox][$name] = $value;
2291                     }
2292                 }
2293             }
2294
2295             return $folders;
2296         }
2297
2298         return false;
2299     }
2300
2301     function fetchMIMEHeaders($mailbox, $uid, $parts, $mime=true)
2302     {
2303         if (!$this->select($mailbox)) {
2304             return false;
2305         }
2306
2307         $result = false;
2308         $parts  = (array) $parts;
2309         $key    = $this->nextTag();
2310         $peeks  = array();
2311         $type   = $mime ? 'MIME' : 'HEADER';
2312
2313         // format request
2314         foreach ($parts as $part) {
2315             $peeks[] = "BODY.PEEK[$part.$type]";
2316         }
2317
2318         $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
2319
2320         // send request
2321         if (!$this->putLine($request)) {
2322             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2323             return false;
2324         }
2325
2326         do {
2327             $line = $this->readLine(1024);
2328
2329             if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2330                 $idx     = $matches[1];
2331                 $headers = '';
2332
2333                 // get complete entry
2334                 if (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
2335                     $bytes = $m[1];
2336                     $out   = '';
2337
2338                     while (strlen($out) < $bytes) {
2339                         $out = $this->readBytes($bytes);
2340                         if ($out === null)
2341                             break;
2342                         $headers .= $out;
2343                     }
2344                 }
2345
2346                 $result[$idx] = trim($headers);
2347             }
2348         } while (!$this->startsWith($line, $key, true));
2349
2350         return $result;
2351     }
2352
2353     function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2354     {
2355         $part = empty($part) ? 'HEADER' : $part.'.MIME';
2356
2357         return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2358     }
2359
2360     function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2361     {
2362         if (!$this->select($mailbox)) {
2363             return false;
2364         }
2365
2366         switch ($encoding) {
2367         case 'base64':
2368             $mode = 1;
2369             break;
2370         case 'quoted-printable':
2371             $mode = 2;
2372             break;
2373         case 'x-uuencode':
2374         case 'x-uue':
2375         case 'uue':
2376         case 'uuencode':
2377             $mode = 3;
2378             break;
2379         default:
2380             $mode = 0;
2381         }
2382
2383         // format request
2384         $reply_key = '* ' . $id;
2385         $key       = $this->nextTag();
2386         $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2387
2388         // send request
2389         if (!$this->putLine($request)) {
2390             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2391             return false;
2392         }
2393
2394         // receive reply line
2395         do {
2396             $line = rtrim($this->readLine(1024));
2397             $a    = explode(' ', $line);
2398         } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2399
2400         $len    = strlen($line);
2401         $result = false;
2402
2403         if ($a[2] != 'FETCH') {
2404         }
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') {
2409                 // NIL response
2410                 $result = '';
2411             } else {
2412                 $from = strpos($line, '"') + 1;
2413                 $to   = strrpos($line, '"');
2414                 $len  = $to - $from;
2415                 $result = substr($line, $from, $len);
2416             }
2417
2418             if ($mode == 1) {
2419                 $result = base64_decode($result);
2420             }
2421             else if ($mode == 2) {
2422                 $result = quoted_printable_decode($result);
2423             }
2424             else if ($mode == 3) {
2425                 $result = convert_uudecode($result);
2426             }
2427
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, '}');
2432             $len      = $to - $from;
2433             $sizeStr  = substr($line, $from, $len);
2434             $bytes    = (int)$sizeStr;
2435             $prev     = '';
2436
2437             while ($bytes > 0) {
2438                 $line = $this->readLine(4096);
2439
2440                 if ($line === NULL) {
2441                     break;
2442                 }
2443
2444                 $len  = strlen($line);
2445
2446                 if ($len > $bytes) {
2447                     $line = substr($line, 0, $bytes);
2448                     $len = strlen($line);
2449                 }
2450                 $bytes -= $len;
2451
2452                 // BASE64
2453                 if ($mode == 1) {
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);
2458                     if ($length % 4) {
2459                         $length = floor($length / 4) * 4;
2460                         $prev = substr($line, $length);
2461                         $line = substr($line, 0, $length);
2462                     }
2463                     else
2464                         $prev = '';
2465                     $line = base64_decode($line);
2466                 // QUOTED-PRINTABLE
2467                 } else if ($mode == 2) {
2468                     $line = rtrim($line, "\t\r\0\x0B");
2469                     $line = quoted_printable_decode($line);
2470                 // UUENCODE
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))
2474                         continue;
2475                     $line = convert_uudecode($line);
2476                 // default
2477                 } else {
2478                     $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2479                 }
2480
2481                 if ($file)
2482                     fwrite($file, $line);
2483                 else if ($print)
2484                     echo $line;
2485                 else
2486                     $result .= $line;
2487             }
2488         }
2489
2490         // read in anything up until last line
2491         if (!$end)
2492             do {
2493                 $line = $this->readLine(1024);
2494             } while (!$this->startsWith($line, $key, true));
2495
2496         if ($result !== false) {
2497             if ($file) {
2498                 fwrite($file, $result);
2499             } else if ($print) {
2500                 echo $result;
2501             } else
2502                 return $result;
2503             return true;
2504         }
2505
2506         return false;
2507     }
2508
2509     function createFolder($mailbox)
2510     {
2511         $result = $this->execute('CREATE', array($this->escape($mailbox)),
2512             self::COMMAND_NORESPONSE);
2513
2514         return ($result == self::ERROR_OK);
2515     }
2516
2517     function renameFolder($from, $to)
2518     {
2519         $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2520             self::COMMAND_NORESPONSE);
2521
2522         return ($result == self::ERROR_OK);
2523     }
2524
2525     /**
2526      * Handler for IMAP APPEND command
2527      *
2528      * @param string $mailbox Mailbox name
2529      * @param string $message Message content
2530      *
2531      * @return string|bool On success APPENDUID response (if available) or True, False on failure
2532      */
2533     function append($mailbox, &$message)
2534     {
2535         unset($this->data['APPENDUID']);
2536
2537         if (!$mailbox) {
2538             return false;
2539         }
2540
2541         $message = str_replace("\r", '', $message);
2542         $message = str_replace("\n", "\r\n", $message);
2543
2544         $len = strlen($message);
2545         if (!$len) {
2546             return false;
2547         }
2548
2549         $key = $this->nextTag();
2550         $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2551             $len, ($this->prefs['literal+'] ? '+' : ''));
2552
2553         if ($this->putLine($request)) {
2554             // Don't wait when LITERAL+ is supported
2555             if (!$this->prefs['literal+']) {
2556                 $line = $this->readReply();
2557
2558                 if ($line[0] != '+') {
2559                     $this->parseResult($line, 'APPEND: ');
2560                     return false;
2561                 }
2562             }
2563
2564             if (!$this->putLine($message)) {
2565                 return false;
2566             }
2567
2568             do {
2569                 $line = $this->readLine();
2570             } while (!$this->startsWith($line, $key, true, true));
2571
2572             // Clear internal status cache
2573             unset($this->data['STATUS:'.$mailbox]);
2574
2575             if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2576                 return false;
2577             else if (!empty($this->data['APPENDUID']))
2578                 return $this->data['APPENDUID'];
2579             else
2580                 return true;
2581         }
2582         else {
2583             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2584         }
2585
2586         return false;
2587     }
2588
2589     /**
2590      * Handler for IMAP APPEND command.
2591      *
2592      * @param string $mailbox Mailbox name
2593      * @param string $path    Path to the file with message body
2594      * @param string $headers Message headers
2595      *
2596      * @return string|bool On success APPENDUID response (if available) or True, False on failure
2597      */
2598     function appendFromFile($mailbox, $path, $headers=null)
2599     {
2600         unset($this->data['APPENDUID']);
2601
2602         if (!$mailbox) {
2603             return false;
2604         }
2605
2606         // open message file
2607         $in_fp = false;
2608         if (file_exists(realpath($path))) {
2609             $in_fp = fopen($path, 'r');
2610         }
2611         if (!$in_fp) {
2612             $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2613             return false;
2614         }
2615
2616         $body_separator = "\r\n\r\n";
2617         $len = filesize($path);
2618
2619         if (!$len) {
2620             return false;
2621         }
2622
2623         if ($headers) {
2624             $headers = preg_replace('/[\r\n]+$/', '', $headers);
2625             $len += strlen($headers) + strlen($body_separator);
2626         }
2627
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+'] ? '+' : ''));
2632
2633         if ($this->putLine($request)) {
2634             // Don't wait when LITERAL+ is supported
2635             if (!$this->prefs['literal+']) {
2636                 $line = $this->readReply();
2637
2638                 if ($line[0] != '+') {
2639                     $this->parseResult($line, 'APPEND: ');
2640                     return false;
2641                 }
2642             }
2643
2644             // send headers with body separator
2645             if ($headers) {
2646                 $this->putLine($headers . $body_separator, false);
2647             }
2648
2649             // send file
2650             while (!feof($in_fp) && $this->fp) {
2651                 $buffer = fgets($in_fp, 4096);
2652                 $this->putLine($buffer, false);
2653             }
2654             fclose($in_fp);
2655
2656             if (!$this->putLine('')) { // \r\n
2657                 return false;
2658             }
2659
2660             // read response
2661             do {
2662                 $line = $this->readLine();
2663             } while (!$this->startsWith($line, $key, true, true));
2664
2665             // Clear internal status cache
2666             unset($this->data['STATUS:'.$mailbox]);
2667
2668             if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
2669                 return false;
2670             else if (!empty($this->data['APPENDUID']))
2671                 return $this->data['APPENDUID'];
2672             else
2673                 return true;
2674         }
2675         else {
2676             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2677         }
2678
2679         return false;
2680     }
2681
2682     function getQuota()
2683     {
2684         /*
2685          * GETQUOTAROOT "INBOX"
2686          * QUOTAROOT INBOX user/rchijiiwa1
2687          * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2688          * OK Completed
2689          */
2690         $result      = false;
2691         $quota_lines = array();
2692         $key         = $this->nextTag();
2693         $command     = $key . ' GETQUOTAROOT INBOX';
2694
2695         // get line(s) containing quota info
2696         if ($this->putLine($command)) {
2697             do {
2698                 $line = rtrim($this->readLine(5000));
2699                 if (preg_match('/^\* QUOTA /', $line)) {
2700                     $quota_lines[] = $line;
2701                 }
2702             } while (!$this->startsWith($line, $key, true, true));
2703         }
2704         else {
2705             $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2706         }
2707
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);
2714
2715             if (!$storage_part) {
2716                 continue;
2717             }
2718
2719             $used  = intval($parts[$storage_part+1]);
2720             $total = intval($parts[$storage_part+2]);
2721             $free  = $total - $used;
2722
2723             // return lowest available space from all quotas
2724             if ($free < $min_free) {
2725                 $min_free          = $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'];
2730             }
2731         }
2732
2733         return $result;
2734     }
2735
2736     /**
2737      * Send the SETACL command (RFC4314)
2738      *
2739      * @param string $mailbox Mailbox name
2740      * @param string $user    User name
2741      * @param mixed  $acl     ACL string or array
2742      *
2743      * @return boolean True on success, False on failure
2744      *
2745      * @since 0.5-beta
2746      */
2747     function setACL($mailbox, $user, $acl)
2748     {
2749         if (is_array($acl)) {
2750             $acl = implode('', $acl);
2751         }
2752
2753         $result = $this->execute('SETACL', array(
2754             $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2755             self::COMMAND_NORESPONSE);
2756
2757         return ($result == self::ERROR_OK);
2758     }
2759
2760     /**
2761      * Send the DELETEACL command (RFC4314)
2762      *
2763      * @param string $mailbox Mailbox name
2764      * @param string $user    User name
2765      *
2766      * @return boolean True on success, False on failure
2767      *
2768      * @since 0.5-beta
2769      */
2770     function deleteACL($mailbox, $user)
2771     {
2772         $result = $this->execute('DELETEACL', array(
2773             $this->escape($mailbox), $this->escape($user)),
2774             self::COMMAND_NORESPONSE);
2775
2776         return ($result == self::ERROR_OK);
2777     }
2778
2779     /**
2780      * Send the GETACL command (RFC4314)
2781      *
2782      * @param string $mailbox Mailbox name
2783      *
2784      * @return array User-rights array on success, NULL on error
2785      * @since 0.5-beta
2786      */
2787     function getACL($mailbox)
2788     {
2789         list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2790
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);
2797
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]);
2805                     unset($ret[$i-1]);
2806                     unset($ret[$i]);
2807                 }
2808                 return $ret;
2809             }
2810
2811             $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2812             return NULL;
2813         }
2814
2815         return NULL;
2816     }
2817
2818     /**
2819      * Send the LISTRIGHTS command (RFC4314)
2820      *
2821      * @param string $mailbox Mailbox name
2822      * @param string $user    User name
2823      *
2824      * @return array List of user rights
2825      * @since 0.5-beta
2826      */
2827     function listRights($mailbox, $user)
2828     {
2829         list($code, $response) = $this->execute('LISTRIGHTS', array(
2830             $this->escape($mailbox), $this->escape($user)));
2831
2832         if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2833             // Parse server response (remove "* LISTRIGHTS ")
2834             $response = substr($response, 13);
2835
2836             $ret_mbox = $this->tokenizeResponse($response, 1);
2837             $ret_user = $this->tokenizeResponse($response, 1);
2838             $granted  = $this->tokenizeResponse($response, 1);
2839             $optional = trim($response);
2840
2841             return array(
2842                 'granted'  => str_split($granted),
2843                 'optional' => explode(' ', $optional),
2844             );
2845         }
2846
2847         return NULL;
2848     }
2849
2850     /**
2851      * Send the MYRIGHTS command (RFC4314)
2852      *
2853      * @param string $mailbox Mailbox name
2854      *
2855      * @return array MYRIGHTS response on success, NULL on error
2856      * @since 0.5-beta
2857      */
2858     function myRights($mailbox)
2859     {
2860         list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2861
2862         if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2863             // Parse server response (remove "* MYRIGHTS ")
2864             $response = substr($response, 11);
2865
2866             $ret_mbox = $this->tokenizeResponse($response, 1);
2867             $rights   = $this->tokenizeResponse($response, 1);
2868
2869             return str_split($rights);
2870         }
2871
2872         return NULL;
2873     }
2874
2875     /**
2876      * Send the SETMETADATA command (RFC5464)
2877      *
2878      * @param string $mailbox Mailbox name
2879      * @param array  $entries Entry-value array (use NULL value as NIL)
2880      *
2881      * @return boolean True on success, False on failure
2882      * @since 0.5-beta
2883      */
2884     function setMetadata($mailbox, $entries)
2885     {
2886         if (!is_array($entries) || empty($entries)) {
2887             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2888             return false;
2889         }
2890
2891         foreach ($entries as $name => $value) {
2892             $entries[$name] = $this->escape($name) . ' ' . $this->escape($value);
2893         }
2894
2895         $entries = implode(' ', $entries);
2896         $result = $this->execute('SETMETADATA', array(
2897             $this->escape($mailbox), '(' . $entries . ')'),
2898             self::COMMAND_NORESPONSE);
2899
2900         return ($result == self::ERROR_OK);
2901     }
2902
2903     /**
2904      * Send the SETMETADATA command with NIL values (RFC5464)
2905      *
2906      * @param string $mailbox Mailbox name
2907      * @param array  $entries Entry names array
2908      *
2909      * @return boolean True on success, False on failure
2910      *
2911      * @since 0.5-beta
2912      */
2913     function deleteMetadata($mailbox, $entries)
2914     {
2915         if (!is_array($entries) && !empty($entries)) {
2916             $entries = explode(' ', $entries);
2917         }
2918
2919         if (empty($entries)) {
2920             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2921             return false;
2922         }
2923
2924         foreach ($entries as $entry) {
2925             $data[$entry] = NULL;
2926         }
2927
2928         return $this->setMetadata($mailbox, $data);
2929     }
2930
2931     /**
2932      * Send the GETMETADATA command (RFC5464)
2933      *
2934      * @param string $mailbox Mailbox name
2935      * @param array  $entries Entries
2936      * @param array  $options Command options (with MAXSIZE and DEPTH keys)
2937      *
2938      * @return array GETMETADATA result on success, NULL on error
2939      *
2940      * @since 0.5-beta
2941      */
2942     function getMetadata($mailbox, $entries, $options=array())
2943     {
2944         if (!is_array($entries)) {
2945             $entries = array($entries);
2946         }
2947
2948         // create entries string
2949         foreach ($entries as $idx => $name) {
2950             $entries[$idx] = $this->escape($name);
2951         }
2952
2953         $optlist = '';
2954         $entlist = '(' . implode(' ', $entries) . ')';
2955
2956         // create options string
2957         if (is_array($options)) {
2958             $options = array_change_key_case($options, CASE_UPPER);
2959             $opts = array();
2960
2961             if (!empty($options['MAXSIZE'])) {
2962                 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2963             }
2964             if (!empty($options['DEPTH'])) {
2965                 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2966             }
2967
2968             if ($opts) {
2969                 $optlist = '(' . implode(' ', $opts) . ')';
2970             }
2971         }
2972
2973         $optlist .= ($optlist ? ' ' : '') . $entlist;
2974
2975         list($code, $response) = $this->execute('GETMETADATA', array(
2976             $this->escape($mailbox), $optlist));
2977
2978         if ($code == self::ERROR_OK) {
2979             $result = array();
2980             $data   = $this->tokenizeResponse($response);
2981
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];
2990                         }
2991                         unset($data[$i]);
2992                     }
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
2999                         }
3000                         // get rid of other untagged responses
3001                         else {
3002                             unset($mbox);
3003                             unset($data[$i]);
3004                         }
3005                     }
3006                     else if (isset($mbox)) {
3007                         $result[$mbox][$data[$i]] = $data[++$i];
3008                         unset($data[$i]);
3009                         unset($data[$i-1]);
3010                     }
3011                     else {
3012                         unset($data[$i]);
3013                     }
3014                 }
3015             }
3016
3017             return $result;
3018         }
3019
3020         return NULL;
3021     }
3022
3023     /**
3024      * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
3025      *
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
3029      *
3030      * @return boolean True on success, False on failure
3031      * @since 0.5-beta
3032      */
3033     function setAnnotation($mailbox, $data)
3034     {
3035         if (!is_array($data) || empty($data)) {
3036             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3037             return false;
3038         }
3039
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));
3044         }
3045
3046         $entries = implode(' ', $entries);
3047         $result  = $this->execute('SETANNOTATION', array(
3048             $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
3049
3050         return ($result == self::ERROR_OK);
3051     }
3052
3053     /**
3054      * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
3055      *
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
3059      *
3060      * @return boolean True on success, False on failure
3061      *
3062      * @since 0.5-beta
3063      */
3064     function deleteAnnotation($mailbox, $data)
3065     {
3066         if (!is_array($data) || empty($data)) {
3067             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3068             return false;
3069         }
3070
3071         return $this->setAnnotation($mailbox, $data);
3072     }
3073
3074     /**
3075      * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3076      *
3077      * @param string $mailbox Mailbox name
3078      * @param array  $entries Entries names
3079      * @param array  $attribs Attribs names
3080      *
3081      * @return array Annotations result on success, NULL on error
3082      *
3083      * @since 0.5-beta
3084      */
3085     function getAnnotation($mailbox, $entries, $attribs)
3086     {
3087         if (!is_array($entries)) {
3088             $entries = array($entries);
3089         }
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);
3094         }
3095         $entries = '(' . implode(' ', $entries) . ')';
3096
3097         if (!is_array($attribs)) {
3098             $attribs = array($attribs);
3099         }
3100         // create entries string
3101         foreach ($attribs as $idx => $name) {
3102             $attribs[$idx] = $this->escape($name, true);
3103         }
3104         $attribs = '(' . implode(' ', $attribs) . ')';
3105
3106         list($code, $response) = $this->execute('GETANNOTATION', array(
3107             $this->escape($mailbox), $entries, $attribs));
3108
3109         if ($code == self::ERROR_OK) {
3110             $result = array();
3111             $data   = $this->tokenizeResponse($response);
3112
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++) {
3116                     $entry = $data[$i];
3117                     if (isset($mbox) && is_array($entry)) {
3118                         $attribs = $entry;
3119                         $entry   = $last_entry;
3120                     }
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
3127                         }
3128                         // get rid of other untagged responses
3129                         else {
3130                             unset($mbox);
3131                             unset($data[$i]);
3132                         }
3133                         continue;
3134                     }
3135                     else if (isset($mbox)) {
3136                         $attribs = $data[++$i];
3137                     }
3138                     else {
3139                         unset($data[$i]);
3140                         continue;
3141                     }
3142
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;
3149                             }
3150                             else if ($attr == 'value.shared') {
3151                                 $result[$mbox]['/shared' . $entry] = $value;
3152                             }
3153                         }
3154                     }
3155                     $last_entry = $entry;
3156                     unset($data[$i]);
3157                 }
3158             }
3159
3160             return $result;
3161         }
3162
3163         return NULL;
3164     }
3165
3166     /**
3167      * Returns BODYSTRUCTURE for the specified message.
3168      *
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
3172      *
3173      * @return array/bool Body structure array or False on error.
3174      * @since 0.6
3175      */
3176     function getStructure($mailbox, $id, $is_uid = false)
3177     {
3178         $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
3179         if (is_array($result)) {
3180             $result = array_shift($result);
3181             return $result->bodystructure;
3182         }
3183         return false;
3184     }
3185
3186     /**
3187      * Returns data of a message part according to specified structure.
3188      *
3189      * @param array  $structure Message structure (getStructure() result)
3190      * @param string $part      Message part identifier
3191      *
3192      * @return array Part data as hash array (type, encoding, charset, size)
3193      */
3194     static function getStructurePartData($structure, $part)
3195     {
3196             $part_a = self::getStructurePartArray($structure, $part);
3197             $data   = array();
3198
3199             if (empty($part_a)) {
3200             return $data;
3201         }
3202
3203         // content-type
3204         if (is_array($part_a[0])) {
3205             $data['type'] = 'multipart';
3206         }
3207         else {
3208             $data['type'] = strtolower($part_a[0]);
3209
3210             // encoding
3211             $data['encoding'] = strtolower($part_a[5]);
3212
3213             // charset
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];
3218                         break;
3219                     }
3220                 }
3221             }
3222         }
3223
3224         // size
3225         $data['size'] = intval($part_a[6]);
3226
3227         return $data;
3228     }
3229
3230     static function getStructurePartArray($a, $part)
3231     {
3232             if (!is_array($a)) {
3233             return false;
3234         }
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)) {
3241                             $a = $a[8];
3242                     }
3243                     return self::getStructurePartArray($a[$part-1], $rest);
3244             }
3245         else if ($part>0) {
3246                     if (!is_array($a[0]) && (strcasecmp($a[0], 'message') == 0)
3247                 && (strcasecmp($a[1], 'rfc822') == 0)) {
3248                             $a = $a[8];
3249                     }
3250                     if (is_array($a[$part-1]))
3251                 return $a[$part-1];
3252                     else
3253                 return $a;
3254             }
3255         else if (($part == 0) || (empty($part))) {
3256                     return $a;
3257             }
3258     }
3259
3260     /**
3261      * Creates next command identifier (tag)
3262      *
3263      * @return string Command identifier
3264      * @since 0.5-beta
3265      */
3266     function nextTag()
3267     {
3268         $this->cmd_num++;
3269         $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3270
3271         return $this->cmd_tag;
3272     }
3273
3274     /**
3275      * Sends IMAP command and parses result
3276      *
3277      * @param string $command   IMAP command
3278      * @param array  $arguments Command arguments
3279      * @param int    $options   Execution options
3280      *
3281      * @return mixed Response code or list of response code and data
3282      * @since 0.5-beta
3283      */
3284     function execute($command, $arguments=array(), $options=0)
3285     {
3286         $tag      = $this->nextTag();
3287         $query    = $tag . ' ' . $command;
3288         $noresp   = ($options & self::COMMAND_NORESPONSE);
3289         $response = $noresp ? null : '';
3290
3291         if (!empty($arguments)) {
3292             foreach ($arguments as $arg) {
3293                 $query .= ' ' . self::r_implode($arg);
3294             }
3295         }
3296
3297         // Send command
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, '');
3301         }
3302
3303         // Parse response
3304         do {
3305             $line = $this->readLine(4096);
3306             if ($response !== null) {
3307                 $response .= $line;
3308             }
3309         } while (!$this->startsWith($line, $tag . ' ', true, true));
3310
3311         $code = $this->parseResult($line, $command . ': ');
3312
3313         // Remove last line from response
3314         if ($response) {
3315             $line_len = min(strlen($response), strlen($line) + 2);
3316             $response = substr($response, 0, -$line_len);
3317         }
3318
3319         // optional CAPABILITY response
3320         if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3321             && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3322         ) {
3323             $this->parseCapability($matches[1], true);
3324         }
3325
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));
3329         }
3330
3331         return $noresp ? $code : array($code, $response);
3332     }
3333
3334     /**
3335      * Splits IMAP response into string tokens
3336      *
3337      * @param string &$str The IMAP's server response
3338      * @param int    $num  Number of tokens to return
3339      *
3340      * @return mixed Tokens array or string if $num=1
3341      * @since 0.5-beta
3342      */
3343     static function tokenizeResponse(&$str, $num=0)
3344     {
3345         $result = array();
3346
3347         while (!$num || count($result) < $num) {
3348             // remove spaces from the beginning of the string
3349             $str = ltrim($str);
3350
3351             switch ($str[0]) {
3352
3353             // String literal
3354             case '{':
3355                 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3356                     // error
3357                 }
3358                 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3359                     // error
3360                 }
3361                 $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
3362                 // Advance the string
3363                 $str = substr($str, $epos + 3 + $bytes);
3364                 break;
3365
3366             // Quoted string
3367             case '"':
3368                 $len = strlen($str);
3369
3370                 for ($pos=1; $pos<$len; $pos++) {
3371                     if ($str[$pos] == '"') {
3372                         break;
3373                     }
3374                     if ($str[$pos] == "\\") {
3375                         if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3376                             $pos++;
3377                         }
3378                     }
3379                 }
3380                 if ($str[$pos] != '"') {
3381                     // error
3382                 }
3383                 // we need to strip slashes for a quoted string
3384                 $result[] = stripslashes(substr($str, 1, $pos - 1));
3385                 $str      = substr($str, $pos + 1);
3386                 break;
3387
3388             // Parenthesized list
3389             case '(':
3390             case '[':
3391                 $str = substr($str, 1);
3392                 $result[] = self::tokenizeResponse($str);
3393                 break;
3394             case ')':
3395             case ']':
3396                 $str = substr($str, 1);
3397                 return $result;
3398                 break;
3399
3400             // String atom, number, NIL, *, %
3401             default:
3402                 // empty string
3403                 if ($str === '' || $str === null) {
3404                     break 2;
3405                 }
3406
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]));
3411                 }
3412                 break;
3413             }
3414         }
3415
3416         return $num == 1 ? $result[0] : $result;
3417     }
3418
3419     static function r_implode($element)
3420     {
3421         $string = '';
3422
3423         if (is_array($element)) {
3424             reset($element);
3425             while (list($key, $value) = each($element)) {
3426                 $string .= ' ' . self::r_implode($value);
3427             }
3428         }
3429         else {
3430             return $element;
3431         }
3432
3433         return '(' . trim($string) . ')';
3434     }
3435
3436     private function _xor($string, $string2)
3437     {
3438         $result = '';
3439         $size   = strlen($string);
3440
3441         for ($i=0; $i<$size; $i++) {
3442             $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3443         }
3444
3445         return $result;
3446     }
3447
3448     /**
3449      * Converts datetime string into unix timestamp
3450      *
3451      * @param string $date Date string
3452      *
3453      * @return int Unix timestamp
3454      */
3455     static function strToTime($date)
3456     {
3457         // support non-standard "GMTXXXX" literal
3458         $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3459
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);
3464             array_pop($d);
3465             if (empty($d)) {
3466                 break;
3467             }
3468             $date = implode(' ', $d);
3469         }
3470
3471         return $ts < 0 ? 0 : $ts;
3472     }
3473
3474     private function parseCapability($str, $trusted=false)
3475     {
3476         $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3477
3478         $this->capability = explode(' ', strtoupper($str));
3479
3480         if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3481             $this->prefs['literal+'] = true;
3482         }
3483
3484         if ($trusted) {
3485             $this->capability_readed = true;
3486         }
3487     }
3488
3489     /**
3490      * Escapes a string when it contains special characters (RFC3501)
3491      *
3492      * @param string  $string       IMAP string
3493      * @param boolean $force_quotes Forces string quoting (for atoms)
3494      *
3495      * @return string String atom, quoted-string or string literal
3496      * @todo lists
3497      */
3498     static function escape($string, $force_quotes=false)
3499     {
3500         if ($string === null) {
3501             return 'NIL';
3502         }
3503         if ($string === '') {
3504             return '""';
3505         }
3506         // atom-string (only safe characters)
3507         if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
3508             return $string;
3509         }
3510         // quoted-string
3511         if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
3512             return '"' . addcslashes($string, '\\"') . '"';
3513         }
3514
3515         // literal-string
3516         return sprintf("{%d}\r\n%s", strlen($string), $string);
3517     }
3518
3519     static function unEscape($string)
3520     {
3521         return stripslashes($string);
3522     }
3523
3524     /**
3525      * Set the value of the debugging flag.
3526      *
3527      * @param   boolean $debug      New value for the debugging flag.
3528      *
3529      * @since   0.5-stable
3530      */
3531     function setDebug($debug, $handler = null)
3532     {
3533         $this->_debug = $debug;
3534         $this->_debug_handler = $handler;
3535     }
3536
3537     /**
3538      * Write the given debug text to the current debug output handler.
3539      *
3540      * @param   string  $message    Debug mesage text.
3541      *
3542      * @since   0.5-stable
3543      */
3544     private function debug($message)
3545     {
3546         if ($this->resourceid) {
3547             $message = sprintf('[%s] %s', $this->resourceid, $message);
3548         }
3549
3550         if ($this->_debug_handler) {
3551             call_user_func_array($this->_debug_handler, array(&$this, $message));
3552         } else {
3553             echo "DEBUG: $message\n";
3554         }
3555     }
3556
3557 }