source: github/program/include/rcube_imap_generic.php @ 8fcc3e1

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 8fcc3e1 was 8fcc3e1, checked in by alecpl <alec@…>, 3 years ago
  • Improved IMAP errors handling
  • Property mode set to 100644
File size: 61.0 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 $f;
54        public $body_structure;
55        public $internaldate;
56        public $references;
57        public $priority;
58        public $mdn_to;
59        public $mdn_sent = false;
60        public $is_draft = false;
61        public $seen = false;
62        public $deleted = false;
63        public $recent = false;
64        public $answered = false;
65        public $forwarded = false;
66        public $junk = false;
67        public $flagged = false;
68        public $has_children = false;
69        public $depth = 0;
70        public $unread_children = 0;
71        public $others = array();
72}
73
74// For backward compatibility with cached messages (#1486602)
75class iilBasicHeader extends rcube_mail_header
76{
77}
78
79/**
80 * PHP based wrapper class to connect to an IMAP server
81 *
82 * @package    Mail
83 * @author     Aleksander Machniak <alec@alec.pl>
84 */
85class rcube_imap_generic
86{
87    public $error;
88    public $errornum;
89        public $message;
90        public $rootdir;
91        public $delimiter;
92        public $permanentflags = array();
93    public $flags = array(
94        'SEEN'     => '\\Seen',
95        'DELETED'  => '\\Deleted',
96        'RECENT'   => '\\Recent',
97        'ANSWERED' => '\\Answered',
98        'DRAFT'    => '\\Draft',
99        'FLAGGED'  => '\\Flagged',
100        'FORWARDED' => '$Forwarded',
101        'MDNSENT'  => '$MDNSent',
102        '*'        => '\\*',
103    );
104
105        private $exists;
106        private $recent;
107    private $selected;
108        private $fp;
109        private $host;
110        private $logged = false;
111        private $capability = array();
112        private $capability_readed = false;
113    private $prefs;
114
115    const ERROR_OK = 0;
116    const ERROR_NO = -1;
117    const ERROR_BAD = -2;
118    const ERROR_BYE = -3;
119    const ERROR_COMMAND = -5;
120    const ERROR_UNKNOWN = -4;
121
122    /**
123     * Object constructor
124     */
125    function __construct()
126    {
127    }
128
129    function putLine($string, $endln=true)
130    {
131        if (!$this->fp)
132            return false;
133
134                if (!empty($this->prefs['debug_mode'])) {
135                write_log('imap', 'C: '. rtrim($string));
136            }
137
138        $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
139
140                if ($res === false) {
141                @fclose($this->fp);
142                $this->fp = null;
143                }
144
145        return $res;
146    }
147
148    // $this->putLine replacement with Command Continuation Requests (RFC3501 7.5) support
149    function putLineC($string, $endln=true)
150    {
151        if (!$this->fp)
152            return false;
153
154            if ($endln)
155                    $string .= "\r\n";
156
157            $res = 0;
158            if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
159                    for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
160                            if (preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
161                                    $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
162                    if ($bytes === false)
163                        return false;
164                    $res += $bytes;
165                                    $line = $this->readLine(1000);
166                                    // handle error in command
167                                    if ($line[0] != '+')
168                                            return false;
169                                    $i++;
170                            }
171                            else {
172                                    $bytes = $this->putLine($parts[$i], false);
173                    if ($bytes === false)
174                        return false;
175                    $res += $bytes;
176                }
177                    }
178            }
179
180            return $res;
181    }
182
183    function readLine($size=1024)
184    {
185                $line = '';
186
187            if (!$this->fp) {
188                return NULL;
189            }
190
191            if (!$size) {
192                    $size = 1024;
193            }
194
195            do {
196                    if (feof($this->fp)) {
197                            return $line ? $line : NULL;
198                    }
199
200                $buffer = fgets($this->fp, $size);
201
202                if ($buffer === false) {
203                @fclose($this->fp);
204                $this->fp = null;
205                        break;
206                }
207                    if (!empty($this->prefs['debug_mode'])) {
208                            write_log('imap', 'S: '. rtrim($buffer));
209                }
210            $line .= $buffer;
211            } while ($buffer[strlen($buffer)-1] != "\n");
212
213            return $line;
214    }
215
216    function multLine($line, $escape=false)
217    {
218            $line = rtrim($line);
219            if (preg_match('/\{[0-9]+\}$/', $line)) {
220                    $out = '';
221
222                    preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
223                    $bytes = $a[2][0];
224                    while (strlen($out) < $bytes) {
225                            $line = $this->readBytes($bytes);
226                            if ($line === NULL)
227                                    break;
228                            $out .= $line;
229                    }
230
231                    $line = $a[1][0] . '"' . ($escape ? $this->Escape($out) : $out) . '"';
232            }
233
234        return $line;
235    }
236
237    function readBytes($bytes)
238    {
239            $data = '';
240            $len  = 0;
241            while ($len < $bytes && !feof($this->fp))
242            {
243                    $d = fread($this->fp, $bytes-$len);
244                    if (!empty($this->prefs['debug_mode'])) {
245                            write_log('imap', 'S: '. $d);
246            }
247            $data .= $d;
248                    $data_len = strlen($data);
249                    if ($len == $data_len) {
250                    break; // nothing was read -> exit to avoid apache lockups
251                }
252                $len = $data_len;
253            }
254
255            return $data;
256    }
257
258    // don't use it in loops, until you exactly know what you're doing
259    function readReply(&$untagged=null)
260    {
261            do {
262                    $line = trim($this->readLine(1024));
263            // store untagged response lines
264                    if ($line[0] == '*')
265                $untagged[] = $line;
266            } while ($line[0] == '*');
267
268        if ($untagged)
269            $untagged = join("\n", $untagged);
270
271            return $line;
272    }
273
274    function parseResult($string, $err_prefix='')
275    {
276            if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
277                    $res = strtoupper($matches[1]);
278            $str = trim($matches[2]);
279
280                    if ($res == 'OK') {
281                            return self::ERROR_OK;
282                    } else if ($res == 'NO') {
283                $this->errornum = self::ERROR_NO;
284                    } else if ($res == 'BAD') {
285                            $this->errornum = self::ERROR_BAD;
286                    } else if ($res == 'BYE') {
287                @fclose($this->fp);
288                $this->fp = null;
289                            $this->errornum = self::ERROR_BYE;
290                    }
291
292            if ($str)
293                $this->error = $err_prefix ? $err_prefix.$str : $str;
294
295                return $this->errornum;
296            }
297            return self::ERROR_UNKNOWN;
298    }
299
300    private function set_error($code, $msg='')
301    {
302        $this->errornum = $code;
303        $this->error    = $msg;
304    }
305
306    // check if $string starts with $match (or * BYE/BAD)
307    function startsWith($string, $match, $error=false, $nonempty=false)
308    {
309            $len = strlen($match);
310            if ($len == 0) {
311                    return false;
312            }
313        if (!$this->fp) {
314            return true;
315        }
316            if (strncmp($string, $match, $len) == 0) {
317                    return true;
318            }
319            if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
320            if (strtoupper($m[1]) == 'BYE') {
321                @fclose($this->fp);
322                $this->fp = null;
323            }
324                    return true;
325            }
326        if ($nonempty && !strlen($string)) {
327            return true;
328        }
329            return false;
330    }
331
332    function getCapability($name)
333    {
334            if (in_array($name, $this->capability)) {
335                    return true;
336            }
337            else if ($this->capability_readed) {
338                    return false;
339            }
340
341            // get capabilities (only once) because initial
342            // optional CAPABILITY response may differ
343            $this->capability = array();
344
345            if (!$this->putLine("cp01 CAPABILITY")) {
346            return false;
347        }
348            do {
349                    $line = trim($this->readLine(1024));
350                if (preg_match('/^\* CAPABILITY (.+)/i', $line, $matches)) {
351                        $this->capability = explode(' ', strtoupper($matches[1]));
352                }
353            } while (!$this->startsWith($line, 'cp01', true));
354
355            $this->capability_readed = true;
356
357            if (in_array($name, $this->capability)) {
358                    return true;
359            }
360
361            return false;
362    }
363
364    function clearCapability()
365    {
366            $this->capability = array();
367            $this->capability_readed = false;
368    }
369
370    function authenticate($user, $pass, $encChallenge)
371    {
372        $ipad = '';
373        $opad = '';
374
375        // initialize ipad, opad
376        for ($i=0; $i<64; $i++) {
377            $ipad .= chr(0x36);
378            $opad .= chr(0x5C);
379        }
380
381        // pad $pass so it's 64 bytes
382        $padLen = 64 - strlen($pass);
383        for ($i=0; $i<$padLen; $i++) {
384            $pass .= chr(0);
385        }
386
387        // generate hash
388        $hash  = md5($this->_xor($pass,$opad) . pack("H*", md5($this->_xor($pass, $ipad) . base64_decode($encChallenge))));
389
390        // generate reply
391        $reply = base64_encode($user . ' ' . $hash);
392
393        // send result, get reply
394        $this->putLine($reply);
395        $line = $this->readLine(1024);
396
397        // process result
398        $result = $this->parseResult($line);
399        if ($result == self::ERROR_OK) {
400            return $this->fp;
401        }
402
403        $this->error = "Authentication for $user failed (AUTH): $line";
404
405        return $result;
406    }
407
408    function login($user, $password)
409    {
410        $this->putLine('a001 LOGIN "'.$this->escape($user).'" "'.$this->escape($password).'"');
411
412        $line = $this->readReply($untagged);
413
414        // re-set capabilities list if untagged CAPABILITY response provided
415            if (preg_match('/\* CAPABILITY (.+)/i', $untagged, $matches)) {
416                    $this->capability = explode(' ', strtoupper($matches[1]));
417            }
418
419        // process result
420        $result = $this->parseResult($line);
421
422        if ($result == self::ERROR_OK) {
423            return $this->fp;
424        }
425
426        @fclose($this->fp);
427        $this->fp    = false;
428        $this->error = "Authentication for $user failed (LOGIN): $line";
429
430        return $result;
431    }
432
433    function getNamespace()
434    {
435            if (isset($this->prefs['rootdir']) && is_string($this->prefs['rootdir'])) {
436                $this->rootdir = $this->prefs['rootdir'];
437                    return true;
438            }
439
440            if (!is_array($data = $this->_namespace())) {
441                return false;
442            }
443
444            $user_space_data = $data[0];
445            if (!is_array($user_space_data)) {
446                return false;
447            }
448
449            $first_userspace = $user_space_data[0];
450            if (count($first_userspace)!=2) {
451                return false;
452            }
453
454            $this->rootdir            = $first_userspace[0];
455            $this->delimiter          = $first_userspace[1];
456            $this->prefs['rootdir']   = substr($this->rootdir, 0, -1);
457            $this->prefs['delimiter'] = $this->delimiter;
458
459            return true;
460    }
461
462
463    /**
464     * Gets the delimiter, for example:
465     * INBOX.foo -> .
466     * INBOX/foo -> /
467     * INBOX\foo -> \
468     *
469     * @return mixed A delimiter (string), or false.
470     * @see connect()
471     */
472    function getHierarchyDelimiter()
473    {
474            if ($this->delimiter) {
475                return $this->delimiter;
476            }
477            if (!empty($this->prefs['delimiter'])) {
478            return ($this->delimiter = $this->prefs['delimiter']);
479            }
480
481            $delimiter = false;
482
483            // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
484            if (!$this->putLine('ghd LIST "" ""')) {
485                return false;
486            }
487
488            do {
489                    $line = $this->readLine(1024);
490                    if (preg_match('/^\* LIST \([^\)]*\) "*([^"]+)"* ""/', $line, $m)) {
491                $delimiter = $this->unEscape($m[1]);
492                    }
493            } while (!$this->startsWith($line, 'ghd', true, true));
494
495            if (strlen($delimiter)>0) {
496                return $delimiter;
497            }
498
499            // if that fails, try namespace extension
500            // try to fetch namespace data
501            if (!is_array($data = $this->_namespace())) {
502            return false;
503        }
504
505            // extract user space data (opposed to global/shared space)
506            $user_space_data = $data[0];
507            if (!is_array($user_space_data)) {
508                return false;
509            }
510
511            // get first element
512            $first_userspace = $user_space_data[0];
513            if (!is_array($first_userspace)) {
514                return false;
515            }
516
517            // extract delimiter
518            $delimiter = $first_userspace[1];
519
520            return $delimiter;
521    }
522
523    function _namespace()
524    {
525        if (!$this->getCapability('NAMESPACE')) {
526                return false;
527            }
528
529            if (!$this->putLine("ns1 NAMESPACE")) {
530            return false;
531        }
532
533            do {
534                    $line = $this->readLine(1024);
535                    if (preg_match('/^\* NAMESPACE/', $line)) {
536                            $i = 0;
537                            $data = $this->parseNamespace(substr($line,11), $i, 0, 0);
538                    }
539            } while (!$this->startsWith($line, 'ns1', true, true));
540
541            if (!is_array($data)) {
542                return false;
543            }
544
545        return $data;
546    }
547
548    function connect($host, $user, $password, $options=null)
549    {
550            // set options
551            if (is_array($options)) {
552            $this->prefs = $options;
553        }
554        // set auth method
555        if (!empty($this->prefs['auth_method'])) {
556            $auth_method = strtoupper($this->prefs['auth_method']);
557            } else {
558                $auth_method = 'CHECK';
559        }
560
561            $message = "INITIAL: $auth_method\n";
562
563            $result = false;
564
565            // initialize connection
566            $this->error    = '';
567            $this->errornum = self::ERROR_OK;
568            $this->selected = '';
569            $this->user     = $user;
570            $this->host     = $host;
571        $this->logged   = false;
572
573            // check input
574            if (empty($host)) {
575                    $this->set_error(self::ERROR_BAD, "Empty host");
576                    return false;
577            }
578        if (empty($user)) {
579                $this->set_error(self::ERROR_NO, "Empty user");
580                return false;
581            }
582            if (empty($password)) {
583                $this->set_error(self::ERROR_NO, "Empty password");
584                    return false;
585            }
586
587            if (!$this->prefs['port']) {
588                    $this->prefs['port'] = 143;
589            }
590            // check for SSL
591            if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
592                    $host = $this->prefs['ssl_mode'] . '://' . $host;
593            }
594
595        // Connect
596        if ($this->prefs['timeout'] > 0)
597                $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
598            else
599                $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr);
600
601            if (!$this->fp) {
602                $this->set_error(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr));
603                    return false;
604            }
605
606        if ($this->prefs['timeout'] > 0)
607                stream_set_timeout($this->fp, $this->prefs['timeout']);
608
609            $line = trim(fgets($this->fp, 8192));
610
611            if ($this->prefs['debug_mode'] && $line) {
612                    write_log('imap', 'S: '. $line);
613        }
614
615            // Connected to wrong port or connection error?
616            if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
617                    if ($line)
618                            $this->error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
619                    else
620                            $this->error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
621                $this->errornum = self::ERROR_BAD;
622                return false;
623            }
624
625            // RFC3501 [7.1] optional CAPABILITY response
626            if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
627                    $this->capability = explode(' ', strtoupper($matches[1]));
628            }
629
630            $this->message .= $line;
631
632            // TLS connection
633            if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
634                if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
635                $this->putLine("tls0 STARTTLS");
636
637                            $line = $this->readLine(4096);
638                if (!preg_match('/^tls0 OK/', $line)) {
639                                    $this->set_error(self::ERROR_BAD, "Server responded to STARTTLS with: $line");
640                    return false;
641                }
642
643                            if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
644                                    $this->set_error(self::ERROR_BAD, "Unable to negotiate TLS");
645                                    return false;
646                            }
647
648                            // Now we're authenticated, capabilities need to be reread
649                            $this->clearCapability();
650                }
651            }
652
653            $orig_method = $auth_method;
654
655            if ($auth_method == 'CHECK') {
656                    // check for supported auth methods
657                    if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
658                            $auth_method = 'AUTH';
659                    }
660                    else {
661                            // default to plain text auth
662                            $auth_method = 'PLAIN';
663                    }
664            }
665
666            if ($auth_method == 'AUTH') {
667                    // do CRAM-MD5 authentication
668                    $this->putLine("a000 AUTHENTICATE CRAM-MD5");
669                    $line = trim($this->readLine(1024));
670
671                    if ($line[0] == '+') {
672                            // got a challenge string, try CRAM-MD5
673                            $result = $this->authenticate($user, $password, substr($line,2));
674
675                            // stop if server sent BYE response
676                            if ($result == self::ERROR_BYE) {
677                                    return false;
678                            }
679                    }
680
681                    if (!is_resource($result) && $orig_method == 'CHECK') {
682                            $auth_method = 'PLAIN';
683                    }
684            }
685
686            if ($auth_method == 'PLAIN') {
687                    // do plain text auth
688                    $result = $this->login($user, $password);
689            }
690
691            if (is_resource($result)) {
692            if ($this->prefs['force_caps']) {
693                            $this->clearCapability();
694            }
695                    $this->getNamespace();
696            $this->logged = true;
697
698                    return true;
699            } else {
700                    return false;
701            }
702    }
703
704    function connected()
705    {
706                return ($this->fp && $this->logged) ? true : false;
707    }
708
709    function close()
710    {
711            if ($this->logged && $this->putLine("I LOGOUT")) {
712                    if (!feof($this->fp))
713                            fgets($this->fp, 1024);
714            }
715                @fclose($this->fp);
716                $this->fp = false;
717    }
718
719    function select($mailbox)
720    {
721            if (empty($mailbox)) {
722                    return false;
723            }
724            if ($this->selected == $mailbox) {
725                    return true;
726            }
727
728        $command = "sel1 SELECT \"".$this->escape($mailbox).'"';
729
730            if (!$this->putLine($command)) {
731            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
732            return false;
733        }
734
735                do {
736                        $line = rtrim($this->readLine(512));
737
738                        if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/', $line, $m)) {
739                            $token = strtolower($m[2]);
740                            $this->$token = (int) $m[1];
741                        }
742                        else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
743                            $this->permanentflags = explode(' ', $match[1]);
744                        }
745                } while (!$this->startsWith($line, 'sel1', true, true));
746
747        if ($this->parseResult($line, 'SELECT: ') == self::ERROR_OK) {
748                    $this->selected = $mailbox;
749                        return true;
750                }
751
752        return false;
753    }
754
755    function checkForRecent($mailbox)
756    {
757            if (empty($mailbox)) {
758                    $mailbox = 'INBOX';
759            }
760
761            $this->select($mailbox);
762            if ($this->selected == $mailbox) {
763                    return $this->recent;
764            }
765
766            return false;
767    }
768
769    function countMessages($mailbox, $refresh = false)
770    {
771            if ($refresh) {
772                    $this->selected = '';
773            }
774
775            $this->select($mailbox);
776            if ($this->selected == $mailbox) {
777                    return $this->exists;
778            }
779
780        return false;
781    }
782
783    function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
784    {
785            $field = strtoupper($field);
786            if ($field == 'INTERNALDATE') {
787                $field = 'ARRIVAL';
788            }
789
790            $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
791            'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
792
793            if (!$fields[$field]) {
794                return false;
795            }
796
797            /*  Do "SELECT" command */
798            if (!$this->select($mailbox)) {
799                return false;
800            }
801
802            $is_uid = $is_uid ? 'UID ' : '';
803
804            // message IDs
805            if (is_array($add))
806                    $add = $this->compressMessageSet(join(',', $add));
807
808            $command  = "s ".$is_uid."SORT ($field) $encoding ALL";
809            $line     = '';
810            $data     = '';
811
812            if (!empty($add))
813                $command .= ' '.$add;
814
815            if (!$this->putLineC($command)) {
816            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
817                return false;
818            }
819            do {
820                    $line = rtrim($this->readLine());
821                    if (!$data && preg_match('/^\* SORT/', $line)) {
822                            $data .= substr($line, 7);
823                } else if (preg_match('/^[0-9 ]+$/', $line)) {
824                            $data .= $line;
825                    }
826            } while (!$this->startsWith($line, 's ', true, true));
827
828            $result_code = $this->parseResult($line, 'SORT: ');
829            if ($result_code != self::ERROR_OK) {
830            return false;
831            }
832
833            return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
834    }
835
836    function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
837    {
838            if (is_array($message_set)) {
839                    if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
840                            return false;
841            } else {
842                    list($from_idx, $to_idx) = explode(':', $message_set);
843                    if (empty($message_set) ||
844                            (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
845                            return false;
846                    }
847            }
848
849            $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
850
851        $fields_a['DATE']         = 1;
852            $fields_a['INTERNALDATE'] = 4;
853        $fields_a['ARRIVAL']      = 4;
854            $fields_a['FROM']         = 1;
855        $fields_a['REPLY-TO']     = 1;
856            $fields_a['SENDER']       = 1;
857        $fields_a['TO']           = 1;
858            $fields_a['CC']           = 1;
859        $fields_a['SUBJECT']      = 1;
860            $fields_a['UID']          = 2;
861        $fields_a['SIZE']         = 2;
862            $fields_a['SEEN']         = 3;
863        $fields_a['RECENT']       = 3;
864            $fields_a['DELETED']      = 3;
865
866        if (!($mode = $fields_a[$index_field])) {
867                return false;
868            }
869
870        /*  Do "SELECT" command */
871            if (!$this->select($mailbox)) {
872                    return false;
873            }
874
875        // build FETCH command string
876            $key     = 'fhi0';
877            $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
878            $deleted = $skip_deleted ? ' FLAGS' : '';
879
880            if ($mode == 1 && $index_field == 'DATE')
881                    $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
882            else if ($mode == 1)
883                    $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
884            else if ($mode == 2) {
885                    if ($index_field == 'SIZE')
886                            $request = " $cmd $message_set (RFC822.SIZE$deleted)";
887                    else
888                            $request = " $cmd $message_set ($index_field$deleted)";
889            } else if ($mode == 3)
890                    $request = " $cmd $message_set (FLAGS)";
891            else // 4
892                    $request = " $cmd $message_set (INTERNALDATE$deleted)";
893
894            $request = $key . $request;
895
896            if (!$this->putLine($request)) {
897            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
898                    return false;
899        }
900
901            $result = array();
902
903            do {
904                    $line = rtrim($this->readLine(200));
905                    $line = $this->multLine($line);
906
907                    if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
908                $id     = $m[1];
909                            $flags  = NULL;
910
911                            if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
912                                    $flags = explode(' ', strtoupper($matches[1]));
913                                    if (in_array('\\DELETED', $flags)) {
914                                            $deleted[$id] = $id;
915                                            continue;
916                                    }
917                            }
918
919                            if ($mode == 1 && $index_field == 'DATE') {
920                                    if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
921                                            $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
922                                            $value = trim($value);
923                                            $result[$id] = $this->strToTime($value);
924                                    }
925                                    // non-existent/empty Date: header, use INTERNALDATE
926                                    if (empty($result[$id])) {
927                                            if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
928                                                    $result[$id] = $this->strToTime($matches[1]);
929                                            else
930                                                    $result[$id] = 0;
931                                    }
932                            } else if ($mode == 1) {
933                                    if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
934                                            $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
935                                            $result[$id] = trim($value);
936                                    } else {
937                                            $result[$id] = '';
938                                    }
939                            } else if ($mode == 2) {
940                                    if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
941                                            $result[$id] = trim($matches[2]);
942                                    } else {
943                                            $result[$id] = 0;
944                                    }
945                            } else if ($mode == 3) {
946                                    if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
947                                            $flags = explode(' ', $matches[1]);
948                                    }
949                                    $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
950                            } else if ($mode == 4) {
951                                    if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
952                                            $result[$id] = $this->strToTime($matches[1]);
953                                    } else {
954                                            $result[$id] = 0;
955                                    }
956                            }
957                    }
958            } while (!$this->startsWith($line, $key, true, true));
959
960            return $result;
961    }
962
963    private function compressMessageSet($message_set)
964    {
965            // given a comma delimited list of independent mid's,
966            // compresses by grouping sequences together
967
968            // if less than 255 bytes long, let's not bother
969            if (strlen($message_set)<255) {
970                return $message_set;
971            }
972
973            // see if it's already been compress
974            if (strpos($message_set, ':') !== false) {
975                return $message_set;
976            }
977
978            // separate, then sort
979            $ids = explode(',', $message_set);
980            sort($ids);
981
982            $result = array();
983            $start  = $prev = $ids[0];
984
985            foreach ($ids as $id) {
986                    $incr = $id - $prev;
987                    if ($incr > 1) {                    //found a gap
988                            if ($start == $prev) {
989                                $result[] = $prev;      //push single id
990                            } else {
991                                $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
992                            }
993                        $start = $id;                   //start of new sequence
994                    }
995                    $prev = $id;
996            }
997
998            // handle the last sequence/id
999            if ($start==$prev) {
1000                $result[] = $prev;
1001            } else {
1002            $result[] = $start.':'.$prev;
1003            }
1004
1005            // return as comma separated string
1006            return implode(',', $result);
1007    }
1008
1009    function UID2ID($folder, $uid)
1010    {
1011            if ($uid > 0) {
1012                $id_a = $this->search($folder, "UID $uid");
1013                if (is_array($id_a) && count($id_a) == 1) {
1014                        return $id_a[0];
1015                    }
1016            }
1017            return false;
1018    }
1019
1020    function ID2UID($folder, $id)
1021    {
1022            if (empty($id)) {
1023                return  -1;
1024            }
1025
1026        if (!$this->select($folder)) {
1027            return -1;
1028        }
1029
1030            $result = -1;
1031        $command = "fuid FETCH $id (UID)";
1032
1033                if (!$this->putLine($command)) {
1034            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1035            return -1;
1036        }
1037
1038            do {
1039                    $line = rtrim($this->readLine(1024));
1040                        if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1041                                $result = $r[1];
1042                        }
1043                } while (!$this->startsWith($line, 'fuid', true, true));
1044
1045        return $result;
1046    }
1047
1048    function fetchUIDs($mailbox, $message_set=null)
1049    {
1050            if (is_array($message_set))
1051                    $message_set = join(',', $message_set);
1052        else if (empty($message_set))
1053                    $message_set = '1:*';
1054
1055            return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1056    }
1057
1058    function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1059    {
1060            $result = array();
1061
1062            if (!$this->select($mailbox)) {
1063                    return false;
1064            }
1065
1066            if (is_array($message_set))
1067                    $message_set = join(',', $message_set);
1068
1069            $message_set = $this->compressMessageSet($message_set);
1070
1071            if ($add)
1072                    $add = ' '.trim($add);
1073
1074            /* FETCH uid, size, flags and headers */
1075            $key          = 'FH12';
1076            $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1077            $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1078            if ($bodystr)
1079                    $request .= "BODYSTRUCTURE ";
1080            $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1081            $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1082
1083            if (!$this->putLine($request)) {
1084            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1085                    return false;
1086            }
1087            do {
1088                    $line = $this->readLine(1024);
1089                    $line = $this->multLine($line);
1090
1091            if (!$line)
1092                break;
1093
1094                    if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1095                            $id = intval($m[1]);
1096
1097                            $result[$id]            = new rcube_mail_header;
1098                            $result[$id]->id        = $id;
1099                            $result[$id]->subject   = '';
1100                            $result[$id]->messageID = 'mid:' . $id;
1101
1102                            $lines = array();
1103                            $ln = 0;
1104
1105                            // Sample reply line:
1106                            // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1107                            // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1108                            // BODY[HEADER.FIELDS ...
1109
1110                            if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1111                                    $str = $matches[1];
1112
1113                                    // swap parents with quotes, then explode
1114                                    $str = preg_replace('/[()]/', '"', $str);
1115                                    $a = rcube_explode_quoted_string(' ', $str);
1116
1117                                    // did we get the right number of replies?
1118                                    $parts_count = count($a);
1119                                    if ($parts_count>=6) {
1120                                            for ($i=0; $i<$parts_count; $i=$i+2) {
1121                                                    if ($a[$i] == 'UID')
1122                                                            $result[$id]->uid = intval($a[$i+1]);
1123                                                    else if ($a[$i] == 'RFC822.SIZE')
1124                                                            $result[$id]->size = intval($a[$i+1]);
1125                                                else if ($a[$i] == 'INTERNALDATE')
1126                                                        $time_str = $a[$i+1];
1127                                                else if ($a[$i] == 'FLAGS')
1128                                                        $flags_str = $a[$i+1];
1129                                        }
1130
1131                                            $time_str = str_replace('"', '', $time_str);
1132
1133                                            // if time is gmt...
1134                                $time_str = str_replace('GMT','+0000',$time_str);
1135
1136                                            $result[$id]->internaldate = $time_str;
1137                                        $result[$id]->timestamp = $this->StrToTime($time_str);
1138                                        $result[$id]->date = $time_str;
1139                                }
1140
1141                                // BODYSTRUCTURE
1142                                    if($bodystr) {
1143                                            while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1144                                                    $line2 = $this->readLine(1024);
1145                                                $line .= $this->multLine($line2, true);
1146                                        }
1147                                        $result[$id]->body_structure = $m[1];
1148                                }
1149
1150                                // the rest of the result
1151                                preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1152                                $reslines = explode("\n", trim($m[1], '"'));
1153                                // re-parse (see below)
1154                                    foreach ($reslines as $resln) {
1155                                        if (ord($resln[0])<=32) {
1156                                                $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1157                                        } else {
1158                                                $lines[++$ln] = trim($resln);
1159                                            }
1160                                }
1161                        }
1162
1163                                // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1164                                // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1165                                // process the previous line.  Otherwise, we'll keep adding the strings until we come
1166                                // to the next valid header line.
1167
1168                            do {
1169                                    $line = rtrim($this->readLine(300), "\r\n");
1170
1171                                // The preg_match below works around communigate imap, which outputs " UID <number>)".
1172                                // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1173                                // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1174                                // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1175                                    // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1176                                // An alternative might be:
1177                                // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1178                                // however, unsure how well this would work with all imap clients.
1179                                if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1180                                        break;
1181                                    }
1182
1183                                // handle FLAGS reply after headers (AOL, Zimbra?)
1184                                if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1185                                        $flags_str = $matches[1];
1186                                        break;
1187                                    }
1188
1189                                if (ord($line[0])<=32) {
1190                                        $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1191                                } else {
1192                                        $lines[++$ln] = trim($line);
1193                                    }
1194                        // patch from "Maksim Rubis" <siburny@hotmail.com>
1195                        } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1196
1197                        if (strncmp($line, $key, strlen($key))) {
1198                                // process header, fill rcube_mail_header obj.
1199                                // initialize
1200                                if (is_array($headers)) {
1201                                        reset($headers);
1202                                            while (list($k, $bar) = each($headers)) {
1203                                                $headers[$k] = '';
1204                                        }
1205                                }
1206
1207                                // create array with header field:data
1208                                while ( list($lines_key, $str) = each($lines) ) {
1209                                        list($field, $string) = $this->splitHeaderLine($str);
1210
1211                                        $field  = strtolower($field);
1212                                        $string = preg_replace('/\n\s*/', ' ', $string);
1213
1214                                        switch ($field) {
1215                                        case 'date';
1216                                                $result[$id]->date = $string;
1217                                                $result[$id]->timestamp = $this->strToTime($string);
1218                                        break;
1219                                        case 'from':
1220                                                $result[$id]->from = $string;
1221                                                break;
1222                                        case 'to':
1223                                                $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1224                                                break;
1225                                        case 'subject':
1226                                                $result[$id]->subject = $string;
1227                                                break;
1228                                        case 'reply-to':
1229                                                $result[$id]->replyto = $string;
1230                                                break;
1231                                        case 'cc':
1232                                                $result[$id]->cc = $string;
1233                                                break;
1234                                        case 'bcc':
1235                                                $result[$id]->bcc = $string;
1236                                                break;
1237                                        case 'content-transfer-encoding':
1238                                                $result[$id]->encoding = $string;
1239                                                break;
1240                                        case 'content-type':
1241                                                $ctype_parts = preg_split('/[; ]/', $string);
1242                                                $result[$id]->ctype = array_shift($ctype_parts);
1243                                                if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1244                                                        $result[$id]->charset = $regs[1];
1245                                                }
1246                                                break;
1247                                            case 'in-reply-to':
1248                                                $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1249                                                break;
1250                                        case 'references':
1251                                                $result[$id]->references = $string;
1252                                                break;
1253                                        case 'return-receipt-to':
1254                                        case 'disposition-notification-to':
1255                                            case 'x-confirm-reading-to':
1256                                                $result[$id]->mdn_to = $string;
1257                                                break;
1258                                        case 'message-id':
1259                                                $result[$id]->messageID = $string;
1260                                                break;
1261                                            case 'x-priority':
1262                                                if (preg_match('/^(\d+)/', $string, $matches))
1263                                                        $result[$id]->priority = intval($matches[1]);
1264                                                break;
1265                                        default:
1266                                                if (strlen($field) > 2)
1267                                                        $result[$id]->others[$field] = $string;
1268                                                    break;
1269                                        } // end switch ()
1270                                } // end while ()
1271                            }
1272
1273                        // process flags
1274                        if (!empty($flags_str)) {
1275                                $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1276                                $flags_a   = explode(' ', $flags_str);
1277
1278                                    if (is_array($flags_a)) {
1279                                        foreach($flags_a as $flag) {
1280                                                $flag = strtoupper($flag);
1281                                                if ($flag == 'SEEN') {
1282                                                    $result[$id]->seen = true;
1283                                                } else if ($flag == 'DELETED') {
1284                                                    $result[$id]->deleted = true;
1285                                                } else if ($flag == 'RECENT') {
1286                                                    $result[$id]->recent = true;
1287                                                } else if ($flag == 'ANSWERED') {
1288                                                        $result[$id]->answered = true;
1289                                                } else if ($flag == '$FORWARDED') {
1290                                                        $result[$id]->forwarded = true;
1291                                                } else if ($flag == 'DRAFT') {
1292                                                        $result[$id]->is_draft = true;
1293                                                } else if ($flag == '$MDNSENT') {
1294                                                        $result[$id]->mdn_sent = true;
1295                                                } else if ($flag == 'FLAGGED') {
1296                                                         $result[$id]->flagged = true;
1297                                                    }
1298                                        }
1299                                        $result[$id]->flags = $flags_a;
1300                                }
1301                            }
1302                }
1303            } while (!$this->startsWith($line, $key, true));
1304
1305        return $result;
1306    }
1307
1308    function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1309    {
1310            $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1311            if (is_array($a)) {
1312                    return array_shift($a);
1313            }
1314            return false;
1315    }
1316
1317    function sortHeaders($a, $field, $flag)
1318    {
1319            if (empty($field)) {
1320                $field = 'uid';
1321            }
1322        else {
1323            $field = strtolower($field);
1324        }
1325
1326            if ($field == 'date' || $field == 'internaldate') {
1327                $field = 'timestamp';
1328            }
1329        if (empty($flag)) {
1330                $flag = 'ASC';
1331            } else {
1332                $flag = strtoupper($flag);
1333        }
1334
1335            $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1336
1337            $c = count($a);
1338            if ($c > 0) {
1339
1340                        // Strategy:
1341                        // First, we'll create an "index" array.
1342                        // Then, we'll use sort() on that array,
1343                        // and use that to sort the main array.
1344
1345                    // create "index" array
1346                    $index = array();
1347                    reset($a);
1348                    while (list($key, $val) = each($a)) {
1349                            if ($field == 'timestamp') {
1350                                    $data = $this->strToTime($val->date);
1351                                    if (!$data) {
1352                                            $data = $val->timestamp;
1353                        }
1354                            } else {
1355                                    $data = $val->$field;
1356                                    if (is_string($data)) {
1357                                            $data = strtoupper(str_replace($stripArr, '', $data));
1358                        }
1359                            }
1360                        $index[$key]=$data;
1361                }
1362
1363                    // sort index
1364                $i = 0;
1365                if ($flag == 'ASC') {
1366                        asort($index);
1367                } else {
1368                    arsort($index);
1369                    }
1370
1371                // form new array based on index
1372                $result = array();
1373                    reset($index);
1374                while (list($key, $val) = each($index)) {
1375                        $result[$key]=$a[$key];
1376                        $i++;
1377                    }
1378            }
1379
1380            return $result;
1381    }
1382
1383    function expunge($mailbox, $messages=NULL)
1384    {
1385            if (!$this->select($mailbox)) {
1386            return -1;
1387        }
1388
1389        $c = 0;
1390                $command = $messages ? "exp1 UID EXPUNGE $messages" : "exp1 EXPUNGE";
1391
1392                if (!$this->putLine($command)) {
1393            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1394            return -1;
1395        }
1396
1397                do {
1398                        $line = $this->readLine(100);
1399                        if ($line[0] == '*') {
1400                $c++;
1401                }
1402                } while (!$this->startsWith($line, 'exp1', true, true));
1403
1404                if ($this->parseResult($line, 'EXPUNGE: ') == self::ERROR_OK) {
1405                        $this->selected = ''; // state has changed, need to reselect
1406                        return $c;
1407                }
1408
1409            return -1;
1410    }
1411
1412    function modFlag($mailbox, $messages, $flag, $mod)
1413    {
1414            if ($mod != '+' && $mod != '-') {
1415                return -1;
1416            }
1417
1418            $flag = $this->flags[strtoupper($flag)];
1419
1420            if (!$this->select($mailbox)) {
1421                return -1;
1422            }
1423
1424        $c = 0;
1425        $command = "flg UID STORE $messages {$mod}FLAGS ($flag)";
1426            if (!$this->putLine($command)) {
1427            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1428            return false;
1429        }
1430
1431            do {
1432                    $line = $this->readLine();
1433                    if ($line[0] == '*') {
1434                        $c++;
1435            }
1436            } while (!$this->startsWith($line, 'flg', true, true));
1437
1438            if ($this->parseResult($line, 'STORE: ') == self::ERROR_OK) {
1439                    return $c;
1440            }
1441
1442            return -1;
1443    }
1444
1445    function flag($mailbox, $messages, $flag) {
1446            return $this->modFlag($mailbox, $messages, $flag, '+');
1447    }
1448
1449    function unflag($mailbox, $messages, $flag) {
1450            return $this->modFlag($mailbox, $messages, $flag, '-');
1451    }
1452
1453    function delete($mailbox, $messages) {
1454            return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1455    }
1456
1457    function copy($messages, $from, $to)
1458    {
1459            if (empty($from) || empty($to)) {
1460                return -1;
1461            }
1462
1463            if (!$this->select($from)) {
1464            return -1;
1465            }
1466
1467        $command = "cpy1 UID COPY $messages \"".$this->escape($to)."\"";
1468
1469        if (!$this->putLine($command)) {
1470            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1471        }
1472
1473        $line = $this->readReply();
1474            return $this->parseResult($line, 'COPY: ');
1475    }
1476
1477    function countUnseen($folder)
1478    {
1479        $index = $this->search($folder, 'ALL UNSEEN');
1480        if (is_array($index))
1481            return count($index);
1482        return false;
1483    }
1484
1485    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1486    // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1487    // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1488    private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1489    {
1490            $node = array();
1491            if ($str[$begin] != '(') {
1492                    $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1493                    $msg = substr($str, $begin, $stop - $begin);
1494                    if ($msg == 0)
1495                        return $node;
1496                    if (is_null($root))
1497                            $root = $msg;
1498                    $depthmap[$msg] = $depth;
1499                    $haschildren[$msg] = false;
1500                    if (!is_null($parent))
1501                            $haschildren[$parent] = true;
1502                    if ($stop + 1 < $end)
1503                            $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1504                    else
1505                            $node[$msg] = array();
1506            } else {
1507                    $off = $begin;
1508                    while ($off < $end) {
1509                            $start = $off;
1510                        $off++;
1511                        $n = 1;
1512                        while ($n > 0) {
1513                                $p = strpos($str, ')', $off);
1514                                    if ($p === false) {
1515                                            error_log('Mismatched brackets parsing IMAP THREAD response:');
1516                                        error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1517                                        error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1518                                        return $node;
1519                                }
1520                                    $p1 = strpos($str, '(', $off);
1521                                if ($p1 !== false && $p1 < $p) {
1522                                        $off = $p1 + 1;
1523                                        $n++;
1524                                } else {
1525                                        $off = $p + 1;
1526                                            $n--;
1527                                }
1528                        }
1529                        $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1530                    }
1531            }
1532
1533            return $node;
1534    }
1535
1536    function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1537    {
1538        $old_sel = $this->selected;
1539
1540            if (!$this->select($folder)) {
1541                return false;
1542            }
1543
1544        // return empty result when folder is empty and we're just after SELECT
1545        if ($old_sel != $folder && !$this->exists) {
1546            return array(array(), array(), array());
1547            }
1548
1549        $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1550            $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1551            $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1552        $data      = '';
1553
1554        $command = "thrd1 THREAD $algorithm $encoding $criteria";
1555
1556            if (!$this->putLineC($command)) {
1557            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1558                    return false;
1559            }
1560            do {
1561                    $line = trim($this->readLine());
1562                    if (!$data && preg_match('/^\* THREAD/', $line)) {
1563                        $data .= substr($line, 9);
1564                } else if (preg_match('/^[0-9() ]+$/', $line)) {
1565                        $data .= $line;
1566                    }
1567            } while (!$this->startsWith($line, 'thrd1', true, true));
1568
1569        $result_code = $this->parseResult($line, 'THREAD: ');
1570            if ($result_code == self::ERROR_OK) {
1571            $depthmap    = array();
1572            $haschildren = array();
1573            $tree = $this->parseThread($data, 0, strlen($data), null, null, 0, $depthmap, $haschildren);
1574            return array($tree, $depthmap, $haschildren);
1575            }
1576
1577            return false;
1578    }
1579
1580    function search($folder, $criteria, $return_uid=false)
1581    {
1582        $old_sel = $this->selected;
1583
1584            if (!$this->select($folder)) {
1585                return false;
1586            }
1587
1588        // return empty result when folder is empty and we're just after SELECT
1589        if ($old_sel != $folder && !$this->exists) {
1590            return array();
1591            }
1592
1593        $data = '';
1594            $query = 'srch1 ' . ($return_uid ? 'UID ' : '') . 'SEARCH ' . trim($criteria);
1595
1596            if (!$this->putLineC($query)) {
1597            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $query");
1598                    return false;
1599            }
1600
1601        do {
1602                $line = trim($this->readLine());
1603                    if (!$data && preg_match('/^\* SEARCH/', $line)) {
1604                        $data .= substr($line, 8);
1605                } else if (preg_match('/^[0-9 ]+$/', $line)) {
1606                        $data .= $line;
1607                    }
1608        } while (!$this->startsWith($line, 'srch1', true, true));
1609
1610            $result_code = $this->parseResult($line, 'SEARCH: ');
1611            if ($result_code == self::ERROR_OK) {
1612                    return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
1613            }
1614
1615            return false;
1616    }
1617
1618    function move($messages, $from, $to)
1619    {
1620        if (!$from || !$to) {
1621            return -1;
1622        }
1623
1624        $r = $this->copy($messages, $from, $to);
1625
1626        if ($r==0) {
1627            return $this->delete($from, $messages);
1628        }
1629        return $r;
1630    }
1631
1632    function listMailboxes($ref, $mailbox)
1633    {
1634        return $this->_listMailboxes($ref, $mailbox, false);
1635    }
1636
1637    function listSubscribed($ref, $mailbox)
1638    {
1639        return $this->_listMailboxes($ref, $mailbox, true);
1640    }
1641
1642    private function _listMailboxes($ref, $mailbox, $subscribed=false)
1643    {
1644                if (empty($mailbox)) {
1645                $mailbox = '*';
1646            }
1647
1648            if (empty($ref) && $this->rootdir) {
1649                $ref = $this->rootdir;
1650            }
1651
1652        if ($subscribed) {
1653            $key     = 'lsb';
1654            $command = 'LSUB';
1655        }
1656        else {
1657            $key     = 'lmb';
1658            $command = 'LIST';
1659        }
1660
1661        $ref = $this->escape($ref);
1662        $mailbox = $this->escape($mailbox);
1663        $query = $key." ".$command." \"". $ref ."\" \"". $mailbox ."\"";
1664
1665        // send command
1666            if (!$this->putLine($query)) {
1667            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $query");
1668                return false;
1669            }
1670
1671            // get folder list
1672            do {
1673                    $line = $this->readLine(500);
1674                    $line = $this->multLine($line, true);
1675                    $line = trim($line);
1676
1677                    if (preg_match('/^\* '.$command.' \(([^\)]*)\) "*([^"]+)"* (.*)$/', $line, $m)) {
1678                        // folder name
1679                            $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($m[3]));
1680                        // attributes
1681//                      $attrib = explode(' ', $this->unEscape($m[1]));
1682                        // delimiter
1683//                      $delim = $this->unEscape($m[2]);
1684                    }
1685            } while (!$this->startsWith($line, $key, true));
1686
1687            if (is_array($folders)) {
1688            return $folders;
1689            } else if ($this->parseResult($line, $command.': ') == self::ERROR_OK) {
1690            return array();
1691        }
1692
1693        return false;
1694    }
1695
1696    function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
1697    {
1698            if (!$this->select($mailbox)) {
1699                    return false;
1700            }
1701
1702        $result = false;
1703            $parts  = (array) $parts;
1704        $key    = 'fmh0';
1705            $peeks  = '';
1706        $idx    = 0;
1707        $type   = $mime ? 'MIME' : 'HEADER';
1708
1709            // format request
1710            foreach($parts as $part)
1711                    $peeks[] = "BODY.PEEK[$part.$type]";
1712
1713            $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
1714
1715            // send request
1716            if (!$this->putLine($request)) {
1717            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1718                return false;
1719            }
1720
1721            do {
1722                $line = $this->readLine(1024);
1723                $line = $this->multLine($line);
1724
1725                    if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
1726                            $idx = $matches[1];
1727                        $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
1728                        $result[$idx] = trim($result[$idx], '"');
1729                        $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
1730                }
1731            } while (!$this->startsWith($line, $key, true));
1732
1733            return $result;
1734    }
1735
1736    function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
1737    {
1738            $part = empty($part) ? 'HEADER' : $part.'.MIME';
1739
1740        return $this->handlePartBody($mailbox, $id, $is_uid, $part);
1741    }
1742
1743    function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
1744    {
1745        if (!$this->select($mailbox)) {
1746            return false;
1747        }
1748
1749            switch ($encoding) {
1750                    case 'base64':
1751                            $mode = 1;
1752                break;
1753                case 'quoted-printable':
1754                        $mode = 2;
1755                break;
1756                case 'x-uuencode':
1757                    case 'x-uue':
1758                case 'uue':
1759                case 'uuencode':
1760                        $mode = 3;
1761                break;
1762                default:
1763                        $mode = 0;
1764            }
1765
1766        // format request
1767                $reply_key = '* ' . $id;
1768                $key       = 'ftch0';
1769                $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
1770
1771        // send request
1772                if (!$this->putLine($request)) {
1773            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
1774                    return false;
1775                }
1776
1777                // receive reply line
1778                do {
1779                $line = rtrim($this->readLine(1024));
1780                $a    = explode(' ', $line);
1781                } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
1782
1783                $len    = strlen($line);
1784        $result = false;
1785
1786                // handle empty "* X FETCH ()" response
1787        if ($line[$len-1] == ')' && $line[$len-2] != '(') {
1788                // one line response, get everything between first and last quotes
1789                        if (substr($line, -4, 3) == 'NIL') {
1790                                // NIL response
1791                                $result = '';
1792                        } else {
1793                            $from = strpos($line, '"') + 1;
1794                        $to   = strrpos($line, '"');
1795                        $len  = $to - $from;
1796                                $result = substr($line, $from, $len);
1797                        }
1798
1799                if ($mode == 1)
1800                                $result = base64_decode($result);
1801                        else if ($mode == 2)
1802                                $result = quoted_printable_decode($result);
1803                        else if ($mode == 3)
1804                                $result = convert_uudecode($result);
1805
1806        } else if ($line[$len-1] == '}') {
1807                // multi-line request, find sizes of content and receive that many bytes
1808                $from     = strpos($line, '{') + 1;
1809                $to       = strrpos($line, '}');
1810                $len      = $to - $from;
1811                $sizeStr  = substr($line, $from, $len);
1812                $bytes    = (int)$sizeStr;
1813                        $prev     = '';
1814
1815                while ($bytes > 0) {
1816                    $line = $this->readLine(1024);
1817
1818                    if ($line === NULL)
1819                        break;
1820
1821                $len  = strlen($line);
1822
1823                        if ($len > $bytes) {
1824                        $line = substr($line, 0, $bytes);
1825                                        $len = strlen($line);
1826                        }
1827                $bytes -= $len;
1828
1829                        if ($mode == 1) {
1830                                        $line = rtrim($line, "\t\r\n\0\x0B");
1831                                        // create chunks with proper length for base64 decoding
1832                                        $line = $prev.$line;
1833                                        $length = strlen($line);
1834                                        if ($length % 4) {
1835                                                $length = floor($length / 4) * 4;
1836                                                $prev = substr($line, $length);
1837                                                $line = substr($line, 0, $length);
1838                                        }
1839                                        else
1840                                                $prev = '';
1841
1842                                        if ($file)
1843                                                fwrite($file, base64_decode($line));
1844                        else if ($print)
1845                                                echo base64_decode($line);
1846                                        else
1847                                                $result .= base64_decode($line);
1848                                } else if ($mode == 2) {
1849                                        $line = rtrim($line, "\t\r\0\x0B");
1850                                        if ($file)
1851                                                fwrite($file, quoted_printable_decode($line));
1852                        else if ($print)
1853                                                echo quoted_printable_decode($line);
1854                                        else
1855                                                $result .= quoted_printable_decode($line);
1856                                } else if ($mode == 3) {
1857                                        $line = rtrim($line, "\t\r\n\0\x0B");
1858                                        if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
1859                                                continue;
1860                                        if ($file)
1861                                                fwrite($file, convert_uudecode($line));
1862                        else if ($print)
1863                                                echo convert_uudecode($line);
1864                                        else
1865                                                $result .= convert_uudecode($line);
1866                                } else {
1867                                        $line = rtrim($line, "\t\r\n\0\x0B");
1868                                        if ($file)
1869                                                fwrite($file, $line . "\n");
1870                        else if ($print)
1871                                                echo $line . "\n";
1872                                        else
1873                                                $result .= $line . "\n";
1874                                }
1875                }
1876        }
1877
1878        // read in anything up until last line
1879                if (!$end)
1880                        do {
1881                                $line = $this->readLine(1024);
1882                        } while (!$this->startsWith($line, $key, true));
1883
1884                if ($result !== false) {
1885                if ($file) {
1886                        fwrite($file, $result);
1887                        } else if ($print) {
1888                        echo $result;
1889                } else
1890                        return $result;
1891                        return true;
1892                }
1893
1894            return false;
1895    }
1896
1897    function createFolder($folder)
1898    {
1899        $command = 'c CREATE "' . $this->escape($folder) . '"';
1900   
1901            if (!$this->putLine($command)) {
1902            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1903            return false;
1904        }
1905
1906            do {
1907                    $line = $this->readLine(300);
1908            } while (!$this->startsWith($line, 'c ', true, true));
1909
1910            return ($this->parseResult($line, 'CREATE: ') == self::ERROR_OK);
1911    }
1912
1913    function renameFolder($from, $to)
1914    {
1915        $command = 'r RENAME "' . $this->escape($from) . '" "' . $this->escape($to) . '"';
1916   
1917            if (!$this->putLine($command)) {
1918            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1919            return false;
1920        }
1921                do {
1922                    $line = $this->readLine(300);
1923                } while (!$this->startsWith($line, 'r ', true, true));
1924
1925                return ($this->parseResult($line, 'RENAME: ') == self::ERROR_OK);
1926    }
1927
1928    function deleteFolder($folder)
1929    {
1930        $command = 'd DELETE "' . $this->escape($folder). '"';
1931   
1932            if (!$this->putLine($command)) {
1933            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1934            return false;
1935        }
1936            do {
1937                    $line = $this->readLine(300);
1938            } while (!$this->startsWith($line, 'd ', true, true));
1939
1940            return ($this->parseResult($line, 'DELETE: ') == self::ERROR_OK);
1941    }
1942
1943    function clearFolder($folder)
1944    {
1945            $num_in_trash = $this->countMessages($folder);
1946            if ($num_in_trash > 0) {
1947                    $this->delete($folder, '1:*');
1948            }
1949            return ($this->expunge($folder) >= 0);
1950    }
1951
1952    function subscribe($folder)
1953    {
1954            $command = 'sub1 SUBSCRIBE "' . $this->escape($folder). '"';
1955
1956            if (!$this->putLine($command)) {
1957            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1958            return false;
1959        }
1960
1961        $line = trim($this->readLine(512));
1962            return ($this->parseResult($line, 'SUBSCRIBE: ') == self::ERROR_OK);
1963    }
1964
1965    function unsubscribe($folder)
1966    {
1967        $command = 'usub1 UNSUBSCRIBE "' . $this->escape($folder) . '"';
1968
1969            if (!$this->putLine($command)) {
1970            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
1971            return false;
1972        }
1973
1974            $line = trim($this->readLine(512));
1975            return ($this->parseResult($line, 'UNSUBSCRIBE: ') == self::ERROR_OK);
1976    }
1977
1978    function append($folder, &$message)
1979    {
1980            if (!$folder) {
1981                    return false;
1982            }
1983
1984        $message = str_replace("\r", '', $message);
1985            $message = str_replace("\n", "\r\n", $message);
1986
1987        $len = strlen($message);
1988            if (!$len) {
1989                    return false;
1990            }
1991
1992            $request = 'a APPEND "' . $this->escape($folder) .'" (\\Seen) {' . $len . '}';
1993
1994            if ($this->putLine($request)) {
1995                    $line = $this->readLine(512);
1996
1997                if ($line[0] != '+') {
1998                        $this->parseResult($line, 'APPEND: ');
1999                            return false;
2000                }
2001
2002                if (!$this->putLine($message)) {
2003                return false;
2004            }
2005
2006                    do {
2007                            $line = $this->readLine();
2008                } while (!$this->startsWith($line, 'a ', true, true));
2009
2010                return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2011            }
2012        else {
2013            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
2014        }
2015
2016            return false;
2017    }
2018
2019    function appendFromFile($folder, $path, $headers=null)
2020    {
2021            if (!$folder) {
2022                return false;
2023            }
2024
2025            // open message file
2026            $in_fp = false;
2027            if (file_exists(realpath($path))) {
2028                    $in_fp = fopen($path, 'r');
2029            }
2030            if (!$in_fp) {
2031                    $this->set_error(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2032                    return false;
2033            }
2034
2035        $body_separator = "\r\n\r\n";
2036            $len = filesize($path);
2037
2038            if (!$len) {
2039                    return false;
2040            }
2041
2042        if ($headers) {
2043            $headers = preg_replace('/[\r\n]+$/', '', $headers);
2044            $len += strlen($headers) + strlen($body_separator);
2045        }
2046
2047        // send APPEND command
2048            $request    = 'a APPEND "' . $this->escape($folder) . '" (\\Seen) {' . $len . '}';
2049            if ($this->putLine($request)) {
2050                    $line = $this->readLine(512);
2051
2052                    if ($line[0] != '+') {
2053                            $this->parseResult($line, 'APPEND: ');
2054                            return false;
2055                    }
2056
2057            // send headers with body separator
2058            if ($headers) {
2059                            $this->putLine($headers . $body_separator, false);
2060            }
2061
2062                    // send file
2063                    while (!feof($in_fp) && $this->fp) {
2064                            $buffer = fgets($in_fp, 4096);
2065                            $this->putLine($buffer, false);
2066                    }
2067                    fclose($in_fp);
2068
2069                    if (!$this->putLine('')) { // \r\n
2070                return false;
2071            }
2072
2073                    // read response
2074                    do {
2075                            $line = $this->readLine();
2076                    } while (!$this->startsWith($line, 'a ', true, true));
2077
2078                   
2079                    return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2080            }
2081        else {
2082            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $request");
2083        }
2084
2085            return false;
2086    }
2087
2088    function fetchStructureString($folder, $id, $is_uid=false)
2089    {
2090            if (!$this->select($folder)) {
2091            return false;
2092        }
2093
2094                $key = 'F1247';
2095        $result = false;
2096        $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2097
2098                if ($this->putLine($command)) {
2099                        do {
2100                                $line = $this->readLine(5000);
2101                                $line = $this->multLine($line, true);
2102                                if (!preg_match("/^$key/", $line))
2103                                        $result .= $line;
2104                        } while (!$this->startsWith($line, $key, true, true));
2105
2106                        $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2107                }
2108        else {
2109            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
2110        }
2111
2112        return $result;
2113    }
2114
2115    function getQuota()
2116    {
2117        /*
2118         * GETQUOTAROOT "INBOX"
2119         * QUOTAROOT INBOX user/rchijiiwa1
2120         * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2121         * OK Completed
2122         */
2123            $result      = false;
2124            $quota_lines = array();
2125        $command     = 'QUOT1 GETQUOTAROOT "INBOX"';
2126
2127            // get line(s) containing quota info
2128            if ($this->putLine($command)) {
2129                    do {
2130                            $line = rtrim($this->readLine(5000));
2131                            if (preg_match('/^\* QUOTA /', $line)) {
2132                                    $quota_lines[] = $line;
2133                        }
2134                    } while (!$this->startsWith($line, 'QUOT1', true, true));
2135            }
2136        else {
2137            $this->set_error(self::ERROR_COMMAND, "Unable to send command: $command");
2138        }
2139
2140            // return false if not found, parse if found
2141            $min_free = PHP_INT_MAX;
2142            foreach ($quota_lines as $key => $quota_line) {
2143                    $quota_line   = str_replace(array('(', ')'), '', $quota_line);
2144                    $parts        = explode(' ', $quota_line);
2145                    $storage_part = array_search('STORAGE', $parts);
2146
2147                    if (!$storage_part)
2148                continue;
2149
2150                    $used  = intval($parts[$storage_part+1]);
2151                    $total = intval($parts[$storage_part+2]);
2152                    $free  = $total - $used;
2153
2154                    // return lowest available space from all quotas
2155                    if ($free < $min_free) {
2156                        $min_free          = $free;
2157                            $result['used']    = $used;
2158                            $result['total']   = $total;
2159                            $result['percent'] = min(100, round(($used/max(1,$total))*100));
2160                            $result['free']    = 100 - $result['percent'];
2161                    }
2162            }
2163
2164            return $result;
2165    }
2166
2167    private function _xor($string, $string2)
2168    {
2169            $result = '';
2170            $size = strlen($string);
2171            for ($i=0; $i<$size; $i++) {
2172                $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
2173            }
2174            return $result;
2175    }
2176
2177    private function strToTime($date)
2178    {
2179            // support non-standard "GMTXXXX" literal
2180            $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
2181        // if date parsing fails, we have a date in non-rfc format.
2182            // remove token from the end and try again
2183            while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
2184                $d = explode(' ', $date);
2185                    array_pop($d);
2186                    if (!$d) break;
2187                    $date = implode(' ', $d);
2188            }
2189
2190            $ts = (int) $ts;
2191
2192            return $ts < 0 ? 0 : $ts;
2193    }
2194
2195    private function SplitHeaderLine($string)
2196    {
2197            $pos = strpos($string, ':');
2198            if ($pos>0) {
2199                    $res[0] = substr($string, 0, $pos);
2200                    $res[1] = trim(substr($string, $pos+1));
2201                    return $res;
2202            }
2203        return $string;
2204    }
2205
2206    private function parseNamespace($str, &$i, $len=0, $l)
2207    {
2208            if (!$l) {
2209                $str = str_replace('NIL', '()', $str);
2210            }
2211            if (!$len) {
2212                $len = strlen($str);
2213            }
2214            $data      = array();
2215            $in_quotes = false;
2216            $elem      = 0;
2217
2218        for ($i; $i<$len; $i++) {
2219                    $c = (string)$str[$i];
2220                    if ($c == '(' && !$in_quotes) {
2221                            $i++;
2222                            $data[$elem] = $this->parseNamespace($str, $i, $len, $l++);
2223                            $elem++;
2224                    } else if ($c == ')' && !$in_quotes) {
2225                            return $data;
2226                } else if ($c == '\\') {
2227                            $i++;
2228                            if ($in_quotes) {
2229                                    $data[$elem] .= $str[$i];
2230                        }
2231                    } else if ($c == '"') {
2232                            $in_quotes = !$in_quotes;
2233                            if (!$in_quotes) {
2234                                    $elem++;
2235                        }
2236                    } else if ($in_quotes) {
2237                            $data[$elem].=$c;
2238                    }
2239            }
2240
2241        return $data;
2242    }
2243
2244    private function escape($string)
2245    {
2246            return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
2247    }
2248
2249    private function unEscape($string)
2250    {
2251            return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
2252    }
2253
2254}
2255
Note: See TracBrowser for help on using the repository browser.