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