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