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

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