source: subversion/branches/release-0.7/program/include/rcube_imap_generic.php @ 5952

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