source: github/program/include/rcube_imap_generic.php @ 80152b33

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