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