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