Bostjan Skufca
2016-04-09 55d90b2f621a9c144b54b07b4e1dafd0fdad0e85
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
55d90b 255         $raw_data_reverse = implode(self::SEPARATOR_ELEMENT, array_reverse(explode(self::SEPARATOR_ELEMENT, $this->raw_data)));
BS 256         $this->raw_data = $raw_data_reverse;
257
40c45e 258         $this->meta['pos'] = array();
A 259     }
260
261
262     /**
263      * Check if the given message ID exists in the object
264      *
265      * @param int $msgid Message ID
266      * @param bool $get_index When enabled element's index will be returned.
267      *                        Elements are indexed starting with 0
268      *
269      * @return boolean True on success, False if message ID doesn't exist
270      */
271     public function exists($msgid, $get_index = false)
272     {
273         $msgid = (int) $msgid;
274         $begin = implode('|', array(
275             '^',
276             preg_quote(self::SEPARATOR_ELEMENT, '/'),
277             preg_quote(self::SEPARATOR_LEVEL, '/'),
278         ));
279         $end = implode('|', array(
280             '$',
281             preg_quote(self::SEPARATOR_ELEMENT, '/'),
282             preg_quote(self::SEPARATOR_ITEM, '/'),
283         ));
284
285         if (preg_match("/($begin)$msgid($end)/", $this->raw_data, $m,
286             $get_index ? PREG_OFFSET_CAPTURE : null)
287         ) {
288             if ($get_index) {
289                 $idx = 0;
290                 if ($m[0][1]) {
291                     $idx = substr_count($this->raw_data, self::SEPARATOR_ELEMENT, 0, $m[0][1]+1)
292                         + substr_count($this->raw_data, self::SEPARATOR_ITEM, 0, $m[0][1]+1);
293                 }
c321a9 294                 // cache position of this element, so we can use it in get_element()
40c45e 295                 $this->meta['pos'][$idx] = (int)$m[0][1];
A 296
297                 return $idx;
298             }
299             return true;
300         }
301
302         return false;
303     }
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     /**
326      * Return all messages in the result.
327      *
328      * @return array List of message identifiers
329      */
c321a9 330     public function get_compressed()
40c45e 331     {
A 332         if (empty($this->raw_data)) {
333             return '';
334         }
335
336         return rcube_imap_generic::compressMessageSet($this->get());
337     }
338
339
340     /**
341      * Return result element at specified index (all messages, not roots)
342      *
343      * @param int|string  $index  Element's index or "FIRST" or "LAST"
344      *
345      * @return int Element value
346      */
c321a9 347     public function get_element($index)
40c45e 348     {
A 349         $count = $this->count();
350
351         if (!$count) {
352             return null;
353         }
354
355         // first element
356         if ($index === 0 || $index === '0' || $index === 'FIRST') {
357             preg_match('/^([0-9]+)/', $this->raw_data, $m);
358             $result = (int) $m[1];
359             return $result;
360         }
361
362         // last element
363         if ($index === 'LAST' || $index == $count-1) {
364             preg_match('/([0-9]+)$/', $this->raw_data, $m);
365             $result = (int) $m[1];
366             return $result;
367         }
368
369         // do we know the position of the element or the neighbour of it?
370         if (!empty($this->meta['pos'])) {
371             $element = preg_quote(self::SEPARATOR_ELEMENT, '/');
372             $item    = preg_quote(self::SEPARATOR_ITEM, '/') . '[0-9]+' . preg_quote(self::SEPARATOR_LEVEL, '/') .'?';
373             $regexp  = '(' . $element . '|' . $item . ')';
374
375             if (isset($this->meta['pos'][$index])) {
376                 if (preg_match('/([0-9]+)/', $this->raw_data, $m, null, $this->meta['pos'][$index]))
377                     $result = $m[1];
378             }
379             else if (isset($this->meta['pos'][$index-1])) {
380                 // get chunk of data after previous element
381                 $data = substr($this->raw_data, $this->meta['pos'][$index-1]+1, 50);
382                 $data = preg_replace('/^[0-9]+/', '', $data); // remove UID at $index position
383                 $data = preg_replace("/^$regexp/", '', $data); // remove separator
384                 if (preg_match('/^([0-9]+)/', $data, $m))
385                     $result = $m[1];
386             }
387             else if (isset($this->meta['pos'][$index+1])) {
388                 // get chunk of data before next element
389                 $pos  = max(0, $this->meta['pos'][$index+1] - 50);
390                 $len  = min(50, $this->meta['pos'][$index+1]);
391                 $data = substr($this->raw_data, $pos, $len);
392                 $data = preg_replace("/$regexp\$/", '', $data); // remove separator
393
394                 if (preg_match('/([0-9]+)$/', $data, $m))
395                     $result = $m[1];
396             }
397
398             if (isset($result)) {
399                 return (int) $result;
400             }
401         }
402
403         // Finally use less effective method
404         $data = $this->get();
405
406         return $data[$index];
407     }
408
409
410     /**
411      * Returns response parameters e.g. MAILBOX, ORDER
412      *
413      * @param string $param  Parameter name
414      *
415      * @return array|string Response parameters or parameter value
416      */
c321a9 417     public function get_parameters($param=null)
40c45e 418     {
A 419         $params = $this->params;
420         $params['MAILBOX'] = $this->mailbox;
421         $params['ORDER']   = $this->order;
422
423         if ($param !== null) {
424             return $params[$param];
425         }
426
427         return $params;
428     }
429
430
431     /**
432      * THREAD=REFS sorting implementation (based on provided index)
433      *
434      * @param rcube_result_index $index  Sorted message identifiers
435      */
436     public function sort($index)
437     {
c321a9 438         $this->sort_order = $index->get_parameters('ORDER');
40c45e 439
A 440         if (empty($this->raw_data)) {
441             return;
442         }
443
444         // when sorting search result it's good to make the index smaller
c321a9 445         if ($index->count() != $this->count_messages()) {
3b1d41 446             $index->filter($this->get());
40c45e 447         }
A 448
449         $result  = array_fill_keys($index->get(), null);
450         $datalen = strlen($this->raw_data);
451         $start   = 0;
452
453         // Here we're parsing raw_data twice, we want only one big array
454         // in memory at a time
455
456         // Assign roots
457         while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
458             || ($start < $datalen && ($pos = $datalen))
459         ) {
460             $len   = $pos - $start;
461             $elem  = substr($this->raw_data, $start, $len);
462             $start = $pos + 1;
463
464             $items = explode(self::SEPARATOR_ITEM, $elem);
465             $root  = (int) array_shift($items);
466
485f23 467             if ($root) {
AM 468                 $result[$root] = $root;
469                 foreach ($items as $item) {
470                     list($lv, $id) = explode(self::SEPARATOR_LEVEL, $item);
40c45e 471                     $result[$id] = $root;
485f23 472                 }
40c45e 473             }
A 474         }
475
476         // get only unique roots
477         $result = array_filter($result); // make sure there are no nulls
485f23 478         $result = array_unique($result);
40c45e 479
A 480         // Re-sort raw data
481         $result = array_fill_keys($result, null);
482         $start = 0;
483
484         while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
485             || ($start < $datalen && ($pos = $datalen))
486         ) {
487             $len   = $pos - $start;
488             $elem  = substr($this->raw_data, $start, $len);
489             $start = $pos + 1;
490
491             $npos = strpos($elem, self::SEPARATOR_ITEM);
492             $root = (int) ($npos ? substr($elem, 0, $npos) : $elem);
493
494             $result[$root] = $elem;
495         }
496
497         $this->raw_data = implode(self::SEPARATOR_ELEMENT, $result);
498     }
499
500
501     /**
502      * Returns data as tree
503      *
504      * @return array Data tree
505      */
c321a9 506     public function get_tree()
40c45e 507     {
A 508         $datalen = strlen($this->raw_data);
509         $result  = array();
510         $start   = 0;
511
512         while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
513             || ($start < $datalen && ($pos = $datalen))
514         ) {
515             $len   = $pos - $start;
516             $elem  = substr($this->raw_data, $start, $len);
517             $items = explode(self::SEPARATOR_ITEM, $elem);
c321a9 518             $result[array_shift($items)] = $this->build_thread($items);
40c45e 519             $start = $pos + 1;
A 520         }
521
522         return $result;
523     }
524
525
526     /**
527      * Returns thread depth and children data
528      *
529      * @return array Thread data
530      */
c321a9 531     public function get_thread_data()
40c45e 532     {
c321a9 533         $data     = $this->get_tree();
40c45e 534         $depth    = array();
A 535         $children = array();
536
c321a9 537         $this->build_thread_data($data, $depth, $children);
40c45e 538
A 539         return array($depth, $children);
540     }
541
542
543     /**
544      * Creates 'depth' and 'children' arrays from stored thread 'tree' data.
545      */
c321a9 546     protected function build_thread_data($data, &$depth, &$children, $level = 0)
40c45e 547     {
A 548         foreach ((array)$data as $key => $val) {
fd43a9 549             $empty          = empty($val) || !is_array($val);
A 550             $children[$key] = !$empty;
551             $depth[$key]    = $level;
552             if (!$empty) {
c321a9 553                 $this->build_thread_data($val, $depth, $children, $level + 1);
fd43a9 554             }
40c45e 555         }
A 556     }
557
558
559     /**
560      * Converts part of the raw thread into an array
561      */
c321a9 562     protected function build_thread($items, $level = 1, &$pos = 0)
40c45e 563     {
A 564         $result = array();
565
566         for ($len=count($items); $pos < $len; $pos++) {
567             list($lv, $id) = explode(self::SEPARATOR_LEVEL, $items[$pos]);
568             if ($level == $lv) {
569                 $pos++;
c321a9 570                 $result[$id] = $this->build_thread($items, $level+1, $pos);
40c45e 571             }
A 572             else {
573                 $pos--;
574                 break;
575             }
576         }
577
578         return $result;
579     }
580
581
582     /**
583      * IMAP THREAD response parser
584      */
c321a9 585     protected function parse_thread($str, $begin = 0, $end = 0, $depth = 0)
40c45e 586     {
A 587         // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
588         // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
589         // http://derickrethans.nl/files/phparch-php-variables-article.pdf
590         $node = '';
591         if (!$end) {
592             $end = strlen($str);
593         }
594
595         // Let's try to store data in max. compacted stracture as a string,
596         // arrays handling is much more expensive
597         // For the following structure: THREAD (2)(3 6 (4 23)(44 7 96))
598         // -- 2
599         // -- 3
600         //     \-- 6
601         //         |-- 4
602         //         |    \-- 23
603         //         |
604         //         \-- 44
1fd6c4 605         //               \-- 7
AM 606         //                    \-- 96
40c45e 607         //
A 608         // The output will be: 2,3^1:6^2:4^3:23^2:44^3:7^4:96
609
610         if ($str[$begin] != '(') {
1fd6c4 611             // find next bracket
AM 612             $stop      = $begin + strcspn($str, '()', $begin, $end - $begin);
613             $messages  = explode(' ', trim(substr($str, $begin, $stop - $begin)));
614
615             if (empty($messages)) {
40c45e 616                 return $node;
A 617             }
618
1fd6c4 619             foreach ($messages as $msg) {
AM 620                 if ($msg) {
621                     $node .= ($depth ? self::SEPARATOR_ITEM.$depth.self::SEPARATOR_LEVEL : '').$msg;
622                     $this->meta['messages']++;
623                     $depth++;
624                 }
40c45e 625             }
1fd6c4 626
AM 627             if ($stop < $end) {
628                 $node .= $this->parse_thread($str, $stop, $end, $depth);
629             }
630         }
631         else {
40c45e 632             $off = $begin;
A 633             while ($off < $end) {
634                 $start = $off;
635                 $off++;
636                 $n = 1;
637                 while ($n > 0) {
638                     $p = strpos($str, ')', $off);
639                     if ($p === false) {
640                         // error, wrong structure, mismatched brackets in IMAP THREAD response
641                         // @TODO: write error to the log or maybe set $this->raw_data = null;
642                         return $node;
643                     }
644                     $p1 = strpos($str, '(', $off);
645                     if ($p1 !== false && $p1 < $p) {
646                         $off = $p1 + 1;
647                         $n++;
1fd6c4 648                     }
AM 649                     else {
40c45e 650                         $off = $p + 1;
A 651                         $n--;
652                     }
653                 }
654
c321a9 655                 $thread = $this->parse_thread($str, $start + 1, $off - 1, $depth);
40c45e 656                 if ($thread) {
A 657                     if (!$depth) {
658                         if ($node) {
659                             $node .= self::SEPARATOR_ELEMENT;
660                         }
661                     }
662                     $node .= $thread;
663                 }
664             }
665         }
666
667         return $node;
668     }
669 }