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

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