alecpl
2012-04-14 9870dac30de1b8d1bdeab57af3eeb7c89b21ef76
commit | author | age
40c45e 1 <?php
A 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_result_thread.php                               |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9  | Copyright (C) 2011, Kolab Systems AG                                  |
7fe381 10  |                                                                       |
T 11  | Licensed under the GNU General Public License version 3 or            |
12  | any later version with exceptions for skins & plugins.                |
13  | See the README file for a full license statement.                     |
40c45e 14  |                                                                       |
A 15  | PURPOSE:                                                              |
16  |   THREAD response handler                                             |
17  |                                                                       |
18  +-----------------------------------------------------------------------+
19  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
20  | Author: Aleksander Machniak <alec@alec.pl>                            |
21  +-----------------------------------------------------------------------+
22
e10f13 23  $Id$
40c45e 24
A 25 */
26
27
28 /**
29  * Class for accessing IMAP's THREAD result
30  */
31 class rcube_result_thread
32 {
c321a9 33     protected $raw_data;
T 34     protected $mailbox;
35     protected $meta = array();
36     protected $order = 'ASC';
40c45e 37
A 38     const SEPARATOR_ELEMENT = ' ';
39     const SEPARATOR_ITEM    = '~';
40     const SEPARATOR_LEVEL   = ':';
41
42
43     /**
44      * Object constructor.
45      */
46     public function __construct($mailbox = null, $data = null)
47     {
48         $this->mailbox = $mailbox;
49         $this->init($data);
50     }
51
52
53     /**
54      * Initializes object with IMAP command response
55      *
56      * @param string $data IMAP response string
57      */
58     public function init($data = null)
59     {
60         $this->meta = array();
61
62         $data = explode('*', (string)$data);
63
64         // ...skip unilateral untagged server responses
65         for ($i=0, $len=count($data); $i<$len; $i++) {
66             if (preg_match('/^ THREAD/i', $data[$i])) {
67                 $data[$i] = substr($data[$i], 7);
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()) {
40c45e 458             $index->intersect($this->get());
A 459         }
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
479             $result[$elem] = $elem;
480             foreach ($items as $item) {
481                 list($lv, $id) = explode(self::SEPARATOR_LEVEL, $item);
482                     $result[$id] = $root;
483             }
484         }
485
486         // get only unique roots
487         $result = array_filter($result); // make sure there are no nulls
488         $result = array_unique($result, SORT_NUMERIC);
489
490         // Re-sort raw data
491         $result = array_fill_keys($result, null);
492         $start = 0;
493
494         while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
495             || ($start < $datalen && ($pos = $datalen))
496         ) {
497             $len   = $pos - $start;
498             $elem  = substr($this->raw_data, $start, $len);
499             $start = $pos + 1;
500
501             $npos = strpos($elem, self::SEPARATOR_ITEM);
502             $root = (int) ($npos ? substr($elem, 0, $npos) : $elem);
503
504             $result[$root] = $elem;
505         }
506
507         $this->raw_data = implode(self::SEPARATOR_ELEMENT, $result);
508     }
509
510
511     /**
512      * Returns data as tree
513      *
514      * @return array Data tree
515      */
c321a9 516     public function get_tree()
40c45e 517     {
A 518         $datalen = strlen($this->raw_data);
519         $result  = array();
520         $start   = 0;
521
522         while (($pos = @strpos($this->raw_data, self::SEPARATOR_ELEMENT, $start))
523             || ($start < $datalen && ($pos = $datalen))
524         ) {
525             $len   = $pos - $start;
526             $elem  = substr($this->raw_data, $start, $len);
527             $items = explode(self::SEPARATOR_ITEM, $elem);
c321a9 528             $result[array_shift($items)] = $this->build_thread($items);
40c45e 529             $start = $pos + 1;
A 530         }
531
532         return $result;
533     }
534
535
536     /**
537      * Returns thread depth and children data
538      *
539      * @return array Thread data
540      */
c321a9 541     public function get_thread_data()
40c45e 542     {
c321a9 543         $data     = $this->get_tree();
40c45e 544         $depth    = array();
A 545         $children = array();
546
c321a9 547         $this->build_thread_data($data, $depth, $children);
40c45e 548
A 549         return array($depth, $children);
550     }
551
552
553     /**
554      * Creates 'depth' and 'children' arrays from stored thread 'tree' data.
555      */
c321a9 556     protected function build_thread_data($data, &$depth, &$children, $level = 0)
40c45e 557     {
A 558         foreach ((array)$data as $key => $val) {
fd43a9 559             $empty          = empty($val) || !is_array($val);
A 560             $children[$key] = !$empty;
561             $depth[$key]    = $level;
562             if (!$empty) {
c321a9 563                 $this->build_thread_data($val, $depth, $children, $level + 1);
fd43a9 564             }
40c45e 565         }
A 566     }
567
568
569     /**
570      * Converts part of the raw thread into an array
571      */
c321a9 572     protected function build_thread($items, $level = 1, &$pos = 0)
40c45e 573     {
A 574         $result = array();
575
576         for ($len=count($items); $pos < $len; $pos++) {
577             list($lv, $id) = explode(self::SEPARATOR_LEVEL, $items[$pos]);
578             if ($level == $lv) {
579                 $pos++;
c321a9 580                 $result[$id] = $this->build_thread($items, $level+1, $pos);
40c45e 581             }
A 582             else {
583                 $pos--;
584                 break;
585             }
586         }
587
588         return $result;
589     }
590
591
592     /**
593      * IMAP THREAD response parser
594      */
c321a9 595     protected function parse_thread($str, $begin = 0, $end = 0, $depth = 0)
40c45e 596     {
A 597         // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
598         // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
599         // http://derickrethans.nl/files/phparch-php-variables-article.pdf
600         $node = '';
601         if (!$end) {
602             $end = strlen($str);
603         }
604
605         // Let's try to store data in max. compacted stracture as a string,
606         // arrays handling is much more expensive
607         // For the following structure: THREAD (2)(3 6 (4 23)(44 7 96))
608         // -- 2
609         //
610         // -- 3
611         //     \-- 6
612         //         |-- 4
613         //         |    \-- 23
614         //         |
615         //         \-- 44
616         //              \-- 7
617         //                   \-- 96
618         //
619         // The output will be: 2,3^1:6^2:4^3:23^2:44^3:7^4:96
620
621         if ($str[$begin] != '(') {
622             $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
623             $msg  = substr($str, $begin, $stop - $begin);
624             if (!$msg) {
625                 return $node;
626             }
627
628             $this->meta['messages']++;
629
630             $node .= ($depth ? self::SEPARATOR_ITEM.$depth.self::SEPARATOR_LEVEL : '').$msg;
631
632             if ($stop + 1 < $end) {
c321a9 633                 $node .= $this->parse_thread($str, $stop + 1, $end, $depth + 1);
40c45e 634             }
A 635         } else {
636             $off = $begin;
637             while ($off < $end) {
638                 $start = $off;
639                 $off++;
640                 $n = 1;
641                 while ($n > 0) {
642                     $p = strpos($str, ')', $off);
643                     if ($p === false) {
644                         // error, wrong structure, mismatched brackets in IMAP THREAD response
645                         // @TODO: write error to the log or maybe set $this->raw_data = null;
646                         return $node;
647                     }
648                     $p1 = strpos($str, '(', $off);
649                     if ($p1 !== false && $p1 < $p) {
650                         $off = $p1 + 1;
651                         $n++;
652                     } else {
653                         $off = $p + 1;
654                         $n--;
655                     }
656                 }
657
c321a9 658                 $thread = $this->parse_thread($str, $start + 1, $off - 1, $depth);
40c45e 659                 if ($thread) {
A 660                     if (!$depth) {
661                         if ($node) {
662                             $node .= self::SEPARATOR_ELEMENT;
663                         }
664                     }
665                     $node .= $thread;
666                 }
667             }
668         }
669
670         return $node;
671     }
672 }