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