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

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