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

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