source: subversion/branches/devel-mcache/roundcubemail/program/include/rcube_imap_generic.php @ 5048

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