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