PageRenderTime 71ms CodeModel.GetById 19ms 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
  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($this->extensions_enabled)) {
  1373. // check if all extensions are already enabled
  1374. $diff = array_diff($extension, $this->extensions_enabled);
  1375. if (empty($diff)) {
  1376. return $extension;
  1377. }
  1378. // Make sure the mailbox isn't selected, before enabling extension(s)
  1379. if ($this->selected !== null) {
  1380. $this->close();
  1381. }
  1382. }
  1383. list($code, $response) = $this->execute('ENABLE', $extension);
  1384. if ($code == self::ERROR_OK && preg_match('/\* ENABLED /i', $response)) {
  1385. $response = substr($response, 10); // remove prefix "* ENABLED "
  1386. $result = (array) $this->tokenizeResponse($response);
  1387. $this->extensions_enabled = array_unique(array_merge((array)$this->extensions_enabled, $result));
  1388. return $this->extensions_enabled;
  1389. }
  1390. return false;
  1391. }
  1392. /**
  1393. * Executes SORT command
  1394. *
  1395. * @param string $mailbox Mailbox name
  1396. * @param string $field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
  1397. * @param string $criteria Searching criteria
  1398. * @param bool $return_uid Enables UID SORT usage
  1399. * @param string $encoding Character set
  1400. *
  1401. * @return rcube_result_index Response data
  1402. */
  1403. function sort($mailbox, $field = 'ARRIVAL', $criteria = '', $return_uid = false, $encoding = 'US-ASCII')
  1404. {
  1405. $old_sel = $this->selected;
  1406. $supported = array('ARRIVAL', 'CC', 'DATE', 'FROM', 'SIZE', 'SUBJECT', 'TO');
  1407. $field = strtoupper($field);
  1408. if ($field == 'INTERNALDATE') {
  1409. $field = 'ARRIVAL';
  1410. }
  1411. if (!in_array($field, $supported)) {
  1412. return new rcube_result_index($mailbox);
  1413. }
  1414. if (!$this->select($mailbox)) {
  1415. return new rcube_result_index($mailbox);
  1416. }
  1417. // return empty result when folder is empty and we're just after SELECT
  1418. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1419. return new rcube_result_index($mailbox, '* SORT');
  1420. }
  1421. // RFC 5957: SORT=DISPLAY
  1422. if (($field == 'FROM' || $field == 'TO') && $this->getCapability('SORT=DISPLAY')) {
  1423. $field = 'DISPLAY' . $field;
  1424. }
  1425. $encoding = $encoding ? trim($encoding) : 'US-ASCII';
  1426. $criteria = $criteria ? 'ALL ' . trim($criteria) : 'ALL';
  1427. list($code, $response) = $this->execute($return_uid ? 'UID SORT' : 'SORT',
  1428. array("($field)", $encoding, $criteria));
  1429. if ($code != self::ERROR_OK) {
  1430. $response = null;
  1431. }
  1432. return new rcube_result_index($mailbox, $response);
  1433. }
  1434. /**
  1435. * Executes THREAD command
  1436. *
  1437. * @param string $mailbox Mailbox name
  1438. * @param string $algorithm Threading algorithm (ORDEREDSUBJECT, REFERENCES, REFS)
  1439. * @param string $criteria Searching criteria
  1440. * @param bool $return_uid Enables UIDs in result instead of sequence numbers
  1441. * @param string $encoding Character set
  1442. *
  1443. * @return rcube_result_thread Thread data
  1444. */
  1445. function thread($mailbox, $algorithm='REFERENCES', $criteria='', $return_uid=false, $encoding='US-ASCII')
  1446. {
  1447. $old_sel = $this->selected;
  1448. if (!$this->select($mailbox)) {
  1449. return new rcube_result_thread($mailbox);
  1450. }
  1451. // return empty result when folder is empty and we're just after SELECT
  1452. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1453. return new rcube_result_thread($mailbox, '* THREAD');
  1454. }
  1455. $encoding = $encoding ? trim($encoding) : 'US-ASCII';
  1456. $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
  1457. $criteria = $criteria ? 'ALL '.trim($criteria) : 'ALL';
  1458. $data = '';
  1459. list($code, $response) = $this->execute($return_uid ? 'UID THREAD' : 'THREAD',
  1460. array($algorithm, $encoding, $criteria));
  1461. if ($code != self::ERROR_OK) {
  1462. $response = null;
  1463. }
  1464. return new rcube_result_thread($mailbox, $response);
  1465. }
  1466. /**
  1467. * Executes SEARCH command
  1468. *
  1469. * @param string $mailbox Mailbox name
  1470. * @param string $criteria Searching criteria
  1471. * @param bool $return_uid Enable UID in result instead of sequence ID
  1472. * @param array $items Return items (MIN, MAX, COUNT, ALL)
  1473. *
  1474. * @return rcube_result_index Result data
  1475. */
  1476. function search($mailbox, $criteria, $return_uid=false, $items=array())
  1477. {
  1478. $old_sel = $this->selected;
  1479. if (!$this->select($mailbox)) {
  1480. return new rcube_result_index($mailbox);
  1481. }
  1482. // return empty result when folder is empty and we're just after SELECT
  1483. if ($old_sel != $mailbox && !$this->data['EXISTS']) {
  1484. return new rcube_result_index($mailbox, '* SEARCH');
  1485. }
  1486. // If ESEARCH is supported always use ALL
  1487. // but not when items are specified or using simple id2uid search
  1488. if (empty($items) && preg_match('/[^0-9]/', $criteria)) {
  1489. $items = array('ALL');
  1490. }
  1491. $esearch = empty($items) ? false : $this->getCapability('ESEARCH');
  1492. $criteria = trim($criteria);
  1493. $params = '';
  1494. // RFC4731: ESEARCH
  1495. if (!empty($items) && $esearch) {
  1496. $params .= 'RETURN (' . implode(' ', $items) . ')';
  1497. }
  1498. if (!empty($criteria)) {
  1499. $params .= ($params ? ' ' : '') . $criteria;
  1500. }
  1501. else {
  1502. $params .= 'ALL';
  1503. }
  1504. list($code, $response) = $this->execute($return_uid ? 'UID SEARCH' : 'SEARCH',
  1505. array($params));
  1506. if ($code != self::ERROR_OK) {
  1507. $response = null;
  1508. }
  1509. return new rcube_result_index($mailbox, $response);
  1510. }
  1511. /**
  1512. * Simulates SORT command by using FETCH and sorting.
  1513. *
  1514. * @param string $mailbox Mailbox name
  1515. * @param string|array $message_set Searching criteria (list of messages to return)
  1516. * @param string $index_field Field to sort by (ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT, TO)
  1517. * @param bool $skip_deleted Makes that DELETED messages will be skipped
  1518. * @param bool $uidfetch Enables UID FETCH usage
  1519. * @param bool $return_uid Enables returning UIDs instead of IDs
  1520. *
  1521. * @return rcube_result_index Response data
  1522. */
  1523. function index($mailbox, $message_set, $index_field='', $skip_deleted=true,
  1524. $uidfetch=false, $return_uid=false)
  1525. {
  1526. $msg_index = $this->fetchHeaderIndex($mailbox, $message_set,
  1527. $index_field, $skip_deleted, $uidfetch, $return_uid);
  1528. if (!empty($msg_index)) {
  1529. asort($msg_index); // ASC
  1530. $msg_index = array_keys($msg_index);
  1531. $msg_index = '* SEARCH ' . implode(' ', $msg_index);
  1532. }
  1533. else {
  1534. $msg_index = is_array($msg_index) ? '* SEARCH' : null;
  1535. }
  1536. return new rcube_result_index($mailbox, $msg_index);
  1537. }
  1538. function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true,
  1539. $uidfetch=false, $return_uid=false)
  1540. {
  1541. if (is_array($message_set)) {
  1542. if (!($message_set = $this->compressMessageSet($message_set)))
  1543. return false;
  1544. } else {
  1545. list($from_idx, $to_idx) = explode(':', $message_set);
  1546. if (empty($message_set) ||
  1547. (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
  1548. return false;
  1549. }
  1550. }
  1551. $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
  1552. $fields_a['DATE'] = 1;
  1553. $fields_a['INTERNALDATE'] = 4;
  1554. $fields_a['ARRIVAL'] = 4;
  1555. $fields_a['FROM'] = 1;
  1556. $fields_a['REPLY-TO'] = 1;
  1557. $fields_a['SENDER'] = 1;
  1558. $fields_a['TO'] = 1;
  1559. $fields_a['CC'] = 1;
  1560. $fields_a['SUBJECT'] = 1;
  1561. $fields_a['UID'] = 2;
  1562. $fields_a['SIZE'] = 2;
  1563. $fields_a['SEEN'] = 3;
  1564. $fields_a['RECENT'] = 3;
  1565. $fields_a['DELETED'] = 3;
  1566. if (!($mode = $fields_a[$index_field])) {
  1567. return false;
  1568. }
  1569. /* Do "SELECT" command */
  1570. if (!$this->select($mailbox)) {
  1571. return false;
  1572. }
  1573. // build FETCH command string
  1574. $key = $this->nextTag();
  1575. $cmd = $uidfetch ? 'UID FETCH' : 'FETCH';
  1576. $fields = array();
  1577. if ($return_uid)
  1578. $fields[] = 'UID';
  1579. if ($skip_deleted)
  1580. $fields[] = 'FLAGS';
  1581. if ($mode == 1) {
  1582. if ($index_field == 'DATE')
  1583. $fields[] = 'INTERNALDATE';
  1584. $fields[] = "BODY.PEEK[HEADER.FIELDS ($index_field)]";
  1585. }
  1586. else if ($mode == 2) {
  1587. if ($index_field == 'SIZE')
  1588. $fields[] = 'RFC822.SIZE';
  1589. else if (!$return_uid || $index_field != 'UID')
  1590. $fields[] = $index_field;
  1591. }
  1592. else if ($mode == 3 && !$skip_deleted)
  1593. $fields[] = 'FLAGS';
  1594. else if ($mode == 4)
  1595. $fields[] = 'INTERNALDATE';
  1596. $request = "$key $cmd $message_set (" . implode(' ', $fields) . ")";
  1597. if (!$this->putLine($request)) {
  1598. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  1599. return false;
  1600. }
  1601. $result = array();
  1602. do {
  1603. $line = rtrim($this->readLine(200));
  1604. $line = $this->multLine($line);
  1605. if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
  1606. $id = $m[1];
  1607. $flags = NULL;
  1608. if ($return_uid) {
  1609. if (preg_match('/UID ([0-9]+)/', $line, $matches))
  1610. $id = (int) $matches[1];
  1611. else
  1612. continue;
  1613. }
  1614. if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
  1615. $flags = explode(' ', strtoupper($matches[1]));
  1616. if (in_array('\\DELETED', $flags)) {
  1617. continue;
  1618. }
  1619. }
  1620. if ($mode == 1 && $index_field == 'DATE') {
  1621. if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
  1622. $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
  1623. $value = trim($value);
  1624. $result[$id] = $this->strToTime($value);
  1625. }
  1626. // non-existent/empty Date: header, use INTERNALDATE
  1627. if (empty($result[$id])) {
  1628. if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
  1629. $result[$id] = $this->strToTime($matches[1]);
  1630. else
  1631. $result[$id] = 0;
  1632. }
  1633. } else if ($mode == 1) {
  1634. if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
  1635. $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
  1636. $result[$id] = trim($value);
  1637. } else {
  1638. $result[$id] = '';
  1639. }
  1640. } else if ($mode == 2) {
  1641. if (preg_match('/' . $index_field . ' ([0-9]+)/', $line, $matches)) {
  1642. $result[$id] = trim($matches[1]);
  1643. } else {
  1644. $result[$id] = 0;
  1645. }
  1646. } else if ($mode == 3) {
  1647. if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
  1648. $flags = explode(' ', $matches[1]);
  1649. }
  1650. $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
  1651. } else if ($mode == 4) {
  1652. if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
  1653. $result[$id] = $this->strToTime($matches[1]);
  1654. } else {
  1655. $result[$id] = 0;
  1656. }
  1657. }
  1658. }
  1659. } while (!$this->startsWith($line, $key, true, true));
  1660. return $result;
  1661. }
  1662. /**
  1663. * Returns message sequence identifier
  1664. *
  1665. * @param string $mailbox Mailbox name
  1666. * @param int $uid Message unique identifier (UID)
  1667. *
  1668. * @return int Message sequence identifier
  1669. */
  1670. function UID2ID($mailbox, $uid)
  1671. {
  1672. if ($uid > 0) {
  1673. $index = $this->search($mailbox, "UID $uid");
  1674. if ($index->count() == 1) {
  1675. $arr = $index->get();
  1676. return (int) $arr[0];
  1677. }
  1678. }
  1679. return null;
  1680. }
  1681. /**
  1682. * Returns message unique identifier (UID)
  1683. *
  1684. * @param string $mailbox Mailbox name
  1685. * @param int $uid Message sequence identifier
  1686. *
  1687. * @return int Message unique identifier
  1688. */
  1689. function ID2UID($mailbox, $id)
  1690. {
  1691. if (empty($id) || $id < 0) {
  1692. return null;
  1693. }
  1694. if (!$this->select($mailbox)) {
  1695. return null;
  1696. }
  1697. $index = $this->search($mailbox, $id, true);
  1698. if ($index->count() == 1) {
  1699. $arr = $index->get();
  1700. return (int) $arr[0];
  1701. }
  1702. return null;
  1703. }
  1704. /**
  1705. * Sets flag of the message(s)
  1706. *
  1707. * @param string $mailbox Mailbox name
  1708. * @param string|array $messages Message UID(s)
  1709. * @param string $flag Flag name
  1710. *
  1711. * @return bool True on success, False on failure
  1712. */
  1713. function flag($mailbox, $messages, $flag) {
  1714. return $this->modFlag($mailbox, $messages, $flag, '+');
  1715. }
  1716. /**
  1717. * Unsets flag of the message(s)
  1718. *
  1719. * @param string $mailbox Mailbox name
  1720. * @param string|array $messages Message UID(s)
  1721. * @param string $flag Flag name
  1722. *
  1723. * @return bool True on success, False on failure
  1724. */
  1725. function unflag($mailbox, $messages, $flag) {
  1726. return $this->modFlag($mailbox, $messages, $flag, '-');
  1727. }
  1728. /**
  1729. * Changes flag of the message(s)
  1730. *
  1731. * @param string $mailbox Mailbox name
  1732. * @param string|array $messages Message UID(s)
  1733. * @param string $flag Flag name
  1734. * @param string $mod Modifier [+|-]. Default: "+".
  1735. *
  1736. * @return bool True on success, False on failure
  1737. */
  1738. protected function modFlag($mailbox, $messages, $flag, $mod = '+')
  1739. {
  1740. if (!$this->select($mailbox)) {
  1741. return false;
  1742. }
  1743. if (!$this->data['READ-WRITE']) {
  1744. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  1745. return false;
  1746. }
  1747. if ($this->flags[strtoupper($flag)]) {
  1748. $flag = $this->flags[strtoupper($flag)];
  1749. }
  1750. if (!$flag || !in_array($flag, (array) $this->data['PERMANENTFLAGS'])
  1751. || !in_array('\\*', (array) $this->data['PERMANENTFLAGS'])
  1752. ) {
  1753. return false;
  1754. }
  1755. // Clear internal status cache
  1756. if ($flag == 'SEEN') {
  1757. unset($this->data['STATUS:'.$mailbox]['UNSEEN']);
  1758. }
  1759. if ($mod != '+' && $mod != '-') {
  1760. $mod = '+';
  1761. }
  1762. $result = $this->execute('UID STORE', array(
  1763. $this->compressMessageSet($messages), $mod . 'FLAGS.SILENT', "($flag)"),
  1764. self::COMMAND_NORESPONSE);
  1765. return ($result == self::ERROR_OK);
  1766. }
  1767. /**
  1768. * Copies message(s) from one folder to another
  1769. *
  1770. * @param string|array $messages Message UID(s)
  1771. * @param string $from Mailbox name
  1772. * @param string $to Destination mailbox name
  1773. *
  1774. * @return bool True on success, False on failure
  1775. */
  1776. function copy($messages, $from, $to)
  1777. {
  1778. // Clear last COPYUID data
  1779. unset($this->data['COPYUID']);
  1780. if (!$this->select($from)) {
  1781. return false;
  1782. }
  1783. // Clear internal status cache
  1784. unset($this->data['STATUS:'.$to]);
  1785. $result = $this->execute('UID COPY', array(
  1786. $this->compressMessageSet($messages), $this->escape($to)),
  1787. self::COMMAND_NORESPONSE);
  1788. return ($result == self::ERROR_OK);
  1789. }
  1790. /**
  1791. * Moves message(s) from one folder to another.
  1792. *
  1793. * @param string|array $messages Message UID(s)
  1794. * @param string $from Mailbox name
  1795. * @param string $to Destination mailbox name
  1796. *
  1797. * @return bool True on success, False on failure
  1798. */
  1799. function move($messages, $from, $to)
  1800. {
  1801. if (!$this->select($from)) {
  1802. return false;
  1803. }
  1804. if (!$this->data['READ-WRITE']) {
  1805. $this->setError(self::ERROR_READONLY, "Mailbox is read-only");
  1806. return false;
  1807. }
  1808. // use MOVE command (RFC 6851)
  1809. if ($this->hasCapability('MOVE')) {
  1810. // Clear last COPYUID data
  1811. unset($this->data['COPYUID']);
  1812. // Clear internal status cache
  1813. unset($this->data['STATUS:'.$to]);
  1814. unset($this->data['STATUS:'.$from]);
  1815. $result = $this->execute('UID MOVE', array(
  1816. $this->compressMessageSet($messages), $this->escape($to)),
  1817. self::COMMAND_NORESPONSE);
  1818. return ($result == self::ERROR_OK);
  1819. }
  1820. // use COPY + STORE +FLAGS.SILENT \Deleted + EXPUNGE
  1821. $result = $this->copy($messages, $from, $to);
  1822. if ($result) {
  1823. // Clear internal status cache
  1824. unset($this->data['STATUS:'.$from]);
  1825. $result = $this->flag($from, $messages, 'DELETED');
  1826. if ($messages == '*') {
  1827. // CLOSE+SELECT should be faster than EXPUNGE
  1828. $this->close();
  1829. }
  1830. else {
  1831. $this->expunge($from, $messages);
  1832. }
  1833. }
  1834. return $result;
  1835. }
  1836. /**
  1837. * FETCH command (RFC3501)
  1838. *
  1839. * @param string $mailbox Mailbox name
  1840. * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
  1841. * @param bool $is_uid True if $message_set contains UIDs
  1842. * @param array $query_items FETCH command data items
  1843. * @param string $mod_seq Modification sequence for CHANGEDSINCE (RFC4551) query
  1844. * @param bool $vanished Enables VANISHED parameter (RFC5162) for CHANGEDSINCE query
  1845. *
  1846. * @return array List of rcube_message_header elements, False on error
  1847. * @since 0.6
  1848. */
  1849. function fetch($mailbox, $message_set, $is_uid = false, $query_items = array(),
  1850. $mod_seq = null, $vanished = false)
  1851. {
  1852. if (!$this->select($mailbox)) {
  1853. return false;
  1854. }
  1855. $message_set = $this->compressMessageSet($message_set);
  1856. $result = array();
  1857. $key = $this->nextTag();
  1858. $request = $key . ($is_uid ? ' UID' : '') . " FETCH $message_set ";
  1859. $request .= "(" . implode(' ', $query_items) . ")";
  1860. if ($mod_seq !== null && $this->hasCapability('CONDSTORE')) {
  1861. $request .= " (CHANGEDSINCE $mod_seq" . ($vanished ? " VANISHED" : '') .")";
  1862. }
  1863. if (!$this->putLine($request)) {
  1864. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  1865. return false;
  1866. }
  1867. do {
  1868. $line = $this->readLine(4096);
  1869. if (!$line)
  1870. break;
  1871. // Sample reply line:
  1872. // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
  1873. // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
  1874. // BODY[HEADER.FIELDS ...
  1875. if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
  1876. $id = intval($m[1]);
  1877. $result[$id] = new rcube_message_header;
  1878. $result[$id]->id = $id;
  1879. $result[$id]->subject = '';
  1880. $result[$id]->messageID = 'mid:' . $id;
  1881. $headers = null;
  1882. $lines = array();
  1883. $line = substr($line, strlen($m[0]) + 2);
  1884. $ln = 0;
  1885. // get complete entry
  1886. while (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
  1887. $bytes = $m[1];
  1888. $out = '';
  1889. while (strlen($out) < $bytes) {
  1890. $out = $this->readBytes($bytes);
  1891. if ($out === NULL)
  1892. break;
  1893. $line .= $out;
  1894. }
  1895. $str = $this->readLine(4096);
  1896. if ($str === false)
  1897. break;
  1898. $line .= $str;
  1899. }
  1900. // Tokenize response and assign to object properties
  1901. while (list($name, $value) = $this->tokenizeResponse($line, 2)) {
  1902. if ($name == 'UID') {
  1903. $result[$id]->uid = intval($value);
  1904. }
  1905. else if ($name == 'RFC822.SIZE') {
  1906. $result[$id]->size = intval($value);
  1907. }
  1908. else if ($name == 'RFC822.TEXT') {
  1909. $result[$id]->body = $value;
  1910. }
  1911. else if ($name == 'INTERNALDATE') {
  1912. $result[$id]->internaldate = $value;
  1913. $result[$id]->date = $value;
  1914. $result[$id]->timestamp = $this->StrToTime($value);
  1915. }
  1916. else if ($name == 'FLAGS') {
  1917. if (!empty($value)) {
  1918. foreach ((array)$value as $flag) {
  1919. $flag = str_replace(array('$', '\\'), '', $flag);
  1920. $flag = strtoupper($flag);
  1921. $result[$id]->flags[$flag] = true;
  1922. }
  1923. }
  1924. }
  1925. else if ($name == 'MODSEQ') {
  1926. $result[$id]->modseq = $value[0];
  1927. }
  1928. else if ($name == 'ENVELOPE') {
  1929. $result[$id]->envelope = $value;
  1930. }
  1931. else if ($name == 'BODYSTRUCTURE' || ($name == 'BODY' && count($value) > 2)) {
  1932. if (!is_array($value[0]) && (strtolower($value[0]) == 'message' && strtolower($value[1]) == 'rfc822')) {
  1933. $value = array($value);
  1934. }
  1935. $result[$id]->bodystructure = $value;
  1936. }
  1937. else if ($name == 'RFC822') {
  1938. $result[$id]->body = $value;
  1939. }
  1940. else if (stripos($name, 'BODY[') === 0) {
  1941. $name = str_replace(']', '', substr($name, 5));
  1942. if ($name == 'HEADER.FIELDS') {
  1943. // skip ']' after headers list
  1944. $this->tokenizeResponse($line, 1);
  1945. $headers = $this->tokenizeResponse($line, 1);
  1946. }
  1947. else if (strlen($name))
  1948. $result[$id]->bodypart[$name] = $value;
  1949. else
  1950. $result[$id]->body = $value;
  1951. }
  1952. }
  1953. // create array with header field:data
  1954. if (!empty($headers)) {
  1955. $headers = explode("\n", trim($headers));
  1956. foreach ($headers as $resln) {
  1957. if (ord($resln[0]) <= 32) {
  1958. $lines[$ln] .= (empty($lines[$ln]) ? '' : "\n") . trim($resln);
  1959. } else {
  1960. $lines[++$ln] = trim($resln);
  1961. }
  1962. }
  1963. foreach ($lines as $str) {
  1964. list($field, $string) = explode(':', $str, 2);
  1965. $field = strtolower($field);
  1966. $string = preg_replace('/\n[\t\s]*/', ' ', trim($string));
  1967. switch ($field) {
  1968. case 'date';
  1969. $result[$id]->date = $string;
  1970. $result[$id]->timestamp = $this->strToTime($string);
  1971. break;
  1972. case 'from':
  1973. $result[$id]->from = $string;
  1974. break;
  1975. case 'to':
  1976. $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
  1977. break;
  1978. case 'subject':
  1979. $result[$id]->subject = $string;
  1980. break;
  1981. case 'reply-to':
  1982. $result[$id]->replyto = $string;
  1983. break;
  1984. case 'cc':
  1985. $result[$id]->cc = $string;
  1986. break;
  1987. case 'bcc':
  1988. $result[$id]->bcc = $string;
  1989. break;
  1990. case 'content-transfer-encoding':
  1991. $result[$id]->encoding = $string;
  1992. break;
  1993. case 'content-type':
  1994. $ctype_parts = preg_split('/[; ]+/', $string);
  1995. $result[$id]->ctype = strtolower(array_shift($ctype_parts));
  1996. if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
  1997. $result[$id]->charset = $regs[1];
  1998. }
  1999. break;
  2000. case 'in-reply-to':
  2001. $result[$id]->in_reply_to = str_replace(array("\n", '<', '>'), '', $string);
  2002. break;
  2003. case 'references':
  2004. $result[$id]->references = $string;
  2005. break;
  2006. case 'return-receipt-to':
  2007. case 'disposition-notification-to':
  2008. case 'x-confirm-reading-to':
  2009. $result[$id]->mdn_to = $string;
  2010. break;
  2011. case 'message-id':
  2012. $result[$id]->messageID = $string;
  2013. break;
  2014. case 'x-priority':
  2015. if (preg_match('/^(\d+)/', $string, $matches)) {
  2016. $result[$id]->priority = intval($matches[1]);
  2017. }
  2018. break;
  2019. default:
  2020. if (strlen($field) < 3) {
  2021. break;
  2022. }
  2023. if ($result[$id]->others[$field]) {
  2024. $string = array_merge((array)$result[$id]->others[$field], (array)$string);
  2025. }
  2026. $result[$id]->others[$field] = $string;
  2027. }
  2028. }
  2029. }
  2030. }
  2031. // VANISHED response (QRESYNC RFC5162)
  2032. // Sample: * VANISHED (EARLIER) 300:310,405,411
  2033. else if (preg_match('/^\* VANISHED [()EARLIER]*/i', $line, $match)) {
  2034. $line = substr($line, strlen($match[0]));
  2035. $v_data = $this->tokenizeResponse($line, 1);
  2036. $this->data['VANISHED'] = $v_data;
  2037. }
  2038. } while (!$this->startsWith($line, $key, true));
  2039. return $result;
  2040. }
  2041. /**
  2042. * Returns message(s) data (flags, headers, etc.)
  2043. *
  2044. * @param string $mailbox Mailbox name
  2045. * @param mixed $message_set Message(s) sequence identifier(s) or UID(s)
  2046. * @param bool $is_uid True if $message_set contains UIDs
  2047. * @param bool $bodystr Enable to add BODYSTRUCTURE data to the result
  2048. * @param array $add_headers List of additional headers
  2049. *
  2050. * @return bool|array List of rcube_message_header elements, False on error
  2051. */
  2052. function fetchHeaders($mailbox, $message_set, $is_uid = false, $bodystr = false, $add_headers = array())
  2053. {
  2054. $query_items = array('UID', 'RFC822.SIZE', 'FLAGS', 'INTERNALDATE');
  2055. $headers = array('DATE', 'FROM', 'TO', 'SUBJECT', 'CONTENT-TYPE', 'CC', 'REPLY-TO',
  2056. 'LIST-POST', 'DISPOSITION-NOTIFICATION-TO', 'X-PRIORITY');
  2057. if (!empty($add_headers)) {
  2058. $add_headers = array_map('strtoupper', $add_headers);
  2059. $headers = array_unique(array_merge($headers, $add_headers));
  2060. }
  2061. if ($bodystr) {
  2062. $query_items[] = 'BODYSTRUCTURE';
  2063. }
  2064. $query_items[] = 'BODY.PEEK[HEADER.FIELDS (' . implode(' ', $headers) . ')]';
  2065. $result = $this->fetch($mailbox, $message_set, $is_uid, $query_items);
  2066. return $result;
  2067. }
  2068. /**
  2069. * Returns message data (flags, headers, etc.)
  2070. *
  2071. * @param string $mailbox Mailbox name
  2072. * @param int $id Message sequence identifier or UID
  2073. * @param bool $is_uid True if $id is an UID
  2074. * @param bool $bodystr Enable to add BODYSTRUCTURE data to the result
  2075. * @param array $add_headers List of additional headers
  2076. *
  2077. * @return bool|rcube_message_header Message data, False on error
  2078. */
  2079. function fetchHeader($mailbox, $id, $is_uid = false, $bodystr = false, $add_headers = array())
  2080. {
  2081. $a = $this->fetchHeaders($mailbox, $id, $is_uid, $bodystr, $add_headers);
  2082. if (is_array($a)) {
  2083. return array_shift($a);
  2084. }
  2085. return false;
  2086. }
  2087. function sortHeaders($a, $field, $flag)
  2088. {
  2089. if (empty($field)) {
  2090. $field = 'uid';
  2091. }
  2092. else {
  2093. $field = strtolower($field);
  2094. }
  2095. if ($field == 'date' || $field == 'internaldate') {
  2096. $field = 'timestamp';
  2097. }
  2098. if (empty($flag)) {
  2099. $flag = 'ASC';
  2100. } else {
  2101. $flag = strtoupper($flag);
  2102. }
  2103. $c = count($a);
  2104. if ($c > 0) {
  2105. // Strategy:
  2106. // First, we'll create an "index" array.
  2107. // Then, we'll use sort() on that array,
  2108. // and use that to sort the main array.
  2109. // create "index" array
  2110. $index = array();
  2111. reset($a);
  2112. while (list($key, $val) = each($a)) {
  2113. if ($field == 'timestamp') {
  2114. $data = $this->strToTime($val->date);
  2115. if (!$data) {
  2116. $data = $val->timestamp;
  2117. }
  2118. } else {
  2119. $data = $val->$field;
  2120. if (is_string($data)) {
  2121. $data = str_replace('"', '', $data);
  2122. if ($field == 'subject') {
  2123. $data = preg_replace('/^(Re: \s*|Fwd:\s*|Fw:\s*)+/i', '', $data);
  2124. }
  2125. $data = strtoupper($data);
  2126. }
  2127. }
  2128. $index[$key] = $data;
  2129. }
  2130. // sort index
  2131. if ($flag == 'ASC') {
  2132. asort($index);
  2133. } else {
  2134. arsort($index);
  2135. }
  2136. // form new array based on index
  2137. $result = array();
  2138. reset($index);
  2139. while (list($key, $val) = each($index)) {
  2140. $result[$key] = $a[$key];
  2141. }
  2142. }
  2143. return $result;
  2144. }
  2145. function fetchMIMEHeaders($mailbox, $uid, $parts, $mime=true)
  2146. {
  2147. if (!$this->select($mailbox)) {
  2148. return false;
  2149. }
  2150. $result = false;
  2151. $parts = (array) $parts;
  2152. $key = $this->nextTag();
  2153. $peeks = array();
  2154. $type = $mime ? 'MIME' : 'HEADER';
  2155. // format request
  2156. foreach ($parts as $part) {
  2157. $peeks[] = "BODY.PEEK[$part.$type]";
  2158. }
  2159. $request = "$key UID FETCH $uid (" . implode(' ', $peeks) . ')';
  2160. // send request
  2161. if (!$this->putLine($request)) {
  2162. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2163. return false;
  2164. }
  2165. do {
  2166. $line = $this->readLine(1024);
  2167. if (preg_match('/^\* [0-9]+ FETCH [0-9UID( ]+BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
  2168. $idx = $matches[1];
  2169. $headers = '';
  2170. // get complete entry
  2171. if (preg_match('/\{([0-9]+)\}\r\n$/', $line, $m)) {
  2172. $bytes = $m[1];
  2173. $out = '';
  2174. while (strlen($out) < $bytes) {
  2175. $out = $this->readBytes($bytes);
  2176. if ($out === null)
  2177. break;
  2178. $headers .= $out;
  2179. }
  2180. }
  2181. $result[$idx] = trim($headers);
  2182. }
  2183. } while (!$this->startsWith($line, $key, true));
  2184. return $result;
  2185. }
  2186. function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
  2187. {
  2188. $part = empty($part) ? 'HEADER' : $part.'.MIME';
  2189. return $this->handlePartBody($mailbox, $id, $is_uid, $part);
  2190. }
  2191. function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL, $formatted=false, $max_bytes=0)
  2192. {
  2193. if (!$this->select($mailbox)) {
  2194. return false;
  2195. }
  2196. switch ($encoding) {
  2197. case 'base64':
  2198. $mode = 1;
  2199. break;
  2200. case 'quoted-printable':
  2201. $mode = 2;
  2202. break;
  2203. case 'x-uuencode':
  2204. case 'x-uue':
  2205. case 'uue':
  2206. case 'uuencode':
  2207. $mode = 3;
  2208. break;
  2209. default:
  2210. $mode = 0;
  2211. }
  2212. // Use BINARY extension when possible (and safe)
  2213. $binary = $mode && preg_match('/^[0-9.]+$/', $part) && $this->hasCapability('BINARY');
  2214. $fetch_mode = $binary ? 'BINARY' : 'BODY';
  2215. $partial = $max_bytes ? sprintf('<0.%d>', $max_bytes) : '';
  2216. // format request
  2217. $key = $this->nextTag();
  2218. $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id ($fetch_mode.PEEK[$part]$partial)";
  2219. $result = false;
  2220. $found = false;
  2221. // send request
  2222. if (!$this->putLine($request)) {
  2223. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2224. return false;
  2225. }
  2226. if ($binary) {
  2227. // WARNING: Use $formatted argument with care, this may break binary data stream
  2228. $mode = -1;
  2229. }
  2230. do {
  2231. $line = trim($this->readLine(1024));
  2232. if (!$line) {
  2233. break;
  2234. }
  2235. // skip irrelevant untagged responses (we have a result already)
  2236. if ($found || !preg_match('/^\* ([0-9]+) FETCH (.*)$/', $line, $m)) {
  2237. continue;
  2238. }
  2239. $line = $m[2];
  2240. // handle one line response
  2241. if ($line[0] == '(' && substr($line, -1) == ')') {
  2242. // tokenize content inside brackets
  2243. // the content can be e.g.: (UID 9844 BODY[2.4] NIL)
  2244. $tokens = $this->tokenizeResponse(preg_replace('/(^\(|\)$)/', '', $line));
  2245. for ($i=0; $i<count($tokens); $i+=2) {
  2246. if (preg_match('/^(BODY|BINARY)/i', $tokens[$i])) {
  2247. $result = $tokens[$i+1];
  2248. $found = true;
  2249. break;
  2250. }
  2251. }
  2252. if ($result !== false) {
  2253. if ($mode == 1) {
  2254. $result = base64_decode($result);
  2255. }
  2256. else if ($mode == 2) {
  2257. $result = quoted_printable_decode($result);
  2258. }
  2259. else if ($mode == 3) {
  2260. $result = convert_uudecode($result);
  2261. }
  2262. }
  2263. }
  2264. // response with string literal
  2265. else if (preg_match('/\{([0-9]+)\}$/', $line, $m)) {
  2266. $bytes = (int) $m[1];
  2267. $prev = '';
  2268. $found = true;
  2269. // empty body
  2270. if (!$bytes) {
  2271. $result = '';
  2272. }
  2273. else while ($bytes > 0) {
  2274. $line = $this->readLine(8192);
  2275. if ($line === NULL) {
  2276. break;
  2277. }
  2278. $len = strlen($line);
  2279. if ($len > $bytes) {
  2280. $line = substr($line, 0, $bytes);
  2281. $len = strlen($line);
  2282. }
  2283. $bytes -= $len;
  2284. // BASE64
  2285. if ($mode == 1) {
  2286. $line = rtrim($line, "\t\r\n\0\x0B");
  2287. // create chunks with proper length for base64 decoding
  2288. $line = $prev.$line;
  2289. $length = strlen($line);
  2290. if ($length % 4) {
  2291. $length = floor($length / 4) * 4;
  2292. $prev = substr($line, $length);
  2293. $line = substr($line, 0, $length);
  2294. }
  2295. else {
  2296. $prev = '';
  2297. }
  2298. $line = base64_decode($line);
  2299. }
  2300. // QUOTED-PRINTABLE
  2301. else if ($mode == 2) {
  2302. $line = rtrim($line, "\t\r\0\x0B");
  2303. $line = quoted_printable_decode($line);
  2304. }
  2305. // UUENCODE
  2306. else if ($mode == 3) {
  2307. $line = rtrim($line, "\t\r\n\0\x0B");
  2308. if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line)) {
  2309. continue;
  2310. }
  2311. $line = convert_uudecode($line);
  2312. }
  2313. // default
  2314. else if ($formatted) {
  2315. $line = rtrim($line, "\t\r\n\0\x0B") . "\n";
  2316. }
  2317. if ($file) {
  2318. if (fwrite($file, $line) === false) {
  2319. break;
  2320. }
  2321. }
  2322. else if ($print) {
  2323. echo $line;
  2324. }
  2325. else {
  2326. $result .= $line;
  2327. }
  2328. }
  2329. }
  2330. } while (!$this->startsWith($line, $key, true));
  2331. if ($result !== false) {
  2332. if ($file) {
  2333. return fwrite($file, $result);
  2334. }
  2335. else if ($print) {
  2336. echo $result;
  2337. return true;
  2338. }
  2339. return $result;
  2340. }
  2341. return false;
  2342. }
  2343. /**
  2344. * Handler for IMAP APPEND command
  2345. *
  2346. * @param string $mailbox Mailbox name
  2347. * @param string|array $message The message source string or array (of strings and file pointers)
  2348. * @param array $flags Message flags
  2349. * @param string $date Message internal date
  2350. * @param bool $binary Enable BINARY append (RFC3516)
  2351. *
  2352. * @return string|bool On success APPENDUID response (if available) or True, False on failure
  2353. */
  2354. function append($mailbox, &$message, $flags = array(), $date = null, $binary = false)
  2355. {
  2356. unset($this->data['APPENDUID']);
  2357. if ($mailbox === null || $mailbox === '') {
  2358. return false;
  2359. }
  2360. $binary = $binary && $this->getCapability('BINARY');
  2361. $literal_plus = !$binary && $this->prefs['literal+'];
  2362. $len = 0;
  2363. $msg = is_array($message) ? $message : array(&$message);
  2364. $chunk_size = 512000;
  2365. for ($i=0, $cnt=count($msg); $i<$cnt; $i++) {
  2366. if (is_resource($msg[$i])) {
  2367. $stat = fstat($msg[$i]);
  2368. if ($stat === false) {
  2369. return false;
  2370. }
  2371. $len += $stat['size'];
  2372. }
  2373. else {
  2374. if (!$binary) {
  2375. $msg[$i] = str_replace("\r", '', $msg[$i]);
  2376. $msg[$i] = str_replace("\n", "\r\n", $msg[$i]);
  2377. }
  2378. $len += strlen($msg[$i]);
  2379. }
  2380. }
  2381. if (!$len) {
  2382. return false;
  2383. }
  2384. // build APPEND command
  2385. $key = $this->nextTag();
  2386. $request = "$key APPEND " . $this->escape($mailbox) . ' (' . $this->flagsToStr($flags) . ')';
  2387. if (!empty($date)) {
  2388. $request .= ' ' . $this->escape($date);
  2389. }
  2390. $request .= ' ' . ($binary ? '~' : '') . '{' . $len . ($literal_plus ? '+' : '') . '}';
  2391. // send APPEND command
  2392. if ($this->putLine($request)) {
  2393. // Do not wait when LITERAL+ is supported
  2394. if (!$literal_plus) {
  2395. $line = $this->readReply();
  2396. if ($line[0] != '+') {
  2397. $this->parseResult($line, 'APPEND: ');
  2398. return false;
  2399. }
  2400. }
  2401. foreach ($msg as $msg_part) {
  2402. // file pointer
  2403. if (is_resource($msg_part)) {
  2404. rewind($msg_part);
  2405. while (!feof($msg_part) && $this->fp) {
  2406. $buffer = fread($msg_part, $chunk_size);
  2407. $this->putLine($buffer, false);
  2408. }
  2409. fclose($msg_part);
  2410. }
  2411. // string
  2412. else {
  2413. $size = strlen($msg_part);
  2414. // Break up the data by sending one chunk (up to 512k) at a time.
  2415. // This approach reduces our peak memory usage
  2416. for ($offset = 0; $offset < $size; $offset += $chunk_size) {
  2417. $chunk = substr($msg_part, $offset, $chunk_size);
  2418. if (!$this->putLine($chunk, false)) {
  2419. return false;
  2420. }
  2421. }
  2422. }
  2423. }
  2424. if (!$this->putLine('')) { // \r\n
  2425. return false;
  2426. }
  2427. do {
  2428. $line = $this->readLine();
  2429. } while (!$this->startsWith($line, $key, true, true));
  2430. // Clear internal status cache
  2431. unset($this->data['STATUS:'.$mailbox]);
  2432. if ($this->parseResult($line, 'APPEND: ') != self::ERROR_OK)
  2433. return false;
  2434. else if (!empty($this->data['APPENDUID']))
  2435. return $this->data['APPENDUID'];
  2436. else
  2437. return true;
  2438. }
  2439. else {
  2440. $this->setError(self::ERROR_COMMAND, "Unable to send command: $request");
  2441. }
  2442. return false;
  2443. }
  2444. /**
  2445. * Handler for IMAP APPEND command.
  2446. *
  2447. * @param string $mailbox Mailbox name
  2448. * @param string $path Path to the file with message body
  2449. * @param string $headers Message headers
  2450. * @param array $flags Message flags
  2451. * @param string $date Message internal date
  2452. * @param bool $binary Enable BINARY append (RFC3516)
  2453. *
  2454. * @return string|bool On success APPENDUID response (if available) or True, False on failure
  2455. */
  2456. function appendFromFile($mailbox, $path, $headers=null, $flags = array(), $date = null, $binary = false)
  2457. {
  2458. // open message file
  2459. if (file_exists(realpath($path))) {
  2460. $fp = fopen($path, 'r');
  2461. }
  2462. if (!$fp) {
  2463. $this->setError(self::ERROR_UNKNOWN, "Couldn't open $path for reading");
  2464. return false;
  2465. }
  2466. $message = array();
  2467. if ($headers) {
  2468. $message[] = trim($headers, "\r\n") . "\r\n\r\n";
  2469. }
  2470. $message[] = $fp;
  2471. return $this->append($mailbox, $message, $flags, $date, $binary);
  2472. }
  2473. /**
  2474. * Returns QUOTA information
  2475. *
  2476. * @param string $mailbox Mailbox name
  2477. *
  2478. * @return array Quota information
  2479. */
  2480. function getQuota($mailbox = null)
  2481. {
  2482. if ($mailbox === null || $mailbox === '') {
  2483. $mailbox = 'INBOX';
  2484. }
  2485. // a0001 GETQUOTAROOT INBOX
  2486. // * QUOTAROOT INBOX user/sample
  2487. // * QUOTA user/sample (STORAGE 654 9765)
  2488. // a0001 OK Completed
  2489. list($code, $response) = $this->execute('GETQUOTAROOT', array($this->escape($mailbox)));
  2490. $result = false;
  2491. $min_free = PHP_INT_MAX;
  2492. $all = array();
  2493. if ($code == self::ERROR_OK) {
  2494. foreach (explode("\n", $response) as $line) {
  2495. if (preg_match('/^\* QUOTA /', $line)) {
  2496. list(, , $quota_root) = $this->tokenizeResponse($line, 3);
  2497. while ($line) {
  2498. list($type, $used, $total) = $this->tokenizeResponse($line, 1);
  2499. $type = strtolower($type);
  2500. if ($type && $total) {
  2501. $all[$quota_root][$type]['used'] = intval($used);
  2502. $all[$quota_root][$type]['total'] = intval($total);
  2503. }
  2504. }
  2505. if (empty($all[$quota_root]['storage'])) {
  2506. continue;
  2507. }
  2508. $used = $all[$quota_root]['storage']['used'];
  2509. $total = $all[$quota_root]['storage']['total'];
  2510. $free = $total - $used;
  2511. // calculate lowest available space from all storage quotas
  2512. if ($free < $min_free) {
  2513. $min_free = $free;
  2514. $result['used'] = $used;
  2515. $result['total'] = $total;
  2516. $result['percent'] = min(100, round(($used/max(1,$total))*100));
  2517. $result['free'] = 100 - $result['percent'];
  2518. }
  2519. }
  2520. }
  2521. }
  2522. if (!empty($result)) {
  2523. $result['all'] = $all;
  2524. }
  2525. return $result;
  2526. }
  2527. /**
  2528. * Send the SETACL command (RFC4314)
  2529. *
  2530. * @param string $mailbox Mailbox name
  2531. * @param string $user User name
  2532. * @param mixed $acl ACL string or array
  2533. *
  2534. * @return boolean True on success, False on failure
  2535. *
  2536. * @since 0.5-beta
  2537. */
  2538. function setACL($mailbox, $user, $acl)
  2539. {
  2540. if (is_array($acl)) {
  2541. $acl = implode('', $acl);
  2542. }
  2543. $result = $this->execute('SETACL', array(
  2544. $this->escape($mailbox), $this->escape($user), strtolower($acl)),
  2545. self::COMMAND_NORESPONSE);
  2546. return ($result == self::ERROR_OK);
  2547. }
  2548. /**
  2549. * Send the DELETEACL command (RFC4314)
  2550. *
  2551. * @param string $mailbox Mailbox name
  2552. * @param string $user User name
  2553. *
  2554. * @return boolean True on success, False on failure
  2555. *
  2556. * @since 0.5-beta
  2557. */
  2558. function deleteACL($mailbox, $user)
  2559. {
  2560. $result = $this->execute('DELETEACL', array(
  2561. $this->escape($mailbox), $this->escape($user)),
  2562. self::COMMAND_NORESPONSE);
  2563. return ($result == self::ERROR_OK);
  2564. }
  2565. /**
  2566. * Send the GETACL command (RFC4314)
  2567. *
  2568. * @param string $mailbox Mailbox name
  2569. *
  2570. * @return array User-rights array on success, NULL on error
  2571. * @since 0.5-beta
  2572. */
  2573. function getACL($mailbox)
  2574. {
  2575. list($code, $response) = $this->execute('GETACL', array($this->escape($mailbox)));
  2576. if ($code == self::ERROR_OK && preg_match('/^\* ACL /i', $response)) {
  2577. // Parse server response (remove "* ACL ")
  2578. $response = substr($response, 6);
  2579. $ret = $this->tokenizeResponse($response);
  2580. $mbox = array_shift($ret);
  2581. $size = count($ret);
  2582. // Create user-rights hash array
  2583. // @TODO: consider implementing fixACL() method according to RFC4314.2.1.1
  2584. // so we could return only standard rights defined in RFC4314,
  2585. // excluding 'c' and 'd' defined in RFC2086.
  2586. if ($size % 2 == 0) {
  2587. for ($i=0; $i<$size; $i++) {
  2588. $ret[$ret[$i]] = str_split($ret[++$i]);
  2589. unset($ret[$i-1]);
  2590. unset($ret[$i]);
  2591. }
  2592. return $ret;
  2593. }
  2594. $this->setError(self::ERROR_COMMAND, "Incomplete ACL response");
  2595. return NULL;
  2596. }
  2597. return NULL;
  2598. }
  2599. /**
  2600. * Send the LISTRIGHTS command (RFC4314)
  2601. *
  2602. * @param string $mailbox Mailbox name
  2603. * @param string $user User name
  2604. *
  2605. * @return array List of user rights
  2606. * @since 0.5-beta
  2607. */
  2608. function listRights($mailbox, $user)
  2609. {
  2610. list($code, $response) = $this->execute('LISTRIGHTS', array(
  2611. $this->escape($mailbox), $this->escape($user)));
  2612. if ($code == self::ERROR_OK && preg_match('/^\* LISTRIGHTS /i', $response)) {
  2613. // Parse server response (remove "* LISTRIGHTS ")
  2614. $response = substr($response, 13);
  2615. $ret_mbox = $this->tokenizeResponse($response, 1);
  2616. $ret_user = $this->tokenizeResponse($response, 1);
  2617. $granted = $this->tokenizeResponse($response, 1);
  2618. $optional = trim($response);
  2619. return array(
  2620. 'granted' => str_split($granted),
  2621. 'optional' => explode(' ', $optional),
  2622. );
  2623. }
  2624. return NULL;
  2625. }
  2626. /**
  2627. * Send the MYRIGHTS command (RFC4314)
  2628. *
  2629. * @param string $mailbox Mailbox name
  2630. *
  2631. * @return array MYRIGHTS response on success, NULL on error
  2632. * @since 0.5-beta
  2633. */
  2634. function myRights($mailbox)
  2635. {
  2636. list($code, $response) = $this->execute('MYRIGHTS', array($this->escape($mailbox)));
  2637. if ($code == self::ERROR_OK && preg_match('/^\* MYRIGHTS /i', $response)) {
  2638. // Parse server response (remove "* MYRIGHTS ")
  2639. $response = substr($response, 11);
  2640. $ret_mbox = $this->tokenizeResponse($response, 1);
  2641. $rights = $this->tokenizeResponse($response, 1);
  2642. return str_split($rights);
  2643. }
  2644. return NULL;
  2645. }
  2646. /**
  2647. * Send the SETMETADATA command (RFC5464)
  2648. *
  2649. * @param string $mailbox Mailbox name
  2650. * @param array $entries Entry-value array (use NULL value as NIL)
  2651. *
  2652. * @return boolean True on success, False on failure
  2653. * @since 0.5-beta
  2654. */
  2655. function setMetadata($mailbox, $entries)
  2656. {
  2657. if (!is_array($entries) || empty($entries)) {
  2658. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
  2659. return false;
  2660. }
  2661. foreach ($entries as $name => $value) {
  2662. $entries[$name] = $this->escape($name) . ' ' . $this->escape($value, true);
  2663. }
  2664. $entries = implode(' ', $entries);
  2665. $result = $this->execute('SETMETADATA', array(
  2666. $this->escape($mailbox), '(' . $entries . ')'),
  2667. self::COMMAND_NORESPONSE);
  2668. return ($result == self::ERROR_OK);
  2669. }
  2670. /**
  2671. * Send the SETMETADATA command with NIL values (RFC5464)
  2672. *
  2673. * @param string $mailbox Mailbox name
  2674. * @param array $entries Entry names array
  2675. *
  2676. * @return boolean True on success, False on failure
  2677. *
  2678. * @since 0.5-beta
  2679. */
  2680. function deleteMetadata($mailbox, $entries)
  2681. {
  2682. if (!is_array($entries) && !empty($entries)) {
  2683. $entries = explode(' ', $entries);
  2684. }
  2685. if (empty($entries)) {
  2686. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETMETADATA command");
  2687. return false;
  2688. }
  2689. foreach ($entries as $entry) {
  2690. $data[$entry] = NULL;
  2691. }
  2692. return $this->setMetadata($mailbox, $data);
  2693. }
  2694. /**
  2695. * Send the GETMETADATA command (RFC5464)
  2696. *
  2697. * @param string $mailbox Mailbox name
  2698. * @param array $entries Entries
  2699. * @param array $options Command options (with MAXSIZE and DEPTH keys)
  2700. *
  2701. * @return array GETMETADATA result on success, NULL on error
  2702. *
  2703. * @since 0.5-beta
  2704. */
  2705. function getMetadata($mailbox, $entries, $options=array())
  2706. {
  2707. if (!is_array($entries)) {
  2708. $entries = array($entries);
  2709. }
  2710. // create entries string
  2711. foreach ($entries as $idx => $name) {
  2712. $entries[$idx] = $this->escape($name);
  2713. }
  2714. $optlist = '';
  2715. $entlist = '(' . implode(' ', $entries) . ')';
  2716. // create options string
  2717. if (is_array($options)) {
  2718. $options = array_change_key_case($options, CASE_UPPER);
  2719. $opts = array();
  2720. if (!empty($options['MAXSIZE'])) {
  2721. $opts[] = 'MAXSIZE '.intval($options['MAXSIZE']);
  2722. }
  2723. if (!empty($options['DEPTH'])) {
  2724. $opts[] = 'DEPTH '.intval($options['DEPTH']);
  2725. }
  2726. if ($opts) {
  2727. $optlist = '(' . implode(' ', $opts) . ')';
  2728. }
  2729. }
  2730. $optlist .= ($optlist ? ' ' : '') . $entlist;
  2731. list($code, $response) = $this->execute('GETMETADATA', array(
  2732. $this->escape($mailbox), $optlist));
  2733. if ($code == self::ERROR_OK) {
  2734. $result = array();
  2735. $data = $this->tokenizeResponse($response);
  2736. // The METADATA response can contain multiple entries in a single
  2737. // response or multiple responses for each entry or group of entries
  2738. if (!empty($data) && ($size = count($data))) {
  2739. for ($i=0; $i<$size; $i++) {
  2740. if (isset($mbox) && is_array($data[$i])) {
  2741. $size_sub = count($data[$i]);
  2742. for ($x=0; $x<$size_sub; $x++) {
  2743. if ($data[$i][$x+1] !== null)
  2744. $result[$mbox][$data[$i][$x]] = $data[$i][++$x];
  2745. }
  2746. unset($data[$i]);
  2747. }
  2748. else if ($data[$i] == '*') {
  2749. if ($data[$i+1] == 'METADATA') {
  2750. $mbox = $data[$i+2];
  2751. unset($data[$i]); // "*"
  2752. unset($data[++$i]); // "METADATA"
  2753. unset($data[++$i]); // Mailbox
  2754. }
  2755. // get rid of other untagged responses
  2756. else {
  2757. unset($mbox);
  2758. unset($data[$i]);
  2759. }
  2760. }
  2761. else if (isset($mbox)) {
  2762. if ($data[$i+1] !== null)
  2763. $result[$mbox][$data[$i]] = $data[++$i];
  2764. unset($data[$i]);
  2765. unset($data[$i-1]);
  2766. }
  2767. else {
  2768. unset($data[$i]);
  2769. }
  2770. }
  2771. }
  2772. return $result;
  2773. }
  2774. return NULL;
  2775. }
  2776. /**
  2777. * Send the SETANNOTATION command (draft-daboo-imap-annotatemore)
  2778. *
  2779. * @param string $mailbox Mailbox name
  2780. * @param array $data Data array where each item is an array with
  2781. * three elements: entry name, attribute name, value
  2782. *
  2783. * @return boolean True on success, False on failure
  2784. * @since 0.5-beta
  2785. */
  2786. function setAnnotation($mailbox, $data)
  2787. {
  2788. if (!is_array($data) || empty($data)) {
  2789. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
  2790. return false;
  2791. }
  2792. foreach ($data as $entry) {
  2793. // Workaround cyrus-murder bug, the entry[2] string needs to be escaped
  2794. if (self::$mupdate) {
  2795. $entry[2] = addcslashes($entry[2], '\\"');
  2796. }
  2797. // ANNOTATEMORE drafts before version 08 require quoted parameters
  2798. $entries[] = sprintf('%s (%s %s)', $this->escape($entry[0], true),
  2799. $this->escape($entry[1], true), $this->escape($entry[2], true));
  2800. }
  2801. $entries = implode(' ', $entries);
  2802. $result = $this->execute('SETANNOTATION', array(
  2803. $this->escape($mailbox), $entries), self::COMMAND_NORESPONSE);
  2804. return ($result == self::ERROR_OK);
  2805. }
  2806. /**
  2807. * Send the SETANNOTATION command with NIL values (draft-daboo-imap-annotatemore)
  2808. *
  2809. * @param string $mailbox Mailbox name
  2810. * @param array $data Data array where each item is an array with
  2811. * two elements: entry name and attribute name
  2812. *
  2813. * @return boolean True on success, False on failure
  2814. *
  2815. * @since 0.5-beta
  2816. */
  2817. function deleteAnnotation($mailbox, $data)
  2818. {
  2819. if (!is_array($data) || empty($data)) {
  2820. $this->setError(self::ERROR_COMMAND, "Wrong argument for SETANNOTATION command");
  2821. return false;
  2822. }
  2823. return $this->setAnnotation($mailbox, $data);
  2824. }
  2825. /**
  2826. * Send the GETANNOTATION command (draft-daboo-imap-annotatemore)
  2827. *
  2828. * @param string $mailbox Mailbox name
  2829. * @param array $entries Entries names
  2830. * @param array $attribs Attribs names
  2831. *
  2832. * @return array Annotations result on success, NULL on error
  2833. *
  2834. * @since 0.5-beta
  2835. */
  2836. function getAnnotation($mailbox, $entries, $attribs)
  2837. {
  2838. if (!is_array($entries)) {
  2839. $entries = array($entries);
  2840. }
  2841. // create entries string
  2842. // ANNOTATEMORE drafts before version 08 require quoted parameters
  2843. foreach ($entries as $idx => $name) {
  2844. $entries[$idx] = $this->escape($name, true);
  2845. }
  2846. $entries = '(' . implode(' ', $entries) . ')';
  2847. if (!is_array($attribs)) {
  2848. $attribs = array($attribs);
  2849. }
  2850. // create entries string
  2851. foreach ($attribs as $idx => $name) {
  2852. $attribs[$idx] = $this->escape($name, true);
  2853. }
  2854. $attribs = '(' . implode(' ', $attribs) . ')';
  2855. list($code, $response) = $this->execute('GETANNOTATION', array(
  2856. $this->escape($mailbox), $entries, $attribs));
  2857. if ($code == self::ERROR_OK) {
  2858. $result = array();
  2859. $data = $this->tokenizeResponse($response);
  2860. // Here we returns only data compatible with METADATA result format
  2861. if (!empty($data) && ($size = count($data))) {
  2862. for ($i=0; $i<$size; $i++) {
  2863. $entry = $data[$i];
  2864. if (isset($mbox) && is_array($entry)) {
  2865. $attribs = $entry;
  2866. $entry = $last_entry;
  2867. }
  2868. else if ($entry == '*') {
  2869. if ($data[$i+1] == 'ANNOTATION') {
  2870. $mbox = $data[$i+2];
  2871. unset($data[$i]); // "*"
  2872. unset($data[++$i]); // "ANNOTATION"
  2873. unset($data[++$i]); // Mailbox
  2874. }
  2875. // get rid of other untagged responses
  2876. else {
  2877. unset($mbox);
  2878. unset($data[$i]);
  2879. }
  2880. continue;
  2881. }
  2882. else if (isset($mbox)) {
  2883. $attribs = $data[++$i];
  2884. }
  2885. else {
  2886. unset($data[$i]);
  2887. continue;
  2888. }
  2889. if (!empty($attribs)) {
  2890. for ($x=0, $len=count($attribs); $x<$len;) {
  2891. $attr = $attribs[$x++];
  2892. $value = $attribs[$x++];
  2893. if ($attr == 'value.priv' && $value !== null) {
  2894. $result[$mbox]['/private' . $entry] = $value;
  2895. }
  2896. else if ($attr == 'value.shared' && $value !== null) {
  2897. $result[$mbox]['/shared' . $entry] = $value;
  2898. }
  2899. }
  2900. }
  2901. $last_entry = $entry;
  2902. unset($data[$i]);
  2903. }
  2904. }
  2905. return $result;
  2906. }
  2907. return NULL;
  2908. }
  2909. /**
  2910. * Returns BODYSTRUCTURE for the specified message.
  2911. *
  2912. * @param string $mailbox Folder name
  2913. * @param int $id Message sequence number or UID
  2914. * @param bool $is_uid True if $id is an UID
  2915. *
  2916. * @return array/bool Body structure array or False on error.
  2917. * @since 0.6
  2918. */
  2919. function getStructure($mailbox, $id, $is_uid = false)
  2920. {
  2921. $result = $this->fetch($mailbox, $id, $is_uid, array('BODYSTRUCTURE'));
  2922. if (is_array($result)) {
  2923. $result = array_shift($result);
  2924. return $result->bodystructure;
  2925. }
  2926. return false;
  2927. }
  2928. /**
  2929. * Returns data of a message part according to specified structure.
  2930. *
  2931. * @param array $structure Message structure (getStructure() result)
  2932. * @param string $part Message part identifier
  2933. *
  2934. * @return array Part data as hash array (type, encoding, charset, size)
  2935. */
  2936. static function getStructurePartData($structure, $part)
  2937. {
  2938. $part_a = self::getStructurePartArray($structure, $part);
  2939. $data = array();
  2940. if (empty($part_a)) {
  2941. return $data;
  2942. }
  2943. // content-type
  2944. if (is_array($part_a[0])) {
  2945. $data['type'] = 'multipart';
  2946. }
  2947. else {
  2948. $data['type'] = strtolower($part_a[0]);
  2949. // encoding
  2950. $data['encoding'] = strtolower($part_a[5]);
  2951. // charset
  2952. if (is_array($part_a[2])) {
  2953. while (list($key, $val) = each($part_a[2])) {
  2954. if (strcasecmp($val, 'charset') == 0) {
  2955. $data['charset'] = $part_a[2][$key+1];
  2956. break;
  2957. }
  2958. }
  2959. }
  2960. }
  2961. // size
  2962. $data['size'] = intval($part_a[6]);
  2963. return $data;
  2964. }
  2965. static function getStructurePartArray($a, $part)
  2966. {
  2967. if (!is_array($a)) {
  2968. return false;
  2969. }
  2970. if (empty($part)) {
  2971. return $a;
  2972. }
  2973. $ctype = is_string($a[0]) && is_string($a[1]) ? $a[0] . '/' . $a[1] : '';
  2974. if (strcasecmp($ctype, 'message/rfc822') == 0) {
  2975. $a = $a[8];
  2976. }
  2977. if (strpos($part, '.') > 0) {
  2978. $orig_part = $part;
  2979. $pos = strpos($part, '.');
  2980. $rest = substr($orig_part, $pos+1);
  2981. $part = substr($orig_part, 0, $pos);
  2982. return self::getStructurePartArray($a[$part-1], $rest);
  2983. }
  2984. else if ($part > 0) {
  2985. return (is_array($a[$part-1])) ? $a[$part-1] : $a;
  2986. }
  2987. }
  2988. /**
  2989. * Creates next command identifier (tag)
  2990. *
  2991. * @return string Command identifier
  2992. * @since 0.5-beta
  2993. */
  2994. function nextTag()
  2995. {
  2996. $this->cmd_num++;
  2997. $this->cmd_tag = sprintf('A%04d', $this->cmd_num);
  2998. return $this->cmd_tag;
  2999. }
  3000. /**
  3001. * Sends IMAP command and parses result
  3002. *
  3003. * @param string $command IMAP command
  3004. * @param array $arguments Command arguments
  3005. * @param int $options Execution options
  3006. *
  3007. * @return mixed Response code or list of response code and data
  3008. * @since 0.5-beta
  3009. */
  3010. function execute($command, $arguments=array(), $options=0)
  3011. {
  3012. $tag = $this->nextTag();
  3013. $query = $tag . ' ' . $command;
  3014. $noresp = ($options & self::COMMAND_NORESPONSE);
  3015. $response = $noresp ? null : '';
  3016. if (!empty($arguments)) {
  3017. foreach ($arguments as $arg) {
  3018. $query .= ' ' . self::r_implode($arg);
  3019. }
  3020. }
  3021. // Send command
  3022. if (!$this->putLineC($query, true, ($options & self::COMMAND_ANONYMIZED))) {
  3023. $this->setError(self::ERROR_COMMAND, "Unable to send command: $query");
  3024. return $noresp ? self::ERROR_COMMAND : array(self::ERROR_COMMAND, '');
  3025. }
  3026. // Parse response
  3027. do {
  3028. $line = $this->readLine(4096);
  3029. if ($response !== null) {
  3030. $response .= $line;
  3031. }
  3032. } while (!$this->startsWith($line, $tag . ' ', true, true));
  3033. $code = $this->parseResult($line, $command . ': ');
  3034. // Remove last line from response
  3035. if ($response) {
  3036. $line_len = min(strlen($response), strlen($line) + 2);
  3037. $response = substr($response, 0, -$line_len);
  3038. }
  3039. // optional CAPABILITY response
  3040. if (($options & self::COMMAND_CAPABILITY) && $code == self::ERROR_OK
  3041. && preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)
  3042. ) {
  3043. $this->parseCapability($matches[1], true);
  3044. }
  3045. // return last line only (without command tag, result and response code)
  3046. if ($line && ($options & self::COMMAND_LASTLINE)) {
  3047. $response = preg_replace("/^$tag (OK|NO|BAD|BYE|PREAUTH)?\s*(\[[a-z-]+\])?\s*/i", '', trim($line));
  3048. }
  3049. return $noresp ? $code : array($code, $response);
  3050. }
  3051. /**
  3052. * Splits IMAP response into string tokens
  3053. *
  3054. * @param string &$str The IMAP's server response
  3055. * @param int $num Number of tokens to return
  3056. *
  3057. * @return mixed Tokens array or string if $num=1
  3058. * @since 0.5-beta
  3059. */
  3060. static function tokenizeResponse(&$str, $num=0)
  3061. {
  3062. $result = array();
  3063. while (!$num || count($result) < $num) {
  3064. // remove spaces from the beginning of the string
  3065. $str = ltrim($str);
  3066. switch ($str[0]) {
  3067. // String literal
  3068. case '{':
  3069. if (($epos = strpos($str, "}\r\n", 1)) == false) {
  3070. // error
  3071. }
  3072. if (!is_numeric(($bytes = substr($str, 1, $epos - 1)))) {
  3073. // error
  3074. }
  3075. $result[] = $bytes ? substr($str, $epos + 3, $bytes) : '';
  3076. // Advance the string
  3077. $str = substr($str, $epos + 3 + $bytes);
  3078. break;
  3079. // Quoted string
  3080. case '"':
  3081. $len = strlen($str);
  3082. for ($pos=1; $pos<$len; $pos++) {
  3083. if ($str[$pos] == '"') {
  3084. break;
  3085. }
  3086. if ($str[$pos] == "\\") {
  3087. if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
  3088. $pos++;
  3089. }
  3090. }
  3091. }
  3092. if ($str[$pos] != '"') {
  3093. // error
  3094. }
  3095. // we need to strip slashes for a quoted string
  3096. $result[] = stripslashes(substr($str, 1, $pos - 1));
  3097. $str = substr($str, $pos + 1);
  3098. break;
  3099. // Parenthesized list
  3100. case '(':
  3101. $str = substr($str, 1);
  3102. $result[] = self::tokenizeResponse($str);
  3103. break;
  3104. case ')':
  3105. $str = substr($str, 1);
  3106. return $result;
  3107. break;
  3108. // String atom, number, astring, NIL, *, %
  3109. default:
  3110. // empty string
  3111. if ($str === '' || $str === null) {
  3112. break 2;
  3113. }
  3114. // excluded chars: SP, CTL, ), DEL
  3115. // we do not exclude [ and ] (#1489223)
  3116. if (preg_match('/^([^\x00-\x20\x29\x7F]+)/', $str, $m)) {
  3117. $result[] = $m[1] == 'NIL' ? NULL : $m[1];
  3118. $str = substr($str, strlen($m[1]));
  3119. }
  3120. break;
  3121. }
  3122. }
  3123. return $num == 1 ? $result[0] : $result;
  3124. }
  3125. static function r_implode($element)
  3126. {
  3127. $string = '';
  3128. if (is_array($element)) {
  3129. reset($element);
  3130. foreach ($element as $value) {
  3131. $string .= ' ' . self::r_implode($value);
  3132. }
  3133. }
  3134. else {
  3135. return $element;
  3136. }
  3137. return '(' . trim($string) . ')';
  3138. }
  3139. /**
  3140. * Converts message identifiers array into sequence-set syntax
  3141. *
  3142. * @param array $messages Message identifiers
  3143. * @param bool $force Forces compression of any size
  3144. *
  3145. * @return string Compressed sequence-set
  3146. */
  3147. static function compressMessageSet($messages, $force=false)
  3148. {
  3149. // given a comma delimited list of independent mid's,
  3150. // compresses by grouping sequences together
  3151. if (!is_array($messages)) {
  3152. // if less than 255 bytes long, let's not bother
  3153. if (!$force && strlen($messages)<255) {
  3154. return $messages;
  3155. }
  3156. // see if it's already been compressed
  3157. if (strpos($messages, ':') !== false) {
  3158. return $messages;
  3159. }
  3160. // separate, then sort
  3161. $messages = explode(',', $messages);
  3162. }
  3163. sort($messages);
  3164. $result = array();
  3165. $start = $prev = $messages[0];
  3166. foreach ($messages as $id) {
  3167. $incr = $id - $prev;
  3168. if ($incr > 1) { // found a gap
  3169. if ($start == $prev) {
  3170. $result[] = $prev; // push single id
  3171. } else {
  3172. $result[] = $start . ':' . $prev; // push sequence as start_id:end_id
  3173. }
  3174. $start = $id; // start of new sequence
  3175. }
  3176. $prev = $id;
  3177. }
  3178. // handle the last sequence/id
  3179. if ($start == $prev) {
  3180. $result[] = $prev;
  3181. } else {
  3182. $result[] = $start.':'.$prev;
  3183. }
  3184. // return as comma separated string
  3185. return implode(',', $result);
  3186. }
  3187. /**
  3188. * Converts message sequence-set into array
  3189. *
  3190. * @param string $messages Message identifiers
  3191. *
  3192. * @return array List of message identifiers
  3193. */
  3194. static function uncompressMessageSet($messages)
  3195. {
  3196. if (empty($messages)) {
  3197. return array();
  3198. }
  3199. $result = array();
  3200. $messages = explode(',', $messages);
  3201. foreach ($messages as $idx => $part) {
  3202. $items = explode(':', $part);
  3203. $max = max($items[0], $items[1]);
  3204. for ($x=$items[0]; $x<=$max; $x++) {
  3205. $result[] = (int)$x;
  3206. }
  3207. unset($messages[$idx]);
  3208. }
  3209. return $result;
  3210. }
  3211. protected function _xor($string, $string2)
  3212. {
  3213. $result = '';
  3214. $size = strlen($string);
  3215. for ($i=0; $i<$size; $i++) {
  3216. $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
  3217. }
  3218. return $result;
  3219. }
  3220. /**
  3221. * Converts flags array into string for inclusion in IMAP command
  3222. *
  3223. * @param array $flags Flags (see self::flags)
  3224. *
  3225. * @return string Space-separated list of flags
  3226. */
  3227. protected function flagsToStr($flags)
  3228. {
  3229. foreach ((array)$flags as $idx => $flag) {
  3230. if ($flag = $this->flags[strtoupper($flag)]) {
  3231. $flags[$idx] = $flag;
  3232. }
  3233. }
  3234. return implode(' ', (array)$flags);
  3235. }
  3236. /**
  3237. * Converts datetime string into unix timestamp
  3238. *
  3239. * @param string $date Date string
  3240. *
  3241. * @return int Unix timestamp
  3242. */
  3243. static function strToTime($date)
  3244. {
  3245. // Clean malformed data
  3246. $date = preg_replace(
  3247. array(
  3248. '/GMT\s*([+-][0-9]+)/', // support non-standard "GMTXXXX" literal
  3249. '/[^a-z0-9\x20\x09:+-]/i', // remove any invalid characters
  3250. '/\s*(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*/i', // remove weekday names
  3251. ),
  3252. array(
  3253. '\\1',
  3254. '',
  3255. '',
  3256. ), $date);
  3257. $date = trim($date);
  3258. // if date parsing fails, we have a date in non-rfc format
  3259. // remove token from the end and try again
  3260. while (($ts = intval(@strtotime($date))) <= 0) {
  3261. $d = explode(' ', $date);
  3262. array_pop($d);
  3263. if (empty($d)) {
  3264. break;
  3265. }
  3266. $date = implode(' ', $d);
  3267. }
  3268. return $ts < 0 ? 0 : $ts;
  3269. }
  3270. /**
  3271. * CAPABILITY response parser
  3272. */
  3273. protected function parseCapability($str, $trusted=false)
  3274. {
  3275. $str = preg_replace('/^\* CAPABILITY /i', '', $str);
  3276. $this->capability = explode(' ', strtoupper($str));
  3277. if (!empty($this->prefs['disabled_caps'])) {
  3278. $this->capability = array_diff($this->capability, $this->prefs['disabled_caps']);
  3279. }
  3280. if (!isset($this->prefs['literal+']) && in_array('LITERAL+', $this->capability)) {
  3281. $this->prefs['literal+'] = true;
  3282. }
  3283. if (preg_match('/(\[| )MUPDATE=.*/', $str)) {
  3284. self::$mupdate = true;
  3285. }
  3286. if ($trusted) {
  3287. $this->capability_readed = true;
  3288. }
  3289. }
  3290. /**
  3291. * Escapes a string when it contains special characters (RFC3501)
  3292. *
  3293. * @param string $string IMAP string
  3294. * @param boolean $force_quotes Forces string quoting (for atoms)
  3295. *
  3296. * @return string String atom, quoted-string or string literal
  3297. * @todo lists
  3298. */
  3299. static function escape($string, $force_quotes=false)
  3300. {
  3301. if ($string === null) {
  3302. return 'NIL';
  3303. }
  3304. if ($string === '') {
  3305. return '""';
  3306. }
  3307. // atom-string (only safe characters)
  3308. if (!$force_quotes && !preg_match('/[\x00-\x20\x22\x25\x28-\x2A\x5B-\x5D\x7B\x7D\x80-\xFF]/', $string)) {
  3309. return $string;
  3310. }
  3311. // quoted-string
  3312. if (!preg_match('/[\r\n\x00\x80-\xFF]/', $string)) {
  3313. return '"' . addcslashes($string, '\\"') . '"';
  3314. }
  3315. // literal-string
  3316. return sprintf("{%d}\r\n%s", strlen($string), $string);
  3317. }
  3318. /**
  3319. * Set the value of the debugging flag.
  3320. *
  3321. * @param boolean $debug New value for the debugging flag.
  3322. * @param callback $handler Logging handler function
  3323. *
  3324. * @since 0.5-stable
  3325. */
  3326. function setDebug($debug, $handler = null)
  3327. {
  3328. $this->_debug = $debug;
  3329. $this->_debug_handler = $handler;
  3330. }
  3331. /**
  3332. * Write the given debug text to the current debug output handler.
  3333. *
  3334. * @param string $message Debug mesage text.
  3335. *
  3336. * @since 0.5-stable
  3337. */
  3338. protected function debug($message)
  3339. {
  3340. if (($len = strlen($message)) > self::DEBUG_LINE_LENGTH) {
  3341. $diff = $len - self::DEBUG_LINE_LENGTH;
  3342. $message = substr($message, 0, self::DEBUG_LINE_LENGTH)
  3343. . "... [truncated $diff bytes]";
  3344. }
  3345. if ($this->resourceid) {
  3346. $message = sprintf('[%s] %s', $this->resourceid, $message);
  3347. }
  3348. if ($this->_debug_handler) {
  3349. call_user_func_array($this->_debug_handler, array(&$this, $message));
  3350. } else {
  3351. echo "DEBUG: $message\n";
  3352. }
  3353. }
  3354. }