You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_result_thread.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2011, The Roundcube Dev Team |
  6. | Copyright (C) 2011, 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. | THREAD response handler |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Author: Aleksander Machniak <alec@alec.pl> |
  17. +-----------------------------------------------------------------------+
  18. */
  19. /**
  20. * Class for accessing IMAP's THREAD result
  21. *
  22. * @package Framework
  23. * @subpackage Storage
  24. */
  25. class rcube_result_thread
  26. {
  27. public $incomplete = false;
  28. protected $raw_data;
  29. protected $mailbox;
  30. protected $meta = array();
  31. protected $order = 'ASC';
  32. const SEPARATOR_ELEMENT = ' ';
  33. const SEPARATOR_ITEM = '~';
  34. const SEPARATOR_LEVEL = ':';
  35. /**
  36. * Object constructor.
  37. */
  38. public function __construct($mailbox = null, $data = null)
  39. {
  40. $this->mailbox = $mailbox;
  41. $this->init($data);
  42. }
  43. /**
  44. * Initializes object with IMAP command response
  45. *
  46. * @param string $data IMAP response string
  47. */
  48. public function init($data = null)
  49. {
  50. $this->meta = array();
  51. $data = explode('*', (string)$data);
  52. // ...skip unilateral untagged server responses
  53. for ($i=0, $len=count($data); $i<$len; $i++) {
  54. if (preg_match('/^ THREAD/i', $data[$i])) {
  55. // valid response, initialize raw_data for is_error()
  56. $this->raw_data = '';
  57. $data[$i] = substr($data[$i], 7);
  58. break;
  59. }
  60. unset($data[$i]);
  61. }
  62. if (empty($data)) {
  63. return;
  64. }
  65. $data = array_shift($data);
  66. $data = trim($data);
  67. $data = preg_replace('/[\r\n]/', '', $data);
  68. $data = preg_replace('/\s+/', ' ', $data);
  69. $this->raw_data = $this->parse_thread($data);
  70. }
  71. /**
  72. * Checks the result from IMAP command
  73. *
  74. * @return bool True if the result is an error, False otherwise
  75. */
  76. public function is_error()
  77. {
  78. return $this->raw_data === null;
  79. }
  80. /**
  81. * Checks if the result is empty
  82. *
  83. * @return bool True if the result is empty, False otherwise
  84. */
  85. public function is_empty()
  86. {
  87. return empty($this->raw_data);
  88. }
  89. /**
  90. * Returns number of elements (threads) in the result
  91. *
  92. * @return int Number of elements
  93. */
  94. public function count()
  95. {
  96. if ($this->meta['count'] !== null)
  97. return $this->meta['count'];
  98. if (empty($this->raw_data)) {
  99. $this->meta['count'] = 0;
  100. }
  101. else {
  102. $this->meta['count'] = 1 + substr_count($this->raw_data, self::SEPARATOR_ELEMENT);
  103. }
  104. if (!$this->meta['count'])
  105. $this->meta['messages'] = 0;
  106. return $this->meta['count'];
  107. }
  108. /**
  109. * Returns number of all messages in the result
  110. *
  111. * @return int Number of elements
  112. */
  113. public function count_messages()
  114. {
  115. if ($this->meta['messages'] !== null)
  116. return $this->meta['messages'];
  117. if (empty($this->raw_data)) {
  118. $this->meta['messages'] = 0;
  119. }
  120. else {
  121. $this->meta['messages'] = 1
  122. + substr_count($this->raw_data, self::SEPARATOR_ELEMENT)
  123. + substr_count($this->raw_data, self::SEPARATOR_ITEM);
  124. }
  125. if ($this->meta['messages'] == 0 || $this->meta['messages'] == 1)
  126. $this->meta['count'] = $this->meta['messages'];
  127. return $this->meta['messages'];
  128. }
  129. /**
  130. * Returns maximum message identifier in the result
  131. *
  132. * @return int Maximum message identifier
  133. */
  134. public function max()
  135. {
  136. if (!isset($this->meta['max'])) {
  137. $this->meta['max'] = (int) @max($this->get());
  138. }
  139. return $this->meta['max'];
  140. }
  141. /**
  142. * Returns minimum message identifier in the result
  143. *
  144. * @return int Minimum message identifier
  145. */
  146. public function min()
  147. {
  148. if (!isset($this->meta['min'])) {
  149. $this->meta['min'] = (int) @min($this->get());
  150. }
  151. return $this->meta['min'];
  152. }
  153. /**
  154. * Slices data set.
  155. *
  156. * @param $offset Offset (as for PHP's array_slice())
  157. * @param $length Number of elements (as for PHP's array_slice())
  158. */
  159. public function slice($offset, $length)
  160. {
  161. $data = explode(self::SEPARATOR_ELEMENT, $this->raw_data);
  162. $data = array_slice($data, $offset, $length);
  163. $this->meta = array();
  164. $this->meta['count'] = count($data);
  165. $this->raw_data = implode(self::SEPARATOR_ELEMENT, $data);
  166. }
  167. /**
  168. * Filters data set. Removes threads not listed in $roots list.
  169. *
  170. * @param array $roots List of IDs of thread roots.
  171. */
  172. public function filter($roots)
  173. {
  174. $datalen = strlen($this->raw_data);
  175. $roots = array_flip($roots);
  176. $result = '';
  177. $start = 0;
  178. $this->meta = array();
  179. $this->meta['count'] = 0;
  180. while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
  181. || ($start < $datalen && ($pos = $datalen))
  182. ) {
  183. $len = $pos - $start;
  184. $elem = substr($this->raw_data, $start, $len);
  185. $start = $pos + 1;
  186. // extract root message ID
  187. if ($npos = strpos($elem, self::SEPARATOR_ITEM)) {
  188. $root = (int) substr($elem, 0, $npos);
  189. }
  190. else {
  191. $root = $elem;
  192. }
  193. if (isset($roots[$root])) {
  194. $this->meta['count']++;
  195. $result .= self::SEPARATOR_ELEMENT . $elem;
  196. }
  197. }
  198. $this->raw_data = ltrim($result, self::SEPARATOR_ELEMENT);
  199. }
  200. /**
  201. * Reverts order of elements in the result
  202. */
  203. public function revert()
  204. {
  205. $this->order = $this->order == 'ASC' ? 'DESC' : 'ASC';
  206. if (empty($this->raw_data)) {
  207. return;
  208. }
  209. $data = explode(self::SEPARATOR_ELEMENT, $this->raw_data);
  210. $data = array_reverse($data);
  211. $this->raw_data = implode(self::SEPARATOR_ELEMENT, $data);
  212. $this->meta['pos'] = array();
  213. }
  214. /**
  215. * Check if the given message ID exists in the object
  216. *
  217. * @param int $msgid Message ID
  218. * @param bool $get_index When enabled element's index will be returned.
  219. * Elements are indexed starting with 0
  220. *
  221. * @return boolean True on success, False if message ID doesn't exist
  222. */
  223. public function exists($msgid, $get_index = false)
  224. {
  225. $msgid = (int) $msgid;
  226. $begin = implode('|', array(
  227. '^',
  228. preg_quote(self::SEPARATOR_ELEMENT, '/'),
  229. preg_quote(self::SEPARATOR_LEVEL, '/'),
  230. ));
  231. $end = implode('|', array(
  232. '$',
  233. preg_quote(self::SEPARATOR_ELEMENT, '/'),
  234. preg_quote(self::SEPARATOR_ITEM, '/'),
  235. ));
  236. if (preg_match("/($begin)$msgid($end)/", $this->raw_data, $m,
  237. $get_index ? PREG_OFFSET_CAPTURE : null)
  238. ) {
  239. if ($get_index) {
  240. $idx = 0;
  241. if ($m[0][1]) {
  242. $idx = substr_count($this->raw_data, self::SEPARATOR_ELEMENT, 0, $m[0][1]+1)
  243. + substr_count($this->raw_data, self::SEPARATOR_ITEM, 0, $m[0][1]+1);
  244. }
  245. // cache position of this element, so we can use it in get_element()
  246. $this->meta['pos'][$idx] = (int)$m[0][1];
  247. return $idx;
  248. }
  249. return true;
  250. }
  251. return false;
  252. }
  253. /**
  254. * Return IDs of all messages in the result. Threaded data will be flattened.
  255. *
  256. * @return array List of message identifiers
  257. */
  258. public function get()
  259. {
  260. if (empty($this->raw_data)) {
  261. return array();
  262. }
  263. $regexp = '/(' . preg_quote(self::SEPARATOR_ELEMENT, '/')
  264. . '|' . preg_quote(self::SEPARATOR_ITEM, '/') . '[0-9]+' . preg_quote(self::SEPARATOR_LEVEL, '/')
  265. .')/';
  266. return preg_split($regexp, $this->raw_data);
  267. }
  268. /**
  269. * Return all messages in the result.
  270. *
  271. * @return array List of message identifiers
  272. */
  273. public function get_compressed()
  274. {
  275. if (empty($this->raw_data)) {
  276. return '';
  277. }
  278. return rcube_imap_generic::compressMessageSet($this->get());
  279. }
  280. /**
  281. * Return result element at specified index (all messages, not roots)
  282. *
  283. * @param int|string $index Element's index or "FIRST" or "LAST"
  284. *
  285. * @return int Element value
  286. */
  287. public function get_element($index)
  288. {
  289. $count = $this->count();
  290. if (!$count) {
  291. return null;
  292. }
  293. // first element
  294. if ($index === 0 || $index === '0' || $index === 'FIRST') {
  295. preg_match('/^([0-9]+)/', $this->raw_data, $m);
  296. $result = (int) $m[1];
  297. return $result;
  298. }
  299. // last element
  300. if ($index === 'LAST' || $index == $count-1) {
  301. preg_match('/([0-9]+)$/', $this->raw_data, $m);
  302. $result = (int) $m[1];
  303. return $result;
  304. }
  305. // do we know the position of the element or the neighbour of it?
  306. if (!empty($this->meta['pos'])) {
  307. $element = preg_quote(self::SEPARATOR_ELEMENT, '/');
  308. $item = preg_quote(self::SEPARATOR_ITEM, '/') . '[0-9]+' . preg_quote(self::SEPARATOR_LEVEL, '/') .'?';
  309. $regexp = '(' . $element . '|' . $item . ')';
  310. if (isset($this->meta['pos'][$index])) {
  311. if (preg_match('/([0-9]+)/', $this->raw_data, $m, null, $this->meta['pos'][$index]))
  312. $result = $m[1];
  313. }
  314. else if (isset($this->meta['pos'][$index-1])) {
  315. // get chunk of data after previous element
  316. $data = substr($this->raw_data, $this->meta['pos'][$index-1]+1, 50);
  317. $data = preg_replace('/^[0-9]+/', '', $data); // remove UID at $index position
  318. $data = preg_replace("/^$regexp/", '', $data); // remove separator
  319. if (preg_match('/^([0-9]+)/', $data, $m))
  320. $result = $m[1];
  321. }
  322. else if (isset($this->meta['pos'][$index+1])) {
  323. // get chunk of data before next element
  324. $pos = max(0, $this->meta['pos'][$index+1] - 50);
  325. $len = min(50, $this->meta['pos'][$index+1]);
  326. $data = substr($this->raw_data, $pos, $len);
  327. $data = preg_replace("/$regexp\$/", '', $data); // remove separator
  328. if (preg_match('/([0-9]+)$/', $data, $m))
  329. $result = $m[1];
  330. }
  331. if (isset($result)) {
  332. return (int) $result;
  333. }
  334. }
  335. // Finally use less effective method
  336. $data = $this->get();
  337. return $data[$index];
  338. }
  339. /**
  340. * Returns response parameters e.g. MAILBOX, ORDER
  341. *
  342. * @param string $param Parameter name
  343. *
  344. * @return array|string Response parameters or parameter value
  345. */
  346. public function get_parameters($param=null)
  347. {
  348. $params = array();
  349. $params['MAILBOX'] = $this->mailbox;
  350. $params['ORDER'] = $this->order;
  351. if ($param !== null) {
  352. return $params[$param];
  353. }
  354. return $params;
  355. }
  356. /**
  357. * THREAD=REFS sorting implementation (based on provided index)
  358. *
  359. * @param rcube_result_index $index Sorted message identifiers
  360. */
  361. public function sort($index)
  362. {
  363. $this->sort_order = $index->get_parameters('ORDER');
  364. if (empty($this->raw_data)) {
  365. return;
  366. }
  367. // when sorting search result it's good to make the index smaller
  368. if ($index->count() != $this->count_messages()) {
  369. $index->filter($this->get());
  370. }
  371. $result = array_fill_keys($index->get(), null);
  372. $datalen = strlen($this->raw_data);
  373. $start = 0;
  374. // Here we're parsing raw_data twice, we want only one big array
  375. // in memory at a time
  376. // Assign roots
  377. while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
  378. || ($start < $datalen && ($pos = $datalen))
  379. ) {
  380. $len = $pos - $start;
  381. $elem = substr($this->raw_data, $start, $len);
  382. $start = $pos + 1;
  383. $items = explode(self::SEPARATOR_ITEM, $elem);
  384. $root = (int) array_shift($items);
  385. if ($root) {
  386. $result[$root] = $root;
  387. foreach ($items as $item) {
  388. list($lv, $id) = explode(self::SEPARATOR_LEVEL, $item);
  389. $result[$id] = $root;
  390. }
  391. }
  392. }
  393. // get only unique roots
  394. $result = array_filter($result); // make sure there are no nulls
  395. $result = array_unique($result);
  396. // Re-sort raw data
  397. $result = array_fill_keys($result, null);
  398. $start = 0;
  399. while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
  400. || ($start < $datalen && ($pos = $datalen))
  401. ) {
  402. $len = $pos - $start;
  403. $elem = substr($this->raw_data, $start, $len);
  404. $start = $pos + 1;
  405. $npos = strpos($elem, self::SEPARATOR_ITEM);
  406. $root = (int) ($npos ? substr($elem, 0, $npos) : $elem);
  407. $result[$root] = $elem;
  408. }
  409. $this->raw_data = implode(self::SEPARATOR_ELEMENT, $result);
  410. }
  411. /**
  412. * Returns data as tree
  413. *
  414. * @return array Data tree
  415. */
  416. public function get_tree()
  417. {
  418. $datalen = strlen($this->raw_data);
  419. $result = array();
  420. $start = 0;
  421. while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
  422. || ($start < $datalen && ($pos = $datalen))
  423. ) {
  424. $len = $pos - $start;
  425. $elem = substr($this->raw_data, $start, $len);
  426. $items = explode(self::SEPARATOR_ITEM, $elem);
  427. $result[array_shift($items)] = $this->build_thread($items);
  428. $start = $pos + 1;
  429. }
  430. return $result;
  431. }
  432. /**
  433. * Returns thread depth and children data
  434. *
  435. * @return array Thread data
  436. */
  437. public function get_thread_data()
  438. {
  439. $data = $this->get_tree();
  440. $depth = array();
  441. $children = array();
  442. $this->build_thread_data($data, $depth, $children);
  443. return array($depth, $children);
  444. }
  445. /**
  446. * Creates 'depth' and 'children' arrays from stored thread 'tree' data.
  447. */
  448. protected function build_thread_data($data, &$depth, &$children, $level = 0)
  449. {
  450. foreach ((array)$data as $key => $val) {
  451. $empty = empty($val) || !is_array($val);
  452. $children[$key] = !$empty;
  453. $depth[$key] = $level;
  454. if (!$empty) {
  455. $this->build_thread_data($val, $depth, $children, $level + 1);
  456. }
  457. }
  458. }
  459. /**
  460. * Converts part of the raw thread into an array
  461. */
  462. protected function build_thread($items, $level = 1, &$pos = 0)
  463. {
  464. $result = array();
  465. for ($len=count($items); $pos < $len; $pos++) {
  466. list($lv, $id) = explode(self::SEPARATOR_LEVEL, $items[$pos]);
  467. if ($level == $lv) {
  468. $pos++;
  469. $result[$id] = $this->build_thread($items, $level+1, $pos);
  470. }
  471. else {
  472. $pos--;
  473. break;
  474. }
  475. }
  476. return $result;
  477. }
  478. /**
  479. * IMAP THREAD response parser
  480. */
  481. protected function parse_thread($str, $begin = 0, $end = 0, $depth = 0)
  482. {
  483. // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
  484. // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
  485. // http://derickrethans.nl/files/phparch-php-variables-article.pdf
  486. $node = '';
  487. if (!$end) {
  488. $end = strlen($str);
  489. }
  490. // Let's try to store data in max. compacted stracture as a string,
  491. // arrays handling is much more expensive
  492. // For the following structure: THREAD (2)(3 6 (4 23)(44 7 96))
  493. // -- 2
  494. // -- 3
  495. // \-- 6
  496. // |-- 4
  497. // | \-- 23
  498. // |
  499. // \-- 44
  500. // \-- 7
  501. // \-- 96
  502. //
  503. // The output will be: 2,3^1:6^2:4^3:23^2:44^3:7^4:96
  504. if ($str[$begin] != '(') {
  505. // find next bracket
  506. $stop = $begin + strcspn($str, '()', $begin, $end - $begin);
  507. $messages = explode(' ', trim(substr($str, $begin, $stop - $begin)));
  508. if (empty($messages)) {
  509. return $node;
  510. }
  511. foreach ($messages as $msg) {
  512. if ($msg) {
  513. $node .= ($depth ? self::SEPARATOR_ITEM.$depth.self::SEPARATOR_LEVEL : '').$msg;
  514. $this->meta['messages']++;
  515. $depth++;
  516. }
  517. }
  518. if ($stop < $end) {
  519. $node .= $this->parse_thread($str, $stop, $end, $depth);
  520. }
  521. }
  522. else {
  523. $off = $begin;
  524. while ($off < $end) {
  525. $start = $off;
  526. $off++;
  527. $n = 1;
  528. while ($n > 0) {
  529. $p = strpos($str, ')', $off);
  530. if ($p === false) {
  531. // error, wrong structure, mismatched brackets in IMAP THREAD response
  532. // @TODO: write error to the log or maybe set $this->raw_data = null;
  533. return $node;
  534. }
  535. $p1 = strpos($str, '(', $off);
  536. if ($p1 !== false && $p1 < $p) {
  537. $off = $p1 + 1;
  538. $n++;
  539. }
  540. else {
  541. $off = $p + 1;
  542. $n--;
  543. }
  544. }
  545. $thread = $this->parse_thread($str, $start + 1, $off - 1, $depth);
  546. if ($thread) {
  547. if (!$depth) {
  548. if ($node) {
  549. $node .= self::SEPARATOR_ELEMENT;
  550. }
  551. }
  552. $node .= $thread;
  553. }
  554. }
  555. }
  556. return $node;
  557. }
  558. }