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