This file is indexed.

/usr/share/php/Horde/Imap/Client/Search/Query.php is in php-horde-imap-client 2.29.12-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
<?php
/**
 * Copyright 2008-2016 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @category  Horde
 * @copyright 2008-2016 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 */

/**
 * Abstraction of the IMAP4rev1 search criteria (see RFC 3501 [6.4.4]).
 * Allows translation between abstracted search criteria and a generated IMAP
 * search criteria string suitable for sending to a remote IMAP server.
 *
 * @author    Michael Slusarz <slusarz@horde.org>
 * @category  Horde
 * @copyright 2008-2016 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 */
class Horde_Imap_Client_Search_Query implements Serializable
{
    /**
     * Serialized version.
     */
    const VERSION = 3;

    /**
     * Constants for dateSearch()
     */
    const DATE_BEFORE = 'BEFORE';
    const DATE_ON = 'ON';
    const DATE_SINCE = 'SINCE';

    /**
     * Constants for intervalSearch()
     */
    const INTERVAL_OLDER = 'OLDER';
    const INTERVAL_YOUNGER = 'YOUNGER';

    /**
     * The charset of the search strings.  All text strings must be in
     * this charset. By default, this is 'US-ASCII' (see RFC 3501 [6.4.4]).
     *
     * @var string
     */
    protected $_charset = null;

    /**
     * The list of search params.
     *
     * @var array
     */
    protected $_search = array();

    /**
     * String representation: The IMAP search string.
     */
    public function __toString()
    {
        try {
            $res = $this->build(null);
            return $res['query']->escape();
        } catch (Exception $e) {
            return '';
        }
    }

    /**
     * Sets the charset of the search text.
     *
     * @param string $charset   The charset to use for the search.
     * @param boolean $convert  Convert existing text values?
     *
     * @throws Horde_Imap_Client_Exception_SearchCharset
     */
    public function charset($charset, $convert = true)
    {
        $oldcharset = $this->_charset;
        $this->_charset = Horde_String::upper($charset);

        if (!$convert || ($oldcharset == $this->_charset)) {
            return;
        }

        foreach (array('and', 'or') as $item) {
            if (isset($this->_search[$item])) {
                foreach ($this->_search[$item] as &$val) {
                    $val->charset($charset, $convert);
                }
            }
        }

        foreach (array('header', 'text') as $item) {
            if (isset($this->_search[$item])) {
                foreach ($this->_search[$item] as $key => $val) {
                    $new_val = Horde_String::convertCharset($val['text'], $oldcharset, $this->_charset);
                    if (Horde_String::convertCharset($new_val, $this->_charset, $oldcharset) != $val['text']) {
                        throw new Horde_Imap_Client_Exception_SearchCharset($this->_charset);
                    }
                    $this->_search[$item][$key]['text'] = $new_val;
                }
            }
        }
    }

    /**
     * Builds an IMAP4rev1 compliant search string.
     *
     * @todo  Change default of $exts to null.
     *
     * @param Horde_Imap_Client_Base $exts  The server object this query will
     *                                      be run on (@since 2.24.0), a
     *                                      Horde_Imap_Client_Data_Capability
     *                                      object (@since 2.24.0), or the
     *                                      list of extensions present
     *                                      on the server (@deprecated).
     *                                      If null, all extensions are
     *                                      assumed to be available.
     *
     * @return array  An array with these elements:
     *   - charset: (string) The charset of the search string. If null, no
     *              text strings appear in query.
     *   - exts: (array) The list of IMAP extensions used to create the
     *           string.
     *   - query: (Horde_Imap_Client_Data_Format_List) The IMAP search
     *            command.
     *
     * @throws Horde_Imap_Client_Data_Format_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function build($exts = array())
    {
        /* @todo: BC */
        if (is_array($exts)) {
            $tmp = new Horde_Imap_Client_Data_Capability_Imap();
            foreach ($exts as $key => $val) {
                $tmp->add($key, is_array($val) ? $val : null);
            }
            $exts = $tmp;
        } elseif (!is_null($exts)) {
            if ($exts instanceof Horde_Imap_Client_Base) {
                $exts = $exts->capability;
            } elseif (!($exts instanceof Horde_Imap_Client_Data_Capability)) {
                throw new InvalidArgumentException('Incorrect $exts parameter');
            }
        }

        $temp = array(
            'cmds' => new Horde_Imap_Client_Data_Format_List(),
            'exts' => $exts,
            'exts_used' => array()
        );
        $cmds = &$temp['cmds'];
        $charset = $charset_cname = null;
        $default_search = true;
        $exts_used = &$temp['exts_used'];
        $ptr = &$this->_search;

        $charset_get = function ($c) use (&$charset, &$charset_cname) {
            $charset = is_null($c)
                ? 'US-ASCII'
                : strval($c);
            $charset_cname = ($charset === 'US-ASCII')
                ? 'Horde_Imap_Client_Data_Format_Astring'
                : 'Horde_Imap_Client_Data_Format_Astring_Nonascii';
        };
        $create_return = function ($charset, $exts_used, $cmds) {
            return array(
                'charset' => $charset,
                'exts' => array_keys(array_flip($exts_used)),
                'query' => $cmds
            );
        };

        /* Do IDs check first. If there is an empty ID query (without a NOT
         * qualifier), the rest of this query is irrelevant since we already
         * know the search will return no results. */
        if (isset($ptr['ids'])) {
            if (!count($ptr['ids']['ids']) && !$ptr['ids']['ids']->special) {
                if (empty($ptr['ids']['not'])) {
                    /* This is a match on an empty list of IDs. We do need to
                     * process any OR queries that may exist, since they are
                     * independent of this result. */
                    if (isset($ptr['or'])) {
                        $this->_buildAndOr(
                            'OR', $ptr['or'], $charset, $exts_used, $cmds
                        );
                    }
                    return $create_return($charset, $exts_used, $cmds);
                }

                /* If reached here, this a NOT search of an empty list. We can
                 * safely discard this from the output. */
            } else {
                $this->_addFuzzy(!empty($ptr['ids']['fuzzy']), $temp);
                if (!empty($ptr['ids']['not'])) {
                    $cmds->add('NOT');
                }
                if (!$ptr['ids']['ids']->sequence) {
                    $cmds->add('UID');
                }
                $cmds->add(strval($ptr['ids']['ids']));
            }
        }

        if (isset($ptr['new'])) {
            $this->_addFuzzy(!empty($ptr['newfuzzy']), $temp);
            if ($ptr['new']) {
                $cmds->add('NEW');
                unset($ptr['flag']['UNSEEN']);
            } else {
                $cmds->add('OLD');
            }
            unset($ptr['flag']['RECENT']);
        }

        if (!empty($ptr['flag'])) {
            foreach ($ptr['flag'] as $key => $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);

                $tmp = '';
                if (empty($val['set'])) {
                    // This is a 'NOT' search.  All system flags but \Recent
                    // have 'UN' equivalents.
                    if ($key == 'RECENT') {
                        $cmds->add('NOT');
                    } else {
                        $tmp = 'UN';
                    }
                }

                if ($val['type'] == 'keyword') {
                    $cmds->add(array(
                        $tmp . 'KEYWORD',
                        $key
                    ));
                } else {
                    $cmds->add($tmp . $key);
                }
            }
        }

        if (!empty($ptr['header'])) {
            /* The list of 'system' headers that have a specific search
             * query. */
            $systemheaders = array(
                'BCC', 'CC', 'FROM', 'SUBJECT', 'TO'
            );

            foreach ($ptr['header'] as $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);

                if (!empty($val['not'])) {
                    $cmds->add('NOT');
                }

                if (in_array($val['header'], $systemheaders)) {
                    $cmds->add($val['header']);
                } else {
                    $cmds->add(array(
                        'HEADER',
                        new Horde_Imap_Client_Data_Format_Astring($val['header'])
                    ));
                }

                $charset_get($this->_charset);
                $cmds->add(
                    new $charset_cname(isset($val['text']) ? $val['text'] : '')
                );
            }
        }

        if (!empty($ptr['text'])) {
            foreach ($ptr['text'] as $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);

                if (!empty($val['not'])) {
                    $cmds->add('NOT');
                }

                $charset_get($this->_charset);
                $cmds->add(array(
                    $val['type'],
                    new $charset_cname($val['text'])
                ));
            }
        }

        if (!empty($ptr['size'])) {
            foreach ($ptr['size'] as $key => $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);
                if (!empty($val['not'])) {
                    $cmds->add('NOT');
                }
                $cmds->add(array(
                    $key,
                    new Horde_Imap_Client_Data_Format_Number(
                        empty($val['size']) ? 0 : $val['size']
                    )
                ));
            }
        }

        if (!empty($ptr['date'])) {
            foreach ($ptr['date'] as $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);

                if (!empty($val['not'])) {
                    $cmds->add('NOT');
                }

                if (empty($val['header'])) {
                    $cmds->add($val['range']);
                } else {
                    $cmds->add('SENT' . $val['range']);
                }
                $cmds->add($val['date']);
            }
        }

        if (!empty($ptr['within'])) {
            if (is_null($exts) || $exts->query('WITHIN')) {
                $exts_used[] = 'WITHIN';
            }

            foreach ($ptr['within'] as $key => $val) {
                $this->_addFuzzy(!empty($val['fuzzy']), $temp);
                if (!empty($val['not'])) {
                    $cmds->add('NOT');
                }

                if (is_null($exts) || $exts->query('WITHIN')) {
                    $cmds->add(array(
                        $key,
                        new Horde_Imap_Client_Data_Format_Number($val['interval'])
                    ));
                } else {
                    // This workaround is only accurate to within 1 day, due
                    // to limitations with the IMAP4rev1 search commands.
                    $cmds->add(array(
                        ($key == self::INTERVAL_OLDER) ? self::DATE_BEFORE : self::DATE_SINCE,
                        new Horde_Imap_Client_Data_Format_Date('now -' . $val['interval'] . ' seconds')
                    ));
                }
            }
        }

        if (!empty($ptr['modseq'])) {
            if (!is_null($exts) && !$exts->query('CONDSTORE')) {
                throw new Horde_Imap_Client_Exception_NoSupportExtension('CONDSTORE');
            }

            $exts_used[] = 'CONDSTORE';

            $this->_addFuzzy(!empty($ptr['modseq']['fuzzy']), $temp);

            if (!empty($ptr['modseq']['not'])) {
                $cmds->add('NOT');
            }
            $cmds->add('MODSEQ');
            if (isset($ptr['modseq']['name'])) {
                $cmds->add(array(
                    new Horde_Imap_Client_Data_Format_String($ptr['modseq']['name']),
                    $ptr['modseq']['type']
                ));
            }
            $cmds->add(new Horde_Imap_Client_Data_Format_Number($ptr['modseq']['value']));
        }

        if (isset($ptr['prevsearch'])) {
            if (!is_null($exts) && !$exts->query('SEARCHRES')) {
                throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCHRES');
            }

            $exts_used[] = 'SEARCHRES';

            $this->_addFuzzy(!empty($ptr['prevsearchfuzzy']), $temp);

            if (!$ptr['prevsearch']) {
                $cmds->add('NOT');
            }
            $cmds->add('$');
        }

        // Add AND'ed queries
        if (!empty($ptr['and'])) {
            $default_search = $this->_buildAndOr(
                'AND', $ptr['and'], $charset, $exts_used, $cmds
            );
        }

        // Add OR'ed queries
        if (!empty($ptr['or'])) {
            $default_search = $this->_buildAndOr(
                'OR', $ptr['or'], $charset, $exts_used, $cmds
            );
        }

        // Default search is 'ALL'
        if ($default_search && !count($cmds)) {
            $cmds->add('ALL');
        }

        return $create_return($charset, $exts_used, $cmds);
    }

    /**
     * Builds the AND/OR query.
     *
     * @param string $type                               'AND' or 'OR'.
     * @param array $data                                Query data.
     * @param string &$charset                           Search charset.
     * @param array &$exts_used                          IMAP extensions used.
     * @param Horde_Imap_Client_Data_Format_List &$cmds  Command list.
     *
     * @return boolean  True if query might return results.
     */
    protected function _buildAndOr($type, $data, &$charset, &$exts_used,
                                   &$cmds)
    {
        $results = false;

        foreach ($data as $val) {
            $ret = $val->build();

            /* Empty sub-query. */
            if (!count($ret['query'])) {
                switch ($type) {
                case 'AND':
                    /* Any empty sub-query means that the query MUST return
                     * no results. */
                    $cmds = new Horde_Imap_Client_Data_Format_List();
                    $exts_used = array();
                    return false;

                case 'OR':
                    /* Skip this query. */
                    continue 2;
                }
            }

            $results = true;

            if (!is_null($ret['charset']) && ($ret['charset'] != 'US-ASCII')) {
                if (!is_null($charset) &&
                    ($charset != 'US-ASCII') &&
                    ($charset != $ret['charset'])) {
                    throw new InvalidArgumentException(
                        'AND/OR queries must all have the same charset.'
                    );
                }
                $charset = $ret['charset'];
            }

            $exts_used = array_merge($exts_used, $ret['exts']);

            switch ($type) {
            case 'AND':
                $cmds->add($ret['query'], true);
                break;

            case 'OR':
                // First OR'd query
                if (count($cmds)) {
                    $new_cmds = new Horde_Imap_Client_Data_Format_List();
                    $new_cmds->add(array(
                        'OR',
                        $ret['query'],
                        $cmds
                    ));
                    $cmds = $new_cmds;
                } else {
                    $cmds = $ret['query'];
                }
                break;
            }
        }

        return $results;
    }

    /**
     * Adds fuzzy modifier to search keys.
     *
     * @param boolean $add  Add the fuzzy modifier?
     * @param array $temp   Temporary build data.
     *
     * @throws Horde_Imap_Client_Exception_NoSupport_Extension
     */
    protected function _addFuzzy($add, &$temp)
    {
        if ($add) {
            if (!$temp['exts']->query('SEARCH', 'FUZZY')) {
                throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCH=FUZZY');
            }
            $temp['cmds']->add('FUZZY');
            $temp['exts_used'][] = 'SEARCH=FUZZY';
        }
    }

    /**
     * Search for a flag/keywords.
     *
     * @param string $name  The flag or keyword name.
     * @param boolean $set  If true, search for messages that have the flag
     *                      set.  If false, search for messages that do not
     *                      have the flag set.
     * @param array $opts   Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function flag($name, $set = true, array $opts = array())
    {
        $name = Horde_String::upper(ltrim($name, '\\'));
        if (!isset($this->_search['flag'])) {
            $this->_search['flag'] = array();
        }

        /* The list of defined system flags (see RFC 3501 [2.3.2]). */
        $systemflags = array(
            'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'RECENT', 'SEEN'
        );

        $this->_search['flag'][$name] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'set' => $set,
            'type' => in_array($name, $systemflags) ? 'flag' : 'keyword'
        ));
    }

    /**
     * Determines if flags are a part of the search.
     *
     * @return boolean  True if search query involves flags.
     */
    public function flagSearch()
    {
        return !empty($this->_search['flag']);
    }

    /**
     * Search for either new messages (messages that have the '\Recent' flag
     * but not the '\Seen' flag) or old messages (messages that do not have
     * the '\Recent' flag).  If new messages are searched, this will clear
     * any '\Recent' or '\Unseen' flag searches.  If old messages are searched,
     * this will clear any '\Recent' flag search.
     *
     * @param boolean $newmsgs  If true, searches for new messages.  Else,
     *                          search for old messages.
     * @param array $opts       Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function newMsgs($newmsgs = true, array $opts = array())
    {
        $this->_search['new'] = $newmsgs;
        if (!empty($opts['fuzzy'])) {
            $this->_search['newfuzzy'] = true;
        }
    }

    /**
     * Search for text in the header of a message.
     *
     * @param string $header  The header field.
     * @param string $text    The search text.
     * @param boolean $not    If true, do a 'NOT' search of $text.
     * @param array $opts     Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function headerText($header, $text, $not = false,
                                array $opts = array())
    {
        if (!isset($this->_search['header'])) {
            $this->_search['header'] = array();
        }
        $this->_search['header'][] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'header' => Horde_String::upper($header),
            'text' => $text,
            'not' => $not
        ));
    }

    /**
     * Search for text in either the entire message, or just the body.
     *
     * @param string $text      The search text.
     * @param string $bodyonly  If true, only search in the body of the
     *                          message. If false, also search in the headers.
     * @param boolean $not      If true, do a 'NOT' search of $text.
     * @param array $opts       Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function text($text, $bodyonly = true, $not = false,
                         array $opts = array())
    {
        if (!isset($this->_search['text'])) {
            $this->_search['text'] = array();
        }

        $this->_search['text'][] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'not' => $not,
            'text' => $text,
            'type' => $bodyonly ? 'BODY' : 'TEXT'
        ));
    }

    /**
     * Search for messages smaller/larger than a certain size.
     *
     * @todo: Remove $not for 3.0
     *
     * @param integer $size    The size (in bytes).
     * @param boolean $larger  Search for messages larger than $size?
     * @param boolean $not     If true, do a 'NOT' search of $text.
     * @param array $opts      Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function size($size, $larger = false, $not = false,
                         array $opts = array())
    {
        if (!isset($this->_search['size'])) {
            $this->_search['size'] = array();
        }
        $this->_search['size'][$larger ? 'LARGER' : 'SMALLER'] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'not' => $not,
            'size' => (float)$size
        ));
    }

    /**
     * Search for messages within a given UID range. Only one message range
     * can be specified per query.
     *
     * @param Horde_Imap_Client_Ids $ids  The list of UIDs to search.
     * @param boolean $not                If true, do a 'NOT' search of the
     *                                    UIDs.
     * @param array $opts                 Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function ids(Horde_Imap_Client_Ids $ids, $not = false,
                        array $opts = array())
    {
        $this->_search['ids'] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'ids' => $ids,
            'not' => $not
        ));
    }

    /**
     * Search for messages within a date range.
     *
     * @param mixed $date    DateTime or Horde_Date object.
     * @param string $range  Either:
     *   - Horde_Imap_Client_Search_Query::DATE_BEFORE
     *   - Horde_Imap_Client_Search_Query::DATE_ON
     *   - Horde_Imap_Client_Search_Query::DATE_SINCE
     * @param boolean $header  If true, search using the date in the message
     *                         headers. If false, search using the internal
     *                         IMAP date (usually arrival time).
     * @param boolean $not     If true, do a 'NOT' search of the range.
     * @param array $opts      Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function dateSearch($date, $range, $header = true, $not = false,
                               array $opts = array())
    {
        if (!isset($this->_search['date'])) {
            $this->_search['date'] = array();
        }

        // We should really be storing the raw DateTime object as data,
        // but all versions of the query object have converted at this stage.
        $ob = new Horde_Imap_Client_Data_Format_Date($date);

        $this->_search['date'][] = array_filter(array(
            'date' => $ob->escape(),
            'fuzzy' => !empty($opts['fuzzy']),
            'header' => $header,
            'range' => $range,
            'not' => $not
        ));
    }

    /**
     * Search for messages within a given interval. Only one interval of each
     * type can be specified per search query. If the IMAP server supports
     * the WITHIN extension (RFC 5032), it will be used.  Otherwise, the
     * search query will be dynamically created using IMAP4rev1 search
     * terms.
     *
     * @param integer $interval  Seconds from the present.
     * @param string $range      Either:
     *   - Horde_Imap_Client_Search_Query::INTERVAL_OLDER
     *   - Horde_Imap_Client_Search_Query::INTERVAL_YOUNGER
     * @param boolean $not       If true, do a 'NOT' search.
     * @param array $opts        Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function intervalSearch($interval, $range, $not = false,
                                   array $opts = array())
    {
        if (!isset($this->_search['within'])) {
            $this->_search['within'] = array();
        }
        $this->_search['within'][$range] = array(
            'fuzzy' => !empty($opts['fuzzy']),
            'interval' => $interval,
            'not' => $not
        );
    }

    /**
     * AND queries - the contents of this query will be AND'ed (in its
     * entirety) with the contents of EACH of the queries passed in.  All
     * AND'd queries must share the same charset as this query.
     *
     * @param mixed $queries  A query, or an array of queries, to AND with the
     *                        current query.
     */
    public function andSearch($queries)
    {
        if (!isset($this->_search['and'])) {
            $this->_search['and'] = array();
        }

        if ($queries instanceof Horde_Imap_Client_Search_Query) {
            $queries = array($queries);
        }

        $this->_search['and'] = array_merge($this->_search['and'], $queries);
    }

    /**
     * OR a query - the contents of this query will be OR'ed (in its entirety)
     * with the contents of EACH of the queries passed in.  All OR'd queries
     * must share the same charset as this query.  All contents of any single
     * query will be AND'ed together.
     *
     * @param mixed $queries  A query, or an array of queries, to OR with the
     *                        current query.
     */
    public function orSearch($queries)
    {
        if (!isset($this->_search['or'])) {
            $this->_search['or'] = array();
        }

        if ($queries instanceof Horde_Imap_Client_Search_Query) {
            $queries = array($queries);
        }

        $this->_search['or'] = array_merge($this->_search['or'], $queries);
    }

    /**
     * Search for messages modified since a specific moment. The IMAP server
     * must support the CONDSTORE extension (RFC 7162) for this query to be
     * used.
     *
     * @param integer $value  The mod-sequence value.
     * @param string $name    The entry-name string.
     * @param string $type    Either 'shared', 'priv', or 'all'. Defaults to
     *                        'all'
     * @param boolean $not    If true, do a 'NOT' search.
     * @param array $opts     Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function modseq($value, $name = null, $type = null, $not = false,
                           array $opts = array())
    {
        if (!is_null($type)) {
            $type = Horde_String::lower($type);
            if (!in_array($type, array('shared', 'priv', 'all'))) {
                $type = 'all';
            }
        }

        $this->_search['modseq'] = array_filter(array(
            'fuzzy' => !empty($opts['fuzzy']),
            'name' => $name,
            'not' => $not,
            'type' => (!is_null($name) && is_null($type)) ? 'all' : $type,
            'value' => $value
        ));
    }

    /**
     * Use the results from the previous SEARCH command. The IMAP server must
     * support the SEARCHRES extension (RFC 5182) for this query to be used.
     *
     * @param boolean $not  If true, don't match the previous query.
     * @param array $opts   Additional options:
     *   - fuzzy: (boolean) If true, perform a fuzzy search. The IMAP server
     *            MUST support RFC 6203.
     */
    public function previousSearch($not = false, array $opts = array())
    {
        $this->_search['prevsearch'] = $not;
        if (!empty($opts['fuzzy'])) {
            $this->_search['prevsearchfuzzy'] = true;
        }
    }

    /* Serializable methods. */

    /**
     * Serialization.
     *
     * @return string  Serialized data.
     */
    public function serialize()
    {
        $data = array(
            // Serialized data ID.
            self::VERSION,
            $this->_search
        );

        if (!is_null($this->_charset)) {
            $data[] = $this->_charset;
        }

        return serialize($data);
    }

    /**
     * Unserialization.
     *
     * @param string $data  Serialized data.
     *
     * @throws Exception
     */
    public function unserialize($data)
    {
        $data = @unserialize($data);
        if (!is_array($data) ||
            !isset($data[0]) ||
            ($data[0] != self::VERSION)) {
            throw new Exception('Cache version change');
        }

        $this->_search = $data[1];
        if (isset($data[2])) {
            $this->_charset = $data[2];
        }
    }

}