source: github/program/include/rcube_imap_generic.php @ 1d51658

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 1d51658 was 1d51658, checked in by alecpl <alec@…>, 3 years ago
  • Parse untagged CAPABILITY response for LOGIN command (#1486742)
  • Property mode set to 100644
File size: 58.8 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            $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, 10);
615            if (!$this->fp) {
616                $this->error    = sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr);
617                $this->errornum = -2;
618                    return false;
619            }
620
621            stream_set_timeout($this->fp, 10);
622            $line = trim(fgets($this->fp, 8192));
623
624            if ($this->prefs['debug_mode'] && $line) {
625                    write_log('imap', 'S: '. $line);
626        }
627
628            // Connected to wrong port or connection error?
629            if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
630                    if ($line)
631                            $this->error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
632                    else
633                            $this->error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
634                $this->errornum = -2;
635                return false;
636            }
637
638            // RFC3501 [7.1] optional CAPABILITY response
639            if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
640                    $this->capability = explode(' ', strtoupper($matches[1]));
641            }
642
643            $this->message .= $line;
644
645            // TLS connection
646            if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
647                if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
648                $this->putLine("tls0 STARTTLS");
649
650                            $line = $this->readLine(4096);
651                if (!$this->startsWith($line, "tls0 OK")) {
652                                    $this->error    = "Server responded to STARTTLS with: $line";
653                                    $this->errornum = -2;
654                    return false;
655                }
656
657                            if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
658                                    $this->error    = "Unable to negotiate TLS";
659                                    $this->errornum = -2;
660                                    return false;
661                            }
662
663                            // Now we're authenticated, capabilities need to be reread
664                            $this->clearCapability();
665                }
666            }
667
668            $orig_method = $auth_method;
669
670            if ($auth_method == 'CHECK') {
671                    // check for supported auth methods
672                    if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
673                            $auth_method = 'AUTH';
674                    }
675                    else {
676                            // default to plain text auth
677                            $auth_method = 'PLAIN';
678                    }
679            }
680
681            if ($auth_method == 'AUTH') {
682                    // do CRAM-MD5 authentication
683                    $this->putLine("a000 AUTHENTICATE CRAM-MD5");
684                    $line = trim($this->readLine(1024));
685
686                    if ($line[0] == '+') {
687                            // got a challenge string, try CRAM-MD5
688                            $result = $this->authenticate($user, $password, substr($line,2));
689
690                            // stop if server sent BYE response
691                            if ($result == -3) {
692                                    return false;
693                            }
694                    }
695
696                    if (!is_resource($result) && $orig_method == 'CHECK') {
697                            $auth_method = 'PLAIN';
698                    }
699            }
700
701            if ($auth_method == 'PLAIN') {
702                    // do plain text auth
703                    $result = $this->login($user, $password);
704            }
705
706            if (is_resource($result)) {
707            if ($this->prefs['force_caps']) {
708                            $this->clearCapability();
709            }
710                    $this->getNamespace();
711            $this->logged = true;
712                    return true;
713            } else {
714                    return false;
715            }
716    }
717
718    function connected()
719    {
720                return ($this->fp && $this->logged) ? true : false;
721    }
722
723    function close()
724    {
725            if ($this->putLine("I LOGOUT")) {
726                    if (!feof($this->fp))
727                            fgets($this->fp, 1024);
728            }
729                @fclose($this->fp);
730                $this->fp = false;
731    }
732
733    function select($mailbox)
734    {
735            if (empty($mailbox)) {
736                    return false;
737            }
738            if ($this->selected == $mailbox) {
739                    return true;
740            }
741
742            if ($this->putLine("sel1 SELECT \"".$this->escape($mailbox).'"')) {
743                    do {
744                            $line = chop($this->readLine(300));
745                            $a = explode(' ', $line);
746                            if (count($a) == 3) {
747                                    $token = strtoupper($a[2]);
748                                    if ($token == 'EXISTS') {
749                                            $this->exists = (int) $a[1];
750                                    }
751                                    else if ($token == 'RECENT') {
752                                            $this->recent = (int) $a[1];
753                                    }
754                            }
755                            else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
756                                    $this->permanentflags = explode(' ', $match[1]);
757                            }
758                    } while (!$this->startsWith($line, 'sel1', true, true));
759
760                    if (strcasecmp($a[1], 'OK') == 0) {
761                            $this->selected = $mailbox;
762                            return true;
763                    }
764            else {
765                $this->error = "Couldn't select $mailbox";
766            }
767            }
768
769        return false;
770    }
771
772    function checkForRecent($mailbox)
773    {
774            if (empty($mailbox)) {
775                    $mailbox = 'INBOX';
776            }
777
778            $this->select($mailbox);
779            if ($this->selected == $mailbox) {
780                    return $this->recent;
781            }
782
783            return false;
784    }
785
786    function countMessages($mailbox, $refresh = false)
787    {
788            if ($refresh) {
789                    $this->selected = '';
790            }
791
792            $this->select($mailbox);
793            if ($this->selected == $mailbox) {
794                    return $this->exists;
795            }
796
797        return false;
798    }
799
800    function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
801    {
802            $field = strtoupper($field);
803            if ($field == 'INTERNALDATE') {
804                $field = 'ARRIVAL';
805            }
806
807            $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
808            'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
809
810            if (!$fields[$field]) {
811                return false;
812            }
813
814            /*  Do "SELECT" command */
815            if (!$this->select($mailbox)) {
816                return false;
817            }
818
819            $is_uid = $is_uid ? 'UID ' : '';
820
821            // message IDs
822            if (is_array($add))
823                    $add = $this->compressMessageSet(join(',', $add));
824
825            $command  = "s ".$is_uid."SORT ($field) $encoding ALL";
826            $line     = $data = '';
827
828            if (!empty($add))
829                $command .= ' '.$add;
830
831            if (!$this->putLineC($command)) {
832                return false;
833            }
834            do {
835                    $line = chop($this->readLine());
836                    if ($this->startsWith($line, '* SORT')) {
837                            $data .= substr($line, 7);
838                } else if (preg_match('/^[0-9 ]+$/', $line)) {
839                            $data .= $line;
840                    }
841            } while (!$this->startsWith($line, 's ', true, true));
842
843            $result_code = $this->parseResult($line);
844
845            if ($result_code != 0) {
846            $this->error = "Sort: $line";
847            return false;
848            }
849
850            return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
851    }
852
853    function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
854    {
855            if (is_array($message_set)) {
856                    if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
857                            return false;
858            } else {
859                    list($from_idx, $to_idx) = explode(':', $message_set);
860                    if (empty($message_set) ||
861                            (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
862                            return false;
863                    }
864            }
865
866            $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
867
868        $fields_a['DATE']         = 1;
869            $fields_a['INTERNALDATE'] = 4;
870        $fields_a['ARRIVAL']      = 4;
871            $fields_a['FROM']         = 1;
872        $fields_a['REPLY-TO']     = 1;
873            $fields_a['SENDER']       = 1;
874        $fields_a['TO']           = 1;
875            $fields_a['CC']           = 1;
876        $fields_a['SUBJECT']      = 1;
877            $fields_a['UID']          = 2;
878        $fields_a['SIZE']         = 2;
879            $fields_a['SEEN']         = 3;
880        $fields_a['RECENT']       = 3;
881            $fields_a['DELETED']      = 3;
882
883        if (!($mode = $fields_a[$index_field])) {
884                return false;
885            }
886
887        /*  Do "SELECT" command */
888            if (!$this->select($mailbox)) {
889                    return false;
890            }
891
892        // build FETCH command string
893            $key     = 'fhi0';
894            $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
895            $deleted = $skip_deleted ? ' FLAGS' : '';
896
897            if ($mode == 1 && $index_field == 'DATE')
898                    $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
899            else if ($mode == 1)
900                    $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
901            else if ($mode == 2) {
902                    if ($index_field == 'SIZE')
903                            $request = " $cmd $message_set (RFC822.SIZE$deleted)";
904                    else
905                            $request = " $cmd $message_set ($index_field$deleted)";
906            } else if ($mode == 3)
907                    $request = " $cmd $message_set (FLAGS)";
908            else // 4
909                    $request = " $cmd $message_set (INTERNALDATE$deleted)";
910
911            $request = $key . $request;
912
913            if (!$this->putLine($request)) {
914                    return false;
915        }
916
917            $result = array();
918
919            do {
920                    $line = chop($this->readLine(200));
921                    $line = $this->multLine($line);
922
923                    if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
924                $id     = $m[1];
925                            $flags  = NULL;
926
927                            if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
928                                    $flags = explode(' ', strtoupper($matches[1]));
929                                    if (in_array('\\DELETED', $flags)) {
930                                            $deleted[$id] = $id;
931                                            continue;
932                                    }
933                            }
934
935                            if ($mode == 1 && $index_field == 'DATE') {
936                                    if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
937                                            $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
938                                            $value = trim($value);
939                                            $result[$id] = $this->strToTime($value);
940                                    }
941                                    // non-existent/empty Date: header, use INTERNALDATE
942                                    if (empty($result[$id])) {
943                                            if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
944                                                    $result[$id] = $this->strToTime($matches[1]);
945                                            else
946                                                    $result[$id] = 0;
947                                    }
948                            } else if ($mode == 1) {
949                                    if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
950                                            $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
951                                            $result[$id] = trim($value);
952                                    } else {
953                                            $result[$id] = '';
954                                    }
955                            } else if ($mode == 2) {
956                                    if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
957                                            $result[$id] = trim($matches[2]);
958                                    } else {
959                                            $result[$id] = 0;
960                                    }
961                            } else if ($mode == 3) {
962                                    if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
963                                            $flags = explode(' ', $matches[1]);
964                                    }
965                                    $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
966                            } else if ($mode == 4) {
967                                    if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
968                                            $result[$id] = $this->strToTime($matches[1]);
969                                    } else {
970                                            $result[$id] = 0;
971                                    }
972                            }
973                    }
974            } while (!$this->startsWith($line, $key, true, true));
975
976            return $result;
977    }
978
979    private function compressMessageSet($message_set)
980    {
981            // given a comma delimited list of independent mid's,
982            // compresses by grouping sequences together
983
984            // if less than 255 bytes long, let's not bother
985            if (strlen($message_set)<255) {
986                return $message_set;
987            }
988
989            // see if it's already been compress
990            if (strpos($message_set, ':') !== false) {
991                return $message_set;
992            }
993
994            // separate, then sort
995            $ids = explode(',', $message_set);
996            sort($ids);
997
998            $result = array();
999            $start  = $prev = $ids[0];
1000
1001            foreach ($ids as $id) {
1002                    $incr = $id - $prev;
1003                    if ($incr > 1) {                    //found a gap
1004                            if ($start == $prev) {
1005                                $result[] = $prev;      //push single id
1006                            } else {
1007                                $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
1008                            }
1009                        $start = $id;                   //start of new sequence
1010                    }
1011                    $prev = $id;
1012            }
1013
1014            // handle the last sequence/id
1015            if ($start==$prev) {
1016                $result[] = $prev;
1017            } else {
1018            $result[] = $start.':'.$prev;
1019            }
1020
1021            // return as comma separated string
1022            return implode(',', $result);
1023    }
1024
1025    function UID2ID($folder, $uid)
1026    {
1027            if ($uid > 0) {
1028                $id_a = $this->search($folder, "UID $uid");
1029                if (is_array($id_a) && count($id_a) == 1) {
1030                        return $id_a[0];
1031                    }
1032            }
1033            return false;
1034    }
1035
1036    function ID2UID($folder, $id)
1037    {
1038            if (empty($id)) {
1039                return  -1;
1040            }
1041
1042        if (!$this->select($folder)) {
1043            return -1;
1044        }
1045
1046            $result = -1;
1047                if ($this->putLine("fuid FETCH $id (UID)")) {
1048                    do {
1049                            $line = chop($this->readLine(1024));
1050                                if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1051                                        $result = $r[1];
1052                                }
1053                        } while (!$this->startsWith($line, 'fuid', true, true));
1054                }
1055
1056        return $result;
1057    }
1058
1059    function fetchUIDs($mailbox, $message_set=null)
1060    {
1061            if (is_array($message_set))
1062                    $message_set = join(',', $message_set);
1063        else if (empty($message_set))
1064                    $message_set = '1:*';
1065
1066            return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1067    }
1068
1069    function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1070    {
1071            $result = array();
1072
1073            if (!$this->select($mailbox)) {
1074                    return false;
1075            }
1076
1077            if (is_array($message_set))
1078                    $message_set = join(',', $message_set);
1079
1080            $message_set = $this->compressMessageSet($message_set);
1081
1082            if ($add)
1083                    $add = ' '.strtoupper(trim($add));
1084
1085            /* FETCH uid, size, flags and headers */
1086            $key          = 'FH12';
1087            $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1088            $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1089            if ($bodystr)
1090                    $request .= "BODYSTRUCTURE ";
1091            $request .= "BODY.PEEK[HEADER.FIELDS ";
1092            $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
1093            $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
1094            $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY ";
1095            $request .= "X-DRAFT-INFO".$add.")])";
1096
1097            if (!$this->putLine($request)) {
1098                    return false;
1099            }
1100            do {
1101                    $line = $this->readLine(1024);
1102                    $line = $this->multLine($line);
1103
1104            if (!$line)
1105                break;
1106
1107                    $a    = explode(' ', $line);
1108
1109                    if (($line[0] == '*') && ($a[2] == 'FETCH')) {
1110                            $id = $a[1];
1111
1112                            $result[$id]            = new rcube_mail_header;
1113                            $result[$id]->id        = $id;
1114                            $result[$id]->subject   = '';
1115                            $result[$id]->messageID = 'mid:' . $id;
1116
1117                            $lines = array();
1118                            $ln = 0;
1119
1120                            // Sample reply line:
1121                            // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1122                            // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1123                            // BODY[HEADER.FIELDS ...
1124
1125                            if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1126                                    $str = $matches[1];
1127
1128                                    // swap parents with quotes, then explode
1129                                    $str = preg_replace('/[()]/', '"', $str);
1130                                    $a = rcube_explode_quoted_string(' ', $str);
1131
1132                                    // did we get the right number of replies?
1133                                    $parts_count = count($a);
1134                                    if ($parts_count>=6) {
1135                                            for ($i=0; $i<$parts_count; $i=$i+2) {
1136                                                    if ($a[$i] == 'UID')
1137                                                            $result[$id]->uid = $a[$i+1];
1138                                                    else if ($a[$i] == 'RFC822.SIZE')
1139                                                            $result[$id]->size = $a[$i+1];
1140                                                else if ($a[$i] == 'INTERNALDATE')
1141                                                        $time_str = $a[$i+1];
1142                                                else if ($a[$i] == 'FLAGS')
1143                                                        $flags_str = $a[$i+1];
1144                                        }
1145
1146                                            $time_str = str_replace('"', '', $time_str);
1147
1148                                            // if time is gmt...
1149                                $time_str = str_replace('GMT','+0000',$time_str);
1150
1151                                            $result[$id]->internaldate = $time_str;
1152                                        $result[$id]->timestamp = $this->StrToTime($time_str);
1153                                        $result[$id]->date = $time_str;
1154                                }
1155
1156                                // BODYSTRUCTURE
1157                                    if($bodystr) {
1158                                            while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1159                                                    $line2 = $this->readLine(1024);
1160                                                $line .= $this->multLine($line2, true);
1161                                        }
1162                                        $result[$id]->body_structure = $m[1];
1163                                }
1164
1165                                // the rest of the result
1166                                preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1167                                $reslines = explode("\n", trim($m[1], '"'));
1168                                // re-parse (see below)
1169                                    foreach ($reslines as $resln) {
1170                                        if (ord($resln[0])<=32) {
1171                                                $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1172                                        } else {
1173                                                $lines[++$ln] = trim($resln);
1174                                            }
1175                                }
1176                        }
1177
1178                                // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1179                                // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1180                                // process the previous line.  Otherwise, we'll keep adding the strings until we come
1181                                // to the next valid header line.
1182
1183                            do {
1184                                    $line = chop($this->readLine(300), "\r\n");
1185
1186                                // The preg_match below works around communigate imap, which outputs " UID <number>)".
1187                                // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1188                                // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1189                                // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1190                                    // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1191                                // An alternative might be:
1192                                // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1193                                // however, unsure how well this would work with all imap clients.
1194                                if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1195                                        break;
1196                                    }
1197
1198                                // handle FLAGS reply after headers (AOL, Zimbra?)
1199                                if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1200                                        $flags_str = $matches[1];
1201                                        break;
1202                                    }
1203
1204                                if (ord($line[0])<=32) {
1205                                        $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1206                                } else {
1207                                        $lines[++$ln] = trim($line);
1208                                    }
1209                        // patch from "Maksim Rubis" <siburny@hotmail.com>
1210                        } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1211
1212                        if (strncmp($line, $key, strlen($key))) {
1213                                // process header, fill rcube_mail_header obj.
1214                                // initialize
1215                                if (is_array($headers)) {
1216                                        reset($headers);
1217                                            while (list($k, $bar) = each($headers)) {
1218                                                $headers[$k] = '';
1219                                        }
1220                                }
1221
1222                                // create array with header field:data
1223                                while ( list($lines_key, $str) = each($lines) ) {
1224                                        list($field, $string) = $this->splitHeaderLine($str);
1225
1226                                        $field  = strtolower($field);
1227                                        $string = preg_replace('/\n\s*/', ' ', $string);
1228
1229                                        switch ($field) {
1230                                        case 'date';
1231                                                $result[$id]->date = $string;
1232                                                $result[$id]->timestamp = $this->strToTime($string);
1233                                        break;
1234                                        case 'from':
1235                                                $result[$id]->from = $string;
1236                                                break;
1237                                        case 'to':
1238                                                $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1239                                                break;
1240                                        case 'subject':
1241                                                $result[$id]->subject = $string;
1242                                                break;
1243                                        case 'reply-to':
1244                                                $result[$id]->replyto = $string;
1245                                                break;
1246                                        case 'cc':
1247                                                $result[$id]->cc = $string;
1248                                                break;
1249                                        case 'bcc':
1250                                                $result[$id]->bcc = $string;
1251                                                break;
1252                                        case 'content-transfer-encoding':
1253                                                $result[$id]->encoding = $string;
1254                                                break;
1255                                        case 'content-type':
1256                                                $ctype_parts = preg_split('/[; ]/', $string);
1257                                                $result[$id]->ctype = array_shift($ctype_parts);
1258                                                if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1259                                                        $result[$id]->charset = $regs[1];
1260                                                }
1261                                                break;
1262                                            case 'in-reply-to':
1263                                                $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
1264                                                break;
1265                                        case 'references':
1266                                                $result[$id]->references = $string;
1267                                                break;
1268                                        case 'return-receipt-to':
1269                                        case 'disposition-notification-to':
1270                                            case 'x-confirm-reading-to':
1271                                                $result[$id]->mdn_to = $string;
1272                                                break;
1273                                        case 'message-id':
1274                                                $result[$id]->messageID = $string;
1275                                                break;
1276                                            case 'x-priority':
1277                                                if (preg_match('/^(\d+)/', $string, $matches))
1278                                                        $result[$id]->priority = intval($matches[1]);
1279                                                break;
1280                                        default:
1281                                                if (strlen($field) > 2)
1282                                                        $result[$id]->others[$field] = $string;
1283                                                    break;
1284                                        } // end switch ()
1285                                } // end while ()
1286                        } else {
1287                                $a = explode(' ', $line);
1288                            }
1289
1290                        // process flags
1291                        if (!empty($flags_str)) {
1292                                $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1293                                $flags_a   = explode(' ', $flags_str);
1294
1295                                    if (is_array($flags_a)) {
1296                                //      reset($flags_a);
1297                                        foreach($flags_a as $flag) {
1298                                                $flag = strtoupper($flag);
1299                                                if ($flag == 'SEEN') {
1300                                                    $result[$id]->seen = true;
1301                                                } else if ($flag == 'DELETED') {
1302                                                    $result[$id]->deleted = true;
1303                                                } else if ($flag == 'RECENT') {
1304                                                    $result[$id]->recent = true;
1305                                                } else if ($flag == 'ANSWERED') {
1306                                                        $result[$id]->answered = true;
1307                                                } else if ($flag == '$FORWARDED') {
1308                                                        $result[$id]->forwarded = true;
1309                                                } else if ($flag == 'DRAFT') {
1310                                                        $result[$id]->is_draft = true;
1311                                                } else if ($flag == '$MDNSENT') {
1312                                                        $result[$id]->mdn_sent = true;
1313                                                } else if ($flag == 'FLAGGED') {
1314                                                         $result[$id]->flagged = true;
1315                                                    }
1316                                        }
1317                                        $result[$id]->flags = $flags_a;
1318                                }
1319                            }
1320                }
1321            } while (!$this->startsWith($line, $key, true));
1322
1323        return $result;
1324    }
1325
1326    function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1327    {
1328            $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1329            if (is_array($a)) {
1330                    return array_shift($a);
1331            }
1332            return false;
1333    }
1334
1335    function sortHeaders($a, $field, $flag)
1336    {
1337            if (empty($field)) {
1338                $field = 'uid';
1339            }
1340        else {
1341            $field = strtolower($field);
1342        }
1343
1344            if ($field == 'date' || $field == 'internaldate') {
1345                $field = 'timestamp';
1346            }
1347        if (empty($flag)) {
1348                $flag = 'ASC';
1349            } else {
1350                $flag = strtoupper($flag);
1351        }
1352
1353            $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1354
1355            $c = count($a);
1356            if ($c > 0) {
1357
1358                        // Strategy:
1359                        // First, we'll create an "index" array.
1360                        // Then, we'll use sort() on that array,
1361                        // and use that to sort the main array.
1362
1363                    // create "index" array
1364                    $index = array();
1365                    reset($a);
1366                    while (list($key, $val) = each($a)) {
1367                            if ($field == 'timestamp') {
1368                                    $data = $this->strToTime($val->date);
1369                                    if (!$data) {
1370                                            $data = $val->timestamp;
1371                        }
1372                            } else {
1373                                    $data = $val->$field;
1374                                    if (is_string($data)) {
1375                                            $data = strtoupper(str_replace($stripArr, '', $data));
1376                        }
1377                            }
1378                        $index[$key]=$data;
1379                }
1380
1381                    // sort index
1382                $i = 0;
1383                if ($flag == 'ASC') {
1384                        asort($index);
1385                } else {
1386                    arsort($index);
1387                    }
1388
1389                // form new array based on index
1390                $result = array();
1391                    reset($index);
1392                while (list($key, $val) = each($index)) {
1393                        $result[$key]=$a[$key];
1394                        $i++;
1395                    }
1396            }
1397
1398            return $result;
1399    }
1400
1401    function expunge($mailbox, $messages=NULL)
1402    {
1403            if (!$this->select($mailbox)) {
1404            return -1;
1405        }
1406
1407        $c = 0;
1408                $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
1409
1410                if (!$this->putLine("exp1 $command")) {
1411            return -1;
1412        }
1413
1414                do {
1415                        $line = $this->readLine(100);
1416                        if ($line[0] == '*') {
1417                $c++;
1418                }
1419                } while (!$this->startsWith($line, 'exp1', true, true));
1420
1421                if ($this->parseResult($line) == 0) {
1422                        $this->selected = ''; // state has changed, need to reselect
1423                        return $c;
1424                }
1425                $this->error = $line;
1426            return -1;
1427    }
1428
1429    function modFlag($mailbox, $messages, $flag, $mod)
1430    {
1431            if ($mod != '+' && $mod != '-') {
1432                return -1;
1433            }
1434
1435            $flag = $this->flags[strtoupper($flag)];
1436
1437            if (!$this->select($mailbox)) {
1438                return -1;
1439            }
1440
1441        $c = 0;
1442            if (!$this->putLine("flg UID STORE $messages {$mod}FLAGS ($flag)")) {
1443            return false;
1444        }
1445
1446            do {
1447                    $line = $this->readLine(1000);
1448                    if ($line[0] == '*') {
1449                        $c++;
1450            }
1451            } while (!$this->startsWith($line, 'flg', true, true));
1452
1453            if ($this->parseResult($line) == 0) {
1454                    return $c;
1455            }
1456
1457            $this->error = $line;
1458            return -1;
1459    }
1460
1461    function flag($mailbox, $messages, $flag) {
1462            return $this->modFlag($mailbox, $messages, $flag, '+');
1463    }
1464
1465    function unflag($mailbox, $messages, $flag) {
1466            return $this->modFlag($mailbox, $messages, $flag, '-');
1467    }
1468
1469    function delete($mailbox, $messages) {
1470            return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1471    }
1472
1473    function copy($messages, $from, $to)
1474    {
1475            if (empty($from) || empty($to)) {
1476                return -1;
1477            }
1478
1479            if (!$this->select($from)) {
1480            return -1;
1481            }
1482
1483        $this->putLine("cpy1 UID COPY $messages \"".$this->escape($to)."\"");
1484            $line = $this->readReply();
1485            return $this->parseResult($line);
1486    }
1487
1488    function countUnseen($folder)
1489    {
1490        $index = $this->search($folder, 'ALL UNSEEN');
1491        if (is_array($index))
1492            return count($index);
1493        return false;
1494    }
1495
1496    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1497    // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1498    // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1499    private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1500    {
1501            $node = array();
1502            if ($str[$begin] != '(') {
1503                    $stop = $begin + strspn($str, "1234567890", $begin, $end - $begin);
1504                    $msg = substr($str, $begin, $stop - $begin);
1505                    if ($msg == 0)
1506                        return $node;
1507                    if (is_null($root))
1508                            $root = $msg;
1509                    $depthmap[$msg] = $depth;
1510                    $haschildren[$msg] = false;
1511                    if (!is_null($parent))
1512                            $haschildren[$parent] = true;
1513                    if ($stop + 1 < $end)
1514                            $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1515                    else
1516                            $node[$msg] = array();
1517            } else {
1518                    $off = $begin;
1519                    while ($off < $end) {
1520                            $start = $off;
1521                        $off++;
1522                        $n = 1;
1523                        while ($n > 0) {
1524                                $p = strpos($str, ')', $off);
1525                                    if ($p === false) {
1526                                            error_log('Mismatched brackets parsing IMAP THREAD response:');
1527                                        error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1528                                        error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1529                                        return $node;
1530                                }
1531                                    $p1 = strpos($str, '(', $off);
1532                                if ($p1 !== false && $p1 < $p) {
1533                                        $off = $p1 + 1;
1534                                        $n++;
1535                                } else {
1536                                        $off = $p + 1;
1537                                            $n--;
1538                                }
1539                        }
1540                        $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1541                    }
1542            }
1543
1544            return $node;
1545    }
1546
1547    function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1548    {
1549            if (!$this->select($folder)) {
1550                    return false;
1551            }
1552
1553        $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1554            $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1555            $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1556
1557            if (!$this->putLineC("thrd1 THREAD $algorithm $encoding $criteria")) {
1558                    return false;
1559            }
1560            do {
1561                    $line = trim($this->readLine(10000));
1562                    if (preg_match('/^\* THREAD/', $line)) {
1563                            $str         = trim(substr($line, 8));
1564                        $depthmap    = array();
1565                        $haschildren = array();
1566                            $tree = $this->parseThread($str, 0, strlen($str), null, null, 0, $depthmap, $haschildren);
1567                    }
1568            } while (!$this->startsWith($line, 'thrd1', true, true));
1569
1570        $result_code = $this->parseResult($line);
1571            if ($result_code == 0) {
1572            return array($tree, $depthmap, $haschildren);
1573            }
1574
1575        $this->error = "Thread: $line";
1576            return false;
1577    }
1578
1579    function search($folder, $criteria, $return_uid=false)
1580    {
1581            if (!$this->select($folder)) {
1582                return false;
1583            }
1584
1585        $data = '';
1586            $query = 'srch1 ' . ($return_uid ? 'UID ' : '') . 'SEARCH ' . chop($criteria);
1587
1588            if (!$this->putLineC($query)) {
1589                    return false;
1590            }
1591
1592        do {
1593                $line = trim($this->readLine());
1594                    if ($this->startsWith($line, '* SEARCH')) {
1595                        $data .= substr($line, 8);
1596                } else if (preg_match('/^[0-9 ]+$/', $line)) {
1597                        $data .= $line;
1598                    }
1599        } while (!$this->startsWith($line, 'srch1', true, true));
1600
1601            $result_code = $this->parseResult($line);
1602            if ($result_code == 0) {
1603                    return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
1604            }
1605
1606        $this->error = "Search: $line";
1607            return false;
1608    }
1609
1610    function move($messages, $from, $to)
1611    {
1612        if (!$from || !$to) {
1613            return -1;
1614        }
1615
1616        $r = $this->copy($messages, $from, $to);
1617
1618        if ($r==0) {
1619            return $this->delete($from, $messages);
1620        }
1621        return $r;
1622    }
1623
1624    function listMailboxes($ref, $mailbox)
1625    {
1626        return $this->_listMailboxes($ref, $mailbox, false);
1627    }
1628
1629    function listSubscribed($ref, $mailbox)
1630    {
1631        return $this->_listMailboxes($ref, $mailbox, true);
1632    }
1633
1634    private function _listMailboxes($ref, $mailbox, $subscribed=false)
1635    {
1636                if (empty($mailbox)) {
1637                $mailbox = '*';
1638            }
1639
1640            if (empty($ref) && $this->rootdir) {
1641                $ref = $this->rootdir;
1642            }
1643
1644        if ($subscribed) {
1645            $key     = 'lsb';
1646            $command = 'LSUB';
1647        }
1648        else {
1649            $key     = 'lmb';
1650            $command = 'LIST';
1651        }
1652
1653        // send command
1654            if (!$this->putLine($key." ".$command." \"". $this->escape($ref) ."\" \"". $this->escape($mailbox) ."\"")) {
1655                    $this->error = "Couldn't send $command command";
1656                return false;
1657            }
1658
1659            // get folder list
1660            do {
1661                    $line = $this->readLine(500);
1662                    $line = $this->multLine($line, true);
1663                    $a    = explode(' ', $line);
1664
1665                    if (($line[0] == '*') && ($a[1] == $command)) {
1666                            $line = rtrim($line);
1667                        // split one line
1668                            $a = rcube_explode_quoted_string(' ', $line);
1669                        // last string is folder name
1670                            $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($a[count($a)-1]));
1671                        // second from last is delimiter
1672                        $delim = trim($a[count($a)-2], '"');
1673                    }
1674            } while (!$this->startsWith($line, $key, true));
1675
1676            if (is_array($folders)) {
1677            return $folders;
1678            } else if ($this->parseResult($line) == 0) {
1679            return array();
1680        }
1681
1682            $this->error = $line;
1683        return false;
1684    }
1685
1686    function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
1687    {
1688            if (!$this->select($mailbox)) {
1689                    return false;
1690            }
1691
1692        $result = false;
1693            $parts  = (array) $parts;
1694        $key    = 'fmh0';
1695            $peeks  = '';
1696        $idx    = 0;
1697        $type   = $mime ? 'MIME' : 'HEADER';
1698
1699            // format request
1700            foreach($parts as $part)
1701                    $peeks[] = "BODY.PEEK[$part.$type]";
1702
1703            $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
1704
1705            // send request
1706            if (!$this->putLine($request)) {
1707                return false;
1708            }
1709
1710            do {
1711                $line = $this->readLine(1000);
1712                $line = $this->multLine($line);
1713
1714                    if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
1715                            $idx = $matches[1];
1716                        $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
1717                        $result[$idx] = trim($result[$idx], '"');
1718                        $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
1719                }
1720            } while (!$this->startsWith($line, $key, true));
1721
1722            return $result;
1723    }
1724
1725    function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
1726    {
1727            $part = empty($part) ? 'HEADER' : $part.'.MIME';
1728
1729        return $this->handlePartBody($mailbox, $id, $is_uid, $part);
1730    }
1731
1732    function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
1733    {
1734        if (!$this->select($mailbox)) {
1735            return false;
1736        }
1737
1738            switch ($encoding) {
1739                    case 'base64':
1740                            $mode = 1;
1741                break;
1742                case 'quoted-printable':
1743                        $mode = 2;
1744                break;
1745                case 'x-uuencode':
1746                    case 'x-uue':
1747                case 'uue':
1748                case 'uuencode':
1749                        $mode = 3;
1750                break;
1751                default:
1752                        $mode = 0;
1753            }
1754
1755                $reply_key = '* ' . $id;
1756        $result = false;
1757
1758        // format request
1759                $key     = 'ftch0';
1760                $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
1761        // send request
1762                if (!$this->putLine($request)) {
1763                    return false;
1764                }
1765
1766                // receive reply line
1767                do {
1768                $line = chop($this->readLine(1000));
1769                $a    = explode(' ', $line);
1770                } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
1771
1772                $len = strlen($line);
1773
1774                // handle empty "* X FETCH ()" response
1775        if ($line[$len-1] == ')' && $line[$len-2] != '(') {
1776                // one line response, get everything between first and last quotes
1777                        if (substr($line, -4, 3) == 'NIL') {
1778                                // NIL response
1779                                $result = '';
1780                        } else {
1781                            $from = strpos($line, '"') + 1;
1782                        $to   = strrpos($line, '"');
1783                        $len  = $to - $from;
1784                                $result = substr($line, $from, $len);
1785                        }
1786
1787                if ($mode == 1)
1788                                $result = base64_decode($result);
1789                        else if ($mode == 2)
1790                                $result = quoted_printable_decode($result);
1791                        else if ($mode == 3)
1792                                $result = convert_uudecode($result);
1793
1794        } else if ($line[$len-1] == '}') {
1795                // multi-line request, find sizes of content and receive that many bytes
1796                $from     = strpos($line, '{') + 1;
1797                $to       = strrpos($line, '}');
1798                $len      = $to - $from;
1799                $sizeStr  = substr($line, $from, $len);
1800                $bytes    = (int)$sizeStr;
1801                        $prev     = '';
1802
1803                while ($bytes > 0) {
1804                    $line = $this->readLine(1024);
1805                $len  = strlen($line);
1806
1807                        if ($len > $bytes) {
1808                        $line = substr($line, 0, $bytes);
1809                                        $len = strlen($line);
1810                        }
1811                $bytes -= $len;
1812
1813                        if ($mode == 1) {
1814                                        $line = rtrim($line, "\t\r\n\0\x0B");
1815                                        // create chunks with proper length for base64 decoding
1816                                        $line = $prev.$line;
1817                                        $length = strlen($line);
1818                                        if ($length % 4) {
1819                                                $length = floor($length / 4) * 4;
1820                                                $prev = substr($line, $length);
1821                                                $line = substr($line, 0, $length);
1822                                        }
1823                                        else
1824                                                $prev = '';
1825
1826                                        if ($file)
1827                                                fwrite($file, base64_decode($line));
1828                        else if ($print)
1829                                                echo base64_decode($line);
1830                                        else
1831                                                $result .= base64_decode($line);
1832                                } else if ($mode == 2) {
1833                                        $line = rtrim($line, "\t\r\0\x0B");
1834                                        if ($file)
1835                                                fwrite($file, quoted_printable_decode($line));
1836                        else if ($print)
1837                                                echo quoted_printable_decode($line);
1838                                        else
1839                                                $result .= quoted_printable_decode($line);
1840                                } else if ($mode == 3) {
1841                                        $line = rtrim($line, "\t\r\n\0\x0B");
1842                                        if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
1843                                                continue;
1844                                        if ($file)
1845                                                fwrite($file, convert_uudecode($line));
1846                        else if ($print)
1847                                                echo convert_uudecode($line);
1848                                        else
1849                                                $result .= convert_uudecode($line);
1850                                } else {
1851                                        $line = rtrim($line, "\t\r\n\0\x0B");
1852                                        if ($file)
1853                                                fwrite($file, $line . "\n");
1854                        else if ($print)
1855                                                echo $line . "\n";
1856                                        else
1857                                                $result .= $line . "\n";
1858                                }
1859                }
1860        }
1861
1862        // read in anything up until last line
1863                if (!$end)
1864                        do {
1865                                $line = $this->readLine(1024);
1866                        } while (!$this->startsWith($line, $key, true));
1867
1868                if ($result) {
1869                if ($file) {
1870                        fwrite($file, $result);
1871                        } else if ($print) {
1872                        echo $result;
1873                } else
1874                        return $result;
1875                        return true;
1876                }
1877
1878            return false;
1879    }
1880
1881    function createFolder($folder)
1882    {
1883            if ($this->putLine('c CREATE "' . $this->escape($folder) . '"')) {
1884                    do {
1885                            $line = $this->readLine(300);
1886                    } while (!$this->startsWith($line, 'c ', true, true));
1887                    return ($this->parseResult($line) == 0);
1888            }
1889            return false;
1890    }
1891
1892    function renameFolder($from, $to)
1893    {
1894            if ($this->putLine('r RENAME "' . $this->escape($from) . '" "' . $this->escape($to) . '"')) {
1895                    do {
1896                            $line = $this->readLine(300);
1897                    } while (!$this->startsWith($line, 'r ', true, true));
1898                    return ($this->parseResult($line) == 0);
1899            }
1900            return false;
1901    }
1902
1903    function deleteFolder($folder)
1904    {
1905            if ($this->putLine('d DELETE "' . $this->escape($folder). '"')) {
1906                    do {
1907                            $line = $this->readLine(300);
1908                    } while (!$this->startsWith($line, 'd ', true, true));
1909                    return ($this->parseResult($line) == 0);
1910            }
1911            return false;
1912    }
1913
1914    function clearFolder($folder)
1915    {
1916            $num_in_trash = $this->countMessages($folder);
1917            if ($num_in_trash > 0) {
1918                    $this->delete($folder, '1:*');
1919            }
1920            return ($this->expunge($folder) >= 0);
1921    }
1922
1923    function subscribe($folder)
1924    {
1925            $query = 'sub1 SUBSCRIBE "' . $this->escape($folder). '"';
1926            $this->putLine($query);
1927
1928        $line = trim($this->readLine(512));
1929            return ($this->parseResult($line) == 0);
1930    }
1931
1932    function unsubscribe($folder)
1933    {
1934        $query = 'usub1 UNSUBSCRIBE "' . $this->escape($folder) . '"';
1935            $this->putLine($query);
1936
1937            $line = trim($this->readLine(512));
1938            return ($this->parseResult($line) == 0);
1939    }
1940
1941    function append($folder, &$message)
1942    {
1943            if (!$folder) {
1944                    return false;
1945            }
1946
1947        $message = str_replace("\r", '', $message);
1948            $message = str_replace("\n", "\r\n", $message);
1949
1950        $len = strlen($message);
1951            if (!$len) {
1952                    return false;
1953            }
1954
1955            $request = 'a APPEND "' . $this->escape($folder) .'" (\\Seen) {' . $len . '}';
1956
1957            if ($this->putLine($request)) {
1958                    $line = $this->readLine(512);
1959
1960                if ($line[0] != '+') {
1961                        // $errornum = $this->parseResult($line);
1962                        $this->error = "Cannot write to folder: $line";
1963                            return false;
1964                }
1965
1966                if (!$this->putLine($message)) {
1967                return false;
1968            }
1969
1970                    do {
1971                            $line = $this->readLine();
1972                } while (!$this->startsWith($line, 'a ', true, true));
1973
1974                $result = ($this->parseResult($line) == 0);
1975                    if (!$result) {
1976                        $this->error = $line;
1977                    }
1978                return $result;
1979            }
1980
1981            $this->error = "Couldn't send command \"$request\"";
1982            return false;
1983    }
1984
1985    function appendFromFile($folder, $path, $headers=null, $separator="\n\n")
1986    {
1987            if (!$folder) {
1988                return false;
1989            }
1990
1991            // open message file
1992            $in_fp = false;
1993            if (file_exists(realpath($path))) {
1994                    $in_fp = fopen($path, 'r');
1995            }
1996            if (!$in_fp) {
1997                    $this->error = "Couldn't open $path for reading";
1998                    return false;
1999            }
2000
2001            $len = filesize($path);
2002            if (!$len) {
2003                    return false;
2004            }
2005
2006        if ($headers) {
2007            $headers = preg_replace('/[\r\n]+$/', '', $headers);
2008            $len += strlen($headers) + strlen($separator);
2009        }
2010
2011        // send APPEND command
2012            $request    = 'a APPEND "' . $this->escape($folder) . '" (\\Seen) {' . $len . '}';
2013            if ($this->putLine($request)) {
2014                    $line = $this->readLine(512);
2015
2016                    if ($line[0] != '+') {
2017                            //$errornum = $this->parseResult($line);
2018                            $this->error = "Cannot write to folder: $line";
2019                            return false;
2020                    }
2021
2022            // send headers with body separator
2023            if ($headers) {
2024                            $this->putLine($headers . $separator, false);
2025            }
2026
2027                    // send file
2028                    while (!feof($in_fp) && $this->fp) {
2029                            $buffer = fgets($in_fp, 4096);
2030                            $this->putLine($buffer, false);
2031                    }
2032                    fclose($in_fp);
2033
2034                    if (!$this->putLine('')) { // \r\n
2035                return false;
2036            }
2037
2038                    // read response
2039                    do {
2040                            $line = $this->readLine();
2041                    } while (!$this->startsWith($line, 'a ', true, true));
2042
2043                    $result = ($this->parseResult($line) == 0);
2044                    if (!$result) {
2045                        $this->error = $line;
2046                    }
2047
2048                    return $result;
2049            }
2050
2051        $this->error = "Couldn't send command \"$request\"";
2052            return false;
2053    }
2054
2055    function fetchStructureString($folder, $id, $is_uid=false)
2056    {
2057            if (!$this->select($folder)) {
2058            return false;
2059        }
2060
2061                $key = 'F1247';
2062        $result = false;
2063
2064                if ($this->putLine($key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
2065                        do {
2066                                $line = $this->readLine(5000);
2067                                $line = $this->multLine($line, true);
2068                                if (!preg_match("/^$key/", $line))
2069                                        $result .= $line;
2070                        } while (!$this->startsWith($line, $key, true, true));
2071
2072                        $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2073                }
2074
2075        return $result;
2076    }
2077
2078    function getQuota()
2079    {
2080        /*
2081         * GETQUOTAROOT "INBOX"
2082         * QUOTAROOT INBOX user/rchijiiwa1
2083         * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2084         * OK Completed
2085         */
2086            $result      = false;
2087            $quota_lines = array();
2088
2089            // get line(s) containing quota info
2090            if ($this->putLine('QUOT1 GETQUOTAROOT "INBOX"')) {
2091                    do {
2092                            $line = chop($this->readLine(5000));
2093                            if ($this->startsWith($line, '* QUOTA ')) {
2094                                    $quota_lines[] = $line;
2095                        }
2096                    } while (!$this->startsWith($line, 'QUOT1', true, true));
2097            }
2098
2099            // return false if not found, parse if found
2100            $min_free = PHP_INT_MAX;
2101            foreach ($quota_lines as $key => $quota_line) {
2102                    $quota_line   = preg_replace('/[()]/', '', $quota_line);
2103                    $parts        = explode(' ', $quota_line);
2104                    $storage_part = array_search('STORAGE', $parts);
2105
2106                    if (!$storage_part)
2107                continue;
2108
2109                    $used  = intval($parts[$storage_part+1]);
2110                    $total = intval($parts[$storage_part+2]);
2111                    $free  = $total - $used;
2112
2113                    // return lowest available space from all quotas
2114                    if ($free < $min_free) {
2115                        $min_free          = $free;
2116                            $result['used']    = $used;
2117                            $result['total']   = $total;
2118                            $result['percent'] = min(100, round(($used/max(1,$total))*100));
2119                            $result['free']    = 100 - $result['percent'];
2120                    }
2121            }
2122
2123            return $result;
2124    }
2125
2126    private function _xor($string, $string2)
2127    {
2128            $result = '';
2129            $size = strlen($string);
2130            for ($i=0; $i<$size; $i++) {
2131                $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
2132            }
2133            return $result;
2134    }
2135
2136    private function strToTime($date)
2137    {
2138            // support non-standard "GMTXXXX" literal
2139            $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
2140        // if date parsing fails, we have a date in non-rfc format.
2141            // remove token from the end and try again
2142            while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
2143                $d = explode(' ', $date);
2144                    array_pop($d);
2145                    if (!$d) break;
2146                    $date = implode(' ', $d);
2147            }
2148
2149            $ts = (int) $ts;
2150
2151            return $ts < 0 ? 0 : $ts;
2152    }
2153
2154    private function SplitHeaderLine($string)
2155    {
2156            $pos = strpos($string, ':');
2157            if ($pos>0) {
2158                    $res[0] = substr($string, 0, $pos);
2159                    $res[1] = trim(substr($string, $pos+1));
2160                    return $res;
2161            }
2162        return $string;
2163    }
2164
2165    private function parseNamespace($str, &$i, $len=0, $l)
2166    {
2167            if (!$l) {
2168                $str = str_replace('NIL', '()', $str);
2169            }
2170            if (!$len) {
2171                $len = strlen($str);
2172            }
2173            $data      = array();
2174            $in_quotes = false;
2175            $elem      = 0;
2176
2177        for ($i;$i<$len;$i++) {
2178                    $c = (string)$str[$i];
2179                    if ($c == '(' && !$in_quotes) {
2180                            $i++;
2181                            $data[$elem] = $this->parseNamespace($str, $i, $len, $l++);
2182                            $elem++;
2183                    } else if ($c == ')' && !$in_quotes) {
2184                            return $data;
2185                } else if ($c == '\\') {
2186                            $i++;
2187                            if ($in_quotes) {
2188                                    $data[$elem] .= $c.$str[$i];
2189                        }
2190                    } else if ($c == '"') {
2191                            $in_quotes = !$in_quotes;
2192                            if (!$in_quotes) {
2193                                    $elem++;
2194                        }
2195                    } else if ($in_quotes) {
2196                            $data[$elem].=$c;
2197                    }
2198            }
2199
2200        return $data;
2201    }
2202
2203    private function escape($string)
2204    {
2205            return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
2206    }
2207
2208    private function unEscape($string)
2209    {
2210            return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
2211    }
2212
2213}
2214
2215?>
Note: See TracBrowser for help on using the repository browser.