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

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