source: subversion/branches/release-0.6/program/include/rcube_imap_generic.php @ 5130

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