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