source: github/program/include/rcube_imap_generic.php @ 4757608

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 4757608 was 4757608, checked in by alecpl <alec@…>, 3 years ago
  • Improve pre-auth and auth capabilities handling
  • Property mode set to 100644
File size: 87.9 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 set_error($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->set_error(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->next_tag() . " 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->set_error(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->next_tag() . " 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->set_error($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            $message = "INITIAL: $auth_method\n";
684
685            $result = false;
686
687            // initialize connection
688            $this->error    = '';
689            $this->errornum = self::ERROR_OK;
690            $this->selected = '';
691            $this->user     = $user;
692            $this->host     = $host;
693        $this->logged   = false;
694
695            // check input
696            if (empty($host)) {
697                    $this->set_error(self::ERROR_BAD, "Empty host");
698                    return false;
699            }
700        if (empty($user)) {
701                $this->set_error(self::ERROR_NO, "Empty user");
702                return false;
703            }
704            if (empty($password)) {
705                $this->set_error(self::ERROR_NO, "Empty password");
706                    return false;
707            }
708
709            if (!$this->prefs['port']) {
710                    $this->prefs['port'] = 143;
711            }
712            // check for SSL
713            if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
714                    $host = $this->prefs['ssl_mode'] . '://' . $host;
715            }
716
717        // Connect
718        if ($this->prefs['timeout'] > 0)
719                $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
720            else
721                $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr);
722
723            if (!$this->fp) {
724                $this->set_error(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
725                    return false;
726            }
727
728        if ($this->prefs['timeout'] > 0)
729                stream_set_timeout($this->fp, $this->prefs['timeout']);
730
731            $line = trim(fgets($this->fp, 8192));
732
733            if ($this->prefs['debug_mode'] && $line) {
734                    write_log('imap', 'S: '. $line);
735        }
736
737            // Connected to wrong port or connection error?
738            if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
739                    if ($line)
740                            $this->error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
741                    else
742                            $this->error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
743                $this->errornum = self::ERROR_BAD;
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                    return false;
761                }
762
763                            if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
764                                    $this->set_error(self::ERROR_BAD, "Unable to negotiate TLS");
765                                    return false;
766                            }
767
768                            // Now we're secure, capabilities need to be reread
769                            $this->clearCapability();
770                }
771            }
772
773            $auth_methods = array();
774        $result       = null;
775
776            // check for supported auth methods
777            if ($auth_method == 'CHECK') {
778                    if ($this->getCapability('AUTH=DIGEST-MD5')) {
779                            $auth_methods[] = 'DIGEST-MD5';
780                    }
781                    if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
782                            $auth_methods[] = 'CRAM-MD5';
783                    }
784                    if ($this->getCapability('AUTH=PLAIN')) {
785                            $auth_methods[] = 'PLAIN';
786                    }
787            // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
788                    if (!$this->getCapability('LOGINDISABLED')) {
789                            $auth_methods[] = 'LOGIN';
790                    }
791            }
792        else {
793            // replace AUTH with CRAM-MD5 for backward compat.
794            $auth_methods[] = $auth_method == 'AUTH' ? 'CRAM-MD5' : $auth_method;
795        }
796
797        // pre-login capabilities can be not complete
798        $this->capability_readed = false;
799
800        // Authenticate
801        foreach ($auth_methods as $method) {
802            switch ($method) {
803            case 'DIGEST-MD5':
804            case 'CRAM-MD5':
805                case 'PLAIN':
806                            $result = $this->authenticate($user, $password, $method);
807                        break;
808            case 'LOGIN':
809                $result = $this->login($user, $password);
810                break;
811            default:
812                $this->set_error(self::ERROR_BAD, "Configuration error. Unknown auth method: $method");
813            }
814
815                    if (is_resource($result)) {
816                            break;
817                    }
818            }
819
820        // Connected and authenticated
821            if (is_resource($result)) {
822            if ($this->prefs['force_caps']) {
823                            $this->clearCapability();
824            }
825                    $this->getRootDir();
826            $this->logged = true;
827
828                    return true;
829        }
830
831        // Close connection
832        @fclose($this->fp);
833        $this->fp = false;
834
835            return false;
836    }
837
838    function connected()
839    {
840                return ($this->fp && $this->logged) ? true : false;
841    }
842
843    function close()
844    {
845            if ($this->logged && $this->putLine($this->next_tag() . ' LOGOUT')) {
846                    if (!feof($this->fp))
847                            fgets($this->fp, 1024);
848            }
849                @fclose($this->fp);
850                $this->fp = false;
851    }
852
853    function select($mailbox)
854    {
855            if (empty($mailbox)) {
856                    return false;
857            }
858
859            if ($this->selected == $mailbox) {
860                    return true;
861            }
862
863        if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
864            if (in_array('\\Noselect', $opts)) {
865                return false;
866            }
867        }
868
869        list($code, $response) = $this->execute('SELECT', array($this->escape($mailbox)));
870
871        if ($code == self::ERROR_OK) {
872            $response = explode("\r\n", $response);
873            foreach ($response as $line) {
874                        if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
875                            $this->data[strtoupper($m[2])] = (int) $m[1];
876                        }
877                            else if (preg_match('/^\* OK \[(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)\]/i', $line, $match)) {
878                                $this->data[strtoupper($match[1])] = (int) $match[2];
879                            }
880                            else if (preg_match('/^\* OK \[PERMANENTFLAGS \(([^\)]+)\)\]/iU', $line, $match)) {
881                                $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
882                            }
883            }
884
885                    $this->selected = $mailbox;
886                        return true;
887                }
888
889        return false;
890    }
891
892    /**
893     * Executes STATUS comand
894     *
895     * @param string $mailbox Mailbox name
896     * @param array  $items   Requested item names
897     *
898     * @return array Status item-value hash
899     * @access public
900     * @since 0.5-beta
901     */
902    function status($mailbox, $items)
903    {
904            if (empty($mailbox) || empty($items)) {
905                    return false;
906            }
907
908        list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
909            '(' . implode(' ', (array) $items) . ')'));
910
911        if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
912            $result   = array();
913            $response = substr($response, 9); // remove prefix "* STATUS "
914
915            list($mbox, $items) = $this->tokenizeResponse($response, 2);
916
917            for ($i=0, $len=count($items); $i<$len; $i += 2) {
918                $result[$items[$i]] = (int) $items[$i+1];
919            }
920
921                        return $result;
922                }
923
924        return false;
925    }
926
927    function checkForRecent($mailbox)
928    {
929            if (empty($mailbox)) {
930                    $mailbox = 'INBOX';
931            }
932
933            $this->select($mailbox);
934            if ($this->selected == $mailbox) {
935                    return $this->data['RECENT'];
936            }
937
938            return false;
939    }
940
941    function countMessages($mailbox, $refresh = false)
942    {
943            if ($refresh) {
944                    $this->selected = '';
945            }
946
947            $this->select($mailbox);
948            if ($this->selected == $mailbox) {
949                    return $this->data['EXISTS'];
950            }
951
952        return false;
953    }
954
955    /**
956     * Returns count of messages without \Seen flag in a specified folder
957     *
958     * @param string $mailbox Mailbox name
959     *
960     * @return int Number of messages, False on error
961     * @access public
962     */
963    function countUnseen($mailbox)
964    {
965        // Try STATUS, should be faster
966        $counts = $this->status($mailbox, array('UNSEEN'));
967        if (is_array($counts)) {
968            return (int) $counts['UNSEEN'];
969        }
970
971        // Invoke SEARCH as a fallback
972        $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
973        if (is_array($index)) {
974            return (int) $index['COUNT'];
975        }
976
977        return false;
978    }
979
980    function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
981    {
982            $field = strtoupper($field);
983            if ($field == 'INTERNALDATE') {
984                $field = 'ARRIVAL';
985            }
986
987            $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
988            'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
989
990            if (!$fields[$field]) {
991                return false;
992            }
993
994            if (!$this->select($mailbox)) {
995                return false;
996            }
997
998            // message IDs
999            if (is_array($add))
1000                    $add = $this->compressMessageSet(join(',', $add));
1001
1002            list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1003                array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1004
1005            if ($code == self::ERROR_OK) {
1006                // remove prefix and \r\n from raw response
1007            $response = str_replace("\r\n", '', substr($response, 7));
1008                return preg_split('/\s+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1009            }
1010
1011        return false;
1012    }
1013
1014    function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1015    {
1016            if (is_array($message_set)) {
1017                    if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
1018                            return false;
1019            } else {
1020                    list($from_idx, $to_idx) = explode(':', $message_set);
1021                    if (empty($message_set) ||
1022                            (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1023                            return false;
1024                    }
1025            }
1026
1027            $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1028
1029        $fields_a['DATE']         = 1;
1030            $fields_a['INTERNALDATE'] = 4;
1031        $fields_a['ARRIVAL']      = 4;
1032            $fields_a['FROM']         = 1;
1033        $fields_a['REPLY-TO']     = 1;
1034            $fields_a['SENDER']       = 1;
1035        $fields_a['TO']           = 1;
1036            $fields_a['CC']           = 1;
1037        $fields_a['SUBJECT']      = 1;
1038            $fields_a['UID']          = 2;
1039        $fields_a['SIZE']         = 2;
1040            $fields_a['SEEN']         = 3;
1041        $fields_a['RECENT']       = 3;
1042            $fields_a['DELETED']      = 3;
1043
1044        if (!($mode = $fields_a[$index_field])) {
1045                return false;
1046            }
1047
1048        /*  Do "SELECT" command */
1049            if (!$this->select($mailbox)) {
1050                    return false;
1051            }
1052
1053        // build FETCH command string
1054            $key     = $this->next_tag();
1055            $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
1056            $deleted = $skip_deleted ? ' FLAGS' : '';
1057
1058            if ($mode == 1 && $index_field == 'DATE')
1059                    $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1060            else if ($mode == 1)
1061                    $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1062            else if ($mode == 2) {
1063                    if ($index_field == 'SIZE')
1064                            $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1065                    else
1066                            $request = " $cmd $message_set ($index_field$deleted)";
1067            } else if ($mode == 3)
1068                    $request = " $cmd $message_set (FLAGS)";
1069            else // 4
1070                    $request = " $cmd $message_set (INTERNALDATE$deleted)";
1071
1072            $request = $key . $request;
1073
1074            if (!$this->putLine($request)) {
1075            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1076                    return false;
1077        }
1078
1079            $result = array();
1080
1081            do {
1082                    $line = rtrim($this->readLine(200));
1083                    $line = $this->multLine($line);
1084
1085                    if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1086                $id     = $m[1];
1087                            $flags  = NULL;
1088
1089                            if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1090                                    $flags = explode(' ', strtoupper($matches[1]));
1091                                    if (in_array('\\DELETED', $flags)) {
1092                                            $deleted[$id] = $id;
1093                                            continue;
1094                                    }
1095                            }
1096
1097                            if ($mode == 1 && $index_field == 'DATE') {
1098                                    if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1099                                            $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1100                                            $value = trim($value);
1101                                            $result[$id] = $this->strToTime($value);
1102                                    }
1103                                    // non-existent/empty Date: header, use INTERNALDATE
1104                                    if (empty($result[$id])) {
1105                                            if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1106                                                    $result[$id] = $this->strToTime($matches[1]);
1107                                            else
1108                                                    $result[$id] = 0;
1109                                    }
1110                            } else if ($mode == 1) {
1111                                    if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1112                                            $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1113                                            $result[$id] = trim($value);
1114                                    } else {
1115                                            $result[$id] = '';
1116                                    }
1117                            } else if ($mode == 2) {
1118                                    if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1119                                            $result[$id] = trim($matches[2]);
1120                                    } else {
1121                                            $result[$id] = 0;
1122                                    }
1123                            } else if ($mode == 3) {
1124                                    if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1125                                            $flags = explode(' ', $matches[1]);
1126                                    }
1127                                    $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1128                            } else if ($mode == 4) {
1129                                    if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1130                                            $result[$id] = $this->strToTime($matches[1]);
1131                                    } else {
1132                                            $result[$id] = 0;
1133                                    }
1134                            }
1135                    }
1136            } while (!$this->startsWith($line, $key, true, true));
1137
1138            return $result;
1139    }
1140
1141    private function compressMessageSet($message_set, $force=false)
1142    {
1143            // given a comma delimited list of independent mid's,
1144            // compresses by grouping sequences together
1145
1146            // if less than 255 bytes long, let's not bother
1147            if (!$force && strlen($message_set)<255) {
1148                return $message_set;
1149            }
1150
1151            // see if it's already been compressed
1152            if (strpos($message_set, ':') !== false) {
1153                return $message_set;
1154            }
1155
1156            // separate, then sort
1157            $ids = explode(',', $message_set);
1158            sort($ids);
1159
1160            $result = array();
1161            $start  = $prev = $ids[0];
1162
1163            foreach ($ids as $id) {
1164                    $incr = $id - $prev;
1165                    if ($incr > 1) {                    //found a gap
1166                            if ($start == $prev) {
1167                                $result[] = $prev;      //push single id
1168                            } else {
1169                                $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
1170                            }
1171                        $start = $id;                   //start of new sequence
1172                    }
1173                    $prev = $id;
1174            }
1175
1176            // handle the last sequence/id
1177            if ($start==$prev) {
1178                $result[] = $prev;
1179            } else {
1180            $result[] = $start.':'.$prev;
1181            }
1182
1183            // return as comma separated string
1184            return implode(',', $result);
1185    }
1186
1187    function UID2ID($folder, $uid)
1188    {
1189            if ($uid > 0) {
1190                $id_a = $this->search($folder, "UID $uid");
1191                if (is_array($id_a) && count($id_a) == 1) {
1192                        return $id_a[0];
1193                    }
1194            }
1195            return false;
1196    }
1197
1198    function ID2UID($folder, $id)
1199    {
1200            if (empty($id)) {
1201                return  -1;
1202            }
1203
1204        if (!$this->select($folder)) {
1205            return -1;
1206        }
1207
1208            $result  = -1;
1209        list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1210
1211        if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1212                        $result = $m[1];
1213        }
1214
1215        return $result;
1216    }
1217
1218    function fetchUIDs($mailbox, $message_set=null)
1219    {
1220            if (is_array($message_set))
1221                    $message_set = join(',', $message_set);
1222        else if (empty($message_set))
1223                    $message_set = '1:*';
1224
1225            return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1226    }
1227
1228    function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1229    {
1230            $result = array();
1231
1232            if (!$this->select($mailbox)) {
1233                    return false;
1234            }
1235
1236            if (is_array($message_set))
1237                    $message_set = join(',', $message_set);
1238
1239            $message_set = $this->compressMessageSet($message_set);
1240
1241            if ($add)
1242                    $add = ' '.trim($add);
1243
1244            /* FETCH uid, size, flags and headers */
1245            $key          = $this->next_tag();
1246            $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1247            $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1248            if ($bodystr)
1249                    $request .= "BODYSTRUCTURE ";
1250            $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1251            $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1252
1253            if (!$this->putLine($request)) {
1254            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1255                    return false;
1256            }
1257            do {
1258                    $line = $this->readLine(1024);
1259                    $line = $this->multLine($line);
1260
1261            if (!$line)
1262                break;
1263
1264                    if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1265                            $id = intval($m[1]);
1266
1267                            $result[$id]            = new rcube_mail_header;
1268                            $result[$id]->id        = $id;
1269                            $result[$id]->subject   = '';
1270                            $result[$id]->messageID = 'mid:' . $id;
1271
1272                            $lines = array();
1273                            $ln = 0;
1274
1275                            // Sample reply line:
1276                            // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1277                            // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1278                            // BODY[HEADER.FIELDS ...
1279
1280                            if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1281                                    $str = $matches[1];
1282
1283                                    // swap parents with quotes, then explode
1284                                    $str = preg_replace('/[()]/', '"', $str);
1285                                    $a = rcube_explode_quoted_string(' ', $str);
1286
1287                                    // did we get the right number of replies?
1288                                    $parts_count = count($a);
1289                                    if ($parts_count>=6) {
1290                                            for ($i=0; $i<$parts_count; $i=$i+2) {
1291                                                    if ($a[$i] == 'UID')
1292                                                            $result[$id]->uid = intval($a[$i+1]);
1293                                                    else if ($a[$i] == 'RFC822.SIZE')
1294                                                            $result[$id]->size = intval($a[$i+1]);
1295                                                else if ($a[$i] == 'INTERNALDATE')
1296                                                        $time_str = $a[$i+1];
1297                                                else if ($a[$i] == 'FLAGS')
1298                                                        $flags_str = $a[$i+1];
1299                                        }
1300
1301                                            $time_str = str_replace('"', '', $time_str);
1302
1303                                            // if time is gmt...
1304                                $time_str = str_replace('GMT','+0000',$time_str);
1305
1306                                            $result[$id]->internaldate = $time_str;
1307                                        $result[$id]->timestamp = $this->StrToTime($time_str);
1308                                        $result[$id]->date = $time_str;
1309                                }
1310
1311                                // BODYSTRUCTURE
1312                                    if($bodystr) {
1313                                            while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1314                                                    $line2 = $this->readLine(1024);
1315                                                $line .= $this->multLine($line2, true);
1316                                        }
1317                                        $result[$id]->body_structure = $m[1];
1318                                }
1319
1320                                // the rest of the result
1321                                preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1322                                $reslines = explode("\n", trim($m[1], '"'));
1323                                // re-parse (see below)
1324                                    foreach ($reslines as $resln) {
1325                                        if (ord($resln[0])<=32) {
1326                                                $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1327                                        } else {
1328                                                $lines[++$ln] = trim($resln);
1329                                            }
1330                                }
1331                        }
1332
1333                                // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1334                                // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1335                                // process the previous line.  Otherwise, we'll keep adding the strings until we come
1336                                // to the next valid header line.
1337
1338                            do {
1339                                    $line = rtrim($this->readLine(300), "\r\n");
1340
1341                                // The preg_match below works around communigate imap, which outputs " UID <number>)".
1342                                // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1343                                // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1344                                // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1345                                    // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1346                                // An alternative might be:
1347                                // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1348                                // however, unsure how well this would work with all imap clients.
1349                                if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1350                                        break;
1351                                    }
1352
1353                                // handle FLAGS reply after headers (AOL, Zimbra?)
1354                                if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1355                                        $flags_str = $matches[1];
1356                                        break;
1357                                    }
1358
1359                                if (ord($line[0])<=32) {
1360                                        $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1361                                } else {
1362                                        $lines[++$ln] = trim($line);
1363                                    }
1364                        // patch from "Maksim Rubis" <siburny@hotmail.com>
1365                        } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1366
1367                        if (strncmp($line, $key, strlen($key))) {
1368                                // process header, fill rcube_mail_header obj.
1369                                // initialize
1370                                if (is_array($headers)) {
1371                                        reset($headers);
1372                                            while (list($k, $bar) = each($headers)) {
1373                                                $headers[$k] = '';
1374                                        }
1375                                }
1376
1377                                // create array with header field:data
1378                                while ( list($lines_key, $str) = each($lines) ) {
1379                                        list($field, $string) = $this->splitHeaderLine($str);
1380
1381                                        $field  = strtolower($field);
1382                                        $string = preg_replace('/\n\s*/', ' ', $string);
1383
1384                                        switch ($field) {
1385                                        case 'date';
1386                                                $result[$id]->date = $string;
1387                                                $result[$id]->timestamp = $this->strToTime($string);
1388                                        break;
1389                                        case 'from':
1390                                                $result[$id]->from = $string;
1391                                                break;
1392                                        case 'to':
1393                                                $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1394                                                break;
1395                                        case 'subject':
1396                                                $result[$id]->subject = $string;
1397                                                break;
1398                                        case 'reply-to':
1399                                                $result[$id]->replyto = $string;
1400                                                break;
1401                                        case 'cc':
1402                                                $result[$id]->cc = $string;
1403                                                break;
1404                                        case 'bcc':
1405                                                $result[$id]->bcc = $string;
1406                                                break;
1407                                        case 'content-transfer-encoding':
1408                                                $result[$id]->encoding = $string;
1409                                                break;
1410                                        case 'content-type':
1411                                                $ctype_parts = preg_split('/[; ]/', $string);
1412                                                $result[$id]->ctype = array_shift($ctype_parts);
1413                                                if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1414                                                        $result[$id]->charset = $regs[1];
1415                                                }
1416                                                break;
1417                                            case 'in-reply-to':
1418                                                $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1419                                                break;
1420                                        case 'references':
1421                                                $result[$id]->references = $string;
1422                                                break;
1423                                        case 'return-receipt-to':
1424                                        case 'disposition-notification-to':
1425                                            case 'x-confirm-reading-to':
1426                                                $result[$id]->mdn_to = $string;
1427                                                break;
1428                                        case 'message-id':
1429                                                $result[$id]->messageID = $string;
1430                                                break;
1431                                            case 'x-priority':
1432                                                if (preg_match('/^(\d+)/', $string, $matches))
1433                                                        $result[$id]->priority = intval($matches[1]);
1434                                                break;
1435                                        default:
1436                                                if (strlen($field) > 2)
1437                                                        $result[$id]->others[$field] = $string;
1438                                                    break;
1439                                        } // end switch ()
1440                                } // end while ()
1441                            }
1442
1443                        // process flags
1444                        if (!empty($flags_str)) {
1445                                $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1446                                $flags_a   = explode(' ', $flags_str);
1447
1448                                    if (is_array($flags_a)) {
1449                                        foreach($flags_a as $flag) {
1450                                                $flag = strtoupper($flag);
1451                                                if ($flag == 'SEEN') {
1452                                                    $result[$id]->seen = true;
1453                                                } else if ($flag == 'DELETED') {
1454                                                    $result[$id]->deleted = true;
1455                                                } else if ($flag == 'RECENT') {
1456                                                    $result[$id]->recent = true;
1457                                                } else if ($flag == 'ANSWERED') {
1458                                                        $result[$id]->answered = true;
1459                                                } else if ($flag == '$FORWARDED') {
1460                                                        $result[$id]->forwarded = true;
1461                                                } else if ($flag == 'DRAFT') {
1462                                                        $result[$id]->is_draft = true;
1463                                                } else if ($flag == '$MDNSENT') {
1464                                                        $result[$id]->mdn_sent = true;
1465                                                } else if ($flag == 'FLAGGED') {
1466                                                         $result[$id]->flagged = true;
1467                                                    }
1468                                        }
1469                                        $result[$id]->flags = $flags_a;
1470                                }
1471                            }
1472                }
1473            } while (!$this->startsWith($line, $key, true));
1474
1475        return $result;
1476    }
1477
1478    function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1479    {
1480            $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1481            if (is_array($a)) {
1482                    return array_shift($a);
1483            }
1484            return false;
1485    }
1486
1487    function sortHeaders($a, $field, $flag)
1488    {
1489            if (empty($field)) {
1490                $field = 'uid';
1491            }
1492        else {
1493            $field = strtolower($field);
1494        }
1495
1496            if ($field == 'date' || $field == 'internaldate') {
1497                $field = 'timestamp';
1498            }
1499        if (empty($flag)) {
1500                $flag = 'ASC';
1501            } else {
1502                $flag = strtoupper($flag);
1503        }
1504
1505            $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1506
1507            $c = count($a);
1508            if ($c > 0) {
1509
1510                        // Strategy:
1511                        // First, we'll create an "index" array.
1512                        // Then, we'll use sort() on that array,
1513                        // and use that to sort the main array.
1514
1515                    // create "index" array
1516                    $index = array();
1517                    reset($a);
1518                    while (list($key, $val) = each($a)) {
1519                            if ($field == 'timestamp') {
1520                                    $data = $this->strToTime($val->date);
1521                                    if (!$data) {
1522                                            $data = $val->timestamp;
1523                        }
1524                            } else {
1525                                    $data = $val->$field;
1526                                    if (is_string($data)) {
1527                                            $data = strtoupper(str_replace($stripArr, '', $data));
1528                        }
1529                            }
1530                        $index[$key]=$data;
1531                }
1532
1533                    // sort index
1534                $i = 0;
1535                if ($flag == 'ASC') {
1536                        asort($index);
1537                } else {
1538                    arsort($index);
1539                    }
1540
1541                // form new array based on index
1542                $result = array();
1543                    reset($index);
1544                while (list($key, $val) = each($index)) {
1545                        $result[$key]=$a[$key];
1546                        $i++;
1547                    }
1548            }
1549
1550            return $result;
1551    }
1552
1553    function expunge($mailbox, $messages=NULL)
1554    {
1555            if (!$this->select($mailbox)) {
1556            return false;
1557        }
1558
1559                $result = $this->execute($messages ? 'UID EXPUNGE' : 'EXPUNGE',
1560                    array($messages), self::COMMAND_NORESPONSE);
1561
1562                if ($result == self::ERROR_OK) {
1563                        $this->selected = ''; // state has changed, need to reselect
1564                        return true;
1565                }
1566
1567            return false;
1568    }
1569
1570    function modFlag($mailbox, $messages, $flag, $mod)
1571    {
1572            if ($mod != '+' && $mod != '-') {
1573                return -1;
1574            }
1575
1576            $flag = $this->flags[strtoupper($flag)];
1577
1578            if (!$this->select($mailbox)) {
1579                return -1;
1580            }
1581
1582        $c = 0;
1583        $key = $this->next_tag();
1584        $command = "$key UID STORE $messages {$mod}FLAGS ($flag)";
1585            if (!$this->putLine($command)) {
1586            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1587            return -1;
1588        }
1589
1590            do {
1591                    $line = $this->readLine();
1592                    if ($line[0] == '*') {
1593                        $c++;
1594            }
1595            } while (!$this->startsWith($line, $key, true, true));
1596
1597            if ($this->parseResult($line, 'STORE: ') == self::ERROR_OK) {
1598                    return $c;
1599            }
1600
1601            return -1;
1602    }
1603
1604    function flag($mailbox, $messages, $flag) {
1605            return $this->modFlag($mailbox, $messages, $flag, '+');
1606    }
1607
1608    function unflag($mailbox, $messages, $flag) {
1609            return $this->modFlag($mailbox, $messages, $flag, '-');
1610    }
1611
1612    function delete($mailbox, $messages) {
1613            return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1614    }
1615
1616    function copy($messages, $from, $to)
1617    {
1618            if (empty($from) || empty($to)) {
1619                return -1;
1620            }
1621
1622            if (!$this->select($from)) {
1623            return -1;
1624            }
1625
1626        $result = $this->execute('UID COPY', array($messages, $this->escape($to)),
1627            self::COMMAND_NORESPONSE);
1628
1629            return $result;
1630    }
1631
1632    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1633    // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1634    // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1635    private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1636    {
1637            $node = array();
1638            if ($str[$begin] != '(') {
1639                    $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1640                    $msg = substr($str, $begin, $stop - $begin);
1641                    if ($msg == 0)
1642                        return $node;
1643                    if (is_null($root))
1644                            $root = $msg;
1645                    $depthmap[$msg] = $depth;
1646                    $haschildren[$msg] = false;
1647                    if (!is_null($parent))
1648                            $haschildren[$parent] = true;
1649                    if ($stop + 1 < $end)
1650                            $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1651                    else
1652                            $node[$msg] = array();
1653            } else {
1654                    $off = $begin;
1655                    while ($off < $end) {
1656                            $start = $off;
1657                        $off++;
1658                        $n = 1;
1659                        while ($n > 0) {
1660                                $p = strpos($str, ')', $off);
1661                                    if ($p === false) {
1662                                            error_log('Mismatched brackets parsing IMAP THREAD response:');
1663                                        error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1664                                        error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1665                                        return $node;
1666                                }
1667                                    $p1 = strpos($str, '(', $off);
1668                                if ($p1 !== false && $p1 < $p) {
1669                                        $off = $p1 + 1;
1670                                        $n++;
1671                                } else {
1672                                        $off = $p + 1;
1673                                            $n--;
1674                                }
1675                        }
1676                        $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1677                    }
1678            }
1679
1680            return $node;
1681    }
1682
1683    function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1684    {
1685        $old_sel = $this->selected;
1686
1687            if (!$this->select($folder)) {
1688                return false;
1689            }
1690
1691        // return empty result when folder is empty and we're just after SELECT
1692        if ($old_sel != $folder && !$this->data['EXISTS']) {
1693            return array(array(), array(), array());
1694            }
1695
1696        $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1697            $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1698            $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1699        $data      = '';
1700
1701        list($code, $response) = $this->execute('THREAD', array(
1702            $algorithm, $encoding, $criteria));
1703
1704            if ($code == self::ERROR_OK && preg_match('/^\* THREAD /i', $response)) {
1705                // remove prefix and \r\n from raw response
1706                $response    = str_replace("\r\n", '', substr($response, 9));
1707            $depthmap    = array();
1708            $haschildren = array();
1709
1710            $tree = $this->parseThread($response, 0, strlen($response),
1711                null, null, 0, $depthmap, $haschildren);
1712
1713            return array($tree, $depthmap, $haschildren);
1714            }
1715
1716            return false;
1717    }
1718
1719    /**
1720     * Executes SEARCH command
1721     *
1722     * @param string $mailbox    Mailbox name
1723     * @param string $criteria   Searching criteria
1724     * @param bool   $return_uid Enable UID in result instead of sequence ID
1725     * @param array  $items      Return items (MIN, MAX, COUNT, ALL)
1726     *
1727     * @return array Message identifiers or item-value hash
1728     */
1729    function search($mailbox, $criteria, $return_uid=false, $items=array())
1730    {
1731        $old_sel = $this->selected;
1732
1733            if (!$this->select($mailbox)) {
1734                return false;
1735            }
1736
1737        // return empty result when folder is empty and we're just after SELECT
1738        if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1739            if (!empty($items))
1740                return array_combine($items, array_fill(0, count($items), 0));
1741            else
1742                return array();
1743            }
1744
1745        $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
1746        $criteria = trim($criteria);
1747        $params   = '';
1748
1749        // RFC4731: ESEARCH
1750        if (!empty($items) && $esearch) {
1751            $params .= 'RETURN (' . implode(' ', $items) . ')';
1752        }
1753        if (!empty($criteria)) {
1754            $params .= ($params ? ' ' : '') . $criteria;
1755        }
1756        else {
1757            $params .= 'ALL';
1758        }
1759
1760            list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
1761                array($params));
1762
1763            if ($code == self::ERROR_OK) {
1764                // remove prefix and \r\n from raw response
1765            $response = substr($response, $esearch ? 10 : 9);
1766                $response = str_replace("\r\n", '', $response);
1767
1768            if ($esearch) {
1769                // Skip prefix: ... (TAG "A285") UID ...     
1770                $this->tokenizeResponse($response, $return_uid ? 2 : 1);
1771
1772                $result = array();
1773                for ($i=0; $i<count($items); $i++) {
1774                    // If the SEARCH results in no matches, the server MUST NOT
1775                    // include the item result option in the ESEARCH response
1776                    if ($ret = $this->tokenizeResponse($response, 2)) {
1777                        list ($name, $value) = $ret;
1778                        $result[$name] = $value;
1779                    }
1780                }
1781
1782                return $result;
1783            }
1784                else {
1785                $response = preg_split('/\s+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1786
1787                if (!empty($items)) {
1788                    $result = array();
1789                    if (in_array('COUNT', $items))
1790                        $result['COUNT'] = count($response);
1791                    if (in_array('MIN', $items))
1792                        $result['MIN'] = !empty($response) ? min($response) : 0;
1793                    if (in_array('MAX', $items))
1794                        $result['MAX'] = !empty($response) ? max($response) : 0;
1795                    if (in_array('ALL', $items))
1796                        $result['ALL'] = $this->compressMessageSet(implode(',', $response), true);
1797
1798                    return $result;                   
1799                }
1800                else {
1801                    return $response;
1802                }
1803                }
1804        }
1805
1806            return false;
1807    }
1808
1809    function move($messages, $from, $to)
1810    {
1811        if (!$from || !$to) {
1812            return -1;
1813        }
1814
1815        $r = $this->copy($messages, $from, $to);
1816
1817        if ($r==0) {
1818            return $this->delete($from, $messages);
1819        }
1820        return $r;
1821    }
1822
1823    /**
1824     * Returns list of mailboxes
1825     *
1826     * @param string $ref         Reference name
1827     * @param string $mailbox     Mailbox name
1828     * @param array  $status_opts (see self::_listMailboxes)
1829     *
1830     * @return array List of mailboxes or hash of options if $status_opts argument
1831     *               is non-empty.
1832     * @access public
1833     */
1834    function listMailboxes($ref, $mailbox, $status_opts=array())
1835    {
1836        return $this->_listMailboxes($ref, $mailbox, false, $status_opts);
1837    }
1838
1839    /**
1840     * Returns list of subscribed mailboxes
1841     *
1842     * @param string $ref         Reference name
1843     * @param string $mailbox     Mailbox name
1844     * @param array  $status_opts (see self::_listMailboxes)
1845     *
1846     * @return array List of mailboxes or hash of options if $status_ops argument
1847     *               is non-empty.
1848     * @access public
1849     */
1850    function listSubscribed($ref, $mailbox, $status_opts=array())
1851    {
1852        return $this->_listMailboxes($ref, $mailbox, true, $status_opts);
1853    }
1854
1855    /**
1856     * IMAP LIST/LSUB command
1857     *
1858     * @param string $ref         Reference name
1859     * @param string $mailbox     Mailbox name
1860     * @param bool   $subscribed  Enables returning subscribed mailboxes only
1861     * @param array  $status_opts List of STATUS options (RFC5819: LIST-STATUS)
1862     *                            Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
1863     *
1864     * @return array List of mailboxes or hash of options if $status_ops argument
1865     *               is non-empty.
1866     * @access private
1867     */
1868    private function _listMailboxes($ref, $mailbox, $subscribed=false, $status_opts=array())
1869    {
1870                if (empty($mailbox)) {
1871                $mailbox = '*';
1872            }
1873
1874            if (empty($ref) && $this->prefs['rootdir']) {
1875                $ref = $this->prefs['rootdir'];
1876            }
1877
1878        $args = array($this->escape($ref), $this->escape($mailbox));
1879
1880        if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
1881            $status_opts = array($status_opts);
1882            $lstatus = true;
1883
1884            $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
1885        }
1886
1887        list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
1888
1889        if ($code == self::ERROR_OK) {
1890            $folders = array();
1891            while ($this->tokenizeResponse($response, 1) == '*') {
1892                $cmd = strtoupper($this->tokenizeResponse($response, 1));
1893                // * LIST (<options>) <delimiter> <mailbox>
1894                if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
1895                    list($opts, $delim, $folder) = $this->tokenizeResponse($response, 3);
1896
1897                    if (!$lstatus) {
1898                                    $folders[] = $folder;
1899                    }
1900                    else {
1901                        $folders[$folder] = array();
1902                    }
1903
1904                    if ($cmd == 'LIST') {
1905                        $this->data['LIST'][$folder] = $opts;
1906                    }
1907                }
1908                // * STATUS <mailbox> (<result>)
1909                else if ($cmd == 'STATUS') {
1910                    list($folder, $status) = $this->tokenizeResponse($response, 2);
1911
1912                    for ($i=0, $len=count($status); $i<$len; $i += 2) {
1913                        list($name, $value) = $this->tokenizeResponse($status, 2);
1914                        $folders[$folder][$name] = $value;
1915                    }
1916                }
1917                    }
1918
1919            return $folders;
1920        }
1921
1922        return false;
1923    }
1924
1925    function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
1926    {
1927            if (!$this->select($mailbox)) {
1928                    return false;
1929            }
1930
1931        $result = false;
1932            $parts  = (array) $parts;
1933        $key    = $this->next_tag();
1934            $peeks  = '';
1935        $idx    = 0;
1936        $type   = $mime ? 'MIME' : 'HEADER';
1937
1938            // format request
1939            foreach($parts as $part)
1940                    $peeks[] = "BODY.PEEK[$part.$type]";
1941
1942            $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
1943
1944            // send request
1945            if (!$this->putLine($request)) {
1946            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1947                return false;
1948            }
1949
1950            do {
1951                $line = $this->readLine(1024);
1952                $line = $this->multLine($line);
1953
1954                    if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
1955                            $idx = $matches[1];
1956                        $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
1957                        $result[$idx] = trim($result[$idx], '"');
1958                        $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
1959                }
1960            } while (!$this->startsWith($line, $key, true));
1961
1962            return $result;
1963    }
1964
1965    function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
1966    {
1967            $part = empty($part) ? 'HEADER' : $part.'.MIME';
1968
1969        return $this->handlePartBody($mailbox, $id, $is_uid, $part);
1970    }
1971
1972    function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
1973    {
1974        if (!$this->select($mailbox)) {
1975            return false;
1976        }
1977
1978            switch ($encoding) {
1979                    case 'base64':
1980                            $mode = 1;
1981                break;
1982                case 'quoted-printable':
1983                        $mode = 2;
1984                break;
1985                case 'x-uuencode':
1986                    case 'x-uue':
1987                case 'uue':
1988                case 'uuencode':
1989                        $mode = 3;
1990                break;
1991                default:
1992                        $mode = 0;
1993            }
1994
1995        // format request
1996                $reply_key = '* ' . $id;
1997                $key       = $this->next_tag();
1998                $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
1999
2000        // send request
2001                if (!$this->putLine($request)) {
2002            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
2003                    return false;
2004                }
2005
2006                // receive reply line
2007                do {
2008                $line = rtrim($this->readLine(1024));
2009                $a    = explode(' ', $line);
2010                } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2011
2012                $len    = strlen($line);
2013        $result = false;
2014
2015                // handle empty "* X FETCH ()" response
2016        if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2017                // one line response, get everything between first and last quotes
2018                        if (substr($line, -4, 3) == 'NIL') {
2019                                // NIL response
2020                                $result = '';
2021                        } else {
2022                            $from = strpos($line, '"') + 1;
2023                        $to   = strrpos($line, '"');
2024                        $len  = $to - $from;
2025                                $result = substr($line, $from, $len);
2026                        }
2027
2028                if ($mode == 1)
2029                                $result = base64_decode($result);
2030                        else if ($mode == 2)
2031                                $result = quoted_printable_decode($result);
2032                        else if ($mode == 3)
2033                                $result = convert_uudecode($result);
2034
2035        } else if ($line[$len-1] == '}') {
2036                // multi-line request, find sizes of content and receive that many bytes
2037                $from     = strpos($line, '{') + 1;
2038                $to       = strrpos($line, '}');
2039                $len      = $to - $from;
2040                $sizeStr  = substr($line, $from, $len);
2041                $bytes    = (int)$sizeStr;
2042                        $prev     = '';
2043
2044                while ($bytes > 0) {
2045                    $line = $this->readLine(4096);
2046
2047                    if ($line === NULL)
2048                        break;
2049
2050                $len  = strlen($line);
2051
2052                        if ($len > $bytes) {
2053                        $line = substr($line, 0, $bytes);
2054                                        $len = strlen($line);
2055                        }
2056                $bytes -= $len;
2057
2058                        if ($mode == 1) {
2059                                        $line = rtrim($line, "\t\r\n\0\x0B");
2060                                        // create chunks with proper length for base64 decoding
2061                                        $line = $prev.$line;
2062                                        $length = strlen($line);
2063                                        if ($length % 4) {
2064                                                $length = floor($length / 4) * 4;
2065                                                $prev = substr($line, $length);
2066                                                $line = substr($line, 0, $length);
2067                                        }
2068                                        else
2069                                                $prev = '';
2070
2071                                        if ($file)
2072                                                fwrite($file, base64_decode($line));
2073                        else if ($print)
2074                                                echo base64_decode($line);
2075                                        else
2076                                                $result .= base64_decode($line);
2077                                } else if ($mode == 2) {
2078                                        $line = rtrim($line, "\t\r\0\x0B");
2079                                        if ($file)
2080                                                fwrite($file, quoted_printable_decode($line));
2081                        else if ($print)
2082                                                echo quoted_printable_decode($line);
2083                                        else
2084                                                $result .= quoted_printable_decode($line);
2085                                } else if ($mode == 3) {
2086                                        $line = rtrim($line, "\t\r\n\0\x0B");
2087                                        if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2088                                                continue;
2089                                        if ($file)
2090                                                fwrite($file, convert_uudecode($line));
2091                        else if ($print)
2092                                                echo convert_uudecode($line);
2093                                        else
2094                                                $result .= convert_uudecode($line);
2095                                } else {
2096                                        $line = rtrim($line, "\t\r\n\0\x0B");
2097                                        if ($file)
2098                                                fwrite($file, $line . "\n");
2099                        else if ($print)
2100                                                echo $line . "\n";
2101                                        else
2102                                                $result .= $line . "\n";
2103                                }
2104                }
2105        }
2106
2107        // read in anything up until last line
2108                if (!$end)
2109                        do {
2110                                $line = $this->readLine(1024);
2111                        } while (!$this->startsWith($line, $key, true));
2112
2113                if ($result !== false) {
2114                if ($file) {
2115                        fwrite($file, $result);
2116                        } else if ($print) {
2117                        echo $result;
2118                } else
2119                        return $result;
2120                        return true;
2121                }
2122
2123            return false;
2124    }
2125
2126    function createFolder($folder)
2127    {
2128        $result = $this->execute('CREATE', array($this->escape($folder)),
2129                self::COMMAND_NORESPONSE);
2130
2131            return ($result == self::ERROR_OK);
2132    }
2133
2134    function renameFolder($from, $to)
2135    {
2136        $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2137                self::COMMAND_NORESPONSE);
2138
2139                return ($result == self::ERROR_OK);
2140    }
2141
2142    function deleteFolder($folder)
2143    {
2144        $result = $this->execute('DELETE', array($this->escape($folder)),
2145                self::COMMAND_NORESPONSE);
2146
2147            return ($result == self::ERROR_OK);
2148    }
2149
2150    function clearFolder($folder)
2151    {
2152            $num_in_trash = $this->countMessages($folder);
2153            if ($num_in_trash > 0) {
2154                    $this->delete($folder, '1:*');
2155            }
2156            return ($this->expunge($folder) >= 0);
2157    }
2158
2159    function subscribe($folder)
2160    {
2161            $result = $this->execute('SUBSCRIBE', array($this->escape($folder)),
2162                self::COMMAND_NORESPONSE);
2163
2164            return ($result == self::ERROR_OK);
2165    }
2166
2167    function unsubscribe($folder)
2168    {
2169            $result = $this->execute('UNSUBSCRIBE', array($this->escape($folder)),
2170                self::COMMAND_NORESPONSE);
2171
2172            return ($result == self::ERROR_OK);
2173    }
2174
2175    function append($folder, &$message)
2176    {
2177            if (!$folder) {
2178                    return false;
2179            }
2180
2181        $message = str_replace("\r", '', $message);
2182            $message = str_replace("\n", "\r\n", $message);
2183
2184        $len = strlen($message);
2185            if (!$len) {
2186                    return false;
2187            }
2188
2189        $key = $this->next_tag();
2190            $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($folder),
2191            $len, ($this->prefs['literal+'] ? '+' : ''));
2192
2193            if ($this->putLine($request)) {
2194            // Don't wait when LITERAL+ is supported
2195            if (!$this->prefs['literal+']) {
2196                $line = $this->readLine(512);
2197
2198                    if ($line[0] != '+') {
2199                            $this->parseResult($line, 'APPEND: ');
2200                                return false;
2201                    }
2202            }
2203
2204                if (!$this->putLine($message)) {
2205                return false;
2206            }
2207
2208                    do {
2209                            $line = $this->readLine();
2210                } while (!$this->startsWith($line, $key, true, true));
2211
2212                return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2213            }
2214        else {
2215            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
2216        }
2217
2218            return false;
2219    }
2220
2221    function appendFromFile($folder, $path, $headers=null)
2222    {
2223            if (!$folder) {
2224                return false;
2225            }
2226
2227            // open message file
2228            $in_fp = false;
2229            if (file_exists(realpath($path))) {
2230                    $in_fp = fopen($path, 'r');
2231            }
2232            if (!$in_fp) {
2233                    $this->set_error(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2234                    return false;
2235            }
2236
2237        $body_separator = "\r\n\r\n";
2238            $len = filesize($path);
2239
2240            if (!$len) {
2241                    return false;
2242            }
2243
2244        if ($headers) {
2245            $headers = preg_replace('/[\r\n]+$/', '', $headers);
2246            $len += strlen($headers) + strlen($body_separator);
2247        }
2248
2249        // send APPEND command
2250        $key = $this->next_tag();
2251            $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($folder),
2252            $len, ($this->prefs['literal+'] ? '+' : ''));
2253
2254            if ($this->putLine($request)) {
2255            // Don't wait when LITERAL+ is supported
2256            if (!$this->prefs['literal+']) {
2257                    $line = $this->readLine(512);
2258
2259                    if ($line[0] != '+') {
2260                            $this->parseResult($line, 'APPEND: ');
2261                                return false;
2262                        }
2263            }
2264
2265            // send headers with body separator
2266            if ($headers) {
2267                            $this->putLine($headers . $body_separator, false);
2268            }
2269
2270                    // send file
2271                    while (!feof($in_fp) && $this->fp) {
2272                            $buffer = fgets($in_fp, 4096);
2273                            $this->putLine($buffer, false);
2274                    }
2275                    fclose($in_fp);
2276
2277                    if (!$this->putLine('')) { // \r\n
2278                return false;
2279            }
2280
2281                    // read response
2282                    do {
2283                            $line = $this->readLine();
2284                    } while (!$this->startsWith($line, $key, true, true));
2285
2286
2287                    return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2288            }
2289        else {
2290            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
2291        }
2292
2293            return false;
2294    }
2295
2296    function fetchStructureString($folder, $id, $is_uid=false)
2297    {
2298            if (!$this->select($folder)) {
2299            return false;
2300        }
2301
2302                $key = $this->next_tag();
2303        $result = false;
2304        $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2305
2306                if ($this->putLine($command)) {
2307                        do {
2308                                $line = $this->readLine(5000);
2309                                $line = $this->multLine($line, true);
2310                                if (!preg_match("/^$key /", $line))
2311                                        $result .= $line;
2312                        } while (!$this->startsWith($line, $key, true, true));
2313
2314                        $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2315                }
2316        else {
2317            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
2318        }
2319
2320        return $result;
2321    }
2322
2323    function getQuota()
2324    {
2325        /*
2326         * GETQUOTAROOT "INBOX"
2327         * QUOTAROOT INBOX user/rchijiiwa1
2328         * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2329         * OK Completed
2330         */
2331            $result      = false;
2332            $quota_lines = array();
2333            $key         = $this->next_tag();
2334        $command     = $key . ' GETQUOTAROOT INBOX';
2335
2336            // get line(s) containing quota info
2337            if ($this->putLine($command)) {
2338                    do {
2339                            $line = rtrim($this->readLine(5000));
2340                            if (preg_match('/^\* QUOTA /', $line)) {
2341                                    $quota_lines[] = $line;
2342                        }
2343                    } while (!$this->startsWith($line, $key, true, true));
2344            }
2345        else {
2346            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
2347        }
2348
2349            // return false if not found, parse if found
2350            $min_free = PHP_INT_MAX;
2351            foreach ($quota_lines as $key => $quota_line) {
2352                    $quota_line   = str_replace(array('(', ')'), '', $quota_line);
2353                    $parts        = explode(' ', $quota_line);
2354                    $storage_part = array_search('STORAGE', $parts);
2355
2356                    if (!$storage_part)
2357                continue;
2358
2359                    $used  = intval($parts[$storage_part+1]);
2360                    $total = intval($parts[$storage_part+2]);
2361                    $free  = $total - $used;
2362
2363                    // return lowest available space from all quotas
2364                    if ($free < $min_free) {
2365                        $min_free          = $free;
2366                            $result['used']    = $used;
2367                            $result['total']   = $total;
2368                            $result['percent'] = min(100, round(($used/max(1,$total))*100));
2369                            $result['free']    = 100 - $result['percent'];
2370                    }
2371            }
2372
2373            return $result;
2374    }
2375
2376    /**
2377     * Send the SETACL command (RFC4314)
2378     *
2379     * @param string $mailbox Mailbox name
2380     * @param string $user    User name
2381     * @param mixed  $acl     ACL string or array
2382     *
2383     * @return boolean True on success, False on failure
2384     *
2385     * @access public
2386     * @since 0.5-beta
2387     */
2388    function setACL($mailbox, $user, $acl)
2389    {
2390        if (is_array($acl)) {
2391            $acl = implode('', $acl);
2392        }
2393
2394        $result = $this->execute('SETACL', array(
2395            $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2396            self::COMMAND_NORESPONSE);
2397
2398            return ($result == self::ERROR_OK);
2399    }
2400
2401    /**
2402     * Send the DELETEACL command (RFC4314)
2403     *
2404     * @param string $mailbox Mailbox name
2405     * @param string $user    User name
2406     *
2407     * @return boolean True on success, False on failure
2408     *
2409     * @access public
2410     * @since 0.5-beta
2411     */
2412    function deleteACL($mailbox, $user)
2413    {
2414        $result = $this->execute('DELETEACL', array(
2415            $this->escape($mailbox), $this->escape($user)),
2416            self::COMMAND_NORESPONSE);
2417
2418            return ($result == self::ERROR_OK);
2419    }
2420
2421    /**
2422     * Send the GETACL command (RFC4314)
2423     *
2424     * @param string $mailbox Mailbox name
2425     *
2426     * @return array User-rights array on success, NULL on error
2427     * @access public
2428     * @since 0.5-beta
2429     */
2430    function getACL($mailbox)
2431    {
2432        list($code, $response) = $this->execute('GETACL', $this->escape($mailbox));
2433
2434        if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2435            // Parse server response (remove "* ACL ")
2436            $response = substr($response, 6);
2437            $ret  = $this->tokenizeResponse($response);
2438            $mbox = array_unshift($ret);
2439            $size = count($ret);
2440
2441            // Create user-rights hash array
2442            // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2443            // so we could return only standard rights defined in RFC4314,
2444            // excluding 'c' and 'd' defined in RFC2086.
2445            if ($size % 2 == 0) {
2446                for ($i=0; $i<$size; $i++) {
2447                    $ret[$ret[$i]] = str_split($ret[++$i]);
2448                    unset($ret[$i-1]);
2449                    unset($ret[$i]);
2450                }
2451                return $ret;
2452            }
2453
2454            $this->set_error(self::ERROR_COMMAND, "Incomplete ACL response");
2455            return NULL;
2456        }
2457
2458        return NULL;
2459    }
2460
2461    /**
2462     * Send the LISTRIGHTS command (RFC4314)
2463     *
2464     * @param string $mailbox Mailbox name
2465     * @param string $user    User name
2466     *
2467     * @return array List of user rights
2468     * @access public
2469     * @since 0.5-beta
2470     */
2471    function listRights($mailbox, $user)
2472    {
2473        list($code, $response) = $this->execute('LISTRIGHTS', array(
2474            $this->escape($mailbox), $this->escape($user)));
2475
2476        if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2477            // Parse server response (remove "* LISTRIGHTS ")
2478            $response = substr($response, 13);
2479
2480            $ret_mbox = $this->tokenizeResponse($response, 1);
2481            $ret_user = $this->tokenizeResponse($response, 1);
2482            $granted  = $this->tokenizeResponse($response, 1);
2483            $optional = trim($response);
2484
2485            return array(
2486                'granted'  => str_split($granted),
2487                'optional' => explode(' ', $optional),
2488            );
2489        }
2490
2491        return NULL;
2492    }
2493
2494    /**
2495     * Send the MYRIGHTS command (RFC4314)
2496     *
2497     * @param string $mailbox Mailbox name
2498     *
2499     * @return array MYRIGHTS response on success, NULL on error
2500     * @access public
2501     * @since 0.5-beta
2502     */
2503    function myRights($mailbox)
2504    {
2505        list($code, $response) = $this->execute('MYRIGHTS', array($this->escape(mailbox)));
2506
2507        if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2508            // Parse server response (remove "* MYRIGHTS ")
2509            $response = substr($response, 11);
2510
2511            $ret_mbox = $this->tokenizeResponse($response, 1);
2512            $rights   = $this->tokenizeResponse($response, 1);
2513
2514            return str_split($rights);
2515        }
2516
2517        return NULL;
2518    }
2519
2520    /**
2521     * Send the SETMETADATA command (RFC5464)
2522     *
2523     * @param string $mailbox Mailbox name
2524     * @param array  $entries Entry-value array (use NULL value as NIL)
2525     *
2526     * @return boolean True on success, False on failure
2527     * @access public
2528     * @since 0.5-beta
2529     */
2530    function setMetadata($mailbox, $entries)
2531    {
2532        if (!is_array($entries) || empty($entries)) {
2533            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2534            return false;
2535        }
2536
2537        foreach ($entries as $name => $value) {
2538            if ($value === null)
2539                $value = 'NIL';
2540            else
2541                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2542
2543            $entries[$name] = $this->escape($name) . ' ' . $value;
2544        }
2545
2546        $entries = implode(' ', $entries);
2547        $result = $this->execute('SETMETADATA', array(
2548            $this->escape($mailbox), '(' . $entries . ')'),
2549            self::COMMAND_NORESPONSE);
2550
2551        return ($result == self::ERROR_OK);
2552    }
2553
2554    /**
2555     * Send the SETMETADATA command with NIL values (RFC5464)
2556     *
2557     * @param string $mailbox Mailbox name
2558     * @param array  $entries Entry names array
2559     *
2560     * @return boolean True on success, False on failure
2561     *
2562     * @access public
2563     * @since 0.5-beta
2564     */
2565    function deleteMetadata($mailbox, $entries)
2566    {
2567        if (!is_array($entries) && !empty($entries))
2568            $entries = explode(' ', $entries);
2569
2570        if (empty($entries)) {
2571            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2572            return false;
2573        }
2574
2575        foreach ($entries as $entry)
2576            $data[$entry] = NULL;
2577
2578        return $this->setMetadata($mailbox, $data);
2579    }
2580
2581    /**
2582     * Send the GETMETADATA command (RFC5464)
2583     *
2584     * @param string $mailbox Mailbox name
2585     * @param array  $entries Entries
2586     * @param array  $options Command options (with MAXSIZE and DEPTH keys)
2587     *
2588     * @return array GETMETADATA result on success, NULL on error
2589     *
2590     * @access public
2591     * @since 0.5-beta
2592     */
2593    function getMetadata($mailbox, $entries, $options=array())
2594    {
2595        if (!is_array($entries)) {
2596            $entries = array($entries);
2597        }
2598
2599        // create entries string
2600        foreach ($entries as $idx => $name) {
2601            $entries[$idx] = $this->escape($name);
2602        }
2603
2604        $optlist = '';
2605        $entlist = '(' . implode(' ', $entries) . ')';
2606
2607        // create options string
2608        if (is_array($options)) {
2609            $options = array_change_key_case($options, CASE_UPPER);
2610            $opts = array();
2611
2612            if (!empty($options['MAXSIZE']))
2613                $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2614            if (!empty($options['DEPTH']))
2615                $opts[] = 'DEPTH '.intval($options['DEPTH']);
2616
2617            if ($opts)
2618                $optlist = '(' . implode(' ', $opts) . ')';
2619        }
2620
2621        $optlist .= ($optlist ? ' ' : '') . $entlist;
2622
2623        list($code, $response) = $this->execute('GETMETADATA', array(
2624            $this->escape($mailbox), $optlist));
2625
2626        if ($code == self::ERROR_OK && preg_match('/^\* METADATA /i', $response)) {
2627            // Parse server response (remove "* METADATA ")
2628            $response = substr($response, 11);
2629            $ret_mbox = $this->tokenizeResponse($response, 1);
2630            $data     = $this->tokenizeResponse($response);
2631
2632            // The METADATA response can contain multiple entries in a single
2633            // response or multiple responses for each entry or group of entries
2634            if (!empty($data) && ($size = count($data))) {
2635                for ($i=0; $i<$size; $i++) {
2636                    if (is_array($data[$i])) {
2637                        $size_sub = count($data[$i]);
2638                        for ($x=0; $x<$size_sub; $x++) {
2639                            $data[$data[$i][$x]] = $data[$i][++$x];
2640                        }
2641                        unset($data[$i]);
2642                    }
2643                    else if ($data[$i] == '*' && $data[$i+1] == 'METADATA') {
2644                        unset($data[$i]);   // "*"
2645                        unset($data[++$i]); // "METADATA"
2646                        unset($data[++$i]); // Mailbox
2647                    }
2648                    else {
2649                        $data[$data[$i]] = $data[++$i];
2650                        unset($data[$i]);
2651                        unset($data[$i-1]);
2652                    }
2653                }
2654            }
2655
2656            return $data;
2657        }
2658
2659        return NULL;
2660    }
2661
2662    /**
2663     * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
2664     *
2665     * @param string $mailbox Mailbox name
2666     * @param array  $data    Data array where each item is an array with
2667     *                        three elements: entry name, attribute name, value
2668     *
2669     * @return boolean True on success, False on failure
2670     * @access public
2671     * @since 0.5-beta
2672     */
2673    function setAnnotation($mailbox, $data)
2674    {
2675        if (!is_array($data) || empty($data)) {
2676            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2677            return false;
2678        }
2679
2680        foreach ($data as $entry) {
2681            $name  = $entry[0];
2682            $attr  = $entry[1];
2683            $value = $entry[2];
2684
2685            if ($value === null)
2686                $value = 'NIL';
2687            else
2688                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2689
2690            $entries[] = sprintf('%s (%s %s)',
2691                $this->escape($name), $this->escape($attr), $value);
2692        }
2693
2694        $entries = implode(' ', $entries);
2695        $result  = $this->execute('SETANNOTATION', array(
2696            $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
2697
2698        return ($result == self::ERROR_OK);
2699    }
2700
2701    /**
2702     * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
2703     *
2704     * @param string $mailbox Mailbox name
2705     * @param array  $data    Data array where each item is an array with
2706     *                        two elements: entry name and attribute name
2707     *
2708     * @return boolean True on success, False on failure
2709     *
2710     * @access public
2711     * @since 0.5-beta
2712     */
2713    function deleteAnnotation($mailbox, $data)
2714    {
2715        if (!is_array($data) || empty($data)) {
2716            $this->set_error(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2717            return false;
2718        }
2719
2720        return $this->setAnnotation($mailbox, $data);
2721    }
2722
2723    /**
2724     * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
2725     *
2726     * @param string $mailbox Mailbox name
2727     * @param array  $entries Entries names
2728     * @param array  $attribs Attribs names
2729     *
2730     * @return array Annotations result on success, NULL on error
2731     *
2732     * @access public
2733     * @since 0.5-beta
2734     */
2735    function getAnnotation($mailbox, $entries, $attribs)
2736    {
2737        if (!is_array($entries)) {
2738            $entries = array($entries);
2739        }
2740        // create entries string
2741        foreach ($entries as $idx => $name) {
2742            $entries[$idx] = $this->escape($name);
2743        }
2744        $entries = '(' . implode(' ', $entries) . ')';
2745
2746        if (!is_array($attribs)) {
2747            $attribs = array($attribs);
2748        }
2749        // create entries string
2750        foreach ($attribs as $idx => $name) {
2751            $attribs[$idx] = $this->escape($name);
2752        }
2753        $attribs = '(' . implode(' ', $attribs) . ')';
2754
2755        list($code, $response) = $this->execute('GETANNOTATION', array(
2756            $this->escape($mailbox), $entries, $attribs));
2757
2758        if ($code == self::ERROR_OK && preg_match('/^\* ANNOTATION /i', $response)) {
2759            // Parse server response (remove "* ANNOTATION ")
2760            $response = substr($response, 13);
2761            $ret_mbox = $this->tokenizeResponse($response, 1);
2762            $data     = $this->tokenizeResponse($response);
2763            $res      = array();
2764
2765            // Here we returns only data compatible with METADATA result format
2766            if (!empty($data) && ($size = count($data))) {
2767                for ($i=0; $i<$size; $i++) {
2768                    $entry = $data[$i++];
2769                    if (is_array($entry)) {
2770                        $attribs = $entry;
2771                        $entry   = $last_entry;
2772                    }
2773                    else
2774                        $attribs = $data[$i++];
2775
2776                    if (!empty($attribs)) {
2777                        for ($x=0, $len=count($attribs); $x<$len;) {
2778                            $attr  = $attribs[$x++];
2779                            $value = $attribs[$x++];
2780                            if ($attr == 'value.priv')
2781                                $res['/private' . $entry] = $value;
2782                            else if ($attr == 'value.shared')
2783                                $res['/shared' . $entry] = $value;
2784                        }
2785                    }
2786                    $last_entry = $entry;
2787                    unset($data[$i-1]);
2788                    unset($data[$i-2]);
2789                }
2790            }
2791
2792            return $res;
2793        }
2794
2795        return NULL;
2796    }
2797
2798    /**
2799     * Creates next command identifier (tag)
2800     *
2801     * @return string Command identifier
2802     * @access public
2803     * @since 0.5-beta
2804     */
2805    function next_tag()
2806    {
2807        $this->cmd_num++;
2808        $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
2809
2810        return $this->cmd_tag;
2811    }
2812
2813    /**
2814     * Sends IMAP command and parses result
2815     *
2816     * @param string $command   IMAP command
2817     * @param array  $arguments Command arguments
2818     * @param int    $options   Execution options
2819     *
2820     * @return mixed Response code or list of response code and data
2821     * @access public
2822     * @since 0.5-beta
2823     */
2824    function execute($command, $arguments=array(), $options=0)
2825    {
2826        $tag      = $this->next_tag();
2827        $query    = $tag . ' ' . $command;
2828        $noresp   = ($options & self::COMMAND_NORESPONSE);
2829        $response = $noresp ? null : '';
2830
2831        if (!empty($arguments))
2832            $query .= ' ' . implode(' ', $arguments);
2833
2834        // Send command
2835            if (!$this->putLineC($query)) {
2836            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $query");
2837                    return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
2838            }
2839
2840        // Parse response
2841        do {
2842                $line = $this->readLine(4096);
2843                if ($response !== null)
2844                    $response .= $line;
2845        } while (!$this->startsWith($line, $tag . ' ', true, true));
2846
2847            $code = $this->parseResult($line, $command . ': ');
2848
2849        // Remove last line from response
2850        if ($response) {
2851            $line_len = min(strlen($response), strlen($line) + 2);
2852            $response = substr($response, 0, -$line_len);
2853        }
2854
2855            // optional CAPABILITY response
2856            if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
2857            && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
2858        ) {
2859                    $this->parseCapability($matches[1], true);
2860            }
2861
2862            return $noresp ? $code : array($code, $response);
2863    }
2864
2865    /**
2866     * Splits IMAP response into string tokens
2867     *
2868     * @param string &$str The IMAP's server response
2869     * @param int    $num  Number of tokens to return
2870     *
2871     * @return mixed Tokens array or string if $num=1
2872     * @access public
2873     * @since 0.5-beta
2874     */
2875    static function tokenizeResponse(&$str, $num=0)
2876    {
2877        $result = array();
2878
2879        while (!$num || count($result) < $num) {
2880            // remove spaces from the beginning of the string
2881            $str = ltrim($str);
2882
2883            switch ($str[0]) {
2884
2885            // String literal
2886            case '{':
2887                if (($epos = strpos($str, "}\r\n", 1)) == false) {
2888                    // error
2889                }
2890                if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
2891                    // error
2892                }
2893                $result[] = substr($str, $epos + 3, $bytes);
2894                // Advance the string
2895                $str = substr($str, $epos + 3 + $bytes);
2896            break;
2897
2898            // Quoted string
2899            case '"':
2900                $len = strlen($str);
2901
2902                for ($pos=1; $pos<$len; $pos++) {
2903                    if ($str[$pos] == '"') {
2904                        break;
2905                    }
2906                    if ($str[$pos] == "\\") {
2907                        if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
2908                            $pos++;
2909                        }
2910                    }
2911                }
2912                if ($str[$pos] != '"') {
2913                    // error
2914                }
2915                // we need to strip slashes for a quoted string
2916                $result[] = stripslashes(substr($str, 1, $pos - 1));
2917                $str      = substr($str, $pos + 1);
2918            break;
2919
2920            // Parenthesized list
2921            case '(':
2922                $str = substr($str, 1);
2923                $result[] = self::tokenizeResponse($str);
2924            break;
2925            case ')':
2926                $str = substr($str, 1);
2927                return $result;
2928            break;
2929
2930            // String atom, number, NIL, *, %
2931            default:
2932                // empty or one character
2933                if ($str === '') {
2934                    break 2;
2935                }
2936                if (strlen($str) < 2) {
2937                    $result[] = $str;
2938                    $str = '';
2939                    break;
2940                }
2941
2942                // excluded chars: SP, CTL, (, ), {, ", ], %
2943                if (preg_match('/^([\x21\x23\x24\x26\x27\x2A-\x5C\x5E-\x7A\x7C-\x7E]+)/', $str, $m)) {
2944                    $result[] = $m[1] == 'NIL' ? NULL : $m[1];
2945                    $str = substr($str, strlen($m[1]));
2946                }
2947            break;
2948            }
2949        }
2950
2951        return $num == 1 ? $result[0] : $result;
2952    }
2953
2954    private function _xor($string, $string2)
2955    {
2956            $result = '';
2957            $size = strlen($string);
2958            for ($i=0; $i<$size; $i++) {
2959                $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
2960            }
2961            return $result;
2962    }
2963
2964    /**
2965     * Converts datetime string into unix timestamp
2966     *
2967     * @param string $date Date string
2968     *
2969     * @return int Unix timestamp
2970     */
2971    private function strToTime($date)
2972    {
2973            // support non-standard "GMTXXXX" literal
2974            $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
2975        // if date parsing fails, we have a date in non-rfc format.
2976            // remove token from the end and try again
2977            while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
2978                $d = explode(' ', $date);
2979                    array_pop($d);
2980                    if (!$d) break;
2981                    $date = implode(' ', $d);
2982            }
2983
2984            $ts = (int) $ts;
2985
2986            return $ts < 0 ? 0 : $ts;
2987    }
2988
2989    private function SplitHeaderLine($string)
2990    {
2991            $pos = strpos($string, ':');
2992            if ($pos>0) {
2993                    $res[0] = substr($string, 0, $pos);
2994                    $res[1] = trim(substr($string, $pos+1));
2995                    return $res;
2996            }
2997        return $string;
2998    }
2999
3000    private function parseCapability($str, $trusted=false)
3001    {
3002        $str = preg_replace('/^\* CAPABILITY /i', '', $str);
3003
3004        $this->capability = explode(' ', strtoupper($str));
3005
3006        if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
3007            $this->prefs['literal+'] = true;
3008        }
3009
3010        if ($trusted) {
3011            $this->capability_readed = true;
3012        }
3013    }
3014
3015    /**
3016     * Escapes a string when it contains special characters (RFC3501)
3017     *
3018     * @param string $string IMAP string
3019     *
3020     * @return string Escaped string
3021     * @todo String literals, lists
3022     */
3023    static function escape($string)
3024    {
3025        // NIL
3026        if ($string === null) {
3027            return 'NIL';
3028        }
3029        // empty string
3030        else if ($string === '') {
3031            return '""';
3032        }
3033        // string: special chars: SP, CTL, (, ), {, %, *, ", \, ]
3034        else if (preg_match('/([\x00-\x20\x28-\x29\x7B\x25\x2A\x22\x5C\x5D\x7F]+)/', $string)) {
3035                return '"' . strtr($string, array('"'=>'\\"', '\\' => '\\\\')) . '"';
3036        }
3037
3038        // atom
3039        return $string;
3040    }
3041
3042    static function unEscape($string)
3043    {
3044            return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
3045    }
3046
3047}
Note: See TracBrowser for help on using the repository browser.