]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_imap_generic.php
Imported Upstream version 0.5
[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 4399 2011-01-08 08:37:55Z 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         $auth_methods = array();
763         $result       = null;
764
765         // check for supported auth methods
766         if ($auth_method == 'CHECK') {
767             if ($auth_caps = $this->getCapability('AUTH')) {
768                 $auth_methods = $auth_caps;
769             }
770             // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
771             $login_disabled = $this->getCapability('LOGINDISABLED');
772             if (($key = array_search('LOGIN', $auth_methods)) !== false) {
773                 if ($login_disabled) {
774                     unset($auth_methods[$key]);
775                 }
776             }
777             else if (!$login_disabled) {
778                 $auth_methods[] = 'LOGIN';
779             }
780         }
781         else {
782             // Prevent from sending credentials in plain text when connection is not secure
783             if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
784                 $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
785                 $this->closeConnection();
786                 return false;
787             }
788             // replace AUTH with CRAM-MD5 for backward compat.
789             $auth_methods[] = $auth_method == 'AUTH' ? 'CRAM-MD5' : $auth_method;
790         }
791
792         // pre-login capabilities can be not complete
793         $this->capability_readed = false;
794
795         // Authenticate
796         foreach ($auth_methods as $method) {
797             switch ($method) {
798             case 'CRAM_MD5':
799                 $method = 'CRAM-MD5';
800             case 'CRAM-MD5':
801             case 'DIGEST-MD5':
802             case 'PLAIN':
803                 $result = $this->authenticate($user, $password, $method);
804                 break;
805             case 'LOGIN':
806                 $result = $this->login($user, $password);
807                 break;
808             default:
809                 $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $method");
810             }
811
812             if (is_resource($result)) {
813                 break;
814             }
815         }
816
817         // Connected and authenticated
818         if (is_resource($result)) {
819             if ($this->prefs['force_caps']) {
820                 $this->clearCapability();
821             }
822             $this->logged = true;
823
824             return true;
825         }
826
827         $this->closeConnection();
828
829         return false;
830     }
831
832     function connected()
833     {
834         return ($this->fp && $this->logged) ? true : false;
835     }
836
837     function closeConnection()
838     {
839         if ($this->putLine($this->nextTag() . ' LOGOUT')) {
840             $this->readReply();
841         }
842
843         @fclose($this->fp);
844         $this->fp = false;
845     }
846
847     /**
848      * Executes SELECT command (if mailbox is already not in selected state)
849      *
850      * @param string $mailbox Mailbox name
851      *
852      * @return boolean True on success, false on error
853      * @access public
854      */
855     function select($mailbox)
856     {
857         if (!strlen($mailbox)) {
858             return false;
859         }
860
861         if ($this->selected == $mailbox) {
862             return true;
863         }
864 /*
865     Temporary commented out because Courier returns \Noselect for INBOX
866     Requires more investigation
867
868         if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
869             if (in_array('\\Noselect', $opts)) {
870                 return false;
871             }
872         }
873 */
874         list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
875
876         if ($code == self::ERROR_OK) {
877             $response = explode("\r\n", $response);
878             foreach ($response as $line) {
879                 if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
880                     $this->data[strtoupper($m[2])] = (int) $m[1];
881                 }
882                 else if (preg_match('/^\* OK \[(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)\]/i', $line, $match)) {
883                     $this->data[strtoupper($match[1])] = (int) $match[2];
884                 }
885                 else if (preg_match('/^\* OK \[PERMANENTFLAGS \(([^\)]+)\)\]/iU', $line, $match)) {
886                     $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
887                 }
888             }
889
890             $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
891
892             $this->selected = $mailbox;
893             return true;
894         }
895
896         return false;
897     }
898
899     /**
900      * Executes STATUS command
901      *
902      * @param string $mailbox Mailbox name
903      * @param array  $items   Additional requested item names. By default
904      *                        MESSAGES and UNSEEN are requested. Other defined
905      *                        in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
906      *
907      * @return array Status item-value hash
908      * @access public
909      * @since 0.5-beta
910      */
911     function status($mailbox, $items=array())
912     {
913         if (!strlen($mailbox)) {
914             return false;
915         }
916
917         if (!in_array('MESSAGES', $items)) {
918             $items[] = 'MESSAGES';
919         }
920         if (!in_array('UNSEEN', $items)) {
921             $items[] = 'UNSEEN';
922         }
923
924         list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
925             '(' . implode(' ', (array) $items) . ')'));
926
927         if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
928             $result   = array();
929             $response = substr($response, 9); // remove prefix "* STATUS "
930
931             list($mbox, $items) = $this->tokenizeResponse($response, 2);
932
933             for ($i=0, $len=count($items); $i<$len; $i += 2) {
934                 $result[$items[$i]] = (int) $items[$i+1];
935             }
936
937             $this->data['STATUS:'.$mailbox] = $result;
938
939             return $result;
940         }
941
942         return false;
943     }
944
945     /**
946      * Executes EXPUNGE command
947      *
948      * @param string $mailbox  Mailbox name
949      * @param string $messages Message UIDs to expunge
950      *
951      * @return boolean True on success, False on error
952      * @access public
953      */
954     function expunge($mailbox, $messages=NULL)
955     {
956         if (!$this->select($mailbox)) {
957             return false;
958         }
959
960         if (!$this->data['READ-WRITE']) {
961             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
962             return false;
963         }
964
965         // Clear internal status cache
966         unset($this->data['STATUS:'.$mailbox]);
967
968         if ($messages)
969             $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
970         else
971             $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
972
973         if ($result == self::ERROR_OK) {
974             $this->selected = ''; // state has changed, need to reselect
975             return true;
976         }
977
978         return false;
979     }
980
981     /**
982      * Executes CLOSE command
983      *
984      * @return boolean True on success, False on error
985      * @access public
986      * @since 0.5
987      */
988     function close()
989     {
990         $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
991
992         if ($result == self::ERROR_OK) {
993             $this->selected = '';
994             return true;
995         }
996
997         return false;
998     }
999
1000     /**
1001      * Executes SUBSCRIBE command
1002      *
1003      * @param string $mailbox Mailbox name
1004      *
1005      * @return boolean True on success, False on error
1006      * @access public
1007      */
1008     function subscribe($mailbox)
1009     {
1010         $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1011             self::COMMAND_NORESPONSE);
1012
1013         return ($result == self::ERROR_OK);
1014     }
1015
1016     /**
1017      * Executes UNSUBSCRIBE command
1018      *
1019      * @param string $mailbox Mailbox name
1020      *
1021      * @return boolean True on success, False on error
1022      * @access public
1023      */
1024     function unsubscribe($mailbox)
1025     {
1026         $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1027             self::COMMAND_NORESPONSE);
1028
1029         return ($result == self::ERROR_OK);
1030     }
1031
1032     /**
1033      * Executes DELETE command
1034      *
1035      * @param string $mailbox Mailbox name
1036      *
1037      * @return boolean True on success, False on error
1038      * @access public
1039      */
1040     function deleteFolder($mailbox)
1041     {
1042         $result = $this->execute('DELETE', array($this->escape($mailbox)),
1043             self::COMMAND_NORESPONSE);
1044
1045         return ($result == self::ERROR_OK);
1046     }
1047
1048     /**
1049      * Removes all messages in a folder
1050      *
1051      * @param string $mailbox Mailbox name
1052      *
1053      * @return boolean True on success, False on error
1054      * @access public
1055      */
1056     function clearFolder($mailbox)
1057     {
1058         $num_in_trash = $this->countMessages($mailbox);
1059         if ($num_in_trash > 0) {
1060             $res = $this->delete($mailbox, '1:*');
1061         }
1062
1063         if ($res) {
1064             if ($this->selected == $mailbox)
1065                 $res = $this->close();
1066             else
1067                 $res = $this->expunge($mailbox);
1068         }
1069
1070         return $res;
1071     }
1072
1073     /**
1074      * Returns count of all messages in a folder
1075      *
1076      * @param string $mailbox Mailbox name
1077      *
1078      * @return int Number of messages, False on error
1079      * @access public
1080      */
1081     function countMessages($mailbox, $refresh = false)
1082     {
1083         if ($refresh) {
1084             $this->selected = '';
1085         }
1086
1087         if ($this->selected == $mailbox) {
1088             return $this->data['EXISTS'];
1089         }
1090
1091         // Check internal cache
1092         $cache = $this->data['STATUS:'.$mailbox];
1093         if (!empty($cache) && isset($cache['MESSAGES'])) {
1094             return (int) $cache['MESSAGES'];
1095         }
1096
1097         // Try STATUS (should be faster than SELECT)
1098         $counts = $this->status($mailbox);
1099         if (is_array($counts)) {
1100             return (int) $counts['MESSAGES'];
1101         }
1102
1103         return false;
1104     }
1105
1106     /**
1107      * Returns count of messages with \Recent flag in a folder
1108      *
1109      * @param string $mailbox Mailbox name
1110      *
1111      * @return int Number of messages, False on error
1112      * @access public
1113      */
1114     function countRecent($mailbox)
1115     {
1116         if (!strlen($mailbox)) {
1117             $mailbox = 'INBOX';
1118         }
1119
1120         $this->select($mailbox);
1121
1122         if ($this->selected == $mailbox) {
1123             return $this->data['RECENT'];
1124         }
1125
1126         return false;
1127     }
1128
1129     /**
1130      * Returns count of messages without \Seen flag in a specified folder
1131      *
1132      * @param string $mailbox Mailbox name
1133      *
1134      * @return int Number of messages, False on error
1135      * @access public
1136      */
1137     function countUnseen($mailbox)
1138     {
1139         // Check internal cache
1140         $cache = $this->data['STATUS:'.$mailbox];
1141         if (!empty($cache) && isset($cache['UNSEEN'])) {
1142             return (int) $cache['UNSEEN'];
1143         }
1144
1145         // Try STATUS (should be faster than SELECT+SEARCH)
1146         $counts = $this->status($mailbox);
1147         if (is_array($counts)) {
1148             return (int) $counts['UNSEEN'];
1149         }
1150
1151         // Invoke SEARCH as a fallback
1152         $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1153         if (is_array($index)) {
1154             return (int) $index['COUNT'];
1155         }
1156
1157         return false;
1158     }
1159
1160     function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1161     {
1162         $field = strtoupper($field);
1163         if ($field == 'INTERNALDATE') {
1164             $field = 'ARRIVAL';
1165         }
1166
1167         $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1168             'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1169
1170         if (!$fields[$field]) {
1171             return false;
1172         }
1173
1174         if (!$this->select($mailbox)) {
1175             return false;
1176         }
1177
1178         // message IDs
1179         if (!empty($add))
1180             $add = $this->compressMessageSet($add);
1181
1182         list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1183             array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1184
1185         if ($code == self::ERROR_OK) {
1186             // remove prefix and unilateral untagged server responses
1187             $response = substr($response, stripos($response, '* SORT') + 7);
1188             if ($pos = strpos($response, '*')) {
1189                 $response = substr($response, 0, $pos);
1190             }
1191             return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1192         }
1193
1194         return false;
1195     }
1196
1197     function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1198     {
1199         if (is_array($message_set)) {
1200             if (!($message_set = $this->compressMessageSet($message_set)))
1201                 return false;
1202         } else {
1203             list($from_idx, $to_idx) = explode(':', $message_set);
1204             if (empty($message_set) ||
1205                 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1206                 return false;
1207             }
1208         }
1209
1210         $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1211
1212         $fields_a['DATE']         = 1;
1213         $fields_a['INTERNALDATE'] = 4;
1214         $fields_a['ARRIVAL']      = 4;
1215         $fields_a['FROM']         = 1;
1216         $fields_a['REPLY-TO']     = 1;
1217         $fields_a['SENDER']       = 1;
1218         $fields_a['TO']           = 1;
1219         $fields_a['CC']           = 1;
1220         $fields_a['SUBJECT']      = 1;
1221         $fields_a['UID']          = 2;
1222         $fields_a['SIZE']         = 2;
1223         $fields_a['SEEN']         = 3;
1224         $fields_a['RECENT']       = 3;
1225         $fields_a['DELETED']      = 3;
1226
1227         if (!($mode = $fields_a[$index_field])) {
1228             return false;
1229         }
1230
1231         /*  Do "SELECT" command */
1232         if (!$this->select($mailbox)) {
1233             return false;
1234         }
1235
1236         // build FETCH command string
1237         $key     = $this->nextTag();
1238         $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
1239         $deleted = $skip_deleted ? ' FLAGS' : '';
1240
1241         if ($mode == 1 && $index_field == 'DATE')
1242             $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1243         else if ($mode == 1)
1244             $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1245         else if ($mode == 2) {
1246             if ($index_field == 'SIZE')
1247                 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1248             else
1249                 $request = " $cmd $message_set ($index_field$deleted)";
1250         } else if ($mode == 3)
1251             $request = " $cmd $message_set (FLAGS)";
1252         else // 4
1253             $request = " $cmd $message_set (INTERNALDATE$deleted)";
1254
1255         $request = $key . $request;
1256
1257         if (!$this->putLine($request)) {
1258             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1259             return false;
1260         }
1261
1262         $result = array();
1263
1264         do {
1265             $line = rtrim($this->readLine(200));
1266             $line = $this->multLine($line);
1267
1268             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1269                 $id     = $m[1];
1270                 $flags  = NULL;
1271
1272                 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1273                     $flags = explode(' ', strtoupper($matches[1]));
1274                     if (in_array('\\DELETED', $flags)) {
1275                         $deleted[$id] = $id;
1276                         continue;
1277                     }
1278                 }
1279
1280                 if ($mode == 1 && $index_field == 'DATE') {
1281                     if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1282                         $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1283                         $value = trim($value);
1284                         $result[$id] = $this->strToTime($value);
1285                     }
1286                     // non-existent/empty Date: header, use INTERNALDATE
1287                     if (empty($result[$id])) {
1288                         if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1289                             $result[$id] = $this->strToTime($matches[1]);
1290                         else
1291                             $result[$id] = 0;
1292                     }
1293                 } else if ($mode == 1) {
1294                     if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1295                         $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1296                         $result[$id] = trim($value);
1297                     } else {
1298                         $result[$id] = '';
1299                     }
1300                 } else if ($mode == 2) {
1301                     if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1302                         $result[$id] = trim($matches[2]);
1303                     } else {
1304                         $result[$id] = 0;
1305                     }
1306                 } else if ($mode == 3) {
1307                     if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1308                         $flags = explode(' ', $matches[1]);
1309                     }
1310                     $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1311                 } else if ($mode == 4) {
1312                     if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1313                         $result[$id] = $this->strToTime($matches[1]);
1314                     } else {
1315                         $result[$id] = 0;
1316                     }
1317                 }
1318             }
1319         } while (!$this->startsWith($line, $key, true, true));
1320
1321         return $result;
1322     }
1323
1324     static function compressMessageSet($messages, $force=false)
1325     {
1326         // given a comma delimited list of independent mid's,
1327         // compresses by grouping sequences together
1328
1329         if (!is_array($messages)) {
1330             // if less than 255 bytes long, let's not bother
1331             if (!$force && strlen($messages)<255) {
1332                 return $messages;
1333            }
1334
1335             // see if it's already been compressed
1336             if (strpos($messages, ':') !== false) {
1337                 return $messages;
1338             }
1339
1340             // separate, then sort
1341             $messages = explode(',', $messages);
1342         }
1343
1344         sort($messages);
1345
1346         $result = array();
1347         $start  = $prev = $messages[0];
1348
1349         foreach ($messages as $id) {
1350             $incr = $id - $prev;
1351             if ($incr > 1) { // found a gap
1352                 if ($start == $prev) {
1353                     $result[] = $prev; // push single id
1354                 } else {
1355                     $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1356                 }
1357                 $start = $id; // start of new sequence
1358             }
1359             $prev = $id;
1360         }
1361
1362         // handle the last sequence/id
1363         if ($start == $prev) {
1364             $result[] = $prev;
1365         } else {
1366             $result[] = $start.':'.$prev;
1367         }
1368
1369         // return as comma separated string
1370         return implode(',', $result);
1371     }
1372
1373     static function uncompressMessageSet($messages)
1374     {
1375         $result   = array();
1376         $messages = explode(',', $messages);
1377
1378         foreach ($messages as $part) {
1379             $items = explode(':', $part);
1380             $max   = max($items[0], $items[1]);
1381
1382             for ($x=$items[0]; $x<=$max; $x++) {
1383                 $result[] = $x;
1384             }
1385         }
1386
1387         return $result;
1388     }
1389
1390     /**
1391      * Returns message sequence identifier
1392      *
1393      * @param string $mailbox Mailbox name
1394      * @param int    $uid     Message unique identifier (UID)
1395      *
1396      * @return int Message sequence identifier
1397      * @access public
1398      */
1399     function UID2ID($mailbox, $uid)
1400     {
1401         if ($uid > 0) {
1402             $id_a = $this->search($mailbox, "UID $uid");
1403             if (is_array($id_a) && count($id_a) == 1) {
1404                 return (int) $id_a[0];
1405             }
1406         }
1407         return null;
1408     }
1409
1410     /**
1411      * Returns message unique identifier (UID)
1412      *
1413      * @param string $mailbox Mailbox name
1414      * @param int    $uid     Message sequence identifier
1415      *
1416      * @return int Message unique identifier
1417      * @access public
1418      */
1419     function ID2UID($mailbox, $id)
1420     {
1421         if (empty($id) || $id < 0) {
1422             return      null;
1423         }
1424
1425         if (!$this->select($mailbox)) {
1426             return null;
1427         }
1428
1429         list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1430
1431         if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1432             return (int) $m[1];
1433         }
1434
1435         return null;
1436     }
1437
1438     function fetchUIDs($mailbox, $message_set=null)
1439     {
1440         if (is_array($message_set))
1441             $message_set = join(',', $message_set);
1442         else if (empty($message_set))
1443             $message_set = '1:*';
1444
1445         return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1446     }
1447
1448     function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1449     {
1450         $result = array();
1451
1452         if (!$this->select($mailbox)) {
1453             return false;
1454         }
1455
1456         $message_set = $this->compressMessageSet($message_set);
1457
1458         if ($add)
1459             $add = ' '.trim($add);
1460
1461         /* FETCH uid, size, flags and headers */
1462         $key      = $this->nextTag();
1463         $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1464         $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1465         if ($bodystr)
1466             $request .= "BODYSTRUCTURE ";
1467         $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1468         $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1469
1470         if (!$this->putLine($request)) {
1471             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1472             return false;
1473         }
1474         do {
1475             $line = $this->readLine(4096);
1476             $line = $this->multLine($line);
1477
1478             if (!$line)
1479                 break;
1480
1481             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1482                 $id = intval($m[1]);
1483
1484                 $result[$id]            = new rcube_mail_header;
1485                 $result[$id]->id        = $id;
1486                 $result[$id]->subject   = '';
1487                 $result[$id]->messageID = 'mid:' . $id;
1488
1489                 $lines = array();
1490                 $ln = 0;
1491
1492                 // Sample reply line:
1493                 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1494                 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1495                 // BODY[HEADER.FIELDS ...
1496
1497                 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1498                     $str = $matches[1];
1499
1500                     // swap parents with quotes, then explode
1501                     $str = preg_replace('/[()]/', '"', $str);
1502                     $a = rcube_explode_quoted_string(' ', $str);
1503
1504                     // did we get the right number of replies?
1505                     $parts_count = count($a);
1506                     if ($parts_count>=6) {
1507                         for ($i=0; $i<$parts_count; $i=$i+2) {
1508                             if ($a[$i] == 'UID') {
1509                                 $result[$id]->uid = intval($a[$i+1]);
1510                             }
1511                             else if ($a[$i] == 'RFC822.SIZE') {
1512                                 $result[$id]->size = intval($a[$i+1]);
1513                             }
1514                             else if ($a[$i] == 'INTERNALDATE') {
1515                                 $time_str = $a[$i+1];
1516                             }
1517                             else if ($a[$i] == 'FLAGS') {
1518                                 $flags_str = $a[$i+1];
1519                             }
1520                         }
1521
1522                         $time_str = str_replace('"', '', $time_str);
1523
1524                         // if time is gmt...
1525                         $time_str = str_replace('GMT','+0000',$time_str);
1526
1527                         $result[$id]->internaldate = $time_str;
1528                         $result[$id]->timestamp    = $this->StrToTime($time_str);
1529                         $result[$id]->date         = $time_str;
1530                     }
1531
1532                     // BODYSTRUCTURE
1533                     if ($bodystr) {
1534                         while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1535                             $line2 = $this->readLine(1024);
1536                             $line .= $this->multLine($line2, true);
1537                         }
1538                         $result[$id]->body_structure = $m[1];
1539                     }
1540
1541                     // the rest of the result
1542                     if (preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m)) {
1543                         $reslines = explode("\n", trim($m[1], '"'));
1544                         // re-parse (see below)
1545                         foreach ($reslines as $resln) {
1546                             if (ord($resln[0])<=32) {
1547                                 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1548                             } else {
1549                                 $lines[++$ln] = trim($resln);
1550                             }
1551                         }
1552                     }
1553                 }
1554
1555                 // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1556                 // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1557                 // process the previous line.  Otherwise, we'll keep adding the strings until we come
1558                 // to the next valid header line.
1559
1560                 do {
1561                     $line = rtrim($this->readLine(300), "\r\n");
1562
1563                     // The preg_match below works around communigate imap, which outputs " UID <number>)".
1564                     // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1565                     // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1566                     // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1567                     // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1568                     // An alternative might be:
1569                     // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1570                     // however, unsure how well this would work with all imap clients.
1571                     if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1572                         break;
1573                     }
1574
1575                     // handle FLAGS reply after headers (AOL, Zimbra?)
1576                     if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1577                         $flags_str = $matches[1];
1578                         break;
1579                     }
1580
1581                     if (ord($line[0])<=32) {
1582                         $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1583                     } else {
1584                         $lines[++$ln] = trim($line);
1585                     }
1586                 // patch from "Maksim Rubis" <siburny@hotmail.com>
1587                 } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1588
1589                 if (strncmp($line, $key, strlen($key))) {
1590                     // process header, fill rcube_mail_header obj.
1591                     // initialize
1592                     if (is_array($headers)) {
1593                         reset($headers);
1594                         while (list($k, $bar) = each($headers)) {
1595                             $headers[$k] = '';
1596                         }
1597                     }
1598
1599                     // create array with header field:data
1600                     while (list($lines_key, $str) = each($lines)) {
1601                         list($field, $string) = $this->splitHeaderLine($str);
1602
1603                         $field  = strtolower($field);
1604                         $string = preg_replace('/\n\s*/', ' ', $string);
1605
1606                         switch ($field) {
1607                         case 'date';
1608                             $result[$id]->date = $string;
1609                             $result[$id]->timestamp = $this->strToTime($string);
1610                             break;
1611                         case 'from':
1612                             $result[$id]->from = $string;
1613                             break;
1614                         case 'to':
1615                             $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1616                             break;
1617                         case 'subject':
1618                             $result[$id]->subject = $string;
1619                             break;
1620                         case 'reply-to':
1621                             $result[$id]->replyto = $string;
1622                             break;
1623                         case 'cc':
1624                             $result[$id]->cc = $string;
1625                             break;
1626                         case 'bcc':
1627                             $result[$id]->bcc = $string;
1628                             break;
1629                         case 'content-transfer-encoding':
1630                             $result[$id]->encoding = $string;
1631                         break;
1632                         case 'content-type':
1633                             $ctype_parts = preg_split('/[; ]/', $string);
1634                             $result[$id]->ctype = array_shift($ctype_parts);
1635                             if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1636                                 $result[$id]->charset = $regs[1];
1637                             }
1638                             break;
1639                         case 'in-reply-to':
1640                             $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1641                             break;
1642                         case 'references':
1643                             $result[$id]->references = $string;
1644                             break;
1645                         case 'return-receipt-to':
1646                         case 'disposition-notification-to':
1647                         case 'x-confirm-reading-to':
1648                             $result[$id]->mdn_to = $string;
1649                             break;
1650                         case 'message-id':
1651                             $result[$id]->messageID = $string;
1652                             break;
1653                         case 'x-priority':
1654                             if (preg_match('/^(\d+)/', $string, $matches)) {
1655                                 $result[$id]->priority = intval($matches[1]);
1656                             }
1657                             break;
1658                         default:
1659                             if (strlen($field) > 2) {
1660                                 $result[$id]->others[$field] = $string;
1661                             }
1662                             break;
1663                         } // end switch ()
1664                     } // end while ()
1665                 }
1666
1667                 // process flags
1668                 if (!empty($flags_str)) {
1669                     $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1670                     $flags_a   = explode(' ', $flags_str);
1671
1672                     if (is_array($flags_a)) {
1673                         foreach($flags_a as $flag) {
1674                             $flag = strtoupper($flag);
1675                             if ($flag == 'SEEN') {
1676                                 $result[$id]->seen = true;
1677                             } else if ($flag == 'DELETED') {
1678                                 $result[$id]->deleted = true;
1679                             } else if ($flag == 'RECENT') {
1680                                 $result[$id]->recent = true;
1681                             } else if ($flag == 'ANSWERED') {
1682                                 $result[$id]->answered = true;
1683                             } else if ($flag == '$FORWARDED') {
1684                                 $result[$id]->forwarded = true;
1685                             } else if ($flag == 'DRAFT') {
1686                                 $result[$id]->is_draft = true;
1687                             } else if ($flag == '$MDNSENT') {
1688                                 $result[$id]->mdn_sent = true;
1689                             } else if ($flag == 'FLAGGED') {
1690                                  $result[$id]->flagged = true;
1691                             }
1692                         }
1693                         $result[$id]->flags = $flags_a;
1694                     }
1695                 }
1696             }
1697         } while (!$this->startsWith($line, $key, true));
1698
1699         return $result;
1700     }
1701
1702     function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1703     {
1704         $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1705         if (is_array($a)) {
1706             return array_shift($a);
1707         }
1708         return false;
1709     }
1710
1711     function sortHeaders($a, $field, $flag)
1712     {
1713         if (empty($field)) {
1714             $field = 'uid';
1715         }
1716         else {
1717             $field = strtolower($field);
1718         }
1719
1720         if ($field == 'date' || $field == 'internaldate') {
1721             $field = 'timestamp';
1722         }
1723
1724         if (empty($flag)) {
1725             $flag = 'ASC';
1726         } else {
1727             $flag = strtoupper($flag);
1728         }
1729
1730         $c = count($a);
1731         if ($c > 0) {
1732             // Strategy:
1733             // First, we'll create an "index" array.
1734             // Then, we'll use sort() on that array,
1735             // and use that to sort the main array.
1736
1737             // create "index" array
1738             $index = array();
1739             reset($a);
1740             while (list($key, $val) = each($a)) {
1741                 if ($field == 'timestamp') {
1742                     $data = $this->strToTime($val->date);
1743                     if (!$data) {
1744                         $data = $val->timestamp;
1745                     }
1746                 } else {
1747                     $data = $val->$field;
1748                     if (is_string($data)) {
1749                         $data = str_replace('"', '', $data);
1750                         if ($field == 'subject') {
1751                             $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1752                         }
1753                         $data = strtoupper($data);
1754                     }
1755                 }
1756                 $index[$key] = $data;
1757             }
1758
1759             // sort index
1760             if ($flag == 'ASC') {
1761                 asort($index);
1762             } else {
1763                 arsort($index);
1764             }
1765
1766             // form new array based on index
1767             $result = array();
1768             reset($index);
1769             while (list($key, $val) = each($index)) {
1770                 $result[$key] = $a[$key];
1771             }
1772         }
1773
1774         return $result;
1775     }
1776
1777
1778     function modFlag($mailbox, $messages, $flag, $mod)
1779     {
1780         if ($mod != '+' && $mod != '-') {
1781             $mod = '+';
1782         }
1783
1784         if (!$this->select($mailbox)) {
1785             return false;
1786         }
1787
1788         if (!$this->data['READ-WRITE']) {
1789             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1790             return false;
1791         }
1792
1793         // Clear internal status cache
1794         if ($flag == 'SEEN') {
1795             unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1796         }
1797
1798         $flag   = $this->flags[strtoupper($flag)];
1799         $result = $this->execute('UID STORE', array(
1800             $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1801             self::COMMAND_NORESPONSE);
1802
1803         return ($result == self::ERROR_OK);
1804     }
1805
1806     function flag($mailbox, $messages, $flag) {
1807         return $this->modFlag($mailbox, $messages, $flag, '+');
1808     }
1809
1810     function unflag($mailbox, $messages, $flag) {
1811         return $this->modFlag($mailbox, $messages, $flag, '-');
1812     }
1813
1814     function delete($mailbox, $messages) {
1815         return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1816     }
1817
1818     function copy($messages, $from, $to)
1819     {
1820         if (!$this->select($from)) {
1821             return false;
1822         }
1823
1824         // Clear internal status cache
1825         unset($this->data['STATUS:'.$to]);
1826
1827         $result = $this->execute('UID COPY', array(
1828             $this->compressMessageSet($messages), $this->escape($to)),
1829             self::COMMAND_NORESPONSE);
1830
1831         return ($result == self::ERROR_OK);
1832     }
1833
1834     function move($messages, $from, $to)
1835     {
1836         if (!$this->select($from)) {
1837             return false;
1838         }
1839
1840         if (!$this->data['READ-WRITE']) {
1841             $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1842             return false;
1843         }
1844
1845         $r = $this->copy($messages, $from, $to);
1846
1847         if ($r) {
1848             // Clear internal status cache
1849             unset($this->data['STATUS:'.$from]);
1850
1851             return $this->delete($from, $messages);
1852         }
1853         return $r;
1854     }
1855
1856     // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1857     // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1858     // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1859     private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1860     {
1861         $node = array();
1862         if ($str[$begin] != '(') {
1863             $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1864             $msg = substr($str, $begin, $stop - $begin);
1865             if ($msg == 0)
1866                 return $node;
1867             if (is_null($root))
1868                 $root = $msg;
1869             $depthmap[$msg] = $depth;
1870             $haschildren[$msg] = false;
1871             if (!is_null($parent))
1872                 $haschildren[$parent] = true;
1873             if ($stop + 1 < $end)
1874                 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1875             else
1876                 $node[$msg] = array();
1877         } else {
1878             $off = $begin;
1879             while ($off < $end) {
1880                 $start = $off;
1881                 $off++;
1882                 $n = 1;
1883                 while ($n > 0) {
1884                     $p = strpos($str, ')', $off);
1885                     if ($p === false) {
1886                         error_log("Mismatched brackets parsing IMAP THREAD response:");
1887                         error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1888                         error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1889                         return $node;
1890                     }
1891                     $p1 = strpos($str, '(', $off);
1892                     if ($p1 !== false && $p1 < $p) {
1893                         $off = $p1 + 1;
1894                         $n++;
1895                     } else {
1896                         $off = $p + 1;
1897                         $n--;
1898                     }
1899                 }
1900                 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1901             }
1902         }
1903
1904         return $node;
1905     }
1906
1907     function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1908     {
1909         $old_sel = $this->selected;
1910
1911         if (!$this->select($mailbox)) {
1912             return false;
1913         }
1914
1915         // return empty result when folder is empty and we're just after SELECT
1916         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1917             return array(array(), array(), array());
1918         }
1919
1920         $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1921         $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1922         $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1923         $data      = '';
1924
1925         list($code, $response) = $this->execute('THREAD', array(
1926             $algorithm, $encoding, $criteria));
1927
1928         if ($code == self::ERROR_OK) {
1929             // remove prefix...
1930             $response = substr($response, stripos($response, '* THREAD') + 9);
1931             // ...unilateral untagged server responses
1932             if ($pos = strpos($response, '*')) {
1933                 $response = substr($response, 0, $pos);
1934             }
1935
1936             $response    = str_replace("\r\n", '', $response);
1937             $depthmap    = array();
1938             $haschildren = array();
1939
1940             $tree = $this->parseThread($response, 0, strlen($response),
1941                 null, null, 0, $depthmap, $haschildren);
1942
1943             return array($tree, $depthmap, $haschildren);
1944         }
1945
1946         return false;
1947     }
1948
1949     /**
1950      * Executes SEARCH command
1951      *
1952      * @param string $mailbox    Mailbox name
1953      * @param string $criteria   Searching criteria
1954      * @param bool   $return_uid Enable UID in result instead of sequence ID
1955      * @param array  $items      Return items (MIN, MAX, COUNT, ALL)
1956      *
1957      * @return array Message identifiers or item-value hash 
1958      */
1959     function search($mailbox, $criteria, $return_uid=false, $items=array())
1960     {
1961         $old_sel = $this->selected;
1962
1963         if (!$this->select($mailbox)) {
1964             return false;
1965         }
1966
1967         // return empty result when folder is empty and we're just after SELECT
1968         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1969             if (!empty($items))
1970                 return array_combine($items, array_fill(0, count($items), 0));
1971             else
1972                 return array();
1973         }
1974
1975         $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
1976         $criteria = trim($criteria);
1977         $params   = '';
1978
1979         // RFC4731: ESEARCH
1980         if (!empty($items) && $esearch) {
1981             $params .= 'RETURN (' . implode(' ', $items) . ')';
1982         }
1983         if (!empty($criteria)) {
1984             $params .= ($params ? ' ' : '') . $criteria;
1985         }
1986         else {
1987             $params .= 'ALL';
1988         }
1989
1990         list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
1991             array($params));
1992
1993         if ($code == self::ERROR_OK) {
1994             // remove prefix...
1995             $response = substr($response, stripos($response, 
1996                 $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
1997             // ...and unilateral untagged server responses
1998             if ($pos = strpos($response, '*')) {
1999                 $response = rtrim(substr($response, 0, $pos));
2000             }
2001
2002             if ($esearch) {
2003                 // Skip prefix: ... (TAG "A285") UID ...
2004                 $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2005
2006                 $result = array();
2007                 for ($i=0; $i<count($items); $i++) {
2008                     // If the SEARCH results in no matches, the server MUST NOT
2009                     // include the item result option in the ESEARCH response
2010                     if ($ret = $this->tokenizeResponse($response, 2)) {
2011                         list ($name, $value) = $ret;
2012                         $result[$name] = $value;
2013                     }
2014                 }
2015
2016                 return $result;
2017             }
2018             else {
2019                 $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2020
2021                 if (!empty($items)) {
2022                     $result = array();
2023                     if (in_array('COUNT', $items)) {
2024                         $result['COUNT'] = count($response);
2025                     }
2026                     if (in_array('MIN', $items)) {
2027                         $result['MIN'] = !empty($response) ? min($response) : 0;
2028                     }
2029                     if (in_array('MAX', $items)) {
2030                         $result['MAX'] = !empty($response) ? max($response) : 0;
2031                     }
2032                     if (in_array('ALL', $items)) {
2033                         $result['ALL'] = $this->compressMessageSet($response, true);
2034                     }
2035
2036                     return $result;
2037                 }
2038                 else {
2039                     return $response;
2040                 }
2041             }
2042         }
2043
2044         return false;
2045     }
2046
2047     /**
2048      * Returns list of mailboxes
2049      *
2050      * @param string $ref         Reference name
2051      * @param string $mailbox     Mailbox name
2052      * @param array  $status_opts (see self::_listMailboxes)
2053      * @param array  $select_opts (see self::_listMailboxes)
2054      *
2055      * @return array List of mailboxes or hash of options if $status_opts argument
2056      *               is non-empty.
2057      * @access public
2058      */
2059     function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2060     {
2061         return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2062     }
2063
2064     /**
2065      * Returns list of subscribed mailboxes
2066      *
2067      * @param string $ref         Reference name
2068      * @param string $mailbox     Mailbox name
2069      * @param array  $status_opts (see self::_listMailboxes)
2070      *
2071      * @return array List of mailboxes or hash of options if $status_opts argument
2072      *               is non-empty.
2073      * @access public
2074      */
2075     function listSubscribed($ref, $mailbox, $status_opts=array())
2076     {
2077         return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2078     }
2079
2080     /**
2081      * IMAP LIST/LSUB command
2082      *
2083      * @param string $ref         Reference name
2084      * @param string $mailbox     Mailbox name
2085      * @param bool   $subscribed  Enables returning subscribed mailboxes only
2086      * @param array  $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2087      *                            Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2088      * @param array  $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2089      *                            Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2090      *
2091      * @return array List of mailboxes or hash of options if $status_ops argument
2092      *               is non-empty.
2093      * @access private
2094      */
2095     private function _listMailboxes($ref, $mailbox, $subscribed=false,
2096         $status_opts=array(), $select_opts=array())
2097     {
2098         if (!strlen($mailbox)) {
2099             $mailbox = '*';
2100         }
2101
2102         $args = array();
2103
2104         if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2105             $select_opts = (array) $select_opts;
2106
2107             $args[] = '(' . implode(' ', $select_opts) . ')';
2108         }
2109
2110         $args[] = $this->escape($ref);
2111         $args[] = $this->escape($mailbox);
2112
2113         if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2114             $status_opts = (array) $status_opts;
2115             $lstatus = true;
2116
2117             $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2118         }
2119
2120         list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2121
2122         if ($code == self::ERROR_OK) {
2123             $folders = array();
2124             while ($this->tokenizeResponse($response, 1) == '*') {
2125                 $cmd = strtoupper($this->tokenizeResponse($response, 1));
2126                 // * LIST (<options>) <delimiter> <mailbox>
2127                 if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
2128                     list($opts, $delim, $mailbox) = $this->tokenizeResponse($response, 3);
2129
2130                     // Add to result array
2131                     if (!$lstatus) {
2132                         $folders[] = $mailbox;
2133                     }
2134                     else {
2135                         $folders[$mailbox] = array();
2136                     }
2137
2138                     // Add to options array
2139                     if (!empty($opts)) {
2140                         if (empty($this->data['LIST'][$mailbox]))
2141                             $this->data['LIST'][$mailbox] = $opts;
2142                         else
2143                             $this->data['LIST'][$mailbox] = array_unique(array_merge(
2144                                 $this->data['LIST'][$mailbox], $opts));
2145                     }
2146                 }
2147                 // * STATUS <mailbox> (<result>)
2148                 else if ($cmd == 'STATUS') {
2149                     list($mailbox, $status) = $this->tokenizeResponse($response, 2);
2150
2151                     for ($i=0, $len=count($status); $i<$len; $i += 2) {
2152                         list($name, $value) = $this->tokenizeResponse($status, 2);
2153                         $folders[$mailbox][$name] = $value;
2154                     }
2155                 }
2156             }
2157
2158             return $folders;
2159         }
2160
2161         return false;
2162     }
2163
2164     function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
2165     {
2166         if (!$this->select($mailbox)) {
2167             return false;
2168         }
2169
2170         $result = false;
2171         $parts  = (array) $parts;
2172         $key    = $this->nextTag();
2173         $peeks  = '';
2174         $idx    = 0;
2175         $type   = $mime ? 'MIME' : 'HEADER';
2176
2177         // format request
2178         foreach($parts as $part) {
2179             $peeks[] = "BODY.PEEK[$part.$type]";
2180         }
2181
2182         $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2183
2184         // send request
2185         if (!$this->putLine($request)) {
2186             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2187             return false;
2188         }
2189
2190         do {
2191             $line = $this->readLine(1024);
2192             $line = $this->multLine($line);
2193
2194             if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2195                 $idx = $matches[1];
2196                 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
2197                 $result[$idx] = trim($result[$idx], '"');
2198                 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2199             }
2200         } while (!$this->startsWith($line, $key, true));
2201
2202         return $result;
2203     }
2204
2205     function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2206     {
2207         $part = empty($part) ? 'HEADER' : $part.'.MIME';
2208
2209         return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2210     }
2211
2212     function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2213     {
2214         if (!$this->select($mailbox)) {
2215             return false;
2216         }
2217
2218         switch ($encoding) {
2219         case 'base64':
2220             $mode = 1;
2221             break;
2222         case 'quoted-printable':
2223             $mode = 2;
2224             break;
2225         case 'x-uuencode':
2226         case 'x-uue':
2227         case 'uue':
2228         case 'uuencode':
2229             $mode = 3;
2230             break;
2231         default:
2232             $mode = 0;
2233         }
2234
2235         // format request
2236         $reply_key = '* ' . $id;
2237         $key       = $this->nextTag();
2238         $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2239
2240         // send request
2241         if (!$this->putLine($request)) {
2242             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2243             return false;
2244         }
2245
2246         // receive reply line
2247         do {
2248             $line = rtrim($this->readLine(1024));
2249             $a    = explode(' ', $line);
2250         } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2251
2252         $len    = strlen($line);
2253         $result = false;
2254
2255         // handle empty "* X FETCH ()" response
2256         if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2257             // one line response, get everything between first and last quotes
2258             if (substr($line, -4, 3) == 'NIL') {
2259                 // NIL response
2260                 $result = '';
2261             } else {
2262                 $from = strpos($line, '"') + 1;
2263                 $to   = strrpos($line, '"');
2264                 $len  = $to - $from;
2265                 $result = substr($line, $from, $len);
2266             }
2267
2268             if ($mode == 1) {
2269                 $result = base64_decode($result);
2270             }
2271             else if ($mode == 2) {
2272                 $result = quoted_printable_decode($result);
2273             }
2274             else if ($mode == 3) {
2275                 $result = convert_uudecode($result);
2276             }
2277
2278         } else if ($line[$len-1] == '}') {
2279             // multi-line request, find sizes of content and receive that many bytes
2280             $from     = strpos($line, '{') + 1;
2281             $to       = strrpos($line, '}');
2282             $len      = $to - $from;
2283             $sizeStr  = substr($line, $from, $len);
2284             $bytes    = (int)$sizeStr;
2285             $prev     = '';
2286
2287             while ($bytes > 0) {
2288                 $line = $this->readLine(4096);
2289
2290                 if ($line === NULL) {
2291                     break;
2292                 }
2293
2294                 $len  = strlen($line);
2295
2296                 if ($len > $bytes) {
2297                     $line = substr($line, 0, $bytes);
2298                     $len = strlen($line);
2299                 }
2300                 $bytes -= $len;
2301
2302                 // BASE64
2303                 if ($mode == 1) {
2304                     $line = rtrim($line, "\t\r\n\0\x0B");
2305                     // create chunks with proper length for base64 decoding
2306                     $line = $prev.$line;
2307                     $length = strlen($line);
2308                     if ($length % 4) {
2309                         $length = floor($length / 4) * 4;
2310                         $prev = substr($line, $length);
2311                         $line = substr($line, 0, $length);
2312                     }
2313                     else
2314                         $prev = '';
2315                     $line = base64_decode($line);
2316                 // QUOTED-PRINTABLE
2317                 } else if ($mode == 2) {
2318                     $line = rtrim($line, "\t\r\0\x0B");
2319                     $line = quoted_printable_decode($line);
2320                     // Remove NULL characters (#1486189)
2321                     $line = str_replace("\x00", '', $line);
2322                 // UUENCODE
2323                 } else if ($mode == 3) {
2324                     $line = rtrim($line, "\t\r\n\0\x0B");
2325                     if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2326                         continue;
2327                     $line = convert_uudecode($line);
2328                 // default
2329                 } else {
2330                     $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2331                 }
2332
2333                 if ($file)
2334                     fwrite($file, $line);
2335                 else if ($print)
2336                     echo $line;
2337                 else
2338                     $result .= $line;
2339             }
2340         }
2341
2342         // read in anything up until last line
2343         if (!$end)
2344             do {
2345                 $line = $this->readLine(1024);
2346             } while (!$this->startsWith($line, $key, true));
2347
2348         if ($result !== false) {
2349             if ($file) {
2350                 fwrite($file, $result);
2351             } else if ($print) {
2352                 echo $result;
2353             } else
2354                 return $result;
2355             return true;
2356         }
2357
2358         return false;
2359     }
2360
2361     function createFolder($mailbox)
2362     {
2363         $result = $this->execute('CREATE', array($this->escape($mailbox)),
2364             self::COMMAND_NORESPONSE);
2365
2366         return ($result == self::ERROR_OK);
2367     }
2368
2369     function renameFolder($from, $to)
2370     {
2371         $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2372             self::COMMAND_NORESPONSE);
2373
2374         return ($result == self::ERROR_OK);
2375     }
2376
2377     function append($mailbox, &$message)
2378     {
2379         if (!$mailbox) {
2380             return false;
2381         }
2382
2383         $message = str_replace("\r", '', $message);
2384         $message = str_replace("\n", "\r\n", $message);
2385
2386         $len = strlen($message);
2387         if (!$len) {
2388             return false;
2389         }
2390
2391         $key = $this->nextTag();
2392         $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2393             $len, ($this->prefs['literal+'] ? '+' : ''));
2394
2395         if ($this->putLine($request)) {
2396             // Don't wait when LITERAL+ is supported
2397             if (!$this->prefs['literal+']) {
2398                 $line = $this->readReply();
2399
2400                 if ($line[0] != '+') {
2401                     $this->parseResult($line, 'APPEND: ');
2402                     return false;
2403                 }
2404             }
2405
2406             if (!$this->putLine($message)) {
2407                 return false;
2408             }
2409
2410             do {
2411                 $line = $this->readLine();
2412             } while (!$this->startsWith($line, $key, true, true));
2413
2414             // Clear internal status cache
2415             unset($this->data['STATUS:'.$mailbox]);
2416
2417             return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2418         }
2419         else {
2420             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2421         }
2422
2423         return false;
2424     }
2425
2426     function appendFromFile($mailbox, $path, $headers=null)
2427     {
2428         if (!$mailbox) {
2429             return false;
2430         }
2431
2432         // open message file
2433         $in_fp = false;
2434         if (file_exists(realpath($path))) {
2435             $in_fp = fopen($path, 'r');
2436         }
2437         if (!$in_fp) {
2438             $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2439             return false;
2440         }
2441
2442         $body_separator = "\r\n\r\n";
2443         $len = filesize($path);
2444
2445         if (!$len) {
2446             return false;
2447         }
2448
2449         if ($headers) {
2450             $headers = preg_replace('/[\r\n]+$/', '', $headers);
2451             $len += strlen($headers) + strlen($body_separator);
2452         }
2453
2454         // send APPEND command
2455         $key = $this->nextTag();
2456         $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2457             $len, ($this->prefs['literal+'] ? '+' : ''));
2458
2459         if ($this->putLine($request)) {
2460             // Don't wait when LITERAL+ is supported
2461             if (!$this->prefs['literal+']) {
2462                 $line = $this->readReply();
2463
2464                 if ($line[0] != '+') {
2465                     $this->parseResult($line, 'APPEND: ');
2466                     return false;
2467                 }
2468             }
2469
2470             // send headers with body separator
2471             if ($headers) {
2472                 $this->putLine($headers . $body_separator, false);
2473             }
2474
2475             // send file
2476             while (!feof($in_fp) && $this->fp) {
2477                 $buffer = fgets($in_fp, 4096);
2478                 $this->putLine($buffer, false);
2479             }
2480             fclose($in_fp);
2481
2482             if (!$this->putLine('')) { // \r\n
2483                 return false;
2484             }
2485
2486             // read response
2487             do {
2488                 $line = $this->readLine();
2489             } while (!$this->startsWith($line, $key, true, true));
2490
2491             // Clear internal status cache
2492             unset($this->data['STATUS:'.$mailbox]);
2493
2494             return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2495         }
2496         else {
2497             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2498         }
2499
2500         return false;
2501     }
2502
2503     function fetchStructureString($mailbox, $id, $is_uid=false)
2504     {
2505         if (!$this->select($mailbox)) {
2506             return false;
2507         }
2508
2509         $key = $this->nextTag();
2510         $result = false;
2511         $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2512
2513         if ($this->putLine($command)) {
2514             do {
2515                 $line = $this->readLine(5000);
2516                 $line = $this->multLine($line, true);
2517                 if (!preg_match("/^$key /", $line))
2518                     $result .= $line;
2519             } while (!$this->startsWith($line, $key, true, true));
2520
2521             $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2522         }
2523         else {
2524             $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2525         }
2526
2527         return $result;
2528     }
2529
2530     function getQuota()
2531     {
2532         /*
2533          * GETQUOTAROOT "INBOX"
2534          * QUOTAROOT INBOX user/rchijiiwa1
2535          * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2536          * OK Completed
2537          */
2538         $result      = false;
2539         $quota_lines = array();
2540         $key         = $this->nextTag();
2541         $command     = $key . ' GETQUOTAROOT INBOX';
2542
2543         // get line(s) containing quota info
2544         if ($this->putLine($command)) {
2545             do {
2546                 $line = rtrim($this->readLine(5000));
2547                 if (preg_match('/^\* QUOTA /', $line)) {
2548                     $quota_lines[] = $line;
2549                 }
2550             } while (!$this->startsWith($line, $key, true, true));
2551         }
2552         else {
2553             $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2554         }
2555
2556         // return false if not found, parse if found
2557         $min_free = PHP_INT_MAX;
2558         foreach ($quota_lines as $key => $quota_line) {
2559             $quota_line   = str_replace(array('(', ')'), '', $quota_line);
2560             $parts        = explode(' ', $quota_line);
2561             $storage_part = array_search('STORAGE', $parts);
2562
2563             if (!$storage_part) {
2564                 continue;
2565             }
2566
2567             $used  = intval($parts[$storage_part+1]);
2568             $total = intval($parts[$storage_part+2]);
2569             $free  = $total - $used;
2570
2571             // return lowest available space from all quotas
2572             if ($free < $min_free) {
2573                 $min_free          = $free;
2574                 $result['used']    = $used;
2575                 $result['total']   = $total;
2576                 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2577                 $result['free']    = 100 - $result['percent'];
2578             }
2579         }
2580
2581         return $result;
2582     }
2583
2584     /**
2585      * Send the SETACL command (RFC4314)
2586      *
2587      * @param string $mailbox Mailbox name
2588      * @param string $user    User name
2589      * @param mixed  $acl     ACL string or array
2590      *
2591      * @return boolean True on success, False on failure
2592      *
2593      * @access public
2594      * @since 0.5-beta
2595      */
2596     function setACL($mailbox, $user, $acl)
2597     {
2598         if (is_array($acl)) {
2599             $acl = implode('', $acl);
2600         }
2601
2602         $result = $this->execute('SETACL', array(
2603             $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2604             self::COMMAND_NORESPONSE);
2605
2606         return ($result == self::ERROR_OK);
2607     }
2608
2609     /**
2610      * Send the DELETEACL command (RFC4314)
2611      *
2612      * @param string $mailbox Mailbox name
2613      * @param string $user    User name
2614      *
2615      * @return boolean True on success, False on failure
2616      *
2617      * @access public
2618      * @since 0.5-beta
2619      */
2620     function deleteACL($mailbox, $user)
2621     {
2622         $result = $this->execute('DELETEACL', array(
2623             $this->escape($mailbox), $this->escape($user)),
2624             self::COMMAND_NORESPONSE);
2625
2626         return ($result == self::ERROR_OK);
2627     }
2628
2629     /**
2630      * Send the GETACL command (RFC4314)
2631      *
2632      * @param string $mailbox Mailbox name
2633      *
2634      * @return array User-rights array on success, NULL on error
2635      * @access public
2636      * @since 0.5-beta
2637      */
2638     function getACL($mailbox)
2639     {
2640         list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2641
2642         if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2643             // Parse server response (remove "* ACL ")
2644             $response = substr($response, 6);
2645             $ret  = $this->tokenizeResponse($response);
2646             $mbox = array_shift($ret);
2647             $size = count($ret);
2648
2649             // Create user-rights hash array
2650             // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2651             // so we could return only standard rights defined in RFC4314,
2652             // excluding 'c' and 'd' defined in RFC2086.
2653             if ($size % 2 == 0) {
2654                 for ($i=0; $i<$size; $i++) {
2655                     $ret[$ret[$i]] = str_split($ret[++$i]);
2656                     unset($ret[$i-1]);
2657                     unset($ret[$i]);
2658                 }
2659                 return $ret;
2660             }
2661
2662             $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2663             return NULL;
2664         }
2665
2666         return NULL;
2667     }
2668
2669     /**
2670      * Send the LISTRIGHTS command (RFC4314)
2671      *
2672      * @param string $mailbox Mailbox name
2673      * @param string $user    User name
2674      *
2675      * @return array List of user rights
2676      * @access public
2677      * @since 0.5-beta
2678      */
2679     function listRights($mailbox, $user)
2680     {
2681         list($code, $response) = $this->execute('LISTRIGHTS', array(
2682             $this->escape($mailbox), $this->escape($user)));
2683
2684         if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2685             // Parse server response (remove "* LISTRIGHTS ")
2686             $response = substr($response, 13);
2687
2688             $ret_mbox = $this->tokenizeResponse($response, 1);
2689             $ret_user = $this->tokenizeResponse($response, 1);
2690             $granted  = $this->tokenizeResponse($response, 1);
2691             $optional = trim($response);
2692
2693             return array(
2694                 'granted'  => str_split($granted),
2695                 'optional' => explode(' ', $optional),
2696             );
2697         }
2698
2699         return NULL;
2700     }
2701
2702     /**
2703      * Send the MYRIGHTS command (RFC4314)
2704      *
2705      * @param string $mailbox Mailbox name
2706      *
2707      * @return array MYRIGHTS response on success, NULL on error
2708      * @access public
2709      * @since 0.5-beta
2710      */
2711     function myRights($mailbox)
2712     {
2713         list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2714
2715         if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2716             // Parse server response (remove "* MYRIGHTS ")
2717             $response = substr($response, 11);
2718
2719             $ret_mbox = $this->tokenizeResponse($response, 1);
2720             $rights   = $this->tokenizeResponse($response, 1);
2721
2722             return str_split($rights);
2723         }
2724
2725         return NULL;
2726     }
2727
2728     /**
2729      * Send the SETMETADATA command (RFC5464)
2730      *
2731      * @param string $mailbox Mailbox name
2732      * @param array  $entries Entry-value array (use NULL value as NIL)
2733      *
2734      * @return boolean True on success, False on failure
2735      * @access public
2736      * @since 0.5-beta
2737      */
2738     function setMetadata($mailbox, $entries)
2739     {
2740         if (!is_array($entries) || empty($entries)) {
2741             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2742             return false;
2743         }
2744
2745         foreach ($entries as $name => $value) {
2746             if ($value === null) {
2747                 $value = 'NIL';
2748             }
2749             else {
2750                 $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2751             }
2752             $entries[$name] = $this->escape($name) . ' ' . $value;
2753         }
2754
2755         $entries = implode(' ', $entries);
2756         $result = $this->execute('SETMETADATA', array(
2757             $this->escape($mailbox), '(' . $entries . ')'),
2758             self::COMMAND_NORESPONSE);
2759
2760         return ($result == self::ERROR_OK);
2761     }
2762
2763     /**
2764      * Send the SETMETADATA command with NIL values (RFC5464)
2765      *
2766      * @param string $mailbox Mailbox name
2767      * @param array  $entries Entry names array
2768      *
2769      * @return boolean True on success, False on failure
2770      *
2771      * @access public
2772      * @since 0.5-beta
2773      */
2774     function deleteMetadata($mailbox, $entries)
2775     {
2776         if (!is_array($entries) && !empty($entries)) {
2777             $entries = explode(' ', $entries);
2778         }
2779
2780         if (empty($entries)) {
2781             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2782             return false;
2783         }
2784
2785         foreach ($entries as $entry) {
2786             $data[$entry] = NULL;
2787         }
2788
2789         return $this->setMetadata($mailbox, $data);
2790     }
2791
2792     /**
2793      * Send the GETMETADATA command (RFC5464)
2794      *
2795      * @param string $mailbox Mailbox name
2796      * @param array  $entries Entries
2797      * @param array  $options Command options (with MAXSIZE and DEPTH keys)
2798      *
2799      * @return array GETMETADATA result on success, NULL on error
2800      *
2801      * @access public
2802      * @since 0.5-beta
2803      */
2804     function getMetadata($mailbox, $entries, $options=array())
2805     {
2806         if (!is_array($entries)) {
2807             $entries = array($entries);
2808         }
2809
2810         // create entries string
2811         foreach ($entries as $idx => $name) {
2812             $entries[$idx] = $this->escape($name);
2813         }
2814
2815         $optlist = '';
2816         $entlist = '(' . implode(' ', $entries) . ')';
2817
2818         // create options string
2819         if (is_array($options)) {
2820             $options = array_change_key_case($options, CASE_UPPER);
2821             $opts = array();
2822
2823             if (!empty($options['MAXSIZE'])) {
2824                 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2825             }
2826             if (!empty($options['DEPTH'])) {
2827                 $opts[] = 'DEPTH '.intval($options['DEPTH']);
2828             }
2829
2830             if ($opts) {
2831                 $optlist = '(' . implode(' ', $opts) . ')';
2832             }
2833         }
2834
2835         $optlist .= ($optlist ? ' ' : '') . $entlist;
2836
2837         list($code, $response) = $this->execute('GETMETADATA', array(
2838             $this->escape($mailbox), $optlist));
2839
2840         if ($code == self::ERROR_OK) {
2841             $result = array();
2842             $data   = $this->tokenizeResponse($response);
2843
2844             // The METADATA response can contain multiple entries in a single
2845             // response or multiple responses for each entry or group of entries
2846             if (!empty($data) && ($size = count($data))) {
2847                 for ($i=0; $i<$size; $i++) {
2848                     if (isset($mbox) && is_array($data[$i])) {
2849                         $size_sub = count($data[$i]);
2850                         for ($x=0; $x<$size_sub; $x++) {
2851                             $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
2852                         }
2853                         unset($data[$i]);
2854                     }
2855                     else if ($data[$i] == '*') {
2856                         if ($data[$i+1] == 'METADATA') {
2857                             $mbox = $data[$i+2];
2858                             unset($data[$i]);   // "*"
2859                             unset($data[++$i]); // "METADATA"
2860                             unset($data[++$i]); // Mailbox
2861                         }
2862                         // get rid of other untagged responses
2863                         else {
2864                             unset($mbox);
2865                             unset($data[$i]);
2866                         }
2867                     }
2868                     else if (isset($mbox)) {
2869                         $result[$mbox][$data[$i]] = $data[++$i];
2870                         unset($data[$i]);
2871                         unset($data[$i-1]);
2872                     }
2873                     else {
2874                         unset($data[$i]);
2875                     }
2876                 }
2877             }
2878
2879             return $result;
2880         }
2881
2882         return NULL;
2883     }
2884
2885     /**
2886      * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
2887      *
2888      * @param string $mailbox Mailbox name
2889      * @param array  $data    Data array where each item is an array with
2890      *                        three elements: entry name, attribute name, value
2891      *
2892      * @return boolean True on success, False on failure
2893      * @access public
2894      * @since 0.5-beta
2895      */
2896     function setAnnotation($mailbox, $data)
2897     {
2898         if (!is_array($data) || empty($data)) {
2899             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2900             return false;
2901         }
2902
2903         foreach ($data as $entry) {
2904             $name  = $entry[0];
2905             $attr  = $entry[1];
2906             $value = $entry[2];
2907
2908             if ($value === null) {
2909                 $value = 'NIL';
2910             }
2911             else {
2912                 $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2913             }
2914
2915             // ANNOTATEMORE drafts before version 08 require quoted parameters
2916             $entries[] = sprintf('%s (%s %s)',
2917                 $this->escape($name, true), $this->escape($attr, true), $value);
2918         }
2919
2920         $entries = implode(' ', $entries);
2921         $result  = $this->execute('SETANNOTATION', array(
2922             $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
2923
2924         return ($result == self::ERROR_OK);
2925     }
2926
2927     /**
2928      * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
2929      *
2930      * @param string $mailbox Mailbox name
2931      * @param array  $data    Data array where each item is an array with
2932      *                        two elements: entry name and attribute name
2933      *
2934      * @return boolean True on success, False on failure
2935      *
2936      * @access public
2937      * @since 0.5-beta
2938      */
2939     function deleteAnnotation($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         return $this->setAnnotation($mailbox, $data);
2947     }
2948
2949     /**
2950      * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
2951      *
2952      * @param string $mailbox Mailbox name
2953      * @param array  $entries Entries names
2954      * @param array  $attribs Attribs names
2955      *
2956      * @return array Annotations result on success, NULL on error
2957      *
2958      * @access public
2959      * @since 0.5-beta
2960      */
2961     function getAnnotation($mailbox, $entries, $attribs)
2962     {
2963         if (!is_array($entries)) {
2964             $entries = array($entries);
2965         }
2966         // create entries string
2967         // ANNOTATEMORE drafts before version 08 require quoted parameters
2968         foreach ($entries as $idx => $name) {
2969             $entries[$idx] = $this->escape($name, true);
2970         }
2971         $entries = '(' . implode(' ', $entries) . ')';
2972
2973         if (!is_array($attribs)) {
2974             $attribs = array($attribs);
2975         }
2976         // create entries string
2977         foreach ($attribs as $idx => $name) {
2978             $attribs[$idx] = $this->escape($name, true);
2979         }
2980         $attribs = '(' . implode(' ', $attribs) . ')';
2981
2982         list($code, $response) = $this->execute('GETANNOTATION', array(
2983             $this->escape($mailbox), $entries, $attribs));
2984
2985         if ($code == self::ERROR_OK) {
2986             $result = array();
2987             $data   = $this->tokenizeResponse($response);
2988
2989             // Here we returns only data compatible with METADATA result format
2990             if (!empty($data) && ($size = count($data))) {
2991                 for ($i=0; $i<$size; $i++) {
2992                     $entry = $data[$i];
2993                     if (isset($mbox) && is_array($entry)) {
2994                         $attribs = $entry;
2995                         $entry   = $last_entry;
2996                     }
2997                     else if ($entry == '*') {
2998                         if ($data[$i+1] == 'ANNOTATION') {
2999                             $mbox = $data[$i+2];
3000                             unset($data[$i]);   // "*"
3001                             unset($data[++$i]); // "ANNOTATION"
3002                             unset($data[++$i]); // Mailbox
3003                         }
3004                         // get rid of other untagged responses
3005                         else {
3006                             unset($mbox);
3007                             unset($data[$i]);
3008                         }
3009                         continue;
3010                     }
3011                     else if (isset($mbox)) {
3012                         $attribs = $data[++$i];
3013                     }
3014                     else {
3015                         unset($data[$i]);
3016                         continue;
3017                     }
3018
3019                     if (!empty($attribs)) {
3020                         for ($x=0, $len=count($attribs); $x<$len;) {
3021                             $attr  = $attribs[$x++];
3022                             $value = $attribs[$x++];
3023                             if ($attr == 'value.priv') {
3024                                 $result[$mbox]['/private' . $entry] = $value;
3025                             }
3026                             else if ($attr == 'value.shared') {
3027                                 $result[$mbox]['/shared' . $entry] = $value;
3028                             }
3029                         }
3030                     }
3031                     $last_entry = $entry;
3032                     unset($data[$i]);
3033                 }
3034             }
3035
3036             return $result;
3037         }
3038
3039         return NULL;
3040     }
3041
3042     /**
3043      * Creates next command identifier (tag)
3044      *
3045      * @return string Command identifier
3046      * @access public
3047      * @since 0.5-beta
3048      */
3049     function nextTag()
3050     {
3051         $this->cmd_num++;
3052         $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3053
3054         return $this->cmd_tag;
3055     }
3056
3057     /**
3058      * Sends IMAP command and parses result
3059      *
3060      * @param string $command   IMAP command
3061      * @param array  $arguments Command arguments
3062      * @param int    $options   Execution options
3063      *
3064      * @return mixed Response code or list of response code and data
3065      * @access public
3066      * @since 0.5-beta
3067      */
3068     function execute($command, $arguments=array(), $options=0)
3069     {
3070         $tag      = $this->nextTag();
3071         $query    = $tag . ' ' . $command;
3072         $noresp   = ($options & self::COMMAND_NORESPONSE);
3073         $response = $noresp ? null : '';
3074
3075         if (!empty($arguments)) {
3076             $query .= ' ' . implode(' ', $arguments);
3077         }
3078
3079         // Send command
3080         if (!$this->putLineC($query)) {
3081             $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3082             return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3083         }
3084
3085         // Parse response
3086         do {
3087             $line = $this->readLine(4096);
3088             if ($response !== null) {
3089                 $response .= $line;
3090             }
3091         } while (!$this->startsWith($line, $tag . ' ', true, true));
3092
3093         $code = $this->parseResult($line, $command . ': ');
3094
3095         // Remove last line from response
3096         if ($response) {
3097             $line_len = min(strlen($response), strlen($line) + 2);
3098             $response = substr($response, 0, -$line_len);
3099         }
3100
3101         // optional CAPABILITY response
3102         if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3103             && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3104         ) {
3105             $this->parseCapability($matches[1], true);
3106         }
3107
3108         // return last line only (without command tag, result and response code)
3109         if ($line && ($options & self::COMMAND_LASTLINE)) {
3110             $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3111         }
3112
3113         return $noresp ? $code : array($code, $response);
3114     }
3115
3116     /**
3117      * Splits IMAP response into string tokens
3118      *
3119      * @param string &$str The IMAP's server response
3120      * @param int    $num  Number of tokens to return
3121      *
3122      * @return mixed Tokens array or string if $num=1
3123      * @access public
3124      * @since 0.5-beta
3125      */
3126     static function tokenizeResponse(&$str, $num=0)
3127     {
3128         $result = array();
3129
3130         while (!$num || count($result) < $num) {
3131             // remove spaces from the beginning of the string
3132             $str = ltrim($str);
3133
3134             switch ($str[0]) {
3135
3136             // String literal
3137             case '{':
3138                 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3139                     // error
3140                 }
3141                 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3142                     // error
3143                 }
3144                 $result[] = substr($str, $epos + 3, $bytes);
3145                 // Advance the string
3146                 $str = substr($str, $epos + 3 + $bytes);
3147                 break;
3148
3149             // Quoted string
3150             case '"':
3151                 $len = strlen($str);
3152
3153                 for ($pos=1; $pos<$len; $pos++) {
3154                     if ($str[$pos] == '"') {
3155                         break;
3156                     }
3157                     if ($str[$pos] == "\\") {
3158                         if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3159                             $pos++;
3160                         }
3161                     }
3162                 }
3163                 if ($str[$pos] != '"') {
3164                     // error
3165                 }
3166                 // we need to strip slashes for a quoted string
3167                 $result[] = stripslashes(substr($str, 1, $pos - 1));
3168                 $str      = substr($str, $pos + 1);
3169                 break;
3170
3171             // Parenthesized list
3172             case '(':
3173                 $str = substr($str, 1);
3174                 $result[] = self::tokenizeResponse($str);
3175                 break;
3176             case ')':
3177                 $str = substr($str, 1);
3178                 return $result;
3179                 break;
3180
3181             // String atom, number, NIL, *, %
3182             default:
3183                 // empty or one character
3184                 if ($str === '') {
3185                     break 2;
3186                 }
3187                 if (strlen($str) < 2) {
3188                     $result[] = $str;
3189                     $str = '';
3190                     break;
3191                 }
3192
3193                 // excluded chars: SP, CTL, (, ), {, ", ], %
3194                 if (preg_match('/^([\x21\x23\x24\x26\x27\x2A-\x5C\x5E-\x7A\x7C-\x7E]+)/', $str, $m)) {
3195                     $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3196                     $str = substr($str, strlen($m[1]));
3197                 }
3198                 break;
3199             }
3200         }
3201
3202         return $num == 1 ? $result[0] : $result;
3203     }
3204
3205     private function _xor($string, $string2)
3206     {
3207         $result = '';
3208         $size   = strlen($string);
3209
3210         for ($i=0; $i<$size; $i++) {
3211             $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3212         }
3213
3214         return $result;
3215     }
3216
3217     /**
3218      * Converts datetime string into unix timestamp
3219      *
3220      * @param string $date Date string
3221      *
3222      * @return int Unix timestamp
3223      */
3224     private function strToTime($date)
3225     {
3226         // support non-standard "GMTXXXX" literal
3227         $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
3228         // if date parsing fails, we have a date in non-rfc format.
3229         // remove token from the end and try again
3230         while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
3231             $d = explode(' ', $date);
3232             array_pop($d);
3233             if (!$d) {
3234                 break;
3235             }
3236             $date = implode(' ', $d);
3237         }
3238
3239         $ts = (int) $ts;
3240
3241         return $ts < 0 ? 0 : $ts;
3242     }
3243
3244     private function splitHeaderLine($string)
3245     {
3246         $pos = strpos($string, ':');
3247         if ($pos>0) {
3248             $res[0] = substr($string, 0, $pos);
3249             $res[1] = trim(substr($string, $pos+1));
3250             return $res;
3251         }
3252         return $string;
3253     }
3254
3255     private function parseCapability($str, $trusted=false)
3256     {
3257         $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3258
3259         $this->capability = explode(' ', strtoupper($str));
3260
3261         if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3262             $this->prefs['literal+'] = true;
3263         }
3264
3265         if ($trusted) {
3266             $this->capability_readed = true;
3267         }
3268     }
3269
3270     /**
3271      * Escapes a string when it contains special characters (RFC3501)
3272      *
3273      * @param string  $string       IMAP string
3274      * @param boolean $force_quotes Forces string quoting
3275      *
3276      * @return string Escaped string
3277      * @todo String literals, lists
3278      */
3279     static function escape($string, $force_quotes=false)
3280     {
3281         if ($string === null) {
3282             return 'NIL';
3283         }
3284         else if ($string === '') {
3285             return '""';
3286         }
3287         else if ($force_quotes ||
3288             preg_match('/([\x00-\x20\x28-\x29\x7B\x25\x2A\x22\x5C\x5D\x7F]+)/', $string)
3289         ) {
3290             // string: special chars: SP, CTL, (, ), {, %, *, ", \, ]
3291             return '"' . strtr($string, array('"'=>'\\"', '\\' => '\\\\')) . '"';
3292         }
3293
3294         // atom
3295         return $string;
3296     }
3297
3298     static function unEscape($string)
3299     {
3300         return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
3301     }
3302
3303     /**
3304      * Set the value of the debugging flag.
3305      *
3306      * @param   boolean $debug      New value for the debugging flag.
3307      *
3308      * @access  public
3309      * @since   0.5-stable
3310      */
3311     function setDebug($debug, $handler = null)
3312     {
3313         $this->_debug = $debug;
3314         $this->_debug_handler = $handler;
3315     }
3316
3317     /**
3318      * Write the given debug text to the current debug output handler.
3319      *
3320      * @param   string  $message    Debug mesage text.
3321      *
3322      * @access  private
3323      * @since   0.5-stable
3324      */
3325     private function debug($message)
3326     {
3327         if ($this->_debug_handler) {
3328             call_user_func_array($this->_debug_handler, array(&$this, $message));
3329         } else {
3330             echo "DEBUG: $message\n";
3331         }
3332     }
3333
3334 }