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