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