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