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