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

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