Aleksander Machniak
2016-05-05 4921c21cff15b9ba2a5a05b2145861b01c9e85d6
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) {
4921c2 1131                 if (preg_match('/^\* OK \[/i', $line)) {
AM 1132                     $pos   = strcspn($line, ' ]', 6);
1133                     $token = strtoupper(substr($line, 6, $pos));
1134                     $pos   += 7;
1135
1136                     switch ($token) {
1137                     case 'UIDNEXT':
1138                     case 'UIDVALIDITY':
1139                     case 'UNSEEN':
1140                         if ($len = strspn($line, '0123456789', $pos)) {
1141                             $this->data[$token] = (int) substr($line, $pos, $len);
1142                         }
1143                         break;
1144
1145                     case 'HIGHESTMODSEQ':
1146                         if ($len = strspn($line, '0123456789', $pos)) {
1147                             $this->data[$token] = (string) substr($line, $pos, $len);
1148                         }
1149                         break;
1150
1151                     case 'NOMODSEQ':
1152                         $this->data[$token] = true;
1153                         break;
1154
1155                     case 'PERMANENTFLAGS':
1156                         $start = strpos($line, '(', $pos);
1157                         $end   = strrpos($line, ')');
1158                         if ($start && $end) {
1159                             $flags = substr($line, $start + 1, $end - $start - 1);
1160                             $this->data[$token] = explode(' ', $flags);
1161                         }
1162                         break;
80152b 1163                     }
c2c820 1164                 }
4921c2 1165                 else if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT|FETCH)/i', $line, $match)) {
AM 1166                     $token = strtoupper($match[2]);
1167                     switch ($token) {
1168                     case 'EXISTS':
1169                     case 'RECENT':
1170                         $this->data[$token] = (int) $match[1];
1171                         break;
80152b 1172
4921c2 1173                     case 'FETCH':
AM 1174                         // QRESYNC FETCH response (RFC5162)
1175                         $line       = substr($line, strlen($match[0]));
1176                         $fetch_data = $this->tokenizeResponse($line, 1);
1177                         $data       = array('id' => $match[1]);
1178
1179                         for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
1180                             $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
1181                         }
1182
1183                         $this->data['QRESYNC'][$data['uid']] = $data;
1184                         break;
80152b 1185                     }
A 1186                 }
1187                 // QRESYNC VANISHED response (RFC5162)
1188                 else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
1189                     $line   = substr($line, strlen($match[0]));
1190                     $v_data = $this->tokenizeResponse($line, 1);
1191
1192                     $this->data['VANISHED'] = $v_data;
c2c820 1193                 }
a2e8cb 1194             }
59c216 1195
90f81a 1196             $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
c2c820 1197             $this->selected = $mailbox;
86b241 1198
c2c820 1199             return true;
A 1200         }
8fcc3e 1201
59c216 1202         return false;
A 1203     }
1204
710e27 1205     /**
e232ac 1206      * Executes STATUS command
710e27 1207      *
A 1208      * @param string $mailbox Mailbox name
36911e 1209      * @param array  $items   Additional requested item names. By default
A 1210      *                        MESSAGES and UNSEEN are requested. Other defined
1211      *                        in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
710e27 1212      *
A 1213      * @return array Status item-value hash
1214      * @since 0.5-beta
1215      */
7fb0ae 1216     public function status($mailbox, $items = array())
710e27 1217     {
c2c820 1218         if (!strlen($mailbox)) {
A 1219             return false;
1220         }
36911e 1221
A 1222         if (!in_array('MESSAGES', $items)) {
1223             $items[] = 'MESSAGES';
1224         }
1225         if (!in_array('UNSEEN', $items)) {
1226             $items[] = 'UNSEEN';
1227         }
710e27 1228
A 1229         list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
1230             '(' . implode(' ', (array) $items) . ')'));
1231
eca19d 1232         if ($code == self::ERROR_OK && preg_match('/^\* STATUS /i', $response)) {
710e27 1233             $result   = array();
A 1234             $response = substr($response, 9); // remove prefix "* STATUS "
1235
1236             list($mbox, $items) = $this->tokenizeResponse($response, 2);
1237
0ea947 1238             // Fix for #1487859. Some buggy server returns not quoted
A 1239             // folder name with spaces. Let's try to handle this situation
1240             if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
1241                 $response = substr($response, $pos);
9e4246 1242                 $items    = $this->tokenizeResponse($response, 1);
AM 1243
0ea947 1244                 if (!is_array($items)) {
A 1245                     return $result;
1246                 }
1247             }
1248
710e27 1249             for ($i=0, $len=count($items); $i<$len; $i += 2) {
80152b 1250                 $result[$items[$i]] = $items[$i+1];
710e27 1251             }
36911e 1252
A 1253             $this->data['STATUS:'.$mailbox] = $result;
710e27 1254
c2c820 1255             return $result;
A 1256         }
710e27 1257
A 1258         return false;
1259     }
1260
e232ac 1261     /**
A 1262      * Executes EXPUNGE command
1263      *
d9dc32 1264      * @param string       $mailbox  Mailbox name
AM 1265      * @param string|array $messages Message UIDs to expunge
e232ac 1266      *
A 1267      * @return boolean True on success, False on error
1268      */
7fb0ae 1269     public function expunge($mailbox, $messages = null)
59c216 1270     {
c2c820 1271         if (!$this->select($mailbox)) {
90f81a 1272             return false;
A 1273         }
1274
1275         if (!$this->data['READ-WRITE']) {
c027ba 1276             $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
e232ac 1277             return false;
A 1278         }
1d5165 1279
e232ac 1280         // Clear internal status cache
1422b0 1281         $this->clear_status_cache($mailbox);
448409 1282
d9dc32 1283         if (!empty($messages) && $messages != '*' && $this->hasCapability('UIDPLUS')) {
AM 1284             $messages = self::compressMessageSet($messages);
1285             $result   = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
1286         }
1287         else {
c2c820 1288             $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
d9dc32 1289         }
e232ac 1290
c2c820 1291         if ($result == self::ERROR_OK) {
609d39 1292             $this->selected = null; // state has changed, need to reselect
c2c820 1293             return true;
A 1294         }
59c216 1295
c2c820 1296         return false;
59c216 1297     }
A 1298
e232ac 1299     /**
A 1300      * Executes CLOSE command
1301      *
1302      * @return boolean True on success, False on error
1303      * @since 0.5
1304      */
7fb0ae 1305     public function close()
e232ac 1306     {
86b241 1307         $result = $this->execute('CLOSE', null, self::COMMAND_NORESPONSE);
e232ac 1308
A 1309         if ($result == self::ERROR_OK) {
609d39 1310             $this->selected = null;
e232ac 1311             return true;
A 1312         }
1313
c2c820 1314         return false;
e232ac 1315     }
A 1316
1317     /**
e361bf 1318      * Folder subscription (SUBSCRIBE)
e232ac 1319      *
A 1320      * @param string $mailbox Mailbox name
1321      *
1322      * @return boolean True on success, False on error
1323      */
7fb0ae 1324     public function subscribe($mailbox)
e232ac 1325     {
c2c820 1326         $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
A 1327             self::COMMAND_NORESPONSE);
e232ac 1328
7fb0ae 1329         return $result == self::ERROR_OK;
e232ac 1330     }
A 1331
1332     /**
e361bf 1333      * Folder unsubscription (UNSUBSCRIBE)
e232ac 1334      *
A 1335      * @param string $mailbox Mailbox name
1336      *
1337      * @return boolean True on success, False on error
1338      */
7fb0ae 1339     public function unsubscribe($mailbox)
e232ac 1340     {
c2c820 1341         $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
e361bf 1342             self::COMMAND_NORESPONSE);
A 1343
7fb0ae 1344         return $result == self::ERROR_OK;
e361bf 1345     }
A 1346
1347     /**
1348      * Folder creation (CREATE)
1349      *
1350      * @param string $mailbox Mailbox name
7fb0ae 1351      * @param array  $types   Optional folder types (RFC 6154)
e361bf 1352      *
A 1353      * @return bool True on success, False on error
1354      */
7fb0ae 1355     public function createFolder($mailbox, $types = null)
e361bf 1356     {
dc0b50 1357         $args = array($this->escape($mailbox));
AM 1358
1359         // RFC 6154: CREATE-SPECIAL-USE
1360         if (!empty($types) && $this->getCapability('CREATE-SPECIAL-USE')) {
1361             $args[] = '(USE (' . implode(' ', $types) . '))';
1362         }
1363
1364         $result = $this->execute('CREATE', $args, self::COMMAND_NORESPONSE);
e361bf 1365
7fb0ae 1366         return $result == self::ERROR_OK;
e361bf 1367     }
A 1368
1369     /**
1370      * Folder renaming (RENAME)
1371      *
1372      * @param string $mailbox Mailbox name
1373      *
1374      * @return bool True on success, False on error
1375      */
7fb0ae 1376     public function renameFolder($from, $to)
e361bf 1377     {
A 1378         $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
c2c820 1379             self::COMMAND_NORESPONSE);
e232ac 1380
7fb0ae 1381         return $result == self::ERROR_OK;
e232ac 1382     }
A 1383
1384     /**
1385      * Executes DELETE command
1386      *
1387      * @param string $mailbox Mailbox name
1388      *
1389      * @return boolean True on success, False on error
1390      */
7fb0ae 1391     public function deleteFolder($mailbox)
e232ac 1392     {
A 1393         $result = $this->execute('DELETE', array($this->escape($mailbox)),
c2c820 1394             self::COMMAND_NORESPONSE);
e232ac 1395
7fb0ae 1396         return $result == self::ERROR_OK;
e232ac 1397     }
A 1398
1399     /**
1400      * Removes all messages in a folder
1401      *
1402      * @param string $mailbox Mailbox name
1403      *
1404      * @return boolean True on success, False on error
1405      */
7fb0ae 1406     public function clearFolder($mailbox)
e232ac 1407     {
7fb0ae 1408         if ($this->countMessages($mailbox) > 0) {
a9ed78 1409             $res = $this->flag($mailbox, '1:*', 'DELETED');
c2c820 1410         }
e232ac 1411
90f81a 1412         if ($res) {
7fb0ae 1413             if ($this->selected === $mailbox) {
90f81a 1414                 $res = $this->close();
7fb0ae 1415             }
AM 1416             else {
c2c820 1417                 $res = $this->expunge($mailbox);
7fb0ae 1418             }
90f81a 1419         }
e232ac 1420
c2c820 1421         return $res;
e361bf 1422     }
A 1423
1424     /**
1425      * Returns list of mailboxes
1426      *
1427      * @param string $ref         Reference name
1428      * @param string $mailbox     Mailbox name
07893b 1429      * @param array  $return_opts (see self::_listMailboxes)
e361bf 1430      * @param array  $select_opts (see self::_listMailboxes)
A 1431      *
e0492d 1432      * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
AM 1433      *                    is requested, False on error.
e361bf 1434      */
7fb0ae 1435     public function listMailboxes($ref, $mailbox, $return_opts = array(), $select_opts = array())
e361bf 1436     {
07893b 1437         return $this->_listMailboxes($ref, $mailbox, false, $return_opts, $select_opts);
e361bf 1438     }
A 1439
1440     /**
1441      * Returns list of subscribed mailboxes
1442      *
1443      * @param string $ref         Reference name
1444      * @param string $mailbox     Mailbox name
07893b 1445      * @param array  $return_opts (see self::_listMailboxes)
e361bf 1446      *
e0492d 1447      * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
AM 1448      *                    is requested, False on error.
e361bf 1449      */
7fb0ae 1450     public function listSubscribed($ref, $mailbox, $return_opts = array())
e361bf 1451     {
86b241 1452         return $this->_listMailboxes($ref, $mailbox, true, $return_opts, null);
e361bf 1453     }
A 1454
1455     /**
1456      * IMAP LIST/LSUB command
1457      *
1458      * @param string $ref         Reference name
1459      * @param string $mailbox     Mailbox name
1460      * @param bool   $subscribed  Enables returning subscribed mailboxes only
07893b 1461      * @param array  $return_opts List of RETURN options (RFC5819: LIST-STATUS, RFC5258: LIST-EXTENDED)
AM 1462      *                            Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN,
1463      *                                      MYRIGHTS, SUBSCRIBED, CHILDREN
e361bf 1464      * @param array  $select_opts List of selection options (RFC5258: LIST-EXTENDED)
dc0b50 1465      *                            Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE,
AM 1466      *                                      SPECIAL-USE (RFC6154)
e361bf 1467      *
e0492d 1468      * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
AM 1469      *                    is requested, False on error.
e361bf 1470      */
232bcd 1471     protected function _listMailboxes($ref, $mailbox, $subscribed=false,
07893b 1472         $return_opts=array(), $select_opts=array())
e361bf 1473     {
A 1474         if (!strlen($mailbox)) {
1475             $mailbox = '*';
1476         }
1477
1478         $args = array();
dc0b50 1479         $rets = array();
e361bf 1480
A 1481         if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
1482             $select_opts = (array) $select_opts;
1483
1484             $args[] = '(' . implode(' ', $select_opts) . ')';
1485         }
1486
1487         $args[] = $this->escape($ref);
1488         $args[] = $this->escape($mailbox);
1489
07893b 1490         if (!empty($return_opts) && $this->getCapability('LIST-EXTENDED')) {
e0492d 1491             $ext_opts    = array('SUBSCRIBED', 'CHILDREN');
AM 1492             $rets        = array_intersect($return_opts, $ext_opts);
1493             $return_opts = array_diff($return_opts, $rets);
dc0b50 1494         }
e361bf 1495
07893b 1496         if (!empty($return_opts) && $this->getCapability('LIST-STATUS')) {
AM 1497             $lstatus     = true;
1498             $status_opts = array('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN');
1499             $opts        = array_diff($return_opts, $status_opts);
1500             $status_opts = array_diff($return_opts, $opts);
dc0b50 1501
AM 1502             if (!empty($status_opts)) {
1503                 $rets[] = 'STATUS (' . implode(' ', $status_opts) . ')';
07893b 1504             }
AM 1505
1506             if (!empty($opts)) {
1507                 $rets = array_merge($rets, $opts);
dc0b50 1508             }
AM 1509         }
1510
1511         if (!empty($rets)) {
1512             $args[] = 'RETURN (' . implode(' ', $rets) . ')';
e361bf 1513         }
A 1514
1515         list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
1516
1517         if ($code == self::ERROR_OK) {
1518             $folders  = array();
1519             $last     = 0;
1520             $pos      = 0;
1521             $response .= "\r\n";
1522
1523             while ($pos = strpos($response, "\r\n", $pos+1)) {
1524                 // literal string, not real end-of-command-line
1525                 if ($response[$pos-1] == '}') {
1526                     continue;
1527                 }
1528
1529                 $line = substr($response, $last, $pos - $last);
1530                 $last = $pos + 2;
1531
07893b 1532                 if (!preg_match('/^\* (LIST|LSUB|STATUS|MYRIGHTS) /i', $line, $m)) {
e361bf 1533                     continue;
A 1534                 }
07893b 1535
e361bf 1536                 $cmd  = strtoupper($m[1]);
A 1537                 $line = substr($line, strlen($m[0]));
1538
1539                 // * LIST (<options>) <delimiter> <mailbox>
1540                 if ($cmd == 'LIST' || $cmd == 'LSUB') {
1541                     list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
1542
2b80d5 1543                     // Remove redundant separator at the end of folder name, UW-IMAP bug? (#1488879)
AM 1544                     if ($delim) {
1545                         $mailbox = rtrim($mailbox, $delim);
1546                     }
1547
e361bf 1548                     // Add to result array
A 1549                     if (!$lstatus) {
1550                         $folders[] = $mailbox;
1551                     }
1552                     else {
1553                         $folders[$mailbox] = array();
1554                     }
1555
bd2846 1556                     // store folder options
AM 1557                     if ($cmd == 'LIST') {
c6a9cd 1558                         // Add to options array
7fb0ae 1559                         if (empty($this->data['LIST'][$mailbox])) {
c6a9cd 1560                             $this->data['LIST'][$mailbox] = $opts;
7fb0ae 1561                         }
AM 1562                         else if (!empty($opts)) {
c6a9cd 1563                             $this->data['LIST'][$mailbox] = array_unique(array_merge(
A 1564                                 $this->data['LIST'][$mailbox], $opts));
7fb0ae 1565                         }
c6a9cd 1566                     }
e361bf 1567                 }
07893b 1568                 else if ($lstatus) {
AM 1569                     // * STATUS <mailbox> (<result>)
1570                     if ($cmd == 'STATUS') {
1571                         list($mailbox, $status) = $this->tokenizeResponse($line, 2);
e361bf 1572
07893b 1573                         for ($i=0, $len=count($status); $i<$len; $i += 2) {
AM 1574                             list($name, $value) = $this->tokenizeResponse($status, 2);
1575                             $folders[$mailbox][$name] = $value;
1576                         }
1577                     }
1578                     // * MYRIGHTS <mailbox> <acl>
1579                     else if ($cmd == 'MYRIGHTS') {
1580                         list($mailbox, $acl)  = $this->tokenizeResponse($line, 2);
1581                         $folders[$mailbox]['MYRIGHTS'] = $acl;
e361bf 1582                     }
A 1583                 }
1584             }
1585
1586             return $folders;
1587         }
1588
1589         return false;
e232ac 1590     }
A 1591
1592     /**
1593      * Returns count of all messages in a folder
1594      *
1595      * @param string $mailbox Mailbox name
1596      *
1597      * @return int Number of messages, False on error
1598      */
7fb0ae 1599     public function countMessages($mailbox)
59c216 1600     {
1422b0 1601         if ($this->selected === $mailbox && isset($this->data['EXISTS'])) {
c2c820 1602             return $this->data['EXISTS'];
A 1603         }
710e27 1604
36911e 1605         // Check internal cache
A 1606         $cache = $this->data['STATUS:'.$mailbox];
1607         if (!empty($cache) && isset($cache['MESSAGES'])) {
1608             return (int) $cache['MESSAGES'];
1609         }
1610
1611         // Try STATUS (should be faster than SELECT)
1612         $counts = $this->status($mailbox);
36ed9d 1613         if (is_array($counts)) {
A 1614             return (int) $counts['MESSAGES'];
1615         }
1616
710e27 1617         return false;
e232ac 1618     }
A 1619
1620     /**
1621      * Returns count of messages with \Recent flag in a folder
1622      *
1623      * @param string $mailbox Mailbox name
1624      *
1625      * @return int Number of messages, False on error
1626      */
7fb0ae 1627     public function countRecent($mailbox)
e232ac 1628     {
1422b0 1629         if ($this->selected === $mailbox && isset($this->data['RECENT'])) {
AM 1630             return $this->data['RECENT'];
c2c820 1631         }
e232ac 1632
1422b0 1633         // Check internal cache
AM 1634         $cache = $this->data['STATUS:'.$mailbox];
1635         if (!empty($cache) && isset($cache['RECENT'])) {
1636             return (int) $cache['RECENT'];
1637         }
e232ac 1638
1422b0 1639         // Try STATUS (should be faster than SELECT)
AM 1640         $counts = $this->status($mailbox, array('RECENT'));
1641         if (is_array($counts)) {
1642             return (int) $counts['RECENT'];
c2c820 1643         }
e232ac 1644
c2c820 1645         return false;
710e27 1646     }
A 1647
1648     /**
1649      * Returns count of messages without \Seen flag in a specified folder
1650      *
1651      * @param string $mailbox Mailbox name
1652      *
1653      * @return int Number of messages, False on error
1654      */
7fb0ae 1655     public function countUnseen($mailbox)
710e27 1656     {
36911e 1657         // Check internal cache
A 1658         $cache = $this->data['STATUS:'.$mailbox];
1659         if (!empty($cache) && isset($cache['UNSEEN'])) {
1660             return (int) $cache['UNSEEN'];
1661         }
1662
1663         // Try STATUS (should be faster than SELECT+SEARCH)
1664         $counts = $this->status($mailbox);
710e27 1665         if (is_array($counts)) {
A 1666             return (int) $counts['UNSEEN'];
1667         }
1668
1669         // Invoke SEARCH as a fallback
659cf1 1670         $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
1d7dcc 1671         if (!$index->is_error()) {
40c45e 1672             return $index->count();
710e27 1673         }
59c216 1674
A 1675         return false;
1676     }
1677
890eae 1678     /**
A 1679      * Executes ID command (RFC2971)
1680      *
1681      * @param array $items Client identification information key/value hash
1682      *
1683      * @return array Server identification information key/value hash
1684      * @since 0.6
1685      */
7fb0ae 1686     public function id($items = array())
890eae 1687     {
A 1688         if (is_array($items) && !empty($items)) {
1689             foreach ($items as $key => $value) {
5c2f06 1690                 $args[] = $this->escape($key, true);
A 1691                 $args[] = $this->escape($value, true);
890eae 1692             }
A 1693         }
1694
1695         list($code, $response) = $this->execute('ID', array(
1696             !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
1697         ));
1698
eca19d 1699         if ($code == self::ERROR_OK && preg_match('/^\* ID /i', $response)) {
890eae 1700             $response = substr($response, 5); // remove prefix "* ID "
1463a5 1701             $items    = $this->tokenizeResponse($response, 1);
890eae 1702             $result   = null;
A 1703
1704             for ($i=0, $len=count($items); $i<$len; $i += 2) {
1705                 $result[$items[$i]] = $items[$i+1];
1706             }
80152b 1707
A 1708             return $result;
1709         }
1710
1711         return false;
1712     }
1713
1714     /**
1715      * Executes ENABLE command (RFC5161)
1716      *
1717      * @param mixed $extension Extension name to enable (or array of names)
1718      *
1719      * @return array|bool List of enabled extensions, False on error
1720      * @since 0.6
1721      */
7fb0ae 1722     public function enable($extension)
80152b 1723     {
7ab9c1 1724         if (empty($extension)) {
80152b 1725             return false;
7ab9c1 1726         }
80152b 1727
7ab9c1 1728         if (!$this->hasCapability('ENABLE')) {
80152b 1729             return false;
7ab9c1 1730         }
80152b 1731
7ab9c1 1732         if (!is_array($extension)) {
80152b 1733             $extension = array($extension);
7ab9c1 1734         }
AM 1735
1736         if (!empty($this->extensions_enabled)) {
1737             // check if all extensions are already enabled
1738             $diff = array_diff($extension, $this->extensions_enabled);
1739
1740             if (empty($diff)) {
1741                 return $extension;
1742             }
1743
1744             // Make sure the mailbox isn't selected, before enabling extension(s)
1745             if ($this->selected !== null) {
1746                 $this->close();
1747             }
1748         }
80152b 1749
A 1750         list($code, $response) = $this->execute('ENABLE', $extension);
1751
eca19d 1752         if ($code == self::ERROR_OK && preg_match('/^\* ENABLED /i', $response)) {
80152b 1753             $response = substr($response, 10); // remove prefix "* ENABLED "
A 1754             $result   = (array) $this->tokenizeResponse($response);
890eae 1755
7ab9c1 1756             $this->extensions_enabled = array_unique(array_merge((array)$this->extensions_enabled, $result));
AM 1757
1758             return $this->extensions_enabled;
890eae 1759         }
A 1760
1761         return false;
1762     }
1763
40c45e 1764     /**
A 1765      * Executes SORT command
1766      *
1767      * @param string $mailbox    Mailbox name
1768      * @param string $field      Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
bee1e1 1769      * @param string $criteria   Searching criteria
40c45e 1770      * @param bool   $return_uid Enables UID SORT usage
A 1771      * @param string $encoding   Character set
1772      *
1773      * @return rcube_result_index Response data
1774      */
7fb0ae 1775     public function sort($mailbox, $field = 'ARRIVAL', $criteria = '', $return_uid = false, $encoding = 'US-ASCII')
59c216 1776     {
bee1e1 1777         $old_sel   = $this->selected;
AM 1778         $supported = array('ARRIVAL', 'CC', 'DATE', 'FROM', 'SIZE', 'SUBJECT', 'TO');
1779         $field     = strtoupper($field);
1780
c2c820 1781         if ($field == 'INTERNALDATE') {
A 1782             $field = 'ARRIVAL';
1783         }
1d5165 1784
bee1e1 1785         if (!in_array($field, $supported)) {
40c45e 1786             return new rcube_result_index($mailbox);
c2c820 1787         }
59c216 1788
c2c820 1789         if (!$this->select($mailbox)) {
40c45e 1790             return new rcube_result_index($mailbox);
c2c820 1791         }
1d5165 1792
bee1e1 1793         // return empty result when folder is empty and we're just after SELECT
AM 1794         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1795             return new rcube_result_index($mailbox, '* SORT');
1796         }
1797
3c71c6 1798         // RFC 5957: SORT=DISPLAY
A 1799         if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
1800             $field = 'DISPLAY' . $field;
1801         }
1802
bee1e1 1803         $encoding = $encoding ? trim($encoding) : 'US-ASCII';
AM 1804         $criteria = $criteria ? 'ALL ' . trim($criteria) : 'ALL';
59c216 1805
40c45e 1806         list($code, $response) = $this->execute($return_uid ? 'UID SORT' : 'SORT',
bee1e1 1807             array("($field)", $encoding, $criteria));
59c216 1808
40c45e 1809         if ($code != self::ERROR_OK) {
A 1810             $response = null;
c2c820 1811         }
1d5165 1812
40c45e 1813         return new rcube_result_index($mailbox, $response);
59c216 1814     }
A 1815
40c45e 1816     /**
e361bf 1817      * Executes THREAD command
A 1818      *
1819      * @param string $mailbox    Mailbox name
1820      * @param string $algorithm  Threading algorithm (ORDEREDSUBJECT, REFERENCES, REFS)
1821      * @param string $criteria   Searching criteria
1822      * @param bool   $return_uid Enables UIDs in result instead of sequence numbers
1823      * @param string $encoding   Character set
1824      *
1825      * @return rcube_result_thread Thread data
1826      */
7fb0ae 1827     public function thread($mailbox, $algorithm = 'REFERENCES', $criteria = '', $return_uid = false, $encoding = 'US-ASCII')
e361bf 1828     {
A 1829         $old_sel = $this->selected;
1830
1831         if (!$this->select($mailbox)) {
1832             return new rcube_result_thread($mailbox);
1833         }
1834
1835         // return empty result when folder is empty and we're just after SELECT
1836         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
bee1e1 1837             return new rcube_result_thread($mailbox, '* THREAD');
e361bf 1838         }
A 1839
1840         $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1841         $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1842         $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1843
1844         list($code, $response) = $this->execute($return_uid ? 'UID THREAD' : 'THREAD',
1845             array($algorithm, $encoding, $criteria));
1846
1847         if ($code != self::ERROR_OK) {
1848             $response = null;
1849         }
1850
1851         return new rcube_result_thread($mailbox, $response);
1852     }
1853
1854     /**
1855      * Executes SEARCH command
1856      *
1857      * @param string $mailbox    Mailbox name
1858      * @param string $criteria   Searching criteria
1859      * @param bool   $return_uid Enable UID in result instead of sequence ID
1860      * @param array  $items      Return items (MIN, MAX, COUNT, ALL)
1861      *
1862      * @return rcube_result_index Result data
1863      */
7fb0ae 1864     public function search($mailbox, $criteria, $return_uid = false, $items = array())
e361bf 1865     {
A 1866         $old_sel = $this->selected;
1867
1868         if (!$this->select($mailbox)) {
1869             return new rcube_result_index($mailbox);
1870         }
1871
1872         // return empty result when folder is empty and we're just after SELECT
1873         if ($old_sel != $mailbox && !$this->data['EXISTS']) {
1874             return new rcube_result_index($mailbox, '* SEARCH');
1875         }
1876
1877         // If ESEARCH is supported always use ALL
1878         // but not when items are specified or using simple id2uid search
91cb9d 1879         if (empty($items) && preg_match('/[^0-9]/', $criteria)) {
e361bf 1880             $items = array('ALL');
A 1881         }
1882
1883         $esearch  = empty($items) ? false : $this->getCapability('ESEARCH');
1884         $criteria = trim($criteria);
1885         $params   = '';
1886
1887         // RFC4731: ESEARCH
1888         if (!empty($items) && $esearch) {
1889             $params .= 'RETURN (' . implode(' ', $items) . ')';
1890         }
1891
1892         if (!empty($criteria)) {
1893             $params .= ($params ? ' ' : '') . $criteria;
1894         }
1895         else {
1896             $params .= 'ALL';
1897         }
1898
1899         list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
1900             array($params));
1901
1902         if ($code != self::ERROR_OK) {
1903             $response = null;
1904         }
1905
1906         return new rcube_result_index($mailbox, $response);
1907     }
1908
1909     /**
40c45e 1910      * Simulates SORT command by using FETCH and sorting.
A 1911      *
1912      * @param string       $mailbox      Mailbox name
1913      * @param string|array $message_set  Searching criteria (list of messages to return)
1914      * @param string       $index_field  Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
1915      * @param bool         $skip_deleted Makes that DELETED messages will be skipped
1916      * @param bool         $uidfetch     Enables UID FETCH usage
1917      * @param bool         $return_uid   Enables returning UIDs instead of IDs
1918      *
1919      * @return rcube_result_index Response data
1920      */
7fb0ae 1921     public function index($mailbox, $message_set, $index_field='', $skip_deleted=true,
40c45e 1922         $uidfetch=false, $return_uid=false)
A 1923     {
1924         $msg_index = $this->fetchHeaderIndex($mailbox, $message_set,
1925             $index_field, $skip_deleted, $uidfetch, $return_uid);
1926
1927         if (!empty($msg_index)) {
1928             asort($msg_index); // ASC
1929             $msg_index = array_keys($msg_index);
1930             $msg_index = '* SEARCH ' . implode(' ', $msg_index);
1931         }
1932         else {
1933             $msg_index = is_array($msg_index) ? '* SEARCH' : null;
1934         }
1935
1936         return new rcube_result_index($mailbox, $msg_index);
1937     }
1938
7fb0ae 1939     /**
AM 1940      * Fetches specified header/data value for a set of messages.
1941      *
1942      * @param string       $mailbox      Mailbox name
1943      * @param string|array $message_set  Searching criteria (list of messages to return)
1944      * @param string       $index_field  Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
1945      * @param bool         $skip_deleted Makes that DELETED messages will be skipped
1946      * @param bool         $uidfetch     Enables UID FETCH usage
1947      * @param bool         $return_uid   Enables returning UIDs instead of IDs
1948      *
1949      * @return array|bool List of header values or False on failure
1950      */
1951     public function fetchHeaderIndex($mailbox, $message_set, $index_field = '', $skip_deleted = true,
1952         $uidfetch = false, $return_uid = false)
59c216 1953     {
c2c820 1954         if (is_array($message_set)) {
7fb0ae 1955             if (!($message_set = $this->compressMessageSet($message_set))) {
c2c820 1956                 return false;
7fb0ae 1957             }
AM 1958         }
1959         else {
c2c820 1960             list($from_idx, $to_idx) = explode(':', $message_set);
A 1961             if (empty($message_set) ||
7fb0ae 1962                 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)
AM 1963             ) {
c2c820 1964                 return false;
A 1965             }
59c216 1966         }
A 1967
c2c820 1968         $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
59c216 1969
c2c820 1970         $fields_a['DATE']         = 1;
A 1971         $fields_a['INTERNALDATE'] = 4;
1972         $fields_a['ARRIVAL']      = 4;
1973         $fields_a['FROM']         = 1;
1974         $fields_a['REPLY-TO']     = 1;
1975         $fields_a['SENDER']       = 1;
1976         $fields_a['TO']           = 1;
1977         $fields_a['CC']           = 1;
1978         $fields_a['SUBJECT']      = 1;
1979         $fields_a['UID']          = 2;
1980         $fields_a['SIZE']         = 2;
1981         $fields_a['SEEN']         = 3;
1982         $fields_a['RECENT']       = 3;
1983         $fields_a['DELETED']      = 3;
59c216 1984
c2c820 1985         if (!($mode = $fields_a[$index_field])) {
A 1986             return false;
1987         }
1d5165 1988
7fb0ae 1989         //  Select the mailbox
c2c820 1990         if (!$this->select($mailbox)) {
A 1991             return false;
1992         }
59c216 1993
c2c820 1994         // build FETCH command string
40c45e 1995         $key    = $this->nextTag();
A 1996         $cmd    = $uidfetch ? 'UID FETCH' : 'FETCH';
1997         $fields = array();
59c216 1998
7fb0ae 1999         if ($return_uid) {
40c45e 2000             $fields[] = 'UID';
7fb0ae 2001         }
AM 2002         if ($skip_deleted) {
40c45e 2003             $fields[] = 'FLAGS';
7fb0ae 2004         }
40c45e 2005
A 2006         if ($mode == 1) {
7fb0ae 2007             if ($index_field == 'DATE') {
40c45e 2008                 $fields[] = 'INTERNALDATE';
7fb0ae 2009             }
40c45e 2010             $fields[] = "BODY.PEEK[HEADER.FIELDS ($index_field)]";
A 2011         }
c2c820 2012         else if ($mode == 2) {
7fb0ae 2013             if ($index_field == 'SIZE') {
40c45e 2014                 $fields[] = 'RFC822.SIZE';
7fb0ae 2015             }
AM 2016             else if (!$return_uid || $index_field != 'UID') {
40c45e 2017                 $fields[] = $index_field;
7fb0ae 2018             }
40c45e 2019         }
7fb0ae 2020         else if ($mode == 3 && !$skip_deleted) {
40c45e 2021             $fields[] = 'FLAGS';
7fb0ae 2022         }
AM 2023         else if ($mode == 4) {
40c45e 2024             $fields[] = 'INTERNALDATE';
7fb0ae 2025         }
c2c820 2026
40c45e 2027         $request = "$key $cmd $message_set (" . implode(' ', $fields) . ")";
c2c820 2028
A 2029         if (!$this->putLine($request)) {
2030             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2031             return false;
2032         }
2033
2034         $result = array();
2035
2036         do {
2037             $line = rtrim($this->readLine(200));
2038             $line = $this->multLine($line);
2039
2040             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
2041                 $id     = $m[1];
86b241 2042                 $flags  = null;
c2c820 2043
40c45e 2044                 if ($return_uid) {
7fb0ae 2045                     if (preg_match('/UID ([0-9]+)/', $line, $matches)) {
40c45e 2046                         $id = (int) $matches[1];
7fb0ae 2047                     }
AM 2048                     else {
40c45e 2049                         continue;
7fb0ae 2050                     }
40c45e 2051                 }
c2c820 2052                 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
A 2053                     $flags = explode(' ', strtoupper($matches[1]));
2054                     if (in_array('\\DELETED', $flags)) {
2055                         continue;
2056                     }
2057                 }
2058
2059                 if ($mode == 1 && $index_field == 'DATE') {
2060                     if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
2061                         $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
2062                         $value = trim($value);
2063                         $result[$id] = $this->strToTime($value);
2064                     }
2065                     // non-existent/empty Date: header, use INTERNALDATE
2066                     if (empty($result[$id])) {
7fb0ae 2067                         if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
c2c820 2068                             $result[$id] = $this->strToTime($matches[1]);
7fb0ae 2069                         }
AM 2070                         else {
c2c820 2071                             $result[$id] = 0;
7fb0ae 2072                         }
c2c820 2073                     }
7fb0ae 2074                 }
AM 2075                 else if ($mode == 1) {
c2c820 2076                     if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
A 2077                         $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
2078                         $result[$id] = trim($value);
7fb0ae 2079                     }
AM 2080                     else {
c2c820 2081                         $result[$id] = '';
A 2082                     }
7fb0ae 2083                 }
AM 2084                 else if ($mode == 2) {
4922e5 2085                     if (preg_match('/' . $index_field . ' ([0-9]+)/', $line, $matches)) {
AM 2086                         $result[$id] = trim($matches[1]);
7fb0ae 2087                     }
AM 2088                     else {
c2c820 2089                         $result[$id] = 0;
A 2090                     }
7fb0ae 2091                 }
AM 2092                 else if ($mode == 3) {
c2c820 2093                     if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
A 2094                         $flags = explode(' ', $matches[1]);
2095                     }
7fb0ae 2096                     $result[$id] = in_array("\\".$index_field, (array) $flags) ? 1 : 0;
AM 2097                 }
2098                 else if ($mode == 4) {
c2c820 2099                     if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
A 2100                         $result[$id] = $this->strToTime($matches[1]);
7fb0ae 2101                     }
AM 2102                     else {
c2c820 2103                         $result[$id] = 0;
A 2104                     }
2105                 }
2106             }
7fb0ae 2107         }
AM 2108         while (!$this->startsWith($line, $key, true, true));
c2c820 2109
A 2110         return $result;
59c216 2111     }
A 2112
93272e 2113     /**
A 2114      * Returns message sequence identifier
2115      *
2116      * @param string $mailbox Mailbox name
2117      * @param int    $uid     Message unique identifier (UID)
2118      *
2119      * @return int Message sequence identifier
2120      */
7fb0ae 2121     public function UID2ID($mailbox, $uid)
59c216 2122     {
c2c820 2123         if ($uid > 0) {
40c45e 2124             $index = $this->search($mailbox, "UID $uid");
A 2125
2126             if ($index->count() == 1) {
2127                 $arr = $index->get();
2128                 return (int) $arr[0];
c2c820 2129             }
A 2130         }
59c216 2131     }
A 2132
93272e 2133     /**
A 2134      * Returns message unique identifier (UID)
2135      *
2136      * @param string $mailbox Mailbox name
2137      * @param int    $uid     Message sequence identifier
2138      *
2139      * @return int Message unique identifier
2140      */
7fb0ae 2141     public function ID2UID($mailbox, $id)
59c216 2142     {
c2c820 2143         if (empty($id) || $id < 0) {
80152b 2144             return null;
c2c820 2145         }
59c216 2146
c2c820 2147         if (!$this->select($mailbox)) {
93272e 2148             return null;
59c216 2149         }
A 2150
85f420 2151         if ($uid = $this->data['UID-MAP'][$id]) {
AM 2152             return $uid;
2153         }
2154
2155         if (isset($this->data['EXISTS']) && $id > $this->data['EXISTS']) {
2156             return null;
2157         }
2158
40c45e 2159         $index = $this->search($mailbox, $id, true);
8fcc3e 2160
40c45e 2161         if ($index->count() == 1) {
A 2162             $arr = $index->get();
85f420 2163             return $this->data['UID-MAP'][$id] = (int) $arr[0];
8fcc3e 2164         }
e361bf 2165     }
A 2166
2167     /**
2168      * Sets flag of the message(s)
2169      *
7fb0ae 2170      * @param string       $mailbox  Mailbox name
AM 2171      * @param string|array $messages Message UID(s)
2172      * @param string       $flag     Flag name
e361bf 2173      *
A 2174      * @return bool True on success, False on failure
2175      */
7fb0ae 2176     public function flag($mailbox, $messages, $flag)
AM 2177     {
e361bf 2178         return $this->modFlag($mailbox, $messages, $flag, '+');
A 2179     }
2180
2181     /**
2182      * Unsets flag of the message(s)
2183      *
7fb0ae 2184      * @param string       $mailbox  Mailbox name
AM 2185      * @param string|array $messages Message UID(s)
2186      * @param string       $flag     Flag name
e361bf 2187      *
A 2188      * @return bool True on success, False on failure
2189      */
7fb0ae 2190     public function unflag($mailbox, $messages, $flag)
AM 2191     {
e361bf 2192         return $this->modFlag($mailbox, $messages, $flag, '-');
A 2193     }
2194
2195     /**
2196      * Changes flag of the message(s)
2197      *
7fb0ae 2198      * @param string       $mailbox  Mailbox name
AM 2199      * @param string|array $messages Message UID(s)
2200      * @param string       $flag     Flag name
2201      * @param string       $mod      Modifier [+|-]. Default: "+".
e361bf 2202      *
A 2203      * @return bool True on success, False on failure
2204      */
232bcd 2205     protected function modFlag($mailbox, $messages, $flag, $mod = '+')
e361bf 2206     {
7fb0ae 2207         if (!$flag) {
AM 2208             return false;
2209         }
2210
e361bf 2211         if (!$this->select($mailbox)) {
A 2212             return false;
2213         }
2214
2215         if (!$this->data['READ-WRITE']) {
c027ba 2216             $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
e361bf 2217             return false;
A 2218         }
2219
e15674 2220         if ($this->flags[strtoupper($flag)]) {
AM 2221             $flag = $this->flags[strtoupper($flag)];
07fa81 2222         }
AM 2223
2224         // if PERMANENTFLAGS is not specified all flags are allowed
2225         if (!empty($this->data['PERMANENTFLAGS'])
2226             && !in_array($flag, (array) $this->data['PERMANENTFLAGS'])
2227             && !in_array('\\*', (array) $this->data['PERMANENTFLAGS'])
e15674 2228         ) {
AM 2229             return false;
2230         }
2231
e361bf 2232         // Clear internal status cache
A 2233         if ($flag == 'SEEN') {
2234             unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
2235         }
2236
e15674 2237         if ($mod != '+' && $mod != '-') {
AM 2238             $mod = '+';
2239         }
2240
e361bf 2241         $result = $this->execute('UID STORE', array(
A 2242             $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
2243             self::COMMAND_NORESPONSE);
2244
7fb0ae 2245         return $result == self::ERROR_OK;
e361bf 2246     }
A 2247
2248     /**
2249      * Copies message(s) from one folder to another
2250      *
7fb0ae 2251      * @param string|array $messages Message UID(s)
AM 2252      * @param string       $from     Mailbox name
2253      * @param string       $to       Destination mailbox name
e361bf 2254      *
A 2255      * @return bool True on success, False on failure
2256      */
7fb0ae 2257     public function copy($messages, $from, $to)
e361bf 2258     {
397976 2259         // Clear last COPYUID data
AM 2260         unset($this->data['COPYUID']);
2261
e361bf 2262         if (!$this->select($from)) {
A 2263             return false;
2264         }
2265
2266         // Clear internal status cache
2267         unset($this->data['STATUS:'.$to]);
2268
2269         $result = $this->execute('UID COPY', array(
2270             $this->compressMessageSet($messages), $this->escape($to)),
2271             self::COMMAND_NORESPONSE);
2272
7fb0ae 2273         return $result == self::ERROR_OK;
e361bf 2274     }
A 2275
2276     /**
2277      * Moves message(s) from one folder to another.
2278      *
7fb0ae 2279      * @param string|array $messages Message UID(s)
AM 2280      * @param string       $from     Mailbox name
2281      * @param string       $to       Destination mailbox name
e361bf 2282      *
A 2283      * @return bool True on success, False on failure
2284      */
7fb0ae 2285     public function move($messages, $from, $to)
e361bf 2286     {
A 2287         if (!$this->select($from)) {
2288             return false;
2289         }
2290
2291         if (!$this->data['READ-WRITE']) {
c027ba 2292             $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
e361bf 2293             return false;
A 2294         }
2295
d9dc32 2296         // use MOVE command (RFC 6851)
AM 2297         if ($this->hasCapability('MOVE')) {
2298             // Clear last COPYUID data
2299             unset($this->data['COPYUID']);
e361bf 2300
A 2301             // Clear internal status cache
d9dc32 2302             unset($this->data['STATUS:'.$to]);
1422b0 2303             $this->clear_status_cache($from);
e361bf 2304
ea98ec 2305             $result = $this->execute('UID MOVE', array(
d9dc32 2306                 $this->compressMessageSet($messages), $this->escape($to)),
AM 2307                 self::COMMAND_NORESPONSE);
ea98ec 2308
7fb0ae 2309             return $result == self::ERROR_OK;
e361bf 2310         }
ea98ec 2311
d9dc32 2312         // use COPY + STORE +FLAGS.SILENT \Deleted + EXPUNGE
ea98ec 2313         $result = $this->copy($messages, $from, $to);
d9dc32 2314
ea98ec 2315         if ($result) {
AM 2316             // Clear internal status cache
2317             unset($this->data['STATUS:'.$from]);
d9dc32 2318
ea98ec 2319             $result = $this->flag($from, $messages, 'DELETED');
d9dc32 2320
ea98ec 2321             if ($messages == '*') {
AM 2322                 // CLOSE+SELECT should be faster than EXPUNGE
2323                 $this->close();
2324             }
2325             else {
2326                 $this->expunge($from, $messages);
d9dc32 2327             }
AM 2328         }
2329
ea98ec 2330         return $result;
59c216 2331     }
A 2332
80152b 2333     /**
A 2334      * FETCH command (RFC3501)
2335      *
2336      * @param string $mailbox     Mailbox name
2337      * @param mixed  $message_set Message(s) sequence identifier(s) or UID(s)
2338      * @param bool   $is_uid      True if $message_set contains UIDs
2339      * @param array  $query_items FETCH command data items
2340      * @param string $mod_seq     Modification sequence for CHANGEDSINCE (RFC4551) query
2341      * @param bool   $vanished    Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
2342      *
0c2596 2343      * @return array List of rcube_message_header elements, False on error
80152b 2344      * @since 0.6
A 2345      */
7fb0ae 2346     public function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
80152b 2347         $mod_seq = null, $vanished = false)
59c216 2348     {
c2c820 2349         if (!$this->select($mailbox)) {
A 2350             return false;
2351         }
59c216 2352
c2c820 2353         $message_set = $this->compressMessageSet($message_set);
80152b 2354         $result      = array();
59c216 2355
c2c820 2356         $key      = $this->nextTag();
80152b 2357         $request  = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
A 2358         $request .= "(" . implode(' ', $query_items) . ")";
2359
2360         if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
2361             $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
2362         }
59c216 2363
c2c820 2364         if (!$this->putLine($request)) {
c0ed78 2365             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
c2c820 2366             return false;
A 2367         }
80152b 2368
c2c820 2369         do {
A 2370             $line = $this->readLine(4096);
1d5165 2371
7fb0ae 2372             if (!$line) {
59c216 2373                 break;
7fb0ae 2374             }
80152b 2375
A 2376             // Sample reply line:
2377             // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
2378             // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
2379             // BODY[HEADER.FIELDS ...
1d5165 2380
c2c820 2381             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
A 2382                 $id = intval($m[1]);
1d5165 2383
0c2596 2384                 $result[$id]            = new rcube_message_header;
c2c820 2385                 $result[$id]->id        = $id;
A 2386                 $result[$id]->subject   = '';
2387                 $result[$id]->messageID = 'mid:' . $id;
59c216 2388
de4de8 2389                 $headers = null;
A 2390                 $lines   = array();
2391                 $line    = substr($line, strlen($m[0]) + 2);
2392                 $ln      = 0;
59c216 2393
80152b 2394                 // get complete entry
A 2395                 while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
2396                     $bytes = $m[1];
2397                     $out   = '';
59c216 2398
80152b 2399                     while (strlen($out) < $bytes) {
A 2400                         $out = $this->readBytes($bytes);
7fb0ae 2401                         if ($out === null) {
80152b 2402                             break;
7fb0ae 2403                         }
80152b 2404                         $line .= $out;
c2c820 2405                     }
59c216 2406
80152b 2407                     $str = $this->readLine(4096);
7fb0ae 2408                     if ($str === false) {
80152b 2409                         break;
7fb0ae 2410                     }
59c216 2411
80152b 2412                     $line .= $str;
A 2413                 }
2414
2415                 // Tokenize response and assign to object properties
2416                 while (list($name, $value) = $this->tokenizeResponse($line, 2)) {
2417                     if ($name == 'UID') {
2418                         $result[$id]->uid = intval($value);
2419                     }
2420                     else if ($name == 'RFC822.SIZE') {
2421                         $result[$id]->size = intval($value);
2422                     }
2423                     else if ($name == 'RFC822.TEXT') {
2424                         $result[$id]->body = $value;
2425                     }
2426                     else if ($name == 'INTERNALDATE') {
2427                         $result[$id]->internaldate = $value;
2428                         $result[$id]->date         = $value;
2429                         $result[$id]->timestamp    = $this->StrToTime($value);
2430                     }
2431                     else if ($name == 'FLAGS') {
2432                         if (!empty($value)) {
2433                             foreach ((array)$value as $flag) {
7fb0ae 2434                                 $flag = str_replace(array('$', "\\"), '', $flag);
609d39 2435                                 $flag = strtoupper($flag);
80152b 2436
609d39 2437                                 $result[$id]->flags[$flag] = true;
c2c820 2438                             }
A 2439                         }
2440                     }
80152b 2441                     else if ($name == 'MODSEQ') {
A 2442                         $result[$id]->modseq = $value[0];
2443                     }
2444                     else if ($name == 'ENVELOPE') {
2445                         $result[$id]->envelope = $value;
2446                     }
2447                     else if ($name == 'BODYSTRUCTURE' || ($name == 'BODY' && count($value) > 2)) {
2448                         if (!is_array($value[0]) && (strtolower($value[0]) == 'message' && strtolower($value[1]) == 'rfc822')) {
2449                             $value = array($value);
2450                         }
2451                         $result[$id]->bodystructure = $value;
2452                     }
2453                     else if ($name == 'RFC822') {
2454                         $result[$id]->body = $value;
2455                     }
6e57fb 2456                     else if (stripos($name, 'BODY[') === 0) {
AM 2457                         $name = str_replace(']', '', substr($name, 5));
2458
2459                         if ($name == 'HEADER.FIELDS') {
2460                             // skip ']' after headers list
2461                             $this->tokenizeResponse($line, 1);
2462                             $headers = $this->tokenizeResponse($line, 1);
2463                         }
7fb0ae 2464                         else if (strlen($name)) {
6e57fb 2465                             $result[$id]->bodypart[$name] = $value;
7fb0ae 2466                         }
AM 2467                         else {
6e57fb 2468                             $result[$id]->body = $value;
7fb0ae 2469                         }
80152b 2470                     }
c2c820 2471                 }
59c216 2472
80152b 2473                 // create array with header field:data
A 2474                 if (!empty($headers)) {
2475                     $headers = explode("\n", trim($headers));
3725cf 2476                     foreach ($headers as $resln) {
80152b 2477                         if (ord($resln[0]) <= 32) {
A 2478                             $lines[$ln] .= (empty($lines[$ln]) ? '' : "\n") . trim($resln);
7fb0ae 2479                         }
AM 2480                         else {
80152b 2481                             $lines[++$ln] = trim($resln);
c2c820 2482                         }
A 2483                     }
59c216 2484
3725cf 2485                     foreach ($lines as $str) {
f66f5f 2486                         list($field, $string) = explode(':', $str, 2);
1d5165 2487
c2c820 2488                         $field  = strtolower($field);
f66f5f 2489                         $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
1d5165 2490
c2c820 2491                         switch ($field) {
A 2492                         case 'date';
2493                             $result[$id]->date = $string;
2494                             $result[$id]->timestamp = $this->strToTime($string);
2495                             break;
2496                         case 'to':
2497                             $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
2498                             break;
7fb0ae 2499                         case 'from':
c2c820 2500                         case 'subject':
7fb0ae 2501                         case 'cc':
AM 2502                         case 'bcc':
2503                         case 'references':
2504                             $result[$id]->{$field} = $string;
c2c820 2505                             break;
A 2506                         case 'reply-to':
2507                             $result[$id]->replyto = $string;
2508                             break;
2509                         case 'content-transfer-encoding':
2510                             $result[$id]->encoding = $string;
2511                         break;
2512                         case 'content-type':
974f9d 2513                             $ctype_parts = preg_split('/[; ]+/', $string);
62481f 2514                             $result[$id]->ctype = strtolower(array_shift($ctype_parts));
c2c820 2515                             if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
A 2516                                 $result[$id]->charset = $regs[1];
2517                             }
2518                             break;
2519                         case 'in-reply-to':
2520                             $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
2521                             break;
2522                         case 'return-receipt-to':
2523                         case 'disposition-notification-to':
2524                         case 'x-confirm-reading-to':
2525                             $result[$id]->mdn_to = $string;
2526                             break;
2527                         case 'message-id':
2528                             $result[$id]->messageID = $string;
2529                             break;
2530                         case 'x-priority':
2531                             if (preg_match('/^(\d+)/', $string, $matches)) {
2532                                 $result[$id]->priority = intval($matches[1]);
2533                             }
2534                             break;
2535                         default:
30cc01 2536                             if (strlen($field) < 3) {
AM 2537                                 break;
c2c820 2538                             }
30cc01 2539                             if ($result[$id]->others[$field]) {
AM 2540                                 $string = array_merge((array)$result[$id]->others[$field], (array)$string);
2541                             }
2542                             $result[$id]->others[$field] = $string;
c2c820 2543                         }
A 2544                     }
2545                 }
2546             }
80152b 2547             // VANISHED response (QRESYNC RFC5162)
A 2548             // Sample: * VANISHED (EARLIER) 300:310,405,411
609d39 2549             else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
80152b 2550                 $line   = substr($line, strlen($match[0]));
A 2551                 $v_data = $this->tokenizeResponse($line, 1);
2552
2553                 $this->data['VANISHED'] = $v_data;
2554             }
7fb0ae 2555         }
AM 2556         while (!$this->startsWith($line, $key, true));
80152b 2557
A 2558         return $result;
2559     }
2560
99edf8 2561     /**
AM 2562      * Returns message(s) data (flags, headers, etc.)
2563      *
2564      * @param string $mailbox     Mailbox name
2565      * @param mixed  $message_set Message(s) sequence identifier(s) or UID(s)
2566      * @param bool   $is_uid      True if $message_set contains UIDs
2567      * @param bool   $bodystr     Enable to add BODYSTRUCTURE data to the result
2568      * @param array  $add_headers List of additional headers
2569      *
2570      * @return bool|array List of rcube_message_header elements, False on error
2571      */
7fb0ae 2572     public function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add_headers = array())
80152b 2573     {
A 2574         $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
99edf8 2575         $headers     = array('DATE', 'FROM', 'TO', 'SUBJECT', 'CONTENT-TYPE', 'CC', 'REPLY-TO',
AM 2576             'LIST-POST', 'DISPOSITION-NOTIFICATION-TO', 'X-PRIORITY');
2577
2578         if (!empty($add_headers)) {
2579             $add_headers = array_map('strtoupper', $add_headers);
2580             $headers     = array_unique(array_merge($headers, $add_headers));
2581         }
2582
2583         if ($bodystr) {
80152b 2584             $query_items[] = 'BODYSTRUCTURE';
99edf8 2585         }
AM 2586
2587         $query_items[] = 'BODY.PEEK[HEADER.FIELDS (' . implode(' ', $headers) . ')]';
80152b 2588
7fb0ae 2589         return $this->fetch($mailbox, $message_set, $is_uid, $query_items);
59c216 2590     }
A 2591
99edf8 2592     /**
AM 2593      * Returns message data (flags, headers, etc.)
2594      *
2595      * @param string $mailbox     Mailbox name
2596      * @param int    $id          Message sequence identifier or UID
2597      * @param bool   $is_uid      True if $id is an UID
2598      * @param bool   $bodystr     Enable to add BODYSTRUCTURE data to the result
2599      * @param array  $add_headers List of additional headers
2600      *
2601      * @return bool|rcube_message_header Message data, False on error
2602      */
7fb0ae 2603     public function fetchHeader($mailbox, $id, $is_uid = false, $bodystr = false, $add_headers = array())
59c216 2604     {
99edf8 2605         $a = $this->fetchHeaders($mailbox, $id, $is_uid, $bodystr, $add_headers);
c2c820 2606         if (is_array($a)) {
A 2607             return array_shift($a);
2608         }
7fb0ae 2609
c2c820 2610         return false;
59c216 2611     }
A 2612
843643 2613     /**
AM 2614      * Sort messages by specified header field
2615      *
2616      * @param array  $messages Array of rcube_message_header objects
2617      * @param string $field    Name of the property to sort by
2618      * @param string $flag     Sorting order (ASC|DESC)
2619      *
2620      * @return array Sorted input array
2621      */
2622     public static function sortHeaders($messages, $field, $flag)
59c216 2623     {
843643 2624         // Strategy: First, we'll create an "index" array.
AM 2625         // Then, we'll use sort() on that array, and use that to sort the main array.
c2c820 2626
7fb0ae 2627         $field  = empty($field) ? 'uid' : strtolower($field);
AM 2628         $flag   = empty($flag) ? 'ASC' : strtoupper($flag);
843643 2629         $index  = array();
AM 2630         $result = array();
2631
2632         reset($messages);
2633
2634         while (list($key, $headers) = each($messages)) {
2635             $value = null;
2636
2637             switch ($field) {
2638             case 'arrival':
2639                 $field = 'internaldate';
2640             case 'date':
2641             case 'internaldate':
2642             case 'timestamp':
2643                 $value = self::strToTime($headers->$field);
2644                 if (!$value && $field != 'timestamp') {
2645                     $value = $headers->timestamp;
c2c820 2646                 }
843643 2647
AM 2648                 break;
2649
2650             default:
2651                 // @TODO: decode header value, convert to UTF-8
2652                 $value = $headers->$field;
2653                 if (is_string($value)) {
2654                     $value = str_replace('"', '', $value);
2655                     if ($field == 'subject') {
2656                         $value = preg_replace('/^(Re:\s*|Fwd:\s*|Fw:\s*)+/i', '', $value);
2657                     }
2658
2659                     $data = strtoupper($value);
2660                 }
c2c820 2661             }
1d5165 2662
843643 2663             $index[$key] = $value;
AM 2664         }
2665
2666         if (!empty($index)) {
c2c820 2667             // sort index
A 2668             if ($flag == 'ASC') {
2669                 asort($index);
843643 2670             }
AM 2671             else {
c2c820 2672                 arsort($index);
A 2673             }
59c216 2674
c2c820 2675             // form new array based on index
A 2676             while (list($key, $val) = each($index)) {
843643 2677                 $result[$key] = $messages[$key];
c2c820 2678             }
A 2679         }
1d5165 2680
c2c820 2681         return $result;
59c216 2682     }
A 2683
7fb0ae 2684     /**
AM 2685      * Fetch MIME headers of specified message parts
2686      *
2687      * @param string $mailbox Mailbox name
2688      * @param int    $uid     Message UID
2689      * @param array  $parts   Message part identifiers
2690      * @param bool   $mime    Use MIME instad of HEADER
2691      *
2692      * @return array|bool Array containing headers string for each specified body
2693      *                    False on failure.
2694      */
2695     public function fetchMIMEHeaders($mailbox, $uid, $parts, $mime = true)
59c216 2696     {
c2c820 2697         if (!$this->select($mailbox)) {
A 2698             return false;
2699         }
1d5165 2700
c2c820 2701         $result = false;
A 2702         $parts  = (array) $parts;
2703         $key    = $this->nextTag();
52c2aa 2704         $peeks  = array();
59c216 2705         $type   = $mime ? 'MIME' : 'HEADER';
A 2706
c2c820 2707         // format request
52c2aa 2708         foreach ($parts as $part) {
c2c820 2709             $peeks[] = "BODY.PEEK[$part.$type]";
A 2710         }
1d5165 2711
80152b 2712         $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
59c216 2713
c2c820 2714         // send request
A 2715         if (!$this->putLine($request)) {
c0ed78 2716             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
c2c820 2717             return false;
A 2718         }
1d5165 2719
c2c820 2720         do {
A 2721             $line = $this->readLine(1024);
59c216 2722
7fb0ae 2723             if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+/', $line, $m)) {
AM 2724                 $line = ltrim(substr($line, strlen($m[0])));
2725                 while (preg_match('/^BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
2726                     $line = substr($line, strlen($matches[0]));
2727                     $result[$matches[1]] = trim($this->multLine($line));
354cff 2728                     $line = $this->readLine(1024);
52c2aa 2729                 }
c2c820 2730             }
7fb0ae 2731         }
AM 2732         while (!$this->startsWith($line, $key, true));
59c216 2733
c2c820 2734         return $result;
59c216 2735     }
A 2736
7fb0ae 2737     /**
AM 2738      * Fetches message part header
2739      */
2740     public function fetchPartHeader($mailbox, $id, $is_uid = false, $part = null)
59c216 2741     {
c2c820 2742         $part = empty($part) ? 'HEADER' : $part.'.MIME';
59c216 2743
A 2744         return $this->handlePartBody($mailbox, $id, $is_uid, $part);
2745     }
2746
7fb0ae 2747     /**
AM 2748      * Fetches body of the specified message part
2749      */
2750     public function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=null, $print=null, $file=null, $formatted=false, $max_bytes=0)
59c216 2751     {
c2c820 2752         if (!$this->select($mailbox)) {
59c216 2753             return false;
A 2754         }
2755
7fb0ae 2756         $binary = true;
59c216 2757
c2c820 2758         do {
81dab3 2759             if (!$initiated) {
AM 2760                 switch ($encoding) {
2761                 case 'base64':
2762                     $mode = 1;
2763                     break;
2764                 case 'quoted-printable':
2765                     $mode = 2;
2766                     break;
2767                 case 'x-uuencode':
2768                 case 'x-uue':
2769                 case 'uue':
2770                 case 'uuencode':
2771                     $mode = 3;
2772                     break;
2773                 default:
2774                     $mode = 0;
2775                 }
2776
2777                 // Use BINARY extension when possible (and safe)
bf9c9b 2778                 $binary     = $binary && $mode && preg_match('/^[0-9.]+$/', $part) && $this->hasCapability('BINARY');
81dab3 2779                 $fetch_mode = $binary ? 'BINARY' : 'BODY';
AM 2780                 $partial    = $max_bytes ? sprintf('<0.%d>', $max_bytes) : '';
2781
2782                 // format request
bf9c9b 2783                 $key       = $this->nextTag();
AM 2784                 $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id ($fetch_mode.PEEK[$part]$partial)";
2785                 $result    = false;
2786                 $found     = false;
2787                 $initiated = true;
81dab3 2788
AM 2789                 // send request
2790                 if (!$this->putLine($request)) {
2791                     $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
2792                     return false;
2793                 }
2794
2795                 if ($binary) {
2796                     // WARNING: Use $formatted argument with care, this may break binary data stream
2797                     $mode = -1;
2798                 }
2799             }
2800
7eb780 2801             $line = trim($this->readLine(1024));
59c216 2802
7eb780 2803             if (!$line) {
AM 2804                 break;
c2c820 2805             }
59c216 2806
bf9c9b 2807             // handle UNKNOWN-CTE response - RFC 3516, try again with standard BODY request
AM 2808             if ($binary && !$found && preg_match('/^' . $key . ' NO \[UNKNOWN-CTE\]/i', $line)) {
2809                 $binary = $initiated = false;
2810                 continue;
2811             }
2812
c6f5ad 2813             // skip irrelevant untagged responses (we have a result already)
AM 2814             if ($found || !preg_match('/^\* ([0-9]+) FETCH (.*)$/', $line, $m)) {
7eb780 2815                 continue;
c2c820 2816             }
59c216 2817
7eb780 2818             $line = $m[2];
1d5165 2819
7eb780 2820             // handle one line response
c6f5ad 2821             if ($line[0] == '(' && substr($line, -1) == ')') {
7eb780 2822                 // tokenize content inside brackets
7045bb 2823                 // the content can be e.g.: (UID 9844 BODY[2.4] NIL)
c6f5ad 2824                 $tokens = $this->tokenizeResponse(preg_replace('/(^\(|\)$)/', '', $line));
AM 2825
2826                 for ($i=0; $i<count($tokens); $i+=2) {
c027ba 2827                     if (preg_match('/^(BODY|BINARY)/i', $tokens[$i])) {
6e57fb 2828                         $result = $tokens[$i+1];
c6f5ad 2829                         $found  = true;
AM 2830                         break;
2831                     }
2832                 }
ed302b 2833
7eb780 2834                 if ($result !== false) {
AM 2835                     if ($mode == 1) {
2836                         $result = base64_decode($result);
c2c820 2837                     }
7eb780 2838                     else if ($mode == 2) {
AM 2839                         $result = quoted_printable_decode($result);
2840                     }
2841                     else if ($mode == 3) {
2842                         $result = convert_uudecode($result);
2843                     }
c2c820 2844                 }
A 2845             }
7eb780 2846             // response with string literal
AM 2847             else if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
2848                 $bytes = (int) $m[1];
2849                 $prev  = '';
c6f5ad 2850                 $found = true;
1d5165 2851
8acf62 2852                 // empty body
AM 2853                 if (!$bytes) {
2854                     $result = '';
2855                 }
2856                 else while ($bytes > 0) {
7eb780 2857                     $line = $this->readLine(8192);
AM 2858
86b241 2859                     if ($line === null) {
7eb780 2860                         break;
AM 2861                     }
2862
2863                     $len = strlen($line);
2864
2865                     if ($len > $bytes) {
2866                         $line = substr($line, 0, $bytes);
2867                         $len  = strlen($line);
2868                     }
2869                     $bytes -= $len;
2870
2871                     // BASE64
2872                     if ($mode == 1) {
9d9623 2873                         $line = preg_replace('|[^a-zA-Z0-9+=/]|', '', $line);
7eb780 2874                         // create chunks with proper length for base64 decoding
AM 2875                         $line = $prev.$line;
2876                         $length = strlen($line);
2877                         if ($length % 4) {
2878                             $length = floor($length / 4) * 4;
2879                             $prev = substr($line, $length);
2880                             $line = substr($line, 0, $length);
2881                         }
2882                         else {
2883                             $prev = '';
2884                         }
2885                         $line = base64_decode($line);
2886                     }
2887                     // QUOTED-PRINTABLE
2888                     else if ($mode == 2) {
2889                         $line = rtrim($line, "\t\r\0\x0B");
2890                         $line = quoted_printable_decode($line);
2891                     }
2892                     // UUENCODE
2893                     else if ($mode == 3) {
2894                         $line = rtrim($line, "\t\r\n\0\x0B");
2895                         if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line)) {
2896                             continue;
2897                         }
2898                         $line = convert_uudecode($line);
2899                     }
2900                     // default
2901                     else if ($formatted) {
2902                         $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
2903                     }
2904
2905                     if ($file) {
2906                         if (fwrite($file, $line) === false) {
2907                             break;
2908                         }
2909                     }
2910                     else if ($print) {
2911                         echo $line;
2912                     }
2913                     else {
2914                         $result .= $line;
2915                     }
2916                 }
2917             }
7fb0ae 2918         }
AM 2919         while (!$this->startsWith($line, $key, true) || !$initiated);
59c216 2920
c2c820 2921         if ($result !== false) {
A 2922             if ($file) {
dff2c7 2923                 return fwrite($file, $result);
7eb780 2924             }
AM 2925             else if ($print) {
c2c820 2926                 echo $result;
7eb780 2927                 return true;
AM 2928             }
2929
2930             return $result;
c2c820 2931         }
59c216 2932
c2c820 2933         return false;
59c216 2934     }
A 2935
765fde 2936     /**
A 2937      * Handler for IMAP APPEND command
2938      *
d76472 2939      * @param string       $mailbox Mailbox name
AM 2940      * @param string|array $message The message source string or array (of strings and file pointers)
2941      * @param array        $flags   Message flags
2942      * @param string       $date    Message internal date
2943      * @param bool         $binary  Enable BINARY append (RFC3516)
765fde 2944      *
A 2945      * @return string|bool On success APPENDUID response (if available) or True, False on failure
2946      */
7fb0ae 2947     public function append($mailbox, &$message, $flags = array(), $date = null, $binary = false)
59c216 2948     {
765fde 2949         unset($this->data['APPENDUID']);
A 2950
b56526 2951         if ($mailbox === null || $mailbox === '') {
c2c820 2952             return false;
A 2953         }
59c216 2954
4f1c88 2955         $binary       = $binary && $this->getCapability('BINARY');
AM 2956         $literal_plus = !$binary && $this->prefs['literal+'];
d76472 2957         $len          = 0;
AM 2958         $msg          = is_array($message) ? $message : array(&$message);
2959         $chunk_size   = 512000;
4f1c88 2960
d76472 2961         for ($i=0, $cnt=count($msg); $i<$cnt; $i++) {
AM 2962             if (is_resource($msg[$i])) {
2963                 $stat = fstat($msg[$i]);
2964                 if ($stat === false) {
2965                     return false;
2966                 }
2967                 $len += $stat['size'];
2968             }
2969             else {
2970                 if (!$binary) {
2971                     $msg[$i] = str_replace("\r", '', $msg[$i]);
2972                     $msg[$i] = str_replace("\n", "\r\n", $msg[$i]);
2973                 }
2974
2975                 $len += strlen($msg[$i]);
2976             }
4f1c88 2977         }
59c216 2978
c2c820 2979         if (!$len) {
A 2980             return false;
2981         }
59c216 2982
00891e 2983         // build APPEND command
c0ed78 2984         $key = $this->nextTag();
00891e 2985         $request = "$key APPEND " . $this->escape($mailbox) . ' (' . $this->flagsToStr($flags) . ')';
AM 2986         if (!empty($date)) {
2987             $request .= ' ' . $this->escape($date);
2988         }
4f1c88 2989         $request .= ' ' . ($binary ? '~' : '') . '{' . $len . ($literal_plus ? '+' : '') . '}';
59c216 2990
00891e 2991         // send APPEND command
c2c820 2992         if ($this->putLine($request)) {
00891e 2993             // Do not wait when LITERAL+ is supported
4f1c88 2994             if (!$literal_plus) {
c2c820 2995                 $line = $this->readReply();
59c216 2996
c2c820 2997                 if ($line[0] != '+') {
A 2998                     $this->parseResult($line, 'APPEND: ');
2999                     return false;
3000                 }
d83351 3001             }
59c216 3002
d76472 3003             foreach ($msg as $msg_part) {
AM 3004                 // file pointer
3005                 if (is_resource($msg_part)) {
3006                     rewind($msg_part);
3007                     while (!feof($msg_part) && $this->fp) {
3008                         $buffer = fread($msg_part, $chunk_size);
3009                         $this->putLine($buffer, false);
3010                     }
3011                     fclose($msg_part);
3012                 }
3013                 // string
3014                 else {
3015                     $size = strlen($msg_part);
3016
3017                     // Break up the data by sending one chunk (up to 512k) at a time.
3018                     // This approach reduces our peak memory usage
3019                     for ($offset = 0; $offset < $size; $offset += $chunk_size) {
3020                         $chunk = substr($msg_part, $offset, $chunk_size);
3021                         if (!$this->putLine($chunk, false)) {
3022                             return false;
3023                         }
3024                     }
3025                 }
3026             }
3027
3028             if (!$this->putLine('')) { // \r\n
59c216 3029                 return false;
A 3030             }
3031
c2c820 3032             do {
A 3033                 $line = $this->readLine();
3034             } while (!$this->startsWith($line, $key, true, true));
1d5165 3035
36911e 3036             // Clear internal status cache
8738e9 3037             unset($this->data['STATUS:'.$mailbox]);
36911e 3038
765fde 3039             if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
A 3040                 return false;
3041             else if (!empty($this->data['APPENDUID']))
3042                 return $this->data['APPENDUID'];
3043             else
3044                 return true;
c2c820 3045         }
8fcc3e 3046         else {
c0ed78 3047             $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
8fcc3e 3048         }
59c216 3049
c2c820 3050         return false;
59c216 3051     }
A 3052
765fde 3053     /**
A 3054      * Handler for IMAP APPEND command.
3055      *
3056      * @param string $mailbox Mailbox name
3057      * @param string $path    Path to the file with message body
3058      * @param string $headers Message headers
00891e 3059      * @param array  $flags   Message flags
AM 3060      * @param string $date    Message internal date
4f1c88 3061      * @param bool   $binary  Enable BINARY append (RFC3516)
765fde 3062      *
A 3063      * @return string|bool On success APPENDUID response (if available) or True, False on failure
3064      */
7fb0ae 3065     public function appendFromFile($mailbox, $path, $headers=null, $flags = array(), $date = null, $binary = false)
59c216 3066     {
c2c820 3067         // open message file
A 3068         if (file_exists(realpath($path))) {
d76472 3069             $fp = fopen($path, 'r');
c2c820 3070         }
b56526 3071
d76472 3072         if (!$fp) {
c2c820 3073             $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
A 3074             return false;
3075         }
1d5165 3076
d76472 3077         $message = array();
59c216 3078         if ($headers) {
d76472 3079             $message[] = trim($headers, "\r\n") . "\r\n\r\n";
59c216 3080         }
d76472 3081         $message[] = $fp;
59c216 3082
d76472 3083         return $this->append($mailbox, $message, $flags, $date, $binary);
59c216 3084     }
A 3085
e361bf 3086     /**
A 3087      * Returns QUOTA information
3088      *
6fa1a0 3089      * @param string $mailbox Mailbox name
AM 3090      *
e361bf 3091      * @return array Quota information
A 3092      */
7fb0ae 3093     public function getQuota($mailbox = null)
59c216 3094     {
6fa1a0 3095         if ($mailbox === null || $mailbox === '') {
AM 3096             $mailbox = 'INBOX';
8fcc3e 3097         }
1d5165 3098
6fa1a0 3099         // a0001 GETQUOTAROOT INBOX
AM 3100         // * QUOTAROOT INBOX user/sample
3101         // * QUOTA user/sample (STORAGE 654 9765)
3102         // a0001 OK Completed
3103
3104         list($code, $response) = $this->execute('GETQUOTAROOT', array($this->escape($mailbox)));
3105
3106         $result   = false;
c2c820 3107         $min_free = PHP_INT_MAX;
6fa1a0 3108         $all      = array();
1d5165 3109
6fa1a0 3110         if ($code == self::ERROR_OK) {
AM 3111             foreach (explode("\n", $response) as $line) {
3112                 if (preg_match('/^\* QUOTA /', $line)) {
3113                     list(, , $quota_root) = $this->tokenizeResponse($line, 3);
3114
3115                     while ($line) {
3116                         list($type, $used, $total) = $this->tokenizeResponse($line, 1);
3117                         $type = strtolower($type);
3118
3119                         if ($type && $total) {
3120                             $all[$quota_root][$type]['used']  = intval($used);
3121                             $all[$quota_root][$type]['total'] = intval($total);
3122                         }
3123                     }
3124
3125                     if (empty($all[$quota_root]['storage'])) {
3126                         continue;
3127                     }
3128
3129                     $used  = $all[$quota_root]['storage']['used'];
3130                     $total = $all[$quota_root]['storage']['total'];
3131                     $free  = $total - $used;
3132
3133                     // calculate lowest available space from all storage quotas
3134                     if ($free < $min_free) {
3135                         $min_free          = $free;
3136                         $result['used']    = $used;
3137                         $result['total']   = $total;
3138                         $result['percent'] = min(100, round(($used/max(1,$total))*100));
3139                         $result['free']    = 100 - $result['percent'];
3140                     }
3141                 }
c2c820 3142             }
6fa1a0 3143         }
1d5165 3144
6fa1a0 3145         if (!empty($result)) {
AM 3146             $result['all'] = $all;
c2c820 3147         }
59c216 3148
c2c820 3149         return $result;
59c216 3150     }
A 3151
8b6eff 3152     /**
A 3153      * Send the SETACL command (RFC4314)
3154      *
3155      * @param string $mailbox Mailbox name
3156      * @param string $user    User name
3157      * @param mixed  $acl     ACL string or array
3158      *
3159      * @return boolean True on success, False on failure
3160      *
3161      * @since 0.5-beta
3162      */
7fb0ae 3163     public function setACL($mailbox, $user, $acl)
8b6eff 3164     {
A 3165         if (is_array($acl)) {
3166             $acl = implode('', $acl);
3167         }
3168
854cf2 3169         $result = $this->execute('SETACL', array(
A 3170             $this->escape($mailbox), $this->escape($user), strtolower($acl)),
3171             self::COMMAND_NORESPONSE);
8b6eff 3172
c2c820 3173         return ($result == self::ERROR_OK);
8b6eff 3174     }
A 3175
3176     /**
3177      * Send the DELETEACL command (RFC4314)
3178      *
3179      * @param string $mailbox Mailbox name
3180      * @param string $user    User name
3181      *
3182      * @return boolean True on success, False on failure
3183      *
3184      * @since 0.5-beta
3185      */
7fb0ae 3186     public function deleteACL($mailbox, $user)
8b6eff 3187     {
854cf2 3188         $result = $this->execute('DELETEACL', array(
A 3189             $this->escape($mailbox), $this->escape($user)),
3190             self::COMMAND_NORESPONSE);
8b6eff 3191
c2c820 3192         return ($result == self::ERROR_OK);
8b6eff 3193     }
A 3194
3195     /**
3196      * Send the GETACL command (RFC4314)
3197      *
3198      * @param string $mailbox Mailbox name
3199      *
3200      * @return array User-rights array on success, NULL on error
3201      * @since 0.5-beta
3202      */
7fb0ae 3203     public function getACL($mailbox)
8b6eff 3204     {
aff04d 3205         list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
8b6eff 3206
854cf2 3207         if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
A 3208             // Parse server response (remove "* ACL ")
3209             $response = substr($response, 6);
8b6eff 3210             $ret  = $this->tokenizeResponse($response);
aff04d 3211             $mbox = array_shift($ret);
8b6eff 3212             $size = count($ret);
A 3213
3214             // Create user-rights hash array
3215             // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
3216             // so we could return only standard rights defined in RFC4314,
3217             // excluding 'c' and 'd' defined in RFC2086.
3218             if ($size % 2 == 0) {
3219                 for ($i=0; $i<$size; $i++) {
3220                     $ret[$ret[$i]] = str_split($ret[++$i]);
3221                     unset($ret[$i-1]);
3222                     unset($ret[$i]);
3223                 }
3224                 return $ret;
3225             }
3226
c0ed78 3227             $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
8b6eff 3228         }
A 3229     }
3230
3231     /**
3232      * Send the LISTRIGHTS command (RFC4314)
3233      *
3234      * @param string $mailbox Mailbox name
3235      * @param string $user    User name
3236      *
3237      * @return array List of user rights
3238      * @since 0.5-beta
3239      */
7fb0ae 3240     public function listRights($mailbox, $user)
8b6eff 3241     {
854cf2 3242         list($code, $response) = $this->execute('LISTRIGHTS', array(
A 3243             $this->escape($mailbox), $this->escape($user)));
8b6eff 3244
854cf2 3245         if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
A 3246             // Parse server response (remove "* LISTRIGHTS ")
3247             $response = substr($response, 13);
8b6eff 3248
A 3249             $ret_mbox = $this->tokenizeResponse($response, 1);
3250             $ret_user = $this->tokenizeResponse($response, 1);
3251             $granted  = $this->tokenizeResponse($response, 1);
3252             $optional = trim($response);
3253
3254             return array(
3255                 'granted'  => str_split($granted),
3256                 'optional' => explode(' ', $optional),
3257             );
3258         }
3259     }
3260
3261     /**
3262      * Send the MYRIGHTS command (RFC4314)
3263      *
3264      * @param string $mailbox Mailbox name
3265      *
3266      * @return array MYRIGHTS response on success, NULL on error
3267      * @since 0.5-beta
3268      */
7fb0ae 3269     public function myRights($mailbox)
8b6eff 3270     {
aff04d 3271         list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
8b6eff 3272
854cf2 3273         if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
A 3274             // Parse server response (remove "* MYRIGHTS ")
3275             $response = substr($response, 11);
8b6eff 3276
A 3277             $ret_mbox = $this->tokenizeResponse($response, 1);
3278             $rights   = $this->tokenizeResponse($response, 1);
3279
3280             return str_split($rights);
3281         }
3282     }
3283
3284     /**
3285      * Send the SETMETADATA command (RFC5464)
3286      *
3287      * @param string $mailbox Mailbox name
3288      * @param array  $entries Entry-value array (use NULL value as NIL)
3289      *
3290      * @return boolean True on success, False on failure
3291      * @since 0.5-beta
3292      */
7fb0ae 3293     public function setMetadata($mailbox, $entries)
8b6eff 3294     {
A 3295         if (!is_array($entries) || empty($entries)) {
c0ed78 3296             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
8b6eff 3297             return false;
A 3298         }
3299
3300         foreach ($entries as $name => $value) {
cc02a9 3301             $entries[$name] = $this->escape($name) . ' ' . $this->escape($value, true);
8b6eff 3302         }
A 3303
3304         $entries = implode(' ', $entries);
854cf2 3305         $result = $this->execute('SETMETADATA', array(
A 3306             $this->escape($mailbox), '(' . $entries . ')'),
3307             self::COMMAND_NORESPONSE);
8b6eff 3308
854cf2 3309         return ($result == self::ERROR_OK);
8b6eff 3310     }
A 3311
3312     /**
3313      * Send the SETMETADATA command with NIL values (RFC5464)
3314      *
3315      * @param string $mailbox Mailbox name
3316      * @param array  $entries Entry names array
3317      *
3318      * @return boolean True on success, False on failure
3319      *
3320      * @since 0.5-beta
3321      */
7fb0ae 3322     public function deleteMetadata($mailbox, $entries)
8b6eff 3323     {
c2c820 3324         if (!is_array($entries) && !empty($entries)) {
8b6eff 3325             $entries = explode(' ', $entries);
c2c820 3326         }
8b6eff 3327
A 3328         if (empty($entries)) {
c0ed78 3329             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
8b6eff 3330             return false;
A 3331         }
3332
c2c820 3333         foreach ($entries as $entry) {
86b241 3334             $data[$entry] = null;
c2c820 3335         }
a85f88 3336
8b6eff 3337         return $this->setMetadata($mailbox, $data);
A 3338     }
3339
3340     /**
3341      * Send the GETMETADATA command (RFC5464)
3342      *
3343      * @param string $mailbox Mailbox name
3344      * @param array  $entries Entries
3345      * @param array  $options Command options (with MAXSIZE and DEPTH keys)
3346      *
3347      * @return array GETMETADATA result on success, NULL on error
3348      *
3349      * @since 0.5-beta
3350      */
7fb0ae 3351     public function getMetadata($mailbox, $entries, $options=array())
8b6eff 3352     {
A 3353         if (!is_array($entries)) {
3354             $entries = array($entries);
3355         }
3356
3357         // create entries string
3358         foreach ($entries as $idx => $name) {
a85f88 3359             $entries[$idx] = $this->escape($name);
8b6eff 3360         }
A 3361
3362         $optlist = '';
3363         $entlist = '(' . implode(' ', $entries) . ')';
3364
3365         // create options string
3366         if (is_array($options)) {
3367             $options = array_change_key_case($options, CASE_UPPER);
3368             $opts = array();
3369
c2c820 3370             if (!empty($options['MAXSIZE'])) {
8b6eff 3371                 $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
c2c820 3372             }
A 3373             if (!empty($options['DEPTH'])) {
8b6eff 3374                 $opts[] = 'DEPTH '.intval($options['DEPTH']);
c2c820 3375             }
8b6eff 3376
c2c820 3377             if ($opts) {
8b6eff 3378                 $optlist = '(' . implode(' ', $opts) . ')';
c2c820 3379             }
8b6eff 3380         }
A 3381
3382         $optlist .= ($optlist ? ' ' : '') . $entlist;
3383
854cf2 3384         list($code, $response) = $this->execute('GETMETADATA', array(
A 3385             $this->escape($mailbox), $optlist));
8b6eff 3386
814baf 3387         if ($code == self::ERROR_OK) {
A 3388             $result = array();
3389             $data   = $this->tokenizeResponse($response);
8b6eff 3390
A 3391             // The METADATA response can contain multiple entries in a single
3392             // response or multiple responses for each entry or group of entries
3393             if (!empty($data) && ($size = count($data))) {
3394                 for ($i=0; $i<$size; $i++) {
814baf 3395                     if (isset($mbox) && is_array($data[$i])) {
8b6eff 3396                         $size_sub = count($data[$i]);
0d273c 3397                         for ($x=0; $x<$size_sub; $x+=2) {
939380 3398                             if ($data[$i][$x+1] !== null)
0d273c 3399                                 $result[$mbox][$data[$i][$x]] = $data[$i][$x+1];
8b6eff 3400                         }
A 3401                         unset($data[$i]);
3402                     }
814baf 3403                     else if ($data[$i] == '*') {
A 3404                         if ($data[$i+1] == 'METADATA') {
3405                             $mbox = $data[$i+2];
3406                             unset($data[$i]);   // "*"
3407                             unset($data[++$i]); // "METADATA"
3408                             unset($data[++$i]); // Mailbox
3409                         }
3410                         // get rid of other untagged responses
3411                         else {
3412                             unset($mbox);
3413                             unset($data[$i]);
3414                         }
8b6eff 3415                     }
814baf 3416                     else if (isset($mbox)) {
664680 3417                         if ($data[++$i] !== null)
TB 3418                             $result[$mbox][$data[$i-1]] = $data[$i];
8b6eff 3419                         unset($data[$i]);
A 3420                         unset($data[$i-1]);
814baf 3421                     }
A 3422                     else {
3423                         unset($data[$i]);
8b6eff 3424                     }
A 3425                 }
3426             }
3427
814baf 3428             return $result;
8b6eff 3429         }
A 3430     }
3431
3432     /**
3433      * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
3434      *
3435      * @param string $mailbox Mailbox name
3436      * @param array  $data    Data array where each item is an array with
3437      *                        three elements: entry name, attribute name, value
3438      *
3439      * @return boolean True on success, False on failure
3440      * @since 0.5-beta
3441      */
7fb0ae 3442     public function setAnnotation($mailbox, $data)
8b6eff 3443     {
A 3444         if (!is_array($data) || empty($data)) {
c0ed78 3445             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
8b6eff 3446             return false;
A 3447         }
3448
3449         foreach ($data as $entry) {
f7221d 3450             // ANNOTATEMORE drafts before version 08 require quoted parameters
b5fb21 3451             $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
A 3452                 $this->escape($entry[1], true), $this->escape($entry[2], true));
8b6eff 3453         }
A 3454
3455         $entries = implode(' ', $entries);
854cf2 3456         $result  = $this->execute('SETANNOTATION', array(
A 3457             $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
8b6eff 3458
854cf2 3459         return ($result == self::ERROR_OK);
8b6eff 3460     }
A 3461
3462     /**
3463      * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
3464      *
3465      * @param string $mailbox Mailbox name
3466      * @param array  $data    Data array where each item is an array with
3467      *                        two elements: entry name and attribute name
3468      *
3469      * @return boolean True on success, False on failure
3470      *
3471      * @since 0.5-beta
3472      */
7fb0ae 3473     public function deleteAnnotation($mailbox, $data)
8b6eff 3474     {
A 3475         if (!is_array($data) || empty($data)) {
c0ed78 3476             $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
8b6eff 3477             return false;
A 3478         }
3479
3480         return $this->setAnnotation($mailbox, $data);
3481     }
3482
3483     /**
3484      * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
3485      *
3486      * @param string $mailbox Mailbox name
3487      * @param array  $entries Entries names
3488      * @param array  $attribs Attribs names
3489      *
3490      * @return array Annotations result on success, NULL on error
3491      *
3492      * @since 0.5-beta
3493      */
7fb0ae 3494     public function getAnnotation($mailbox, $entries, $attribs)
8b6eff 3495     {
A 3496         if (!is_array($entries)) {
3497             $entries = array($entries);
3498         }
746209 3499
8b6eff 3500         // create entries string
f7221d 3501         // ANNOTATEMORE drafts before version 08 require quoted parameters
8b6eff 3502         foreach ($entries as $idx => $name) {
f7221d 3503             $entries[$idx] = $this->escape($name, true);
8b6eff 3504         }
A 3505         $entries = '(' . implode(' ', $entries) . ')';
3506
3507         if (!is_array($attribs)) {
3508             $attribs = array($attribs);
3509         }
746209 3510
AM 3511         // create attributes string
8b6eff 3512         foreach ($attribs as $idx => $name) {
f7221d 3513             $attribs[$idx] = $this->escape($name, true);
8b6eff 3514         }
A 3515         $attribs = '(' . implode(' ', $attribs) . ')';
3516
854cf2 3517         list($code, $response) = $this->execute('GETANNOTATION', array(
A 3518             $this->escape($mailbox), $entries, $attribs));
8b6eff 3519
814baf 3520         if ($code == self::ERROR_OK) {
A 3521             $result = array();
3522             $data   = $this->tokenizeResponse($response);
8b6eff 3523
A 3524             // Here we returns only data compatible with METADATA result format
3525             if (!empty($data) && ($size = count($data))) {
3526                 for ($i=0; $i<$size; $i++) {
814baf 3527                     $entry = $data[$i];
A 3528                     if (isset($mbox) && is_array($entry)) {
8b6eff 3529                         $attribs = $entry;
A 3530                         $entry   = $last_entry;
3531                     }
814baf 3532                     else if ($entry == '*') {
A 3533                         if ($data[$i+1] == 'ANNOTATION') {
3534                             $mbox = $data[$i+2];
3535                             unset($data[$i]);   // "*"
3536                             unset($data[++$i]); // "ANNOTATION"
3537                             unset($data[++$i]); // Mailbox
3538                         }
3539                         // get rid of other untagged responses
3540                         else {
3541                             unset($mbox);
3542                             unset($data[$i]);
3543                         }
3544                         continue;
3545                     }
3546                     else if (isset($mbox)) {
3547                         $attribs = $data[++$i];
3548                     }
3549                     else {
3550                         unset($data[$i]);
3551                         continue;
3552                     }
8b6eff 3553
A 3554                     if (!empty($attribs)) {
3555                         for ($x=0, $len=count($attribs); $x<$len;) {
3556                             $attr  = $attribs[$x++];
3557                             $value = $attribs[$x++];
939380 3558                             if ($attr == 'value.priv' && $value !== null) {
814baf 3559                                 $result[$mbox]['/private' . $entry] = $value;
c2c820 3560                             }
939380 3561                             else if ($attr == 'value.shared' && $value !== null) {
814baf 3562                                 $result[$mbox]['/shared' . $entry] = $value;
c2c820 3563                             }
8b6eff 3564                         }
A 3565                     }
3566                     $last_entry = $entry;
814baf 3567                     unset($data[$i]);
8b6eff 3568                 }
A 3569             }
3570
814baf 3571             return $result;
8b6eff 3572         }
854cf2 3573     }
A 3574
3575     /**
80152b 3576      * Returns BODYSTRUCTURE for the specified message.
A 3577      *
3578      * @param string $mailbox Folder name
3579      * @param int    $id      Message sequence number or UID
3580      * @param bool   $is_uid  True if $id is an UID
3581      *
3582      * @return array/bool Body structure array or False on error.
3583      * @since 0.6
3584      */
7fb0ae 3585     public function getStructure($mailbox, $id, $is_uid = false)
80152b 3586     {
A 3587         $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
7fb0ae 3588
80152b 3589         if (is_array($result)) {
A 3590             $result = array_shift($result);
3591             return $result->bodystructure;
3592         }
7fb0ae 3593
80152b 3594         return false;
A 3595     }
3596
8a6503 3597     /**
A 3598      * Returns data of a message part according to specified structure.
3599      *
3600      * @param array  $structure Message structure (getStructure() result)
3601      * @param string $part      Message part identifier
3602      *
3603      * @return array Part data as hash array (type, encoding, charset, size)
3604      */
7fb0ae 3605     public static function getStructurePartData($structure, $part)
80152b 3606     {
27bcb0 3607         $part_a = self::getStructurePartArray($structure, $part);
AM 3608         $data   = array();
80152b 3609
27bcb0 3610         if (empty($part_a)) {
8a6503 3611             return $data;
A 3612         }
80152b 3613
8a6503 3614         // content-type
A 3615         if (is_array($part_a[0])) {
3616             $data['type'] = 'multipart';
3617         }
3618         else {
3619             $data['type'] = strtolower($part_a[0]);
80152b 3620
8a6503 3621             // encoding
A 3622             $data['encoding'] = strtolower($part_a[5]);
80152b 3623
8a6503 3624             // charset
A 3625             if (is_array($part_a[2])) {
3626                while (list($key, $val) = each($part_a[2])) {
3627                     if (strcasecmp($val, 'charset') == 0) {
3628                         $data['charset'] = $part_a[2][$key+1];
3629                         break;
3630                     }
3631                 }
3632             }
3633         }
80152b 3634
8a6503 3635         // size
A 3636         $data['size'] = intval($part_a[6]);
3637
3638         return $data;
80152b 3639     }
A 3640
7fb0ae 3641     public static function getStructurePartArray($a, $part)
80152b 3642     {
27bcb0 3643         if (!is_array($a)) {
80152b 3644             return false;
A 3645         }
cc7544 3646
A 3647         if (empty($part)) {
27bcb0 3648             return $a;
AM 3649         }
cc7544 3650
A 3651         $ctype = is_string($a[0]) && is_string($a[1]) ? $a[0] . '/' . $a[1] : '';
3652
3653         if (strcasecmp($ctype, 'message/rfc822') == 0) {
3654             $a = $a[8];
3655         }
3656
27bcb0 3657         if (strpos($part, '.') > 0) {
AM 3658             $orig_part = $part;
3659             $pos       = strpos($part, '.');
3660             $rest      = substr($orig_part, $pos+1);
3661             $part      = substr($orig_part, 0, $pos);
cc7544 3662
27bcb0 3663             return self::getStructurePartArray($a[$part-1], $rest);
AM 3664         }
cc7544 3665         else if ($part > 0) {
27bcb0 3666             return (is_array($a[$part-1])) ? $a[$part-1] : $a;
AM 3667         }
80152b 3668     }
A 3669
3670     /**
854cf2 3671      * Creates next command identifier (tag)
A 3672      *
3673      * @return string Command identifier
3674      * @since 0.5-beta
3675      */
7fb0ae 3676     public function nextTag()
854cf2 3677     {
A 3678         $this->cmd_num++;
3679         $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
3680
3681         return $this->cmd_tag;
3682     }
3683
3684     /**
3685      * Sends IMAP command and parses result
3686      *
3687      * @param string $command   IMAP command
3688      * @param array  $arguments Command arguments
3689      * @param int    $options   Execution options
3690      *
3691      * @return mixed Response code or list of response code and data
3692      * @since 0.5-beta
3693      */
7fb0ae 3694     public function execute($command, $arguments=array(), $options=0)
854cf2 3695     {
c0ed78 3696         $tag      = $this->nextTag();
854cf2 3697         $query    = $tag . ' ' . $command;
A 3698         $noresp   = ($options & self::COMMAND_NORESPONSE);
3699         $response = $noresp ? null : '';
3700
c2c820 3701         if (!empty($arguments)) {
80152b 3702             foreach ($arguments as $arg) {
A 3703                 $query .= ' ' . self::r_implode($arg);
3704             }
c2c820 3705         }
854cf2 3706
A 3707         // Send command
774dea 3708         if (!$this->putLineC($query, true, ($options & self::COMMAND_ANONYMIZED))) {
c0ed78 3709             $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
c2c820 3710             return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
A 3711         }
854cf2 3712
A 3713         // Parse response
c2c820 3714         do {
A 3715             $line = $this->readLine(4096);
3716             if ($response !== null) {
3717                 $response .= $line;
3718             }
7fb0ae 3719         }
AM 3720         while (!$this->startsWith($line, $tag . ' ', true, true));
854cf2 3721
c2c820 3722         $code = $this->parseResult($line, $command . ': ');
854cf2 3723
A 3724         // Remove last line from response
c2c820 3725         if ($response) {
A 3726             $line_len = min(strlen($response), strlen($line) + 2);
854cf2 3727             $response = substr($response, 0, -$line_len);
A 3728         }
3729
c2c820 3730         // optional CAPABILITY response
A 3731         if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
781f0c 3732             && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
A 3733         ) {
c2c820 3734             $this->parseCapability($matches[1], true);
A 3735         }
781f0c 3736
90f81a 3737         // return last line only (without command tag, result and response code)
d903fb 3738         if ($line && ($options & self::COMMAND_LASTLINE)) {
90f81a 3739             $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
d903fb 3740         }
A 3741
c2c820 3742         return $noresp ? $code : array($code, $response);
8b6eff 3743     }
A 3744
3745     /**
3746      * Splits IMAP response into string tokens
3747      *
3748      * @param string &$str The IMAP's server response
3749      * @param int    $num  Number of tokens to return
3750      *
3751      * @return mixed Tokens array or string if $num=1
3752      * @since 0.5-beta
3753      */
7fb0ae 3754     public static function tokenizeResponse(&$str, $num=0)
8b6eff 3755     {
A 3756         $result = array();
3757
3758         while (!$num || count($result) < $num) {
3759             // remove spaces from the beginning of the string
3760             $str = ltrim($str);
3761
3762             switch ($str[0]) {
3763
3764             // String literal
3765             case '{':
3766                 if (($epos = strpos($str, "}\r\n", 1)) == false) {
3767                     // error
3768                 }
3769                 if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
3770                     // error
3771                 }
ca34ba 3772
80152b 3773                 $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
ca34ba 3774                 $str      = substr($str, $epos + 3 + $bytes);
c2c820 3775                 break;
8b6eff 3776
A 3777             // Quoted string
3778             case '"':
3779                 $len = strlen($str);
3780
3781                 for ($pos=1; $pos<$len; $pos++) {
3782                     if ($str[$pos] == '"') {
3783                         break;
3784                     }
3785                     if ($str[$pos] == "\\") {
3786                         if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
3787                             $pos++;
3788                         }
3789                     }
3790                 }
ca34ba 3791
8b6eff 3792                 // we need to strip slashes for a quoted string
A 3793                 $result[] = stripslashes(substr($str, 1, $pos - 1));
3794                 $str      = substr($str, $pos + 1);
c2c820 3795                 break;
8b6eff 3796
A 3797             // Parenthesized list
3798             case '(':
ca34ba 3799                 $str      = substr($str, 1);
8b6eff 3800                 $result[] = self::tokenizeResponse($str);
c2c820 3801                 break;
ca34ba 3802
8b6eff 3803             case ')':
A 3804                 $str = substr($str, 1);
3805                 return $result;
3806
6e57fb 3807             // String atom, number, astring, NIL, *, %
8b6eff 3808             default:
923052 3809                 // empty string
A 3810                 if ($str === '' || $str === null) {
8b6eff 3811                     break 2;
A 3812                 }
3813
6e57fb 3814                 // excluded chars: SP, CTL, ), DEL
AM 3815                 // we do not exclude [ and ] (#1489223)
3816                 if (preg_match('/^([^\x00-\x20\x29\x7F]+)/', $str, $m)) {
86b241 3817                     $result[] = $m[1] == 'NIL' ? null : $m[1];
ca34ba 3818                     $str      = substr($str, strlen($m[1]));
8b6eff 3819                 }
c2c820 3820                 break;
8b6eff 3821             }
A 3822         }
3823
3824         return $num == 1 ? $result[0] : $result;
80152b 3825     }
A 3826
7fb0ae 3827     protected static function r_implode($element)
80152b 3828     {
A 3829         $string = '';
3830
3831         if (is_array($element)) {
3832             reset($element);
3725cf 3833             foreach ($element as $value) {
80152b 3834                 $string .= ' ' . self::r_implode($value);
A 3835             }
3836         }
3837         else {
3838             return $element;
3839         }
3840
3841         return '(' . trim($string) . ')';
8b6eff 3842     }
A 3843
e361bf 3844     /**
A 3845      * Converts message identifiers array into sequence-set syntax
3846      *
3847      * @param array $messages Message identifiers
3848      * @param bool  $force    Forces compression of any size
3849      *
3850      * @return string Compressed sequence-set
3851      */
7fb0ae 3852     public static function compressMessageSet($messages, $force=false)
e361bf 3853     {
A 3854         // given a comma delimited list of independent mid's,
3855         // compresses by grouping sequences together
3856
3857         if (!is_array($messages)) {
3858             // if less than 255 bytes long, let's not bother
3859             if (!$force && strlen($messages)<255) {
3860                 return $messages;
d9dc32 3861             }
e361bf 3862
A 3863             // see if it's already been compressed
3864             if (strpos($messages, ':') !== false) {
3865                 return $messages;
3866             }
3867
3868             // separate, then sort
3869             $messages = explode(',', $messages);
3870         }
3871
3872         sort($messages);
3873
3874         $result = array();
3875         $start  = $prev = $messages[0];
3876
3877         foreach ($messages as $id) {
3878             $incr = $id - $prev;
3879             if ($incr > 1) { // found a gap
3880                 if ($start == $prev) {
3881                     $result[] = $prev; // push single id
7fb0ae 3882                 }
AM 3883                 else {
e361bf 3884                     $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
A 3885                 }
3886                 $start = $id; // start of new sequence
3887             }
3888             $prev = $id;
3889         }
3890
3891         // handle the last sequence/id
3892         if ($start == $prev) {
3893             $result[] = $prev;
7fb0ae 3894         }
AM 3895         else {
e361bf 3896             $result[] = $start.':'.$prev;
A 3897         }
3898
3899         // return as comma separated string
3900         return implode(',', $result);
3901     }
3902
3903     /**
3904      * Converts message sequence-set into array
3905      *
3906      * @param string $messages Message identifiers
3907      *
3908      * @return array List of message identifiers
3909      */
7fb0ae 3910     public static function uncompressMessageSet($messages)
e361bf 3911     {
e68fa7 3912         if (empty($messages)) {
AM 3913             return array();
3914         }
3915
e361bf 3916         $result   = array();
A 3917         $messages = explode(',', $messages);
3918
3919         foreach ($messages as $idx => $part) {
3920             $items = explode(':', $part);
3921             $max   = max($items[0], $items[1]);
3922
3923             for ($x=$items[0]; $x<=$max; $x++) {
e68fa7 3924                 $result[] = (int)$x;
e361bf 3925             }
A 3926             unset($messages[$idx]);
3927         }
3928
3929         return $result;
3930     }
3931
232bcd 3932     protected function _xor($string, $string2)
59c216 3933     {
c2c820 3934         $result = '';
A 3935         $size   = strlen($string);
3936
3937         for ($i=0; $i<$size; $i++) {
3938             $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
3939         }
3940
3941         return $result;
59c216 3942     }
A 3943
8b6eff 3944     /**
1422b0 3945      * Clear internal status cache
AM 3946      */
3947     protected function clear_status_cache($mailbox)
3948     {
3949         unset($this->data['STATUS:' . $mailbox]);
85f420 3950
AM 3951         $keys = array('EXISTS', 'RECENT', 'UNSEEN', 'UID-MAP');
3952
3953         foreach ($keys as $key) {
3954             unset($this->data[$key]);
3955         }
3956     }
3957
3958     /**
3959      * Clear internal cache of the current mailbox
3960      */
3961     protected function clear_mailbox_cache()
3962     {
3963         $this->clear_status_cache($this->selected);
3964
3965         $keys = array('UIDNEXT', 'UIDVALIDITY', 'HIGHESTMODSEQ', 'NOMODSEQ',
3966             'PERMANENTFLAGS', 'QRESYNC', 'VANISHED', 'READ-WRITE');
3967
3968         foreach ($keys as $key) {
3969             unset($this->data[$key]);
3970         }
1422b0 3971     }
AM 3972
3973     /**
00891e 3974      * Converts flags array into string for inclusion in IMAP command
AM 3975      *
3976      * @param array $flags Flags (see self::flags)
3977      *
3978      * @return string Space-separated list of flags
3979      */
232bcd 3980     protected function flagsToStr($flags)
00891e 3981     {
AM 3982         foreach ((array)$flags as $idx => $flag) {
3983             if ($flag = $this->flags[strtoupper($flag)]) {
3984                 $flags[$idx] = $flag;
3985             }
3986         }
3987
3988         return implode(' ', (array)$flags);
3989     }
3990
3991     /**
8b6eff 3992      * Converts datetime string into unix timestamp
A 3993      *
3994      * @param string $date Date string
3995      *
3996      * @return int Unix timestamp
3997      */
7fb0ae 3998     protected static function strToTime($date)
59c216 3999     {
b7570f 4000         // Clean malformed data
AM 4001         $date = preg_replace(
4002             array(
4003                 '/GMT\s*([+-][0-9]+)/',                     // support non-standard "GMTXXXX" literal
4004                 '/[^a-z0-9\x20\x09:+-]/i',                  // remove any invalid characters
4005                 '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i',   // remove weekday names
4006             ),
4007             array(
4008                 '\\1',
4009                 '',
4010                 '',
4011             ), $date);
4012
4013         $date = trim($date);
59c216 4014
f66f5f 4015         // if date parsing fails, we have a date in non-rfc format
A 4016         // remove token from the end and try again
4017         while (($ts = intval(@strtotime($date))) <= 0) {
4018             $d = explode(' ', $date);
4019             array_pop($d);
4020             if (empty($d)) {
4021                 break;
4022             }
4023             $date = implode(' ', $d);
c2c820 4024         }
f66f5f 4025
A 4026         return $ts < 0 ? 0 : $ts;
59c216 4027     }
A 4028
e361bf 4029     /**
A 4030      * CAPABILITY response parser
4031      */
232bcd 4032     protected function parseCapability($str, $trusted=false)
d83351 4033     {
854cf2 4034         $str = preg_replace('/^\* CAPABILITY /i', '', $str);
A 4035
d83351 4036         $this->capability = explode(' ', strtoupper($str));
A 4037
ed3e51 4038         if (!empty($this->prefs['disabled_caps'])) {
AM 4039             $this->capability = array_diff($this->capability, $this->prefs['disabled_caps']);
4040         }
4041
d83351 4042         if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
A 4043             $this->prefs['literal+'] = true;
5251ec 4044         }
AM 4045
475760 4046         if ($trusted) {
A 4047             $this->capability_readed = true;
4048         }
d83351 4049     }
A 4050
a85f88 4051     /**
A 4052      * Escapes a string when it contains special characters (RFC3501)
4053      *
f7221d 4054      * @param string  $string       IMAP string
b5fb21 4055      * @param boolean $force_quotes Forces string quoting (for atoms)
a85f88 4056      *
b5fb21 4057      * @return string String atom, quoted-string or string literal
A 4058      * @todo lists
a85f88 4059      */
7fb0ae 4060     public static function escape($string, $force_quotes=false)
59c216 4061     {
a85f88 4062         if ($string === null) {
A 4063             return 'NIL';
4064         }
8b3c68 4065
b5fb21 4066         if ($string === '') {
a85f88 4067             return '""';
A 4068         }
8b3c68 4069
b5fb21 4070         // atom-string (only safe characters)
8b3c68 4071         if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x25\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
b5fb21 4072             return $string;
A 4073         }
8b3c68 4074
b5fb21 4075         // quoted-string
A 4076         if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
261ea4 4077             return '"' . addcslashes($string, '\\"') . '"';
a85f88 4078         }
A 4079
b5fb21 4080         // literal-string
A 4081         return sprintf("{%d}\r\n%s", strlen($string), $string);
59c216 4082     }
A 4083
e361bf 4084     /**
7f1da4 4085      * Set the value of the debugging flag.
A 4086      *
9b8d22 4087      * @param boolean  $debug   New value for the debugging flag.
AM 4088      * @param callback $handler Logging handler function
7f1da4 4089      *
9b8d22 4090      * @since 0.5-stable
7f1da4 4091      */
7fb0ae 4092     public function setDebug($debug, $handler = null)
7f1da4 4093     {
7fb0ae 4094         $this->debug         = $debug;
86b241 4095         $this->debug_handler = $handler;
7f1da4 4096     }
A 4097
4098     /**
4099      * Write the given debug text to the current debug output handler.
4100      *
9b8d22 4101      * @param string $message Debug mesage text.
7f1da4 4102      *
9b8d22 4103      * @since 0.5-stable
7f1da4 4104      */
232bcd 4105     protected function debug($message)
7f1da4 4106     {
9b8d22 4107         if (($len = strlen($message)) > self::DEBUG_LINE_LENGTH) {
43079d 4108             $diff    = $len - self::DEBUG_LINE_LENGTH;
AM 4109             $message = substr($message, 0, self::DEBUG_LINE_LENGTH)
4110                 . "... [truncated $diff bytes]";
9b8d22 4111         }
AM 4112
0c7fe2 4113         if ($this->resourceid) {
A 4114             $message = sprintf('[%s] %s', $this->resourceid, $message);
4115         }
4116
86b241 4117         if ($this->debug_handler) {
AM 4118             call_user_func_array($this->debug_handler, array(&$this, $message));
7fb0ae 4119         }
AM 4120         else {
7f1da4 4121             echo "DEBUG: $message\n";
A 4122         }
4123     }
59c216 4124 }