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