source: github/program/include/rcube_imap_generic.php @ c09e328

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since c09e328 was c09e328, checked in by alecpl <alec@…>, 2 years ago
  • Remove unused rcube_mail_header class variables
  • Property mode set to 100644
File size: 105.7 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            for ($i=0, $len=count($items); $i<$len; $i += 2) {
957                $result[$items[$i]] = (int) $items[$i+1];
958            }
959
960            $this->data['STATUS:'.$mailbox] = $result;
961
962            return $result;
963        }
964
965        return false;
966    }
967
968    /**
969     * Executes EXPUNGE command
970     *
971     * @param string $mailbox  Mailbox name
972     * @param string $messages Message UIDs to expunge
973     *
974     * @return boolean True on success, False on error
975     * @access public
976     */
977    function expunge($mailbox, $messages=NULL)
978    {
979        if (!$this->select($mailbox)) {
980            return false;
981        }
982
983        if (!$this->data['READ-WRITE']) {
984            $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'EXPUNGE');
985            return false;
986        }
987
988        // Clear internal status cache
989        unset($this->data['STATUS:'.$mailbox]);
990
991        if ($messages)
992            $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
993        else
994            $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
995
996        if ($result == self::ERROR_OK) {
997            $this->selected = ''; // state has changed, need to reselect
998            return true;
999        }
1000
1001        return false;
1002    }
1003
1004    /**
1005     * Executes CLOSE command
1006     *
1007     * @return boolean True on success, False on error
1008     * @access public
1009     * @since 0.5
1010     */
1011    function close()
1012    {
1013        $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
1014
1015        if ($result == self::ERROR_OK) {
1016            $this->selected = '';
1017            return true;
1018        }
1019
1020        return false;
1021    }
1022
1023    /**
1024     * Executes SUBSCRIBE command
1025     *
1026     * @param string $mailbox Mailbox name
1027     *
1028     * @return boolean True on success, False on error
1029     * @access public
1030     */
1031    function subscribe($mailbox)
1032    {
1033        $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
1034            self::COMMAND_NORESPONSE);
1035
1036        return ($result == self::ERROR_OK);
1037    }
1038
1039    /**
1040     * Executes UNSUBSCRIBE command
1041     *
1042     * @param string $mailbox Mailbox name
1043     *
1044     * @return boolean True on success, False on error
1045     * @access public
1046     */
1047    function unsubscribe($mailbox)
1048    {
1049        $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
1050            self::COMMAND_NORESPONSE);
1051
1052        return ($result == self::ERROR_OK);
1053    }
1054
1055    /**
1056     * Executes DELETE command
1057     *
1058     * @param string $mailbox Mailbox name
1059     *
1060     * @return boolean True on success, False on error
1061     * @access public
1062     */
1063    function deleteFolder($mailbox)
1064    {
1065        $result = $this->execute('DELETE', array($this->escape($mailbox)),
1066            self::COMMAND_NORESPONSE);
1067
1068        return ($result == self::ERROR_OK);
1069    }
1070
1071    /**
1072     * Removes all messages in a folder
1073     *
1074     * @param string $mailbox Mailbox name
1075     *
1076     * @return boolean True on success, False on error
1077     * @access public
1078     */
1079    function clearFolder($mailbox)
1080    {
1081        $num_in_trash = $this->countMessages($mailbox);
1082        if ($num_in_trash > 0) {
1083            $res = $this->delete($mailbox, '1:*');
1084        }
1085
1086        if ($res) {
1087            if ($this->selected == $mailbox)
1088                $res = $this->close();
1089            else
1090                $res = $this->expunge($mailbox);
1091        }
1092
1093        return $res;
1094    }
1095
1096    /**
1097     * Returns count of all messages in a folder
1098     *
1099     * @param string $mailbox Mailbox name
1100     *
1101     * @return int Number of messages, False on error
1102     * @access public
1103     */
1104    function countMessages($mailbox, $refresh = false)
1105    {
1106        if ($refresh) {
1107            $this->selected = '';
1108        }
1109
1110        if ($this->selected == $mailbox) {
1111            return $this->data['EXISTS'];
1112        }
1113
1114        // Check internal cache
1115        $cache = $this->data['STATUS:'.$mailbox];
1116        if (!empty($cache) && isset($cache['MESSAGES'])) {
1117            return (int) $cache['MESSAGES'];
1118        }
1119
1120        // Try STATUS (should be faster than SELECT)
1121        $counts = $this->status($mailbox);
1122        if (is_array($counts)) {
1123            return (int) $counts['MESSAGES'];
1124        }
1125
1126        return false;
1127    }
1128
1129    /**
1130     * Returns count of messages with \Recent flag in a folder
1131     *
1132     * @param string $mailbox Mailbox name
1133     *
1134     * @return int Number of messages, False on error
1135     * @access public
1136     */
1137    function countRecent($mailbox)
1138    {
1139        if (!strlen($mailbox)) {
1140            $mailbox = 'INBOX';
1141        }
1142
1143        $this->select($mailbox);
1144
1145        if ($this->selected == $mailbox) {
1146            return $this->data['RECENT'];
1147        }
1148
1149        return false;
1150    }
1151
1152    /**
1153     * Returns count of messages without \Seen flag in a specified folder
1154     *
1155     * @param string $mailbox Mailbox name
1156     *
1157     * @return int Number of messages, False on error
1158     * @access public
1159     */
1160    function countUnseen($mailbox)
1161    {
1162        // Check internal cache
1163        $cache = $this->data['STATUS:'.$mailbox];
1164        if (!empty($cache) && isset($cache['UNSEEN'])) {
1165            return (int) $cache['UNSEEN'];
1166        }
1167
1168        // Try STATUS (should be faster than SELECT+SEARCH)
1169        $counts = $this->status($mailbox);
1170        if (is_array($counts)) {
1171            return (int) $counts['UNSEEN'];
1172        }
1173
1174        // Invoke SEARCH as a fallback
1175        $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1176        if (is_array($index)) {
1177            return (int) $index['COUNT'];
1178        }
1179
1180        return false;
1181    }
1182
1183    /**
1184     * Executes ID command (RFC2971)
1185     *
1186     * @param array $items Client identification information key/value hash
1187     *
1188     * @return array Server identification information key/value hash
1189     * @access public
1190     * @since 0.6
1191     */
1192    function id($items=array())
1193    {
1194        if (is_array($items) && !empty($items)) {
1195            foreach ($items as $key => $value) {
1196                $args[] = $this->escape($key);
1197                $args[] = $this->escape($value);
1198            }
1199        }
1200
1201        list($code, $response) = $this->execute('ID', array(
1202            !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1203        ));
1204
1205
1206        if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
1207            $response = substr($response, 5); // remove prefix "* ID "
1208            $items    = $this->tokenizeResponse($response);
1209            $result   = null;
1210
1211            for ($i=0, $len=count($items); $i<$len; $i += 2) {
1212                $result[$items[$i]] = $items[$i+1];
1213            }
1214
1215            return $result;
1216        }
1217
1218        return false;
1219    }
1220
1221    function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
1222    {
1223        $field = strtoupper($field);
1224        if ($field == 'INTERNALDATE') {
1225            $field = 'ARRIVAL';
1226        }
1227
1228        $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
1229            'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
1230
1231        if (!$fields[$field]) {
1232            return false;
1233        }
1234
1235        if (!$this->select($mailbox)) {
1236            return false;
1237        }
1238
1239        // message IDs
1240        if (!empty($add))
1241            $add = $this->compressMessageSet($add);
1242
1243        list($code, $response) = $this->execute($is_uid ? 'UID SORT' : 'SORT',
1244            array("($field)", $encoding, 'ALL' . (!empty($add) ? ' '.$add : '')));
1245
1246        if ($code == self::ERROR_OK) {
1247            // remove prefix and unilateral untagged server responses
1248            $response = substr($response, stripos($response, '* SORT') + 7);
1249            if ($pos = strpos($response, '*')) {
1250                $response = substr($response, 0, $pos);
1251            }
1252            return preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
1253        }
1254
1255        return false;
1256    }
1257
1258    function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
1259    {
1260        if (is_array($message_set)) {
1261            if (!($message_set = $this->compressMessageSet($message_set)))
1262                return false;
1263        } else {
1264            list($from_idx, $to_idx) = explode(':', $message_set);
1265            if (empty($message_set) ||
1266                (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
1267                return false;
1268            }
1269        }
1270
1271        $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1272
1273        $fields_a['DATE']         = 1;
1274        $fields_a['INTERNALDATE'] = 4;
1275        $fields_a['ARRIVAL']      = 4;
1276        $fields_a['FROM']         = 1;
1277        $fields_a['REPLY-TO']     = 1;
1278        $fields_a['SENDER']       = 1;
1279        $fields_a['TO']           = 1;
1280        $fields_a['CC']           = 1;
1281        $fields_a['SUBJECT']      = 1;
1282        $fields_a['UID']          = 2;
1283        $fields_a['SIZE']         = 2;
1284        $fields_a['SEEN']         = 3;
1285        $fields_a['RECENT']       = 3;
1286        $fields_a['DELETED']      = 3;
1287
1288        if (!($mode = $fields_a[$index_field])) {
1289            return false;
1290        }
1291
1292        /*  Do "SELECT" command */
1293        if (!$this->select($mailbox)) {
1294            return false;
1295        }
1296
1297        // build FETCH command string
1298        $key     = $this->nextTag();
1299        $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
1300        $deleted = $skip_deleted ? ' FLAGS' : '';
1301
1302        if ($mode == 1 && $index_field == 'DATE')
1303            $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
1304        else if ($mode == 1)
1305            $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
1306        else if ($mode == 2) {
1307            if ($index_field == 'SIZE')
1308                $request = " $cmd $message_set (RFC822.SIZE$deleted)";
1309            else
1310                $request = " $cmd $message_set ($index_field$deleted)";
1311        } else if ($mode == 3)
1312            $request = " $cmd $message_set (FLAGS)";
1313        else // 4
1314            $request = " $cmd $message_set (INTERNALDATE$deleted)";
1315
1316        $request = $key . $request;
1317
1318        if (!$this->putLine($request)) {
1319            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1320            return false;
1321        }
1322
1323        $result = array();
1324
1325        do {
1326            $line = rtrim($this->readLine(200));
1327            $line = $this->multLine($line);
1328
1329            if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1330                $id     = $m[1];
1331                $flags  = NULL;
1332
1333                if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1334                    $flags = explode(' ', strtoupper($matches[1]));
1335                    if (in_array('\\DELETED', $flags)) {
1336                        $deleted[$id] = $id;
1337                        continue;
1338                    }
1339                }
1340
1341                if ($mode == 1 && $index_field == 'DATE') {
1342                    if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
1343                        $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
1344                        $value = trim($value);
1345                        $result[$id] = $this->strToTime($value);
1346                    }
1347                    // non-existent/empty Date: header, use INTERNALDATE
1348                    if (empty($result[$id])) {
1349                        if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
1350                            $result[$id] = $this->strToTime($matches[1]);
1351                        else
1352                            $result[$id] = 0;
1353                    }
1354                } else if ($mode == 1) {
1355                    if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
1356                        $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
1357                        $result[$id] = trim($value);
1358                    } else {
1359                        $result[$id] = '';
1360                    }
1361                } else if ($mode == 2) {
1362                    if (preg_match('/(UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1363                        $result[$id] = trim($matches[2]);
1364                    } else {
1365                        $result[$id] = 0;
1366                    }
1367                } else if ($mode == 3) {
1368                    if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1369                        $flags = explode(' ', $matches[1]);
1370                    }
1371                    $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1372                } else if ($mode == 4) {
1373                    if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1374                        $result[$id] = $this->strToTime($matches[1]);
1375                    } else {
1376                        $result[$id] = 0;
1377                    }
1378                }
1379            }
1380        } while (!$this->startsWith($line, $key, true, true));
1381
1382        return $result;
1383    }
1384
1385    static function compressMessageSet($messages, $force=false)
1386    {
1387        // given a comma delimited list of independent mid's,
1388        // compresses by grouping sequences together
1389
1390        if (!is_array($messages)) {
1391            // if less than 255 bytes long, let's not bother
1392            if (!$force && strlen($messages)<255) {
1393                return $messages;
1394           }
1395
1396            // see if it's already been compressed
1397            if (strpos($messages, ':') !== false) {
1398                return $messages;
1399            }
1400
1401            // separate, then sort
1402            $messages = explode(',', $messages);
1403        }
1404
1405        sort($messages);
1406
1407        $result = array();
1408        $start  = $prev = $messages[0];
1409
1410        foreach ($messages as $id) {
1411            $incr = $id - $prev;
1412            if ($incr > 1) { // found a gap
1413                if ($start == $prev) {
1414                    $result[] = $prev; // push single id
1415                } else {
1416                    $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
1417                }
1418                $start = $id; // start of new sequence
1419            }
1420            $prev = $id;
1421        }
1422
1423        // handle the last sequence/id
1424        if ($start == $prev) {
1425            $result[] = $prev;
1426        } else {
1427            $result[] = $start.':'.$prev;
1428        }
1429
1430        // return as comma separated string
1431        return implode(',', $result);
1432    }
1433
1434    static function uncompressMessageSet($messages)
1435    {
1436        $result   = array();
1437        $messages = explode(',', $messages);
1438
1439        foreach ($messages as $part) {
1440            $items = explode(':', $part);
1441            $max   = max($items[0], $items[1]);
1442
1443            for ($x=$items[0]; $x<=$max; $x++) {
1444                $result[] = $x;
1445            }
1446        }
1447
1448        return $result;
1449    }
1450
1451    /**
1452     * Returns message sequence identifier
1453     *
1454     * @param string $mailbox Mailbox name
1455     * @param int    $uid     Message unique identifier (UID)
1456     *
1457     * @return int Message sequence identifier
1458     * @access public
1459     */
1460    function UID2ID($mailbox, $uid)
1461    {
1462        if ($uid > 0) {
1463            $id_a = $this->search($mailbox, "UID $uid");
1464            if (is_array($id_a) && count($id_a) == 1) {
1465                return (int) $id_a[0];
1466            }
1467        }
1468        return null;
1469    }
1470
1471    /**
1472     * Returns message unique identifier (UID)
1473     *
1474     * @param string $mailbox Mailbox name
1475     * @param int    $uid     Message sequence identifier
1476     *
1477     * @return int Message unique identifier
1478     * @access public
1479     */
1480    function ID2UID($mailbox, $id)
1481    {
1482        if (empty($id) || $id < 0) {
1483            return      null;
1484        }
1485
1486        if (!$this->select($mailbox)) {
1487            return null;
1488        }
1489
1490        list($code, $response) = $this->execute('FETCH', array($id, '(UID)'));
1491
1492        if ($code == self::ERROR_OK && preg_match("/^\* $id FETCH \(UID (.*)\)/i", $response, $m)) {
1493            return (int) $m[1];
1494        }
1495
1496        return null;
1497    }
1498
1499    function fetchUIDs($mailbox, $message_set=null)
1500    {
1501        if (is_array($message_set))
1502            $message_set = join(',', $message_set);
1503        else if (empty($message_set))
1504            $message_set = '1:*';
1505
1506        return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
1507    }
1508
1509    function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1510    {
1511        $result = array();
1512
1513        if (!$this->select($mailbox)) {
1514            return false;
1515        }
1516
1517        $message_set = $this->compressMessageSet($message_set);
1518
1519        if ($add)
1520            $add = ' '.trim($add);
1521
1522        /* FETCH uid, size, flags and headers */
1523        $key      = $this->nextTag();
1524        $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1525        $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1526        if ($bodystr)
1527            $request .= "BODYSTRUCTURE ";
1528        $request .= "BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT CONTENT-TYPE ";
1529        $request .= "LIST-POST DISPOSITION-NOTIFICATION-TO".$add.")])";
1530
1531        if (!$this->putLine($request)) {
1532            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
1533            return false;
1534        }
1535        do {
1536            $line = $this->readLine(4096);
1537            $line = $this->multLine($line);
1538
1539            if (!$line)
1540                break;
1541
1542            if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
1543                $id = intval($m[1]);
1544
1545                $result[$id]            = new rcube_mail_header;
1546                $result[$id]->id        = $id;
1547                $result[$id]->subject   = '';
1548                $result[$id]->messageID = 'mid:' . $id;
1549
1550                $lines = array();
1551                $ln = 0;
1552
1553                // Sample reply line:
1554                // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1555                // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1556                // BODY[HEADER.FIELDS ...
1557
1558                if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/sU', $line, $matches)) {
1559                    $str = $matches[1];
1560
1561                    // swap parents with quotes, then explode
1562                    $str = preg_replace('/[()]/', '"', $str);
1563                    $a = rcube_explode_quoted_string(' ', $str);
1564
1565                    // did we get the right number of replies?
1566                    $parts_count = count($a);
1567                    if ($parts_count>=6) {
1568                        for ($i=0; $i<$parts_count; $i=$i+2) {
1569                            if ($a[$i] == 'UID') {
1570                                $result[$id]->uid = intval($a[$i+1]);
1571                            }
1572                            else if ($a[$i] == 'RFC822.SIZE') {
1573                                $result[$id]->size = intval($a[$i+1]);
1574                            }
1575                            else if ($a[$i] == 'INTERNALDATE') {
1576                                $time_str = $a[$i+1];
1577                            }
1578                            else if ($a[$i] == 'FLAGS') {
1579                                $flags_str = $a[$i+1];
1580                            }
1581                        }
1582
1583                        $time_str = str_replace('"', '', $time_str);
1584
1585                        // if time is gmt...
1586                        $time_str = str_replace('GMT','+0000',$time_str);
1587
1588                        $result[$id]->internaldate = $time_str;
1589                        $result[$id]->timestamp    = $this->StrToTime($time_str);
1590                        $result[$id]->date         = $time_str;
1591                    }
1592
1593                    // BODYSTRUCTURE
1594                    if ($bodystr) {
1595                        while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/sU', $line, $m)) {
1596                            $line2 = $this->readLine(1024);
1597                            $line .= $this->multLine($line2, true);
1598                        }
1599                        $result[$id]->body_structure = $m[1];
1600                    }
1601
1602                    // the rest of the result
1603                    if (preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m)) {
1604                        $reslines = explode("\n", trim($m[1], '"'));
1605                        // re-parse (see below)
1606                        foreach ($reslines as $resln) {
1607                            if (ord($resln[0])<=32) {
1608                                $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1609                            } else {
1610                                $lines[++$ln] = trim($resln);
1611                            }
1612                        }
1613                    }
1614                }
1615
1616                // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1617                // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1618                // process the previous line.  Otherwise, we'll keep adding the strings until we come
1619                // to the next valid header line.
1620
1621                do {
1622                    $line = rtrim($this->readLine(300), "\r\n");
1623
1624                    // The preg_match below works around communigate imap, which outputs " UID <number>)".
1625                    // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1626                    // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1627                    // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1628                    // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1629                    // An alternative might be:
1630                    // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1631                    // however, unsure how well this would work with all imap clients.
1632                    if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1633                        break;
1634                    }
1635
1636                    // handle FLAGS reply after headers (AOL, Zimbra?)
1637                    if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1638                        $flags_str = $matches[1];
1639                        break;
1640                    }
1641
1642                    if (ord($line[0])<=32) {
1643                        $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1644                    } else {
1645                        $lines[++$ln] = trim($line);
1646                    }
1647                // patch from "Maksim Rubis" <siburny@hotmail.com>
1648                } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1649
1650                if (strncmp($line, $key, strlen($key))) {
1651                    // process header, fill rcube_mail_header obj.
1652                    // initialize
1653                    if (is_array($headers)) {
1654                        reset($headers);
1655                        while (list($k, $bar) = each($headers)) {
1656                            $headers[$k] = '';
1657                        }
1658                    }
1659
1660                    // create array with header field:data
1661                    while (list($lines_key, $str) = each($lines)) {
1662                        list($field, $string) = $this->splitHeaderLine($str);
1663
1664                        $field  = strtolower($field);
1665                        $string = preg_replace('/\n\s*/', ' ', $string);
1666
1667                        switch ($field) {
1668                        case 'date';
1669                            $result[$id]->date = $string;
1670                            $result[$id]->timestamp = $this->strToTime($string);
1671                            break;
1672                        case 'from':
1673                            $result[$id]->from = $string;
1674                            break;
1675                        case 'to':
1676                            $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1677                            break;
1678                        case 'subject':
1679                            $result[$id]->subject = $string;
1680                            break;
1681                        case 'reply-to':
1682                            $result[$id]->replyto = $string;
1683                            break;
1684                        case 'cc':
1685                            $result[$id]->cc = $string;
1686                            break;
1687                        case 'bcc':
1688                            $result[$id]->bcc = $string;
1689                            break;
1690                        case 'content-transfer-encoding':
1691                            $result[$id]->encoding = $string;
1692                        break;
1693                        case 'content-type':
1694                            $ctype_parts = preg_split('/[; ]/', $string);
1695                            $result[$id]->ctype = strtolower(array_shift($ctype_parts));
1696                            if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1697                                $result[$id]->charset = $regs[1];
1698                            }
1699                            break;
1700                        case 'in-reply-to':
1701                            $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
1702                            break;
1703                        case 'references':
1704                            $result[$id]->references = $string;
1705                            break;
1706                        case 'return-receipt-to':
1707                        case 'disposition-notification-to':
1708                        case 'x-confirm-reading-to':
1709                            $result[$id]->mdn_to = $string;
1710                            break;
1711                        case 'message-id':
1712                            $result[$id]->messageID = $string;
1713                            break;
1714                        case 'x-priority':
1715                            if (preg_match('/^(\d+)/', $string, $matches)) {
1716                                $result[$id]->priority = intval($matches[1]);
1717                            }
1718                            break;
1719                        default:
1720                            if (strlen($field) > 2) {
1721                                $result[$id]->others[$field] = $string;
1722                            }
1723                            break;
1724                        } // end switch ()
1725                    } // end while ()
1726                }
1727
1728                // process flags
1729                if (!empty($flags_str)) {
1730                    $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1731                    $flags_a   = explode(' ', $flags_str);
1732
1733                    if (is_array($flags_a)) {
1734                        foreach($flags_a as $flag) {
1735                            $flag = strtoupper($flag);
1736                            if ($flag == 'SEEN') {
1737                                $result[$id]->seen = true;
1738                            } else if ($flag == 'DELETED') {
1739                                $result[$id]->deleted = true;
1740                            } else if ($flag == 'ANSWERED') {
1741                                $result[$id]->answered = true;
1742                            } else if ($flag == '$FORWARDED') {
1743                                $result[$id]->forwarded = true;
1744                            } else if ($flag == '$MDNSENT') {
1745                                $result[$id]->mdn_sent = true;
1746                            } else if ($flag == 'FLAGGED') {
1747                                 $result[$id]->flagged = true;
1748                            }
1749                        }
1750                        $result[$id]->flags = $flags_a;
1751                    }
1752                }
1753            }
1754        } while (!$this->startsWith($line, $key, true));
1755
1756        return $result;
1757    }
1758
1759    function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1760    {
1761        $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1762        if (is_array($a)) {
1763            return array_shift($a);
1764        }
1765        return false;
1766    }
1767
1768    function sortHeaders($a, $field, $flag)
1769    {
1770        if (empty($field)) {
1771            $field = 'uid';
1772        }
1773        else {
1774            $field = strtolower($field);
1775        }
1776
1777        if ($field == 'date' || $field == 'internaldate') {
1778            $field = 'timestamp';
1779        }
1780
1781        if (empty($flag)) {
1782            $flag = 'ASC';
1783        } else {
1784            $flag = strtoupper($flag);
1785        }
1786
1787        $c = count($a);
1788        if ($c > 0) {
1789            // Strategy:
1790            // First, we'll create an "index" array.
1791            // Then, we'll use sort() on that array,
1792            // and use that to sort the main array.
1793
1794            // create "index" array
1795            $index = array();
1796            reset($a);
1797            while (list($key, $val) = each($a)) {
1798                if ($field == 'timestamp') {
1799                    $data = $this->strToTime($val->date);
1800                    if (!$data) {
1801                        $data = $val->timestamp;
1802                    }
1803                } else {
1804                    $data = $val->$field;
1805                    if (is_string($data)) {
1806                        $data = str_replace('"', '', $data);
1807                        if ($field == 'subject') {
1808                            $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
1809                        }
1810                        $data = strtoupper($data);
1811                    }
1812                }
1813                $index[$key] = $data;
1814            }
1815
1816            // sort index
1817            if ($flag == 'ASC') {
1818                asort($index);
1819            } else {
1820                arsort($index);
1821            }
1822
1823            // form new array based on index
1824            $result = array();
1825            reset($index);
1826            while (list($key, $val) = each($index)) {
1827                $result[$key] = $a[$key];
1828            }
1829        }
1830
1831        return $result;
1832    }
1833
1834
1835    function modFlag($mailbox, $messages, $flag, $mod)
1836    {
1837        if ($mod != '+' && $mod != '-') {
1838            $mod = '+';
1839        }
1840
1841        if (!$this->select($mailbox)) {
1842            return false;
1843        }
1844
1845        if (!$this->data['READ-WRITE']) {
1846            $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1847            return false;
1848        }
1849
1850        // Clear internal status cache
1851        if ($flag == 'SEEN') {
1852            unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
1853        }
1854
1855        $flag   = $this->flags[strtoupper($flag)];
1856        $result = $this->execute('UID STORE', array(
1857            $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
1858            self::COMMAND_NORESPONSE);
1859
1860        return ($result == self::ERROR_OK);
1861    }
1862
1863    function flag($mailbox, $messages, $flag) {
1864        return $this->modFlag($mailbox, $messages, $flag, '+');
1865    }
1866
1867    function unflag($mailbox, $messages, $flag) {
1868        return $this->modFlag($mailbox, $messages, $flag, '-');
1869    }
1870
1871    function delete($mailbox, $messages) {
1872        return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1873    }
1874
1875    function copy($messages, $from, $to)
1876    {
1877        if (!$this->select($from)) {
1878            return false;
1879        }
1880
1881        // Clear internal status cache
1882        unset($this->data['STATUS:'.$to]);
1883
1884        $result = $this->execute('UID COPY', array(
1885            $this->compressMessageSet($messages), $this->escape($to)),
1886            self::COMMAND_NORESPONSE);
1887
1888        return ($result == self::ERROR_OK);
1889    }
1890
1891    function move($messages, $from, $to)
1892    {
1893        if (!$this->select($from)) {
1894            return false;
1895        }
1896
1897        if (!$this->data['READ-WRITE']) {
1898            $this->setError(self::ERROR_READONLY, "Mailbox is read-only", 'STORE');
1899            return false;
1900        }
1901
1902        $r = $this->copy($messages, $from, $to);
1903
1904        if ($r) {
1905            // Clear internal status cache
1906            unset($this->data['STATUS:'.$from]);
1907
1908            return $this->delete($from, $messages);
1909        }
1910        return $r;
1911    }
1912
1913    // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1914    // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1915    // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1916    private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1917    {
1918        $node = array();
1919        if ($str[$begin] != '(') {
1920            $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
1921            $msg = substr($str, $begin, $stop - $begin);
1922            if ($msg == 0)
1923                return $node;
1924            if (is_null($root))
1925                $root = $msg;
1926            $depthmap[$msg] = $depth;
1927            $haschildren[$msg] = false;
1928            if (!is_null($parent))
1929                $haschildren[$parent] = true;
1930            if ($stop + 1 < $end)
1931                $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1932            else
1933                $node[$msg] = array();
1934        } else {
1935            $off = $begin;
1936            while ($off < $end) {
1937                $start = $off;
1938                $off++;
1939                $n = 1;
1940                while ($n > 0) {
1941                    $p = strpos($str, ')', $off);
1942                    if ($p === false) {
1943                        error_log("Mismatched brackets parsing IMAP THREAD response:");
1944                        error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1945                        error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1946                        return $node;
1947                    }
1948                    $p1 = strpos($str, '(', $off);
1949                    if ($p1 !== false && $p1 < $p) {
1950                        $off = $p1 + 1;
1951                        $n++;
1952                    } else {
1953                        $off = $p + 1;
1954                        $n--;
1955                    }
1956                }
1957                $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1958            }
1959        }
1960
1961        return $node;
1962    }
1963
1964    function thread($mailbox, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1965    {
1966        $old_sel = $this->selected;
1967
1968        if (!$this->select($mailbox)) {
1969            return false;
1970        }
1971
1972        // return empty result when folder is empty and we're just after SELECT
1973        if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1974            return array(array(), array(), array());
1975        }
1976
1977        $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1978        $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1979        $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1980        $data      = '';
1981
1982        list($code, $response) = $this->execute('THREAD', array(
1983            $algorithm, $encoding, $criteria));
1984
1985        if ($code == self::ERROR_OK) {
1986            // remove prefix...
1987            $response = substr($response, stripos($response, '* THREAD') + 9);
1988            // ...unilateral untagged server responses
1989            if ($pos = strpos($response, '*')) {
1990                $response = substr($response, 0, $pos);
1991            }
1992
1993            $response    = str_replace("\r\n", '', $response);
1994            $depthmap    = array();
1995            $haschildren = array();
1996
1997            $tree = $this->parseThread($response, 0, strlen($response),
1998                null, null, 0, $depthmap, $haschildren);
1999
2000            return array($tree, $depthmap, $haschildren);
2001        }
2002
2003        return false;
2004    }
2005
2006    /**
2007     * Executes SEARCH command
2008     *
2009     * @param string $mailbox    Mailbox name
2010     * @param string $criteria   Searching criteria
2011     * @param bool   $return_uid Enable UID in result instead of sequence ID
2012     * @param array  $items      Return items (MIN, MAX, COUNT, ALL)
2013     *
2014     * @return array Message identifiers or item-value hash
2015     */
2016    function search($mailbox, $criteria, $return_uid=false, $items=array())
2017    {
2018        $old_sel = $this->selected;
2019
2020        if (!$this->select($mailbox)) {
2021            return false;
2022        }
2023
2024        // return empty result when folder is empty and we're just after SELECT
2025        if ($old_sel != $mailbox && !$this->data['EXISTS']) {
2026            if (!empty($items))
2027                return array_combine($items, array_fill(0, count($items), 0));
2028            else
2029                return array();
2030        }
2031
2032        $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
2033        $criteria = trim($criteria);
2034        $params   = '';
2035
2036        // RFC4731: ESEARCH
2037        if (!empty($items) && $esearch) {
2038            $params .= 'RETURN (' . implode(' ', $items) . ')';
2039        }
2040        if (!empty($criteria)) {
2041            $params .= ($params ? ' ' : '') . $criteria;
2042        }
2043        else {
2044            $params .= 'ALL';
2045        }
2046
2047        list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
2048            array($params));
2049
2050        if ($code == self::ERROR_OK) {
2051            // remove prefix...
2052            $response = substr($response, stripos($response, 
2053                $esearch ? '* ESEARCH' : '* SEARCH') + ($esearch ? 10 : 9));
2054            // ...and unilateral untagged server responses
2055            if ($pos = strpos($response, '*')) {
2056                $response = rtrim(substr($response, 0, $pos));
2057            }
2058
2059            if ($esearch) {
2060                // Skip prefix: ... (TAG "A285") UID ...
2061                $this->tokenizeResponse($response, $return_uid ? 2 : 1);
2062
2063                $result = array();
2064                for ($i=0; $i<count($items); $i++) {
2065                    // If the SEARCH results in no matches, the server MUST NOT
2066                    // include the item result option in the ESEARCH response
2067                    if ($ret = $this->tokenizeResponse($response, 2)) {
2068                        list ($name, $value) = $ret;
2069                        $result[$name] = $value;
2070                    }
2071                }
2072
2073                return $result;
2074            }
2075            else {
2076                $response = preg_split('/[\s\r\n]+/', $response, -1, PREG_SPLIT_NO_EMPTY);
2077
2078                if (!empty($items)) {
2079                    $result = array();
2080                    if (in_array('COUNT', $items)) {
2081                        $result['COUNT'] = count($response);
2082                    }
2083                    if (in_array('MIN', $items)) {
2084                        $result['MIN'] = !empty($response) ? min($response) : 0;
2085                    }
2086                    if (in_array('MAX', $items)) {
2087                        $result['MAX'] = !empty($response) ? max($response) : 0;
2088                    }
2089                    if (in_array('ALL', $items)) {
2090                        $result['ALL'] = $this->compressMessageSet($response, true);
2091                    }
2092
2093                    return $result;
2094                }
2095                else {
2096                    return $response;
2097                }
2098            }
2099        }
2100
2101        return false;
2102    }
2103
2104    /**
2105     * Returns list of mailboxes
2106     *
2107     * @param string $ref         Reference name
2108     * @param string $mailbox     Mailbox name
2109     * @param array  $status_opts (see self::_listMailboxes)
2110     * @param array  $select_opts (see self::_listMailboxes)
2111     *
2112     * @return array List of mailboxes or hash of options if $status_opts argument
2113     *               is non-empty.
2114     * @access public
2115     */
2116    function listMailboxes($ref, $mailbox, $status_opts=array(), $select_opts=array())
2117    {
2118        return $this->_listMailboxes($ref, $mailbox, false, $status_opts, $select_opts);
2119    }
2120
2121    /**
2122     * Returns list of subscribed mailboxes
2123     *
2124     * @param string $ref         Reference name
2125     * @param string $mailbox     Mailbox name
2126     * @param array  $status_opts (see self::_listMailboxes)
2127     *
2128     * @return array List of mailboxes or hash of options if $status_opts argument
2129     *               is non-empty.
2130     * @access public
2131     */
2132    function listSubscribed($ref, $mailbox, $status_opts=array())
2133    {
2134        return $this->_listMailboxes($ref, $mailbox, true, $status_opts, NULL);
2135    }
2136
2137    /**
2138     * IMAP LIST/LSUB command
2139     *
2140     * @param string $ref         Reference name
2141     * @param string $mailbox     Mailbox name
2142     * @param bool   $subscribed  Enables returning subscribed mailboxes only
2143     * @param array  $status_opts List of STATUS options (RFC5819: LIST-STATUS)
2144     *                            Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN
2145     * @param array  $select_opts List of selection options (RFC5258: LIST-EXTENDED)
2146     *                            Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE
2147     *
2148     * @return array List of mailboxes or hash of options if $status_ops argument
2149     *               is non-empty.
2150     * @access private
2151     */
2152    private function _listMailboxes($ref, $mailbox, $subscribed=false,
2153        $status_opts=array(), $select_opts=array())
2154    {
2155        if (!strlen($mailbox)) {
2156            $mailbox = '*';
2157        }
2158
2159        $args = array();
2160
2161        if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
2162            $select_opts = (array) $select_opts;
2163
2164            $args[] = '(' . implode(' ', $select_opts) . ')';
2165        }
2166
2167        $args[] = $this->escape($ref);
2168        $args[] = $this->escape($mailbox);
2169
2170        if (!empty($status_opts) && $this->getCapability('LIST-STATUS')) {
2171            $status_opts = (array) $status_opts;
2172            $lstatus = true;
2173
2174            $args[] = 'RETURN (STATUS (' . implode(' ', $status_opts) . '))';
2175        }
2176
2177        list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
2178
2179        if ($code == self::ERROR_OK) {
2180            $folders = array();
2181            while ($this->tokenizeResponse($response, 1) == '*') {
2182                $cmd = strtoupper($this->tokenizeResponse($response, 1));
2183                // * LIST (<options>) <delimiter> <mailbox>
2184                if (!$lstatus || $cmd == 'LIST' || $cmd == 'LSUB') {
2185                    list($opts, $delim, $mailbox) = $this->tokenizeResponse($response, 3);
2186
2187                    // Add to result array
2188                    if (!$lstatus) {
2189                        $folders[] = $mailbox;
2190                    }
2191                    else {
2192                        $folders[$mailbox] = array();
2193                    }
2194
2195                    // Add to options array
2196                    if (!empty($opts)) {
2197                        if (empty($this->data['LIST'][$mailbox]))
2198                            $this->data['LIST'][$mailbox] = $opts;
2199                        else
2200                            $this->data['LIST'][$mailbox] = array_unique(array_merge(
2201                                $this->data['LIST'][$mailbox], $opts));
2202                    }
2203                }
2204                // * STATUS <mailbox> (<result>)
2205                else if ($cmd == 'STATUS') {
2206                    list($mailbox, $status) = $this->tokenizeResponse($response, 2);
2207
2208                    for ($i=0, $len=count($status); $i<$len; $i += 2) {
2209                        list($name, $value) = $this->tokenizeResponse($status, 2);
2210                        $folders[$mailbox][$name] = $value;
2211                    }
2212                }
2213            }
2214
2215            return $folders;
2216        }
2217
2218        return false;
2219    }
2220
2221    function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
2222    {
2223        if (!$this->select($mailbox)) {
2224            return false;
2225        }
2226
2227        $result = false;
2228        $parts  = (array) $parts;
2229        $key    = $this->nextTag();
2230        $peeks  = '';
2231        $idx    = 0;
2232        $type   = $mime ? 'MIME' : 'HEADER';
2233
2234        // format request
2235        foreach($parts as $part) {
2236            $peeks[] = "BODY.PEEK[$part.$type]";
2237        }
2238
2239        $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2240
2241        // send request
2242        if (!$this->putLine($request)) {
2243            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2244            return false;
2245        }
2246
2247        do {
2248            $line = $this->readLine(1024);
2249            $line = $this->multLine($line);
2250
2251            if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2252                $idx = $matches[1];
2253                $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
2254                $result[$idx] = trim($result[$idx], '"');
2255                $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2256            }
2257        } while (!$this->startsWith($line, $key, true));
2258
2259        return $result;
2260    }
2261
2262    function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
2263    {
2264        $part = empty($part) ? 'HEADER' : $part.'.MIME';
2265
2266        return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2267    }
2268
2269    function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
2270    {
2271        if (!$this->select($mailbox)) {
2272            return false;
2273        }
2274
2275        switch ($encoding) {
2276        case 'base64':
2277            $mode = 1;
2278            break;
2279        case 'quoted-printable':
2280            $mode = 2;
2281            break;
2282        case 'x-uuencode':
2283        case 'x-uue':
2284        case 'uue':
2285        case 'uuencode':
2286            $mode = 3;
2287            break;
2288        default:
2289            $mode = 0;
2290        }
2291
2292        // format request
2293        $reply_key = '* ' . $id;
2294        $key       = $this->nextTag();
2295        $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2296
2297        // send request
2298        if (!$this->putLine($request)) {
2299            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2300            return false;
2301        }
2302
2303        // receive reply line
2304        do {
2305            $line = rtrim($this->readLine(1024));
2306            $a    = explode(' ', $line);
2307        } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
2308
2309        $len    = strlen($line);
2310        $result = false;
2311
2312        // handle empty "* X FETCH ()" response
2313        if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2314            // one line response, get everything between first and last quotes
2315            if (substr($line, -4, 3) == 'NIL') {
2316                // NIL response
2317                $result = '';
2318            } else {
2319                $from = strpos($line, '"') + 1;
2320                $to   = strrpos($line, '"');
2321                $len  = $to - $from;
2322                $result = substr($line, $from, $len);
2323            }
2324
2325            if ($mode == 1) {
2326                $result = base64_decode($result);
2327            }
2328            else if ($mode == 2) {
2329                $result = quoted_printable_decode($result);
2330            }
2331            else if ($mode == 3) {
2332                $result = convert_uudecode($result);
2333            }
2334
2335        } else if ($line[$len-1] == '}') {
2336            // multi-line request, find sizes of content and receive that many bytes
2337            $from     = strpos($line, '{') + 1;
2338            $to       = strrpos($line, '}');
2339            $len      = $to - $from;
2340            $sizeStr  = substr($line, $from, $len);
2341            $bytes    = (int)$sizeStr;
2342            $prev     = '';
2343
2344            while ($bytes > 0) {
2345                $line = $this->readLine(4096);
2346
2347                if ($line === NULL) {
2348                    break;
2349                }
2350
2351                $len  = strlen($line);
2352
2353                if ($len > $bytes) {
2354                    $line = substr($line, 0, $bytes);
2355                    $len = strlen($line);
2356                }
2357                $bytes -= $len;
2358
2359                // BASE64
2360                if ($mode == 1) {
2361                    $line = rtrim($line, "\t\r\n\0\x0B");
2362                    // create chunks with proper length for base64 decoding
2363                    $line = $prev.$line;
2364                    $length = strlen($line);
2365                    if ($length % 4) {
2366                        $length = floor($length / 4) * 4;
2367                        $prev = substr($line, $length);
2368                        $line = substr($line, 0, $length);
2369                    }
2370                    else
2371                        $prev = '';
2372                    $line = base64_decode($line);
2373                // QUOTED-PRINTABLE
2374                } else if ($mode == 2) {
2375                    $line = rtrim($line, "\t\r\0\x0B");
2376                    $line = quoted_printable_decode($line);
2377                    // Remove NULL characters (#1486189)
2378                    $line = str_replace("\x00", '', $line);
2379                // UUENCODE
2380                } else if ($mode == 3) {
2381                    $line = rtrim($line, "\t\r\n\0\x0B");
2382                    if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2383                        continue;
2384                    $line = convert_uudecode($line);
2385                // default
2386                } else {
2387                    $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2388                }
2389
2390                if ($file)
2391                    fwrite($file, $line);
2392                else if ($print)
2393                    echo $line;
2394                else
2395                    $result .= $line;
2396            }
2397        }
2398
2399        // read in anything up until last line
2400        if (!$end)
2401            do {
2402                $line = $this->readLine(1024);
2403            } while (!$this->startsWith($line, $key, true));
2404
2405        if ($result !== false) {
2406            if ($file) {
2407                fwrite($file, $result);
2408            } else if ($print) {
2409                echo $result;
2410            } else
2411                return $result;
2412            return true;
2413        }
2414
2415        return false;
2416    }
2417
2418    function createFolder($mailbox)
2419    {
2420        $result = $this->execute('CREATE', array($this->escape($mailbox)),
2421            self::COMMAND_NORESPONSE);
2422
2423        return ($result == self::ERROR_OK);
2424    }
2425
2426    function renameFolder($from, $to)
2427    {
2428        $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
2429            self::COMMAND_NORESPONSE);
2430
2431        return ($result == self::ERROR_OK);
2432    }
2433
2434    function append($mailbox, &$message)
2435    {
2436        if (!$mailbox) {
2437            return false;
2438        }
2439
2440        $message = str_replace("\r", '', $message);
2441        $message = str_replace("\n", "\r\n", $message);
2442
2443        $len = strlen($message);
2444        if (!$len) {
2445            return false;
2446        }
2447
2448        $key = $this->nextTag();
2449        $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2450            $len, ($this->prefs['literal+'] ? '+' : ''));
2451
2452        if ($this->putLine($request)) {
2453            // Don't wait when LITERAL+ is supported
2454            if (!$this->prefs['literal+']) {
2455                $line = $this->readReply();
2456
2457                if ($line[0] != '+') {
2458                    $this->parseResult($line, 'APPEND: ');
2459                    return false;
2460                }
2461            }
2462
2463            if (!$this->putLine($message)) {
2464                return false;
2465            }
2466
2467            do {
2468                $line = $this->readLine();
2469            } while (!$this->startsWith($line, $key, true, true));
2470
2471            // Clear internal status cache
2472            unset($this->data['STATUS:'.$mailbox]);
2473
2474            return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2475        }
2476        else {
2477            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2478        }
2479
2480        return false;
2481    }
2482
2483    function appendFromFile($mailbox, $path, $headers=null)
2484    {
2485        if (!$mailbox) {
2486            return false;
2487        }
2488
2489        // open message file
2490        $in_fp = false;
2491        if (file_exists(realpath($path))) {
2492            $in_fp = fopen($path, 'r');
2493        }
2494        if (!$in_fp) {
2495            $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
2496            return false;
2497        }
2498
2499        $body_separator = "\r\n\r\n";
2500        $len = filesize($path);
2501
2502        if (!$len) {
2503            return false;
2504        }
2505
2506        if ($headers) {
2507            $headers = preg_replace('/[\r\n]+$/', '', $headers);
2508            $len += strlen($headers) + strlen($body_separator);
2509        }
2510
2511        // send APPEND command
2512        $key = $this->nextTag();
2513        $request = sprintf("$key APPEND %s (\\Seen) {%d%s}", $this->escape($mailbox),
2514            $len, ($this->prefs['literal+'] ? '+' : ''));
2515
2516        if ($this->putLine($request)) {
2517            // Don't wait when LITERAL+ is supported
2518            if (!$this->prefs['literal+']) {
2519                $line = $this->readReply();
2520
2521                if ($line[0] != '+') {
2522                    $this->parseResult($line, 'APPEND: ');
2523                    return false;
2524                }
2525            }
2526
2527            // send headers with body separator
2528            if ($headers) {
2529                $this->putLine($headers . $body_separator, false);
2530            }
2531
2532            // send file
2533            while (!feof($in_fp) && $this->fp) {
2534                $buffer = fgets($in_fp, 4096);
2535                $this->putLine($buffer, false);
2536            }
2537            fclose($in_fp);
2538
2539            if (!$this->putLine('')) { // \r\n
2540                return false;
2541            }
2542
2543            // read response
2544            do {
2545                $line = $this->readLine();
2546            } while (!$this->startsWith($line, $key, true, true));
2547
2548            // Clear internal status cache
2549            unset($this->data['STATUS:'.$mailbox]);
2550
2551            return ($this->parseResult($line, 'APPEND: ') == self::ERROR_OK);
2552        }
2553        else {
2554            $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2555        }
2556
2557        return false;
2558    }
2559
2560    function fetchStructureString($mailbox, $id, $is_uid=false)
2561    {
2562        if (!$this->select($mailbox)) {
2563            return false;
2564        }
2565
2566        $key = $this->nextTag();
2567        $result = false;
2568        $command = $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)";
2569
2570        if ($this->putLine($command)) {
2571            do {
2572                $line = $this->readLine(5000);
2573                $line = $this->multLine($line, true);
2574                if (!preg_match("/^$key /", $line))
2575                    $result .= $line;
2576            } while (!$this->startsWith($line, $key, true, true));
2577
2578            $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2579        }
2580        else {
2581            $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2582        }
2583
2584        return $result;
2585    }
2586
2587    function getQuota()
2588    {
2589        /*
2590         * GETQUOTAROOT "INBOX"
2591         * QUOTAROOT INBOX user/rchijiiwa1
2592         * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2593         * OK Completed
2594         */
2595        $result      = false;
2596        $quota_lines = array();
2597        $key         = $this->nextTag();
2598        $command     = $key . ' GETQUOTAROOT INBOX';
2599
2600        // get line(s) containing quota info
2601        if ($this->putLine($command)) {
2602            do {
2603                $line = rtrim($this->readLine(5000));
2604                if (preg_match('/^\* QUOTA /', $line)) {
2605                    $quota_lines[] = $line;
2606                }
2607            } while (!$this->startsWith($line, $key, true, true));
2608        }
2609        else {
2610            $this->setError(self::ERROR_COMMAND, "Unable to send command: $command");
2611        }
2612
2613        // return false if not found, parse if found
2614        $min_free = PHP_INT_MAX;
2615        foreach ($quota_lines as $key => $quota_line) {
2616            $quota_line   = str_replace(array('(', ')'), '', $quota_line);
2617            $parts        = explode(' ', $quota_line);
2618            $storage_part = array_search('STORAGE', $parts);
2619
2620            if (!$storage_part) {
2621                continue;
2622            }
2623
2624            $used  = intval($parts[$storage_part+1]);
2625            $total = intval($parts[$storage_part+2]);
2626            $free  = $total - $used;
2627
2628            // return lowest available space from all quotas
2629            if ($free < $min_free) {
2630                $min_free          = $free;
2631                $result['used']    = $used;
2632                $result['total']   = $total;
2633                $result['percent'] = min(100, round(($used/max(1,$total))*100));
2634                $result['free']    = 100 - $result['percent'];
2635            }
2636        }
2637
2638        return $result;
2639    }
2640
2641    /**
2642     * Send the SETACL command (RFC4314)
2643     *
2644     * @param string $mailbox Mailbox name
2645     * @param string $user    User name
2646     * @param mixed  $acl     ACL string or array
2647     *
2648     * @return boolean True on success, False on failure
2649     *
2650     * @access public
2651     * @since 0.5-beta
2652     */
2653    function setACL($mailbox, $user, $acl)
2654    {
2655        if (is_array($acl)) {
2656            $acl = implode('', $acl);
2657        }
2658
2659        $result = $this->execute('SETACL', array(
2660            $this->escape($mailbox), $this->escape($user), strtolower($acl)),
2661            self::COMMAND_NORESPONSE);
2662
2663        return ($result == self::ERROR_OK);
2664    }
2665
2666    /**
2667     * Send the DELETEACL command (RFC4314)
2668     *
2669     * @param string $mailbox Mailbox name
2670     * @param string $user    User name
2671     *
2672     * @return boolean True on success, False on failure
2673     *
2674     * @access public
2675     * @since 0.5-beta
2676     */
2677    function deleteACL($mailbox, $user)
2678    {
2679        $result = $this->execute('DELETEACL', array(
2680            $this->escape($mailbox), $this->escape($user)),
2681            self::COMMAND_NORESPONSE);
2682
2683        return ($result == self::ERROR_OK);
2684    }
2685
2686    /**
2687     * Send the GETACL command (RFC4314)
2688     *
2689     * @param string $mailbox Mailbox name
2690     *
2691     * @return array User-rights array on success, NULL on error
2692     * @access public
2693     * @since 0.5-beta
2694     */
2695    function getACL($mailbox)
2696    {
2697        list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
2698
2699        if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
2700            // Parse server response (remove "* ACL ")
2701            $response = substr($response, 6);
2702            $ret  = $this->tokenizeResponse($response);
2703            $mbox = array_shift($ret);
2704            $size = count($ret);
2705
2706            // Create user-rights hash array
2707            // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
2708            // so we could return only standard rights defined in RFC4314,
2709            // excluding 'c' and 'd' defined in RFC2086.
2710            if ($size % 2 == 0) {
2711                for ($i=0; $i<$size; $i++) {
2712                    $ret[$ret[$i]] = str_split($ret[++$i]);
2713                    unset($ret[$i-1]);
2714                    unset($ret[$i]);
2715                }
2716                return $ret;
2717            }
2718
2719            $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
2720            return NULL;
2721        }
2722
2723        return NULL;
2724    }
2725
2726    /**
2727     * Send the LISTRIGHTS command (RFC4314)
2728     *
2729     * @param string $mailbox Mailbox name
2730     * @param string $user    User name
2731     *
2732     * @return array List of user rights
2733     * @access public
2734     * @since 0.5-beta
2735     */
2736    function listRights($mailbox, $user)
2737    {
2738        list($code, $response) = $this->execute('LISTRIGHTS', array(
2739            $this->escape($mailbox), $this->escape($user)));
2740
2741        if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
2742            // Parse server response (remove "* LISTRIGHTS ")
2743            $response = substr($response, 13);
2744
2745            $ret_mbox = $this->tokenizeResponse($response, 1);
2746            $ret_user = $this->tokenizeResponse($response, 1);
2747            $granted  = $this->tokenizeResponse($response, 1);
2748            $optional = trim($response);
2749
2750            return array(
2751                'granted'  => str_split($granted),
2752                'optional' => explode(' ', $optional),
2753            );
2754        }
2755
2756        return NULL;
2757    }
2758
2759    /**
2760     * Send the MYRIGHTS command (RFC4314)
2761     *
2762     * @param string $mailbox Mailbox name
2763     *
2764     * @return array MYRIGHTS response on success, NULL on error
2765     * @access public
2766     * @since 0.5-beta
2767     */
2768    function myRights($mailbox)
2769    {
2770        list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
2771
2772        if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
2773            // Parse server response (remove "* MYRIGHTS ")
2774            $response = substr($response, 11);
2775
2776            $ret_mbox = $this->tokenizeResponse($response, 1);
2777            $rights   = $this->tokenizeResponse($response, 1);
2778
2779            return str_split($rights);
2780        }
2781
2782        return NULL;
2783    }
2784
2785    /**
2786     * Send the SETMETADATA command (RFC5464)
2787     *
2788     * @param string $mailbox Mailbox name
2789     * @param array  $entries Entry-value array (use NULL value as NIL)
2790     *
2791     * @return boolean True on success, False on failure
2792     * @access public
2793     * @since 0.5-beta
2794     */
2795    function setMetadata($mailbox, $entries)
2796    {
2797        if (!is_array($entries) || empty($entries)) {
2798            $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2799            return false;
2800        }
2801
2802        foreach ($entries as $name => $value) {
2803            if ($value === null) {
2804                $value = 'NIL';
2805            }
2806            else {
2807                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2808            }
2809            $entries[$name] = $this->escape($name) . ' ' . $value;
2810        }
2811
2812        $entries = implode(' ', $entries);
2813        $result = $this->execute('SETMETADATA', array(
2814            $this->escape($mailbox), '(' . $entries . ')'),
2815            self::COMMAND_NORESPONSE);
2816
2817        return ($result == self::ERROR_OK);
2818    }
2819
2820    /**
2821     * Send the SETMETADATA command with NIL values (RFC5464)
2822     *
2823     * @param string $mailbox Mailbox name
2824     * @param array  $entries Entry names array
2825     *
2826     * @return boolean True on success, False on failure
2827     *
2828     * @access public
2829     * @since 0.5-beta
2830     */
2831    function deleteMetadata($mailbox, $entries)
2832    {
2833        if (!is_array($entries) && !empty($entries)) {
2834            $entries = explode(' ', $entries);
2835        }
2836
2837        if (empty($entries)) {
2838            $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
2839            return false;
2840        }
2841
2842        foreach ($entries as $entry) {
2843            $data[$entry] = NULL;
2844        }
2845
2846        return $this->setMetadata($mailbox, $data);
2847    }
2848
2849    /**
2850     * Send the GETMETADATA command (RFC5464)
2851     *
2852     * @param string $mailbox Mailbox name
2853     * @param array  $entries Entries
2854     * @param array  $options Command options (with MAXSIZE and DEPTH keys)
2855     *
2856     * @return array GETMETADATA result on success, NULL on error
2857     *
2858     * @access public
2859     * @since 0.5-beta
2860     */
2861    function getMetadata($mailbox, $entries, $options=array())
2862    {
2863        if (!is_array($entries)) {
2864            $entries = array($entries);
2865        }
2866
2867        // create entries string
2868        foreach ($entries as $idx => $name) {
2869            $entries[$idx] = $this->escape($name);
2870        }
2871
2872        $optlist = '';
2873        $entlist = '(' . implode(' ', $entries) . ')';
2874
2875        // create options string
2876        if (is_array($options)) {
2877            $options = array_change_key_case($options, CASE_UPPER);
2878            $opts = array();
2879
2880            if (!empty($options['MAXSIZE'])) {
2881                $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
2882            }
2883            if (!empty($options['DEPTH'])) {
2884                $opts[] = 'DEPTH '.intval($options['DEPTH']);
2885            }
2886
2887            if ($opts) {
2888                $optlist = '(' . implode(' ', $opts) . ')';
2889            }
2890        }
2891
2892        $optlist .= ($optlist ? ' ' : '') . $entlist;
2893
2894        list($code, $response) = $this->execute('GETMETADATA', array(
2895            $this->escape($mailbox), $optlist));
2896
2897        if ($code == self::ERROR_OK) {
2898            $result = array();
2899            $data   = $this->tokenizeResponse($response);
2900
2901            // The METADATA response can contain multiple entries in a single
2902            // response or multiple responses for each entry or group of entries
2903            if (!empty($data) && ($size = count($data))) {
2904                for ($i=0; $i<$size; $i++) {
2905                    if (isset($mbox) && is_array($data[$i])) {
2906                        $size_sub = count($data[$i]);
2907                        for ($x=0; $x<$size_sub; $x++) {
2908                            $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
2909                        }
2910                        unset($data[$i]);
2911                    }
2912                    else if ($data[$i] == '*') {
2913                        if ($data[$i+1] == 'METADATA') {
2914                            $mbox = $data[$i+2];
2915                            unset($data[$i]);   // "*"
2916                            unset($data[++$i]); // "METADATA"
2917                            unset($data[++$i]); // Mailbox
2918                        }
2919                        // get rid of other untagged responses
2920                        else {
2921                            unset($mbox);
2922                            unset($data[$i]);
2923                        }
2924                    }
2925                    else if (isset($mbox)) {
2926                        $result[$mbox][$data[$i]] = $data[++$i];
2927                        unset($data[$i]);
2928                        unset($data[$i-1]);
2929                    }
2930                    else {
2931                        unset($data[$i]);
2932                    }
2933                }
2934            }
2935
2936            return $result;
2937        }
2938
2939        return NULL;
2940    }
2941
2942    /**
2943     * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
2944     *
2945     * @param string $mailbox Mailbox name
2946     * @param array  $data    Data array where each item is an array with
2947     *                        three elements: entry name, attribute name, value
2948     *
2949     * @return boolean True on success, False on failure
2950     * @access public
2951     * @since 0.5-beta
2952     */
2953    function setAnnotation($mailbox, $data)
2954    {
2955        if (!is_array($data) || empty($data)) {
2956            $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
2957            return false;
2958        }
2959
2960        foreach ($data as $entry) {
2961            $name  = $entry[0];
2962            $attr  = $entry[1];
2963            $value = $entry[2];
2964
2965            if ($value === null) {
2966                $value = 'NIL';
2967            }
2968            else {
2969                $value = sprintf("{%d}\r\n%s", strlen($value), $value);
2970            }
2971
2972            // ANNOTATEMORE drafts before version 08 require quoted parameters
2973            $entries[] = sprintf('%s (%s %s)',
2974                $this->escape($name, true), $this->escape($attr, true), $value);
2975        }
2976
2977        $entries = implode(' ', $entries);
2978        $result  = $this->execute('SETANNOTATION', array(
2979            $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
2980
2981        return ($result == self::ERROR_OK);
2982    }
2983
2984    /**
2985     * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
2986     *
2987     * @param string $mailbox Mailbox name
2988     * @param array  $data    Data array where each item is an array with
2989     *                        two elements: entry name and attribute name
2990     *
2991     * @return boolean True on success, False on failure
2992     *
2993     * @access public
2994     * @since 0.5-beta
2995     */
2996    function deleteAnnotation($mailbox, $data)
2997    {
2998        if (!is_array($data) || empty($data)) {
2999            $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
3000            return false;
3001        }
3002
3003        return $this->setAnnotation($mailbox, $data);
3004    }
3005
3006    /**
3007     * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3008     *
3009     * @param string $mailbox Mailbox name
3010     * @param array  $entries Entries names
3011     * @param array  $attribs Attribs names
3012     *
3013     * @return array Annotations result on success, NULL on error
3014     *
3015     * @access public
3016     * @since 0.5-beta
3017     */
3018    function getAnnotation($mailbox, $entries, $attribs)
3019    {
3020        if (!is_array($entries)) {
3021            $entries = array($entries);
3022        }
3023        // create entries string
3024        // ANNOTATEMORE drafts before version 08 require quoted parameters
3025        foreach ($entries as $idx => $name) {
3026            $entries[$idx] = $this->escape($name, true);
3027        }
3028        $entries = '(' . implode(' ', $entries) . ')';
3029
3030        if (!is_array($attribs)) {
3031            $attribs = array($attribs);
3032        }
3033        // create entries string
3034        foreach ($attribs as $idx => $name) {
3035            $attribs[$idx] = $this->escape($name, true);
3036        }
3037        $attribs = '(' . implode(' ', $attribs) . ')';
3038
3039        list($code, $response) = $this->execute('GETANNOTATION', array(
3040            $this->escape($mailbox), $entries, $attribs));
3041
3042        if ($code == self::ERROR_OK) {
3043            $result = array();
3044            $data   = $this->tokenizeResponse($response);
3045
3046            // Here we returns only data compatible with METADATA result format
3047            if (!empty($data) && ($size = count($data))) {
3048                for ($i=0; $i<$size; $i++) {
3049                    $entry = $data[$i];
3050                    if (isset($mbox) && is_array($entry)) {
3051                        $attribs = $entry;
3052                        $entry   = $last_entry;
3053                    }
3054                    else if ($entry == '*') {
3055                        if ($data[$i+1] == 'ANNOTATION') {
3056                            $mbox = $data[$i+2];
3057                            unset($data[$i]);   // "*"
3058                            unset($data[++$i]); // "ANNOTATION"
3059                            unset($data[++$i]); // Mailbox
3060                        }
3061                        // get rid of other untagged responses
3062                        else {
3063                            unset($mbox);
3064                            unset($data[$i]);
3065                        }
3066                        continue;
3067                    }
3068                    else if (isset($mbox)) {
3069                        $attribs = $data[++$i];
3070                    }
3071                    else {
3072                        unset($data[$i]);
3073                        continue;
3074                    }
3075
3076                    if (!empty($attribs)) {
3077                        for ($x=0, $len=count($attribs); $x<$len;) {
3078                            $attr  = $attribs[$x++];
3079                            $value = $attribs[$x++];
3080                            if ($attr == 'value.priv') {
3081                                $result[$mbox]['/private' . $entry] = $value;
3082                            }
3083                            else if ($attr == 'value.shared') {
3084                                $result[$mbox]['/shared' . $entry] = $value;
3085                            }
3086                        }
3087                    }
3088                    $last_entry = $entry;
3089                    unset($data[$i]);
3090                }
3091            }
3092
3093            return $result;
3094        }
3095
3096        return NULL;
3097    }
3098
3099    /**
3100     * Creates next command identifier (tag)
3101     *
3102     * @return string Command identifier
3103     * @access public
3104     * @since 0.5-beta
3105     */
3106    function nextTag()
3107    {
3108        $this->cmd_num++;
3109        $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3110
3111        return $this->cmd_tag;
3112    }
3113
3114    /**
3115     * Sends IMAP command and parses result
3116     *
3117     * @param string $command   IMAP command
3118     * @param array  $arguments Command arguments
3119     * @param int    $options   Execution options
3120     *
3121     * @return mixed Response code or list of response code and data
3122     * @access public
3123     * @since 0.5-beta
3124     */
3125    function execute($command, $arguments=array(), $options=0)
3126    {
3127        $tag      = $this->nextTag();
3128        $query    = $tag . ' ' . $command;
3129        $noresp   = ($options & self::COMMAND_NORESPONSE);
3130        $response = $noresp ? null : '';
3131
3132        if (!empty($arguments)) {
3133            $query .= ' ' . implode(' ', $arguments);
3134        }
3135
3136        // Send command
3137        if (!$this->putLineC($query)) {
3138            $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
3139            return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
3140        }
3141
3142        // Parse response
3143        do {
3144            $line = $this->readLine(4096);
3145            if ($response !== null) {
3146                $response .= $line;
3147            }
3148        } while (!$this->startsWith($line, $tag . ' ', true, true));
3149
3150        $code = $this->parseResult($line, $command . ': ');
3151
3152        // Remove last line from response
3153        if ($response) {
3154            $line_len = min(strlen($response), strlen($line) + 2);
3155            $response = substr($response, 0, -$line_len);
3156        }
3157
3158        // optional CAPABILITY response
3159        if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
3160            && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
3161        ) {
3162            $this->parseCapability($matches[1], true);
3163        }
3164
3165        // return last line only (without command tag, result and response code)
3166        if ($line && ($options & self::COMMAND_LASTLINE)) {
3167            $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
3168        }
3169
3170        return $noresp ? $code : array($code, $response);
3171    }
3172
3173    /**
3174     * Splits IMAP response into string tokens
3175     *
3176     * @param string &$str The IMAP's server response
3177     * @param int    $num  Number of tokens to return
3178     *
3179     * @return mixed Tokens array or string if $num=1
3180     * @access public
3181     * @since 0.5-beta
3182     */
3183    static function tokenizeResponse(&$str, $num=0)
3184    {
3185        $result = array();
3186
3187        while (!$num || count($result) < $num) {
3188            // remove spaces from the beginning of the string
3189            $str = ltrim($str);
3190
3191            switch ($str[0]) {
3192
3193            // String literal
3194            case '{':
3195                if (($epos = strpos($str, "}\r\n", 1)) == false) {
3196                    // error
3197                }
3198                if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3199                    // error
3200                }
3201                $result[] = substr($str, $epos + 3, $bytes);
3202                // Advance the string
3203                $str = substr($str, $epos + 3 + $bytes);
3204                break;
3205
3206            // Quoted string
3207            case '"':
3208                $len = strlen($str);
3209
3210                for ($pos=1; $pos<$len; $pos++) {
3211                    if ($str[$pos] == '"') {
3212                        break;
3213                    }
3214                    if ($str[$pos] == "\\") {
3215                        if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3216                            $pos++;
3217                        }
3218                    }
3219                }
3220                if ($str[$pos] != '"') {
3221                    // error
3222                }
3223                // we need to strip slashes for a quoted string
3224                $result[] = stripslashes(substr($str, 1, $pos - 1));
3225                $str      = substr($str, $pos + 1);
3226                break;
3227
3228            // Parenthesized list
3229            case '(':
3230                $str = substr($str, 1);
3231                $result[] = self::tokenizeResponse($str);
3232                break;
3233            case ')':
3234                $str = substr($str, 1);
3235                return $result;
3236                break;
3237
3238            // String atom, number, NIL, *, %
3239            default:
3240                // empty or one character
3241                if ($str === '') {
3242                    break 2;
3243                }
3244                if (strlen($str) < 2) {
3245                    $result[] = $str;
3246                    $str = '';
3247                    break;
3248                }
3249
3250                // excluded chars: SP, CTL, (, ), {, ", ], %
3251                if (preg_match('/^([\x21\x23\x24\x26\x27\x2A-\x5C\x5E-\x7A\x7C-\x7E]+)/', $str, $m)) {
3252                    $result[] = $m[1] == 'NIL' ? NULL : $m[1];
3253                    $str = substr($str, strlen($m[1]));
3254                }
3255                break;
3256            }
3257        }
3258
3259        return $num == 1 ? $result[0] : $result;
3260    }
3261
3262    private function _xor($string, $string2)
3263    {
3264        $result = '';
3265        $size   = strlen($string);
3266
3267        for ($i=0; $i<$size; $i++) {
3268            $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3269        }
3270
3271        return $result;
3272    }
3273
3274    /**
3275     * Converts datetime string into unix timestamp
3276     *
3277     * @param string $date Date string
3278     *
3279     * @return int Unix timestamp
3280     */
3281    private function strToTime($date)
3282    {
3283        $ts = (int) rcube_strtotime($date);
3284        return $ts < 0 ? 0 : $ts;
3285    }
3286
3287    private function splitHeaderLine($string)
3288    {
3289        $pos = strpos($string, ':');
3290        if ($pos>0) {
3291            $res[0] = substr($string, 0, $pos);
3292            $res[1] = trim(substr($string, $pos+1));
3293            return $res;
3294        }
3295        return $string;
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.