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

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