source: subversion/trunk/roundcubemail/program/include/rcube_imap_generic.php @ 4321

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