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