PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/program/include/rcube_result_thread.php

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