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

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