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

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