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