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