summaryrefslogtreecommitdiff
path: root/ext/imap/php_imap.c
blob: c4be4a392eb96b66c09973bc8853c269f6412a94 (plain)
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
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
/*
   +----------------------------------------------------------------------+
   | PHP version 4.0                                                      |
   +----------------------------------------------------------------------+
   | Copyright (c) 1997-2001 The PHP Group                                |
   +----------------------------------------------------------------------+
   | This source file is subject to version 2.02 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available at through the world-wide-web at                           |
   | http://www.php.net/license/2_02.txt.                                 |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Authors: Rex Logan           <veebert@dimensional.com>               |
   |          Mark Musone         <musone@afterfive.com>                  |
   |          Brian Wang          <brian@vividnet.com>                    |
   |          Kaj-Michael Lang    <milang@tal.org>                        |
   |          Antoni Pamies Olive <toni@readysoft.net>                    |
   |          Rasmus Lerdorf      <rasmus@lerdorf.on.ca>                  |
   |          Chuck Hagenbuch     <chuck@horde.org>                       |
   |          Andrew Skalski      <askalski@chekinc.com>                  |
   |          Hartmut Holzgraefe  <hartmut@six.de>                        |
   |          Jani Taskinen       <sniper@iki.fi>                         |
   | PHP 4.0 updates:  Zeev Suraski <zeev@zend.com>                       |
   +----------------------------------------------------------------------+
 */
/* $Id$ */

#define IMAP41

#undef OP_RELOGIN

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/php_string.h"
#include "ext/standard/info.h"

#ifdef ERROR
#undef ERROR
#endif
#include "php_imap.h"

ZEND_DECLARE_MODULE_GLOBALS(imap)

#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
#ifdef PHP_WIN32
#include "winsock.h"
MAILSTREAM DEFAULTPROTO;
#endif

#define CRLF	"\015\012"
#define PHP_EXPUNGE 32768

static void _php_make_header_object(zval *myzvalue, ENVELOPE *en);
static void _php_imap_add_body(zval *arg, BODY *body);
static void _php_imap_parse_address(ADDRESS *addresslist, char *fulladdress, zval *paddress);


/* These function declarations are missing from the IMAP header files... */
void rfc822_date(char *date);
char *cpystr(const char *str);
char *cpytxt(SIZEDTEXT *dst, char *text, unsigned long size);
long utf8_mime2text(SIZEDTEXT *src, SIZEDTEXT *dst);
unsigned long find_rightmost_bit(unsigned long *valptr);
void fs_give(void **block);
void *fs_get(size_t size);
int imap_mail(char *to, char *subject, char *message, char *headers, char *cc, char *bcc, char *rpath);


void mail_close_it (zend_rsrc_list_entry *rsrc);
#ifdef OP_RELOGIN
/* AJS: close persistent connection */
void mail_userlogout_it(zend_rsrc_list_entry *rsrc);
void mail_nuke_chain(zend_rsrc_list_entry *rsrc);
#endif

/* {{{ imap_functions[]
 */
function_entry imap_functions[] = {
	PHP_FE(imap_open,			NULL)
	PHP_FE(imap_popen,			NULL)
	PHP_FE(imap_reopen,			NULL)
	PHP_FE(imap_num_msg,		NULL)
	PHP_FE(imap_num_recent,		NULL)
	PHP_FE(imap_headers,		NULL)
	PHP_FALIAS(imap_header, imap_headerinfo, NULL)
	PHP_FE(imap_headerinfo,		NULL)
	PHP_FE(imap_rfc822_parse_headers,	NULL)
	PHP_FE(imap_body,			NULL)
	PHP_FE(imap_fetchstructure,	NULL)
	PHP_FE(imap_fetchbody,		NULL)
	PHP_FE(imap_expunge,		NULL)
	PHP_FE(imap_delete,			NULL)
	PHP_FE(imap_undelete,		NULL)
	PHP_FE(imap_check,			NULL)
	PHP_FE(imap_close,			NULL)
	PHP_FE(imap_mail_copy,		NULL)
	PHP_FE(imap_mail_move,		NULL)
	PHP_FE(imap_createmailbox,	NULL)
	PHP_FE(imap_renamemailbox,	NULL)
	PHP_FE(imap_deletemailbox,	NULL)
#ifdef HAVE_IMAP2000
	PHP_FE(imap_get_quota,		NULL)
	PHP_FE(imap_set_quota,		NULL)
#endif
	PHP_FALIAS(imap_listmailbox, imap_list,	NULL)
	PHP_FALIAS(imap_getmailboxes, imap_list_full,	NULL)
	PHP_FALIAS(imap_scanmailbox, imap_listscan,	NULL)
	PHP_FALIAS(imap_listsubscribed, imap_lsub,	NULL)
	PHP_FALIAS(imap_getsubscribed, imap_lsub_full,	NULL)
	PHP_FE(imap_subscribe,		NULL)
	PHP_FE(imap_unsubscribe,	NULL)
	PHP_FE(imap_append,			NULL)
	PHP_FE(imap_ping,			NULL)
	PHP_FE(imap_base64,			NULL)
	PHP_FE(imap_qprint,			NULL)
	PHP_FE(imap_8bit,			NULL)
	PHP_FE(imap_binary,			NULL)
	PHP_FE(imap_mailboxmsginfo,	NULL)
	PHP_FE(imap_rfc822_write_address,		NULL)
	PHP_FE(imap_rfc822_parse_adrlist,		NULL)
	PHP_FE(imap_setflag_full,	NULL)
	PHP_FE(imap_clearflag_full,	NULL)
	PHP_FE(imap_sort,			NULL)
	PHP_FE(imap_fetchheader,	NULL)
	PHP_FALIAS(imap_fetchtext,	imap_body,		NULL)
	PHP_FE(imap_uid,			NULL)
	PHP_FE(imap_msgno,			NULL)
	PHP_FE(imap_list,			NULL)
	PHP_FALIAS(imap_scan,		imap_listscan,			NULL)
	PHP_FE(imap_lsub,			NULL)
	PHP_FALIAS(imap_create,		imap_createmailbox,			NULL)
	PHP_FALIAS(imap_rename,		imap_renamemailbox,			NULL)
	PHP_FE(imap_status,			NULL)
	PHP_FE(imap_bodystruct,		NULL)
	PHP_FE(imap_fetch_overview,	NULL)
	PHP_FE(imap_mail_compose,	NULL)
	PHP_FE(imap_alerts,			NULL)
	PHP_FE(imap_errors,			NULL)
	PHP_FE(imap_last_error,		NULL)
#ifndef PHP_WIN32
	PHP_FE(imap_mail,           NULL)
#else
	PHP_FALIAS(imap_mail, warn_not_available, NULL)
#endif
	PHP_FE(imap_search,			NULL)
	PHP_FE(imap_utf7_decode,	NULL)
	PHP_FE(imap_utf7_encode,	NULL)
	PHP_FE(imap_utf8,       	NULL)
	PHP_FE(imap_mime_header_decode,	NULL)
	PHP_FE(imap_thread,		NULL)
	{NULL, NULL, NULL}
};
/* }}} */

#ifdef OP_RELOGIN
#define IS_STREAM(ind_type)     ((ind_type)==le_imap || (ind_type)==le_pimap)
#else
#define IS_STREAM(ind_type)     ((ind_type)==le_imap)
#endif


zend_module_entry imap_module_entry = {
    "imap", imap_functions, PHP_MINIT(imap), NULL, PHP_RINIT(imap), PHP_RSHUTDOWN(imap), PHP_MINFO(imap), STANDARD_MODULE_PROPERTIES
};


#ifdef COMPILE_DL_IMAP
ZEND_GET_MODULE(imap)
#endif


static int le_imap;
#ifdef OP_RELOGIN
/* AJS: persistent connection type, chain pointer type */
static int le_pimap;
static int le_pimapchain;
#endif


void mail_close_it(zend_rsrc_list_entry *rsrc)
{
	pils *imap_le_struct = (pils *)rsrc->ptr;
	TSRMLS_FETCH();

	mail_close_full(imap_le_struct->imap_stream, imap_le_struct->flags);

	if (IMAPG(imap_user)) {
		efree(IMAPG(imap_user));
		IMAPG(imap_user) = 0;
	}
	if (IMAPG(imap_password)) {
		efree(IMAPG(imap_password));
		IMAPG(imap_password) = 0;
	}

	efree(imap_le_struct);
}

#ifdef OP_RELOGIN
/* AJS: stream close functions for persistent connections */
void mail_userlogout_it(zend_rsrc_list_entry *rsrc)
{
	pils *imap_le_struct = (pils *)rsrc->ptr;
	/* Close this user's session, putting the stream back
	 * into AUTHENTICATE state.  (Note that IMAP does not
	 * support this behavior... yet)
	 */
	imap_le_struct->busy = 0;
	mail_close_full(imap_le_struct->imap_stream, imap_le_struct->flags | CL_HALF);
}

void mail_nuke_chain(zend_rsrc_list_entry *rsrc)
{
	pils **headp = (pils **)rsrc->ptr;
	pils		*node, *next;

	for (node = *headp; node; node = next) {
		next = node->next;
		mail_close(node->imap_stream);
		free(node);
	}

	free(headp);
}
#endif

static int add_assoc_object(zval *arg, char *key, zval *tmp)
{
	HashTable *symtable;
	
	if (arg->type == IS_OBJECT) {
		symtable = arg->value.obj.properties;
	} else {
		symtable = arg->value.ht;
	}
	return zend_hash_update(symtable, key, strlen(key)+1, (void *) &tmp, sizeof(zval *), NULL);
}

/* Mail instantiate FOBJECTLIST
 * Returns: new FOBJECTLIST list
 * Author: CJH
 */
FOBJECTLIST *mail_newfolderobjectlist(void)
{
  return (FOBJECTLIST *) memset(fs_get(sizeof(FOBJECTLIST)),0,
				sizeof(FOBJECTLIST));
}


/* Mail garbage collect FOBJECTLIST
 * Accepts: pointer to FOBJECTLIST pointer
 * Author: CJH
 */
void mail_free_foblist(FOBJECTLIST **foblist)
{
	if (*foblist) {		/* only free if exists */
		if ((*foblist)->text.data) {
			fs_give ((void **) &(*foblist)->text.data);
		}
		mail_free_foblist (&(*foblist)->next);
		fs_give ((void **) foblist);	/* return string to free storage */
	}
}


/* Mail instantiate ERRORLIST
 * Returns: new ERRORLIST list
 * Author: CJH
 */
ERRORLIST *mail_newerrorlist(void)
{
	return (ERRORLIST *) memset(fs_get(sizeof(ERRORLIST)), 0, sizeof(ERRORLIST));
}

/* Mail garbage collect FOBJECTLIST
 * Accepts: pointer to FOBJECTLIST pointer
 * Author: CJH
 */
void mail_free_errorlist(ERRORLIST **errlist)
{
	if (*errlist) {		/* only free if exists */
		if ((*errlist)->text.data) {
			fs_give((void **) &(*errlist)->text.data);
		}
		mail_free_errorlist (&(*errlist)->next);
		fs_give((void **) errlist);	/* return string to free storage */
	}
}


/* Author: CJH */
PHP_RINIT_FUNCTION(imap)
{
	IMAPG(imap_errorstack) = NIL;
	IMAPG(imap_alertstack) = NIL;
	return SUCCESS;
}

/* Author: CJH */
PHP_RSHUTDOWN_FUNCTION(imap)
{
	ERRORLIST *ecur = NIL;
	STRINGLIST *acur = NIL;

	if (IMAPG(imap_errorstack) != NIL) {
		/* output any remaining errors at their original error level */
		ecur = IMAPG(imap_errorstack);
		while (ecur != NIL) {
			php_error(E_NOTICE, "%s (errflg=%d)", ecur->LTEXT, ecur->errflg);
			ecur = ecur->next;
		}
		mail_free_errorlist(&IMAPG(imap_errorstack));
	}

	if (IMAPG(imap_alertstack) != NIL) {
		/* output any remaining alerts at E_NOTICE level */
		acur = IMAPG(imap_alertstack);
		while (acur != NIL) {
			php_error(E_NOTICE, acur->LTEXT);
			acur = acur->next;
		}
		mail_free_stringlist(&IMAPG(imap_alertstack));
	}
	return SUCCESS;
}


static inline int add_next_index_object(zval *arg, zval *tmp)
{
	HashTable *symtable;
	
	if (arg->type == IS_OBJECT) {
		symtable = arg->value.obj.properties;
	} else {
		symtable = arg->value.ht;
	}

	return zend_hash_next_index_insert(symtable, (void *) &tmp, sizeof(zval *), NULL); 
}


/* Mail instantiate MESSAGELIST
 * Returns: new MESSAGELIST list
 * Author: CJH
 */
MESSAGELIST *mail_newmessagelist(void)
{
	return (MESSAGELIST *) memset(fs_get(sizeof(MESSAGELIST)),0,
								  sizeof(MESSAGELIST));
}

#ifdef HAVE_IMAP2000
/* Mail GET_QUOTA callback
 * Called via the mail_parameter function in c-client:src/c-client/mail.c
 * Author DRK
 */
void mail_getquota(MAILSTREAM *stream, char *qroot,QUOTALIST *qlist)
{
	TSRMLS_FETCH();

	/* this should only be run through once */
	for (; qlist; qlist = qlist->next)
	{
		IMAPG(quota_usage) = qlist->usage;
		IMAPG(quota_limit) = qlist->limit;
	}
}
#endif

/* Mail garbage collect MESSAGELIST
 * Accepts: pointer to MESSAGELIST pointer
 * Author: CJH
 */
void mail_free_messagelist(MESSAGELIST **msglist)
{
	if (*msglist) {		/* only free if exists */
		mail_free_messagelist (&(*msglist)->next);
		fs_give ((void **) msglist);	/* return string to free storage */
	}
}

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(imap)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "IMAP Support", "enabled" );
#if HAVE_IMAP2000
	php_info_print_table_row(2, "IMAP c-Client Version", "2000");               
#elif defined(IMAP41)
	php_info_print_table_row(2, "IMAP c-Client Version", "4.1");               
#else
	php_info_print_table_row(2, "IMAP c-Client Version", "4.0"); 
#endif
#if HAVE_IMAP_SSL
	php_info_print_table_row(2, "SSL Support", "enabled"); 
#endif
#if HAVE_IMAP_KRB
	php_info_print_table_row(2, "Kerberos Support", "enabled"); 
#endif
	php_info_print_table_end();
}
/* }}} */

static void php_imap_init_globals(zend_imap_globals *imap_globals)
{
	imap_globals->imap_user=NIL;
	imap_globals->imap_password=NIL;
	imap_globals->imap_folders=NIL;
	imap_globals->imap_sfolders=NIL;
	imap_globals->imap_alertstack=NIL;
	imap_globals->imap_errorstack=NIL;
	imap_globals->imap_messages=NIL;
	imap_globals->imap_folder_objects=NIL;
	imap_globals->imap_sfolder_objects=NIL;
	imap_globals->folderlist_style = FLIST_ARRAY;
}

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(imap)
{
	unsigned long sa_all =	SA_MESSAGES | SA_RECENT | SA_UNSEEN |
				SA_UIDNEXT | SA_UIDVALIDITY;

	ZEND_INIT_MODULE_GLOBALS(imap, php_imap_init_globals, NULL)


#if 1
#ifndef PHP_WIN32
	mail_link(&unixdriver);		/* link in the unix driver */
#endif
	mail_link(&imapdriver);		/* link in the imap driver */
	mail_link(&nntpdriver);		/* link in the nntp driver */
	mail_link(&pop3driver);		/* link in the pop3 driver */
#ifndef PHP_WIN32
	mail_link(&mhdriver);		/* link in the mh driver */
	mail_link(&mxdriver);		/* link in the mx driver */
#endif
	mail_link(&mbxdriver);		/* link in the mbx driver */
	mail_link(&tenexdriver);	/* link in the tenex driver */
	mail_link(&mtxdriver);		/* link in the mtx driver */
#ifndef PHP_WIN32
	mail_link(&mmdfdriver);		/* link in the mmdf driver */
	mail_link(&newsdriver);		/* link in the news driver */
	mail_link(&philedriver);	/* link in the phile driver */
	auth_link(&auth_log);		/* link in the log authenticator */
	auth_link(&auth_md5);       /* link in the cram-md5 authenticator */ 
#ifdef  HAVE_IMAP_SSL
	ssl_onceonlyinit ();
#endif
#endif
	mail_link(&dummydriver);	/* link in the dummy driver */
#else
	/* link in the c-client mail and auth drivers */
#include "linkage.c"
#endif

	/* lets allow NIL */

	REGISTER_MAIN_LONG_CONSTANT("NIL", NIL, CONST_PERSISTENT | CONST_CS);


	/* Open Options */

	REGISTER_MAIN_LONG_CONSTANT("OP_DEBUG", OP_DEBUG, CONST_PERSISTENT | CONST_CS);
	/* debug protocol negotiations */

	REGISTER_MAIN_LONG_CONSTANT("OP_READONLY", OP_READONLY, CONST_PERSISTENT | CONST_CS);
	/* read-only open */

	REGISTER_MAIN_LONG_CONSTANT("OP_ANONYMOUS", OP_ANONYMOUS, CONST_PERSISTENT | CONST_CS);
	/* anonymous open of newsgroup */

	REGISTER_MAIN_LONG_CONSTANT("OP_SHORTCACHE", OP_SHORTCACHE, CONST_PERSISTENT | CONST_CS);

	/* short (elt-only) caching */

	REGISTER_MAIN_LONG_CONSTANT("OP_SILENT", OP_SILENT, CONST_PERSISTENT | CONST_CS);
	/* don't pass up events (internal use) */
	REGISTER_MAIN_LONG_CONSTANT("OP_PROTOTYPE", OP_PROTOTYPE, CONST_PERSISTENT | CONST_CS);
	/* return driver prototype */
	REGISTER_MAIN_LONG_CONSTANT("OP_HALFOPEN", OP_HALFOPEN, CONST_PERSISTENT | CONST_CS);
	/* half-open (IMAP connect but no select) */

	REGISTER_MAIN_LONG_CONSTANT("OP_EXPUNGE", OP_EXPUNGE, CONST_PERSISTENT | CONST_CS);
	/* silently expunge recycle stream */

	REGISTER_MAIN_LONG_CONSTANT("OP_SECURE", OP_SECURE, CONST_PERSISTENT | CONST_CS);
	/* don't do non-secure authentication */

	/* 
	PHP re-assigns CL_EXPUNGE a custom value that can be used as part of the imap_open() bitfield
	because it seems like a good idea to be able to indicate that the mailbox should be 
	automatically expunged during imap_open in case the script get interrupted and it doesn't get
	to the imap_close() where this option is normally placed.  If the c-client library adds other
	options and the value for this one conflicts, simply make PHP_EXPUNGE higher at the top of 
	this file 
	*/
	REGISTER_MAIN_LONG_CONSTANT("CL_EXPUNGE", PHP_EXPUNGE, CONST_PERSISTENT | CONST_CS);
	/* expunge silently */


	/* Fetch options */

	REGISTER_MAIN_LONG_CONSTANT("FT_UID", FT_UID, CONST_PERSISTENT | CONST_CS);
	/* argument is a UID */
	REGISTER_MAIN_LONG_CONSTANT("FT_PEEK", FT_PEEK, CONST_PERSISTENT | CONST_CS);
	/* peek at data */
	REGISTER_MAIN_LONG_CONSTANT("FT_NOT", FT_NOT, CONST_PERSISTENT | CONST_CS);
	/* NOT flag for header lines fetch */
	REGISTER_MAIN_LONG_CONSTANT("FT_INTERNAL", FT_INTERNAL, CONST_PERSISTENT | CONST_CS);
	/* text can be internal strings */
	REGISTER_MAIN_LONG_CONSTANT("FT_PREFETCHTEXT", FT_PREFETCHTEXT, CONST_PERSISTENT | CONST_CS);
	/* IMAP prefetch text when fetching header */


	/* Flagging options */

	REGISTER_MAIN_LONG_CONSTANT("ST_UID", ST_UID, CONST_PERSISTENT | CONST_CS);
	/* argument is a UID sequence */
	REGISTER_MAIN_LONG_CONSTANT("ST_SILENT", ST_SILENT, CONST_PERSISTENT | CONST_CS);
	/* don't return results */
	REGISTER_MAIN_LONG_CONSTANT("ST_SET", ST_SET, CONST_PERSISTENT | CONST_CS);
	/* set vs. clear */

	/* Copy options */

	REGISTER_MAIN_LONG_CONSTANT("CP_UID", CP_UID, CONST_PERSISTENT | CONST_CS);
	/* argument is a UID sequence */
	REGISTER_MAIN_LONG_CONSTANT("CP_MOVE", CP_MOVE, CONST_PERSISTENT | CONST_CS);
	/* delete from source after copying */


	/* Search/sort options */

	REGISTER_MAIN_LONG_CONSTANT("SE_UID", SE_UID, CONST_PERSISTENT | CONST_CS);
	/* return UID */
	REGISTER_MAIN_LONG_CONSTANT("SE_FREE", SE_FREE, CONST_PERSISTENT | CONST_CS);
	/* free search program after finished */
	REGISTER_MAIN_LONG_CONSTANT("SE_NOPREFETCH", SE_NOPREFETCH, CONST_PERSISTENT | CONST_CS);
	/* no search prefetching */
	REGISTER_MAIN_LONG_CONSTANT("SO_FREE", SO_FREE, CONST_PERSISTENT | CONST_CS);
	/* free sort program after finished */
	REGISTER_MAIN_LONG_CONSTANT("SO_NOSERVER", SO_NOSERVER, CONST_PERSISTENT | CONST_CS);
	/* don't do server-based sort */

	/* Status options */

	REGISTER_MAIN_LONG_CONSTANT("SA_MESSAGES",SA_MESSAGES , CONST_PERSISTENT | CONST_CS);
	/* number of messages */
	REGISTER_MAIN_LONG_CONSTANT("SA_RECENT", SA_RECENT, CONST_PERSISTENT | CONST_CS);
	/* number of recent messages */
	REGISTER_MAIN_LONG_CONSTANT("SA_UNSEEN",SA_UNSEEN , CONST_PERSISTENT | CONST_CS);
	/* number of unseen messages */
	REGISTER_MAIN_LONG_CONSTANT("SA_UIDNEXT", SA_UIDNEXT, CONST_PERSISTENT | CONST_CS);
	/* next UID to be assigned */
	REGISTER_MAIN_LONG_CONSTANT("SA_UIDVALIDITY",SA_UIDVALIDITY , CONST_PERSISTENT | CONST_CS);
	/* UID validity value */
	REGISTER_MAIN_LONG_CONSTANT("SA_ALL", sa_all, CONST_PERSISTENT | CONST_CS);
     /* get all status information */
		


	/* Bits for mm_list() and mm_lsub() */

	REGISTER_MAIN_LONG_CONSTANT("LATT_NOINFERIORS",LATT_NOINFERIORS , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("LATT_NOSELECT", LATT_NOSELECT, CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("LATT_MARKED", LATT_MARKED, CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("LATT_UNMARKED",LATT_UNMARKED , CONST_PERSISTENT | CONST_CS);


	/* Sort functions */

	REGISTER_MAIN_LONG_CONSTANT("SORTDATE",SORTDATE , CONST_PERSISTENT | CONST_CS);
	/* date */
	REGISTER_MAIN_LONG_CONSTANT("SORTARRIVAL",SORTARRIVAL , CONST_PERSISTENT | CONST_CS);
	/* arrival date */
	REGISTER_MAIN_LONG_CONSTANT("SORTFROM",SORTFROM , CONST_PERSISTENT | CONST_CS);
	/* from */
	REGISTER_MAIN_LONG_CONSTANT("SORTSUBJECT",SORTSUBJECT , CONST_PERSISTENT | CONST_CS);
	/* subject */
	REGISTER_MAIN_LONG_CONSTANT("SORTTO",SORTTO , CONST_PERSISTENT | CONST_CS);
	/* to */
	REGISTER_MAIN_LONG_CONSTANT("SORTCC",SORTCC , CONST_PERSISTENT | CONST_CS);
	/* cc */
	REGISTER_MAIN_LONG_CONSTANT("SORTSIZE",SORTSIZE , CONST_PERSISTENT | CONST_CS);
	/* size */

	REGISTER_MAIN_LONG_CONSTANT("TYPETEXT",TYPETEXT , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEMULTIPART",TYPEMULTIPART , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEMESSAGE",TYPEMESSAGE , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEAPPLICATION",TYPEAPPLICATION , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEAUDIO",TYPEAUDIO , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEIMAGE",TYPEIMAGE , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEVIDEO",TYPEVIDEO , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("TYPEOTHER",TYPEOTHER , CONST_PERSISTENT | CONST_CS);
	/*      TYPETEXT                unformatted text
	TYPEMULTIPART           multiple part
	TYPEMESSAGE             encapsulated message
	TYPEAPPLICATION         application data
	TYPEAUDIO               audio
	TYPEIMAGE               static image (GIF, JPEG, etc.)
	TYPEVIDEO               video
	TYPEOTHER               unknown
	*/
	REGISTER_MAIN_LONG_CONSTANT("ENC7BIT",ENC7BIT , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("ENC8BIT",ENC8BIT , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("ENCBINARY",ENCBINARY , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("ENCBASE64",ENCBASE64, CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("ENCQUOTEDPRINTABLE",ENCQUOTEDPRINTABLE , CONST_PERSISTENT | CONST_CS);
	REGISTER_MAIN_LONG_CONSTANT("ENCOTHER",ENCOTHER , CONST_PERSISTENT | CONST_CS);
	/*
	ENC7BIT                 7 bit SMTP semantic data
	ENC8BIT                 8 bit SMTP semantic data
	ENCBINARY               8 bit binary data
	ENCBASE64               base-64 encoded data
	ENCQUOTEDPRINTABLE      human-readable 8-as-7 bit data
	ENCOTHER                unknown
	*/

    le_imap = zend_register_list_destructors_ex(mail_close_it, NULL, "imap", module_number);
#ifdef OP_RELOGIN
    /* AJS: destructors for persistent connections */
    le_pimap = zend_register_list_destructors_ex(mail_userlogout_it, NULL, "imap persistent", module_number);
    le_pimapchain = zend_register_list_destructors_ex(NULL, mail_nuke_chain, "imap chain persistent", module_number);
#endif
	return SUCCESS;
}
/* }}} */

/* {{{ imap_do_open
 */
void imap_do_open(INTERNAL_FUNCTION_PARAMETERS, int persistent)
{
	zval **mailbox, **user, **passwd, **options;
	MAILSTREAM *imap_stream;
	pils *imap_le_struct;
	long flags=NIL;
	long cl_flags=NIL;
#ifdef OP_RELOGIN
	NETMBX netmbx;
	char *hashed_details = NULL;
	int hashed_details_length = 0;
#endif
	int ind;
	int myargc=ZEND_NUM_ARGS();
	
	if (myargc <3 || myargc >4 || zend_get_parameters_ex(myargc, &mailbox, &user, &passwd, &options) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_string_ex(mailbox);
	convert_to_string_ex(user);
	convert_to_string_ex(passwd);
	if (myargc ==4) {
		convert_to_long_ex(options);
		flags = Z_LVAL_PP(options);
		if (flags & PHP_EXPUNGE) {
			cl_flags = CL_EXPUNGE;
			flags ^= PHP_EXPUNGE;
		}
	}

	if (IMAPG(imap_user)) { 
		efree(IMAPG(imap_user));
	}

	if (IMAPG(imap_password)) { 
		efree(IMAPG(imap_password));
	}

	IMAPG(imap_user)     = estrndup(Z_STRVAL_PP(user), Z_STRLEN_PP(user));
	IMAPG(imap_password) = estrndup(Z_STRVAL_PP(passwd), Z_STRLEN_PP(passwd));
	
#ifdef OP_RELOGIN
	/* AJS: persistent connection handling */
	/* Cannot use a persistent connection if we cannot parse
	 * out the server's hostname.
	 */
	if (persistent
		&& !mail_valid_net_parse(Z_STRVAL_PP(mailbox), &netmbx)) {
		persistent = 0;
	}

	imap_stream = NIL;
	if (persistent) {
		list_entry	*le = NULL;
		list_entry	new_le;
		pils		**headp, *node;
		int		need_update = 0;

		hashed_details_length = sizeof("imap_") + strlen(netmbx.host);
		hashed_details = (char*) emalloc(hashed_details_length);
		sprintf(hashed_details, "imap_%s", netmbx.host);

		/* Check for an existing connection. */
		if (	(zend_hash_find(&EG(persistent_list),
					hashed_details,
					hashed_details_length,
					(void*) &le) == FAILURE) ||
			(le->type != le_pimapchain))
		{
			le = NULL;
		}

		/* Re-use existing connection if available. */
		node = NULL;
		headp = NULL;
		if (le) {
			headp = (pils**) le->ptr;

			/* find a non-busy connection */
			for (node=*headp; node; node=node->next)
				if (!node->busy)
					break;
		}

		/* If we found a node, do a relogin.  */
		if (node) {
			imap_stream = mail_open(node->imap_stream, Z_STRVAL_PP(mailbox), flags | OP_RELOGIN);
			if (imap_stream) {
				/* Ping the stream to see if it is
				 * still good. 
				 */
				if (!mail_ping(imap_stream)) {
					mail_close(imap_stream);
					imap_stream = NIL;
				}
			}
		}

		/* Get a fresh stream if we don't have one yet. */
		if (imap_stream == NIL) {
			/* Open a new connection. */
			imap_stream = mail_open(NIL, Z_STRVAL_PP(mailbox), flags | OP_RELOGIN);
		}

		/* Do we have a stream yet?  If not, bail. */
		if (imap_stream == NIL) {
			if (node) {
				/* unlink the node */
				if ((*node->prev = node->next))
					node->next->prev = node->prev;
				free(node);
				/* delete the hash entry if empty */
				if (*headp == NULL) {
					zend_hash_del(&EG(persistent_list), hashed_details, hashed_details_length);
				}
 			}
			efree(hashed_details);
			efree(IMAPG(imap_user)); IMAPG(imap_user) = 0;
			efree(IMAPG(imap_password)); IMAPG(imap_password) = 0;
			RETURN_FALSE;
		}

		/* Allocate a new node if none. */
		if (node == NULL) {
			/* Alloc new hash entry. */
			node = malloc(sizeof(pils));
			if (node == NULL) {
				efree(hashed_details);
				efree(IMAPG(imap_user)); IMAPG(imap_user) = 0;
				efree(IMAPG(imap_password)); IMAPG(imap_password) = 0;
				RETURN_FALSE;
			}

			/* Allocate headp if it does not exist. */
			if (headp == NULL) {
				headp = calloc(1, sizeof(*headp));
				need_update = 1;
			}

			node->prev = headp;
			node->next = *headp;
			*headp = node;
		}


		/* Initialize the node. */
		node->busy = 1;
		node->imap_stream = imap_stream;
		node->flags = cl_flags;

		/* Update the hash. */
		new_le.type = le_pimapchain;
		new_le.ptr = headp;
		if (need_update
			&& zend_hash_update(&EG(persistent_list), hashed_details,
				hashed_details_length, &new_le,
				sizeof(new_le), NULL) == FAILURE) {
			/* unlink and free the new node */
			if ((*node->prev = node->next)) {
				node->next->prev = node->prev;
			}
			mail_close(node->imap_stream);
			free(node);

			free(headp);
			efree(hashed_details);
			efree(IMAPG(imap_user)); IMAPG(imap_user) = 0;
			efree(IMAPG(imap_password)); IMAPG(imap_password) = 0;
 			RETURN_FALSE;
		}

		efree(hashed_details);

		imap_le_struct = node;
	} else {
#endif
		imap_stream = mail_open(NIL, Z_STRVAL_PP(mailbox), flags);

		if (imap_stream == NIL) {
			php_error(E_WARNING, "Couldn't open stream %s\n", (*mailbox)->value.str.val);
			efree(IMAPG(imap_user)); IMAPG(imap_user) = 0;
			efree(IMAPG(imap_password)); IMAPG(imap_password) = 0;
			RETURN_FALSE;
		}

		imap_le_struct = emalloc(sizeof(pils));
		imap_le_struct->imap_stream = imap_stream;
		imap_le_struct->flags = cl_flags;	
#ifdef OP_RELOGIN
	}

	if (persistent)
		ind = zend_list_insert(imap_le_struct, le_pimap);
	else
#endif
		ind = zend_list_insert(imap_le_struct, le_imap);

	RETURN_LONG(ind);
}
/* }}} */

/* {{{ proto int imap_open(string mailbox, string user, string password [, int options])
   Open an IMAP stream to a mailbox */
PHP_FUNCTION(imap_open)
{
	imap_do_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* }}} */

/* {{{ proto int imap_popen(string mailbox, string user, string password [, int options])
   Open a persistant IMAP stream to a mailbox */
PHP_FUNCTION(imap_popen)
{
#ifdef OP_RELOGIN
	imap_do_open(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
	RETURN_TRUE;
#else
	php_error(E_WARNING, "Persistent IMAP connections are not yet supported.\n");
	RETURN_FALSE;
#endif
}
/* }}} */
 
/* {{{ proto int imap_reopen(int stream_id, string mailbox [, int options])
   Reopen an IMAP stream to a new mailbox */
PHP_FUNCTION(imap_reopen)
{
	zval **streamind;
	zval **mailbox;
	zval **options;
	MAILSTREAM *imap_stream;
	pils *imap_le_struct; 
	int ind, ind_type;
	long flags=NIL;
	long cl_flags=NIL;
	int myargc=ZEND_NUM_ARGS();

	if (myargc<2 || myargc>3 || zend_get_parameters_ex(myargc, &streamind, &mailbox, &options) == FAILURE) {
        ZEND_WRONG_PARAM_COUNT();
    }

	convert_to_long_ex(streamind);
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	convert_to_string_ex(mailbox);
	if (myargc == 3) {
		convert_to_long_ex(options);
		flags = Z_LVAL_PP(options);
		if (flags & PHP_EXPUNGE) {
			cl_flags = CL_EXPUNGE;
			flags ^= PHP_EXPUNGE;
		}
		imap_le_struct->flags = cl_flags;	
	}
	imap_stream = mail_open(imap_le_struct->imap_stream, (*mailbox)->value.str.val, flags);
	if (imap_stream == NIL) {
		php_error(E_WARNING, "Couldn't re-open stream\n");
		RETURN_FALSE;
	}
	imap_le_struct->imap_stream = imap_stream;
	RETURN_TRUE;
}
/* }}} */

/* {{{ proto int imap_append(int stream_id, string folder, string message [, string flags])
   Append a new message to a specified mailbox */
PHP_FUNCTION(imap_append)
{
	zval **streamind, **folder, **message, **flags;
	int ind, ind_type;
	pils *imap_le_struct; 
	STRING st;
	int myargc=ZEND_NUM_ARGS();
  
	if (myargc < 3 || myargc > 4 || zend_get_parameters_ex(myargc, &streamind, &folder, &message, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
  
	convert_to_long_ex(streamind);
	convert_to_string_ex(folder);
	convert_to_string_ex(message);
	if (myargc == 4) {
		convert_to_string_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);
  
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);

	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	INIT (&st, mail_string, (void *) (*message)->value.str.val, (*message)->value.str.len);
	if (mail_append_full(imap_le_struct->imap_stream, (*folder)->value.str.val, myargc==4?(*flags)->value.str.val:NIL, NIL, &st)) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_num_msg(int stream_id)
   Gives the number of messages in the current mailbox */
PHP_FUNCTION(imap_num_msg)
{
	zval **streamind;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);

	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	RETURN_LONG(imap_le_struct->imap_stream->nmsgs);
}
/* }}} */

/* {{{ proto int imap_ping(int stream_id)
   Check if the IMAP stream is still active */
PHP_FUNCTION(imap_ping)
{
	zval **streamind;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	RETURN_LONG(mail_ping(imap_le_struct->imap_stream));
}
/* }}} */

/* {{{ proto int imap_num_recent(int stream_id)
   Gives the number of recent messages in current mailbox */
PHP_FUNCTION(imap_num_recent)
{
	zval **streamind;
	int ind, ind_type;
	pils *imap_le_struct;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_long_ex(streamind);
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	RETURN_LONG(imap_le_struct->imap_stream->recent);
}
/* }}} */

#ifdef HAVE_IMAP2000
/* {{{ proto array imap_get_quota(int stream_id, string qroot)
	Returns the quota set to the mailbox account qroot */
PHP_FUNCTION(imap_get_quota)
{
	zval **streamind, **qroot;
	int ind, ind_type;
	pils *imap_le_struct;

	if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &streamind, &qroot) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(qroot);

	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	/* set the callback for the GET_QUOTA function */
	mail_parameters(NIL, SET_QUOTA, (void *) mail_getquota);
	if(!imap_getquota(imap_le_struct->imap_stream, Z_STRVAL_PP(qroot))) {
		php_error(E_WARNING, "c-client imap_getquota failed");
		RETURN_FALSE;
	}

	/* MAKE_STD_ZVAL(quota_array); */
	/* if (array_init(quota_array) != SUCCESS) { */
	if (array_init(return_value) == FAILURE) {
		php_error(E_WARNING, "Unable to allocate array memory");
		RETURN_FALSE;
	}
		
	add_assoc_long(return_value, "usage", IMAPG(quota_usage));
	add_assoc_long(return_value, "limit", IMAPG(quota_limit));
}
/* }}} */

/* {{{ proto int imap_set_quota(int stream_id, string qroot, int mailbox_size)
   Will set the quota for qroot mailbox */
PHP_FUNCTION(imap_set_quota)
{
	zval **streamind, **qroot, **mailbox_size;
	STRINGLIST	limits;
	int ind, ind_type;
	pils *imap_le_struct;

	if (ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &streamind, &qroot, &mailbox_size) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(qroot);
	convert_to_long_ex(mailbox_size);

	limits.text.data = "STORAGE";
	limits.text.size = Z_LVAL_PP(mailbox_size);
	limits.next = NIL;

	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	RETURN_LONG(imap_setquota(imap_le_struct->imap_stream, Z_STRVAL_PP(qroot), &limits)); 
}
/* }}} */
#endif


/* {{{ proto int imap_expunge(int stream_id)
   Permanently delete all messages marked for deletion */
PHP_FUNCTION(imap_expunge)
{
	zval **streamind;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);

	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	mail_expunge (imap_le_struct->imap_stream);

	RETURN_TRUE;
}
/* }}} */

/* {{{ proto int imap_close(int stream_id [, int options])
   Close an IMAP stream */
PHP_FUNCTION(imap_close)
{
	zval **options, **streamind;
	int ind, ind_type;
	pils *imap_le_struct=NULL; 
	int myargcount=ZEND_NUM_ARGS();
	long flags = NIL;

	if (myargcount < 1 || myargcount > 2 || zend_get_parameters_ex(myargcount, &streamind, &options) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_long_ex(streamind);
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
    }
	if (myargcount==2) {
		convert_to_long_ex(options);
		flags = Z_LVAL_PP(options);
		/* Do the translation from PHP's internal PHP_EXPUNGE define to c-client's CL_EXPUNGE */
		if (flags & PHP_EXPUNGE) {
			flags ^= PHP_EXPUNGE;
			flags |= CL_EXPUNGE;
		}	
		imap_le_struct->flags = flags;
	}

	zend_list_delete(ind);
	RETURN_TRUE;
}
/* }}} */

/* {{{ proto array imap_headers(int stream_id)
   Returns headers for all messages in a mailbox */
PHP_FUNCTION(imap_headers)
{
	zval **streamind;
	int ind, ind_type;
	unsigned long i;
	char *t;
	unsigned int msgno;
	pils *imap_le_struct; 
	char tmp[MAILTMPLEN];
	
	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	/* Initialize return array */
	if (array_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}
	
	for (msgno = 1; msgno <= imap_le_struct->imap_stream->nmsgs; msgno++) {
		MESSAGECACHE * cache = mail_elt (imap_le_struct->imap_stream,msgno);
		mail_fetchstructure(imap_le_struct->imap_stream,msgno,NIL);
		tmp[0] = cache->recent ? (cache->seen ? 'R': 'N') : ' ';
		tmp[1] = (cache->recent | cache->seen) ? ' ' : 'U';
		tmp[2] = cache->flagged ? 'F' : ' ';
		tmp[3] = cache->answered ? 'A' : ' ';
		tmp[4] = cache->deleted ? 'D' : ' ';
		tmp[5] = cache->draft ? 'X' : ' ';
		sprintf(tmp + 6, "%4ld) ", cache->msgno);
		mail_date(tmp+11, cache);
		tmp[22] = ' ';
		tmp[23] = '\0';
		mail_fetchfrom(tmp+23, imap_le_struct->imap_stream, msgno, (long)20);
		strcat(tmp, " ");
		if ((i = cache->user_flags)) {
			strcat(tmp, "{");
			while (i) {
				strcat(tmp, imap_le_struct->imap_stream->user_flags[find_rightmost_bit (&i)]);
				if (i) strcat(tmp, " ");
			}
			strcat(tmp, "} ");
		}
		mail_fetchsubject(t = tmp + strlen(tmp), imap_le_struct->imap_stream, msgno, (long)25);
		sprintf(t += strlen(t), " (%ld chars)", cache->rfc822_size);
		add_next_index_string(return_value, tmp, 1);
	}
}
/* }}} */

/* {{{ proto string imap_body(int stream_id, int msg_no [, int options])
   Read the message body */
PHP_FUNCTION(imap_body)
{
	zval **streamind, **msgno, **flags;
	int ind, ind_type, msgindex;
	pils *imap_le_struct; 
	int myargc=ZEND_NUM_ARGS();
	if (myargc < 2 || myargc > 3 || zend_get_parameters_ex(myargc, &streamind, &msgno, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	if (myargc == 3) {
		convert_to_long_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	if ((myargc == 3) && (Z_LVAL_PP(flags) & FT_UID)) {
		/* This should be cached; if it causes an extra RTT to the
		   IMAP server, then that's the price we pay for making
		   sure we don't crash. */
		msgindex = mail_msgno(imap_le_struct->imap_stream, Z_LVAL_PP(msgno));
	} else {
		msgindex = Z_LVAL_PP(msgno);
	}
	if ((msgindex < 1) || ((unsigned) msgindex > imap_le_struct->imap_stream->nmsgs)) {
		php_error(E_WARNING, "Bad message number");
		RETURN_FALSE;
	}
    
	RETVAL_STRING(mail_fetchtext_full (imap_le_struct->imap_stream, Z_LVAL_PP(msgno), NIL, myargc==3 ? Z_LVAL_PP(flags) : NIL), 1);
}
/* }}} */

/* {{{ proto string imap_fetchtext_full(int stream_id, int msg_no [, int options])
   Read the full text of a message */
PHP_FUNCTION(imap_fetchtext_full)
{
	zval **streamind, **msgno, **flags;
	int ind, ind_type;
	pils *imap_le_struct; 
	int myargcount = ZEND_NUM_ARGS();
	if (myargcount >3 || myargcount <2 || zend_get_parameters_ex(myargcount, &streamind, &msgno, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	if (myargcount == 3) {
		convert_to_long_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	RETVAL_STRING(mail_fetchtext_full(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), NIL, myargcount==3 ? Z_LVAL_PP(flags) : NIL), 1);
}
/* }}} */

/* {{{ proto int imap_mail_copy(int stream_id, int msg_no, string mailbox [, int options])
   Copy specified message to a mailbox */
PHP_FUNCTION(imap_mail_copy)
{
	zval **streamind, **seq, **folder, **options;
	int ind, ind_type;
	pils *imap_le_struct; 
	int myargcount = ZEND_NUM_ARGS();

	if (myargcount > 4 || myargcount < 3 
		|| zend_get_parameters_ex(myargcount, &streamind, &seq, &folder, &options) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(seq);
	convert_to_string_ex(folder);
	if (myargcount == 4) {
		convert_to_long_ex(options);
	}
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_copy_full(imap_le_struct->imap_stream, Z_STRVAL_PP(seq), Z_STRVAL_PP(folder), myargcount==4 ? Z_LVAL_PP(options) : NIL)==T) {
        RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_mail_move(int stream_id, int msg_no, string mailbox [, int options])
   Move specified message to a mailbox */
PHP_FUNCTION(imap_mail_move)
{
	zval **streamind, **seq, **folder, **options;
	int ind, ind_type;
	pils *imap_le_struct; 
	int myargcount = ZEND_NUM_ARGS();

	if (myargcount > 4 || myargcount < 3 
		|| zend_get_parameters_ex(myargcount, &streamind, &seq, &folder, &options) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(seq);
	convert_to_string_ex(folder);
	if (myargcount == 4) {
		convert_to_long_ex(options);
	}
		
	ind = Z_LVAL_PP(streamind);
	
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_copy_full(imap_le_struct->imap_stream, Z_STRVAL_PP(seq), Z_STRVAL_PP(folder), myargcount==4 ? (Z_LVAL_PP(options) | CP_MOVE) : CP_MOVE) == T) {
        RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_createmailbox(int stream_id, string mailbox)
   Create a new mailbox */
PHP_FUNCTION(imap_createmailbox)
{
	zval **streamind, **folder;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &streamind, &folder) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(folder);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_create(imap_le_struct->imap_stream, Z_STRVAL_PP(folder))==T) {
        RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_renamemailbox(int stream_id, string old_name, string new_name)
   Rename a mailbox */
PHP_FUNCTION(imap_renamemailbox)
{
	zval **streamind, **old_mailbox, **new_mailbox;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS()!=3 || zend_get_parameters_ex(3, &streamind, &old_mailbox, &new_mailbox)==FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(old_mailbox);
	convert_to_string_ex(new_mailbox);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_rename(imap_le_struct->imap_stream, Z_STRVAL_PP(old_mailbox), Z_STRVAL_PP(new_mailbox))==T) {
        RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_deletemailbox(int stream_id, string mailbox)
   Delete a mailbox */
PHP_FUNCTION(imap_deletemailbox)
{
	zval **streamind, **folder;
	int ind, ind_type;
	pils *imap_le_struct; 

	if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &streamind, &folder) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(folder);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_delete(imap_le_struct->imap_stream, Z_STRVAL_PP(folder))==T) {
        RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto array imap_list(int stream_id, string ref, string pattern)
   Read the list of mailboxes */
PHP_FUNCTION(imap_list)
{
	zval **streamind, **ref, **pat;
	int ind, ind_type;
	pils *imap_le_struct; 
	STRINGLIST *cur=NIL;

	/* set flag for normal, old mailbox list */
	IMAPG(folderlist_style) = FLIST_ARRAY;
	
	if (ZEND_NUM_ARGS()!=3 
		|| zend_get_parameters_ex(3, &streamind, &ref, &pat) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(ref);
	convert_to_string_ex(pat);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	IMAPG(imap_folders) = NIL;
	mail_list(imap_le_struct->imap_stream, Z_STRVAL_PP(ref), Z_STRVAL_PP(pat));
	if (IMAPG(imap_folders) == NIL) {
		RETURN_FALSE;
	}
	array_init(return_value);
    cur=IMAPG(imap_folders);
    while (cur != NIL) {
		add_next_index_string(return_value, cur->LTEXT, 1);
        cur=cur->next;
    }
	mail_free_stringlist (&IMAPG(imap_folders));
}

/* }}} */

/* {{{ proto array imap_getmailboxes(int stream_id, string ref, string pattern)
   Reads the list of mailboxes and returns a full array of objects containing name, attributes, and delimiter */
/* Author: CJH */
PHP_FUNCTION(imap_list_full)
{
	zval **streamind, **ref, **pat, *mboxob;
	int ind, ind_type;
	pils *imap_le_struct; 
	FOBJECTLIST *cur=NIL;
	char *delim=NIL;
	
	/* set flag for new, improved array of objects mailbox list */
	IMAPG(folderlist_style) = FLIST_OBJECT;
	
	if (ZEND_NUM_ARGS()!=3 
		|| zend_get_parameters_ex(3, &streamind, &ref, &pat) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_string_ex(ref);
	convert_to_string_ex(pat);
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	IMAPG(imap_folder_objects) = NIL;
	mail_list(imap_le_struct->imap_stream, Z_STRVAL_PP(ref), Z_STRVAL_PP(pat));
	if (IMAPG(imap_folder_objects) == NIL) {
		RETURN_FALSE;
	}
	
	array_init(return_value);
	delim = emalloc(2 * sizeof(char));
	cur=IMAPG(imap_folder_objects);
	while (cur != NIL) {
		MAKE_STD_ZVAL(mboxob);
		object_init(mboxob);
		add_property_string(mboxob, "name", cur->LTEXT, 1);
		add_property_long(mboxob, "attributes", cur->attributes);
#ifdef IMAP41
		delim[0] = (char)cur->delimiter;
		delim[1] = 0;
		add_property_string(mboxob, "delimiter", delim, 1);
#else
		add_property_string(mboxob, "delimiter", cur->delimiter, 1);
#endif
		add_next_index_object(return_value, mboxob);
		cur=cur->next;
	}
	mail_free_foblist(&IMAPG(imap_folder_objects));
	efree(delim);
	IMAPG(folderlist_style) = FLIST_ARRAY;		/* reset to default */
}
/* }}} */

/* {{{ proto array imap_scan(int stream_id, string ref, string pattern, string content)
   Read list of mailboxes containing a certain string */
PHP_FUNCTION(imap_listscan)
{
	zval **streamind, **ref, **pat, **content;
	int ind, ind_type;
	pils *imap_le_struct;
	STRINGLIST *cur=NIL;

	if (ZEND_NUM_ARGS()!=4 || zend_get_parameters_ex(4, &streamind, &ref, &pat, &content) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(ref);
	convert_to_string_ex(pat);
	convert_to_string_ex(content);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	IMAPG(imap_folders) = NIL;
	mail_scan(imap_le_struct->imap_stream, Z_STRVAL_PP(ref), Z_STRVAL_PP(pat), Z_STRVAL_PP(content));
	if (IMAPG(imap_folders) == NIL) {
		RETURN_FALSE;
	}
	array_init(return_value);
	cur=IMAPG(imap_folders);
	while (cur != NIL) {
		add_next_index_string(return_value, cur->LTEXT, 1);
		cur=cur->next;
	}
	mail_free_stringlist (&IMAPG(imap_folders));
}

/* }}} */

/* {{{ proto object imap_check(int stream_id)
   Get mailbox properties */
PHP_FUNCTION(imap_check)
{
	zval **streamind;
	int ind, ind_type;
	pils *imap_le_struct;
	char date[100];

	if (ZEND_NUM_ARGS()!=1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	if (mail_ping (imap_le_struct->imap_stream) == NIL) {
		RETURN_FALSE;
    }
	if (imap_le_struct->imap_stream && imap_le_struct->imap_stream->mailbox) {
		rfc822_date(date);
		object_init(return_value);
		add_property_string(return_value, "Date", date, 1);
		add_property_string(return_value, "Driver", imap_le_struct->imap_stream->dtb->name, 1);
		add_property_string(return_value, "Mailbox", imap_le_struct->imap_stream->mailbox, 1);
		add_property_long(return_value, "Nmsgs", imap_le_struct->imap_stream->nmsgs);
		add_property_long(return_value, "Recent", imap_le_struct->imap_stream->recent);
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_delete(int stream_id, int msg_no [, int flags])
   Mark a message for deletion */
PHP_FUNCTION(imap_delete)
{
	zval **streamind, **sequence, **flags;
	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();
	
	if (myargc < 2 || myargc > 3 || zend_get_parameters_ex(myargc, &streamind, &sequence, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_string_ex(sequence);
	if (myargc == 3) {
		convert_to_long_ex(flags);
	}
	
	ind = Z_LVAL_PP(streamind);
	
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	mail_setflag_full(imap_le_struct->imap_stream, Z_STRVAL_PP(sequence), "\\DELETED", myargc==3 ? Z_LVAL_PP(flags) : NIL);
	RETVAL_TRUE;
}
/* }}} */

/* {{{ proto int imap_undelete(int stream_id, int msg_no)
   Remove the delete flag from a message */
PHP_FUNCTION(imap_undelete)
{
	zval **streamind, **sequence, **flags;
	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();

	if (myargc < 2 || myargc > 3 || zend_get_parameters_ex(myargc, &streamind, &sequence, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_string_ex(sequence);
	if (myargc == 3) {
		convert_to_long_ex(flags);
	}

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	mail_clearflag_full(imap_le_struct->imap_stream, Z_STRVAL_PP(sequence), "\\DELETED", myargc==3 ? Z_LVAL_PP(flags) : NIL);
	RETVAL_TRUE;
}
/* }}} */

/* {{{ proto object imap_headerinfo(int stream_id, int msg_no [, int from_length [, int subject_length [, string default_host]]])
   Read the headers of the message */
PHP_FUNCTION(imap_headerinfo)
{
	zval **streamind, **msgno, **fromlength, **subjectlength, **defaulthost;
	int ind, ind_type;
	unsigned long length;
	pils *imap_le_struct;
	MESSAGECACHE *cache;
	char *mystring;
	char dummy[2000];
	ENVELOPE *en;
	char fulladdress[MAILTMPLEN];
	
	int myargc = ZEND_NUM_ARGS();
	if (myargc < 2 || myargc > 5 || zend_get_parameters_ex(myargc, &streamind, &msgno, &fromlength, &subjectlength, &defaulthost)==FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	if (myargc >= 3) {
		convert_to_long_ex(fromlength); 
	} else {
		fromlength = 0x00;
	}
	if (myargc >= 4) {
		convert_to_long_ex(subjectlength);
	} else {
		subjectlength = 0x00;
	}
	if (myargc == 5) {
		convert_to_string_ex(defaulthost);
	}
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	if (!Z_LVAL_PP(msgno) || Z_LVAL_PP(msgno) < 1 || (unsigned) Z_LVAL_PP(msgno) > imap_le_struct->imap_stream->nmsgs) {
		php_error(E_WARNING, "Bad message number");
		RETURN_FALSE;
	}
	
	if (mail_fetchstructure(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), NIL)) {
		cache = mail_elt(imap_le_struct->imap_stream, Z_LVAL_PP(msgno));
	} else {
		RETURN_FALSE;
	}
	
    mystring = mail_fetchheader_full(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), NIL, &length, NIL);
	if (myargc == 5) {
		rfc822_parse_msg(&en, NULL, mystring, length, NULL, Z_STRVAL_PP(defaulthost), NIL);
	} else {
		rfc822_parse_msg(&en, NULL, mystring, length, NULL, "UNKNOWN", NIL);
	}
	
	/* call a function to parse all the text, so that we can use the
       same function to parse text from other sources */
	_php_make_header_object(return_value, en);
	
	/* now run through properties that are only going to be returned
       from a server, not text headers */
	add_property_string(return_value, "Recent", cache->recent ? (cache->seen ? "R": "N") : " ", 1);
	add_property_string(return_value, "Unseen", (cache->recent | cache->seen) ? " " : "U", 1);
	add_property_string(return_value, "Flagged", cache->flagged ? "F" : " ", 1);
	add_property_string(return_value, "Answered", cache->answered ? "A" : " ", 1);
	add_property_string(return_value, "Deleted", cache->deleted ? "D" : " ", 1);
	add_property_string(return_value, "Draft", cache->draft ? "X" : " ", 1);
	
	sprintf(dummy, "%4ld", cache->msgno);
	add_property_string(return_value, "Msgno", dummy, 1);
	
	mail_date(dummy, cache);
	add_property_string(return_value, "MailDate", dummy, 1);
	
	sprintf(dummy, "%ld", cache->rfc822_size); 
	add_property_string(return_value, "Size", dummy, 1);
	
	add_property_long(return_value, "udate", mail_longdate(cache));
	
	if (en->from && fromlength) {
		fulladdress[0] = 0x00;
		mail_fetchfrom(fulladdress, imap_le_struct->imap_stream, Z_LVAL_PP(msgno), Z_LVAL_PP(fromlength));
		add_property_string(return_value, "fetchfrom", fulladdress, 1);
	}
	if (en->subject && subjectlength) {
		fulladdress[0] = 0x00;
		mail_fetchsubject(fulladdress, imap_le_struct->imap_stream, Z_LVAL_PP(msgno), Z_LVAL_PP(subjectlength));
		add_property_string(return_value, "fetchsubject", fulladdress, 1);
	}
	mail_free_envelope(&en);
}
/* }}} */

/* {{{ proto object imap_rfc822_parse_headers(string headers [, string default_host])
   Parse a set of mail headers contained in a string, and return an object similar to imap_headerinfo() */
PHP_FUNCTION(imap_rfc822_parse_headers)
{
	zval **headers, **defaulthost;
	ENVELOPE *en;
	
	int myargc = ZEND_NUM_ARGS();
	if (myargc < 1 || myargc > 2 || zend_get_parameters_ex(myargc, &headers, &defaulthost) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_string_ex(headers);
	if (myargc == 2) {
		convert_to_string_ex(defaulthost);
	}
	
	if (myargc == 2) {
		rfc822_parse_msg(&en, NULL, (*headers)->value.str.val, (*headers)->value.str.len, NULL, (*defaulthost)->value.str.val, NIL);
	} else {
		rfc822_parse_msg(&en, NULL, (*headers)->value.str.val, (*headers)->value.str.len, NULL, "UNKNOWN", NIL);
	}
	
	/* call a function to parse all the text, so that we can use the
       same function no matter where the headers are from */
	_php_make_header_object(return_value, en);
	mail_free_envelope(&en);
}
/* }}} */


/* KMLANG */
/* {{{ proto array imap_lsub(int stream_id, string ref, string pattern)
   Return a list of subscribed mailboxes */
PHP_FUNCTION(imap_lsub)
{
	zval **streamind, **ref, **pat;
	int ind, ind_type;
	pils *imap_le_struct;
	STRINGLIST *cur=NIL;
	
	/* set flag for normal, old mailbox list */
	IMAPG(folderlist_style) = FLIST_ARRAY;
	
	if (ZEND_NUM_ARGS()!=3 || zend_get_parameters_ex(3, &streamind, &ref, &pat) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(ref);
	convert_to_string_ex(pat);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	IMAPG(imap_sfolders) = NIL;
	mail_lsub(imap_le_struct->imap_stream, Z_STRVAL_PP(ref), Z_STRVAL_PP(pat));
	if (IMAPG(imap_sfolders) == NIL) {
		RETURN_FALSE;
	}
	array_init(return_value);
	cur=IMAPG(imap_sfolders);
	while (cur != NIL) {
		add_next_index_string(return_value, cur->LTEXT, 1);
		cur=cur->next;
	}
	mail_free_stringlist (&IMAPG(imap_sfolders));
}
/* }}} */

/* {{{ proto array imap_getsubscribed(int stream_id, string ref, string pattern)
   Return a list of subscribed mailboxes, in the same format as imap_getmailboxes() */
/* Author: CJH */
PHP_FUNCTION(imap_lsub_full)
{
	zval **streamind, **ref, **pat, *mboxob;
	int ind, ind_type;
	pils *imap_le_struct;
	FOBJECTLIST *cur=NIL;
	char *delim=NIL;
	TSRMLS_FETCH();
	
	delim = emalloc(2 * sizeof(char));
	
	/* set flag for new, improved array of objects list */
	IMAPG(folderlist_style) = FLIST_OBJECT;
	
	if (ZEND_NUM_ARGS()!=3 || zend_get_parameters_ex(3, &streamind, &ref, &pat) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_string_ex(ref);
	convert_to_string_ex(pat);
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	IMAPG(imap_sfolder_objects) = NIL;
	mail_lsub(imap_le_struct->imap_stream, Z_STRVAL_PP(ref), Z_STRVAL_PP(pat));
	if (IMAPG(imap_sfolder_objects) == NIL) {
		RETURN_FALSE;
	}
	
	array_init(return_value);
	cur=IMAPG(imap_sfolder_objects);
	while (cur != NIL) {
		MAKE_STD_ZVAL(mboxob);
		object_init(mboxob);
		add_property_string(mboxob, "name", cur->LTEXT, 1);
		add_property_long(mboxob, "attributes", cur->attributes);
#ifdef IMAP41
		delim[0] = (char)cur->delimiter;
		delim[1] = 0;
		add_property_string(mboxob, "delimiter", delim, 1);
#else
		add_property_string(mboxob, "delimiter", cur->delimiter, 1);
#endif
		add_next_index_object(return_value, mboxob);
		cur=cur->next;
	}
	mail_free_foblist (&IMAPG(imap_sfolder_objects));
	efree(delim);
	IMAPG(folderlist_style) = FLIST_ARRAY; /* reset to default */
}
/* }}} */

/* {{{ proto int imap_subscribe(int stream_id, string mailbox)
   Subscribe to a mailbox */
PHP_FUNCTION(imap_subscribe)
{
	zval **streamind, **folder;
	int ind, ind_type;
	pils *imap_le_struct;

	if (ZEND_NUM_ARGS()!=2 || zend_get_parameters_ex(2, &streamind, &folder) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(folder);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_subscribe(imap_le_struct->imap_stream, Z_STRVAL_PP(folder))==T) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto int imap_unsubscribe(int stream_id, string mailbox)
   Unsubscribe from a mailbox */
PHP_FUNCTION(imap_unsubscribe)
{
	zval **streamind, **folder;
	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();
	if (myargc !=2 || zend_get_parameters_ex(myargc, &streamind, &folder) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_string_ex(folder);
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	if (mail_unsubscribe(imap_le_struct->imap_stream, Z_STRVAL_PP(folder))==T) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto object imap_fetchstructure(int stream_id, int msg_no [, int options])
   Read the full structure of a message */
PHP_FUNCTION(imap_fetchstructure)
{
	zval **streamind, **msgno, **flags;
	int ind, ind_type, msgindex;
	pils *imap_le_struct;
	BODY *body;
	int myargc=ZEND_NUM_ARGS();

	if (myargc < 2  || myargc > 3 || zend_get_parameters_ex(myargc, &streamind, &msgno, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	if (Z_LVAL_PP(msgno) < 1) {
		RETURN_FALSE;
	}
	if (myargc == 3) {
		convert_to_long_ex(flags);
	}
	object_init(return_value);
    
	ind = Z_LVAL_PP(streamind);
    
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
    
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	if ((myargc == 3) && (Z_LVAL_PP(flags) & FT_UID)) {
		/* This should be cached; if it causes an extra RTT to the
		   IMAP server, then that's the price we pay for making
		   sure we don't crash. */
		msgindex = mail_msgno(imap_le_struct->imap_stream, Z_LVAL_PP(msgno));
	} else {
		msgindex = Z_LVAL_PP(msgno);
	}
	if ((msgindex < 1) || ((unsigned) msgindex > imap_le_struct->imap_stream->nmsgs)) {
		php_error(E_WARNING, "Bad message number");
		RETURN_FALSE;
	}
    
	mail_fetchstructure_full(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), &body ,myargc == 3 ? Z_LVAL_PP(flags) : NIL);
	
	if (!body) {
		php_error(E_WARNING, "No body information available");
		RETURN_FALSE;
	}
	
	_php_imap_add_body(return_value, body);
}
/* }}} */

/* {{{ proto string imap_fetchbody(int stream_id, int msg_no, int section [, int options])
   Get a specific body section */
PHP_FUNCTION(imap_fetchbody)
{
	zval **streamind, **msgno, **sec, **flags;
	int ind, ind_type;
	pils *imap_le_struct;
	char *body;
	unsigned long len;
	int myargc=ZEND_NUM_ARGS();

	if (myargc < 3 || myargc >4 || zend_get_parameters_ex(myargc, &streamind, &msgno, &sec, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	convert_to_string_ex(sec);
	if (myargc == 4) {
		convert_to_long_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);

	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
 
	body = mail_fetchbody_full(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), Z_STRVAL_PP(sec), &len, myargc==4 ? Z_LVAL_PP(flags) : NIL);

	if (!body) {
		php_error(E_WARNING, "No body information available");
		RETURN_FALSE;
	}
	RETVAL_STRINGL(body, len, 1);
}

/* }}} */

/* {{{ proto string imap_base64(string text)
   Decode BASE64 encoded text */
PHP_FUNCTION(imap_base64)
{
	zval **text;
	char *decode;
	unsigned long newlength;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &text) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_string_ex(text);

	decode = (char *) rfc822_base64((unsigned char *) Z_STRVAL_PP(text), Z_STRLEN_PP(text), &newlength);
	if (decode == NULL) {
		RETURN_FALSE;
	}
	RETVAL_STRINGL(decode, newlength, 1);
	fs_give((void**) &decode);
}
/* }}} */

/* {{{ proto string imap_qprint(string text)
   Convert a quoted-printable string to an 8-bit string */
PHP_FUNCTION(imap_qprint)
{
	zval **text;
	char *decode;
	unsigned long newlength;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &text) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_string_ex(text);

	decode = (char *) rfc822_qprint((unsigned char *) Z_STRVAL_PP(text), Z_STRLEN_PP(text), &newlength);
	if (decode == NULL) {
		RETURN_FALSE;
	}
	RETVAL_STRINGL(decode, newlength, 1);
	fs_give((void**) &decode);
}
/* }}} */

/* {{{ proto string imap_8bit(string text)
   Convert an 8-bit string to a quoted-printable string */
PHP_FUNCTION(imap_8bit)
{
	zval **text;
	char *decode;
	unsigned long newlength;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &text) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_string_ex(text);

	decode = (char *) rfc822_8bit((unsigned char *) Z_STRVAL_PP(text), Z_STRLEN_PP(text), &newlength);
	RETVAL_STRINGL(decode, newlength, 1);
	fs_give((void**) &decode);
}
/* }}} */

/* {{{ proto string imap_binary(string text)
   Convert an 8bit string to a base64 string */
PHP_FUNCTION(imap_binary)
{
	zval **text;
	unsigned long len;
	char *decode;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &text) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_string_ex(text);
	decode = rfc822_binary(Z_STRVAL_PP(text), Z_STRLEN_PP(text), &len);
	RETVAL_STRINGL(decode, len, 1);
	fs_give((void**) &decode);
}
/* }}} */

/* {{{ proto object imap_mailboxmsginfo(int stream_id)
   Returns info about the current mailbox */
PHP_FUNCTION(imap_mailboxmsginfo)
{
	zval **streamind;
	char date[100];
	int ind, ind_type;
	unsigned int msgno;
	pils *imap_le_struct;
	unsigned unreadmsg, deletedmsg, msize;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &streamind) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_long_ex(streamind);

	ind = Z_LVAL_PP(streamind);

	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);

	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}

	/* Initialize return object */
	if (object_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}

	unreadmsg = 0;
	deletedmsg = 0;
	msize = 0;
	for (msgno = 1; msgno <= imap_le_struct->imap_stream->nmsgs; msgno++) {
		MESSAGECACHE * cache = mail_elt (imap_le_struct->imap_stream,msgno);
		mail_fetchstructure (imap_le_struct->imap_stream,msgno,NIL);
                if (!cache->seen || cache->recent) unreadmsg++;
                if (cache->deleted) deletedmsg++;
		msize = msize + cache->rfc822_size;
	}
	add_property_long(return_value, "Unread", unreadmsg);
        add_property_long(return_value, "Deleted", deletedmsg);
	add_property_long(return_value, "Nmsgs", imap_le_struct->imap_stream->nmsgs);
	add_property_long(return_value, "Size", msize);
	rfc822_date(date);
	add_property_string(return_value, "Date", date, 1);
	add_property_string(return_value, "Driver", imap_le_struct->imap_stream->dtb->name, 1);
	add_property_string(return_value, "Mailbox", imap_le_struct->imap_stream->mailbox, 1);
	add_property_long(return_value, "Recent", imap_le_struct->imap_stream->recent);
}
/* }}} */

/* {{{ proto string imap_rfc822_write_address(string mailbox, string host, string personal)
   Returns a properly formatted email address given the mailbox, host, and personal info */
PHP_FUNCTION(imap_rfc822_write_address)
{
	zval **mailbox, **host, **personal;
	ADDRESS *addr;
	char string[MAILTMPLEN];
	int argc;
	argc=ZEND_NUM_ARGS();

	if (argc != 3 || zend_get_parameters_ex(argc, &mailbox, &host, &personal) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_string_ex(mailbox);
	convert_to_string_ex(host);
	convert_to_string_ex(personal);
	addr=mail_newaddr();
	if (mailbox) {
		addr->mailbox = cpystr(Z_STRVAL_PP(mailbox));
	}
	if (host) {
		addr->host = cpystr(Z_STRVAL_PP(host));
	}
	if (personal) {
		addr->personal = cpystr(Z_STRVAL_PP(personal));
	}
	addr->next=NIL;
	addr->error=NIL;
	addr->adl=NIL;

	string[0]='\0';
	rfc822_write_address(string, addr);
	RETVAL_STRING(string, 1);
}
/* }}} */

/* {{{ proto array imap_rfc822_parse_adrlist(string address_string, string default_host)
   Parses an address string */
PHP_FUNCTION(imap_rfc822_parse_adrlist)
{
	zval *str, *defaulthost, *tovals;
	ADDRESS *addresstmp;
	ENVELOPE *env;
	int argc;
	
	env=mail_newenvelope();
	argc=ZEND_NUM_ARGS();
	if (argc != 2 || zend_get_parameters(ht, argc, &str, &defaulthost) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_string(str);
	convert_to_string(defaulthost);
	rfc822_parse_adrlist(&env->to, str->value.str.val, defaulthost->value.str.val);
	if (array_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}
	addresstmp=env->to;
	if (addresstmp) do {
		MAKE_STD_ZVAL(tovals);
		object_init(tovals);
		if (addresstmp->mailbox) {
			add_property_string(tovals, "mailbox", addresstmp->mailbox, 1);
		}
		if (addresstmp->host) {
			add_property_string(tovals, "host", addresstmp->host, 1);
		}
		if (addresstmp->personal) {
			add_property_string(tovals, "personal", addresstmp->personal, 1);
		}
		if (addresstmp->adl) {
			add_property_string(tovals, "adl", addresstmp->adl, 1);
		}
		add_next_index_object(return_value, tovals);
	} while ((addresstmp = addresstmp->next));
}
/* }}} */

/* {{{ proto string imap_utf8(string string)
   Convert a string to UTF-8 */
PHP_FUNCTION(imap_utf8)
{
	zval **str;
	int argc;
	SIZEDTEXT src, dest;
	
	src.data  = NULL;
	src.size  = 0;
	dest.data = NULL;
	dest.size = 0;
	
	argc = ZEND_NUM_ARGS();
	if (argc != 1 || zend_get_parameters_ex(argc, &str) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_string_ex(str);
	cpytxt(&src, Z_STRVAL_PP(str), Z_STRLEN_PP(str));
	utf8_mime2text(&src, &dest);
	RETURN_STRINGL(dest.data, strlen(dest.data), 1);
}
/* }}} */


/* macros for the modified utf7 conversion functions */
/* author: Andrew Skalski <askalski@chek.com> */

/* tests `c' and returns true if it is a special character */
#define SPECIAL(c) ((c) <= 0x1f || (c) >= 0x7f)
/* validate a modified-base64 character */
#define B64CHAR(c) (isalnum(c) || (c) == '+' || (c) == ',')
/* map the low 64 bits of `n' to the modified-base64 characters */
#define B64(n)  ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                "abcdefghijklmnopqrstuvwxyz0123456789+,"[(n) & 0x3f])
/* map the modified-base64 character `c' to its 64 bit value */
#define UNB64(c)        ((c) == '+' ? 62 : (c) == ',' ? 63 : (c) >= 'a' ? \
                        (c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4)

/* {{{ proto string imap_utf7_decode(string buf)
   Decode a modified UTF-7 string */
PHP_FUNCTION(imap_utf7_decode)
{
	/* author: Andrew Skalski <askalski@chek.com> */
	int argc;
	zval **arg;
	const unsigned char *in, *inp, *endp;
	unsigned char *out, *outp;
	int inlen, outlen;
	enum {
		ST_NORMAL,	/* printable text */
		ST_DECODE0,	/* encoded text rotation... */
		ST_DECODE1,
		ST_DECODE2,
		ST_DECODE3
	} state;

	/* collect arguments */
	argc = ZEND_NUM_ARGS();
	if (argc != 1 || zend_get_parameters_ex(argc, &arg) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_writable_string_ex(arg);		/* Is this string really modified? */
	in = (const unsigned char *) Z_STRVAL_PP(arg);
	inlen = Z_STRLEN_PP(arg);
	
	/* validate and compute length of output string */
	outlen = 0;
	state = ST_NORMAL;
	for (endp = (inp = in) + inlen; inp < endp; inp++) {
		if (state == ST_NORMAL) {
			/* process printable character */
			if (SPECIAL(*inp)) {
				php_error(E_WARNING, "imap_utf7_decode: "
					"Invalid modified UTF-7 character: "
					"`%c'", *inp);
				RETURN_FALSE;
			} else if (*inp != '&') {
				outlen++;
			} else if (inp + 1 == endp) {
				php_error(E_WARNING, "imap_utf7_decode: "
					"Unexpected end of string");
				RETURN_FALSE;
			} else if (inp[1] != '-') {
				state = ST_DECODE0;
			} else {
				outlen++;
				inp++;
			}
		} else if (*inp == '-') {
			/* return to NORMAL mode */
			if (state == ST_DECODE1) {
				php_error(E_WARNING, "imap_utf7_decode: "
					"Stray modified base64 character: "
					"`%c'", *--inp);
				RETURN_FALSE;
			}
			state = ST_NORMAL;
		} else if (!B64CHAR(*inp)) {
			php_error(E_WARNING, "imap_utf7_decode: "
				"Invalid modified base64 character: "
				"`%c'", *inp);
			RETURN_FALSE;
		} else {
			switch (state) {
				case ST_DECODE3:
					outlen++;
					state = ST_DECODE0;
					break;
				case ST_DECODE2:
				case ST_DECODE1:
					outlen++;
				case ST_DECODE0:
					state++;
				case ST_NORMAL:
					break;
			}
		}
	}

	/* enforce end state */
	if (state != ST_NORMAL) {
		php_error(E_WARNING, "imap_utf7_decode: "
			"Unexpected end of string");
		RETURN_FALSE;
	}

	/* allocate output buffer */
	if ((out = emalloc(outlen + 1)) == NULL) {
		php_error(E_WARNING, "imap_utf7_decode: "
			"Unable to allocate result string");
		RETURN_FALSE;
	}

	/* decode input string */
	outp = out;
	state = ST_NORMAL;
	for (endp = (inp = in) + inlen; inp < endp; inp++) {
		if (state == ST_NORMAL) {
			if (*inp == '&' && inp[1] != '-') {
				state = ST_DECODE0;
			}
			else if ((*outp++ = *inp) == '&') {
				inp++;
			}
		}
		else if (*inp == '-') {
			state = ST_NORMAL;
		}
		else {
			/* decode input character */
			switch (state) {
			case ST_DECODE0:
				*outp = UNB64(*inp) << 2;
				state = ST_DECODE1;
				break;
			case ST_DECODE1:
				outp[1] = UNB64(*inp);
				*outp++ |= outp[1] >> 4;
				*outp <<= 4;
				state = ST_DECODE2;
				break;
			case ST_DECODE2:
				outp[1] = UNB64(*inp);
				*outp++ |= outp[1] >> 2;
				*outp <<= 6;
				state = ST_DECODE3;
				break;
			case ST_DECODE3:
				*outp++ |= UNB64(*inp);
				state = ST_DECODE0;
			case ST_NORMAL:
				break;
			}
		}
	}

	*outp = 0;

#if PHP_DEBUG
	/* warn if we computed outlen incorrectly */
	if (outp - out != outlen) {
		php_error(E_WARNING,
			"imap_utf7_decode: outp - out [%d] != outlen [%d]",
			outp - out, outlen);
	}
#endif

	RETURN_STRINGL(out, outlen, 0);
}
/* }}} */

/* {{{ proto string imap_utf7_encode(string buf)
   Encode a string in modified UTF-7 */
PHP_FUNCTION(imap_utf7_encode)
{
	/* author: Andrew Skalski <askalski@chek.com> */
	int argc;
	zval **arg;
	const unsigned char *in, *inp, *endp;
	unsigned char *out, *outp;
	int inlen, outlen;
	enum {
		ST_NORMAL,	/* printable text */
		ST_ENCODE0,	/* encoded text rotation... */
		ST_ENCODE1,
		ST_ENCODE2
	} state;

	/* collect arguments */
	argc = ZEND_NUM_ARGS();
	if (argc != 1 || zend_get_parameters_ex(argc, &arg) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_string_ex(arg);
	in = (const unsigned char *) Z_STRVAL_PP(arg);
	inlen = Z_STRLEN_PP(arg);

	/* compute the length of the result string */
	outlen = 0;
	state = ST_NORMAL;
	endp = (inp = in) + inlen;
	while (inp < endp) {
		if (state == ST_NORMAL) {
			if (SPECIAL(*inp)) {
				state = ST_ENCODE0;
				outlen++;
			} else if (*inp++ == '&') {
				outlen++;
			}
			outlen++;
		} else if (!SPECIAL(*inp)) {
			state = ST_NORMAL;
		} else {
			/* ST_ENCODE0 -> ST_ENCODE1	- two chars
			 * ST_ENCODE1 -> ST_ENCODE2	- one char
			 * ST_ENCODE2 -> ST_ENCODE0	- one char
			 */
			if (state == ST_ENCODE2) {
				state = ST_ENCODE0;
			}
			else if (state++ == ST_ENCODE0) {
				outlen++;
			}
			outlen++;
			inp++;
		}
	}

	/* allocate output buffer */
	if ((out = emalloc(outlen + 1)) == NULL) {
		php_error(E_WARNING, "imap_utf7_encode: "
			"Unable to allocate result string");
		RETURN_FALSE;
	}

	/* encode input string */
	outp = out;
	state = ST_NORMAL;
	endp = (inp = in) + inlen;
	while (inp < endp || state != ST_NORMAL) {
		if (state == ST_NORMAL) {
			if (SPECIAL(*inp)) {
				/* begin encoding */
				*outp++ = '&';
				state = ST_ENCODE0;
			} else if ((*outp++ = *inp++) == '&') {
				*outp++ = '-';
			}
		} else if (inp == endp || !SPECIAL(*inp)) {
			/* flush overflow and terminate region */
			if (state != ST_ENCODE0) {
				*outp++ = B64(*outp);
			}
			*outp++ = '-';
			state = ST_NORMAL;
		} else {
			/* encode input character */
			switch (state) {
				case ST_ENCODE0:
					*outp++ = B64(*inp >> 2);
					*outp = *inp++ << 4;
					state = ST_ENCODE1;
					break;
				case ST_ENCODE1:
					*outp++ = B64(*outp | *inp >> 4);
					*outp = *inp++ << 2;
					state = ST_ENCODE2;
					break;
				case ST_ENCODE2:
					*outp++ = B64(*outp | *inp >> 6);
					*outp++ = B64(*inp++);
					state = ST_ENCODE0;
				case ST_NORMAL:
					break;
			}
		}
	}

	*outp = 0;

#if PHP_DEBUG
	/* warn if we computed outlen incorrectly */
	if (outp - out != outlen) {
		php_error(E_WARNING,
			"imap_utf7_encode: outp - out [%d] != outlen [%d]",
			outp - out, outlen);
	}
#endif

	RETURN_STRINGL(out, outlen, 0);
}
/* }}} */

#undef SPECIAL
#undef B64CHAR
#undef B64
#undef UNB64

/* {{{ proto int imap_setflag_full(int stream_id, string sequence, string flag [, int options])
   Sets flags on messages */
PHP_FUNCTION(imap_setflag_full)
{
	zval **streamind, **sequence, **flag, **flags;
	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();

	if (myargc < 3 || myargc > 4 || zend_get_parameters_ex(myargc, &streamind, &sequence, &flag, &flags) ==FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_long_ex(streamind);
	convert_to_string_ex(sequence);
	convert_to_string_ex(flag);
	if (myargc==4) {
		convert_to_long_ex(flags);
	}

	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	mail_setflag_full(imap_le_struct->imap_stream, Z_STRVAL_PP(sequence), Z_STRVAL_PP(flag), myargc==4 ? Z_LVAL_PP(flags) : NIL);
	RETURN_TRUE;
}
/* }}} */

/* {{{ proto int imap_clearflag_full(int stream_id, string sequence, string flag [, int options])
   Clears flags on messages */
PHP_FUNCTION(imap_clearflag_full)
{
	zval **streamind, **sequence, **flag, **flags;
	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();

	if (myargc < 3 || myargc > 4 || zend_get_parameters_ex(myargc, &streamind, &sequence, &flag, &flags) ==FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_long_ex(streamind);
	convert_to_string_ex(sequence);
	convert_to_string_ex(flag);
	if (myargc==4) {
		convert_to_long_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	mail_clearflag_full(imap_le_struct->imap_stream, Z_STRVAL_PP(sequence), Z_STRVAL_PP(flag), myargc==4 ? Z_LVAL_PP(flags) : NIL);
    RETURN_TRUE;
}
/* }}} */

/* {{{ proto array imap_sort(int stream_id, int criteria, int reverse [, int options [, string search_criteria]])
   Sort an array of message headers, optionally including only messages that meet specified criteria. */
PHP_FUNCTION(imap_sort)
{
	zval **streamind, **pgm, **rev, **flags, **criteria;
	int ind, ind_type;
	unsigned long *slst, *sl;
	char *search_criteria;
	SORTPGM *mypgm=NIL;
	SEARCHPGM *spg=NIL;
	pils *imap_le_struct;
	int myargc = ZEND_NUM_ARGS();
	
	if (myargc < 3 || myargc > 5 || zend_get_parameters_ex(myargc, &streamind, &pgm, &rev, &flags, &criteria) ==FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	convert_to_long_ex(streamind);
	convert_to_long_ex(rev);
	convert_to_long_ex(pgm);
	if (Z_LVAL_PP(pgm) > SORTSIZE) {
		php_error(E_WARNING, "Unrecognized sort criteria");
		RETURN_FALSE;
	}
	if (myargc >= 4) {
		convert_to_long_ex(flags);
	}
	if (myargc == 5) {
		search_criteria = estrndup(Z_STRVAL_PP(criteria), Z_STRLEN_PP(criteria));
		spg = mail_criteria(search_criteria);
		efree(search_criteria);
	} else {
		spg = mail_newsearchpgm();
	}
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	mypgm = mail_newsortpgm();
	mypgm->reverse = Z_LVAL_PP(rev);
	mypgm->function = (short) Z_LVAL_PP(pgm);
	mypgm->next = NIL;
	
	slst = mail_sort(imap_le_struct->imap_stream, NIL, spg, mypgm, myargc >= 4 ? Z_LVAL_PP(flags) : NIL);
	if (spg) {
		mail_free_searchpgm(&spg);
	}

	array_init(return_value);
	if (slst != NIL && slst != 0) {
		for (sl = slst; *sl; sl++) { 
			add_next_index_long(return_value, *sl);
		}
		fs_give ((void **) &slst);
	}
}
/* }}} */

/* {{{ proto string imap_fetchheader(int stream_id, int msg_no [, int options])
   Get the full unfiltered header for a message */
PHP_FUNCTION(imap_fetchheader)
{
	zval **streamind, **msgno, **flags;
	int ind, ind_type, msgindex;
	pils *imap_le_struct;
	int myargc = ZEND_NUM_ARGS();
	
	if (myargc < 2 || myargc > 3 || zend_get_parameters_ex(myargc, &streamind, &msgno, &flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_long_ex(msgno);
	if (myargc == 3) {
		convert_to_long_ex(flags);
	}
	ind = Z_LVAL_PP(streamind);
	
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	if ((myargc == 3) && (Z_LVAL_PP(flags) & FT_UID)) {
		/* This should be cached; if it causes an extra RTT to the
           IMAP server, then that's the price we pay for making sure
           we don't crash. */
		msgindex = mail_msgno(imap_le_struct->imap_stream, Z_LVAL_PP(msgno));
	} else {
		msgindex = Z_LVAL_PP(msgno);
	}
	if ((msgindex < 1) || ((unsigned) msgindex > imap_le_struct->imap_stream->nmsgs)) {
		php_error(E_WARNING, "Bad message number");
		RETURN_FALSE;
	}

    RETVAL_STRING(mail_fetchheader_full(imap_le_struct->imap_stream, Z_LVAL_PP(msgno), NIL, NIL, (myargc == 3 ? Z_LVAL_PP(flags) : NIL)), 1);
}
/* }}} */

/* {{{ proto int imap_uid(int stream_id, int msg_no)
   Get the unique message id associated with a standard sequential message number */
PHP_FUNCTION(imap_uid)
{
 	zval **streamind, **msgno;
 	int ind, ind_type, msgindex;
	pils *imap_le_struct;
 
 	if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &streamind, &msgno) == FAILURE) {
 		ZEND_WRONG_PARAM_COUNT();
 	}
 	
 	convert_to_long_ex(streamind);
 	convert_to_long_ex(msgno);
 
 	ind = Z_LVAL_PP(streamind);
 
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
 
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
 
    	msgindex = Z_LVAL_PP(msgno);
	if ((msgindex < 1) || ((unsigned) msgindex > imap_le_struct->imap_stream->nmsgs)) {
		php_error(E_WARNING, "Bad message number");
		RETURN_FALSE;
	}
    
	RETURN_LONG(mail_uid(imap_le_struct->imap_stream, Z_LVAL_PP(msgno)));
}
/* }}} */

/* {{{ proto int imap_msgno(int stream_id, int unique_msg_id)
   Get the sequence number associated with a UID */
PHP_FUNCTION(imap_msgno)
{
 	zval **streamind, **msgno;
 	int ind, ind_type;
	pils *imap_le_struct;
 
 	if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &streamind, &msgno) == FAILURE) {
 		ZEND_WRONG_PARAM_COUNT();
 	}
 	
 	convert_to_long_ex(streamind);
 	convert_to_long_ex(msgno);
 
 	ind = Z_LVAL_PP(streamind);
 
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
 
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
 
 	RETURN_LONG(mail_msgno(imap_le_struct->imap_stream, Z_LVAL_PP(msgno)));
}
/* }}} */

/* {{{ proto object imap_status(int stream_id, string mailbox, int options)
   Get status info from a mailbox */
PHP_FUNCTION(imap_status)
{
 	zval **streamind, **mbx, **flags;
 	int ind, ind_type;
	pils *imap_le_struct;
	int myargc=ZEND_NUM_ARGS();

 	if (myargc != 3 || zend_get_parameters_ex(myargc, &streamind, &mbx, &flags) == FAILURE) {
 		ZEND_WRONG_PARAM_COUNT();
 	}
 	
 	convert_to_long_ex(streamind);
 	convert_to_string_ex(mbx);
	convert_to_long_ex(flags);
 	ind = Z_LVAL_PP(streamind);
 
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
 
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
 
	if (object_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}

 	if (mail_status(imap_le_struct->imap_stream, Z_STRVAL_PP(mbx), Z_LVAL_PP(flags))) {
	    add_property_long(return_value, "flags", IMAPG(status_flags));
		if (IMAPG(status_flags) & SA_MESSAGES) {
			add_property_long(return_value, "messages", IMAPG(status_messages));
		}
		if (IMAPG(status_flags) & SA_RECENT) {
			add_property_long(return_value, "recent", IMAPG(status_recent));
		}
		if (IMAPG(status_flags) & SA_UNSEEN) {
			add_property_long(return_value, "unseen", IMAPG(status_unseen));
		}
		if (IMAPG(status_flags) & SA_UIDNEXT) {
			add_property_long(return_value, "uidnext", IMAPG(status_uidnext));
		}
		if (IMAPG(status_flags) & SA_UIDVALIDITY) {
			add_property_long(return_value, "uidvalidity", IMAPG(status_uidvalidity));
		}
	} else {
		RETURN_FALSE;
	}
}
/* }}} */

/* {{{ proto object imap_bodystruct(int stream_id, int msg_no, int section)
   Read the structure of a specified body section of a specific message */
PHP_FUNCTION(imap_bodystruct)
{
	zval **streamind, **msg, **section;
	int ind, ind_type;
	pils *imap_le_struct;
	zval *parametres, *param, *dparametres, *dparam;
	PARAMETER *par, *dpar;
	BODY *body;
	int myargc=ZEND_NUM_ARGS();

	if (myargc != 3 || zend_get_parameters_ex(myargc, &streamind, &msg, &section) == FAILURE) {
 		ZEND_WRONG_PARAM_COUNT();
 	}
 	
 	convert_to_long_ex(streamind);
 	convert_to_long_ex(msg);
	convert_to_string_ex(section);
 	ind = Z_LVAL_PP(streamind);
 
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	if (object_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}
	
	body=mail_body(imap_le_struct->imap_stream, Z_LVAL_PP(msg), Z_STRVAL_PP(section));
	if (body->type <= TYPEMAX) {
		add_property_long(return_value, "type", body->type);
	}
	if (body->encoding <= ENCMAX) {
		add_property_long(return_value, "encoding", body->encoding);
	}
	
	if (body->subtype) {
		add_property_long(return_value, "ifsubtype", 1);
		add_property_string(return_value, "subtype",  body->subtype, 1);
	} else {
		add_property_long(return_value, "ifsubtype", 0);
	}
	
	if (body->description) {
		add_property_long(return_value, "ifdescription", 1);
		add_property_string(return_value, "description",  body->description, 1);
	} else {
		add_property_long(return_value, "ifdescription", 0);
	}
	if (body->id) {
		add_property_long(return_value, "ifid", 1);
		add_property_string(return_value, "id",  body->id, 1);
	} else {
		add_property_long(return_value, "ifid", 0);
	}

	
	if (body->size.lines) {
		add_property_long(return_value, "lines", body->size.lines);
	}
	if (body->size.bytes) {
		add_property_long(return_value, "bytes", body->size.bytes);
	}
#ifdef IMAP41
	if (body->disposition.type) {
		add_property_long(return_value, "ifdisposition", 1);
		add_property_string(return_value, "disposition", body->disposition.type, 1);
	} else {
		add_property_long(return_value, "ifdisposition", 0);
	}
	
	if (body->disposition.parameter) {
		dpar = body->disposition.parameter;
		add_property_long(return_value, "ifdparameters", 1);
		MAKE_STD_ZVAL(dparametres);
		array_init(dparametres);
		do {
			MAKE_STD_ZVAL(dparam);
			object_init(dparam);
			add_property_string(dparam, "attribute", dpar->attribute, 1);
			add_property_string(dparam, "value", dpar->value, 1);
			add_next_index_object(dparametres, dparam);
		} while ((dpar = dpar->next));
		add_assoc_object(return_value, "dparameters", dparametres);
	} else {
		add_property_long(return_value, "ifdparameters", 0);
	}
#endif
	
	if ((par = body->parameter)) {
		add_property_long(return_value, "ifparameters", 1);
		
		MAKE_STD_ZVAL(parametres);
		array_init(parametres);
		do {
			MAKE_STD_ZVAL(param);
			object_init(param);
			if (par->attribute) {
				add_property_string(param, "attribute", par->attribute, 1);
			}
			if (par->value) {
				add_property_string(param, "value", par->value, 1);
			}
			
			add_next_index_object(parametres, param);
		} while ((par = par->next));
	} else {
		MAKE_STD_ZVAL(parametres);
		object_init(parametres);
		add_property_long(return_value, "ifparameters", 0);
	}
	add_assoc_object(return_value, "parameters", parametres);
}

/* }}} */

/* {{{ proto array imap_fetch_overview(int stream_id, int msg_no)
   Read an overview of the information in the headers of the given message sequence */ 
PHP_FUNCTION(imap_fetch_overview)
{
 	zval **streamind, **sequence, **pflags;
 	int ind, ind_type;
	pils *imap_le_struct;
	zval *myoverview;
	char address[MAILTMPLEN];
	long status, flags=0L;

	switch (ZEND_NUM_ARGS()) {
		case 2:
			if (zend_get_parameters_ex(2, &streamind, &sequence) == FAILURE) {
				ZEND_WRONG_PARAM_COUNT();
			}
			break;
		case 3:
			if (zend_get_parameters_ex(3, &streamind, &sequence, &pflags) == FAILURE) {
				ZEND_WRONG_PARAM_COUNT();
			} else {
				convert_to_long_ex(pflags);
				flags = Z_LVAL_PP(pflags);
			}
			break;
		default:
			ZEND_WRONG_PARAM_COUNT();
			break;
	}
 	
 	convert_to_long_ex(streamind);
 	convert_to_string_ex(sequence);
	
 	ind = Z_LVAL_PP(streamind);
 	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	array_init(return_value);
	
	status = (flags & FT_UID)
		? mail_uid_sequence (imap_le_struct->imap_stream, Z_STRVAL_PP(sequence))
		: mail_sequence (imap_le_struct->imap_stream, Z_STRVAL_PP(sequence))
		;
	
	
	if (status) {  
		MESSAGECACHE *elt;
		ENVELOPE *env;
		unsigned long i;
		
		for (i = 1; i <= imap_le_struct->imap_stream->nmsgs; i++) {
			if (((elt = mail_elt (imap_le_struct->imap_stream, i))->sequence) &&
				(env = mail_fetch_structure (imap_le_struct->imap_stream, i, NIL, NIL))) {
				MAKE_STD_ZVAL(myoverview);
				object_init(myoverview);
				if (env->subject) {
					add_property_string(myoverview, "subject", env->subject, 1);
				}
				if (env->from) {
					env->from->next=NULL;
					address[0] = '\0';
					rfc822_write_address(address, env->from);
					add_property_string(myoverview, "from", address, 1);
				}
			        if (env->to) {
					env->to->next = NULL;
				    	address[0] = '\0';
					rfc822_write_address(address, env->to);
					add_property_string(myoverview, "to", address, 1);
				}
				if (env->date) {
					add_property_string(myoverview, "date", env->date, 1);
				}
				if (env->message_id) {
					add_property_string(myoverview, "message_id", env->message_id, 1);
				}
				if (env->references) {
					add_property_string(myoverview, "references", env->references, 1);
				}
				add_property_long(myoverview, "size", elt->rfc822_size);
				add_property_long(myoverview, "uid", mail_uid(imap_le_struct->imap_stream, i));
				add_property_long(myoverview, "msgno", i);
				add_property_long(myoverview, "recent", elt->recent);
				add_property_long(myoverview, "flagged", elt->flagged);
				add_property_long(myoverview, "answered", elt->answered);
				add_property_long(myoverview, "deleted", elt->deleted);
				add_property_long(myoverview, "seen", elt->seen);
				add_property_long(myoverview, "draft", elt->draft);
				add_next_index_object(return_value, myoverview);
			}
		}
	}
}
/* }}} */

/* {{{ proto string imap_mail_compose(array envelope, array body)
   Create a MIME message based on given envelope and body sections */
PHP_FUNCTION(imap_mail_compose)
{
	zval **envelope, **body;
	char *key;
	zval **data, **pvalue, **disp_data, **env_data;
	ulong ind;
	char *cookie = NIL;
	ENVELOPE *env;
	BODY *bod=NULL, *topbod=NULL;
	PART *mypart=NULL, *toppart=NULL, *part;
	PARAMETER *param, *disp_param = NULL, *custom_headers_param = NULL, *tmp_param = NULL;
	char tmp[8 * MAILTMPLEN], *mystring=NULL, *t=NULL, *tempstring=NULL;
	int myargc = ZEND_NUM_ARGS();

	if (myargc != 2 || zend_get_parameters_ex(myargc, &envelope, &body) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	if ((*envelope)->type != IS_ARRAY) {
		php_error(E_WARNING, "IMAP: Expected Array as envelope parameter");
		RETURN_FALSE;
 	}

	if ((*body)->type != IS_ARRAY) {
		php_error(E_WARNING, "IMAP: Expected Array as body parameter");
		RETURN_FALSE;
 	}

	env = mail_newenvelope();
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "remail", sizeof("remail"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		env->remail=cpystr(Z_STRVAL_PP(pvalue));
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "return_path", sizeof("return_path"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue)
		rfc822_parse_adrlist(&env->return_path, Z_STRVAL_PP(pvalue), "NO HOST");
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "date", sizeof("date"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		env->date=cpystr(Z_STRVAL_PP(pvalue));
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "from", sizeof("from"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		rfc822_parse_adrlist (&env->from, Z_STRVAL_PP(pvalue), "NO HOST");
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "reply_to", sizeof("reply_to"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		rfc822_parse_adrlist (&env->reply_to, Z_STRVAL_PP(pvalue), "NO HOST");
	}
        if (zend_hash_find(Z_ARRVAL_PP(envelope), "in_reply_to", sizeof("in_reply_to"), (void **) &pvalue)== SUCCESS) {
                convert_to_string_ex(pvalue);
		env->in_reply_to=cpystr(Z_STRVAL_PP(pvalue));
        }
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "subject", sizeof("subject"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		env->subject=cpystr(Z_STRVAL_PP(pvalue));
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "to", sizeof("to"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		rfc822_parse_adrlist (&env->to, Z_STRVAL_PP(pvalue), "NO HOST");
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "cc", sizeof("cc"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		rfc822_parse_adrlist (&env->cc, Z_STRVAL_PP(pvalue), "NO HOST");
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "bcc", sizeof("bcc"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		rfc822_parse_adrlist (&env->bcc, Z_STRVAL_PP(pvalue), "NO HOST");
	}
	if (zend_hash_find(Z_ARRVAL_PP(envelope), "message_id", sizeof("message_id"), (void **) &pvalue)== SUCCESS) {
		convert_to_string_ex(pvalue);
		env->message_id=cpystr(Z_STRVAL_PP(pvalue));
	}

        if (zend_hash_find(Z_ARRVAL_PP(envelope), "custom_headers", sizeof("custom_headers"), (void **) &pvalue)== SUCCESS) {
		if (Z_TYPE_PP(pvalue) == IS_ARRAY) {
			custom_headers_param = tmp_param = NULL;
			while (zend_hash_get_current_data(Z_ARRVAL_PP(pvalue), (void **) &env_data) == SUCCESS) {
				custom_headers_param = mail_newbody_parameter();
				convert_to_string_ex(env_data);
				custom_headers_param->value = (char *) fs_get(Z_STRLEN_PP(env_data) + 1);
				memcpy(custom_headers_param->value, Z_STRVAL_PP(env_data), Z_STRLEN_PP(env_data) + 1);
				zend_hash_move_forward(Z_ARRVAL_PP(pvalue));
				custom_headers_param->next = tmp_param;
				tmp_param = custom_headers_param;
			}
		}
	}

	zend_hash_internal_pointer_reset(Z_ARRVAL_PP(body));
	zend_hash_get_current_data(Z_ARRVAL_PP(body), (void **) &data);
	zend_hash_get_current_key(Z_ARRVAL_PP(body), &key, &ind, 0); /* FIXME: is this necessary?  we're not using key/ind */

	if (Z_TYPE_PP(data) == IS_ARRAY) {
		bod = mail_newbody();
		topbod = bod;

		if (zend_hash_find(Z_ARRVAL_PP(data), "type", sizeof("type"), (void **) &pvalue)== SUCCESS) {
			convert_to_long_ex(pvalue);
			bod->type = (short) Z_LVAL_PP(pvalue);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "encoding", sizeof("encoding"), (void **) &pvalue)== SUCCESS) {
			convert_to_long_ex(pvalue);
			bod->encoding = (short) Z_LVAL_PP(pvalue);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "charset", sizeof("charset"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			tmp_param = mail_newbody_parameter();
			tmp_param->value = cpystr(Z_STRVAL_PP(pvalue));
			tmp_param->attribute = "CHARSET";
			tmp_param->next = bod->parameter;
			bod->parameter = tmp_param;
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "subtype", sizeof("subtype"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->subtype = cpystr(Z_STRVAL_PP(pvalue));
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "id", sizeof("id"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->id = cpystr(Z_STRVAL_PP(pvalue));
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "description", sizeof("description"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->description = cpystr(Z_STRVAL_PP(pvalue));
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "disposition.type", sizeof("disposition.type"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->disposition.type = (char *) fs_get(Z_STRLEN_PP(pvalue) + 1);
			memcpy(bod->disposition.type, Z_STRVAL_PP(pvalue), Z_STRLEN_PP(pvalue)+1);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "disposition", sizeof("disposition"), (void **) &pvalue)== SUCCESS) {
			if (Z_TYPE_PP(pvalue) == IS_ARRAY) {
				disp_param = tmp_param = NULL;
				while (zend_hash_get_current_data(Z_ARRVAL_PP(pvalue), (void **) &disp_data) == SUCCESS) {
					disp_param = mail_newbody_parameter();
					zend_hash_get_current_key(Z_ARRVAL_PP(pvalue), &key, &ind, 0);
					disp_param->attribute = key;
					convert_to_string_ex(disp_data);
					disp_param->value = (char *) fs_get(Z_STRLEN_PP(disp_data) + 1);
					memcpy(disp_param->value, Z_STRVAL_PP(disp_data), Z_STRLEN_PP(disp_data) + 1);
                		        zend_hash_move_forward(Z_ARRVAL_PP(pvalue));
					disp_param->next = tmp_param;
					tmp_param = disp_param;
				}
				bod->disposition.parameter = disp_param;
			}
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "contents.data", sizeof("contents.data"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->contents.text.data = (char *) fs_get(Z_STRLEN_PP(pvalue) + 1);
			memcpy(bod->contents.text.data, Z_STRVAL_PP(pvalue), Z_STRLEN_PP(pvalue)+1);
			bod->contents.text.size = Z_STRLEN_PP(pvalue);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "lines", sizeof("lines"), (void **) &pvalue)== SUCCESS) {
			convert_to_long_ex(pvalue);
			bod->size.lines = Z_LVAL_PP(pvalue);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "bytes", sizeof("bytes"), (void **) &pvalue)== SUCCESS) {
			convert_to_long_ex(pvalue);
			bod->size.bytes = Z_LVAL_PP(pvalue);
		}
		if (zend_hash_find(Z_ARRVAL_PP(data), "md5", sizeof("md5"), (void **) &pvalue)== SUCCESS) {
			convert_to_string_ex(pvalue);
			bod->md5 = cpystr(Z_STRVAL_PP(pvalue));
		}
	}

 	zend_hash_move_forward(Z_ARRVAL_PP(body));

	while (zend_hash_get_current_data(Z_ARRVAL_PP(body), (void **) &data) == SUCCESS) {
		zend_hash_get_current_key(Z_ARRVAL_PP(body), &key, &ind, 0);  /* FIXME: Is this necessary?  We're not using key/ind */
		if (Z_TYPE_PP(data) == IS_ARRAY) {
			if (!toppart) {
				bod->nested.part = mail_newbody_part();
				mypart = bod->nested.part;
				toppart = mypart;
				bod=&mypart->body;
			} else {
				 mypart->next = mail_newbody_part();
				 mypart = mypart->next;
				 bod = &mypart->body;
			}

			if (zend_hash_find(Z_ARRVAL_PP(data), "type", sizeof("type"), (void **) &pvalue)== SUCCESS) {
				convert_to_long_ex(pvalue);
				bod->type = (short) Z_LVAL_PP(pvalue);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "encoding", sizeof("encoding"), (void **) &pvalue)== SUCCESS) {
				convert_to_long_ex(pvalue);
				bod->encoding = (short) Z_LVAL_PP(pvalue);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "charset", sizeof("charset"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				tmp_param = mail_newbody_parameter();
				tmp_param->value = cpystr(Z_STRVAL_PP(pvalue));
				tmp_param->attribute = "CHARSET";
				tmp_param->next = bod->parameter;
				bod->parameter = tmp_param;
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "subtype", sizeof("subtype"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->subtype = cpystr(Z_STRVAL_PP(pvalue));	
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "id", sizeof("id"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->id = cpystr(Z_STRVAL_PP(pvalue));
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "description", sizeof("description"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->description = cpystr(Z_STRVAL_PP(pvalue));
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "disposition.type", sizeof("disposition.type"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->disposition.type = (char *) fs_get(Z_STRLEN_PP(pvalue) + 1);
				memcpy(bod->disposition.type, Z_STRVAL_PP(pvalue), Z_STRLEN_PP(pvalue)+1);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "disposition", sizeof("disposition"), (void **) &pvalue)== SUCCESS) {
				if (Z_TYPE_PP(pvalue) == IS_ARRAY) {
					disp_param = tmp_param = NULL;
					while (zend_hash_get_current_data(Z_ARRVAL_PP(pvalue), (void **) &disp_data) == SUCCESS) {
						disp_param = mail_newbody_parameter();
						zend_hash_get_current_key(Z_ARRVAL_PP(pvalue), &key, &ind, 0);
						disp_param->attribute = key;
						convert_to_string_ex(disp_data);
						disp_param->value = (char *) fs_get(Z_STRLEN_PP(disp_data) + 1);
						memcpy(disp_param->value, Z_STRVAL_PP(disp_data), Z_STRLEN_PP(disp_data) + 1);
			                        zend_hash_move_forward(Z_ARRVAL_PP(pvalue));
						disp_param->next = tmp_param;
						tmp_param = disp_param;
					}
					bod->disposition.parameter = disp_param;
				}
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "contents.data", sizeof("contents.data"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->contents.text.data = (char *) fs_get(Z_STRLEN_PP(pvalue) + 1);
				memcpy(bod->contents.text.data, Z_STRVAL_PP(pvalue), Z_STRLEN_PP(pvalue) + 1);
				bod->contents.text.size = Z_STRLEN_PP(pvalue);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "lines", sizeof("lines"), (void **) &pvalue)== SUCCESS) {
				convert_to_long_ex(pvalue);
				bod->size.lines = Z_LVAL_PP(pvalue);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "bytes", sizeof("bytes"), (void **) &pvalue)== SUCCESS) {
				convert_to_long_ex(pvalue);
				bod->size.bytes = Z_LVAL_PP(pvalue);
			}
			if (zend_hash_find(Z_ARRVAL_PP(data), "md5", sizeof("md5"), (void **) &pvalue)== SUCCESS) {
				convert_to_string_ex(pvalue);
				bod->md5 = cpystr(Z_STRVAL_PP(pvalue));
			}

			zend_hash_move_forward(Z_ARRVAL_PP(body));
		}
	}

	rfc822_encode_body_7bit(env, topbod); 
	rfc822_header (tmp, env, topbod);

	/* add custom envelope headers */
	if (custom_headers_param) {
		/* remove last CRLF from tmp */
		tmp[strlen(tmp) - 2] = '\0';
		tempstring = emalloc(strlen(tmp) + 1);
		strcpy(tempstring, tmp);
		do {
			tempstring = erealloc(tempstring, strlen(tempstring) + strlen(custom_headers_param->value) + strlen(CRLF) + 1);
			sprintf(tempstring, "%s%s%s", tempstring, custom_headers_param->value, CRLF);
		} while ((custom_headers_param = custom_headers_param->next));

		mystring = emalloc(strlen(tempstring) + strlen(CRLF) + 1);
		sprintf(mystring, "%s%s", tempstring, CRLF);
		efree(tempstring);
	} else {
		mystring = emalloc(strlen(tmp) + 1);
		strcpy(mystring, tmp);
	}

	bod = topbod;

	if (bod && bod->type == TYPEMULTIPART) {	

		/* first body part */
			part = bod->nested.part;	

		/* find cookie */
			for (param = bod->parameter; param && !cookie; param = param->next) {
				if (!strcmp (param->attribute, "BOUNDARY")) {
					cookie = param->value;
				}
			}

		/* yucky default */
			if (!cookie) {
				cookie = "-";  
			}

		/* for each part */
			do {
			/* build cookie */
				sprintf (t=tmp, "--%s%s", cookie, CRLF);

			/* append mini-header */
				rfc822_write_body_header(&t, &part->body);

			/* write terminating blank line */
				strcat (t, CRLF);

			/* output cookie, mini-header, and contents */
				tempstring=emalloc(strlen(mystring)+strlen(tmp)+1);
				strcpy(tempstring,mystring);
				efree(mystring);
				mystring=tempstring;
				strcat(mystring,tmp);

				bod=&part->body;

				tempstring=emalloc(strlen(bod->contents.text.data)+strlen(CRLF)+strlen(mystring)+1);
				strcpy(tempstring,mystring);
				efree(mystring);
				mystring=tempstring;
				sprintf(mystring, "%s%s%s", mystring, bod->contents.text.data, CRLF);

			} while ((part = part->next));/* until done */
            /* output trailing cookie */

			sprintf(tmp, "--%s--", cookie);
			tempstring=emalloc(strlen(tmp)+strlen(CRLF)+strlen(mystring)+1);
			strcpy(tempstring,mystring);
			efree(mystring);
			mystring=tempstring;
			sprintf(mystring, "%s%s%s", mystring, tmp, CRLF);

	} else if (bod) {

			tempstring=emalloc(strlen(bod->contents.text.data)+strlen(CRLF)+strlen(mystring)+1);
			strcpy(tempstring,mystring);
			efree(mystring);
			mystring=tempstring;
			sprintf(mystring, "%s%s%s", mystring, bod->contents.text.data, CRLF);

	} else {
		efree(mystring);
		RETURN_FALSE;
	}

	RETVAL_STRINGL(mystring,strlen(mystring), 1);  
	efree(tempstring);

}
/* }}} */


#ifndef PHP_WIN32
/* {{{ _php_imap_mail
 */
int _php_imap_mail(char *to, char *subject, char *message, char *headers, char *cc, char *bcc, char* rpath)
{
#ifdef PHP_WIN32
	int tsm_err;
#else
	FILE *sendmail;
	int ret;
#endif

#ifdef PHP_WIN32
	if (imap_TSendMail(INI_STR("smtp"), &tsm_err, headers, subject, to, message, cc, bcc, rpath) != SUCCESS) {
		php_error(E_WARNING, GetSMErrorText(tsm_err));
		return 0;
	}
#else
	if (!INI_STR("sendmail_path")) {
		return 0;
	}
	sendmail = popen(INI_STR("sendmail_path"), "w");
	if (sendmail) {
		if (rpath && rpath[0]) fprintf(sendmail, "From: %s\n", rpath);
		fprintf(sendmail, "To: %s\n", to);
		if (cc && cc[0]) fprintf(sendmail, "Cc: %s\n", cc);
		if (bcc && bcc[0]) fprintf(sendmail, "Bcc: %s\n", bcc);
		fprintf(sendmail, "Subject: %s\n", subject);
		if (headers != NULL) {
			fprintf(sendmail, "%s\n", headers);
		}
		fprintf(sendmail, "\n%s\n", message);
		ret = pclose(sendmail);
		if (ret == -1) {
			return 0;
		} else {
			return 1;
		}
	} else {
		php_error(E_WARNING, "Could not execute mail delivery program");
		return 0;
	}
#endif
	return 1;
}
/* }}} */
#endif

#ifndef PHP_WIN32
/* {{{ proto int imap_mail(string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])
   Send an email message */
PHP_FUNCTION(imap_mail)
{
	zval *argv[7];
	char *to=NULL, *message=NULL, *headers=NULL, *subject=NULL, *cc=NULL, *bcc=NULL, *rpath=NULL;
	int argc;
	
	argc = ZEND_NUM_ARGS();
	if (argc < 3 || argc > 7 || zend_get_parameters_array(ht, argc, argv) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	/* To: */
	convert_to_string(argv[0]);
	if (argv[0]->value.str.val) {
		to = argv[0]->value.str.val;
	} else {
		php_error(E_WARNING, "No to field in mail command");
		RETURN_FALSE;
	}

	/* Subject: */
	convert_to_string(argv[1]);
	if (argv[1]->value.str.val) {
		subject = argv[1]->value.str.val;
	} else {
		php_error(E_WARNING, "No subject field in mail command");
		RETURN_FALSE;
	}

	/* message body */
	convert_to_string(argv[2]);
	if (argv[2]->value.str.val) {
		message = argv[2]->value.str.val;
	} else {
		/* this is not really an error, so it is allowed. */
		php_error(E_WARNING, "No message string in mail command");
		message = NULL;
	}

	/* other headers */
	if (argc > 3) {
		convert_to_string(argv[3]);
		headers = argv[3]->value.str.val;
	}
	
	/* cc */
	if (argc > 4) {
		convert_to_string(argv[4]);
		cc = argv[4]->value.str.val;
	}

	/* bcc */
	if (argc > 5) {
		convert_to_string(argv[5]);
		bcc = argv[5]->value.str.val;
	}

	/* rpath */
	if (argc > 6) {
		convert_to_string(argv[6]);
		rpath = argv[6]->value.str.val;
	}

	if (_php_imap_mail(to, subject, message, headers, cc, bcc, rpath)) {
		RETURN_TRUE;
	} else {
		RETURN_FALSE;
	}
}
/* }}} */
#endif

/* {{{ proto array imap_search(int stream_id, string criteria [, long flags])
   Return a list of messages matching the given criteria */
PHP_FUNCTION(imap_search)
{
	zval **streamind, **criteria, **search_flags;
	int ind, ind_type, args;
	pils *imap_le_struct;
	long flags;
    char *search_criteria;
	MESSAGELIST *cur;
    
	args = ZEND_NUM_ARGS();
	if (args < 2 || args > 3 || zend_get_parameters_ex(args, &streamind, &criteria, &search_flags) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}
	
	convert_to_long_ex(streamind);
	convert_to_string_ex(criteria);
    search_criteria = estrndup(Z_STRVAL_PP(criteria), Z_STRLEN_PP(criteria));
	
	if (args == 2) {
		flags = SE_FREE;
	} else {
		convert_to_long_ex(search_flags);
		flags = Z_LVAL_PP(search_flags);
	}
	
	ind = Z_LVAL_PP(streamind);
	imap_le_struct = (pils *) zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		efree(search_criteria);
		RETURN_FALSE;
	}
	
	IMAPG(imap_messages) = NIL;
	mail_search_full(imap_le_struct->imap_stream, NIL, mail_criteria(search_criteria), flags);
	if (IMAPG(imap_messages) == NIL) {
		efree(search_criteria);
		RETURN_FALSE;
	}
	
	array_init(return_value);
	cur = IMAPG(imap_messages);
	while (cur != NIL) {
		add_next_index_long(return_value, cur->msgid);
		cur = cur->next;
	}
	mail_free_messagelist(&IMAPG(imap_messages));
	efree(search_criteria);
}
/* }}} */

/* {{{ proto array imap_alerts(void)
   Returns an array of all IMAP alerts that have been generated since the last page load or since the last imap_alerts() call, whichever came last. The alert stack is cleared after imap_alerts() is called. */
/* Author: CJH */
PHP_FUNCTION(imap_alerts)
{
	STRINGLIST *cur=NIL;
	int arg_count = ZEND_NUM_ARGS();
    
	if (arg_count > 0) {
		ZEND_WRONG_PARAM_COUNT();
	} 
  
	if (IMAPG(imap_alertstack) == NIL) {
		RETURN_FALSE;
	}
  
	array_init(return_value);
	cur = IMAPG(imap_alertstack);
	while (cur != NIL) {
		add_next_index_string(return_value, cur->LTEXT, 1);
		cur = cur->next;
	}
	mail_free_stringlist(&IMAPG(imap_alertstack));
	IMAPG(imap_alertstack) = NIL;
}
/* }}} */

/* {{{ proto array imap_errors(void)
   Returns an array of all IMAP errors generated since the last  page load, or since the last imap_errors() call, whichever came last. The error stack is cleared after imap_errors() is called. */
/* Author: CJH */
PHP_FUNCTION(imap_errors)
{
	ERRORLIST *cur=NIL;
	int arg_count = ZEND_NUM_ARGS();
    
	if (arg_count > 0) {
		ZEND_WRONG_PARAM_COUNT();
	}
  
	if (IMAPG(imap_errorstack) == NIL) {
		RETURN_FALSE;
	}
  
	array_init(return_value);
	cur = IMAPG(imap_errorstack);
	while (cur != NIL) {
		add_next_index_string(return_value, cur->LTEXT, 1);
		cur = cur->next;
	}
	mail_free_errorlist(&IMAPG(imap_errorstack));
	IMAPG(imap_errorstack) = NIL;
}
/* }}} */

/* {{{ proto string imap_last_error(void) 
   Returns the last error that was generated by an IMAP function. The error stack is NOT cleared after this call. */
/* Author: CJH */
PHP_FUNCTION(imap_last_error)
{
	ERRORLIST *cur=NIL;
	int arg_count = ZEND_NUM_ARGS();
    
	if (arg_count > 0) {
		ZEND_WRONG_PARAM_COUNT();
	}
  
	if (IMAPG(imap_errorstack) == NIL) {
		RETURN_FALSE;
	}
  
	cur = IMAPG(imap_errorstack);
	while (cur != NIL) {
		if (cur->next == NIL) {
			RETURN_STRING(cur->LTEXT, 1);
		}
		cur = cur->next;
	}
}
/* }}} */

/* {{{ proto array imap_mime_header_decode(string str)
   Decode mime header element in accordance with RFC 2047 and return array of objects containing 'charset' encoding and decoded 'text' */
PHP_FUNCTION(imap_mime_header_decode)
{
	/* Author: Ted Parnefors <ted@mtv.se> */
	zval **str, *myobject;
	char *string, *charset, encoding, *text, *decode;
	long charset_token, encoding_token, end_token, end, offset=0, i;
	unsigned long newlength;

	if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &str) == FAILURE) {
		ZEND_WRONG_PARAM_COUNT();
	}

	convert_to_string_ex(str);

	if (array_init(return_value) == FAILURE) {
		RETURN_FALSE;
	}

	string = (*str)->value.str.val;
	end = (*str)->value.str.len;
			
	if ((charset = ((char *)emalloc((end + 1) * 2)))) {
		text = &charset[end + 1];
		while (offset < end) {	/* Reached end of the string? */
			if ((charset_token = (long)php_memnstr(&string[offset], "=?", 2, string + end))) {	/* Is there anything encoded in the string? */
				charset_token -= (long)string;
				if (offset != charset_token) {	/* Is there anything before the encoded data? */
					/* Retrieve unencoded data that is found before encoded data */
					memcpy(text, &string[offset], charset_token-offset);
					text[charset_token - offset] = 0x00;
					MAKE_STD_ZVAL(myobject);
					object_init(myobject);
					add_property_string(myobject, "charset", "default", 1);
					add_property_string(myobject, "text", text, 1);
					zend_hash_next_index_insert(return_value->value.ht, (void *)&myobject, sizeof(zval *), NULL);
				}
				if ((encoding_token = (long)php_memnstr(&string[charset_token+2], "?", 1, string+end))) {		/* Find token for encoding */
					encoding_token -= (long)string;
					if ((end_token = (long)php_memnstr(&string[encoding_token+3], "?=", 2, string+end))) {	/* Find token for end of encoded data */
						end_token -= (long)string;
						memcpy(charset, &string[charset_token + 2], encoding_token - (charset_token + 2));	/* Extract charset encoding */
						charset[encoding_token-(charset_token + 2)] = 0x00;
						encoding=string[encoding_token + 1];	/* Extract encoding from string */
						memcpy(text, &string[encoding_token + 3], end_token - (encoding_token + 3));	/* Extract text */
						text[end_token - (encoding_token + 3)] = 0x00;
						decode = text;
						if (encoding == 'q' || encoding == 'Q') {	/* Decode 'q' encoded data */
							for(i=0; text[i] != 0x00; i++) if (text[i] == '_') text[i] = ' ';	/* Replace all *_' with space. */
							decode = (char *)rfc822_qprint((unsigned char *) text, strlen(text), &newlength);
						} else if (encoding == 'b' || encoding == 'B') {
							decode = (char *)rfc822_base64((unsigned char *) text, strlen(text), &newlength); /* Decode 'B' encoded data */
						}
						if (decode == NULL) {
							efree(charset);
							zval_dtor(return_value);
							RETURN_FALSE;
						}
						MAKE_STD_ZVAL(myobject);
						object_init(myobject);
						add_property_string(myobject, "charset", charset, 1);
						add_property_string(myobject, "text", decode, 1);
						zend_hash_next_index_insert(return_value->value.ht, (void *)&myobject, sizeof(zval *), NULL);
						fs_give((void**)&decode);
						
						offset = end_token+2;
						for (i = 0; (string[offset + i] == ' ') || (string[offset + i] == 0x0a) || (string[offset + i] == 0x0d); i++);
						if ((string[offset + i] == '=') && (string[offset + i + 1] == '?') && (offset + i < end)) {
							offset += i;
						}
						continue;	/*/ Iterate the loop again please. */
					}
				}
			} else {
				/* Just some tweaking to optimize the code, and get the end statements work in a general manner.
				   If we end up here we didn't find a position for "charset_token",
				   so we need to set it to the start of the yet unextracted data. */
				charset_token = offset;
			}
			/* Return the rest of the data as unencoded, as it was either unencoded or was missing separators
			   which rendered the the remainder of the string impossible for us to decode. */
			memcpy(text, &string[charset_token], end - charset_token);	/* Extract unencoded text from string */
			text[end - charset_token] = 0x00;
			MAKE_STD_ZVAL(myobject);
			object_init(myobject);
			add_property_string(myobject, "charset", "default", 1);
			add_property_string(myobject, "text", text, 1);
			zend_hash_next_index_insert(return_value->value.ht, (void *)&myobject, sizeof(zval *), NULL);
			
			offset = end;	/* We have reached the end of the string. */
		}
		efree(charset);
	} else {
		php_error(E_WARNING, "Unable to allocate temporary memory buffer for imap_mime_header_decode");
		RETURN_FALSE;
	}
}
/* }}} */


/* Support Functions */
/* {{{ _php_imap_parse_address
 */
void _php_imap_parse_address (ADDRESS *addresslist, char *fulladdress, zval *paddress)
{
	ADDRESS *addresstmp, *addresstmp2;
	char tempaddress[MAILTMPLEN];
	zval *tmpvals;
	int ok = 1;
	
	addresstmp = addresslist;
	fulladdress[0] = 0x00;
	while (ok && addresstmp) {                                    /* while length < 1000 and we are not at the end of the list */
		addresstmp2 = addresstmp->next;                           /* save the pointer to the next address */
		addresstmp->next = NULL;                                  /* make this address the only one now. */
		tempaddress[0] = '\0';                                    /* reset tempaddress buffer */
		rfc822_write_address(tempaddress, addresstmp);            /* ok, write the address into tempaddress string */
		if ((strlen(tempaddress) + strlen(fulladdress)) < 1000) { /* is the new address + total address < 1000 */
			if (strlen(fulladdress)) {
				strcat(fulladdress, ",");	                      /* put in a comma */ 
			}
			strcat(fulladdress, tempaddress);                     /* put in the new address */
		} else {                                                  /* no */
			ok = 0;                                               /* stop looping */
			strcat(fulladdress, ", ..."); 
		}		/* DO NOT optimize this out - changing it breaks things */
		addresstmp->next = addresstmp2; /* reset the pointer to the next address first! */
		addresstmp = addresstmp->next; 
	}
	
	addresstmp = addresslist;
	do {
		MAKE_STD_ZVAL(tmpvals);
		object_init(tmpvals);
		if (addresstmp->personal) add_property_string(tmpvals, "personal", addresstmp->personal, 1);
		if (addresstmp->adl) add_property_string(tmpvals, "adl", addresstmp->adl, 1);
		if (addresstmp->mailbox) add_property_string(tmpvals, "mailbox", addresstmp->mailbox, 1);
		if (addresstmp->host) add_property_string(tmpvals, "host", addresstmp->host, 1);
		add_next_index_object(paddress, tmpvals);
	} while ((addresstmp = addresstmp->next));
}
/* }}} */

/* {{{ _php_make_header_object
 */
void _php_make_header_object(zval *myzvalue, ENVELOPE *en)
{
	zval *paddress;
	char fulladdress[MAILTMPLEN];
	
	object_init(myzvalue);
	
    if (en->remail) add_property_string(myzvalue, "remail", en->remail, 1);
    if (en->date) add_property_string(myzvalue, "date", en->date, 1);
    if (en->date) add_property_string(myzvalue, "Date", en->date, 1);
    if (en->subject) add_property_string(myzvalue, "subject", en->subject, 1);
    if (en->subject) add_property_string(myzvalue, "Subject", en->subject, 1);
    if (en->in_reply_to) add_property_string(myzvalue, "in_reply_to", en->in_reply_to, 1);
    if (en->message_id) add_property_string(myzvalue, "message_id", en->message_id, 1);
    if (en->newsgroups) add_property_string(myzvalue, "newsgroups", en->newsgroups, 1);
    if (en->followup_to) add_property_string(myzvalue, "followup_to", en->followup_to, 1);
    if (en->references) add_property_string(myzvalue, "references", en->references, 1);
	
	if (en->to) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->to, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "toaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "to", paddress);
	}
	
	if (en->from) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->from, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "fromaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "from", paddress);
	}
	
	if (en->cc) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->cc, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "ccaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "cc", paddress);
	}
	
	if (en->bcc) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->bcc, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "bccaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "bcc", paddress);
	}
	
	if (en->reply_to) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->reply_to, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "reply_toaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "reply_to", paddress);
	}

	if (en->sender) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->sender, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "senderaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "sender", paddress);
	}

	if (en->return_path) {
		MAKE_STD_ZVAL(paddress);
		array_init(paddress);
		_php_imap_parse_address(en->return_path, fulladdress, paddress);
		if (fulladdress) add_property_string(myzvalue, "return_pathaddress", fulladdress, 1);
		add_assoc_object(myzvalue, "return_path", paddress);
	}
	
}
/* }}} */

/* {{{ _php_imap_add_body
 */
void _php_imap_add_body(zval *arg, BODY *body)
{
	zval *parametres, *param, *dparametres, *dparam;
	PARAMETER *par, *dpar;
	PART *part;
	
	if (body->type <= TYPEMAX) {
		add_property_long(arg, "type", body->type);
	}
	if (body->encoding <= ENCMAX) {
		add_property_long(arg, "encoding", body->encoding);
	}

	if (body->subtype) {
		add_property_long(arg, "ifsubtype", 1);
		add_property_string(arg, "subtype",  body->subtype, 1);
	} else {
		add_property_long(arg, "ifsubtype", 0);
	}

	if (body->description) {
		add_property_long(arg, "ifdescription", 1);
		add_property_string(arg, "description",  body->description, 1);
	} else {
		add_property_long(arg, "ifdescription", 0);
	}
	if (body->id) {
		add_property_long(arg, "ifid", 1);
		add_property_string(arg, "id",  body->id, 1);
	} else {
		add_property_long(arg, "ifid", 0);
	}
	
	if (body->size.lines) {
		add_property_long(arg, "lines", body->size.lines);
	}
	if (body->size.bytes) {
		add_property_long(arg, "bytes", body->size.bytes);
	}
#ifdef IMAP41
	if (body->disposition.type) {
		add_property_long(arg, "ifdisposition", 1);
		add_property_string(arg, "disposition", body->disposition.type, 1);
	} else {
		add_property_long(arg, "ifdisposition", 0);
	}

	if (body->disposition.parameter) {
		dpar = body->disposition.parameter;
		add_property_long(arg, "ifdparameters", 1);
		MAKE_STD_ZVAL(dparametres);
		array_init(dparametres);
		do {
			MAKE_STD_ZVAL(dparam);
			object_init(dparam);
			add_property_string(dparam, "attribute", dpar->attribute, 1);
			add_property_string(dparam, "value", dpar->value, 1);
			add_next_index_object(dparametres, dparam);
        } while ((dpar = dpar->next));
		add_assoc_object(arg, "dparameters", dparametres);
	} else {
		add_property_long(arg, "ifdparameters", 0);
	}
#endif
 
	if ((par = body->parameter)) {
		add_property_long(arg, "ifparameters", 1);

		MAKE_STD_ZVAL(parametres);
		array_init(parametres);
		do {
			MAKE_STD_ZVAL(param);
			object_init(param);
			if (par->attribute) {
				add_property_string(param, "attribute", par->attribute, 1);
			}
			if (par->value) {
				add_property_string(param, "value", par->value, 1);
			}

			add_next_index_object(parametres, param);
		} while ((par = par->next));
	} else {
		MAKE_STD_ZVAL(parametres);
		object_init(parametres);
		add_property_long(arg, "ifparameters", 0);
	}
	add_assoc_object(arg, "parameters", parametres);

	/* multipart message ? */
	if (body->type == TYPEMULTIPART) {
		MAKE_STD_ZVAL(parametres);
		array_init(parametres);
		for (part = body->CONTENT_PART; part; part = part->next) {
			MAKE_STD_ZVAL(param);
			object_init(param);
			_php_imap_add_body(param, &part->body);
			add_next_index_object(parametres, param);
		}
		add_assoc_object(arg, "parts", parametres);
	}
	
	/* encapsulated message ? */
	if ((body->type == TYPEMESSAGE) && (!strcasecmp(body->subtype, "rfc822"))) {
		body = body->CONTENT_MSG_BODY;
		MAKE_STD_ZVAL(parametres);
		array_init(parametres);
		MAKE_STD_ZVAL(param);
		object_init(param);
		_php_imap_add_body(param, body);
		add_next_index_object(parametres, param);
		add_assoc_object(arg, "parts", parametres);
	}
}
/* }}} */

/* Interfaces to C-client */
void mm_searched(MAILSTREAM *stream,unsigned long number)
{
	MESSAGELIST *cur = NIL;
	TSRMLS_FETCH();
  
	if (IMAPG(imap_messages) == NIL) {
		IMAPG(imap_messages) = mail_newmessagelist();
		IMAPG(imap_messages)->msgid = number;
		IMAPG(imap_messages)->next = NIL;
	} else {
		cur = IMAPG(imap_messages);
		while (cur->next != NIL) {
			cur = cur->next;
		}
		cur->next = mail_newmessagelist();
		cur = cur->next;
		cur->msgid = number;
		cur->next = NIL;
	}
}

void mm_exists(MAILSTREAM *stream,unsigned long number)
{
}

void mm_expunged(MAILSTREAM *stream,unsigned long number)
{
}

void mm_flags(MAILSTREAM *stream,unsigned long number)
{
}

/* Author: CJH */
void mm_notify(MAILSTREAM *stream, char *str, long errflg)
{
	STRINGLIST *cur = NIL;
	TSRMLS_FETCH();
  
	if (strncmp(str, "[ALERT] ", 8) == 0) {
		if (IMAPG(imap_alertstack) == NIL) {
			IMAPG(imap_alertstack) = mail_newstringlist();
			IMAPG(imap_alertstack)->LSIZE = strlen(IMAPG(imap_alertstack)->LTEXT = cpystr(str));
			IMAPG(imap_alertstack)->next = NIL; 
		} else {
			cur = IMAPG(imap_alertstack);
			while (cur->next != NIL) {
				cur = cur->next;
			}
			cur->next = mail_newstringlist ();
			cur = cur->next;
			cur->LSIZE = strlen(cur->LTEXT = cpystr(str));
			cur->next = NIL;
		}
	}
}

void mm_list(MAILSTREAM *stream,DTYPE delimiter, char *mailbox, long attributes)
{
	STRINGLIST *cur=NIL;
	FOBJECTLIST *ocur=NIL;
	TSRMLS_FETCH();
	
	if (IMAPG(folderlist_style) == FLIST_OBJECT) {
		/* build up a the new array of objects */
		/* Author: CJH */
		if (IMAPG(imap_folder_objects) == NIL) {
			IMAPG(imap_folder_objects) = mail_newfolderobjectlist();
			IMAPG(imap_folder_objects)->LSIZE=strlen(IMAPG(imap_folder_objects)->LTEXT=cpystr(mailbox));
			IMAPG(imap_folder_objects)->delimiter = delimiter;
			IMAPG(imap_folder_objects)->attributes = attributes;
			IMAPG(imap_folder_objects)->next = NIL;
		} else {
			ocur=IMAPG(imap_folder_objects);
			while (ocur->next != NIL) {
				ocur=ocur->next;
			}
			ocur->next=mail_newfolderobjectlist();
			ocur=ocur->next;
			ocur->LSIZE = strlen(ocur->LTEXT = cpystr(mailbox));
			ocur->delimiter = delimiter;
			ocur->attributes = attributes;
			ocur->next = NIL;
		}
		
	} else {
		/* build the old IMAPG(imap_folders) variable to allow old imap_listmailbox() to work */
		if (!(attributes & LATT_NOSELECT)) {
			if (IMAPG(imap_folders) == NIL) {
				IMAPG(imap_folders)=mail_newstringlist();
				IMAPG(imap_folders)->LSIZE=strlen(IMAPG(imap_folders)->LTEXT=cpystr(mailbox));
				IMAPG(imap_folders)->next=NIL; 
			} else {
				cur=IMAPG(imap_folders);
				while (cur->next != NIL) {
					cur=cur->next;
				}
				cur->next=mail_newstringlist ();
				cur=cur->next;
				cur->LSIZE = strlen (cur->LTEXT = cpystr (mailbox));
				cur->next = NIL;
			}
		}
	}
}

void mm_lsub(MAILSTREAM *stream,DTYPE delimiter, char *mailbox, long attributes)
{
	STRINGLIST *cur=NIL;
	FOBJECTLIST *ocur=NIL;
	TSRMLS_FETCH();
	
	if (IMAPG(folderlist_style) == FLIST_OBJECT) {
		/* build the array of objects */
		/* Author: CJH */
		if (IMAPG(imap_sfolder_objects) == NIL) {
			IMAPG(imap_sfolder_objects) = mail_newfolderobjectlist();
			IMAPG(imap_sfolder_objects)->LSIZE=strlen(IMAPG(imap_sfolder_objects)->LTEXT=cpystr(mailbox));
			IMAPG(imap_sfolder_objects)->delimiter = delimiter;
			IMAPG(imap_sfolder_objects)->attributes = attributes;
			IMAPG(imap_sfolder_objects)->next = NIL;
		} else {
			ocur=IMAPG(imap_sfolder_objects);
			while (ocur->next != NIL) {
				ocur=ocur->next;
			}
			ocur->next=mail_newfolderobjectlist();
			ocur=ocur->next;
			ocur->LSIZE=strlen(ocur->LTEXT = cpystr(mailbox));
			ocur->delimiter = delimiter;
			ocur->attributes = attributes;
			ocur->next = NIL;
		}
	} else {
		/* build the old simple array for imap_listsubscribed() */
		if (IMAPG(imap_sfolders) == NIL) {
			IMAPG(imap_sfolders)=mail_newstringlist();
			IMAPG(imap_sfolders)->LSIZE=strlen(IMAPG(imap_sfolders)->LTEXT=cpystr(mailbox));
			IMAPG(imap_sfolders)->next=NIL; 
		} else {
			cur=IMAPG(imap_sfolders);
			while (cur->next != NIL) {
				cur=cur->next;
			}
			cur->next=mail_newstringlist ();
			cur=cur->next;
			cur->LSIZE = strlen (cur->LTEXT = cpystr (mailbox));
			cur->next = NIL;
		}
	}
}

void mm_status(MAILSTREAM *stream, char *mailbox,MAILSTATUS *status)
{
	TSRMLS_FETCH();

	IMAPG(status_flags)=status->flags;
	if (IMAPG(status_flags) & SA_MESSAGES) {
		IMAPG(status_messages)=status->messages;
	}
	if (IMAPG(status_flags) & SA_RECENT) {
		IMAPG(status_recent)=status->recent;
	}
	if (IMAPG(status_flags) & SA_UNSEEN) {
		IMAPG(status_unseen)=status->unseen;
	}
	if (IMAPG(status_flags) & SA_UIDNEXT) {
		IMAPG(status_uidnext)=status->uidnext;
	}
	if (IMAPG(status_flags) & SA_UIDVALIDITY) {
		IMAPG(status_uidvalidity)=status->uidvalidity;
	}
}

void mm_log(char *str, long errflg)
{
	ERRORLIST *cur = NIL;
	TSRMLS_FETCH();
  
	/* Author: CJH */
	if (errflg != NIL) { /* CJH: maybe put these into a more comprehensive log for debugging purposes? */
		if (IMAPG(imap_errorstack) == NIL) {
			IMAPG(imap_errorstack) = mail_newerrorlist();
			IMAPG(imap_errorstack)->LSIZE = strlen(IMAPG(imap_errorstack)->LTEXT = cpystr(str));
			IMAPG(imap_errorstack)->errflg = errflg;
			IMAPG(imap_errorstack)->next = NIL; 
		} else {
			cur = IMAPG(imap_errorstack);
			while (cur->next != NIL) {
				cur = cur->next;
			}
			cur->next = mail_newerrorlist();
			cur = cur->next;
			cur->LSIZE = strlen(cur->LTEXT = cpystr(str));
			cur->errflg = errflg;
			cur->next = NIL;
		}
	}
}

void mm_dlog(char *str)
{
	/* CJH: this is for debugging; it might be useful to allow setting
	   the stream to debug mode and capturing this somewhere - syslog?
	   php debugger? */
}

void mm_login(NETMBX *mb, char *user, char *pwd, long trial)
{
	TSRMLS_FETCH();

	if (*mb->user) {
		strlcpy (user,mb->user, MAILTMPLEN);
	} else {
		strlcpy (user, IMAPG(imap_user), MAILTMPLEN);
	}
	strlcpy (pwd, IMAPG(imap_password), MAILTMPLEN);
}

void mm_critical(MAILSTREAM *stream)
{
}

void mm_nocritical(MAILSTREAM *stream)
{
}

long mm_diskerror(MAILSTREAM *stream, long errcode, long serious)
{
	return 1;
}

void mm_fatal(char *str)
{
}

/* Added imap_thread functionality */
/* stealing this from header cclient -rjs3 */
THREADNODE *imap_thread (MAILSTREAM *stream,char *type,char *charset,
   SEARCHPGM *spg,long flags);

void build_thread_tree_helper(THREADNODE *cur, zval *tree, long *numNodes, char *buf) {
	unsigned long thisNode = *numNodes;

	/* define "#.num" */
	snprintf(buf,25,"%ld.num", thisNode);

	add_assoc_long(tree,buf,cur->num);

	snprintf(buf,25,"%ld.next", thisNode);
	if(cur->next) {
	    (*numNodes)++;
	    add_assoc_long(tree,buf,*numNodes);
	    build_thread_tree_helper(cur->next, tree, numNodes, buf);
	} else { /* "null pointer" */
	    add_assoc_long(tree,buf,0);
	}

	snprintf(buf,25,"%ld.branch", thisNode);
	if(cur->branch) {
	    (*numNodes)++;
	    add_assoc_long(tree,buf,*numNodes);
	    build_thread_tree_helper(cur->branch, tree, numNodes, buf);	    
	} else { /* "null pointer" */
	    add_assoc_long(tree,buf,0);
	}
}

int build_thread_tree(THREADNODE *top, zval **tree) {
	long numNodes = 0;
	char buf[25];

	if(array_init(*tree) != SUCCESS) return FAILURE;
	
	build_thread_tree_helper(top, *tree, &numNodes, buf);

	return SUCCESS;
}

/* {{{ proto int imap_thread(int stream_id)
   Return threaded by REFERENCES tree */
PHP_FUNCTION (imap_thread)
{
	pval *streamind, *search_flags;
	int ind, ind_type, args;
	pils *imap_le_struct;
	long flags;
	char criteria[] = "ALL";
        THREADNODE *top;

	if(!return_value_used) {
		php_error(E_WARNING, "imap_thread does not make use of return value");
		RETURN_FALSE;
	}

	args = ARG_COUNT(ht);
	if (  args < 1 || args > 2
	   || getParameters(ht, args, &streamind, &search_flags) == FAILURE) {
		WRONG_PARAM_COUNT;
	}
	
	convert_to_long(streamind);
	
	if (args == 1) {
		flags = SE_FREE;
	} else {
		convert_to_long(search_flags);
		flags = search_flags->value.lval;
	}
	
	ind = streamind->value.lval;
	imap_le_struct = (pils *)zend_list_find(ind, &ind_type);
	if (!imap_le_struct || !IS_STREAM(ind_type)) {
		php_error(E_WARNING, "Unable to find stream pointer");
		RETURN_FALSE;
	}
	
	top = mail_thread(imap_le_struct->imap_stream,
		"REFERENCES", NIL, mail_criteria(criteria), flags);

	if(top == NIL) {
		php_error(E_WARNING, "imap_thread returned an empty tree");
		RETURN_FALSE;
	}

	/* Populate our return value data structure here. */
	if(build_thread_tree(top, &return_value) == FAILURE){
	    mail_free_threadnode(&top);
	    RETURN_FALSE;
	}
	
	mail_free_threadnode(&top);
}
/* }}} */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: sw=4 ts=4 tw=78 fdm=marker
 * vim<600: sw=4 ts=4 tw=78
 */