PageRenderTime 76ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/program/lib/Roundcube/rcube_imap_generic.php

https://bitbucket.org/gencer/roundcubemail
PHP | 3908 lines | 2872 code | 408 blank | 628 comment | 601 complexity | 3741b39582fdb8b3b833cad995167338 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2012, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2012, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Provide alternative IMAP library that doesn't rely on the standard |
  14. | C-Client based version. This allows to function regardless |
  15. | of whether or not the PHP build it's running on has IMAP |
  16. | functionality built-in. |
  17. | |
  18. | Based on Iloha IMAP Library. See http://ilohamail.org/ for details |
  19. +-----------------------------------------------------------------------+
  20. | Author: Aleksander Machniak <alec@alec.pl> |
  21. | Author: Ryo Chijiiwa <Ryo@IlohaMail.org> |
  22. +-----------------------------------------------------------------------+
  23. */
  24. /**
  25. * PHP based wrapper class to connect to an IMAP server
  26. *
  27. * @package Framework
  28. * @subpackage Storage
  29. */
  30. class rcube_imap_generic
  31. {
  32. public $error;
  33. public $errornum;
  34. public $result;
  35. public $resultcode;
  36. public $selected;
  37. public $data = array();
  38. public $flags = array(
  39. 'SEEN' => '\\Seen',
  40. 'DELETED' => '\\Deleted',
  41. 'ANSWERED' => '\\Answered',
  42. 'DRAFT' => '\\Draft',
  43. 'FLAGGED' => '\\Flagged',
  44. 'FORWARDED' => '$Forwarded',
  45. 'MDNSENT' => '$MDNSent',
  46. '*' => '\\*',
  47. );
  48. public static $mupdate;
  49. protected $fp;
  50. protected $host;
  51. protected $logged = false;
  52. protected $capability = array();
  53. protected $capability_readed = false;
  54. protected $prefs;
  55. protected $cmd_tag;
  56. protected $cmd_num = 0;
  57. protected $resourceid;
  58. protected $_debug = false;
  59. protected $_debug_handler = false;
  60. const ERROR_OK = 0;
  61. const ERROR_NO = -1;
  62. const ERROR_BAD = -2;
  63. const ERROR_BYE = -3;
  64. const ERROR_UNKNOWN = -4;
  65. const ERROR_COMMAND = -5;
  66. const ERROR_READONLY = -6;
  67. const COMMAND_NORESPONSE = 1;
  68. const COMMAND_CAPABILITY = 2;
  69. const COMMAND_LASTLINE = 4;
  70. const COMMAND_ANONYMIZED = 8;
  71. const DEBUG_LINE_LENGTH = 4098; // 4KB + 2B for \r\n
  72. /**
  73. * Object constructor
  74. */
  75. function __construct()
  76. {
  77. }
  78. /**
  79. * Send simple (one line) command to the connection stream
  80. *
  81. * @param string $string Command string
  82. * @param bool $endln True if CRLF need to be added at the end of command
  83. * @param bool $anonymized Don't write the given data to log but a placeholder
  84. *
  85. * @param int Number of bytes sent, False on error
  86. */
  87. function putLine($string, $endln=true, $anonymized=false)
  88. {
  89. if (!$this->fp)
  90. return false;
  91. if ($this->_debug) {
  92. // anonymize the sent command for logging
  93. $cut = $endln ? 2 : 0;
  94. if ($anonymized && preg_match('/^(A\d+ (?:[A-Z]+ )+)(.+)/', $string, $m)) {
  95. $log = $m[1] . sprintf('****** [%d]', strlen($m[2]) - $cut);
  96. }
  97. else if ($anonymized) {
  98. $log = sprintf('****** [%d]', strlen($string) - $cut);
  99. }
  100. else {
  101. $log = rtrim($string);
  102. }
  103. $this->debug('C: ' . $log);
  104. }
  105. $res = fwrite($this->fp, $string . ($endln ? "\r\n" : ''));
  106. if ($res === false) {
  107. @fclose($this->fp);
  108. $this->fp = null;
  109. }
  110. return $res;
  111. }
  112. /**
  113. * Send command to the connection stream with Command Continuation
  114. * Requests (RFC3501 7.5) and LITERAL+ (RFC2088) support
  115. *
  116. * @param string $string Command string
  117. * @param bool $endln True if CRLF need to be added at the end of command
  118. * @param bool $anonymized Don't write the given data to log but a placeholder
  119. *
  120. * @return int|bool Number of bytes sent, False on error
  121. */
  122. function putLineC($string, $endln=true, $anonymized=false)
  123. {
  124. if (!$this->fp) {
  125. return false;
  126. }
  127. if ($endln) {
  128. $string .= "\r\n";
  129. }
  130. $res = 0;
  131. if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
  132. for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
  133. if (preg_match('/^\{([0-9]+)\}\r\n$/', $parts[$i+1], $matches)) {
  134. // LITERAL+ support
  135. if ($this->prefs['literal+']) {
  136. $parts[$i+1] = sprintf("{%d+}\r\n", $matches[1]);
  137. }
  138. $bytes = $this->putLine($parts[$i].$parts[$i+1], false, $anonymized);
  139. if ($bytes === false)
  140. return false;
  141. $res += $bytes;
  142. // don't wait if server supports LITERAL+ capability
  143. if (!$this->prefs['literal+']) {
  144. $line = $this->readLine(1000);
  145. // handle error in command
  146. if ($line[0] != '+')
  147. return false;
  148. }
  149. $i++;
  150. }
  151. else {
  152. $bytes = $this->putLine($parts[$i], false, $anonymized);
  153. if ($bytes === false)
  154. return false;
  155. $res += $bytes;
  156. }
  157. }
  158. }
  159. return $res;
  160. }
  161. /**
  162. * Reads line from the connection stream
  163. *
  164. * @param int $size Buffer size
  165. *
  166. * @return string Line of text response
  167. */
  168. function readLine($size=1024)
  169. {
  170. $line = '';
  171. if (!$size) {
  172. $size = 1024;
  173. }
  174. do {
  175. if ($this->eof()) {
  176. return $line ? $line : NULL;
  177. }
  178. $buffer = fgets($this->fp, $size);
  179. if ($buffer === false) {
  180. $this->closeSocket();
  181. break;
  182. }
  183. if ($this->_debug) {
  184. $this->debug('S: '. rtrim($buffer));
  185. }
  186. $line .= $buffer;
  187. } while (substr($buffer, -1) != "\n");
  188. return $line;
  189. }
  190. /**
  191. * Reads more data from the connection stream when provided
  192. * data contain string literal
  193. *
  194. * @param string $line Response text
  195. * @param bool $escape Enables escaping
  196. *
  197. * @return string Line of text response
  198. */
  199. function multLine($line, $escape = false)
  200. {
  201. $line = rtrim($line);
  202. if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
  203. $out = '';
  204. $str = substr($line, 0, -strlen($m[0]));
  205. $bytes = $m[1];
  206. while (strlen($out) < $bytes) {
  207. $line = $this->readBytes($bytes);
  208. if ($line === NULL)
  209. break;
  210. $out .= $line;
  211. }
  212. $line = $str . ($escape ? $this->escape($out) : $out);
  213. }
  214. return $line;
  215. }
  216. /**
  217. * Reads specified number of bytes from the connection stream
  218. *
  219. * @param int $bytes Number of bytes to get
  220. *
  221. * @return string Response text
  222. */
  223. function readBytes($bytes)
  224. {
  225. $data = '';
  226. $len = 0;
  227. while ($len < $bytes && !$this->eof())
  228. {
  229. $d = fread($this->fp, $bytes-$len);
  230. if ($this->_debug) {
  231. $this->debug('S: '. $d);
  232. }
  233. $data .= $d;
  234. $data_len = strlen($data);
  235. if ($len == $data_len) {
  236. break; // nothing was read -> exit to avoid apache lockups
  237. }
  238. $len = $data_len;
  239. }
  240. return $data;
  241. }
  242. /**
  243. * Reads complete response to the IMAP command
  244. *
  245. * @param array $untagged Will be filled with untagged response lines
  246. *
  247. * @return string Response text
  248. */
  249. function readReply(&$untagged=null)
  250. {
  251. do {
  252. $line = trim($this->readLine(1024));
  253. // store untagged response lines
  254. if ($line[0] == '*')
  255. $untagged[] = $line;
  256. } while ($line[0] == '*');
  257. if ($untagged)
  258. $untagged = join("\n", $untagged);
  259. return $line;
  260. }
  261. /**
  262. * Response parser.
  263. *
  264. * @param string $string Response text
  265. * @param string $err_prefix Error message prefix
  266. *
  267. * @return int Response status
  268. */
  269. function parseResult($string, $err_prefix='')
  270. {
  271. if (preg_match('/^[a-z0-9*]+ (OK|NO|BAD|BYE)(.*)$/i', trim($string), $matches)) {
  272. $res = strtoupper($matches[1]);
  273. $str = trim($matches[2]);
  274. if ($res == 'OK') {
  275. $this->errornum = self::ERROR_OK;
  276. } else if ($res == 'NO') {
  277. $this->errornum = self::ERROR_NO;
  278. } else if ($res == 'BAD') {
  279. $this->errornum = self::ERROR_BAD;
  280. } else if ($res == 'BYE') {
  281. $this->closeSocket();
  282. $this->errornum = self::ERROR_BYE;
  283. }
  284. if ($str) {
  285. $str = trim($str);
  286. // get response string and code (RFC5530)
  287. if (preg_match("/^\[([a-z-]+)\]/i", $str, $m)) {
  288. $this->resultcode = strtoupper($m[1]);
  289. $str = trim(substr($str, strlen($m[1]) + 2));
  290. }
  291. else {
  292. $this->resultcode = null;
  293. // parse response for [APPENDUID 1204196876 3456]
  294. if (preg_match("/^\[APPENDUID [0-9]+ ([0-9]+)\]/i", $str, $m)) {
  295. $this->data['APPENDUID'] = $m[1];
  296. }
  297. // parse response for [COPYUID 1204196876 3456:3457 123:124]
  298. else if (preg_match("/^\[COPYUID [0-9]+ ([0-9,:]+) ([0-9,:]+)\]/i", $str, $m)) {
  299. $this->data['COPYUID'] = array($m[1], $m[2]);
  300. }
  301. }
  302. $this->result = $str;
  303. if ($this->errornum != self::ERROR_OK) {
  304. $this->error = $err_prefix ? $err_prefix.$str : $str;
  305. }
  306. }
  307. return $this->errornum;
  308. }
  309. return self::ERROR_UNKNOWN;
  310. }
  311. /**
  312. * Checks connection stream state.
  313. *
  314. * @return bool True if connection is closed
  315. */
  316. protected function eof()
  317. {
  318. if (!is_resource($this->fp)) {
  319. return true;
  320. }
  321. // If a connection opened by fsockopen() wasn't closed
  322. // by the server, feof() will hang.
  323. $start = microtime(true);
  324. if (feof($this->fp) ||
  325. ($this->prefs['timeout'] && (microtime(true) - $start > $this->prefs['timeout']))
  326. ) {
  327. $this->closeSocket();
  328. return true;
  329. }
  330. return false;
  331. }
  332. /**
  333. * Closes connection stream.
  334. */
  335. protected function closeSocket()
  336. {
  337. @fclose($this->fp);
  338. $this->fp = null;
  339. }
  340. /**
  341. * Error code/message setter.
  342. */
  343. function setError($code, $msg='')
  344. {
  345. $this->errornum = $code;
  346. $this->error = $msg;
  347. }
  348. /**
  349. * Checks response status.
  350. * Checks if command response line starts with specified prefix (or * BYE/BAD)
  351. *
  352. * @param string $string Response text
  353. * @param string $match Prefix to match with (case-sensitive)
  354. * @param bool $error Enables BYE/BAD checking
  355. * @param bool $nonempty Enables empty response checking
  356. *
  357. * @return bool True any check is true or connection is closed.
  358. */
  359. function startsWith($string, $match, $error=false, $nonempty=false)
  360. {
  361. if (!$this->fp) {
  362. return true;
  363. }
  364. if (strncmp($string, $match, strlen($match)) == 0) {
  365. return true;
  366. }
  367. if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
  368. if (strtoupper($m[1]) == 'BYE') {
  369. $this->closeSocket();
  370. }
  371. return true;
  372. }
  373. if ($nonempty && !strlen($string)) {
  374. return true;
  375. }
  376. return false;
  377. }
  378. protected function hasCapability($name)
  379. {
  380. if (empty($this->capability) || $name == '') {
  381. return false;
  382. }
  383. if (in_array($name, $this->capability)) {
  384. return true;
  385. }
  386. else if (strpos($name, '=')) {
  387. return false;
  388. }
  389. $result = array();
  390. foreach ($this->capability as $cap) {
  391. $entry = explode('=', $cap);
  392. if ($entry[0] == $name) {
  393. $result[] = $entry[1];
  394. }
  395. }
  396. return !empty($result) ? $result : false;
  397. }
  398. /**
  399. * Capabilities checker
  400. *
  401. * @param string $name Capability name
  402. *
  403. * @return mixed Capability values array for key=value pairs, true/false for others
  404. */
  405. function getCapability($name)
  406. {
  407. $result = $this->hasCapability($name);
  408. if (!empty($result)) {
  409. return $result;
  410. }
  411. else if ($this->capability_readed) {
  412. return false;
  413. }
  414. // get capabilities (only once) because initial
  415. // optional CAPABILITY response may differ
  416. $result = $this->execute('CAPABILITY');
  417. if ($result[0] == self::ERROR_OK) {
  418. $this->parseCapability($result[1]);
  419. }
  420. $this->capability_readed = true;
  421. return $this->hasCapability($name);
  422. }
  423. function clearCapability()
  424. {
  425. $this->capability = array();
  426. $this->capability_readed = false;
  427. }
  428. /**
  429. * DIGEST-MD5/CRAM-MD5/PLAIN Authentication
  430. *
  431. * @param string $user
  432. * @param string $pass
  433. * @param string $type Authentication type (PLAIN/CRAM-MD5/DIGEST-MD5)
  434. *
  435. * @return resource Connection resourse on success, error code on error
  436. */
  437. function authenticate($user, $pass, $type='PLAIN')
  438. {
  439. if ($type == 'CRAM-MD5' || $type == 'DIGEST-MD5') {
  440. if ($type == 'DIGEST-MD5' && !class_exists('Auth_SASL')) {
  441. $this->setError(self::ERROR_BYE,
  442. "The Auth_SASL package is required for DIGEST-MD5 authentication");
  443. return self::ERROR_BAD;
  444. }
  445. $this->putLine($this->nextTag() . " AUTHENTICATE $type");
  446. $line = trim($this->readReply());
  447. if ($line[0] == '+') {
  448. $challenge = substr($line, 2);
  449. }
  450. else {
  451. return $this->parseResult($line);
  452. }
  453. if ($type == 'CRAM-MD5') {
  454. // RFC2195: CRAM-MD5
  455. $ipad = '';
  456. $opad = '';
  457. // initialize ipad, opad
  458. for ($i=0; $i<64; $i++) {
  459. $ipad .= chr(0x36);
  460. $opad .= chr(0x5C);
  461. }
  462. // pad $pass so it's 64 bytes
  463. $padLen = 64 - strlen($pass);
  464. for ($i=0; $i<$padLen; $i++) {
  465. $pass .= chr(0);
  466. }
  467. // generate hash
  468. $hash = md5($this->_xor($pass, $opad) . pack("H*",
  469. md5($this->_xor($pass, $ipad) . base64_decode($challenge))));
  470. $reply = base64_encode($user . ' ' . $hash);
  471. // send result
  472. $this->putLine($reply, true, true);
  473. }
  474. else {
  475. // RFC2831: DIGEST-MD5
  476. // proxy authorization
  477. if (!empty($this->prefs['auth_cid'])) {
  478. $authc = $this->prefs['auth_cid'];
  479. $pass = $this->prefs['auth_pw'];
  480. }
  481. else {
  482. $authc = $user;
  483. $user = '';
  484. }
  485. $auth_sasl = Auth_SASL::factory('digestmd5');
  486. $reply = base64_encode($auth_sasl->getResponse($authc, $pass,
  487. base64_decode($challenge), $this->host, 'imap', $user));
  488. // send result
  489. $this->putLine($reply, true, true);
  490. $line = trim($this->readReply());
  491. if ($line[0] == '+') {
  492. $challenge = substr($line, 2);
  493. }
  494. else {
  495. return $this->parseResult($line);
  496. }
  497. // check response
  498. $challenge = base64_decode($challenge);
  499. if (strpos($challenge, 'rspauth=') === false) {
  500. $this->setError(self::ERROR_BAD,
  501. "Unexpected response from server to DIGEST-MD5 response");
  502. return self::ERROR_BAD;
  503. }
  504. $this->putLine('');
  505. }
  506. $line = $this->readReply();
  507. $result = $this->parseResult($line);
  508. }
  509. else { // PLAIN
  510. // proxy authorization
  511. if (!empty($this->prefs['auth_cid'])) {
  512. $authc = $this->prefs['auth_cid'];
  513. $pass = $this->prefs['auth_pw'];
  514. }
  515. else {
  516. $authc = $user;
  517. $user = '';
  518. }
  519. $reply = base64_encode($user . chr(0) . $authc . chr(0) . $pass);
  520. // RFC 4959 (SASL-IR): save one round trip
  521. if ($this->getCapability('SASL-IR')) {
  522. list($result, $line) = $this->execute("AUTHENTICATE PLAIN", array($reply),
  523. self::COMMAND_LASTLINE | self::COMMAND_CAPABILITY | self::COMMAND_ANONYMIZED);
  524. }
  525. else {
  526. $this->putLine($this->nextTag() . " AUTHENTICATE PLAIN");
  527. $line = trim($this->readReply());
  528. if ($line[0] != '+') {
  529. return $this->parseResult($line);
  530. }
  531. // send result, get reply and process it
  532. $this->putLine($reply, true, true);
  533. $line = $this->readReply();
  534. $result = $this->parseResult($line);
  535. }
  536. }
  537. if ($result == self::ERROR_OK) {
  538. // optional CAPABILITY response
  539. if ($line && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
  540. $this->parseCapability($matches[1], true);
  541. }
  542. return $this->fp;
  543. }
  544. else {
  545. $this->setError($result, "AUTHENTICATE $type: $line");
  546. }
  547. return $result;
  548. }
  549. /**
  550. * LOGIN Authentication
  551. *
  552. * @param string $user
  553. * @param string $pass
  554. *
  555. * @return resource Connection resourse on success, error code on error
  556. */
  557. function login($user, $password)
  558. {
  559. list($code, $response) = $this->execute('LOGIN', array(
  560. $this->escape($user), $this->escape($password)), self::COMMAND_CAPABILITY | self::COMMAND_ANONYMIZED);
  561. // re-set capabilities list if untagged CAPABILITY response provided
  562. if (preg_match('/\* CAPABILITY (.+)/i', $response, $matches)) {
  563. $this->parseCapability($matches[1], true);
  564. }
  565. if ($code == self::ERROR_OK) {
  566. return $this->fp;
  567. }
  568. return $code;
  569. }
  570. /**
  571. * Detects hierarchy delimiter
  572. *
  573. * @return string The delimiter
  574. */
  575. function getHierarchyDelimiter()
  576. {
  577. if ($this->prefs['delimiter']) {
  578. return $this->prefs['delimiter'];
  579. }
  580. // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
  581. list($code, $response) = $this->execute('LIST',
  582. array($this->escape(''), $this->escape('')));
  583. if ($code == self::ERROR_OK) {
  584. $args = $this->tokenizeResponse($response, 4);
  585. $delimiter = $args[3];
  586. if (strlen($delimiter) > 0) {
  587. return ($this->prefs['delimiter'] = $delimiter);
  588. }
  589. }
  590. return NULL;
  591. }
  592. /**
  593. * NAMESPACE handler (RFC 2342)
  594. *
  595. * @return array Namespace data hash (personal, other, shared)
  596. */
  597. function getNamespace()
  598. {
  599. if (array_key_exists('namespace', $this->prefs)) {
  600. return $this->prefs['namespace'];
  601. }
  602. if (!$this->getCapability('NAMESPACE')) {
  603. return self::ERROR_BAD;
  604. }
  605. list($code, $response) = $this->execute('NAMESPACE');
  606. if ($code == self::ERROR_OK && preg_match('/^\* NAMESPACE /', $response)) {
  607. $data = $this->tokenizeResponse(substr($response, 11));
  608. }
  609. if (!is_array($data)) {
  610. return $code;
  611. }
  612. $this->prefs['namespace'] = array(
  613. 'personal' => $data[0],
  614. 'other' => $data[1],
  615. 'shared' => $data[2],
  616. );
  617. return $this->prefs['namespace'];
  618. }
  619. /**
  620. * Connects to IMAP server and authenticates.
  621. *
  622. * @param string $host Server hostname or IP
  623. * @param string $user User name
  624. * @param string $password Password
  625. * @param array $options Connection and class options
  626. *
  627. * @return bool True on success, False on failure
  628. */
  629. function connect($host, $user, $password, $options=null)
  630. {
  631. // configure
  632. $this->set_prefs($options);
  633. $this->host = $host;
  634. $this->user = $user;
  635. $this->logged = false;
  636. $this->selected = null;
  637. // check input
  638. if (empty($host)) {
  639. $this->setError(self::ERROR_BAD, "Empty host");
  640. return false;
  641. }
  642. if (empty($user)) {
  643. $this->setError(self::ERROR_NO, "Empty user");
  644. return false;
  645. }
  646. if (empty($password)) {
  647. $this->setError(self::ERROR_NO, "Empty password");
  648. return false;
  649. }
  650. // Connect
  651. if (!$this->_connect($host)) {
  652. return false;
  653. }
  654. // Send ID info
  655. if (!empty($this->prefs['ident']) && $this->getCapability('ID')) {
  656. $this->id($this->prefs['ident']);
  657. }
  658. $auth_method = $this->prefs['auth_type'];
  659. $auth_methods = array();
  660. $result = null;
  661. // check for supported auth methods
  662. if ($auth_method == 'CHECK') {
  663. if ($auth_caps = $this->getCapability('AUTH')) {
  664. $auth_methods = $auth_caps;
  665. }
  666. // RFC 2595 (LOGINDISABLED) LOGIN disabled when connection is not secure
  667. $login_disabled = $this->getCapability('LOGINDISABLED');
  668. if (($key = array_search('LOGIN', $auth_methods)) !== false) {
  669. if ($login_disabled) {
  670. unset($auth_methods[$key]);
  671. }
  672. }
  673. else if (!$login_disabled) {
  674. $auth_methods[] = 'LOGIN';
  675. }
  676. // Use best (for security) supported authentication method
  677. foreach (array('DIGEST-MD5', 'CRAM-MD5', 'CRAM_MD5', 'PLAIN', 'LOGIN') as $auth_method) {
  678. if (in_array($auth_method, $auth_methods)) {
  679. break;
  680. }
  681. }
  682. }
  683. else {
  684. // Prevent from sending credentials in plain text when connection is not secure
  685. if ($auth_method == 'LOGIN' && $this->getCapability('LOGINDISABLED')) {
  686. $this->setError(self::ERROR_BAD, "Login disabled by IMAP server");
  687. $this->closeConnection();
  688. return false;
  689. }
  690. // replace AUTH with CRAM-MD5 for backward compat.
  691. if ($auth_method == 'AUTH') {
  692. $auth_method = 'CRAM-MD5';
  693. }
  694. }
  695. // pre-login capabilities can be not complete
  696. $this->capability_readed = false;
  697. // Authenticate
  698. switch ($auth_method) {
  699. case 'CRAM_MD5':
  700. $auth_method = 'CRAM-MD5';
  701. case 'CRAM-MD5':
  702. case 'DIGEST-MD5':
  703. case 'PLAIN':
  704. $result = $this->authenticate($user, $password, $auth_method);
  705. break;
  706. case 'LOGIN':
  707. $result = $this->login($user, $password);
  708. break;
  709. default:
  710. $this->setError(self::ERROR_BAD, "Configuration error. Unknown auth method: $auth_method");
  711. }
  712. // Connected and authenticated
  713. if (is_resource($result)) {
  714. if ($this->prefs['force_caps']) {
  715. $this->clearCapability();
  716. }
  717. $this->logged = true;
  718. return true;
  719. }
  720. $this->closeConnection();
  721. return false;
  722. }
  723. /**
  724. * Connects to IMAP server.
  725. *
  726. * @param string $host Server hostname or IP
  727. *
  728. * @return bool True on success, False on failure
  729. */
  730. protected function _connect($host)
  731. {
  732. // initialize connection
  733. $this->error = '';
  734. $this->errornum = self::ERROR_OK;
  735. if (!$this->prefs['port']) {
  736. $this->prefs['port'] = 143;
  737. }
  738. // check for SSL
  739. if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
  740. $host = $this->prefs['ssl_mode'] . '://' . $host;
  741. }
  742. if ($this->prefs['timeout'] <= 0) {
  743. $this->prefs['timeout'] = max(0, intval(ini_get('default_socket_timeout')));
  744. }
  745. if (!empty($this->prefs['socket_options'])) {
  746. $context = stream_context_create($this->prefs['socket_options']);
  747. $this->fp = stream_socket_client($host . ':' . $this->prefs['port'], $errno, $errstr,
  748. $this->prefs['timeout'], STREAM_CLIENT_CONNECT, $context);
  749. }
  750. else {
  751. $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
  752. }
  753. if (!$this->fp) {
  754. $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s",
  755. $host, $this->prefs['port'], $errstr ?: "Unknown reason"));
  756. return false;
  757. }
  758. if ($this->prefs['timeout'] > 0) {
  759. stream_set_timeout($this->fp, $this->prefs['timeout']);
  760. }
  761. $line = trim(fgets($this->fp, 8192));
  762. if ($this->_debug) {
  763. // set connection identifier for debug output
  764. preg_match('/#([0-9]+)/', (string) $this->fp, $m);
  765. $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));
  766. if ($line) {
  767. $this->debug('S: '. $line);
  768. }
  769. }
  770. // Connected to wrong port or connection error?
  771. if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
  772. if ($line)
  773. $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
  774. else
  775. $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
  776. $this->setError(self::ERROR_BAD, $error);
  777. $this->closeConnection();
  778. return false;
  779. }
  780. // RFC3501 [7.1] optional CAPABILITY response
  781. if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
  782. $this->parseCapability($matches[1], true);
  783. }
  784. // TLS connection
  785. if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
  786. $res = $this->execute('STARTTLS');
  787. if ($res[0] != self::ERROR_OK) {
  788. $this->closeConnection();
  789. return false;
  790. }
  791. if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
  792. $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
  793. $this->closeConnection();
  794. return false;
  795. }
  796. // Now we're secure, capabilities need to be reread
  797. $this->clearCapability();
  798. }
  799. return true;
  800. }
  801. /**
  802. * Initializes environment
  803. */
  804. protected function set_prefs($prefs)
  805. {
  806. // set preferences
  807. if (is_array($prefs)) {
  808. $this->prefs = $prefs;
  809. }
  810. // set auth method
  811. if (!empty($this->prefs['auth_type'])) {
  812. $this->prefs['auth_type'] = strtoupper($this->prefs['auth_type']);
  813. }
  814. else {
  815. $this->prefs['auth_type'] = 'CHECK';
  816. }
  817. // disabled capabilities
  818. if (!empty($this->prefs['disabled_caps'])) {
  819. $this->prefs['disabled_caps'] = array_map('strtoupper', (array)$this->prefs['disabled_caps']);
  820. }
  821. // additional message flags
  822. if (!empty($this->prefs['message_flags'])) {
  823. $this->flags = array_merge($this->flags, $this->prefs['message_flags']);
  824. unset($this->prefs['message_flags']);
  825. }
  826. }
  827. /**
  828. * Checks connection status
  829. *
  830. * @return bool True if connection is active and user is logged in, False otherwise.
  831. */
  832. function connected()
  833. {
  834. return ($this->fp && $this->logged) ? true : false;
  835. }
  836. /**
  837. * Closes connection with logout.
  838. */
  839. function closeConnection()
  840. {
  841. if ($this->logged && $this->putLine($this->nextTag() . ' LOGOUT')) {
  842. $this->readReply();
  843. }
  844. $this->closeSocket();
  845. }
  846. /**
  847. * Executes SELECT command (if mailbox is already not in selected state)
  848. *
  849. * @param string $mailbox Mailbox name
  850. * @param array $qresync_data QRESYNC data (RFC5162)
  851. *
  852. * @return boolean True on success, false on error
  853. */
  854. function select($mailbox, $qresync_data = null)
  855. {
  856. if (!strlen($mailbox)) {
  857. return false;
  858. }
  859. if ($this->selected === $mailbox) {
  860. return true;
  861. }
  862. /*
  863. Temporary commented out because Courier returns \Noselect for INBOX
  864. Requires more investigation
  865. if (is_array($this->data['LIST']) && is_array($opts = $this->data['LIST'][$mailbox])) {
  866. if (in_array('\\Noselect', $opts)) {
  867. return false;
  868. }
  869. }
  870. */
  871. $params = array($this->escape($mailbox));
  872. // QRESYNC data items
  873. // 0. the last known UIDVALIDITY,
  874. // 1. the last known modification sequence,
  875. // 2. the optional set of known UIDs, and
  876. // 3. an optional parenthesized list of known sequence ranges and their
  877. // corresponding UIDs.
  878. if (!empty($qresync_data)) {
  879. if (!empty($qresync_data[2]))
  880. $qresync_data[2] = self::compressMessageSet($qresync_data[2]);
  881. $params[] = array('QRESYNC', $qresync_data);
  882. }
  883. list($code, $response) = $this->execute('SELECT', $params);
  884. if ($code == self::ERROR_OK) {
  885. $response = explode("\r\n", $response);
  886. foreach ($response as $line) {
  887. if (preg_match('/^\* ([0-9]+) (EXISTS|RECENT)$/i', $line, $m)) {
  888. $this->data[strtoupper($m[2])] = (int) $m[1];
  889. }
  890. else if (preg_match('/^\* OK \[/i', $line, $match)) {
  891. $line = substr($line, 6);
  892. if (preg_match('/^(UIDNEXT|UIDVALIDITY|UNSEEN) ([0-9]+)/i', $line, $match)) {
  893. $this->data[strtoupper($match[1])] = (int) $match[2];
  894. }
  895. else if (preg_match('/^(HIGHESTMODSEQ) ([0-9]+)/i', $line, $match)) {
  896. $this->data[strtoupper($match[1])] = (string) $match[2];
  897. }
  898. else if (preg_match('/^(NOMODSEQ)/i', $line, $match)) {
  899. $this->data[strtoupper($match[1])] = true;
  900. }
  901. else if (preg_match('/^PERMANENTFLAGS \(([^\)]+)\)/iU', $line, $match)) {
  902. $this->data['PERMANENTFLAGS'] = explode(' ', $match[1]);
  903. }
  904. }
  905. // QRESYNC FETCH response (RFC5162)
  906. else if (preg_match('/^\* ([0-9+]) FETCH/i', $line, $match)) {
  907. $line = substr($line, strlen($match[0]));
  908. $fetch_data = $this->tokenizeResponse($line, 1);
  909. $data = array('id' => $match[1]);
  910. for ($i=0, $size=count($fetch_data); $i<$size; $i+=2) {
  911. $data[strtolower($fetch_data[$i])] = $fetch_data[$i+1];
  912. }
  913. $this->data['QRESYNC'][$data['uid']] = $data;
  914. }
  915. // QRESYNC VANISHED response (RFC5162)
  916. else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
  917. $line = substr($line, strlen($match[0]));
  918. $v_data = $this->tokenizeResponse($line, 1);
  919. $this->data['VANISHED'] = $v_data;
  920. }
  921. }
  922. $this->data['READ-WRITE'] = $this->resultcode != 'READ-ONLY';
  923. $this->selected = $mailbox;
  924. return true;
  925. }
  926. return false;
  927. }
  928. /**
  929. * Executes STATUS command
  930. *
  931. * @param string $mailbox Mailbox name
  932. * @param array $items Additional requested item names. By default
  933. * MESSAGES and UNSEEN are requested. Other defined
  934. * in RFC3501: UIDNEXT, UIDVALIDITY, RECENT
  935. *
  936. * @return array Status item-value hash
  937. * @since 0.5-beta
  938. */
  939. function status($mailbox, $items=array())
  940. {
  941. if (!strlen($mailbox)) {
  942. return false;
  943. }
  944. if (!in_array('MESSAGES', $items)) {
  945. $items[] = 'MESSAGES';
  946. }
  947. if (!in_array('UNSEEN', $items)) {
  948. $items[] = 'UNSEEN';
  949. }
  950. list($code, $response) = $this->execute('STATUS', array($this->escape($mailbox),
  951. '(' . implode(' ', (array) $items) . ')'));
  952. if ($code == self::ERROR_OK && preg_match('/\* STATUS /i', $response)) {
  953. $result = array();
  954. $response = substr($response, 9); // remove prefix "* STATUS "
  955. list($mbox, $items) = $this->tokenizeResponse($response, 2);
  956. // Fix for #1487859. Some buggy server returns not quoted
  957. // folder name with spaces. Let's try to handle this situation
  958. if (!is_array($items) && ($pos = strpos($response, '(')) !== false) {
  959. $response = substr($response, $pos);
  960. $items = $this->tokenizeResponse($response, 1);
  961. if (!is_array($items)) {
  962. return $result;
  963. }
  964. }
  965. for ($i=0, $len=count($items); $i<$len; $i += 2) {
  966. $result[$items[$i]] = $items[$i+1];
  967. }
  968. $this->data['STATUS:'.$mailbox] = $result;
  969. return $result;
  970. }
  971. return false;
  972. }
  973. /**
  974. * Executes EXPUNGE command
  975. *
  976. * @param string $mailbox Mailbox name
  977. * @param string|array $messages Message UIDs to expunge
  978. *
  979. * @return boolean True on success, False on error
  980. */
  981. function expunge($mailbox, $messages=NULL)
  982. {
  983. if (!$this->select($mailbox)) {
  984. return false;
  985. }
  986. if (!$this->data['READ-WRITE']) {
  987. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  988. return false;
  989. }
  990. // Clear internal status cache
  991. unset($this->data['STATUS:'.$mailbox]);
  992. if (!empty($messages) && $messages != '*' && $this->hasCapability('UIDPLUS')) {
  993. $messages = self::compressMessageSet($messages);
  994. $result = $this->execute('UID EXPUNGE', array($messages), self::COMMAND_NORESPONSE);
  995. }
  996. else {
  997. $result = $this->execute('EXPUNGE', null, self::COMMAND_NORESPONSE);
  998. }
  999. if ($result == self::ERROR_OK) {
  1000. $this->selected = null; // state has changed, need to reselect
  1001. return true;
  1002. }
  1003. return false;
  1004. }
  1005. /**
  1006. * Executes CLOSE command
  1007. *
  1008. * @return boolean True on success, False on error
  1009. * @since 0.5
  1010. */
  1011. function close()
  1012. {
  1013. $result = $this->execute('CLOSE', NULL, self::COMMAND_NORESPONSE);
  1014. if ($result == self::ERROR_OK) {
  1015. $this->selected = null;
  1016. return true;
  1017. }
  1018. return false;
  1019. }
  1020. /**
  1021. * Folder subscription (SUBSCRIBE)
  1022. *
  1023. * @param string $mailbox Mailbox name
  1024. *
  1025. * @return boolean True on success, False on error
  1026. */
  1027. function subscribe($mailbox)
  1028. {
  1029. $result = $this->execute('SUBSCRIBE', array($this->escape($mailbox)),
  1030. self::COMMAND_NORESPONSE);
  1031. return ($result == self::ERROR_OK);
  1032. }
  1033. /**
  1034. * Folder unsubscription (UNSUBSCRIBE)
  1035. *
  1036. * @param string $mailbox Mailbox name
  1037. *
  1038. * @return boolean True on success, False on error
  1039. */
  1040. function unsubscribe($mailbox)
  1041. {
  1042. $result = $this->execute('UNSUBSCRIBE', array($this->escape($mailbox)),
  1043. self::COMMAND_NORESPONSE);
  1044. return ($result == self::ERROR_OK);
  1045. }
  1046. /**
  1047. * Folder creation (CREATE)
  1048. *
  1049. * @param string $mailbox Mailbox name
  1050. * @param array $types Optional folder types (RFC 6154)
  1051. *
  1052. * @return bool True on success, False on error
  1053. */
  1054. function createFolder($mailbox, $types = null)
  1055. {
  1056. $args = array($this->escape($mailbox));
  1057. // RFC 6154: CREATE-SPECIAL-USE
  1058. if (!empty($types) && $this->getCapability('CREATE-SPECIAL-USE')) {
  1059. $args[] = '(USE (' . implode(' ', $types) . '))';
  1060. }
  1061. $result = $this->execute('CREATE', $args, self::COMMAND_NORESPONSE);
  1062. return ($result == self::ERROR_OK);
  1063. }
  1064. /**
  1065. * Folder renaming (RENAME)
  1066. *
  1067. * @param string $mailbox Mailbox name
  1068. *
  1069. * @return bool True on success, False on error
  1070. */
  1071. function renameFolder($from, $to)
  1072. {
  1073. $result = $this->execute('RENAME', array($this->escape($from), $this->escape($to)),
  1074. self::COMMAND_NORESPONSE);
  1075. return ($result == self::ERROR_OK);
  1076. }
  1077. /**
  1078. * Executes DELETE command
  1079. *
  1080. * @param string $mailbox Mailbox name
  1081. *
  1082. * @return boolean True on success, False on error
  1083. */
  1084. function deleteFolder($mailbox)
  1085. {
  1086. $result = $this->execute('DELETE', array($this->escape($mailbox)),
  1087. self::COMMAND_NORESPONSE);
  1088. return ($result == self::ERROR_OK);
  1089. }
  1090. /**
  1091. * Removes all messages in a folder
  1092. *
  1093. * @param string $mailbox Mailbox name
  1094. *
  1095. * @return boolean True on success, False on error
  1096. */
  1097. function clearFolder($mailbox)
  1098. {
  1099. $num_in_trash = $this->countMessages($mailbox);
  1100. if ($num_in_trash > 0) {
  1101. $res = $this->flag($mailbox, '1:*', 'DELETED');
  1102. }
  1103. if ($res) {
  1104. if ($this->selected === $mailbox)
  1105. $res = $this->close();
  1106. else
  1107. $res = $this->expunge($mailbox);
  1108. }
  1109. return $res;
  1110. }
  1111. /**
  1112. * Returns list of mailboxes
  1113. *
  1114. * @param string $ref Reference name
  1115. * @param string $mailbox Mailbox name
  1116. * @param array $return_opts (see self::_listMailboxes)
  1117. * @param array $select_opts (see self::_listMailboxes)
  1118. *
  1119. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1120. * is requested, False on error.
  1121. */
  1122. function listMailboxes($ref, $mailbox, $return_opts=array(), $select_opts=array())
  1123. {
  1124. return $this->_listMailboxes($ref, $mailbox, false, $return_opts, $select_opts);
  1125. }
  1126. /**
  1127. * Returns list of subscribed mailboxes
  1128. *
  1129. * @param string $ref Reference name
  1130. * @param string $mailbox Mailbox name
  1131. * @param array $return_opts (see self::_listMailboxes)
  1132. *
  1133. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1134. * is requested, False on error.
  1135. */
  1136. function listSubscribed($ref, $mailbox, $return_opts=array())
  1137. {
  1138. return $this->_listMailboxes($ref, $mailbox, true, $return_opts, NULL);
  1139. }
  1140. /**
  1141. * IMAP LIST/LSUB command
  1142. *
  1143. * @param string $ref Reference name
  1144. * @param string $mailbox Mailbox name
  1145. * @param bool $subscribed Enables returning subscribed mailboxes only
  1146. * @param array $return_opts List of RETURN options (RFC5819: LIST-STATUS, RFC5258: LIST-EXTENDED)
  1147. * Possible: MESSAGES, RECENT, UIDNEXT, UIDVALIDITY, UNSEEN,
  1148. * MYRIGHTS, SUBSCRIBED, CHILDREN
  1149. * @param array $select_opts List of selection options (RFC5258: LIST-EXTENDED)
  1150. * Possible: SUBSCRIBED, RECURSIVEMATCH, REMOTE,
  1151. * SPECIAL-USE (RFC6154)
  1152. *
  1153. * @return array|bool List of mailboxes or hash of options if STATUS/MYROGHTS response
  1154. * is requested, False on error.
  1155. */
  1156. protected function _listMailboxes($ref, $mailbox, $subscribed=false,
  1157. $return_opts=array(), $select_opts=array())
  1158. {
  1159. if (!strlen($mailbox)) {
  1160. $mailbox = '*';
  1161. }
  1162. $args = array();
  1163. $rets = array();
  1164. if (!empty($select_opts) && $this->getCapability('LIST-EXTENDED')) {
  1165. $select_opts = (array) $select_opts;
  1166. $args[] = '(' . implode(' ', $select_opts) . ')';
  1167. }
  1168. $args[] = $this->escape($ref);
  1169. $args[] = $this->escape($mailbox);
  1170. if (!empty($return_opts) && $this->getCapability('LIST-EXTENDED')) {
  1171. $ext_opts = array('SUBSCRIBED', 'CHILDREN');
  1172. $rets = array_intersect($return_opts, $ext_opts);
  1173. $return_opts = array_diff($return_opts, $rets);
  1174. }
  1175. if (!empty($return_opts) && $this->getCapability('LIST-STATUS')) {
  1176. $lstatus = true;
  1177. $status_opts = array('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN');
  1178. $opts = array_diff($return_opts, $status_opts);
  1179. $status_opts = array_diff($return_opts, $opts);
  1180. if (!empty($status_opts)) {
  1181. $rets[] = 'STATUS (' . implode(' ', $status_opts) . ')';
  1182. }
  1183. if (!empty($opts)) {
  1184. $rets = array_merge($rets, $opts);
  1185. }
  1186. }
  1187. if (!empty($rets)) {
  1188. $args[] = 'RETURN (' . implode(' ', $rets) . ')';
  1189. }
  1190. list($code, $response) = $this->execute($subscribed ? 'LSUB' : 'LIST', $args);
  1191. if ($code == self::ERROR_OK) {
  1192. $folders = array();
  1193. $last = 0;
  1194. $pos = 0;
  1195. $response .= "\r\n";
  1196. while ($pos = strpos($response, "\r\n", $pos+1)) {
  1197. // literal string, not real end-of-command-line
  1198. if ($response[$pos-1] == '}') {
  1199. continue;
  1200. }
  1201. $line = substr($response, $last, $pos - $last);
  1202. $last = $pos + 2;
  1203. if (!preg_match('/^\* (LIST|LSUB|STATUS|MYRIGHTS) /i', $line, $m)) {
  1204. continue;
  1205. }
  1206. $cmd = strtoupper($m[1]);
  1207. $line = substr($line, strlen($m[0]));
  1208. // * LIST (<options>) <delimiter> <mailbox>
  1209. if ($cmd == 'LIST' || $cmd == 'LSUB') {
  1210. list($opts, $delim, $mailbox) = $this->tokenizeResponse($line, 3);
  1211. // Remove redundant separator at the end of folder name, UW-IMAP bug? (#1488879)
  1212. if ($delim) {
  1213. $mailbox = rtrim($mailbox, $delim);
  1214. }
  1215. // Add to result array
  1216. if (!$lstatus) {
  1217. $folders[] = $mailbox;
  1218. }
  1219. else {
  1220. $folders[$mailbox] = array();
  1221. }
  1222. // store folder options
  1223. if ($cmd == 'LIST') {
  1224. // Add to options array
  1225. if (empty($this->data['LIST'][$mailbox]))
  1226. $this->data['LIST'][$mailbox] = $opts;
  1227. else if (!empty($opts))
  1228. $this->data['LIST'][$mailbox] = array_unique(array_merge(
  1229. $this->data['LIST'][$mailbox], $opts));
  1230. }
  1231. }
  1232. else if ($lstatus) {
  1233. // * STATUS <mailbox> (<result>)
  1234. if ($cmd == 'STATUS') {
  1235. list($mailbox, $status) = $this->tokenizeResponse($line, 2);
  1236. for ($i=0, $len=count($status); $i<$len; $i += 2) {
  1237. list($name, $value) = $this->tokenizeResponse($status, 2);
  1238. $folders[$mailbox][$name] = $value;
  1239. }
  1240. }
  1241. // * MYRIGHTS <mailbox> <acl>
  1242. else if ($cmd == 'MYRIGHTS') {
  1243. list($mailbox, $acl) = $this->tokenizeResponse($line, 2);
  1244. $folders[$mailbox]['MYRIGHTS'] = $acl;
  1245. }
  1246. }
  1247. }
  1248. return $folders;
  1249. }
  1250. return false;
  1251. }
  1252. /**
  1253. * Returns count of all messages in a folder
  1254. *
  1255. * @param string $mailbox Mailbox name
  1256. *
  1257. * @return int Number of messages, False on error
  1258. */
  1259. function countMessages($mailbox, $refresh = false)
  1260. {
  1261. if ($refresh) {
  1262. $this->selected = null;
  1263. }
  1264. if ($this->selected === $mailbox) {
  1265. return $this->data['EXISTS'];
  1266. }
  1267. // Check internal cache
  1268. $cache = $this->data['STATUS:'.$mailbox];
  1269. if (!empty($cache) && isset($cache['MESSAGES'])) {
  1270. return (int) $cache['MESSAGES'];
  1271. }
  1272. // Try STATUS (should be faster than SELECT)
  1273. $counts = $this->status($mailbox);
  1274. if (is_array($counts)) {
  1275. return (int) $counts['MESSAGES'];
  1276. }
  1277. return false;
  1278. }
  1279. /**
  1280. * Returns count of messages with \Recent flag in a folder
  1281. *
  1282. * @param string $mailbox Mailbox name
  1283. *
  1284. * @return int Number of messages, False on error
  1285. */
  1286. function countRecent($mailbox)
  1287. {
  1288. if (!strlen($mailbox)) {
  1289. $mailbox = 'INBOX';
  1290. }
  1291. $this->select($mailbox);
  1292. if ($this->selected === $mailbox) {
  1293. return $this->data['RECENT'];
  1294. }
  1295. return false;
  1296. }
  1297. /**
  1298. * Returns count of messages without \Seen flag in a specified folder
  1299. *
  1300. * @param string $mailbox Mailbox name
  1301. *
  1302. * @return int Number of messages, False on error
  1303. */
  1304. function countUnseen($mailbox)
  1305. {
  1306. // Check internal cache
  1307. $cache = $this->data['STATUS:'.$mailbox];
  1308. if (!empty($cache) && isset($cache['UNSEEN'])) {
  1309. return (int) $cache['UNSEEN'];
  1310. }
  1311. // Try STATUS (should be faster than SELECT+SEARCH)
  1312. $counts = $this->status($mailbox);
  1313. if (is_array($counts)) {
  1314. return (int) $counts['UNSEEN'];
  1315. }
  1316. // Invoke SEARCH as a fallback
  1317. $index = $this->search($mailbox, 'ALL UNSEEN', false, array('COUNT'));
  1318. if (!$index->is_error()) {
  1319. return $index->count();
  1320. }
  1321. return false;
  1322. }
  1323. /**
  1324. * Executes ID command (RFC2971)
  1325. *
  1326. * @param array $items Client identification information key/value hash
  1327. *
  1328. * @return array Server identification information key/value hash
  1329. * @since 0.6
  1330. */
  1331. function id($items=array())
  1332. {
  1333. if (is_array($items) && !empty($items)) {
  1334. foreach ($items as $key => $value) {
  1335. $args[] = $this->escape($key, true);
  1336. $args[] = $this->escape($value, true);
  1337. }
  1338. }
  1339. list($code, $response) = $this->execute('ID', array(
  1340. !empty($args) ? '(' . implode(' ', (array) $args) . ')' : $this->escape(null)
  1341. ));
  1342. if ($code == self::ERROR_OK && preg_match('/\* ID /i', $response)) {
  1343. $response = substr($response, 5); // remove prefix "* ID "
  1344. $items = $this->tokenizeResponse($response, 1);
  1345. $result = null;
  1346. for ($i=0, $len=count($items); $i<$len; $i += 2) {
  1347. $result[$items[$i]] = $items[$i+1];
  1348. }
  1349. return $result;
  1350. }
  1351. return false;
  1352. }
  1353. /**
  1354. * Executes ENABLE command (RFC5161)
  1355. *
  1356. * @param mixed $extension Extension name to enable (or array of names)
  1357. *
  1358. * @return array|bool List of enabled extensions, False on error
  1359. * @since 0.6
  1360. */
  1361. function enable($extension)
  1362. {
  1363. if (empty($extension)) {
  1364. return false;
  1365. }
  1366. if (!$this->hasCapability('ENABLE')) {
  1367. return false;
  1368. }
  1369. if (!is_array($extension)) {
  1370. $extension = array($extension);
  1371. }
  1372. if (!empty(

Large files files are truncated, but you can click here to view the full file