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