File: Base.php

package info (click to toggle)
php-horde-imap-client 2.25.2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,780 kB
  • ctags: 2,943
  • sloc: php: 18,185; xml: 2,818; sh: 3; makefile: 2
file content (4027 lines) | stat: -rw-r--r-- 147,111 bytes parent folder | download
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
<?php
/**
 * Copyright 2008-2014 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-2014 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 */

/**
 * An abstracted API interface to IMAP backends supporting the IMAP4rev1
 * protocol (RFC 3501).
 *
 * @author    Michael Slusarz <slusarz@horde.org>
 * @category  Horde
 * @copyright 2008-2014 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 *
 * @property-read Horde_Imap_Client_Data_Capability $capability
 *                A capability object. (@since 2.24.0)
 * @property-read Horde_Imap_Client_Data_SearchCharset $search_charset
 *                A search charset object. (@since 2.24.0)
 * @property-read Horde_Imap_Client_Url $url  The URL object for the current
 *                connection parameters (@since 2.24.0)
 */
abstract class Horde_Imap_Client_Base
implements Serializable, SplObserver
{
    /** Serialized version. */
    const VERSION = 2;

    /** Cache names for miscellaneous data. */
    const CACHE_MODSEQ = '_m';
    const CACHE_SEARCH = '_s';
    /* @since 2.9.0 */
    const CACHE_SEARCHID = '_i';

    /** Cache names used exclusively within this class. @since 2.11.0 */
    const CACHE_DOWNGRADED = 'HICdg';

    /**
     * The list of fetch fields that can be cached, and their cache names.
     *
     * @var array
     */
    public $cacheFields = array(
        Horde_Imap_Client::FETCH_ENVELOPE => 'HICenv',
        Horde_Imap_Client::FETCH_FLAGS => 'HICflags',
        Horde_Imap_Client::FETCH_HEADERS => 'HIChdrs',
        Horde_Imap_Client::FETCH_IMAPDATE => 'HICdate',
        Horde_Imap_Client::FETCH_SIZE => 'HICsize',
        Horde_Imap_Client::FETCH_STRUCTURE => 'HICstruct'
    );

    /**
     * Has the internal configuration changed?
     *
     * @var boolean
     */
    public $changed = false;

    /**
     * Horde_Imap_Client is optimized for short (i.e. 1 seconds) scripts. It
     * makes heavy use of mailbox caching to save on server accesses. This
     * property should be set to false for long-running scripts, or else
     * status() data may not reflect the current state of the mailbox on the
     * server.
     *
     * @since 2.14.0
     *
     * @var boolean
     */
    public $statuscache = true;

    /**
     * The Horde_Imap_Client_Cache object.
     *
     * @var Horde_Imap_Client_Cache
     */
    protected $_cache = null;

    /**
     * Connection to the IMAP server.
     *
     * @var Horde\Socket\Client
     */
    protected $_connection = null;

    /**
     * The debug object.
     *
     * @var Horde_Imap_Client_Base_Debug
     */
    protected $_debug = null;

    /**
     * The default ports to use for a connection.
     * First element is non-secure, second is SSL.
     *
     * @var array
     */
    protected $_defaultPorts = array();

    /**
     * The fetch data object type to return.
     *
     * @var string
     */
    protected $_fetchDataClass = 'Horde_Imap_Client_Data_Fetch';

    /**
     * Cached server data.
     *
     * @var array
     */
    protected $_init;

    /**
     * Is there an active authenticated connection to the IMAP Server?
     *
     * @var boolean
     */
    protected $_isAuthenticated = false;

    /**
     * The current mailbox selection mode.
     *
     * @var integer
     */
    protected $_mode = 0;

    /**
     * Hash containing connection parameters.
     * This hash never changes.
     *
     * @var array
     */
    protected $_params = array();

    /**
     * The currently selected mailbox.
     *
     * @var Horde_Imap_Client_Mailbox
     */
    protected $_selected = null;

    /**
     * Temp array (destroyed at end of process).
     *
     * @var array
     */
    protected $_temp = array();

    /**
     * Constructor.
     *
     * @param array $params   Configuration parameters:
     * <pre>
     * - cache: (array) If set, caches data from fetch(), search(), and
     *          thread() calls. Requires the horde/Cache package to be
     *          installed. The array can contain the following keys (see
     *          Horde_Imap_Client_Cache for default values):
     *   - backend: [REQUIRED (or cacheob)] (Horde_Imap_Client_Cache_Backend)
     *              Backend cache driver [@since 2.9.0].
     *   - fetch_ignore: (array) A list of mailboxes to ignore when storing
     *                   fetch data.
     *   - fields: (array) The fetch criteria to cache. If not defined, all
     *             cacheable data is cached. The following is a list of
     *             criteria that can be cached:
     *     - Horde_Imap_Client::FETCH_ENVELOPE
     *     - Horde_Imap_Client::FETCH_FLAGS
     *       Only if server supports CONDSTORE extension
     *     - Horde_Imap_Client::FETCH_HEADERS
     *       Only for queries that specifically request caching
     *     - Horde_Imap_Client::FETCH_IMAPDATE
     *     - Horde_Imap_Client::FETCH_SIZE
     *     - Horde_Imap_Client::FETCH_STRUCTURE
     * - capability_ignore: (array) A list of IMAP capabilites to ignore, even
     *                      if they are supported on the server.
     *                      DEFAULT: No supported capabilities are ignored.
     * - comparator: (string) The search comparator to use instead of the
     *               default server comparator. See setComparator() for
     *               format.
     *               DEFAULT: Use the server default
     * - debug: (string) If set, will output debug information to the stream
     *          provided. The value can be any PHP supported wrapper that can
     *          be opened via PHP's fopen() function.
     *          DEFAULT: No debug output
     * - hostspec: (string) The hostname or IP address of the server.
     *             DEFAULT: 'localhost'
     * - id: (array) Send ID information to the server (only if server
     *       supports the ID extension). An array with the keys as the fields
     *       to send and the values being the associated values. See RFC 2971
     *       [3.3] for a list of standard field values.
     *       DEFAULT: No info sent to server
     * - lang: (array) A list of languages (in priority order) to be used to
     *         display human readable messages.
     *         DEFAULT: Messages output in IMAP server default language
     * - password: (mixed) The user password. Either a string or a
     *             Horde_Imap_Client_Base_Password object [@since 2.14.0].
     * - port: (integer) The server port to which we will connect.
     *         DEFAULT: 143 (imap or imap w/TLS) or 993 (imaps)
     * - secure: (string) Use SSL or TLS to connect. Values:
     *   - false (No encryption)
     *   - 'ssl' (Auto-detect SSL version)
     *   - 'sslv2' (Force SSL version 3)
     *   - 'sslv3' (Force SSL version 2)
     *   - 'tls' (TLS; started via protocol-level negotation over
     *     unencrypted channel; RECOMMENDED way of initiating secure
     *     connection)
     *   - 'tlsv1' (TLS direct version 1.x connection to server) [@since
     *     2.16.0]
     *   - true (TLS if available/necessary) [@since 2.15.0]
     *     DEFAULT: false
     * - timeout: (integer)  Connection timeout, in seconds.
     *            DEFAULT: 30 seconds
     * - username: (string) [REQUIRED] The username.
     * </pre>
     */
    public function __construct(array $params = array())
    {
        if (!isset($params['username'])) {
            throw new InvalidArgumentException('Horde_Imap_Client requires a username.');
        }

        $this->_setInit();

        // Default values.
        $params = array_merge(array(
            'hostspec' => 'localhost',
            'secure' => false,
            'timeout' => 30
        ), array_filter($params));

        if (!isset($params['port'])) {
            $params['port'] = (!empty($params['secure']) && in_array($params['secure'], array('ssl', 'sslv2', 'sslv3'), true))
                ? $this->_defaultPorts[1]
                : $this->_defaultPorts[0];
        }

        if (empty($params['cache'])) {
            $params['cache'] = array('fields' => array());
        } elseif (empty($params['cache']['fields'])) {
            $params['cache']['fields'] = $this->cacheFields;
        } else {
            $params['cache']['fields'] = array_flip($params['cache']['fields']);
        }

        if (empty($params['cache']['fetch_ignore'])) {
            $params['cache']['fetch_ignore'] = array();
        }

        $this->_params = $params;
        if (isset($params['password'])) {
            $this->setParam('password', $params['password']);
        }

        $this->changed = true;
        $this->_initOb();
    }

    /**
     * Get encryption key.
     *
     * @deprecated  Pass callable into 'password' parameter instead.
     *
     * @return string  The encryption key.
     */
    protected function _getEncryptKey()
    {
        if (is_callable($ekey = $this->getParam('encryptKey'))) {
            return call_user_func($ekey);
        }

        throw new InvalidArgumentException('encryptKey parameter is not a valid callback.');
    }

    /**
     * Do initialization tasks.
     */
    protected function _initOb()
    {
        register_shutdown_function(array($this, 'shutdown'));
        $this->_debug = ($debug = $this->getParam('debug'))
            ? new Horde_Imap_Client_Base_Debug($debug)
            : new Horde_Support_Stub();

        // @todo: Remove (BC purposes)
        if (isset($this->_init['capability']) &&
            !is_object($this->_init['capability'])) {
            $this->_setInit('capability');
        }

        foreach (array('capability', 'search_charset') as $val) {
            if (isset($this->_init[$val])) {
                $this->_init[$val]->attach($this);
            }
        }
    }

    /**
     * Shutdown actions.
     */
    public function shutdown()
    {
        $this->logout();
    }

    /**
     * This object can not be cloned.
     */
    public function __clone()
    {
        throw new LogicException('Object cannot be cloned.');
    }

    /**
     */
    public function update(SplSubject $subject)
    {
        if (($subject instanceof Horde_Imap_Client_Data_Capability) ||
            ($subject instanceof Horde_Imap_Client_Data_SearchCharset)) {
            $this->changed = true;
        }
    }

    /**
     */
    public function serialize()
    {
        return serialize(array(
            'i' => $this->_init,
            'p' => $this->_params,
            'v' => self::VERSION
        ));
    }

    /**
     */
    public function unserialize($data)
    {
        $data = @unserialize($data);
        if (!is_array($data) ||
            !isset($data['v']) ||
            ($data['v'] != self::VERSION)) {
            throw new Exception('Cache version change');
        }

        $this->_init = $data['i'];
        $this->_params = $data['p'];

        $this->_initOb();
    }

    /**
     */
    public function __get($name)
    {
        switch ($name) {
        case 'capability':
            return $this->_capability();

        case 'search_charset':
            if (!isset($this->_init['search_charset'])) {
                $this->_init['search_charset'] = new Horde_Imap_Client_Data_SearchCharset();
               $this->_init['search_charset']->attach($this);
            }
            $this->_init['search_charset']->setBaseOb($this);
            return $this->_init['search_charset'];

        case 'url':
            $url = new Horde_Imap_Client_Url();
            $url->hostspec = $this->getParam('hostspec');
            $url->port = $this->getParam('port');
            $url->protocol = 'imap';
            return $url;
        }
    }

    /**
     * Set an initialization value.
     *
     * @param string $key  The initialization key. If null, resets all keys.
     * @param mixed $val   The cached value. If null, removes the key.
     */
    public function _setInit($key = null, $val = null)
    {
        if (is_null($key)) {
            $this->_init = array();
        } elseif (is_null($val)) {
            unset($this->_init[$key]);
        } else {
            switch ($key) {
            case 'capability':
                if ($ci = $this->getParam('capability_ignore')) {
                    $ignored = array();

                    foreach ($ci as $val2) {
                        $c = explode('=', $val2);

                        if ($val->query($c[0], isset($c[1]) ? $c[1] : null)) {
                            $ignored[] = $val2;
                            $val->remove($c[0], isset($c[1]) ? $c[1] : null);
                        }
                    }

                    if ($this->_debug->debug && !empty($ignored)) {
                        $this->_debug->info(sprintf(
                            'CONFIG: IGNORING these IMAP capabilities: %s',
                            implode(', ', $ignored)
                        ));
                    }
                }

                $val->attach($this);
                break;
            }

            /* Nothing has changed. */
            if (isset($this->_init[$key]) && ($this->_init[$key] === $val)) {
                return;
            }

            $this->_init[$key] = $val;
        }

        $this->changed = true;
    }

    /**
     * Initialize the Horde_Imap_Client_Cache object, if necessary.
     *
     * @param boolean $current  If true, we are going to update the currently
     *                          selected mailbox. Add an additional check to
     *                          see if caching is available in current
     *                          mailbox.
     *
     * @return boolean  Returns true if caching is enabled.
     */
    protected function _initCache($current = false)
    {
        $c = $this->getParam('cache');

        if (empty($c['fields'])) {
            return false;
        }

        if (is_null($this->_cache)) {
            if (isset($c['backend'])) {
                $backend = $c['backend'];
            } elseif (isset($c['cacheob'])) {
                /* Deprecated */
                $backend = new Horde_Imap_Client_Cache_Backend_Cache($c);
            } else {
                return false;
            }

            $this->_cache = new Horde_Imap_Client_Cache(array(
                'backend' => $backend,
                'baseob' => $this,
                'debug' => $this->_debug
            ));
        }

        return $current
            /* If UIDs are labeled as not sticky, don't cache since UIDs will
             * change on every access. */
            ? !($this->_mailboxOb()->getStatus(Horde_Imap_Client::STATUS_UIDNOTSTICKY))
            : true;
    }

    /**
     * Returns a value from the internal params array.
     *
     * @param string $key  The param key.
     *
     * @return mixed  The param value, or null if not found.
     */
    public function getParam($key)
    {
        /* Passwords may be stored encrypted. */
        switch ($key) {
        case 'password':
            if (isset($this->_params[$key]) &&
                ($this->_params[$key] instanceof Horde_Imap_Client_Base_Password)) {
                return $this->_params[$key]->getPassword();
            }

            // DEPRECATED
            if (!empty($this->_params['_passencrypt'])) {
                try {
                    $secret = new Horde_Secret();
                    return $secret->read($this->_getEncryptKey(), $this->_params['password']);
                } catch (Exception $e) {
                    return null;
                }
            }
            break;
        }

        return isset($this->_params[$key])
            ? $this->_params[$key]
            : null;
    }

    /**
     * Sets a configuration parameter value.
     *
     * @param string $key  The param key.
     * @param mixed $val   The param value.
     */
    public function setParam($key, $val)
    {
        switch ($key) {
        case 'password':
            if ($val instanceof Horde_Imap_Client_Base_Password) {
                break;
            }

            // DEPRECATED: Encrypt password.
            try {
                $encrypt_key = $this->_getEncryptKey();
                if (strlen($encrypt_key)) {
                    $secret = new Horde_Secret();
                    $val = $secret->write($encrypt_key, $val);
                    $this->_params['_passencrypt'] = true;
                }
            } catch (Exception $e) {}
            break;
        }

        $this->_params[$key] = $val;
        $this->changed = true;
    }

    /**
     * Returns the Horde_Imap_Client_Cache object used, if available.
     *
     * @return mixed  Either the cache object or null.
     */
    public function getCache()
    {
        $this->_initCache();
        return $this->_cache;
    }

    /**
     * Returns the correct IDs object for use with this driver.
     *
     * @param mixed $ids         See add().
     * @param boolean $sequence  Are $ids message sequence numbers?
     *
     * @return Horde_Imap_Client_Ids  The IDs object.
     */
    public function getIdsOb($ids = null, $sequence = false)
    {
        return new Horde_Imap_Client_Ids($ids, $sequence);
    }

    /**
     * Returns whether the IMAP server supports the given capability
     * (See RFC 3501 [6.1.1]).
     *
     * @deprecated  Use $capability property instead.
     *
     * @param string $capability  The capability string to query.
     *
     * @return mixed  True if the server supports the queried capability,
     *                false if it doesn't, or an array if the capability can
     *                contain multiple values.
     */
    public function queryCapability($capability)
    {
        try {
            $c = $this->_capability();
            return ($out = $c->getParams($capability))
                ? $out
                : $c->query($capability);
        } catch (Horde_Imap_Client_Exception $e) {
            return false;
        }
    }

    /**
     * Get CAPABILITY information from the IMAP server.
     *
     * @deprecated  Use $capability property instead.
     *
     * @return array  The capability array.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function capability()
    {
        return $this->_capability()->toArray();
    }

    /**
     * Query server capability.
     *
     * Required because internal code can't call capability via magic method
     * directly - it may not exist yet, the creation code may call capability
     * recursively, and __get() doesn't allow recursive calls to the same
     * property (chicken/egg issue).
     *
     * @return mixed  The capability object if no arguments provided. If
     *                arguments are provided, they are passed to the query()
     *                method and this value is returned.
     * @throws Horde_Imap_Client_Exception
     */
    protected function _capability()
    {
        if (!isset($this->_init['capability'])) {
            $this->_initCapability();
        }

        return ($args = func_num_args())
            ? $this->_init['capability']->query(func_get_arg(0), ($args > 1) ? func_get_arg(1) : null)
            : $this->_init['capability'];
    }

    /**
     * Retrieve capability information from the IMAP server.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _initCapability();

    /**
     * Send a NOOP command (RFC 3501 [6.1.2]).
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function noop()
    {
        if (!$this->_connection) {
            // NOOP can be called in the unauthenticated state.
            $this->_connect();
        }
        $this->_noop();
    }

    /**
     * Send a NOOP command.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _noop();

    /**
     * Get the NAMESPACE information from the IMAP server (RFC 2342).
     *
     * @param array $additional  If the server supports namespaces, any
     *                           additional namespaces to add to the
     *                           namespace list that are not broadcast by
     *                           the server. The namespaces must be UTF-8
     *                           strings.
     * @param array $opts        Additional options:
     *   - ob_return: (boolean) If true, returns a
     *                Horde_Imap_Client_Namespace_List object instead of an
     *                array.
     *
     * @return mixed  A Horde_Imap_Client_Namespace_List object if
     *                'ob_return', is true. Otherwise, an array of namespace
     *                objects (@deprecated) with the name as the key (UTF-8)
     *                and the following values:
     * <pre>
     *  - delimiter: (string) The namespace delimiter.
     *  - hidden: (boolean) Is this a hidden namespace?
     *  - name: (string) The namespace name (UTF-8).
     *  - translation: (string) Returns the translated name of the namespace
     *                 (UTF-8). Requires RFC 5255 and a previous call to
     *                 setLanguage().
     *  - type: (integer) The namespace type. Either:
     *    - Horde_Imap_Client::NS_PERSONAL
     *    - Horde_Imap_Client::NS_OTHER
     *    - Horde_Imap_Client::NS_SHARED
     * </pre>
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getNamespaces(
        array $additional = array(), array $opts = array()
    )
    {
        $additional = array_map('strval', $additional);
        $sig = hash(
            (PHP_MINOR_VERSION >= 4) ? 'fnv132' : 'sha1',
            json_encode($additional) . intval(empty($opts['ob_return']))
        );

        if (isset($this->_init['namespace'][$sig])) {
            $ns = $this->_init['namespace'][$sig];
        } else {
            $this->login();

            $ns = $this->_getNamespaces();

            /* Skip namespaces if we have already auto-detected them. Also,
             * hidden namespaces cannot be empty. */
            $to_process = array_diff(array_filter($additional, 'strlen'), array_map('strlen', iterator_to_array($ns)));
            if (!empty($to_process)) {
                foreach ($this->listMailboxes($to_process, Horde_Imap_Client::MBOX_ALL, array('delimiter' => true)) as $val) {
                    $ob = new Horde_Imap_Client_Data_Namespace();
                    $ob->delimiter = $val['delimiter'];
                    $ob->hidden = true;
                    $ob->name = $val;
                    $ob->type = $ob::NS_SHARED;
                    $ns[$val] = $ob;
                }
            }

            if (!count($ns)) {
                /* This accurately determines the namespace information of the
                 * base namespace if the NAMESPACE command is not supported.
                 * See: RFC 3501 [6.3.8] */
                $mbox = $this->listMailboxes('', Horde_Imap_Client::MBOX_ALL, array('delimiter' => true));
                $first = reset($mbox);

                $ob = new Horde_Imap_Client_Data_Namespace();
                $ob->delimiter = $first['delimiter'];
                $ns[''] = $ob;
            }

            $this->_init['namespace'][$sig] = $ns;
            $this->_setInit('namespace', $this->_init['namespace']);
        }

        if (!empty($opts['ob_return'])) {
            return $ns;
        }

        /* @todo Remove for 3.0 */
        $out = array();
        foreach ($ns as $key => $val) {
            $out[$key] = array(
                'delimiter' => $val->delimiter,
                'hidden' => $val->hidden,
                'name' => $val->name,
                'translation' => $val->translation,
                'type' => $val->type
            );
        }

        return $out;
    }

    /**
     * Get the NAMESPACE information from the IMAP server.
     *
     * @return Horde_Imap_Client_Namespace_List  Namespace list object.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getNamespaces();

    /**
     * Display if connection to the server has been secured via TLS or SSL.
     *
     * @return boolean  True if the IMAP connection is secured.
     */
    public function isSecureConnection()
    {
        return ($this->_connection && $this->_connection->secure);
    }

    /**
     * Connect to the remote server.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _connect();

    /**
     * Return a list of alerts that MUST be presented to the user (RFC 3501
     * [7.1]).
     *
     * @return array  An array of alert messages.
     */
    abstract public function alerts();

    /**
     * Login to the IMAP server.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function login()
    {
        if (!$this->_isAuthenticated && $this->_login()) {
            if ($this->getParam('id')) {
                try {
                    $this->sendID();
                } catch (Horde_Imap_Client_Exception_NoSupportExtension $e) {
                    // Ignore if server doesn't support ID extension.
                }
            }

            if ($this->getParam('comparator')) {
                try {
                    $this->setComparator();
                } catch (Horde_Imap_Client_Exception_NoSupportExtension $e) {
                    // Ignore if server doesn't support I18NLEVEL=2
                }
            }
        }

        $this->_isAuthenticated = true;
    }

    /**
     * Login to the IMAP server.
     *
     * @return boolean  Return true if global login tasks should be run.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _login();

    /**
     * Logout from the IMAP server (see RFC 3501 [6.1.3]).
     */
    public function logout()
    {
        if ($this->_isAuthenticated && $this->_connection->connected) {
            $this->_logout();
            $this->_connection->close();
        }

        $this->_connection = $this->_selected = null;
        $this->_isAuthenticated = false;
        $this->_mode = 0;
    }

    /**
     * Logout from the IMAP server (see RFC 3501 [6.1.3]).
     */
    abstract protected function _logout();

    /**
     * Send ID information to the IMAP server (RFC 2971).
     *
     * @param array $info  Overrides the value of the 'id' param and sends
     *                     this information instead.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function sendID($info = null)
    {
        if (!$this->_capability('ID')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ID');
        }

        $this->_sendID(is_null($info) ? ($this->getParam('id') ?: array()) : $info);
    }

    /**
     * Send ID information to the IMAP server (RFC 2971).
     *
     * @param array $info  The information to send to the server.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _sendID($info);

    /**
     * Return ID information from the IMAP server (RFC 2971).
     *
     * @return array  An array of information returned, with the keys as the
     *                'field' and the values as the 'value'.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function getID()
    {
        if (!$this->_capability('ID')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ID');
        }

        return $this->_getID();
    }

    /**
     * Return ID information from the IMAP server (RFC 2971).
     *
     * @return array  An array of information returned, with the keys as the
     *                'field' and the values as the 'value'.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getID();

    /**
     * Sets the preferred language for server response messages (RFC 5255).
     *
     * @param array $langs  Overrides the value of the 'lang' param and sends
     *                      this list of preferred languages instead. The
     *                      special string 'i-default' can be used to restore
     *                      the language to the server default.
     *
     * @return string  The language accepted by the server, or null if the
     *                 default language is used.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function setLanguage($langs = null)
    {
        $lang = null;

        if ($this->_capability('LANGUAGE')) {
            $lang = is_null($langs)
                ? $this->getParam('lang')
                : $langs;
        }

        return is_null($lang)
            ? null
            : $this->_setLanguage($lang);
    }

    /**
     * Sets the preferred language for server response messages (RFC 5255).
     *
     * @param array $langs  The preferred list of languages.
     *
     * @return string  The language accepted by the server, or null if the
     *                 default language is used.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _setLanguage($langs);

    /**
     * Gets the preferred language for server response messages (RFC 5255).
     *
     * @param array $list  If true, return the list of available languages.
     *
     * @return mixed  If $list is true, the list of languages available on the
     *                server (may be empty). If false, the language used by
     *                the server, or null if the default language is used.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getLanguage($list = false)
    {
        if (!$this->_capability('LANGUAGE')) {
            return $list ? array() : null;
        }

        return $this->_getLanguage($list);
    }

    /**
     * Gets the preferred language for server response messages (RFC 5255).
     *
     * @param array $list  If true, return the list of available languages.
     *
     * @return mixed  If $list is true, the list of languages available on the
     *                server (may be empty). If false, the language used by
     *                the server, or null if the default language is used.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getLanguage($list);

    /**
     * Open a mailbox.
     *
     * @param mixed $mailbox  The mailbox to open. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param integer $mode   The access mode. Either
     *   - Horde_Imap_Client::OPEN_READONLY
     *   - Horde_Imap_Client::OPEN_READWRITE
     *   - Horde_Imap_Client::OPEN_AUTO
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function openMailbox($mailbox, $mode = Horde_Imap_Client::OPEN_AUTO)
    {
        $this->login();

        $change = false;
        $mailbox = Horde_Imap_Client_Mailbox::get($mailbox);

        if ($mode == Horde_Imap_Client::OPEN_AUTO) {
            if (is_null($this->_selected) ||
                !$mailbox->equals($this->_selected)) {
                $mode = Horde_Imap_Client::OPEN_READONLY;
                $change = true;
            }
        } else {
            $change = (is_null($this->_selected) ||
                       !$mailbox->equals($this->_selected) ||
                       ($mode != $this->_mode));
        }

        if ($change) {
            $this->_openMailbox($mailbox, $mode);
            $this->_mailboxOb()->open = true;
            if ($this->_initCache(true)) {
                $this->_condstoreSync();
            }
        }
    }

    /**
     * Open a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to open.
     * @param integer $mode                       The access mode.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _openMailbox(Horde_Imap_Client_Mailbox $mailbox,
                                             $mode);

    /**
     * Called when the selected mailbox is changed.
     *
     * @param mixed $mailbox  The selected mailbox or null.
     * @param integer $mode   The access mode.
     */
    protected function _changeSelected($mailbox = null, $mode = null)
    {
        $this->_mode = $mode;
        if (is_null($mailbox)) {
            $this->_selected = null;
        } else {
            $this->_selected = clone $mailbox;
            $this->_mailboxOb()->reset();
        }
    }

    /**
     * Return the Horde_Imap_Client_Base_Mailbox object.
     *
     * @param string $mailbox  The mailbox name. Defaults to currently
     *                         selected mailbox.
     *
     * @return Horde_Imap_Client_Base_Mailbox  Mailbox object.
     */
    protected function _mailboxOb($mailbox = null)
    {
        $name = is_null($mailbox)
            ? strval($this->_selected)
            : strval($mailbox);

        if (!isset($this->_temp['mailbox_ob'][$name])) {
            $this->_temp['mailbox_ob'][$name] = new Horde_Imap_Client_Base_Mailbox();
        }

        return $this->_temp['mailbox_ob'][$name];
    }

    /**
     * Return the currently opened mailbox and access mode.
     *
     * @return mixed  Null if no mailbox selected, or an array with two
     *                elements:
     *   - mailbox: (Horde_Imap_Client_Mailbox) The mailbox object.
     *   - mode: (integer) Current mode.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function currentMailbox()
    {
        return is_null($this->_selected)
            ? null
            : array(
                'mailbox' => clone $this->_selected,
                'mode' => $this->_mode
            );
    }

    /**
     * Create a mailbox.
     *
     * @param mixed $mailbox  The mailbox to create. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param array $opts     Additional options:
     *   - special_use: (array) An array of special-use flags to mark the
     *                  mailbox with. The server MUST support RFC 6154.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function createMailbox($mailbox, array $opts = array())
    {
        $this->login();

        if (!$this->_capability('CREATE-SPECIAL-USE')) {
            unset($opts['special_use']);
        }

        $this->_createMailbox(Horde_Imap_Client_Mailbox::get($mailbox), $opts);
    }

    /**
     * Create a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to create.
     * @param array $opts                         Additional options. See
     *                                            createMailbox().
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _createMailbox(Horde_Imap_Client_Mailbox $mailbox,
                                               $opts);

    /**
     * Delete a mailbox.
     *
     * @param mixed $mailbox  The mailbox to delete. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function deleteMailbox($mailbox)
    {
        $this->login();

        $mailbox = Horde_Imap_Client_Mailbox::get($mailbox);

        $this->_deleteMailbox($mailbox);
        $this->_deleteMailboxPost($mailbox);
    }

    /**
     * Delete a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to delete.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _deleteMailbox(Horde_Imap_Client_Mailbox $mailbox);

    /**
     * Actions to perform after a mailbox delete.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The deleted mailbox.
     */
    protected function _deleteMailboxPost(Horde_Imap_Client_Mailbox $mailbox)
    {
        /* Delete mailbox caches. */
        if ($this->_initCache()) {
            $this->_cache->deleteMailbox($mailbox);
        }
        unset($this->_temp['mailbox_ob'][strval($mailbox)]);

        /* Unsubscribe from mailbox. */
        try {
            $this->subscribeMailbox($mailbox, false);
        } catch (Horde_Imap_Client_Exception $e) {
            // Ignore failed unsubscribe request
        }
    }

    /**
     * Rename a mailbox.
     *
     * @param mixed $old  The old mailbox name. Either a
     *                    Horde_Imap_Client_Mailbox object or a string (UTF-8).
     * @param mixed $new  The new mailbox name. Either a
     *                    Horde_Imap_Client_Mailbox object or a string (UTF-8).
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function renameMailbox($old, $new)
    {
        // Login will be handled by first listMailboxes() call.

        $old = Horde_Imap_Client_Mailbox::get($old);
        $new = Horde_Imap_Client_Mailbox::get($new);

        /* Check if old mailbox(es) were subscribed to. */
        $base = $this->listMailboxes($old, Horde_Imap_Client::MBOX_SUBSCRIBED, array('delimiter' => true));
        if (empty($base)) {
            $base = $this->listMailboxes($old, Horde_Imap_Client::MBOX_ALL, array('delimiter' => true));
            $base = reset($base);
            $subscribed = array();
        } else {
            $base = reset($base);
            $subscribed = array($base['mailbox']);
        }

        $all_mboxes = array($base['mailbox']);
        if (strlen($base['delimiter'])) {
            $search = $old->list_escape . $base['delimiter'] . '*';
            $all_mboxes = array_merge($all_mboxes, $this->listMailboxes($search, Horde_Imap_Client::MBOX_ALL, array('flat' => true)));
            $subscribed = array_merge($subscribed, $this->listMailboxes($search, Horde_Imap_Client::MBOX_SUBSCRIBED, array('flat' => true)));
        }

        $this->_renameMailbox($old, $new);

        /* Delete mailbox actions. */
        foreach ($all_mboxes as $val) {
            $this->_deleteMailboxPost($val);
        }

        foreach ($subscribed as $val) {
            try {
                $this->subscribeMailbox(new Horde_Imap_Client_Mailbox(substr_replace($val, $new, 0, strlen($old))));
            } catch (Horde_Imap_Client_Exception $e) {
                // Ignore failed subscription requests
            }
        }
    }

    /**
     * Rename a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $old  The old mailbox name.
     * @param Horde_Imap_Client_Mailbox $new  The new mailbox name.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _renameMailbox(Horde_Imap_Client_Mailbox $old,
                                               Horde_Imap_Client_Mailbox $new);

    /**
     * Manage subscription status for a mailbox.
     *
     * @param mixed $mailbox      The mailbox to [un]subscribe to. Either a
     *                            Horde_Imap_Client_Mailbox object or a string
     *                            (UTF-8).
     * @param boolean $subscribe  True to subscribe, false to unsubscribe.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function subscribeMailbox($mailbox, $subscribe = true)
    {
        $this->login();
        $this->_subscribeMailbox(Horde_Imap_Client_Mailbox::get($mailbox), (bool)$subscribe);
    }

    /**
     * Manage subscription status for a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to [un]subscribe
     *                                            to.
     * @param boolean $subscribe                  True to subscribe, false to
     *                                            unsubscribe.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _subscribeMailbox(Horde_Imap_Client_Mailbox $mailbox,
                                                  $subscribe);

    /**
     * Obtain a list of mailboxes matching a pattern.
     *
     * @param mixed $pattern   The mailbox search pattern(s) (see RFC 3501
     *                         [6.3.8] for the format). A UTF-8 string or an
     *                         array of strings. If a Horde_Imap_Client_Mailbox
     *                         object is given, it is escaped (i.e. wildcard
     *                         patterns are converted to return the miminal
     *                         number of matches possible).
     * @param integer $mode    Which mailboxes to return.  Either:
     *   - Horde_Imap_Client::MBOX_SUBSCRIBED
     *     Return subscribed mailboxes.
     *   - Horde_Imap_Client::MBOX_SUBSCRIBED_EXISTS
     *     Return subscribed mailboxes that exist on the server.
     *   - Horde_Imap_Client::MBOX_UNSUBSCRIBED
     *     Return unsubscribed mailboxes.
     *   - Horde_Imap_Client::MBOX_ALL
     *     Return all mailboxes regardless of subscription status.
     *   - Horde_Imap_Client::MBOX_ALL_SUBSCRIBED (@since 2.23.0)
     *     Return all mailboxes regardless of subscription status, and ensure
     *     the '\subscribed' attribute is set if mailbox is subscribed
     *     (implies 'attributes' option is true).
     * @param array $options   Additional options:
     * <pre>
     *   - attributes: (boolean) If true, return attribute information under
     *                 the 'attributes' key.
     *                 DEFAULT: Do not return this information.
     *   - children: (boolean) Tell server to return children attribute
     *               information (\HasChildren, \HasNoChildren). Requires the
     *               LIST-EXTENDED extension to guarantee this information is
     *               returned. Server MAY return this attribute without this
     *               option, or if the CHILDREN extension is available, but it
     *               is not guaranteed.
     *               DEFAULT: false
     *   - flat: (boolean) If true, return a flat list of mailbox names only.
     *           Overrides the 'attributes' option.
     *           DEFAULT: Do not return flat list.
     *   - recursivematch: (boolean) Force the server to return information
     *                     about parent mailboxes that don't match other
     *                     selection options, but have some sub-mailboxes that
     *                     do. Information about children is returned in the
     *                     CHILDINFO extended data item ('extended'). Requires
     *                     the LIST-EXTENDED extension.
     *                     DEFAULT: false
     *   - remote: (boolean) Tell server to return mailboxes that reside on
     *             another server. Requires the LIST-EXTENDED extension.
     *             DEFAULT: false
     *   - special_use: (boolean) Tell server to return special-use attribute
     *                  information (see Horde_Imap_Client SPECIALUSE_*
     *                  constants). Server must support the SPECIAL-USE return
     *                  option for this setting to have any effect.
     *                  DEFAULT: false
     *   - status: (integer) Tell server to return status information. The
     *             value is a bitmask that may contain any of:
     *     - Horde_Imap_Client::STATUS_MESSAGES
     *     - Horde_Imap_Client::STATUS_RECENT
     *     - Horde_Imap_Client::STATUS_UIDNEXT
     *     - Horde_Imap_Client::STATUS_UIDVALIDITY
     *     - Horde_Imap_Client::STATUS_UNSEEN
     *     - Horde_Imap_Client::STATUS_HIGHESTMODSEQ
     *     DEFAULT: 0
     *   - sort: (boolean) If true, return a sorted list of mailboxes?
     *           DEFAULT: Do not sort the list.
     *   - sort_delimiter: (string) If 'sort' is true, this is the delimiter
     *                     used to sort the mailboxes.
     *                     DEFAULT: '.'
     * </pre>
     *
     * @return array  If 'flat' option is true, the array values are a list
     *                of Horde_Imap_Client_Mailbox objects. Otherwise, the
     *                keys are UTF-8 mailbox names and the values are arrays
     *                with these keys:
     *   - attributes: (array) List of lower-cased attributes [only if
     *                 'attributes' option is true].
     *   - delimiter: (string) The delimiter for the mailbox.
     *   - extended: (TODO) TODO [only if 'recursivematch' option is true and
     *               LIST-EXTENDED extension is supported on the server].
     *   - mailbox: (Horde_Imap_Client_Mailbox) The mailbox object.
     *   - status: (array) See status() [only if 'status' option is true].
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function listMailboxes($pattern,
                                  $mode = Horde_Imap_Client::MBOX_ALL,
                                  array $options = array())
    {
        $this->login();

        $pattern = is_array($pattern)
            ? array_unique($pattern)
            : array($pattern);

        /* Prepare patterns. */
        $plist = array();
        foreach ($pattern as $val) {
            if ($val instanceof Horde_Imap_Client_Mailbox) {
                $val = $val->list_escape;
            }
            $plist[] = Horde_Imap_Client_Mailbox::get(preg_replace(
                array("/\*{2,}/", "/\%{2,}/"),
                array('*', '%'),
                Horde_Imap_Client_Utf7imap::Utf8ToUtf7Imap($val)
            ), true);
        }

        if (isset($options['special_use']) &&
            !$this->_capability('SPECIAL-USE')) {
            unset($options['special_use']);
        }

        $ret = $this->_listMailboxes($plist, $mode, $options);

        if (!empty($options['status']) &&
            !$this->_capability('LIST-STATUS')) {
            foreach ($this->status(array_keys($ret), $options['status']) as $key => $val) {
                $ret[$key]['status'] = $val;
            }
        }

        if (empty($options['sort'])) {
            return $ret;
        }

        $list_ob = new Horde_Imap_Client_Mailbox_List(empty($options['flat']) ? array_keys($ret) : $ret);
        $sorted = $list_ob->sort(array(
            'delimiter' => empty($options['sort_delimiter']) ? '.' : $options['sort_delimiter']
        ));

        if (!empty($options['flat'])) {
            return $sorted;
        }

        $out = array();
        foreach ($sorted as $val) {
            $out[$val] = $ret[$val];
        }

        return $out;
    }

    /**
     * Obtain a list of mailboxes matching a pattern.
     *
     * @param array $pattern  The mailbox search patterns
     *                        (Horde_Imap_Client_Mailbox objects).
     * @param integer $mode   Which mailboxes to return.
     * @param array $options  Additional options.
     *
     * @return array  See listMailboxes().
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _listMailboxes($pattern, $mode, $options);

    /**
     * Obtain status information for a mailbox.
     *
     * @param mixed $mailbox  The mailbox(es) to query. Either a
     *                        Horde_Imap_Client_Mailbox object, a string
     *                        (UTF-8), or an array of objects/strings (since
     *                        2.10.0).
     * @param integer $flags  A bitmask of information requested from the
     *                        server. Allowed flags:
     * <pre>
     *   - Horde_Imap_Client::STATUS_MESSAGES
     *     Return key: messages
     *     Return format: (integer) The number of messages in the mailbox.
     *
     *   - Horde_Imap_Client::STATUS_RECENT
     *     Return key: recent
     *     Return format: (integer) The number of messages with the \Recent
     *                    flag set as currently reported in the mailbox
     *
     *   - Horde_Imap_Client::STATUS_RECENT_TOTAL
     *     Return key: recent_total
     *     Return format: (integer) The number of messages with the \Recent
     *                    flag set. This returns the total number of messages
     *                    that have been marked as recent in this mailbox
     *                    since the PHP process began. (since 2.12.0)
     *
     *   - Horde_Imap_Client::STATUS_UIDNEXT
     *     Return key: uidnext
     *     Return format: (integer) The next UID to be assigned in the
     *                    mailbox. Only returned if the server automatically
     *                    provides the data.
     *
     *   - Horde_Imap_Client::STATUS_UIDNEXT_FORCE
     *     Return key: uidnext
     *     Return format: (integer) The next UID to be assigned in the
     *                    mailbox. This option will always determine this
     *                    value, even if the server does not automatically
     *                    provide this data.
     *
     *   - Horde_Imap_Client::STATUS_UIDVALIDITY
     *     Return key: uidvalidity
     *     Return format: (integer) The unique identifier validity of the
     *                    mailbox.
     *
     *   - Horde_Imap_Client::STATUS_UNSEEN
     *     Return key: unseen
     *     Return format: (integer) The number of messages which do not have
     *                    the \Seen flag set.
     *
     *   - Horde_Imap_Client::STATUS_FIRSTUNSEEN
     *     Return key: firstunseen
     *     Return format: (integer) The sequence number of the first unseen
     *                    message in the mailbox.
     *
     *   - Horde_Imap_Client::STATUS_FLAGS
     *     Return key: flags
     *     Return format: (array) The list of defined flags in the mailbox
     *                    (all flags are in lowercase).
     *
     *   - Horde_Imap_Client::STATUS_PERMFLAGS
     *     Return key: permflags
     *     Return format: (array) The list of flags that a client can change
     *                    permanently (all flags are in lowercase).
     *
     *   - Horde_Imap_Client::STATUS_HIGHESTMODSEQ
     *     Return key: highestmodseq
     *     Return format: (integer) If the server supports the CONDSTORE
     *                    IMAP extension, this will be the highest
     *                    mod-sequence value of all messages in the mailbox.
     *                    Else 0 if CONDSTORE not available or the mailbox
     *                    does not support mod-sequences.
     *
     *   - Horde_Imap_Client::STATUS_SYNCMODSEQ
     *     Return key: syncmodseq
     *     Return format: (integer) If caching, and the server supports the
     *                    CONDSTORE IMAP extension, this is the cached
     *                    mod-sequence value of the mailbox when it was opened
     *                    for the first time in this access. Will be null if
     *                    not caching, CONDSTORE not available, or the mailbox
     *                    does not support mod-sequences.
     *
     *   - Horde_Imap_Client::STATUS_SYNCFLAGUIDS
     *     Return key: syncflaguids
     *     Return format: (Horde_Imap_Client_Ids) If caching, the server
     *                    supports the CONDSTORE IMAP extension, and the
     *                    mailbox contained cached data when opened for the
     *                    first time in this access, this is the list of UIDs
     *                    in which flags have changed since STATUS_SYNCMODSEQ.
     *
     *   - Horde_Imap_Client::STATUS_SYNCVANISHED
     *     Return key: syncvanished
     *     Return format: (Horde_Imap_Client_Ids) If caching, the server
     *                    supports the CONDSTORE IMAP extension, and the
     *                    mailbox contained cached data when opened for the
     *                    first time in this access, this is the list of UIDs
     *                    which have been deleted since STATUS_SYNCMODSEQ.
     *
     *   - Horde_Imap_Client::STATUS_UIDNOTSTICKY
     *     Return key: uidnotsticky
     *     Return format: (boolean) If the server supports the UIDPLUS IMAP
     *                    extension, and the queried mailbox does not support
     *                    persistent UIDs, this value will be true. In all
     *                    other cases, this value will be false.
     *
     *   - Horde_Imap_Client::STATUS_FORCE_REFRESH
     *     Normally, the status information will be cached for a given
     *     mailbox. Since most PHP requests are generally less than a second,
     *     this is fine. However, if your script is long running, the status
     *     information may not be up-to-date. Specifying this flag will ensure
     *     that the server is always polled for the current mailbox status
     *     before results are returned. (since 2.14.0)
     *
     *   - Horde_Imap_Client::STATUS_ALL (DEFAULT)
     *     Shortcut to return 'messages', 'recent', 'uidnext', 'uidvalidity',
     *     and 'unseen' values.
     * </ul>
     * @param array $opts     Additional options:
     * <pre>
     *   - sort: (boolean) If true, sort the list of mailboxes? (since 2.10.0)
     *           DEFAULT: Do not sort the list.
     *   - sort_delimiter: (string) If 'sort' is true, this is the delimiter
     *                     used to sort the mailboxes. (since 2.10.0)
     *                     DEFAULT: '.'
     * </pre>
     *
     * @return array  If $mailbox contains multiple mailboxes, an array with
     *                keys being the UTF-8 mailbox name and values as arrays
     *                containing the requested keys (see above).
     *                Otherwise, an array with keys as the requested keys (see
     *                above) and values as the key data.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function status($mailbox, $flags = Horde_Imap_Client::STATUS_ALL,
                           array $opts = array())
    {
        $opts = array_merge(array(
            'sort' => false,
            'sort_delimiter' => '.'
        ), $opts);

        $this->login();

        if (is_array($mailbox)) {
            if (empty($mailbox)) {
                return array();
            }
            $ret_array = true;
        } else {
            $mailbox = array($mailbox);
            $ret_array = false;
        }

        $mlist = array_map(array('Horde_Imap_Client_Mailbox', 'get'), $mailbox);

        $unselected_flags = array(
            'messages' => Horde_Imap_Client::STATUS_MESSAGES,
            'recent' => Horde_Imap_Client::STATUS_RECENT,
            'uidnext' => Horde_Imap_Client::STATUS_UIDNEXT,
            'uidvalidity' => Horde_Imap_Client::STATUS_UIDVALIDITY,
            'unseen' => Horde_Imap_Client::STATUS_UNSEEN
        );

        if (!$this->statuscache) {
            $flags |= Horde_Imap_Client::STATUS_FORCE_REFRESH;
        }

        if ($flags & Horde_Imap_Client::STATUS_ALL) {
            foreach ($unselected_flags as $val) {
                $flags |= $val;
            }
        }

        $master = $ret = array();

        /* Catch flags that are not supported. */
        if (($flags & Horde_Imap_Client::STATUS_HIGHESTMODSEQ) &&
            !$this->_capability()->isEnabled('CONDSTORE')) {
            $master['highestmodseq'] = 0;
            $flags &= ~Horde_Imap_Client::STATUS_HIGHESTMODSEQ;
        }

        if (($flags & Horde_Imap_Client::STATUS_UIDNOTSTICKY) &&
            !$this->_capability('UIDPLUS')) {
            $master['uidnotsticky'] = false;
            $flags &= ~Horde_Imap_Client::STATUS_UIDNOTSTICKY;
        }

        /* UIDNEXT return options. */
        if ($flags & Horde_Imap_Client::STATUS_UIDNEXT_FORCE) {
            $flags |= Horde_Imap_Client::STATUS_UIDNEXT;
        }

        foreach ($mlist as $val) {
            $name = strval($val);
            $tmp_flags = $flags;

            if ($val->equals($this->_selected)) {
                /* Check if already in mailbox. */
                $opened = true;

                if ($flags & Horde_Imap_Client::STATUS_FORCE_REFRESH) {
                    $this->noop();
                }
            } else {
                /* A list of STATUS options (other than those handled directly
                 * below) that require the mailbox to be explicitly opened. */
                $opened = ($flags & Horde_Imap_Client::STATUS_FIRSTUNSEEN) ||
                    ($flags & Horde_Imap_Client::STATUS_FLAGS) ||
                    ($flags & Horde_Imap_Client::STATUS_PERMFLAGS) ||
                    ($flags & Horde_Imap_Client::STATUS_UIDNOTSTICKY) ||
                    /* Force mailboxes containing wildcards to be accessed via
                     * STATUS so that wildcards do not return a bunch of
                     * mailboxes in the LIST-STATUS response. */
                    (strpbrk($name, '*%') !== false);
            }

            $ret[$name] = $master;
            $ptr = &$ret[$name];

            /* STATUS_PERMFLAGS requires a read/write mailbox. */
            if ($flags & Horde_Imap_Client::STATUS_PERMFLAGS) {
                $this->openMailbox($val, Horde_Imap_Client::OPEN_READWRITE);
                $opened = true;
            }

            /* Handle SYNC related return options. These require the mailbox
             * to be opened at least once. */
            if ($flags & Horde_Imap_Client::STATUS_SYNCMODSEQ) {
                $this->openMailbox($val);
                $ptr['syncmodseq'] = $this->_mailboxOb($val)->getStatus(Horde_Imap_Client::STATUS_SYNCMODSEQ);
                $tmp_flags &= ~Horde_Imap_Client::STATUS_SYNCMODSEQ;
                $opened = true;
            }

            if ($flags & Horde_Imap_Client::STATUS_SYNCFLAGUIDS) {
                $this->openMailbox($val);
                $ptr['syncflaguids'] = $this->getIdsOb($this->_mailboxOb($val)->getStatus(Horde_Imap_Client::STATUS_SYNCFLAGUIDS));
                $tmp_flags &= ~Horde_Imap_Client::STATUS_SYNCFLAGUIDS;
                $opened = true;
            }

            if ($flags & Horde_Imap_Client::STATUS_SYNCVANISHED) {
                $this->openMailbox($val);
                $ptr['syncvanished'] = $this->getIdsOb($this->_mailboxOb($val)->getStatus(Horde_Imap_Client::STATUS_SYNCVANISHED));
                $tmp_flags &= ~Horde_Imap_Client::STATUS_SYNCVANISHED;
                $opened = true;
            }

            /* Handle RECENT_TOTAL option. */
            if ($flags & Horde_Imap_Client::STATUS_RECENT_TOTAL) {
                $this->openMailbox($val);
                $ptr['recent_total'] = $this->_mailboxOb($val)->getStatus(Horde_Imap_Client::STATUS_RECENT_TOTAL);
                $tmp_flags &= ~Horde_Imap_Client::STATUS_RECENT_TOTAL;
                $opened = true;
            }

            if ($opened) {
                if ($tmp_flags) {
                    $tmp = $this->_status(array($val), $tmp_flags);
                    $ptr += reset($tmp);
                }
            } else {
                $to_process[] = $val;
            }
        }

        if ($flags && !empty($to_process)) {
            if ((count($to_process) > 1) &&
                $this->_capability('LIST-STATUS')) {
                foreach ($this->listMailboxes($to_process, Horde_Imap_Client::MBOX_ALL, array('status' => $flags)) as $key => $val) {
                    if (isset($val['status'])) {
                        $ret[$key] += $val['status'];
                    }
                }
            } else {
                foreach ($this->_status($to_process, $flags) as $key => $val) {
                    $ret[$key] += $val;
                }
            }
        }

        if (!$opts['sort'] || (count($ret) === 1)) {
            return $ret_array
                ? $ret
                : reset($ret);
        }

        $list_ob = new Horde_Imap_Client_Mailbox_List(array_keys($ret));
        $sorted = $list_ob->sort(array(
            'delimiter' => $opts['sort_delimiter']
        ));

        $out = array();
        foreach ($sorted as $val) {
            $out[$val] = $ret[$val];
        }

        return $out;
    }

    /**
     * Obtain status information for mailboxes.
     *
     * @param array $mboxes   The list of mailbox objects to query.
     * @param integer $flags  A bitmask of information requested from the
     *                        server.
     *
     * @return array  See array return for status().
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _status($mboxes, $flags);

    /**
     * Perform a STATUS call on multiple mailboxes at the same time.
     *
     * This method leverages the LIST-EXTENDED and LIST-STATUS extensions on
     * the IMAP server to improve the efficiency of this operation.
     *
     * @deprecated  Use status() instead.
     *
     * @param array $mailboxes  The mailboxes to query. Either
     *                          Horde_Imap_Client_Mailbox objects, strings
     *                          (UTF-8), or a combination of the two.
     * @param integer $flags    See status().
     * @param array $opts       Additional options:
     *   - sort: (boolean) If true, sort the list of mailboxes?
     *           DEFAULT: Do not sort the list.
     *   - sort_delimiter: (string) If 'sort' is true, this is the delimiter
     *                     used to sort the mailboxes.
     *                     DEFAULT: '.'
     *
     * @return array  An array with the keys as the mailbox names (UTF-8) and
     *                the values as arrays with the requested keys (from the
     *                mask given in $flags).
     */
    public function statusMultiple($mailboxes,
                                   $flags = Horde_Imap_Client::STATUS_ALL,
                                   array $opts = array())
    {
        return $this->status($mailboxes, $flags, $opts);
    }

    /**
     * Append message(s) to a mailbox.
     *
     * @param mixed $mailbox  The mailbox to append the message(s) to. Either
     *                        a Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param array $data     The message data to append, along with
     *                        additional options. An array of arrays with
     *                        each embedded array having the following
     *                        entries:
     * <pre>
     *   - data: (mixed) The data to append. If a string or a stream resource,
     *           this will be used as the entire contents of a single message.
     *           If an array, will catenate all given parts into a single
     *           message. This array contains one or more arrays with
     *           two keys:
     *     - t: (string) Either 'url' or 'text'.
     *     - v: (mixed) If 't' is 'url', this is the IMAP URL to the message
     *          part to append. If 't' is 'text', this is either a string or
     *          resource representation of the message part data.
     *     DEFAULT: NONE (entry is MANDATORY)
     *   - flags: (array) An array of flags/keywords to set on the appended
     *            message.
     *            DEFAULT: Only the \Recent flag is set.
     *   - internaldate: (DateTime) The internaldate to set for the appended
     *                   message.
     *                   DEFAULT: internaldate will be the same date as when
     *                   the message was appended.
     * </pre>
     * @param array $options  Additonal options:
     * <pre>
     *   - create: (boolean) Try to create $mailbox if it does not exist?
     *             DEFAULT: No.
     * </pre>
     *
     * @return Horde_Imap_Client_Ids  The UIDs of the appended messages.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function append($mailbox, $data, array $options = array())
    {
        $this->login();

        $mailbox = Horde_Imap_Client_Mailbox::get($mailbox);

        $ret = $this->_append($mailbox, $data, $options);

        if ($ret instanceof Horde_Imap_Client_Ids) {
            return $ret;
        }

        $uids = $this->getIdsOb();

        while (list(,$val) = each($data)) {
            if (is_resource($val['data'])) {
                rewind($val['data']);
            }

            $uids->add($this->_getUidByMessageId(
                $mailbox,
                Horde_Mime_Headers::parseHeaders($val['data'])->getValue('message-id')
            ));
        }

        return $uids;
    }

    /**
     * Append message(s) to a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to append the
     *                                            message(s) to.
     * @param array $data                         The message data.
     * @param array $options                      Additional options.
     *
     * @return mixed  A Horde_Imap_Client_Ids object containing the UIDs of
     *                the appended messages (if server supports UIDPLUS
     *                extension) or true.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _append(Horde_Imap_Client_Mailbox $mailbox,
                                        $data, $options);

    /**
     * Request a checkpoint of the currently selected mailbox (RFC 3501
     * [6.4.1]).
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function check()
    {
        // CHECK only useful if we are already authenticated.
        if ($this->_isAuthenticated) {
            $this->_check();
        }
    }

    /**
     * Request a checkpoint of the currently selected mailbox.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _check();

    /**
     * Close the connection to the currently selected mailbox, optionally
     * expunging all deleted messages (RFC 3501 [6.4.2]).
     *
     * @param array $options  Additional options:
     *   - expunge: (boolean) Expunge all messages flagged as deleted?
     *              DEFAULT: No
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function close(array $options = array())
    {
        // This check catches the non-logged in case.
        if (is_null($this->_selected)) {
            return;
        }

        /* If we are caching, search for deleted messages. */
        if (!empty($options['expunge']) && $this->_initCache(true)) {
            /* Make sure mailbox is read-write to expunge. */
            $this->openMailbox($this->_selected, Horde_Imap_Client::OPEN_READWRITE);
            if ($this->_mode == Horde_Imap_Client::OPEN_READONLY) {
                throw new Horde_Imap_Client_Exception(
                    Horde_Imap_Client_Translation::r("Cannot expunge read-only mailbox."),
                    Horde_Imap_Client_Exception::MAILBOX_READONLY
                );
            }

            $search_query = new Horde_Imap_Client_Search_Query();
            $search_query->flag(Horde_Imap_Client::FLAG_DELETED, true);
            $search_res = $this->search($this->_selected, $search_query);
            $mbox = $this->_selected;
        } else {
            $search_res = null;
        }

        $this->_close($options);
        $this->_selected = null;
        $this->_mode = 0;

        if (!is_null($search_res)) {
            $this->_deleteMsgs($mbox, $search_res['match']);
        }
    }

    /**
     * Close the connection to the currently selected mailbox, optionally
     * expunging all deleted messages (RFC 3501 [6.4.2]).
     *
     * @param array $options  Additional options.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _close($options);

    /**
     * Expunge deleted messages from the given mailbox.
     *
     * @param mixed $mailbox  The mailbox to expunge. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param array $options  Additional options:
     *   - delete: (boolean) If true, will flag all messages in 'ids' as
     *             deleted (since 2.10.0).
     *             DEFAULT: false
     *   - ids: (Horde_Imap_Client_Ids) A list of messages to expunge. These
     *          messages must already be flagged as deleted (unless 'delete'
     *          is true).
     *          DEFAULT: All messages marked as deleted will be expunged.
     *   - list: (boolean) If true, returns the list of expunged messages
     *           (UIDs only).
     *           DEFAULT: false
     *
     * @return Horde_Imap_Client_Ids  If 'list' option is true, returns the
     *                                UID list of expunged messages.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function expunge($mailbox, array $options = array())
    {
        // Open mailbox call will handle the login.
        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_READWRITE);

        /* Don't expunge if the mailbox is readonly. */
        if ($this->_mode == Horde_Imap_Client::OPEN_READONLY) {
            throw new Horde_Imap_Client_Exception(
                Horde_Imap_Client_Translation::r("Cannot expunge read-only mailbox."),
                Horde_Imap_Client_Exception::MAILBOX_READONLY
            );
        }

        if (empty($options['ids'])) {
            $options['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($options['ids']->isEmpty()) {
            return $this->getIdsOb();
        }

        return $this->_expunge($options);
    }

    /**
     * Expunge all deleted messages from the given mailbox.
     *
     * @param array $options  Additional options.
     *
     * @return Horde_Imap_Client_Ids  If 'list' option is true, returns the
     *                                list of expunged messages.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _expunge($options);

    /**
     * Search a mailbox.
     *
     * @param mixed $mailbox                         The mailbox to search.
     *                                               Either a
     *                                               Horde_Imap_Client_Mailbox
     *                                               object or a string
     *                                               (UTF-8).
     * @param Horde_Imap_Client_Search_Query $query  The search query.
     *                                               Defaults to an ALL
     *                                               search.
     * @param array $options                         Additional options:
     * <pre>
     *   - nocache: (boolean) Don't cache the results.
     *              DEFAULT: false (results cached, if possible)
     *   - partial: (mixed) The range of results to return (message sequence
     *              numbers) Only a single range is supported (represented by
     *              the minimum and maximum values contained in the range
     *              given).
     *              DEFAULT: All messages are returned.
     *   - results: (array) The data to return. Consists of zero or more of
     *              the following flags:
     *     - Horde_Imap_Client::SEARCH_RESULTS_COUNT
     *     - Horde_Imap_Client::SEARCH_RESULTS_MATCH (DEFAULT)
     *     - Horde_Imap_Client::SEARCH_RESULTS_MAX
     *     - Horde_Imap_Client::SEARCH_RESULTS_MIN
     *     - Horde_Imap_Client::SEARCH_RESULTS_SAVE
     *     - Horde_Imap_Client::SEARCH_RESULTS_RELEVANCY
     *   - sequence: (boolean) If true, returns an array of sequence numbers.
     *               DEFAULT: Returns an array of UIDs
     *   - sort: (array) Sort the returned list of messages. Multiple sort
     *           criteria can be specified. Any sort criteria can be sorted in
     *           reverse order (instead of the default ascending order) by
     *           adding a Horde_Imap_Client::SORT_REVERSE element to the array
     *           directly before adding the sort element. The following sort
     *           criteria are available:
     *     - Horde_Imap_Client::SORT_ARRIVAL
     *     - Horde_Imap_Client::SORT_CC
     *     - Horde_Imap_Client::SORT_DATE
     *     - Horde_Imap_Client::SORT_DISPLAYFROM
     *       On servers that don't support SORT=DISPLAY, this criteria will
     *       fallback to doing client-side sorting.
     *     - Horde_Imap_Client::SORT_DISPLAYFROM_FALLBACK
     *       On servers that don't support SORT=DISPLAY, this criteria will
     *       fallback to Horde_Imap_Client::SORT_FROM [since 2.4.0].
     *     - Horde_Imap_Client::SORT_DISPLAYTO
     *       On servers that don't support SORT=DISPLAY, this criteria will
     *       fallback to doing client-side sorting.
     *     - Horde_Imap_Client::SORT_DISPLAYTO_FALLBACK
     *       On servers that don't support SORT=DISPLAY, this criteria will
     *       fallback to Horde_Imap_Client::SORT_TO [since 2.4.0].
     *     - Horde_Imap_Client::SORT_FROM
     *     - Horde_Imap_Client::SORT_SEQUENCE
     *     - Horde_Imap_Client::SORT_SIZE
     *     - Horde_Imap_Client::SORT_SUBJECT
     *     - Horde_Imap_Client::SORT_TO
     *
     *     [On servers that support SEARCH=FUZZY, this criteria is also
     *     available:]
     *     - Horde_Imap_Client::SORT_RELEVANCY
     * </pre>
     *
     * @return array  An array with the following keys:
     * <pre>
     *   - count: (integer) The number of messages that match the search
     *            criteria. Always returned.
     *   - match: (Horde_Imap_Client_Ids) The IDs that match $criteria, sorted
     *            if the 'sort' modifier was set. Returned if
     *            Horde_Imap_Client::SEARCH_RESULTS_MATCH is set.
     *   - max: (integer) The UID (default) or message sequence number (if
     *          'sequence' is true) of the highest message that satisifies
     *          $criteria. Returns null if no matches found. Returned if
     *          Horde_Imap_Client::SEARCH_RESULTS_MAX is set.
     *   - min: (integer) The UID (default) or message sequence number (if
     *          'sequence' is true) of the lowest message that satisifies
     *          $criteria. Returns null if no matches found. Returned if
     *          Horde_Imap_Client::SEARCH_RESULTS_MIN is set.
     *   - modseq: (integer) The highest mod-sequence for all messages being
     *            returned. Returned if 'sort' is false, the search query
     *            includes a MODSEQ command, and the server supports the
     *            CONDSTORE IMAP extension.
     *   - relevancy: (array) The list of relevancy scores. Returned if
     *                Horde_Imap_Client::SEARCH_RESULTS_RELEVANCY is set and
     *                the server supports FUZZY search matching.
     *   - save: (boolean) Whether the search results were saved. Returned if
     *           Horde_Imap_Client::SEARCH_RESULTS_SAVE is set.
     * </pre>
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function search($mailbox, $query = null, array $options = array())
    {
        $this->login();

        if (empty($options['results'])) {
            $options['results'] = array(
                Horde_Imap_Client::SEARCH_RESULTS_MATCH,
                Horde_Imap_Client::SEARCH_RESULTS_COUNT
            );
        } elseif (!in_array(Horde_Imap_Client::SEARCH_RESULTS_COUNT, $options['results'])) {
            $options['results'][] = Horde_Imap_Client::SEARCH_RESULTS_COUNT;
        }

        // Default to an ALL search.
        if (is_null($query)) {
            $query = new Horde_Imap_Client_Search_Query();
        }

        // Check for SEARCHRES support.
        if ((($pos = array_search(Horde_Imap_Client::SEARCH_RESULTS_SAVE, $options['results'])) !== false) &&
            !$this->_capability('SEARCHRES')) {
            unset($options['results'][$pos]);
        }

        // Check for SORT-related options.
        if (!empty($options['sort'])) {
            foreach ($options['sort'] as $key => $val) {
                switch ($val) {
                case Horde_Imap_Client::SORT_DISPLAYFROM_FALLBACK:
                    $options['sort'][$key] = $this->_capability('SORT', 'DISPLAY')
                        ? Horde_Imap_Client::SORT_DISPLAYFROM
                        : Horde_Imap_Client::SORT_FROM;
                    break;

                case Horde_Imap_Client::SORT_DISPLAYTO_FALLBACK:
                    $options['sort'][$key] = $this->_capability('SORT', 'DISPLAY')
                        ? Horde_Imap_Client::SORT_DISPLAYTO
                        : Horde_Imap_Client::SORT_TO;
                    break;
                }
            }
        }

        // Check for supported charset.
        $options['_query'] = $query->build($this);
        if (!is_null($options['_query']['charset']) &&
            ($this->search_charset->query($options['_query']['charset'], true) === false)) {
            foreach ($this->search_charset->charsets as $val) {
                try {
                    $new_query = clone $query;
                    $new_query->charset($val);
                    break;
                } catch (Horde_Imap_Client_Exception_SearchCharset $e) {
                    unset($new_query);
                }
            }

            if (!isset($new_query)) {
                throw $e;
            }

            $query = $new_query;
            $options['_query'] = $query->build($this);
        }

        /* RFC 6203: MUST NOT request relevancy results if we are not using
         * FUZZY searching. */
        if (in_array(Horde_Imap_Client::SEARCH_RESULTS_RELEVANCY, $options['results']) &&
            !in_array('SEARCH=FUZZY', $options['_query']['exts_used'])) {
            throw new InvalidArgumentException('Cannot specify RELEVANCY results if not doing a FUZZY search.');
        }

        /* Check for partial matching. */
        if (!empty($options['partial'])) {
            $pids = $this->getIdsOb($options['partial'], true)->range_string;
            if (!strlen($pids)) {
                throw new InvalidArgumentException('Cannot specify empty sequence range for a PARTIAL search.');
            }

            if (strpos($pids, ':') === false) {
                $pids .= ':' . $pids;
            }

            $options['partial'] = $pids;
        }

        /* Optimization - if query is just for a count of either RECENT or
         * ALL messages, we can send status information instead. Can't
         * optimize with unseen queries because we may cause an infinite loop
         * between here and the status() call. */
        if ((count($options['results']) === 1) &&
            (reset($options['results']) == Horde_Imap_Client::SEARCH_RESULTS_COUNT)) {
            switch ($options['_query']['query']) {
            case 'ALL':
                $ret = $this->status($mailbox, Horde_Imap_Client::STATUS_MESSAGES);
                return array('count' => $ret['messages']);

            case 'RECENT':
                $ret = $this->status($mailbox, Horde_Imap_Client::STATUS_RECENT);
                return array('count' => $ret['recent']);
            }
        }

        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_AUTO);

        /* Take advantage of search result caching.  If CONDSTORE available,
         * we can cache all queries and invalidate the cache when the MODSEQ
         * changes. If CONDSTORE not available, we can only store queries
         * that don't involve flags. We store results by hashing the options
         * array - the generated query is already added to '_query' key
         * above. */
        $cache = null;
        if (empty($options['nocache']) &&
            $this->_initCache(true) &&
            ($this->_capability()->isEnabled('CONDSTORE') ||
             !$query->flagSearch())) {
            $cache = $this->_getSearchCache('search', $options);
            if (isset($cache['data'])) {
                if (isset($cache['data']['match'])) {
                    $cache['data']['match'] = $this->getIdsOb($cache['data']['match']);
                }
                return $cache['data'];
            }
        }

        /* Optimization: Catch when there are no messages in a mailbox. */
        $status_res = $this->status($this->_selected, Horde_Imap_Client::STATUS_MESSAGES | Horde_Imap_Client::STATUS_HIGHESTMODSEQ);
        if ($status_res['messages'] ||
            in_array(Horde_Imap_Client::SEARCH_RESULTS_SAVE, $options['results'])) {
            /* RFC 7162 [3.1.2.2] - trying to do a MODSEQ SEARCH on a mailbox
             * that doesn't support it will return BAD. */
            if (in_array('CONDSTORE', $options['_query']['exts']) &&
                !$this->_mailboxOb()->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) {
                throw new Horde_Imap_Client_Exception(
                    Horde_Imap_Client_Translation::r("Mailbox does not support mod-sequences."),
                    Horde_Imap_Client_Exception::MBOXNOMODSEQ
                );
            }

            $ret = $this->_search($query, $options);
        } else {
            $ret = array(
                'count' => 0,
                'match' => $this->getIdsOb(),
                'max' => null,
                'min' => null,
                'relevancy' => array()
            );
            if (isset($status_res['highestmodseq'])) {
                $ret['modseq'] = $status_res['highestmodseq'];
            }
        }

        if ($cache) {
            $save = $ret;
            if (isset($save['match'])) {
                $save['match'] = strval($ret['match']);
            }
            $this->_setSearchCache($save, $cache);
        }

        return $ret;
    }

    /**
     * Search a mailbox.
     *
     * @param object $query   The search query.
     * @param array $options  Additional options. The '_query' key contains
     *                        the value of $query->build().
     *
     * @return Horde_Imap_Client_Ids  An array of IDs.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _search($query, $options);

    /**
     * Set the comparator to use for searching/sorting (RFC 5255).
     *
     * @param string $comparator  The comparator string (see RFC 4790 [3.1] -
     *                            "collation-id" - for format). The reserved
     *                            string 'default' can be used to select
     *                            the default comparator.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function setComparator($comparator = null)
    {
        $comp = is_null($comparator)
            ? $this->getParam('comparator')
            : $comparator;
        if (is_null($comp)) {
            return;
        }

        $this->login();

        if (!$this->_capability('I18NLEVEL', '2')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension(
                'I18NLEVEL',
                'The IMAP server does not support changing SEARCH/SORT comparators.'
            );
        }

        $this->_setComparator($comp);
    }

    /**
     * Set the comparator to use for searching/sorting (RFC 5255).
     *
     * @param string $comparator  The comparator string (see RFC 4790 [3.1] -
     *                            "collation-id" - for format). The reserved
     *                            string 'default' can be used to select
     *                            the default comparator.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _setComparator($comparator);

    /**
     * Get the comparator used for searching/sorting (RFC 5255).
     *
     * @return mixed  Null if the default comparator is being used, or an
     *                array of comparator information (see RFC 5255 [4.8]).
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getComparator()
    {
        $this->login();

        return $this->_capability('I18NLEVEL', '2')
            ? $this->_getComparator()
            : null;
    }

    /**
     * Get the comparator used for searching/sorting (RFC 5255).
     *
     * @return mixed  Null if the default comparator is being used, or an
     *                array of comparator information (see RFC 5255 [4.8]).
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getComparator();

    /**
     * Thread sort a given list of messages (RFC 5256).
     *
     * @param mixed $mailbox  The mailbox to query. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param array $options  Additional options:
     * <pre>
     *   - criteria: (mixed) The following thread criteria are available:
     *     - Horde_Imap_Client::THREAD_ORDEREDSUBJECT
     *     - Horde_Imap_Client::THREAD_REFERENCES
     *     - Horde_Imap_Client::THREAD_REFS
     *       Other algorithms can be explicitly specified by passing the IMAP
     *       thread algorithm in as a string value.
     *     DEFAULT: Horde_Imap_Client::THREAD_ORDEREDSUBJECT
     *   - search: (Horde_Imap_Client_Search_Query) The search query.
     *             DEFAULT: All messages in mailbox included in thread sort.
     *   - sequence: (boolean) If true, each message is stored and referred to
     *               by its message sequence number.
     *               DEFAULT: Stored/referred to by UID.
     * </pre>
     *
     * @return Horde_Imap_Client_Data_Thread  A thread data object.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function thread($mailbox, array $options = array())
    {
        // Open mailbox call will handle the login.
        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_AUTO);

        /* Take advantage of search result caching.  If CONDSTORE available,
         * we can cache all queries and invalidate the cache when the MODSEQ
         * changes. If CONDSTORE not available, we can only store queries
         * that don't involve flags. See search() for similar caching. */
        $cache = null;
        if ($this->_initCache(true) &&
            ($this->_capability()->isEnabled('CONDSTORE') ||
             empty($options['search']) ||
             !$options['search']->flagSearch())) {
            $cache = $this->_getSearchCache('thread', $options);
            if (isset($cache['data']) &&
                ($cache['data'] instanceof Horde_Imap_Client_Data_Thread)) {
                return $cache['data'];
            }
        }

        $status_res = $this->status($this->_selected, Horde_Imap_Client::STATUS_MESSAGES);

        $ob = $status_res['messages']
            ? $this->_thread($options)
            : new Horde_Imap_Client_Data_Thread(array(), empty($options['sequence']) ? 'uid' : 'sequence');

        if ($cache) {
            $this->_setSearchCache($ob, $cache);
        }

        return $ob;
    }

    /**
     * Thread sort a given list of messages (RFC 5256).
     *
     * @param array $options  Additional options. See thread().
     *
     * @return Horde_Imap_Client_Data_Thread  A thread data object.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _thread($options);

    /**
     * Fetch message data (see RFC 3501 [6.4.5]).
     *
     * @param mixed $mailbox                        The mailbox to search.
     *                                              Either a
     *                                              Horde_Imap_Client_Mailbox
     *                                              object or a string (UTF-8).
     * @param Horde_Imap_Client_Fetch_Query $query  Fetch query object.
     * @param array $options                        Additional options:
     *   - changedsince: (integer) Only return messages that have a
     *                   mod-sequence larger than this value. This option
     *                   requires the CONDSTORE IMAP extension (if not present,
     *                   this value is ignored). Additionally, the mailbox
     *                   must support mod-sequences or an exception will be
     *                   thrown. If valid, this option implicity adds the
     *                   mod-sequence fetch criteria to the fetch command.
     *                   DEFAULT: Mod-sequence values are ignored.
     *   - exists: (boolean) Ensure that all ids returned exist on the server.
     *             If false, the list of ids returned in the results object
     *             is not guaranteed to reflect the current state of the
     *             remote mailbox.
     *             DEFAULT: false
     *   - ids: (Horde_Imap_Client_Ids) A list of messages to fetch data from.
     *          DEFAULT: All messages in $mailbox will be fetched.
     *   - nocache: (boolean) If true, will not cache the results (previously
     *              cached data will still be used to generate results) [since
     *              2.8.0].
     *              DEFAULT: false
     *
     * @return Horde_Imap_Client_Fetch_Results  A results object.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function fetch($mailbox, $query, array $options = array())
    {
        try {
            $ret = $this->_fetchWrapper($mailbox, $query, $options);
            unset($this->_temp['fetch_nocache']);
            return $ret;
        } catch (Exception $e) {
            unset($this->_temp['fetch_nocache']);
            throw $e;
        }
    }

    /**
     * Wrapper for fetch() to allow internal state to be reset on exception.
     *
     * @internal
     * @see fetch()
     */
    private function _fetchWrapper($mailbox, $query, $options)
    {
        $this->login();

        $query = clone $query;

        $cache_array = $header_cache = $new_query = array();

        if (empty($options['ids'])) {
            $options['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($options['ids']->isEmpty()) {
            return new Horde_Imap_Client_Fetch_Results($this->_fetchDataClass);
        } elseif ($options['ids']->search_res &&
                  !$this->_capability('SEARCHRES')) {
            /* SEARCHRES requires server support. */
            throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCHRES');
        }

        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_AUTO);
        $mbox_ob = $this->_mailboxOb();

        if (!empty($options['nocache'])) {
            $this->_temp['fetch_nocache'] = true;
        }

        $cf = $this->_initCache(true)
            ? $this->_cacheFields()
            : array();

        if (!empty($cf)) {
            /* If using cache, we store by UID so we need to return UIDs. */
            $query->uid();
        }

        $modseq_check = !empty($options['changedsince']);
        if ($query->contains(Horde_Imap_Client::FETCH_MODSEQ)) {
            if (!$this->_capability()->isEnabled('CONDSTORE')) {
                unset($query[Horde_Imap_Client::FETCH_MODSEQ]);
            } elseif (empty($options['changedsince'])) {
                $modseq_check = true;
            }
        }

        if ($modseq_check &&
            !$mbox_ob->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) {
            /* RFC 7162 [3.1.2.2] - trying to do a MODSEQ FETCH on a mailbox
             * that doesn't support it will return BAD. */
            throw new Horde_Imap_Client_Exception(
                Horde_Imap_Client_Translation::r("Mailbox does not support mod-sequences."),
                Horde_Imap_Client_Exception::MBOXNOMODSEQ
            );
        }

        /* Determine if caching is available and if anything in $query is
         * cacheable. */
        foreach ($cf as $k => $v) {
            if (isset($query[$k])) {
                switch ($k) {
                case Horde_Imap_Client::FETCH_ENVELOPE:
                case Horde_Imap_Client::FETCH_FLAGS:
                case Horde_Imap_Client::FETCH_IMAPDATE:
                case Horde_Imap_Client::FETCH_SIZE:
                case Horde_Imap_Client::FETCH_STRUCTURE:
                    $cache_array[$k] = $v;
                    break;

                case Horde_Imap_Client::FETCH_HEADERS:
                    $this->_temp['headers_caching'] = array();

                    foreach ($query[$k] as $key => $val) {
                        /* Only cache if directly requested.  Iterate through
                         * requests to ensure at least one can be cached. */
                        if (!empty($val['cache']) && !empty($val['peek'])) {
                            $cache_array[$k] = $v;
                            ksort($val);
                            $header_cache[$key] = hash(
                                (PHP_MINOR_VERSION >= 4) ? 'fnv132' : 'sha1',
                                serialize($val)
                            );
                        }
                    }
                    break;
                }
            }
        }

        $ret = new Horde_Imap_Client_Fetch_Results(
            $this->_fetchDataClass,
            $options['ids']->sequence ? Horde_Imap_Client_Fetch_Results::SEQUENCE : Horde_Imap_Client_Fetch_Results::UID
        );

        /* If nothing is cacheable, we can do a straight search. */
        if (empty($cache_array)) {
            $options['_query'] = $query;
            $this->_fetch($ret, array($options));
            return $ret;
        }

        $cs_ret = empty($options['changedsince'])
            ? null
            : clone $ret;

        /* Convert special searches to UID lists and create mapping. */
        $ids = $this->resolveIds(
            $this->_selected,
            $options['ids'],
            empty($options['exists']) ? 1 : 2
        );

        /* Add non-user settable cache fields. */
        $cache_array[Horde_Imap_Client::FETCH_DOWNGRADED] = self::CACHE_DOWNGRADED;

        /* Get the cached values. */
        $data = $this->_cache->get(
            $this->_selected,
            $ids->ids,
            array_values($cache_array),
            $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY)
        );

        /* Build a list of what we still need. */
        $map = array_flip($mbox_ob->map->map);
        $sequence = $options['ids']->sequence;
        foreach ($ids as $uid) {
            $crit = clone $query;

            if ($sequence) {
                if (!isset($map[$uid])) {
                    continue;
                }
                $entry_idx = $map[$uid];
            } else {
                $entry_idx = $uid;
                unset($crit[Horde_Imap_Client::FETCH_UID]);
            }

            $entry = $ret->get($entry_idx);

            if (isset($map[$uid])) {
                $entry->setSeq($map[$uid]);
                unset($crit[Horde_Imap_Client::FETCH_SEQ]);
            }

            $entry->setUid($uid);

            foreach ($cache_array as $key => $cid) {
                switch ($key) {
                case Horde_Imap_Client::FETCH_DOWNGRADED:
                    if (!empty($data[$uid][$cid])) {
                        $entry->setDowngraded(true);
                    }
                    break;

                case Horde_Imap_Client::FETCH_ENVELOPE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Imap_Client_Data_Envelope)) {
                        $entry->setEnvelope($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_FLAGS:
                    if (isset($data[$uid][$cid]) &&
                        is_array($data[$uid][$cid])) {
                        $entry->setFlags($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_HEADERS:
                    foreach ($header_cache as $hkey => $hval) {
                        if (isset($data[$uid][$cid][$hval])) {
                            /* We have found a cached entry with the same
                             * MD5 sum. */
                            $entry->setHeaders($hkey, $data[$uid][$cid][$hval]);
                            $crit->remove($key, $hkey);
                        } else {
                            $this->_temp['headers_caching'][$hkey] = $hval;
                        }
                    }
                    break;

                case Horde_Imap_Client::FETCH_IMAPDATE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Imap_Client_DateTime)) {
                        $entry->setImapDate($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_SIZE:
                    if (isset($data[$uid][$cid])) {
                        $entry->setSize($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;

                case Horde_Imap_Client::FETCH_STRUCTURE:
                    if (isset($data[$uid][$cid]) &&
                        ($data[$uid][$cid] instanceof Horde_Mime_Part)) {
                        $entry->setStructure($data[$uid][$cid]);
                        unset($crit[$key]);
                    }
                    break;
                }
            }

            if (count($crit)) {
                $sig = $crit->hash();
                if (isset($new_query[$sig])) {
                    $new_query[$sig]['i'][] = $entry_idx;
                } else {
                    $new_query[$sig] = array(
                        'c' => $crit,
                        'i' => array($entry_idx)
                    );
                }
            }
        }

        $to_fetch = array();
        foreach ($new_query as $val) {
            $ids_ob = $this->getIdsOb(null, $sequence);
            $ids_ob->duplicates = true;
            $ids_ob->add($val['i']);
            $to_fetch[] = array_merge($options, array(
                '_query' => $val['c'],
                'ids' => $ids_ob
            ));
        }

        if (!empty($to_fetch)) {
            $this->_fetch(is_null($cs_ret) ? $ret : $cs_ret, $to_fetch);
        }

        if (is_null($cs_ret)) {
            return $ret;
        }

        /* If doing changedsince query, and all other data is cached, we still
         * need to hit IMAP server to determine proper results set. */
        if (empty($new_query)) {
            $squery = new Horde_Imap_Client_Search_Query();
            $squery->modseq($options['changedsince'] + 1);
            $squery->ids($options['ids']);

            $cs = $this->search($this->_selected, $squery, array(
                'sequence' => $sequence
            ));

            foreach ($cs['match'] as $val) {
                $entry = $ret->get($val);
                if ($sequence) {
                    $entry->setSeq($val);
                } else {
                    $entry->setUid($val);
                }
                $cs_ret[$val] = $entry;
            }
        } else {
            foreach ($cs_ret as $key => $val) {
                $val->merge($ret->get($key));
            }
        }

        return $cs_ret;
    }

    /**
     * Fetch message data.
     *
     * Fetch queries should be grouped in the $queries argument. Each value
     * is an array of fetch options, with the fetch query stored in the
     * '_query' parameter. IMPORTANT: All queries must have the same ID
     * type (either sequence or UID).
     *
     * @param Horde_Imap_Client_Fetch_Results $results  Fetch results.
     * @param array $queries                            The list of queries.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _fetch(Horde_Imap_Client_Fetch_Results $results,
                                       $queries);

    /**
     * Get the list of vanished messages (UIDs that have been expunged since a
     * given mod-sequence value).
     *
     * @param mixed $mailbox   The mailbox to query. Either a
     *                         Horde_Imap_Client_Mailbox object or a string
     *                         (UTF-8).
     * @param integer $modseq  Search for expunged messages after this
     *                         mod-sequence value.
     * @param array $opts      Additional options:
     *   - ids: (Horde_Imap_Client_Ids)  Restrict to these UIDs.
     *          DEFAULT: Returns full list of UIDs vanished (QRESYNC only).
     *                   This option is REQUIRED for non-QRESYNC servers or
     *                   else an empty list will be returned.
     *
     * @return Horde_Imap_Client_Ids  List of UIDs that have vanished.
     *
     * @throws Horde_Imap_Client_NoSupportExtension
     */
    public function vanished($mailbox, $modseq, array $opts = array())
    {
        $this->login();

        if (empty($opts['ids'])) {
            if (!$this->_capability('QRESYNC')) {
                return $this->getIdsOb();
            }
            $opts['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($opts['ids']->isEmpty()) {
            return $this->getIdsOb();
        } elseif ($opts['ids']->sequence) {
            throw new InvalidArgumentException('Vanished requires UIDs.');
        }

        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_AUTO);

        if ($this->_capability('QRESYNC')) {
            if (!$this->_mailboxOb()->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) {
                throw new Horde_Imap_Client_Exception(
                    Horde_Imap_Client_Translation::r("Mailbox does not support mod-sequences."),
                    Horde_Imap_Client_Exception::MBOXNOMODSEQ
                );
            }

            return $this->_vanished(max(1, $modseq), $opts['ids']);
        }

        $ids = $this->resolveIds($mailbox, $opts['ids']);

        $squery = new Horde_Imap_Client_Search_Query();
        $squery->ids($this->getIdsOb($ids->range_string));
        $search = $this->search($mailbox, $squery, array(
            'nocache' => true
        ));

        return $this->getIdsOb(array_diff($ids->ids, $search['match']->ids));
    }

    /**
     * Get the list of vanished messages.
     *
     * @param integer $modseq             Mod-sequence value.
     * @param Horde_Imap_Client_Ids $ids  UIDs.
     *
     * @return Horde_Imap_Client_Ids  List of UIDs that have vanished.
     */
    abstract protected function _vanished($modseq, Horde_Imap_Client_Ids $ids);

    /**
     * Store message flag data (see RFC 3501 [6.4.6]).
     *
     * @param mixed $mailbox  The mailbox containing the messages to modify.
     *                        Either a Horde_Imap_Client_Mailbox object or a
     *                        string (UTF-8).
     * @param array $options  Additional options:
     *   - add: (array) An array of flags to add.
     *          DEFAULT: No flags added.
     *   - ids: (Horde_Imap_Client_Ids) The list of messages to modify.
     *          DEFAULT: All messages in $mailbox will be modified.
     *   - remove: (array) An array of flags to remove.
     *             DEFAULT: No flags removed.
     *   - replace: (array) Replace the current flags with this set
     *              of flags. Overrides both the 'add' and 'remove' options.
     *              DEFAULT: No replace is performed.
     *   - unchangedsince: (integer) Only changes flags if the mod-sequence ID
     *                     of the message is equal or less than this value.
     *                     Requires the CONDSTORE IMAP extension on the server.
     *                     Also requires the mailbox to support mod-sequences.
     *                     Will throw an exception if either condition is not
     *                     met.
     *                     DEFAULT: mod-sequence is ignored when applying
     *                              changes
     *
     * @return Horde_Imap_Client_Ids  A Horde_Imap_Client_Ids object
     *                                containing the list of IDs that failed
     *                                the 'unchangedsince' test.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function store($mailbox, array $options = array())
    {
        // Open mailbox call will handle the login.
        $this->openMailbox($mailbox, Horde_Imap_Client::OPEN_READWRITE);

        /* SEARCHRES requires server support. */
        if (empty($options['ids'])) {
            $options['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($options['ids']->isEmpty()) {
            return $this->getIdsOb();
        } elseif ($options['ids']->search_res &&
                  !$this->_capability('SEARCHRES')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCHRES');
        }

        if (!empty($options['unchangedsince'])) {
            if (!$this->_capability()->isEnabled('CONDSTORE')) {
                throw new Horde_Imap_Client_Exception_NoSupportExtension('CONDSTORE');
            }

            /* RFC 7162 [3.1.2.2] - trying to do a UNCHANGEDSINCE STORE on a
             * mailbox that doesn't support it will return BAD. */
            if (!$this->_mailboxOb()->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) {
                throw new Horde_Imap_Client_Exception(
                    Horde_Imap_Client_Translation::r("Mailbox does not support mod-sequences."),
                    Horde_Imap_Client_Exception::MBOXNOMODSEQ
                );
            }
        }

        return $this->_store($options);
    }

    /**
     * Store message flag data.
     *
     * @param array $options  Additional options.
     *
     * @return Horde_Imap_Client_Ids  A Horde_Imap_Client_Ids object
     *                                containing the list of IDs that failed
     *                                the 'unchangedsince' test.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _store($options);

    /**
     * Copy messages to another mailbox.
     *
     * @param mixed $source   The source mailbox. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param mixed $dest     The destination mailbox. Either a
     *                        Horde_Imap_Client_Mailbox object or a string
     *                        (UTF-8).
     * @param array $options  Additional options:
     *   - create: (boolean) Try to create $dest if it does not exist?
     *             DEFAULT: No.
     *   - force_map: (boolean) Forces the array mapping to always be
     *                returned. [@since 2.19.0]
     *   - ids: (Horde_Imap_Client_Ids) The list of messages to copy.
     *          DEFAULT: All messages in $mailbox will be copied.
     *   - move: (boolean) If true, delete the original messages.
     *           DEFAULT: Original messages are not deleted.
     *
     * @return mixed  An array mapping old UIDs (keys) to new UIDs (values) on
     *                success (only guaranteed if 'force_map' is true) or
     *                true.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function copy($source, $dest, array $options = array())
    {
        // Open mailbox call will handle the login.
        $this->openMailbox($source, empty($options['move']) ? Horde_Imap_Client::OPEN_AUTO : Horde_Imap_Client::OPEN_READWRITE);

        /* SEARCHRES requires server support. */
        if (empty($options['ids'])) {
            $options['ids'] = $this->getIdsOb(Horde_Imap_Client_Ids::ALL);
        } elseif ($options['ids']->isEmpty()) {
            return array();
        } elseif ($options['ids']->search_res &&
                  !$this->_capability('SEARCHRES')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('SEARCHRES');
        }

        $dest = Horde_Imap_Client_Mailbox::get($dest);
        $res = $this->_copy($dest, $options);

        if (($res === true) && !empty($options['force_map'])) {
            /* Need to manually create mapping from Message-ID data. */
            $query = new Horde_Imap_Client_Fetch_Query();
            $query->envelope();
            $fetch = $this->fetch($source, $query, array(
                'ids' => $options['ids']
            ));

            $res = array();
            foreach ($fetch as $val) {
                if ($uid = $this->_getUidByMessageId($dest, $val->getEnvelope()->message_id)) {
                    $res[$val->getUid()] = $uid;
                }
            }
        }

        return $res;
    }

    /**
     * Copy messages to another mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $dest  The destination mailbox.
     * @param array $options                   Additional options.
     *
     * @return mixed  An array mapping old UIDs (keys) to new UIDs (values) on
     *                success (if the IMAP server and/or driver support the
     *                UIDPLUS extension) or true.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _copy(Horde_Imap_Client_Mailbox $dest,
                                      $options);

    /**
     * Set quota limits. The server must support the IMAP QUOTA extension
     * (RFC 2087).
     *
     * @param mixed $root       The quota root. Either a
     *                          Horde_Imap_Client_Mailbox object or a string
     *                          (UTF-8).
     * @param array $resources  The resource values to set. Keys are the
     *                          resource atom name; value is the resource
     *                          value.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function setQuota($root, array $resources = array())
    {
        $this->login();

        if (!$this->_capability('QUOTA')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('QUOTA');
        }

        if (!empty($resources)) {
            $this->_setQuota(Horde_Imap_Client_Mailbox::get($root), $resources);
        }
    }

    /**
     * Set quota limits.
     *
     * @param Horde_Imap_Client_Mailbox $root  The quota root.
     * @param array $resources                 The resource values to set.
     *
     * @return boolean  True on success.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _setQuota(Horde_Imap_Client_Mailbox $root,
                                          $resources);

    /**
     * Get quota limits. The server must support the IMAP QUOTA extension
     * (RFC 2087).
     *
     * @param mixed $root  The quota root. Either a Horde_Imap_Client_Mailbox
     *                     object or a string (UTF-8).
     *
     * @return mixed  An array with resource keys. Each key holds an array
     *                with 2 values: 'limit' and 'usage'.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function getQuota($root)
    {
        $this->login();

        if (!$this->_capability('QUOTA')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('QUOTA');
        }

        return $this->_getQuota(Horde_Imap_Client_Mailbox::get($root));
    }

    /**
     * Get quota limits.
     *
     * @param Horde_Imap_Client_Mailbox $root  The quota root.
     *
     * @return mixed  An array with resource keys. Each key holds an array
     *                with 2 values: 'limit' and 'usage'.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getQuota(Horde_Imap_Client_Mailbox $root);

    /**
     * Get quota limits for a mailbox. The server must support the IMAP QUOTA
     * extension (RFC 2087).
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     *
     * @return mixed  An array with the keys being the quota roots. Each key
     *                holds an array with resource keys: each of these keys
     *                holds an array with 2 values: 'limit' and 'usage'.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function getQuotaRoot($mailbox)
    {
        $this->login();

        if (!$this->_capability('QUOTA')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('QUOTA');
        }

        return $this->_getQuotaRoot(Horde_Imap_Client_Mailbox::get($mailbox));
    }

    /**
     * Get quota limits for a mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     *
     * @return mixed  An array with the keys being the quota roots. Each key
     *                holds an array with resource keys: each of these keys
     *                holds an array with 2 values: 'limit' and 'usage'.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getQuotaRoot(Horde_Imap_Client_Mailbox $mailbox);

    /**
     * Get the ACL rights for a given mailbox. The server must support the
     * IMAP ACL extension (RFC 2086/4314).
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     *
     * @return array  An array with identifiers as the keys and
     *                Horde_Imap_Client_Data_Acl objects as the values.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getACL($mailbox)
    {
        $this->login();
        return $this->_getACL(Horde_Imap_Client_Mailbox::get($mailbox));
    }

    /**
     * Get ACL rights for a given mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     *
     * @return array  An array with identifiers as the keys and
     *                Horde_Imap_Client_Data_Acl objects as the values.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getACL(Horde_Imap_Client_Mailbox $mailbox);

    /**
     * Set ACL rights for a given mailbox/identifier.
     *
     * @param mixed $mailbox      A mailbox. Either a Horde_Imap_Client_Mailbox
     *                            object or a string (UTF-8).
     * @param string $identifier  The identifier to alter (UTF-8).
     * @param array $options      Additional options:
     *   - rights: (string) The rights to alter or set.
     *   - action: (string, optional) If 'add' or 'remove', adds or removes the
     *             specified rights. Sets the rights otherwise.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function setACL($mailbox, $identifier, $options)
    {
        $this->login();

        if (!$this->_capability('ACL')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ACL');
        }

        if (empty($options['rights'])) {
            if (!isset($options['action']) ||
                (($options['action'] != 'add') &&
                 $options['action'] != 'remove')) {
                $this->_deleteACL(
                    Horde_Imap_Client_Mailbox::get($mailbox),
                    Horde_Imap_Client_Utf7imap::Utf8ToUtf7Imap($identifier)
                );
            }
            return;
        }

        $acl = ($options['rights'] instanceof Horde_Imap_Client_Data_Acl)
            ? $options['rights']
            : new Horde_Imap_Client_Data_Acl(strval($options['rights']));

        $options['rights'] = $acl->getString(
            $this->_capability('RIGHTS')
                ? Horde_Imap_Client_Data_AclCommon::RFC_4314
                : Horde_Imap_Client_Data_AclCommon::RFC_2086
        );
        if (isset($options['action'])) {
            switch ($options['action']) {
            case 'add':
                $options['rights'] = '+' . $options['rights'];
                break;
            case 'remove':
                $options['rights'] = '-' . $options['rights'];
                break;
            }
        }

        $this->_setACL(
            Horde_Imap_Client_Mailbox::get($mailbox),
            Horde_Imap_Client_Utf7imap::Utf8ToUtf7Imap($identifier),
            $options
        );
    }

    /**
     * Set ACL rights for a given mailbox/identifier.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     * @param string $identifier                  The identifier to alter
     *                                            (UTF7-IMAP).
     * @param array $options                      Additional options. 'rights'
     *                                            contains the string of
     *                                            rights to set on the server.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _setACL(Horde_Imap_Client_Mailbox $mailbox,
                                        $identifier, $options);

    /**
     * Deletes ACL rights for a given mailbox/identifier.
     *
     * @param mixed $mailbox      A mailbox. Either a Horde_Imap_Client_Mailbox
     *                            object or a string (UTF-8).
     * @param string $identifier  The identifier to delete (UTF-8).
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function deleteACL($mailbox, $identifier)
    {
        $this->login();

        if (!$this->_capability('ACL')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ACL');
        }

        $this->_deleteACL(
            Horde_Imap_Client_Mailbox::get($mailbox),
            Horde_Imap_Client_Utf7imap::Utf8ToUtf7Imap($identifier)
        );
    }

    /**
     * Deletes ACL rights for a given mailbox/identifier.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     * @param string $identifier                  The identifier to delete
     *                                            (UTF7-IMAP).
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _deleteACL(Horde_Imap_Client_Mailbox $mailbox,
                                           $identifier);

    /**
     * List the ACL rights for a given mailbox/identifier. The server must
     * support the IMAP ACL extension (RFC 2086/4314).
     *
     * @param mixed $mailbox      A mailbox. Either a Horde_Imap_Client_Mailbox
     *                            object or a string (UTF-8).
     * @param string $identifier  The identifier to query (UTF-8).
     *
     * @return Horde_Imap_Client_Data_AclRights  An ACL data rights object.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function listACLRights($mailbox, $identifier)
    {
        $this->login();

        if (!$this->_capability('ACL')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ACL');
        }

        return $this->_listACLRights(
            Horde_Imap_Client_Mailbox::get($mailbox),
            Horde_Imap_Client_Utf7imap::Utf8ToUtf7Imap($identifier)
        );
    }

    /**
     * Get ACL rights for a given mailbox/identifier.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     * @param string $identifier                  The identifier to query
     *                                            (UTF7-IMAP).
     *
     * @return Horde_Imap_Client_Data_AclRights  An ACL data rights object.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _listACLRights(Horde_Imap_Client_Mailbox $mailbox,
                                               $identifier);

    /**
     * Get the ACL rights for the current user for a given mailbox. The
     * server must support the IMAP ACL extension (RFC 2086/4314).
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     *
     * @return Horde_Imap_Client_Data_Acl  An ACL data object.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_NoSupportExtension
     */
    public function getMyACLRights($mailbox)
    {
        $this->login();

        if (!$this->_capability('ACL')) {
            throw new Horde_Imap_Client_Exception_NoSupportExtension('ACL');
        }

        return $this->_getMyACLRights(Horde_Imap_Client_Mailbox::get($mailbox));
    }

    /**
     * Get the ACL rights for the current user for a given mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     *
     * @return Horde_Imap_Client_Data_Acl  An ACL data object.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getMyACLRights(Horde_Imap_Client_Mailbox $mailbox);

    /**
     * Return master list of ACL rights available on the server.
     *
     * @return array  A list of ACL rights.
     */
    public function allAclRights()
    {
        $this->login();

        $rights = array(
            Horde_Imap_Client::ACL_LOOKUP,
            Horde_Imap_Client::ACL_READ,
            Horde_Imap_Client::ACL_SEEN,
            Horde_Imap_Client::ACL_WRITE,
            Horde_Imap_Client::ACL_INSERT,
            Horde_Imap_Client::ACL_POST,
            Horde_Imap_Client::ACL_ADMINISTER
        );

        if ($capability = $this->_capability()->getParams('RIGHTS')) {
            // Add rights defined in CAPABILITY string (RFC 4314).
            return array_merge($rights, str_split(reset($capability)));
        }

        // Add RFC 2086 rights (deprecated by RFC 4314, but need to keep for
        // compatibility with old servers).
        return array_merge($rights, array(
            Horde_Imap_Client::ACL_CREATE,
            Horde_Imap_Client::ACL_DELETE
        ));
    }

    /**
     * Get metadata for a given mailbox. The server must support either the
     * IMAP METADATA extension (RFC 5464) or the ANNOTATEMORE extension
     * (http://ietfreport.isoc.org/idref/draft-daboo-imap-annotatemore/).
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     * @param array $entries  The entries to fetch (UTF-8 strings).
     * @param array $options  Additional options:
     *   - depth: (string) Either "0", "1" or "infinity". Returns only the
     *            given value (0), only values one level below the specified
     *            value (1) or all entries below the specified value
     *            (infinity).
     *   - maxsize: (integer) The maximal size the returned values may have.
     *              DEFAULT: No maximal size.
     *
     * @return array  An array with metadata names as the keys and metadata
     *                values as the values. If 'maxsize' is set, and entries
     *                exist on the server larger than this size, the size will
     *                be returned in the key '*longentries'.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getMetadata($mailbox, $entries, array $options = array())
    {
        $this->login();

        if (!is_array($entries)) {
            $entries = array($entries);
        }

        return $this->_getMetadata(Horde_Imap_Client_Mailbox::get($mailbox), array_map(array('Horde_Imap_Client_Utf7imap', 'Utf8ToUtf7Imap'), $entries), $options);
    }

    /**
     * Get metadata for a given mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     * @param array $entries                      The entries to fetch
     *                                            (UTF7-IMAP strings).
     * @param array $options                      Additional options.
     *
     * @return array  An array with metadata names as the keys and metadata
     *                values as the values.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _getMetadata(Horde_Imap_Client_Mailbox $mailbox,
                                             $entries, $options);

    /**
     * Set metadata for a given mailbox/identifier.
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8). If empty, sets a
     *                        server annotation.
     * @param array $data     A set of data values. The metadata values
     *                        corresponding to the keys of the array will
     *                        be set to the values in the array.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function setMetadata($mailbox, $data)
    {
        $this->login();
        $this->_setMetadata(Horde_Imap_Client_Mailbox::get($mailbox), $data);
    }

    /**
     * Set metadata for a given mailbox/identifier.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  A mailbox.
     * @param array $data                         A set of data values. See
     *                                            setMetadata() for format.
     *
     * @throws Horde_Imap_Client_Exception
     */
    abstract protected function _setMetadata(Horde_Imap_Client_Mailbox $mailbox,
                                             $data);

    /* Public utility functions. */

    /**
     * Returns a unique identifier for the current mailbox status.
     *
     * @deprecated
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     * @param array $addl     Additional cache info to add to the cache ID
     *                        string.
     *
     * @return string  The cache ID string, which will change when the
     *                 composition of the mailbox changes. The uidvalidity
     *                 will always be the first element, and will be delimited
     *                 by the '|' character.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getCacheId($mailbox, array $addl = array())
    {
        return Horde_Imap_Client_Base_Deprecated::getCacheId($this, $mailbox, $this->_capability()->isEnabled('CONDSTORE'), $addl);
    }

    /**
     * Parses a cacheID created by getCacheId().
     *
     * @deprecated
     *
     * @param string $id  The cache ID.
     *
     * @return array  An array with the following information:
     *   - highestmodseq: (integer)
     *   - messages: (integer)
     *   - uidnext: (integer)
     *   - uidvalidity: (integer) Always present
     */
    public function parseCacheId($id)
    {
        return Horde_Imap_Client_Base_Deprecated::parseCacheId($id);
    }

    /**
     * Resolves an IDs object into a list of IDs.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox.
     * @param Horde_Imap_Client_Ids $ids          The Ids object.
     * @param integer $convert                    Convert to UIDs?
     *   - 0: No
     *   - 1: Only if $ids is not already a UIDs object
     *   - 2: Always
     *
     * @return Horde_Imap_Client_Ids  The list of IDs.
     */
    public function resolveIds(Horde_Imap_Client_Mailbox $mailbox,
                               Horde_Imap_Client_Ids $ids, $convert = 0)
    {
        $map = $this->_mailboxOb($mailbox)->map;

        if ($ids->special) {
            /* Optimization for ALL sequence searches. */
            if (!$convert && $ids->all && $ids->sequence) {
                $res = $this->status($mailbox, Horde_Imap_Client::STATUS_MESSAGES);
                return $this->getIdsOb($res['messages'] ? ('1:' . $res['messages']) : array(), true);
            }

            $convert = 2;
        } elseif (!$convert ||
                  (!$ids->sequence && ($convert == 1)) ||
                  $ids->isEmpty()) {
            return clone $ids;
        } else {
            /* Do an all or nothing: either we have all the numbers/UIDs in
             * memory and can return, or just send the whole ID query to the
             * server. Any advantage we would get by a partial search are
             * outweighed by the complexities needed to make the search and
             * then merge back into the original results. */
            $lookup = $map->lookup($ids);
            if (count($lookup) === count($ids)) {
                return $this->getIdsOb(array_values($lookup));
            }
        }

        $query = new Horde_Imap_Client_Search_Query();
        $query->ids($ids);

        $res = $this->search($mailbox, $query, array(
            'results' => array(
                Horde_Imap_Client::SEARCH_RESULTS_MATCH,
                Horde_Imap_Client::SEARCH_RESULTS_SAVE
            ),
            'sequence' => (!$convert && $ids->sequence),
            'sort' => array(Horde_Imap_Client::SORT_SEQUENCE)
        ));

        /* Update mapping. */
        if ($convert) {
            if ($ids->all) {
                $ids = $this->getIdsOb('1:' . count($res['match']));
            } elseif ($ids->special) {
                return $res['match'];
            }

            /* Sanity checking (Bug #12911). */
            $list1 = array_slice($ids->ids, 0, count($res['match']));
            $list2 = $res['match']->ids;
            if (!empty($list1) &&
                !empty($list2) &&
                (count($list1) === count($list2))) {
                $map->update(array_combine($list1, $list2));
            }
        }

        return $res['match'];
    }

    /**
     * Determines if the given charset is valid for search-related queries.
     * This check pertains just to the basic IMAP SEARCH command.
     *
     * @deprecated Use $search_charset property instead.
     *
     * @param string $charset  The query charset.
     *
     * @return boolean  True if server supports this charset.
     */
    public function validSearchCharset($charset)
    {
        return $this->search_charset->query($charset);
    }

    /* Mailbox syncing functions. */

    /**
     * Returns a unique token for the current mailbox synchronization status.
     *
     * @since 2.2.0
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     *
     * @return string  The sync token.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function getSyncToken($mailbox)
    {
        $out = array();

        foreach ($this->_syncStatus($mailbox) as $key => $val) {
            $out[] = $key . $val;
        }

        return base64_encode(implode(',', $out));
    }

    /**
     * Synchronize a mailbox from a sync token.
     *
     * @since 2.2.0
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     * @param string $token   A sync token generated by getSyncToken().
     * @param array $opts     Additional options:
     *   - criteria: (integer) Mask of Horde_Imap_Client::SYNC_* criteria to
     *               return. Defaults to SYNC_ALL.
     *   - ids: (Horde_Imap_Client_Ids) A cached list of UIDs. Unless QRESYNC
     *          is available on the server, failure to specify this option
     *          means SYNC_VANISHEDUIDS information cannot be returned.
     *
     * @return Horde_Imap_Client_Data_Sync  A sync object.
     *
     * @throws Horde_Imap_Client_Exception
     * @throws Horde_Imap_Client_Exception_Sync
     */
    public function sync($mailbox, $token, array $opts = array())
    {
        if (($token = base64_decode($token, true)) === false) {
            throw new Horde_Imap_Client_Exception_Sync('Bad token.', Horde_Imap_Client_Exception_Sync::BAD_TOKEN);
        }

        $sync = array();
        foreach (explode(',', $token) as $val) {
            $sync[substr($val, 0, 1)] = substr($val, 1);
        }

        return new Horde_Imap_Client_Data_Sync(
            $this,
            $mailbox,
            $sync,
            $this->_syncStatus($mailbox),
            (isset($opts['criteria']) ? $opts['criteria'] : Horde_Imap_Client::SYNC_ALL),
            (isset($opts['ids']) ? $opts['ids'] : null)
        );
    }

    /* Private utility functions. */

    /**
     * Store FETCH data in cache.
     *
     * @param Horde_Imap_Client_Fetch_Results $data  The fetch results.
     *
     * @throws Horde_Imap_Client_Exception
     */
    protected function _updateCache(Horde_Imap_Client_Fetch_Results $data)
    {
        if (!empty($this->_temp['fetch_nocache']) ||
            empty($this->_selected) ||
            !count($data) ||
            !$this->_initCache(true)) {
            return;
        }

        $c = $this->getParam('cache');
        if (in_array(strval($this->_selected), $c['fetch_ignore'])) {
            $this->_debug->info(sprintf(
                'CACHE: Ignoring FETCH data [%s]',
                $this->_selected
            ));
            return;
        }

        /* Optimization: we can directly use getStatus() here since we know
         * these values are initialized. */
        $mbox_ob = $this->_mailboxOb();
        $highestmodseq = $mbox_ob->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ);
        $uidvalidity = $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY);

        $mapping = $modseq = $tocache = array();
        if (count($data)) {
            $cf = $this->_cacheFields();
        }

        foreach ($data as $v) {
            /* It is possible that we received FETCH information that doesn't
             * contain UID data. This is uncacheable so don't process. */
            if (!($uid = $v->getUid())) {
                return;
            }

            $tmp = array();

            if ($v->isDowngraded()) {
                $tmp[self::CACHE_DOWNGRADED] = true;
            }

            foreach ($cf as $key => $val) {
                if ($v->exists($key)) {
                    switch ($key) {
                    case Horde_Imap_Client::FETCH_ENVELOPE:
                        $tmp[$val] = $v->getEnvelope();
                        break;

                    case Horde_Imap_Client::FETCH_FLAGS:
                        if ($highestmodseq) {
                            $modseq[$uid] = $v->getModSeq();
                            $tmp[$val] = $v->getFlags();
                        }
                        break;

                    case Horde_Imap_Client::FETCH_HEADERS:
                        foreach ($this->_temp['headers_caching'] as $label => $hash) {
                            if ($hdr = $v->getHeaders($label)) {
                                $tmp[$val][$hash] = $hdr;
                            }
                        }
                        break;

                    case Horde_Imap_Client::FETCH_IMAPDATE:
                        $tmp[$val] = $v->getImapDate();
                        break;

                    case Horde_Imap_Client::FETCH_SIZE:
                        $tmp[$val] = $v->getSize();
                        break;

                    case Horde_Imap_Client::FETCH_STRUCTURE:
                        $tmp[$val] = clone $v->getStructure();
                        break;
                    }
                }
            }

            if (!empty($tmp)) {
                $tocache[$uid] = $tmp;
            }

            $mapping[$v->getSeq()] = $uid;
        }

        if (!empty($mapping)) {
            if (!empty($tocache)) {
                $this->_cache->set($this->_selected, $tocache, $uidvalidity);
            }

            $this->_mailboxOb()->map->update($mapping);
        }

        if (!empty($modseq)) {
            $this->_updateModSeq(max(array_merge($modseq, array($highestmodseq))));
            $mbox_ob->setStatus(Horde_Imap_Client::STATUS_SYNCFLAGUIDS, array_keys($modseq));
        }
    }

    /**
     * Moves cache entries from the current mailbox to another mailbox.
     *
     * @param Horde_Imap_Client_Mailbox $to  The destination mailbox.
     * @param array $map                     Mapping of source UIDs (keys) to
     *                                       destination UIDs (values).
     * @param string $uidvalid               UIDVALIDITY of destination
     *                                       mailbox.
     *
     * @throws Horde_Imap_Client_Exception
     */
    protected function _moveCache(Horde_Imap_Client_Mailbox $to, $map,
                                  $uidvalid)
    {
        if (!$this->_initCache()) {
            return;
        }

        $c = $this->getParam('cache');
        if (in_array(strval($to), $c['fetch_ignore'])) {
            $this->_debug->info(sprintf(
                'CACHE: Ignoring moving FETCH data (%s => %s)',
                $this->_selected,
                $to
            ));
            return;
        }

        $old = $this->_cache->get($this->_selected, array_keys($map), null);
        $new = array();

        foreach ($map as $key => $val) {
            if (!empty($old[$key])) {
                $new[$val] = $old[$key];
            }
        }

        if (!empty($new)) {
            $this->_cache->set($to, $new, $uidvalid);
        }
    }

    /**
     * Delete messages in the cache.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox.
     * @param Horde_Imap_Client_Ids $ids          The list of IDs to delete in
     *                                            $mailbox.
     * @param array $opts                         Additional options (not used
     *                                            in base class).
     *
     * @return Horde_Imap_Client_Ids  UIDs that were deleted.
     * @throws Horde_Imap_Client_Exception
     */
    protected function _deleteMsgs(Horde_Imap_Client_Mailbox $mailbox,
                                   Horde_Imap_Client_Ids $ids,
                                   array $opts = array())
    {
        if (!$this->_initCache()) {
            return $ids;
        }

        $mbox_ob = $this->_mailboxOb();
        $ids_ob = $ids->sequence
            ? $this->getIdsOb($mbox_ob->map->lookup($ids))
            : $ids;

        $this->_cache->deleteMsgs($mailbox, $ids_ob->ids);
        $mbox_ob->setStatus(Horde_Imap_Client::STATUS_SYNCVANISHED, $ids_ob->ids);
        $mbox_ob->map->remove($ids);

        return $ids_ob;
    }

    /**
     * Retrieve data from the search cache.
     *
     * @param string $type    The cache type ('search' or 'thread').
     * @param array $options  The options array of the calling function.
     *
     * @return mixed  Returns search cache metadata. If search was retrieved,
     *                data is in key 'data'.
     *                Returns null if caching is not available.
     */
    protected function _getSearchCache($type, $options)
    {
        $status = $this->status($this->_selected, Horde_Imap_Client::STATUS_HIGHESTMODSEQ | Horde_Imap_Client::STATUS_UIDVALIDITY);

        /* Search caching requires MODSEQ, which may not be active for a
         * mailbox. */
        if (empty($status['highestmodseq'])) {
            return null;
        }

        ksort($options);
        $cache = hash(
            (PHP_MINOR_VERSION >= 4) ? 'fnv132' : 'sha1',
            $type . serialize($options)
        );
        $cacheid = $this->getSyncToken($this->_selected);
        $ret = array();

        $md = $this->_cache->getMetaData(
            $this->_selected,
            $status['uidvalidity'],
            array(self::CACHE_SEARCH, self::CACHE_SEARCHID)
        );

        if (!isset($md[self::CACHE_SEARCHID]) ||
            ($md[self::CACHE_SEARCHID] != $cacheid)) {
            $md[self::CACHE_SEARCH] = array();
            $md[self::CACHE_SEARCHID] = $cacheid;
            if ($this->_debug->debug &&
                !isset($this->_temp['searchcacheexpire'][strval($this->_selected)])) {
                $this->_debug->info(sprintf(
                    'SEARCH: Expired from cache [%s]',
                    $this->_selected
                ));
                $this->_temp['searchcacheexpire'][strval($this->_selected)] = true;
            }
        } elseif (isset($md[self::CACHE_SEARCH][$cache])) {
            $this->_debug->info(sprintf(
                'SEARCH: Retrieved %s from cache (%s [%s])',
                $type,
                $cache,
                $this->_selected
            ));
            $ret['data'] = $md[self::CACHE_SEARCH][$cache];
            unset($md[self::CACHE_SEARCHID]);
        }

        return array_merge($ret, array(
            'id' => $cache,
            'metadata' => $md,
            'type' => $type
        ));
    }

    /**
     * Set data in the search cache.
     *
     * @param mixed $data    The cache data to store.
     * @param string $sdata  The search data returned from _getSearchCache().
     */
    protected function _setSearchCache($data, $sdata)
    {
        $sdata['metadata'][self::CACHE_SEARCH][$sdata['id']] = $data;

        $this->_cache->setMetaData($this->_selected, null, $sdata['metadata']);

        if ($this->_debug->debug) {
            $this->_debug->info(sprintf(
                'SEARCH: Saved %s to cache (%s [%s])',
                $sdata['type'],
                $sdata['id'],
                $this->_selected
            ));
            unset($this->_temp['searchcacheexpire'][strval($this->_selected)]);
        }
    }

    /**
     * Updates the cached MODSEQ value.
     *
     * @param integer $modseq  MODSEQ value to store.
     *
     * @return mixed  The MODSEQ of the old value if it was replaced (or false
     *                if it didn't exist or is the same).
     */
    protected function _updateModSeq($modseq)
    {
        if (!$this->_initCache(true)) {
            return false;
        }

        $mbox_ob = $this->_mailboxOb();
        $uidvalid = $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY);
        $md = $this->_cache->getMetaData($this->_selected, $uidvalid, array(self::CACHE_MODSEQ));

        if (isset($md[self::CACHE_MODSEQ])) {
            if ($md[self::CACHE_MODSEQ] < $modseq) {
                $set = true;
                $sync = $md[self::CACHE_MODSEQ];
            } else {
                $set = false;
                $sync = 0;
            }
            $mbox_ob->setStatus(Horde_Imap_Client::STATUS_SYNCMODSEQ, $md[self::CACHE_MODSEQ]);
        } else {
            $set = true;
            $sync = 0;
        }

        if ($set) {
            $this->_cache->setMetaData($this->_selected, $uidvalid, array(
                self::CACHE_MODSEQ => $modseq
            ));
        }

        return $sync;
    }

    /**
     * Synchronizes the current mailbox cache with the server (using CONDSTORE
     * or QRESYNC).
     */
    protected function _condstoreSync()
    {
        $mbox_ob = $this->_mailboxOb();

        /* Check that modseqs are available in mailbox. */
        if (!($highestmodseq = $mbox_ob->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) ||
            !($modseq = $this->_updateModSeq($highestmodseq))) {
            $mbox_ob->sync = true;
        }

        if ($mbox_ob->sync) {
            return;
        }

        $uids_ob = $this->getIdsOb($this->_cache->get(
            $this->_selected,
            array(),
            array(),
            $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY)
        ));

        if (!count($uids_ob)) {
            $mbox_ob->sync = true;
            return;
        }

        /* Are we caching flags? */
        if (array_key_exists(Horde_Imap_Client::FETCH_FLAGS, $this->_cacheFields())) {
            $fquery = new Horde_Imap_Client_Fetch_Query();
            $fquery->flags();

            /* Update flags in cache. Cache will be updated in _fetch(). */
            $this->_fetch(new Horde_Imap_Client_Fetch_Results(), array(
                array(
                    '_query' => $fquery,
                    'changedsince' => $modseq,
                    'ids' => $uids_ob
                )
            ));
        }

        /* Search for deleted messages, and remove from cache. */
        $vanished = $this->vanished($this->_selected, $modseq, array(
            'ids' => $uids_ob
        ));
        $disappear = array_diff($uids_ob->ids, $vanished->ids);
        if (!empty($disappear)) {
            $this->_deleteMsgs($this->_selected, $this->getIdsOb($disappear));
        }

        $mbox_ob->sync = true;
    }

    /**
     * Provide the list of available caching fields.
     *
     * @return array  The list of available caching fields (fields are in the
     *                key).
     */
    protected function _cacheFields()
    {
        $c = $this->getParam('cache');
        $out = $c['fields'];

        if (!$this->_capability()->isEnabled('CONDSTORE')) {
            unset($out[Horde_Imap_Client::FETCH_FLAGS]);
        }

        return $out;
    }

    /**
     * Return the current mailbox synchronization status.
     *
     * @param mixed $mailbox  A mailbox. Either a Horde_Imap_Client_Mailbox
     *                        object or a string (UTF-8).
     *
     * @return array  An array with status data. (This data is not guaranteed
     *                to have any specific format).
     */
    protected function _syncStatus($mailbox)
    {
        $status = $this->status(
            $mailbox,
            Horde_Imap_Client::STATUS_HIGHESTMODSEQ |
            Horde_Imap_Client::STATUS_MESSAGES |
            Horde_Imap_Client::STATUS_UIDNEXT_FORCE |
            Horde_Imap_Client::STATUS_UIDVALIDITY
        );

        $fields = array('uidnext', 'uidvalidity');
        if (empty($status['highestmodseq'])) {
            $fields[] = 'messages';
        } else {
            $fields[] = 'highestmodseq';
        }

        $out = array();
        $sync_map = array_flip(Horde_Imap_Client_Data_Sync::$map);

        foreach ($fields as $val) {
            $out[$sync_map[$val]] = $status[$val];
        }

        return array_filter($out);
    }

    /**
     * Get a message UID by the Message-ID. Returns the last message in a
     * mailbox that matches.
     *
     * @param Horde_Imap_Client_Mailbox $mailbox  The mailbox to search
     * @param string $msgid                       Message-ID.
     *
     * @return string  UID (null if not found).
     */
    protected function _getUidByMessageId($mailbox, $msgid)
    {
        if (!$msgid) {
            return null;
        }

        $query = new Horde_Imap_Client_Search_Query();
        $query->headerText('Message-ID', $msgid);
        $res = $this->search($mailbox, $query, array(
            'results' => array(Horde_Imap_Client::SEARCH_RESULTS_MAX)
        ));

        return $res['max'];
    }

}