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

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