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