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