summaryrefslogtreecommitdiff
path: root/program/lib/imap.inc
blob: 65cc5c69f7600f7c5a9382c00c6d723b17bba6df (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
<?php
/////////////////////////////////////////////////////////
//	
//	Iloha IMAP Library (IIL)
//
//	(C)Copyright 2002 Ryo Chijiiwa <Ryo@IlohaMail.org>
//
//	This file is part of IlohaMail. IlohaMail is free software released 
//	under the GPL license.  See enclosed file COPYING for details, or 
//	see http://www.fsf.org/copyleft/gpl.html
//
/////////////////////////////////////////////////////////

/********************************************************

	FILE: include/imap.inc
	PURPOSE:
		Provide alternative IMAP library that doesn't rely on the standard 
		C-Client based version.  This allows IlohaMail to function regardless
		of whether or not the PHP build it's running on has IMAP functionality
		built-in.
	USEAGE:
		Function containing "_C_" in name require connection handler to be
		passed as one of the parameters.  To obtain connection handler, use
		iil_Connect()
	VERSION:
		IlohaMail-0.9-20050415
	CHANGES:
		File altered by Thomas Bruederli <roundcube@gmail.com>
		to fit enhanced equirements by the RoundCube Webmail:
		- Added list of server capabilites and check these before invoking commands
		- Added junk flag to iilBasicHeader
		- Enhanced error reporting on fsockopen()
		- Additional parameter for SORT command
		- Removed Call-time pass-by-reference because deprecated
		- Parse charset from content-type in iil_C_FetchHeaders()
		- Enhanced heaer sorting
		- Pass message as reference in iil_C_Append (to save memory)
		- Added BCC and REFERENCE to the list of headers to fetch in iil_C_FetchHeaders()
		- Leave messageID unchanged in iil_C_FetchHeaders()
		- Avoid stripslahes in iil_Connect()
		- Escape quotes and backslashes in iil_C_Login()
		- Added patch to iil_SortHeaders() by Richard Green
		- Removed <br> from error messages (better for logging)
		- Added patch to iil_C_Sort() enabling UID SORT commands
		- Added function iil_C_ID2UID()
		- Casting date parts in iil_StrToTime() to avoid mktime() warnings
		- Also acceppt LIST responses in iil_C_ListSubscribed()
		- Sanity check of $message_set in iil_C_FetchHeaders(), iil_C_FetchHeaderIndex(), iil_C_FetchThreadHeaders()
		- Implemented UID FETCH in iil_C_FetchHeaders()
		- Abort do-loop on socket errors (fgets returns false)
		- $ICL_SSL is not boolean anymore but contains the connection schema (ssl or tls)
		- Removed some debuggers (echo ...)
		File altered by Aleksander Machniak <alec@alec.pl>
		- trim(chop()) replaced by trim()
		- added iil_Escape() with support for " and \ in folder names
		- support \ character in username in iil_C_Login()
		- fixed iil_MultLine(): use iil_ReadBytes() instead of iil_ReadLine()
		- fixed iil_C_FetchStructureString() to handle many literal strings in response
		- removed hardcoded data size in iil_ReadLine() 
		- added iil_PutLine() wrapper for fputs()
		- code cleanup and identation fixes
		- removed flush() calls in iil_C_HandlePartBody() to prevent from memory leak (#1485187)
		- don't return "??" from iil_C_GetQuota()
		- RFC3501 [7.1] don't call CAPABILITY if was returned in server 
		  optional resposne in iil_Connect(), added iil_C_GetCapability()
		- remove 'undisclosed-recipients' string from 'To' header
		- iil_C_HandlePartBody(): added 6th argument and fixed endless loop
		- added iil_PutLineC() 
		- fixed iil_C_Sort() to support very long and/or divided responses
		- added BYE response simple support for endless loop prevention
		- added 3rd argument in iil_StartsWith* functions
		- fix iil_C_FetchPartHeader() in some cases by use of iil_C_HandlePartBody()
		- allow iil_C_HandlePartBody() to fetch whole message

********************************************************/

/**
 * @todo Possibly clean up more CS.
 * @todo Try to replace most double-quotes with single-quotes.
 * @todo Split this file into smaller files.
 * @todo Refactor code.
 * @todo Replace echo-debugging (make it adhere to config setting and log)
 */

// changed path to work within roundcube webmail
include_once 'lib/icl_commons.inc';


if (!isset($IMAP_USE_HEADER_DATE) || !$IMAP_USE_HEADER_DATE) {
    $IMAP_USE_INTERNAL_DATE = true;
}

/**
 * @todo Maybe use date() to generate this.
 */
$GLOBALS['IMAP_MONTHS'] = array("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4,
    "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10,
    "Nov" => 11, "Dec" => 12);

$GLOBALS['IMAP_SERVER_TZ'] = date('Z');

$GLOBALS['IMAP_FLAGS'] = array(
    'SEEN'     => '\\Seen',
    'DELETED'  => '\\Deleted',
    'RECENT'   => '\\Recent',
    'ANSWERED' => '\\Answered',
    'DRAFT'    => '\\Draft',
    'FLAGGED'  => '\\Flagged',
    'FORWARDED' => '$Forwarded',
    'MDNSENT'  => '$MDNSent');

$iil_error;
$iil_errornum;
$iil_selected;

/**
 * @todo Change class vars to public/private
 */
class iilConnection
{
	var $fp;
	var $error;
	var $errorNum;
	var $selected;
	var $message;
	var $host;
	var $cache;
	var $uid_cache;
	var $do_cache;
	var $exists;
	var $recent;
	var $rootdir;
	var $delimiter;
	var $capability = array();
	var $permanentflags = array();
	var $capability_readed = false;
}

/**
 * @todo Change class vars to public/private
 */
class iilBasicHeader
{
	var $id;
	var $uid;
	var $subject;
	var $from;
	var $to;
	var $cc;
	var $replyto;
	var $in_reply_to;
	var $date;
	var $messageID;
	var $size;
	var $encoding;
	var $charset;
	var $ctype;
	var $flags;
	var $timestamp;
	var $f;
	var $internaldate;
	var $references;
	var $priority;
	var $mdn_to;
	var $mdn_sent = false;
	var $is_draft = false;
	var $seen = false;
	var $deleted = false;
	var $recent = false;
	var $answered = false;
	var $forwarded = false;
	var $junk = false;
	var $flagged = false;
}

/**
 * @todo Change class vars to public/private
 */
class iilThreadHeader
{
	var $id;
	var $sbj;
	var $irt;
	var $mid;
}

function iil_xor($string, $string2) {
	$result = '';
	$size = strlen($string);
	for ($i=0; $i<$size; $i++) {
    		$result .= chr(ord($string[$i]) ^ ord($string2[$i]));
	}
	return $result;
}

function iil_PutLine($fp, $string, $endln=true) {
//      console('C: '. rtrim($string));
        return fputs($fp, $string . ($endln ? "\r\n" : ''));
}

// iil_PutLine replacement with Command Continuation Requests (RFC3501 7.5) support
function iil_PutLineC($fp, $string, $endln=true) {
	if ($endln)
		$string .= "\r\n";

	$res = 0;
	if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
		for($i=0, $cnt=count($parts); $i<$cnt; $i++) {
			if(preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
				$res += iil_PutLine($fp, $parts[$i].$parts[$i+1], false);
				$line = iil_ReadLine($fp, 1000);
				$i++;
			}
			else
				$res += iil_PutLine($fp, $parts[$i], false);
		}
	}
	return $res;
}

function iil_ReadLine($fp, $size) {
	$line = '';

	if (!$fp) {
    		return $line;
	}
    
	if (!$size) {
		$size = 1024;
	}
    
	do {
    		$buffer = fgets($fp, $size);
    		if ($buffer === false) {
        		break;
    		}
//		console('S: '. chop($buffer));
    		$line .= $buffer;
	} while ($buffer[strlen($buffer)-1] != "\n");
	
	return $line;
}

function iil_MultLine($fp, $line) {
	$line = chop($line);
	if (ereg('\{[0-9]+\}$', $line)) {
		$out = '';
        
		preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
		$bytes = $a[2][0];
		while (strlen($out) < $bytes) {
			$line = iil_ReadBytes($fp, $bytes); 
			$out .= $line;
		}
		$line = $a[1][0] . "\"$out\"";
//		console('[...] '. $out);
	}
	return $line;
}

function iil_ReadBytes($fp, $bytes) {
	$data = '';
	$len  = 0;
	do {
    		$data .= fread($fp, $bytes-$len);
		if ($len == strlen($data)) {
    		        break; //nothing was read -> exit to avoid apache lockups
    		}
    		$len = strlen($data);
	} while ($len < $bytes);
	
	return $data;
}

function iil_ReadReply($fp) {
	do {
		$line = trim(iil_ReadLine($fp, 1024));
	} while ($line[0] == '*');
	
	return $line;
}

function iil_ParseResult($string) {
	$a=explode(' ', $string);
	if (count($a) > 2) {
		if (strcasecmp($a[1], 'OK') == 0) {
			return 0;
		} else if (strcasecmp($a[1], 'NO') == 0) {
			return -1;
		} else if (strcasecmp($a[1], 'BAD') == 0) {
			return -2;
		} else if (strcasecmp($a[1], 'BYE') == 0) {
			return -3;
    		}
	}
	return -4;
}

// check if $string starts with $match
function iil_StartsWith($string, $match, $bye=false) {
	$len = strlen($match);
	if ($len == 0) {
		return false;
	}
	if (strncmp($string, $match, $len) == 0) {
		return true;
	}
	if ($bye && strncmp($string, '* BYE ', 6) == 0) {
		return true;
	}
	return false;
}

function iil_StartsWithI($string, $match, $bye=false) {
	$len = strlen($match);
	if ($len == 0) {
		return false;
	}
	if (strncasecmp($string, $match, $len) == 0) {
		return true;
	}
	if ($bye && strncmp($string, '* BYE ', 6) == 0) {
		return true;
	}
	return false;
}

function iil_Escape($string)
{
	return strtr($string, array('"'=>'\\"', '\\' => '\\\\')); 
}

function iil_C_GetCapability(&$conn, $name)
{
	if (in_array($name, $conn->capability)) {
		return true;
	}
	else if ($conn->capability_readed) {
		return false;
	}

	// get capabilities (only once) because initial 
	// optional CAPABILITY response may differ
	$conn->capability = array();

	iil_PutLine($conn->fp, "cp01 CAPABILITY");
	do {
		$line = trim(iil_ReadLine($conn->fp, 1024));
		$a = explode(' ', $line);
		if ($line[0] == '*') {
			while (list($k, $w) = each($a)) {
				if ($w != '*' && $w != 'CAPABILITY')
    					$conn->capability[] = strtoupper($w);
			}
		}
	} while ($a[0] != 'cp01');
	
	$conn->capability_readed = true;

	if (in_array($name, $conn->capability)) {
		return true;
	}

	return false;
}

function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge) {
    
    $ipad = '';
    $opad = '';
    
    // initialize ipad, opad
    for ($i=0;$i<64;$i++) {
        $ipad .= chr(0x36);
        $opad .= chr(0x5C);
    }

    // pad $pass so it's 64 bytes
    $padLen = 64 - strlen($pass);
    for ($i=0;$i<$padLen;$i++) {
        $pass .= chr(0);
    }
    
    // generate hash
    $hash  = md5(iil_xor($pass,$opad) . pack("H*", md5(iil_xor($pass, $ipad) . base64_decode($encChallenge))));
    
    // generate reply
    $reply = base64_encode($user . ' ' . $hash);
    
    // send result, get reply
    iil_PutLine($conn->fp, $reply);
    $line = iil_ReadLine($conn->fp, 1024);
    
    // process result
    $result = iil_ParseResult($line);
    if ($result == 0) {
        $conn->error    .= '';
        $conn->errorNum  = 0;
        return $conn->fp;
    }

    if ($result == -3) fclose($conn->fp); // BYE response

    $conn->error    .= 'Authentication for ' . $user . ' failed (AUTH): "';
    $conn->error    .= htmlspecialchars($line) . '"';
    $conn->errorNum  = $result;

    return $result;
}

function iil_C_Login(&$conn, $user, $password) {

    iil_PutLine($conn->fp, 'a001 LOGIN "'.iil_Escape($user).'" "'.iil_Escape($password).'"');

    do {
        $line = iil_ReadReply($conn->fp);
        if ($line === false) {
            break;
        }
    } while (!iil_StartsWith($line, 'a001 ', true));
    
    // process result
    $result = iil_ParseResult($line);

    if ($result == 0) {
        $conn->error    .= '';
        $conn->errorNum  = 0;
        return $conn->fp;
    }

    fclose($conn->fp);
    
    $conn->error    .= 'Authentication for ' . $user . ' failed (LOGIN): "';
    $conn->error    .= htmlspecialchars($line)."\"";
    $conn->errorNum  = $result;

    return $result;
}

function iil_ParseNamespace2($str, &$i, $len=0, $l) {
	if (!$l) {
	    $str = str_replace('NIL', '()', $str);
	}
	if (!$len) {
	    $len = strlen($str);
	}
	$data      = array();
	$in_quotes = false;
	$elem      = 0;
	for ($i;$i<$len;$i++) {
		$c = (string)$str[$i];
		if ($c == '(' && !$in_quotes) {
			$i++;
			$data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
			$elem++;
		} else if ($c == ')' && !$in_quotes) {
			return $data;
    		} else if ($c == '\\') {
			$i++;
			if ($in_quotes) {
				$data[$elem] .= $c.$str[$i];
        		}
		} else if ($c == '"') {
			$in_quotes = !$in_quotes;
			if (!$in_quotes) {
				$elem++;
        		}
		} else if ($in_quotes) {
			$data[$elem].=$c;
		}
	}
	return $data;
}

function iil_C_NameSpace(&$conn) {
	global $my_prefs;
	
	if (!iil_C_GetCapability($conn, 'NAMESPACE')) {
	    return false;
	}
    
	if ($my_prefs["rootdir"]) {
	    return true;
	}
    
	iil_PutLine($conn->fp, "ns1 NAMESPACE");
	do {
		$line = iil_ReadLine($conn->fp, 1024);
		if (iil_StartsWith($line, '* NAMESPACE')) {
			$i    = 0;
			$data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
		}
	} while (!iil_StartsWith($line, 'ns1', true));
	
	if (!is_array($data)) {
	    return false;
	}
    
	$user_space_data = $data[0];
	if (!is_array($user_space_data)) {
	    return false;
	}
    
	$first_userspace = $user_space_data[0];
	if (count($first_userspace)!=2) {
	    return false;
	}
    
	$conn->rootdir       = $first_userspace[0];
	$conn->delimiter     = $first_userspace[1];
	$my_prefs["rootdir"] = substr($conn->rootdir, 0, -1);
	
	return true;
}

function iil_Connect($host, $user, $password) {	
	global $iil_error, $iil_errornum;
	global $ICL_SSL, $ICL_PORT;
	global $IMAP_NO_CACHE;
	global $my_prefs, $IMAP_USE_INTERNAL_DATE;
	
	$iil_error = '';
	$iil_errornum = 0;
	
	//set auth method
	$auth_method = 'plain';
	if (func_num_args() >= 4) {
		$auth_array = func_get_arg(3);
		if (is_array($auth_array)) {
			$auth_method = $auth_array['imap'];
    		}
		if (empty($auth_method)) {
        		$auth_method = "plain";
    		}
	}
	$message = "INITIAL: $auth_method\n";
		
	$result = false;
	
	//initialize connection
	$conn              = new iilConnection;
	$conn->error       = '';
	$conn->errorNum    = 0;
	$conn->selected    = '';
	$conn->user        = $user;
	$conn->host        = $host;
	$conn->cache       = array();
	$conn->do_cache    = (function_exists("cache_write")&&!$IMAP_NO_CACHE);
	$conn->cache_dirty = array();
	
	if ($my_prefs['sort_field'] == 'INTERNALDATE') {
		$IMAP_USE_INTERNAL_DATE = true;
	} else if ($my_prefs['sort_field'] == 'DATE') {
    		$IMAP_USE_INTERNAL_DATE = false;
	}
	//echo '<!-- conn sort_field: '.$my_prefs['sort_field'].' //-->';
	
	//check input
	if (empty($host)) {
		$iil_error = "Empty host";
		$iil_errornum = -1;
		return false;
	}
	if (empty($user)) {
		$iil_error = "Empty user";
		$iil_errornum = -1;
		return false;
	}
	if (empty($password)) {
		$iil_error = "Empty password";
		$iil_errornum = -1;
		return false;
	}
	if (!$ICL_PORT) {
		$ICL_PORT = 143;
	}
    
	//check for SSL
	if ($ICL_SSL) {
		$host = $ICL_SSL . '://' . $host;
	}
	
	//open socket connection
	$conn->fp = fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
	if (!$conn->fp) {
    		$iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
    		$iil_errornum = -1;
		return false;
	}

	$iil_error .= "Socket connection established\r\n";
	$line       = iil_ReadLine($conn->fp, 4096);

	// RFC3501 [7.1] optional CAPABILITY response
	if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
		$conn->capability = explode(' ', strtoupper($matches[1]));
	}

	$conn->message .= $line;

	if (strcasecmp($auth_method, "check") == 0) {
		//check for supported auth methods
		if (iil_C_GetCapability($conn, 'AUTH=CRAM-MD5') || iil_C_GetCapability($conn, 'AUTH=CRAM_MD5')) {
			$auth_method = 'auth';
		}
		else {
			//default to plain text auth
			$auth_method = 'plain';
		}
	}

	if (strcasecmp($auth_method, 'auth') == 0) {
		$conn->message .= "Trying CRAM-MD5\n";

		//do CRAM-MD5 authentication
		iil_PutLine($conn->fp, "a000 AUTHENTICATE CRAM-MD5");
		$line = trim(iil_ReadLine($conn->fp, 1024));

		$conn->message .= "$line\n";

		if ($line[0] == '+') {
			$conn->message .= 'Got challenge: ' . htmlspecialchars($line) . "\n";

			//got a challenge string, try CRAM-5
			$result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
        		
			// stop if server sent BYE response
			if($result == -3) {
	            		$iil_error = $conn->error;
	            		$iil_errornum = $conn->errorNum;
				return false;
			}
			$conn->message .= "Tried CRAM-MD5: $result \n";
		} else {
			$conn->message .='No challenge ('.htmlspecialchars($line)."), try plain\n";
			$auth = 'plain';
		}
	}
		
	if ((!$result)||(strcasecmp($auth, "plain") == 0)) {
		//do plain text auth
		$result = iil_C_Login($conn, $user, $password);
		$conn->message .= "Tried PLAIN: $result \n";
	}
		
	$conn->message .= $auth;
			
	if (!is_int($result)) {
		iil_C_Namespace($conn);
		return $conn;
	} else {
		$iil_error = $conn->error;
		$iil_errornum = $conn->errorNum;
		return false;
	}
}

function iil_Close(&$conn) {
	iil_C_WriteCache($conn);
	if (iil_PutLine($conn->fp, "I LOGOUT")) {
		fgets($conn->fp, 1024);
		fclose($conn->fp);
		$conn->fp = false;
	}
}

function iil_ClearCache($user, $host) {
}

function iil_C_WriteCache(&$conn) {
	//echo "<!-- doing iil_C_WriteCache //-->\n";
	if (!$conn->do_cache) return false;
	
	if (is_array($conn->cache)) {
		while (list($folder,$data)=each($conn->cache)) {
			if ($folder && is_array($data) && $conn->cache_dirty[$folder]) {
				$key = $folder.".imap";
				$result = cache_write($conn->user, $conn->host, $key, $data, true);
				//echo "<!-- writing $key $data: $result //-->\n";
			}
		}
	}
}

function iil_C_EnableCache(&$conn) {
	$conn->do_cache = true;
}

function iil_C_DisableCache(&$conn) {
	$conn->do_cache = false;
}

function iil_C_LoadCache(&$conn, $folder) {
	if (!$conn->do_cache) {
	    return false;
	}
    
	$key = $folder.'.imap';
	if (!is_array($conn->cache[$folder])) {
		$conn->cache[$folder]       = cache_read($conn->user, $conn->host, $key);
		$conn->cache_dirty[$folder] = false;
	}
}

function iil_C_ExpireCachedItems(&$conn, $folder, $message_set) {
	
	if (!$conn->do_cache) {
		return;	//caching disabled
	}
	if (!is_array($conn->cache[$folder])) {
    		return;	//cache not initialized|empty
	}
	if (count($conn->cache[$folder]) == 0) {
    		return;	//cache not initialized|empty
	}
    
	$uids = iil_C_FetchHeaderIndex($conn, $folder, $message_set, 'UID');
	$num_removed = 0;
	if (is_array($uids)) {
		//echo "<!-- unsetting: ".implode(",",$uids)." //-->\n";
		while (list($n,$uid)=each($uids)) {
			unset($conn->cache[$folder][$uid]);
			//$conn->cache[$folder][$uid] = false;
			//$num_removed++;
		}
		$conn->cache_dirty[$folder] = true;

		//echo '<!--'."\n";
		//print_r($conn->cache);
		//echo "\n".'//-->'."\n";
	} else {
		echo "<!-- failed to get uids: $message_set //-->\n";
	}
	
	/*
	if ($num_removed>0) {
		$new_cache;
		reset($conn->cache[$folder]);
		while (list($uid,$item)=each($conn->cache[$folder])) {
			if ($item) $new_cache[$uid] = $conn->cache[$folder][$uid];
		}
		$conn->cache[$folder] = $new_cache;
	}
	*/
}

function iil_ExplodeQuotedString($delimiter, $string) {
	$quotes = explode('"', $string);
	while ( list($key, $val) = each($quotes)) {
		if (($key % 2) == 1) {
			$quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
    		}
	}
	$string = implode('"', $quotes);
	
	$result = explode($delimiter, $string);
	while ( list($key, $val) = each($result) ) {
		$result[$key] = str_replace('_!@!_', $delimiter, $result[$key]);
	}
    
	return $result;
}

function iil_CheckForRecent($host, $user, $password, $mailbox) {
	if (empty($mailbox)) {
		$mailbox = 'INBOX';
	}
    
	$conn = iil_Connect($host, $user, $password, 'plain');
	$fp   = $conn->fp;
	if ($fp) {
		iil_PutLine($fp, "a002 EXAMINE \"".iil_Escape($mailbox)."\"");
		do {
			$line=chop(iil_ReadLine($fp, 300));
			$a=explode(' ', $line);
			if (($a[0] == '*') && (strcasecmp($a[2], 'RECENT') == 0)) {
			    $result = (int) $a[1];
        		}
		} while (!iil_StartsWith($a[0], 'a002', true));

		iil_PutLine($fp, "a003 LOGOUT");
		fclose($fp);
	} else {
	    $result = -2;
	}
    
	return $result;
}

function iil_C_Select(&$conn, $mailbox) {

	if (empty($mailbox)) {
		return false;
	}
	if (strcmp($conn->selected, $mailbox) == 0) {
		return true;
	}
    
	iil_C_LoadCache($conn, $mailbox);
	
	if (iil_PutLine($conn->fp, "sel1 SELECT \"".iil_Escape($mailbox).'"')) {
		do {
			$line = chop(iil_ReadLine($conn->fp, 300));
			$a = explode(' ', $line);
			if (count($a) == 3) {
				if (strcasecmp($a[2], 'EXISTS') == 0) {
					$conn->exists = (int) $a[1];
				}
				if (strcasecmp($a[2], 'RECENT') == 0) {
					$conn->recent = (int) $a[1];
				}
			}
			else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
				$conn->permanentflags = explode(' ', $match[1]);
			}
		} while (!iil_StartsWith($line, 'sel1', true));

		$a = explode(' ', $line);

		if (strcasecmp($a[1], 'OK') == 0) {
			$conn->selected = $mailbox;
			return true;
		}
	}
	return false;
}

function iil_C_CheckForRecent(&$conn, $mailbox) {
	if (empty($mailbox)) {
		$mailbox = 'INBOX';
	}
    
	iil_C_Select($conn, $mailbox);
	if ($conn->selected == $mailbox) {
		return $conn->recent;
	}
	return false;
}

function iil_C_CountMessages(&$conn, $mailbox, $refresh = false) {
	if ($refresh) {
		$conn->selected = '';
	}
	
	iil_C_Select($conn, $mailbox);
	if ($conn->selected == $mailbox) {
		return $conn->exists;
	}
	return false;
}

function iil_SplitHeaderLine($string) {
	$pos=strpos($string, ':');
	if ($pos>0) {
		$res[0] = substr($string, 0, $pos);
		$res[1] = trim(substr($string, $pos+1));
		return $res;
	}
	return $string;
}

function iil_StrToTime($str) {
	$IMAP_MONTHS    = $GLOBALS['IMAP_MONTHS'];
	$IMAP_SERVER_TZ = $GLOBALS['IMAP_SERVER_TZ'];
		
	if ($str) {
    	    $time1 = strtotime($str);
	}
	if ($time1 && $time1 != -1) {
	    return $time1-$IMAP_SERVER_TZ;
	}
	//echo '<!--'.$str.'//-->';
	
	//replace double spaces with single space
	$str = trim($str);
	$str = str_replace('  ', ' ', $str);
	
	//strip off day of week
	$pos = strpos($str, ' ');
	if (!is_numeric(substr($str, 0, $pos))) {
	    $str = substr($str, $pos+1);
	}
	//explode, take good parts
	$a = explode(' ', $str);

	$month_str = $a[1];
	$month     = $IMAP_MONTHS[$month_str];
	$day       = (int)$a[0];
	$year      = (int)$a[2];
	$time      = $a[3];
	$tz_str    = $a[4];
	$tz        = substr($tz_str, 0, 3);
	$ta        = explode(':', $time);
	$hour      = (int)$ta[0]-(int)$tz;
	$minute    = (int)$ta[1];
	$second    = (int)$ta[2];
	
	//make UNIX timestamp
	$time2 = mktime($hour, $minute, $second, $month, $day, $year);
	//echo '<!--'.$time1.' '.$time2.' //-->'."\n";
	return $time2;
}

function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE,
    $encoding = 'US-ASCII') {

	$field = strtoupper($field);
	if ($field == 'INTERNALDATE') {
	    $field = 'ARRIVAL';
	}
	
	$fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
        'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
	
	if (!$fields[$field]) {
	    return false;
	}

	/*  Do "SELECT" command */
	if (!iil_C_Select($conn, $mailbox)) {
	    return false;
	}
    
	$is_uid = $is_uid ? 'UID ' : '';
	
	if (!empty($add)) {
	    $add = " $add";
	}

	$command  = 's ' . $is_uid . 'SORT (' . $field . ') ';
	$command .= $encoding . ' ALL' . $add;
	$line     = $data = '';
	
	if (!iil_PutLineC($conn->fp, $command)) {
	    return false;
	}
	do {
		$line = chop(iil_ReadLine($conn->fp, 1024));
		if (iil_StartsWith($line, '* SORT')) {
			$data .= ($data ? ' ' : '') . substr($line, 7);
    		} else if (preg_match('/^[0-9 ]+$/', $line)) {
			$data .= $line;
		}
	} while (!iil_StartsWith($line, 's ', true));
	
	$result_code = iil_ParseResult($line);
	
	if ($result_code != 0) {
                $conn->error = 'iil_C_Sort: ' . $line . "\n";
                return false;
	}
	
	$out = explode(' ',$data);
	return $out;
}

function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field,
    $normalize=true) {
	global $IMAP_USE_INTERNAL_DATE;
	
	$c=0;
	$result=array();
	$fp = $conn->fp;
		
	if (empty($index_field)) {
	    $index_field = 'DATE';
	}
	$index_field = strtoupper($index_field);
	
	list($from_idx, $to_idx) = explode(':', $message_set);
	if (empty($message_set) || (isset($to_idx)
    	    && (int)$from_idx > (int)$to_idx)) {
		return false;
	}
	
	//$fields_a['DATE'] = ($IMAP_USE_INTERNAL_DATE?6:1);
	$fields_a['DATE']         = 1;
	$fields_a['INTERNALDATE'] = 6;
	$fields_a['FROM']         = 1;
	$fields_a['REPLY-TO']     = 1;
	$fields_a['SENDER']       = 1;
	$fields_a['TO']           = 1;
	$fields_a['SUBJECT']      = 1;
	$fields_a['UID']          = 2;
	$fields_a['SIZE']         = 2;
	$fields_a['SEEN']         = 3;
	$fields_a['RECENT']       = 4;
	$fields_a['DELETED']      = 5;
	
	$mode=$fields_a[$index_field];
	if (!($mode > 0)) {
	    return false;
	}
    
	/*  Do "SELECT" command */
	if (!iil_C_Select($conn, $mailbox)) {
	    return false;
	}
    
	/* FETCH date,from,subject headers */
	if ($mode == 1) {
		$key     = 'fhi' . ($c++);
		$request = $key . " FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)])";
		if (!iil_PutLine($fp, $request)) {
		    return false;
    		}
		do {
			
			$line=chop(iil_ReadLine($fp, 200));
			$a=explode(' ', $line);
			if (($line[0] == '*') && ($a[2] == 'FETCH')
            		    && ($line[strlen($line)-1] != ')')) {
				$id=$a[1];

				$str=$line=chop(iil_ReadLine($fp, 300));

				while ($line[0] != ')') {					//caution, this line works only in this particular case
					$line=chop(iil_ReadLine($fp, 300));
					if ($line[0] != ')') {
						if (ord($line[0]) <= 32) {			//continuation from previous header line
							$str.= ' ' . trim($line);
						}
						if ((ord($line[0]) > 32) || (strlen($line[0]) == 0)) {
							list($field, $string) = iil_SplitHeaderLine($str);
							if (strcasecmp($field, 'date') == 0) {
								$result[$id] = iil_StrToTime($string);
							} else {
								$result[$id] = str_replace('"', '', $string);
								if ($normalize) {
								    $result[$id] = strtoupper($result[$id]);
                            					}
							}
							$str=$line;
						}
					}
				}
			}
			/*
			$end_pos = strlen($line)-1;
			if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[$end_pos]=="}")) {
				$id = $a[1];
				$pos = strrpos($line, "{")+1;
				$bytes = (int)substr($line, $pos, $end_pos-$pos);
				$received = 0;
				do {
					$line      = iil_ReadLine($fp, 0);
					$received += strlen($line);
					$line      = chop($line);
					
					if ($received>$bytes) {
                    				break;
					} else if (!$line) {
                    				continue;
					}

					list($field, $string) = explode(': ', $line);
					
					if (strcasecmp($field, 'date') == 0) {
						$result[$id] = iil_StrToTime($string);
					} else if ($index_field != 'DATE') {
						$result[$id]=strtoupper(str_replace('"', '', $string));
                			}
				} while ($line[0] != ')');
			} else {
				//one line response, not expected so ignore				
			}
			*/
		} while (!iil_StartsWith($line, $key, true));

	}else if ($mode == 6) {

		$key     = 'fhi' . ($c++);
		$request = $key . " FETCH $message_set (INTERNALDATE)";
		if (!iil_PutLine($fp, $request)) {
		    return false;
    		}
		do {
			$line=chop(iil_ReadLine($fp, 200));
			if ($line[0] == '*') {
				/*
				 * original:
				 * "* 10 FETCH (INTERNALDATE "31-Jul-2002 09:18:02 -0500")"
				 */
				$paren_pos = strpos($line, '(');
				$foo       = substr($line, 0, $paren_pos);
				$a         = explode(' ', $foo);
				$id        = $a[1];
				
				$open_pos  = strpos($line, '"') + 1;
				$close_pos = strrpos($line, '"');
				if ($open_pos && $close_pos) {
					$len         = $close_pos - $open_pos;
					$time_str    = substr($line, $open_pos, $len);
					$result[$id] = strtotime($time_str);
				}
			} else {
				$a = explode(' ', $line);
			}
		} while (!iil_StartsWith($a[0], $key, true));
	} else {
		if ($mode >= 3) {
		    $field_name = 'FLAGS';
		} else if ($index_field == 'SIZE') {
		    $field_name = 'RFC822.SIZE';
		} else {
		    $field_name = $index_field;
    		}
        
		/* 			FETCH uid, size, flags		*/
		$key     = 'fhi' .($c++);
		$request = $key . " FETCH $message_set ($field_name)";

		if (!iil_PutLine($fp, $request)) {
		    return false;
    		}
		do {
			$line=chop(iil_ReadLine($fp, 200));
			$a = explode(' ', $line);
			if (($line[0] == '*') && ($a[2] == 'FETCH')) {
				$line = str_replace('(', '', $line);
				$line = str_replace(')', '', $line);
				$a    = explode(' ', $line);
				
				$id = $a[1];

				if (isset($result[$id])) {
				    continue; //if we already got the data, skip forward
				}
            			if ($a[3]!=$field_name) {
                			continue;  //make sure it's returning what we requested
				}
                
				/*  Caution, bad assumptions, next several lines */
				if ($mode == 2) {
				    $result[$id] = $a[4];
				} else {
					$haystack    = strtoupper($line);
					$result[$id] = (strpos($haystack, $index_field) > 0 ? "F" : "N");
				}
			}
		} while (!iil_StartsWith($line, $key, true));
	}

	//check number of elements...
	list($start_mid, $end_mid) = explode(':', $message_set);
	if (is_numeric($start_mid) && is_numeric($end_mid)) {
		//count how many we should have
		$should_have = $end_mid - $start_mid +1;
		
		//if we have less, try and fill in the "gaps"
		if (count($result) < $should_have) {
			for ($i=$start_mid; $i<=$end_mid; $i++) {
				if (!isset($result[$i])) {
			    		$result[$i] = '';
            			}
        		}
		}
	}
	return $result;	
}

function iil_CompressMessageSet($message_set) {
	//given a comma delimited list of independent mid's, 
	//compresses by grouping sequences together
	
	//if less than 255 bytes long, let's not bother
	if (strlen($message_set)<255) {
	    return $message_set;
	}
    
	//see if it's already been compress
	if (strpos($message_set, ':') !== false) {
	    return $message_set;
	}
    
	//separate, then sort
	$ids = explode(',', $message_set);
	sort($ids);
	
	$result = array();
	$start  = $prev = $ids[0];

	foreach ($ids as $id) {
		$incr = $id - $prev;
		if ($incr > 1) {			//found a gap
			if ($start == $prev) {
			    $result[] = $prev;	//push single id
			} else {
			    $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
			}
        		$start = $id;			//start of new sequence
		}
		$prev = $id;
	}

	//handle the last sequence/id
	if ($start==$prev) {
	    $result[] = $prev;
	} else {
    	    $result[] = $start.':'.$prev;
	}
    
	//return as comma separated string
	return implode(',', $result);
}

function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids) {
	if (!is_array($uids) || count($uids) == 0) {
	    return array();
	}
	return iil_C_Search($conn, $mailbox, 'UID ' . implode(',', $uids));
}

function iil_C_UIDToMID(&$conn, $mailbox, $uid) {
	$result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
	if (count($result) == 1) {
	    return $result[0];
	}
        return false;
}

function iil_C_FetchUIDs(&$conn,$mailbox) {
	global $clock;
	
	$num = iil_C_CountMessages($conn, $mailbox);
	if ($num == 0) {
	    return array();
	}
	$message_set = '1' . ($num>1?':' . $num:'');
	
	//if cache not enabled, just call iil_C_FetchHeaderIndex on 'UID' field
	if (!$conn->do_cache)
		return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');

	//otherwise, let's check cache first
	$key        = $mailbox.'.uids';
	$cache_good = true;
	if ($conn->uid_cache) {
	    $data = $conn->uid_cache;
	} else {
	    $data = cache_read($conn->user, $conn->host, $key);
	}
    
	//was anything cached at all?
	if ($data === false) {
	    $cache_good = -1;
	}
    
	//make sure number of messages were the same
	if ($cache_good > 0 && $data['n'] != $num) {
	    $cache_good = -2;
	}
    
	//if everything's okay so far...
	if ($cache_good > 0) {
		//check UIDs of highest mid with current and cached
		$temp = iil_C_Search($conn, $mailbox, 'UID ' . $data['d'][$num]);
		if (!$temp || !is_array($temp) || $temp[0] != $num) {
		    $cache_good = -3;
    		}
	}

	//if cached data's good, return it
	if ($cache_good > 0) {
		return $data['d'];
	}

	//otherwise, we need to fetch it
	$data      = array('n' => $num, 'd' => array());
	$data['d'] = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
    
	cache_write($conn->user, $conn->host, $key, $data);
	$conn->uid_cache = $data;
	return $data['d'];
}

function iil_SortThreadHeaders($headers, $index_a, $uids) {
	asort($index_a);
	$result = array();
	foreach ($index_a as $mid=>$foobar) {
		$uid = $uids[$mid];
		$result[$uid] = $headers[$uid];
	}
	return $result;
}

function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set) {
	global $clock;
	global $index_a;
	
	list($from_idx, $to_idx) = explode(':', $message_set);
	if (empty($message_set) || (isset($to_idx)
        && (int)$from_idx > (int)$to_idx)) {
		return false;
	}

	$result = array();
	$uids   = iil_C_FetchUIDs($conn, $mailbox);
	$debug  = false;
	
	/* Get cached records where possible */
	if ($conn->do_cache) {
		$cached = cache_read($conn->user, $conn->host, $mailbox.'.thhd');
		if ($cached && is_array($uids) && count($uids)>0) {
			$needed_set = '';
			foreach ($uids as $id=>$uid) {
				if ($cached[$uid]) {
					$result[$uid]     = $cached[$uid];
					$result[$uid]->id = $id;
				} else {
				    $needed_set .= ($needed_set ? ',' : '') . $id;
            			}
			}
			if ($needed_set) {
			    $message_set = $needed_set;
			} else {
			    $message_set = '';
        		}
		}
	}
	$message_set = iil_CompressMessageSet($message_set);
	if ($debug) {
	    echo "Still need: ".$message_set;
	}
    
	/* if we're missing any, get them */
	if ($message_set) {
		/* FETCH date,from,subject headers */
		$key        = 'fh';
		$fp         = $conn->fp;
		$request    = $key . " FETCH $message_set ";
    		$request   .= "(BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])";
		$mid_to_id  = array();
		if (!iil_PutLine($fp, $request)) {
		    return false;
    		}
		do {
			$line = chop(iil_ReadLine($fp, 1024));
			if ($debug) {
			    echo $line . "\n";
        		}
			if (ereg('\{[0-9]+\}$', $line)) {
				$a 	 = explode(' ', $line);
				$new = array();

				$new_thhd = new iilThreadHeader;
				$new_thhd->id = $a[1];
				do {
					$line = chop(iil_ReadLine($fp, 1024), "\r\n");
					if (iil_StartsWithI($line, 'Message-ID:')
                    				|| (iil_StartsWithI($line,'In-Reply-To:'))
                    				|| (iil_StartsWithI($line,'SUBJECT:'))) {

						$pos        = strpos($line, ':');
						$field_name = substr($line, 0, $pos);
						$field_val  = substr($line, $pos+1);

						$new[strtoupper($field_name)] = trim($field_val);

					} else if (ereg('^[[:space:]]', $line)) {
						$new[strtoupper($field_name)] .= trim($line);
					}
				} while ($line[0] != ')');
                
				$new_thhd->sbj = $new['SUBJECT'];
				$new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
				$new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
				
				$result[$uids[$new_thhd->id]] = $new_thhd;
			}
		} while (!iil_StartsWith($line, 'fh'));
	}
	
	/* sort headers */
	if (is_array($index_a)) {
		$result = iil_SortThreadHeaders($result, $index_a, $uids);	
	}
	
	/* write new set to cache */
	if ($conn->do_cache) {
		if (count($result)!=count($cached)) {
			cache_write($conn->user, $conn->host, $mailbox . '.thhd', $result);
    		}
	}
	
	//echo 'iil_FetchThreadHeaders:'."\n";
	//print_r($result);
	
	return $result;
}

function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock) {
	global $index_a;

	list($from_idx, $to_idx) = explode(':', $message_set);
	if (empty($message_set) || (isset($to_idx)
    		&& (int)$from_idx > (int)$to_idx)) {
		return false;
	}
    
	$result    = array();
	$roots     = array();
	$root_mids = array();
	$sub_mids  = array();
	$strays    = array();
	$messages  = array();
	$fp        = $conn->fp;
	$debug     = false;
	
	$sbj_filter_pat = '[a-zA-Z]{2,3}(\[[0-9]*\])?:([[:space:]]*)';
	
	/*  Do "SELECT" command */
	if (!iil_C_Select($conn, $mailbox)) {
	    return false;
	}
    
	/* FETCH date,from,subject headers */
	$mid_to_id = array();
	$messages  = array();
	$headers   = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
	if ($clock) {
	    $clock->register('fetched headers');
	}
    
	if ($debug) {
	    print_r($headers);
	}
    
	/* go through header records */
	foreach ($headers as $header) {
		//$id = $header['i'];
		//$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'], 
		//			'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
		$id  = $header->id;
		$new = array('id' => $id, 'MESSAGE-ID' => $header->mid, 
        		'IN-REPLY-TO' => $header->irt, 'SUBJECT' => $header->sbj);

		/* add to message-id -> mid lookup table */
		$mid_to_id[$new['MESSAGE-ID']] = $id;
		
		/* if no subject, use message-id */
		if (empty($new['SUBJECT'])) {
		    $new['SUBJECT'] = $new['MESSAGE-ID'];
		}
        
		/* if subject contains 'RE:' or has in-reply-to header, it's a reply */
		$sbj_pre ='';
		$has_re = false;
		if (eregi($sbj_filter_pat, $new['SUBJECT'])) {
		    $has_re = true;
		}
    		if ($has_re||$new['IN-REPLY-TO']) {
        	    $sbj_pre = 'RE:';
		}
        
		/* strip out 're:', 'fw:' etc */
		if ($has_re) {
		    $sbj = ereg_replace($sbj_filter_pat, '', $new['SUBJECT']);
		} else {
		    $sbj = $new['SUBJECT'];
		}
    		$new['SUBJECT'] = $sbj_pre.$sbj;
		
		
		/* if subject not a known thread-root, add to list */
		if ($debug) {
		    echo $id . ' ' . $new['SUBJECT'] . "\t" . $new['MESSAGE-ID'] . "\n";
		}
    		$root_id = $roots[$sbj];
		
		if ($root_id && ($has_re || !$root_in_root[$root_id])) {
			if ($debug) {
			    echo "\tfound root: $root_id\n";
			}
        		$sub_mids[$new['MESSAGE-ID']] = $root_id;
			$result[$root_id][]           = $id;
		} else if (!isset($roots[$sbj]) || (!$has_re && $root_in_root[$root_id])) {
			/* try to use In-Reply-To header to find root 
				unless subject contains 'Re:' */
			if ($has_re&&$new['IN-REPLY-TO']) {
				if ($debug) {
				    echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
				}
				//reply to known message?
				$temp = $sub_mids[$new['IN-REPLY-TO']];
				
				if ($temp) {
					//found it, root:=parent's root
					if ($debug) {
					    echo "\tfound parent: ".$new['SUBJECT']."\n";
					}
                			$result[$temp][]              = $id;
					$sub_mids[$new['MESSAGE-ID']] = $temp;
					$sbj                          = '';
				} else {
					//if we can't find referenced parent, it's a "stray"
					$strays[$id] = $new['IN-REPLY-TO'];
				}
			}
			
			//add subject as root
			if ($sbj) {
				if ($debug) {
				    echo "\t added to root\n";
				}
            			$roots[$sbj]                  = $id;
				$root_in_root[$id]            = !$has_re;
				$sub_mids[$new['MESSAGE-ID']] = $id;
				$result[$id]                  = array($id);
			}
			if ($debug) {
			    echo $new['MESSAGE-ID'] . "\t" . $sbj . "\n";
        		}
		}
	}
	
	//now that we've gone through all the messages,
	//go back and try and link up the stray threads
	if (count($strays) > 0) {
		foreach ($strays as $id=>$irt) {
			$root_id = $sub_mids[$irt];
			if (!$root_id || $root_id==$id) {
			    continue;
			}
        		$result[$root_id] = array_merge($result[$root_id],$result[$id]);
			unset($result[$id]);
		}
	}
	
	if ($clock) {
	    $clock->register('data prepped');
	}
    
	if ($debug) {
	    print_r($roots);
	}

	return $result;
}

function iil_SortThreads(&$tree, $index, $sort_order = 'ASC') {
	if (!is_array($tree) || !is_array($index)) {
	    return false;
	}
    
	//create an id to position lookup table
	$i = 0;
	foreach ($index as $id=>$val) {
		$i++;
		$index[$id] = $i;
	}
	$max = $i+1;
	
	//for each tree, set array key to position
	$itree = array();
	foreach ($tree as $id=>$node) {
		if (count($tree[$id])<=1) {
			//for "threads" with only one message, key is position of that message
			$n         = $index[$id];
			$itree[$n] = array($n=>$id);
		} else {
			//for "threads" with multiple messages, 
			$min   = $max;
			$new_a = array();
			foreach ($tree[$id] as $mid) {
				$new_a[$index[$mid]] = $mid;		//create new sub-array mapping position to id
				$pos                 = $index[$mid];
				if ($pos&&$pos<$min) {
				    $min = $index[$mid];	//find smallest position
				}
			}
			$n = $min;	//smallest position of child is thread position
			
			//assign smallest position to root level key
			//set children array to one created above
			ksort($new_a);
			$itree[$n] = $new_a;
		}
	}
	
	//sort by key, this basically sorts all threads
	ksort($itree);
	$i   = 0;
	$out = array();
	foreach ($itree as $k=>$node) {
		$out[$i] = $itree[$k];
		$i++;
	}
	
	return $out;
}

function iil_IndexThreads(&$tree) {
	/* creates array mapping mid to thread id */
	
	if (!is_array($tree)) {
	    return false;
	}
    
	$t_index = array();
	foreach ($tree as $pos=>$kids) {
		foreach ($kids as $kid) $t_index[$kid] = $pos;
	}
	
	return $t_index;
}

function iil_C_FetchHeaders(&$conn, $mailbox, $message_set, $uidfetch=false)
{
	global $IMAP_USE_INTERNAL_DATE;
	
	$c      = 0;
	$result = array();
	$fp     = $conn->fp;
	
	list($from_idx, $to_idx) = explode(':', $message_set);
	if (empty($message_set) || (isset($to_idx)
		&& (int)$from_idx > (int)$to_idx)) {
		return false;
	}
		
	/*  Do "SELECT" command */
	if (!iil_C_Select($conn, $mailbox)) {
		$conn->error = "Couldn't select $mailbox";
		return false;
	}
		
	/* Get cached records where possible */
	if ($conn->do_cache) {
		$uids = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, "UID");
		if (is_array($uids) && count($conn->cache[$mailbox]>0)) {
			$needed_set = '';
			while (list($id,$uid)=each($uids)) {
				if ($conn->cache[$mailbox][$uid]) {
					$result[$id]     = $conn->cache[$mailbox][$uid];
					$result[$id]->id = $id;
				} else {
				    $needed_set.=($needed_set ? ',': '') . $id;
				}
			}
			//echo "<!-- iil_C_FetchHeader\nMessage Set: $message_set\nNeeded Set:$needed_set\n//-->\n";
			if ($needed_set) {
				$message_set = iil_CompressMessageSet($needed_set);
			} else {
				return $result;
			}
		}
	}

	/* FETCH date,from,subject headers */
	$key	  = 'fh' . ($c++);
	$prefix	  = $uidfetch?' UID':'';
	$request  = $key . $prefix;
	$request .= " FETCH $message_set (BODY.PEEK[HEADER.FIELDS ";
	$request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
	$request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
	$request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY)])";

	if (!iil_PutLine($fp, $request)) {
		return false;
	}
	do {
		$line = chop(iil_ReadLine($fp, 200));
		$a    = explode(' ', $line);
		if (($line[0] == '*') && ($a[2] == 'FETCH')) {
			$id = $a[1];
            
			$result[$id]            = new iilBasicHeader;
			$result[$id]->id        = $id;
			$result[$id]->subject   = '';
			$result[$id]->messageID = 'mid:' . $id;

			/*
				Start parsing headers.  The problem is, some header "lines" take up multiple lines.
				So, we'll read ahead, and if the one we're reading now is a valid header, we'll
				process the previous line.  Otherwise, we'll keep adding the strings until we come
				to the next valid header line.
			*/
			$i     = 0;
			$lines = array();
			do {
				$line = chop(iil_ReadLine($fp, 300), "\r\n");
				if (ord($line[0])<=32) {
				    $lines[$i] .= (empty($lines[$i])?'':"\n").trim($line);
				} else {
					$i++;
					$lines[$i] = trim($line);
				}
				/* 
					The preg_match below works around communigate imap, which outputs " UID <number>)".
					Without this, the while statement continues on and gets the "fh0 OK completed" message.
					If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.  
					This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
					If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
					An alternative might be:
					if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
					however, unsure how well this would work with all imap clients.
				*/
				if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
				    break;
				}
			// patch from "Maksim Rubis" <siburny@hotmail.com>
			} while (trim($line[0]) != ')' && strncmp($line, $key, strlen($key)));
			
			if (strncmp($line, $key, strlen($key))) { 
				//process header, fill iilBasicHeader obj.
				//	initialize
				if (is_array($headers)) {
					reset($headers);
					while (list($k, $bar) = each($headers)) {
						$headers[$k] = '';
					}
				}
	
				//	create array with header field:data
				while ( list($lines_key, $str) = each($lines) ) {
					list($field, $string) = iil_SplitHeaderLine($str);
					
					$field  = strtolower($field);
                                        $string = ereg_replace("\n[[:space:]]*"," ",$string); 
					
					switch ($field) {
					case 'date';
						$result[$id]->date = $string;
						$result[$id]->timestamp = iil_StrToTime($string);
						break;
					case 'from':
						$result[$id]->from = $string;
						break;
					case 'to':
						$result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
						break;
					case 'subject':
						$result[$id]->subject = $string;
						break;
					case 'reply-to':
						$result[$id]->replyto = $string;
						break;
					case 'cc':
						$result[$id]->cc = $string;
						break;
					case 'bcc':
						$result[$id]->bcc = $string;
						break;
					case 'content-transfer-encoding':
						$result[$id]->encoding = $string;
						break;
					case 'content-type':
						$ctype_parts = explode(";", $string);
						$result[$id]->ctype = array_shift($ctype_parts);
						foreach ($ctype_parts as $ctype_add) {
							if (preg_match('/charset="?([a-z0-9\-\.\_]+)"?/i',
								$ctype_add, $regs)) {
								$result[$id]->charset = $regs[1];
							}
						}
						break;
					case 'in-reply-to':
						$result[$id]->in_reply_to = ereg_replace("[\n<>]", '', $string);
						break;
					case 'references':
						$result[$id]->references = $string;
						break;
					case 'return-receipt-to':
					case 'disposition-notification-to':
					case 'x-confirm-reading-to':
						$result[$id]->mdn_to = $string;
						break;
					case 'message-id':
						$result[$id]->messageID = $string;
						break;
					case 'x-priority':
						if (preg_match('/^(\d+)/', $string, $matches))
							$result[$id]->priority = intval($matches[1]);
						break;
					} // end switch ()
				} // end while ()
			} else {
				$a = explode(' ', $line);
			}
		}
	} while (strcmp($a[0], $key) != 0);

	/* 
		FETCH uid, size, flags
		Sample reply line: "* 3 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen \Deleted))"
	*/
	$command_key = 'fh' . ($c++);
	$request     = $command_key . $prefix;
	$request    .= " FETCH $message_set (UID RFC822.SIZE FLAGS INTERNALDATE)";
	
	if (!iil_PutLine($fp, $request)) {
	    return false;
	}
	do {
		$line = chop(iil_ReadLine($fp, 200));
		//$a = explode(' ', $line);
		//if (($line[0]=="*") && ($a[2]=="FETCH")) {
		if ($line[0] == '*') {
			//echo "<!-- $line //-->\n";
			//get outter most parens
			$open_pos = strpos($line, "(") + 1;
			$close_pos = strrpos($line, ")");
			if ($open_pos && $close_pos) {
				//extract ID from pre-paren
				$pre_str = substr($line, 0, $open_pos);
				$pre_a = explode(' ', $line);
				$id = $pre_a[1];
				
				//get data
				$len = $close_pos - $open_pos;
				$str = substr($line, $open_pos, $len);
				
				//swap parents with quotes, then explode
				$str = eregi_replace("[()]", "\"", $str);
				$a = iil_ExplodeQuotedString(' ', $str);
				
				//did we get the right number of replies?
				$parts_count = count($a);
				if ($parts_count>=8) {
					for ($i=0;$i<$parts_count;$i=$i+2) {
						if (strcasecmp($a[$i],"UID") == 0) $result[$id]->uid=$a[$i+1];
						else if (strcasecmp($a[$i],"RFC822.SIZE") == 0) $result[$id]->size=$a[$i+1];
						else if (strcasecmp($a[$i],"INTERNALDATE") == 0) $time_str = $a[$i+1];
						else if (strcasecmp($a[$i],"FLAGS") == 0) $flags_str = $a[$i+1];
					}

					// process flags
					$flags_str = eregi_replace('[\\\"]', '', $flags_str);
					$flags_a   = explode(' ', $flags_str);
					
					if (is_array($flags_a)) {
						reset($flags_a);
						while (list($key,$val)=each($flags_a)) {
							if (strcasecmp($val,'Seen') == 0) {
							    $result[$id]->seen = true;
							} else if (strcasecmp($val, 'Deleted') == 0) {
							    $result[$id]->deleted=true;
							} else if (strcasecmp($val, 'Recent') == 0) {
							    $result[$id]->recent = true;
							} else if (strcasecmp($val, 'Answered') == 0) {
							    $result[$id]->answered = true;
							} else if (strcasecmp($val, '$Forwarded') == 0) {
							    $result[$id]->forwarded = true;
							} else if (strcasecmp($val, 'Draft') == 0) {
							    $result[$id]->is_draft = true;
							} else if (strcasecmp($val, '$MDNSent') == 0) {
							    $result[$id]->mdn_sent = true;
							} else if (strcasecmp($val, 'Flagged') == 0) {
							     $result[$id]->flagged = true;
							}
						}
						$result[$id]->flags = $flags_a;
					}
			
					// if time is gmt...	
					$time_str = str_replace('GMT','+0000',$time_str);
					
					//get timezone
					$time_str      = substr($time_str, 0, -1);
					$time_zone_str = substr($time_str, -5); //extract timezone
					$time_str      = substr($time_str, 1, -6); //remove quotes
					$time_zone     = (float)substr($time_zone_str, 1, 2); //get first two digits
					if ($time_zone_str[3] != '0') {
					    $time_zone += 0.5;  //handle half hour offset
					}
					if ($time_zone_str[0] == '-') {
						$time_zone = $time_zone * -1.0; //minus?
					}
					$result[$id]->internaldate = $time_str;
					
					if ($IMAP_USE_INTERNAL_DATE || empty($result[$id]->date)) {
						//calculate timestamp
						$timestamp     = strtotime($time_str); //return's server's time
						$na_timestamp  = $timestamp;
						$timestamp    -= $time_zone * 3600; //compensate for tz, get GMT
						
						$result[$id]->timestamp = $timestamp;
						$result[$id]->date = $time_str;
					}
						
					if ($conn->do_cache) {
						$uid = $result[$id]->uid;
						$conn->cache[$mailbox][$uid] = $result[$id];
						$conn->cache_dirty[$mailbox] = true;
					}
					//echo "<!-- ID: $id : $time_str -- local: $na_timestamp (".date("F j, Y, g:i a", $na_timestamp).") tz: $time_zone -- GMT: ".$timestamp." (".date("F j, Y, g:i a", $timestamp).")  //-->\n";
				} else {
					//echo "<!-- ERROR: $id : $str //-->\n";
				}
			}
		}
	} while (strpos($line, $command_key) === false);
		
	return $result;
}

function iil_C_FetchHeader(&$conn, $mailbox, $id, $uidfetch=false) {
	$fp = $conn->fp;
	$a  = iil_C_FetchHeaders($conn, $mailbox, $id, $uidfetch);
	if (is_array($a)) {
		return array_shift($a);
	}
	return false;
}

function iil_SortHeaders($a, $field, $flag) {
	if (empty($field)) {
	    $field = 'uid';
	}
	$field = strtolower($field);
	if ($field == 'date' || $field == 'internaldate') {
	    $field = 'timestamp';
	}
	if (empty($flag)) {
	    $flag = 'ASC';
	}
    
	$flag     = strtoupper($flag);
	$stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');

	$c=count($a);
	if ($c > 0) {
		/*
			Strategy:
			First, we'll create an "index" array.
			Then, we'll use sort() on that array, 
			and use that to sort the main array.
		*/
                
		// create "index" array
		$index = array();
		reset($a);
		while (list($key, $val)=each($a)) {

			if ($field == 'timestamp') {
				$data = @strtotime($val->date);
				if ($data == false) {
					$data = $val->timestamp;
            			}
			} else {
				$data = $val->$field;
				if (is_string($data)) {
					$data=strtoupper(str_replace($stripArr, '', $data));
            			}
			}
			$index[$key]=$data;
		}
		
		// sort index
		$i = 0;
		if ($flag == 'ASC') {
			asort($index);
    		} else {
        		arsort($index);
		}
        
		// form new array based on index 
		$result = array();
		reset($index);
		while (list($key, $val)=each($index)) {
			$result[$key]=$a[$key];
			$i++;
		}
	}
	
	return $result;
}

function iil_C_Expunge(&$conn, $mailbox) {

	if (iil_C_Select($conn, $mailbox)) {
		$c = 0;
		iil_PutLine($conn->fp, "exp1 EXPUNGE");
		do {
			$line=chop(iil_ReadLine($conn->fp, 100));
			if ($line[0] == '*') {
            			$c++;
        		}
		} while (!iil_StartsWith($line, 'exp1', true));
		
		if (iil_ParseResult($line) == 0) {
			$conn->selected = ''; //state has changed, need to reselect			
			//$conn->exists-=$c;
			return $c;
		}
		$conn->error = $line;
	}
	
	return -1;
}

function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod) {
	if ($mod != '+' && $mod != '-') {
	    return -1;
	}
    
	$fp    = $conn->fp;
	$flags = $GLOBALS['IMAP_FLAGS'];
        
	$flag = strtoupper($flag);
	$flag = $flags[$flag];
    
	if (iil_C_Select($conn, $mailbox)) {
		$c = 0;
		iil_PutLine($fp, "flg STORE $messages " . $mod . "FLAGS (" . $flag . ")");
		do {
			$line=chop(iil_ReadLine($fp, 100));
			if ($line[0] == '*') {
			    $c++;
        		}
		} while (!iil_StartsWith($line, 'flg', true));

		if (iil_ParseResult($line) == 0) {
			iil_C_ExpireCachedItems($conn, $mailbox, $messages);
			return $c;
		}
		$conn->error = $line;
		return -1;
	}
	$conn->error = 'Select failed';
	return -1;
}

function iil_C_Flag(&$conn, $mailbox, $messages, $flag) {
	return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '+');
}

function iil_C_Unflag(&$conn, $mailbox, $messages, $flag) {
	return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '-');
}

function iil_C_Delete(&$conn, $mailbox, $messages) {
	return iil_C_ModFlag($conn, $mailbox, $messages, 'DELETED', '+');
}

function iil_C_Undelete(&$conn, $mailbox, $messages) {
	return iil_C_ModFlag($conn, $mailbox, $messages, 'DELETED', '-');
}

function iil_C_Unseen(&$conn, $mailbox, $messages) {
	return iil_C_ModFlag($conn, $mailbox, $messages, 'SEEN', '-');
}

function iil_C_Copy(&$conn, $messages, $from, $to) {
	$fp = $conn->fp;

	if (empty($from) || empty($to)) {
	    return -1;
	}
    
	if (iil_C_Select($conn, $from)) {
		$c=0;
		
		iil_PutLine($fp, "cpy1 COPY $messages \"".iil_Escape($to)."\"");
		$line=iil_ReadReply($fp);
		return iil_ParseResult($line);
	} else {
		return -1;
	}
}

function iil_FormatSearchDate($month, $day, $year) {
	$month  = (int) $month;
	$months = $GLOBALS['IMAP_MONTHS'];
	return $day . '-' . $months[$month] . '-' . $year;
}

function iil_C_CountUnseen(&$conn, $folder) {
	$index = iil_C_Search($conn, $folder, 'ALL UNSEEN');
	if (is_array($index)) {
		if (($cnt = count($index)) && $index[0] != '') {
			return $cnt;
		}
	}
	return false;
}

function iil_C_UID2ID(&$conn, $folder, $uid) {
	if ($uid > 0) {
		$id_a = iil_C_Search($conn, $folder, "UID $uid");
		if (is_array($id_a) && count($id_a) == 1) {
			return $id_a[0];
		}
	}
	return false;
}

function iil_C_ID2UID(&$conn, $folder, $id) {
	$fp = $conn->fp;
	if ($id == 0) {
	    return 	-1;
	}
	$result = -1;
	if (iil_C_Select($conn, $folder)) {
		$key = 'FUID';
		if (iil_PutLine($fp, "$key FETCH $id (UID)")) {
			do {
				$line=chop(iil_ReadLine($fp, 1024));
				if (eregi("^\* $id FETCH \(UID (.*)\)", $line, $r)) {
					$result = $r[1];
				}
			} while (!preg_match("/^$key/", $line));
		}
	}
	return $result;
}

function iil_C_Search(&$conn, $folder, $criteria) {
	$fp = $conn->fp;
	if (iil_C_Select($conn, $folder)) {
		$c = 0;
		
		$query = 'srch1 SEARCH ' . chop($criteria);
		iil_PutLineC($fp, $query);
		do {
			$line=trim(iil_ReadLine($fp, 10000));
			if (eregi("^\* SEARCH", $line)) {
				$str = trim(substr($line, 8));
				$messages = explode(' ', $str);
			}
		} while (!iil_StartsWith($line, 'srch1', true));

		$result_code = iil_ParseResult($line);
		if ($result_code == 0) {
		    return $messages;
		}
		$conn->error = 'iil_C_Search: ' . $line . "\n";
		return false;	
	}
	$conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
	return false;
}

function iil_C_Move(&$conn, $messages, $from, $to) {
    $fp = $conn->fp;

    if (!$from || !$to) {
        return -1;
    }
    $r = iil_C_Copy($conn, $messages, $from,$to);
    if ($r==0) {
        return iil_C_Delete($conn, $from, $messages);
    }
    return $r;
}

/**
 * Gets the delimiter, for example:
 * INBOX.foo -> .
 * INBOX/foo -> /
 * INBOX\foo -> \
 * 
 * @return mixed A delimiter (string), or false. 
 * @param object $conn The current connection.
 * @see iil_Connect()
 */
function iil_C_GetHierarchyDelimiter(&$conn) {
	if ($conn->delimiter) {
        return $conn->delimiter;
	}
    
	$fp        = $conn->fp;
	$delimiter = false;
	
	//try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
	if (!iil_PutLine($fp, 'ghd LIST "" ""')) {
	    return false;
	}
    
	do {
		$line=iil_ReadLine($fp, 500);
		if ($line[0] == '*') {
			$line = rtrim($line);
			$a=iil_ExplodeQuotedString(' ', $line);
			if ($a[0] == '*') {
			    $delimiter = str_replace('"', '', $a[count($a)-2]);
        		}
		}
	} while (!iil_StartsWith($line, 'ghd', true));

	if (strlen($delimiter)>0) {
	    return $delimiter;
	}
    
	//if that fails, try namespace extension
	//try to fetch namespace data
	iil_PutLine($conn->fp, "ns1 NAMESPACE");
	do {
		$line = iil_ReadLine($conn->fp, 1024);
		if (iil_StartsWith($line, '* NAMESPACE')) {
			$i = 0;
			$data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
		}
	} while (!iil_StartsWith($line, 'ns1', true));
		
	if (!is_array($data)) {
	    return false;
	}
    
	//extract user space data (opposed to global/shared space)
	$user_space_data = $data[0];
	if (!is_array($user_space_data)) {
	    return false;
	}
    
	//get first element
	$first_userspace = $user_space_data[0];
	if (!is_array($first_userspace)) {
	    return false;
	}
    
	//extract delimiter
	$delimiter = $first_userspace[1];	

	return $delimiter;
}

function iil_C_ListMailboxes(&$conn, $ref, $mailbox) {
	global $IGNORE_FOLDERS;
	
	$ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
		
	$fp = $conn->fp;
	
	if (empty($mailbox)) {
	    $mailbox = '*';
	}
	
	if (empty($ref) && $conn->rootdir) {
	    $ref = $conn->rootdir;
	}
    
	// send command
	if (!iil_PutLine($fp, "lmb LIST \"".$ref."\" \"".iil_Escape($mailbox)."\"")) {
	    return false;
	}
    
	$i = 0;
	// get folder list
	do {
		$line = iil_ReadLine($fp, 500);
		$line = iil_MultLine($fp, $line);

		$a = explode(' ', $line);
		if (($line[0] == '*') && ($a[1] == 'LIST')) {
			$line = rtrim($line);
        		// split one line
			$a = iil_ExplodeQuotedString(' ', $line);
        		// last string is folder name
			$folder = trim($a[count($a)-1], '"');
            
        		if (empty($ignore) || (!empty($ignore)
            			&& !eregi($ignore, $folder))) {
            			$folders[$i] = $folder;
        		}
            
		        // second from last is delimiter
        		$delim = trim($a[count($a)-2], '"');
        		// is it a container?
        		$i++;
		}
	} while (!iil_StartsWith($line, 'lmb', true));

	if (is_array($folders)) {
    	    if (!empty($ref)) {
        	// if rootdir was specified, make sure it's the first element
        	// some IMAP servers (i.e. Courier) won't return it
        	if ($ref[strlen($ref)-1]==$delim)
		    $ref = substr($ref, 0, strlen($ref)-1);
    		if ($folders[0]!=$ref)
		    array_unshift($folders, $ref);
    	    }
    	    return $folders;
	} else if (iil_ParseResult($line) == 0) {
		return array('INBOX');
	} else {
		$conn->error = $line;
		return false;
	}
}

function iil_C_ListSubscribed(&$conn, $ref, $mailbox) {
	global $IGNORE_FOLDERS;
	
	$ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
	
	$fp = $conn->fp;
	if (empty($mailbox)) {
		$mailbox = '*';
	}
	if (empty($ref) && $conn->rootdir) {
		$ref = $conn->rootdir;
	}
	$folders = array();

	// send command
	if (!iil_PutLine($fp, 'lsb LSUB "' . $ref . '" "' . iil_Escape($mailbox).'"')) {
		$conn->error = "Couldn't send LSUB command\n";
		return false;
	}
	
	$i = 0;
	
	// get folder list
	do {
		$line = iil_ReadLine($fp, 500);
		$line = iil_MultLine($fp, $line);
		$a    = explode(' ', $line);
        
		if (($line[0] == '*') && ($a[1] == 'LSUB' || $a[1] == 'LIST')) {
			$line = rtrim($line);
            
        		// split one line
			$a = iil_ExplodeQuotedString(' ', $line);
            
        		// last string is folder name
        		//$folder = UTF7DecodeString(str_replace('"', '', $a[count($a)-1]));
        		$folder = trim($a[count($a)-1], '"');
            
			if ((!in_array($folder, $folders)) && (empty($ignore)
            			|| (!empty($ignore) && !eregi($ignore, $folder)))) {
			    $folders[$i] = $folder;
        		}
            
        		// second from last is delimiter
        		$delim = trim($a[count($a)-2], '"');
            
        		// is it a container?
        		$i++;
		}
	} while (!iil_StartsWith($line, 'lsb', true));

	if (is_array($folders)) {
    	    if (!empty($ref)) {
        	// if rootdir was specified, make sure it's the first element
        	// some IMAP servers (i.e. Courier) won't return it
        	if ($ref[strlen($ref)-1]==$delim) {
            	    $ref = substr($ref, 0, strlen($ref)-1);
        	}
        	if ($folders[0]!=$ref) {
            	    array_unshift($folders, $ref);
        	}
    	    }
    	    return $folders;
	}
	$conn->error = $line;
	return false;
}

function iil_C_Subscribe(&$conn, $folder) {
	$fp = $conn->fp;

	$query = 'sub1 SUBSCRIBE "' . iil_Escape($folder). '"';
	iil_PutLine($fp, $query);

	$line = trim(iil_ReadLine($fp, 10000));
	return iil_ParseResult($line);
}

function iil_C_UnSubscribe(&$conn, $folder) {
	$fp = $conn->fp;

	$query = 'usub1 UNSUBSCRIBE "' . iil_Escape($folder) . '"';
	iil_PutLine($fp, $query);
    
	$line = trim(iil_ReadLine($fp, 10000));
	return iil_ParseResult($line);
}

function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $part) {

	$part = empty($part) ? 'HEADER' : $part.'.MIME';

	return iil_C_HandlePartBody(&$conn, $mailbox, $id, $part, 1);
}

function iil_C_HandlePartBody(&$conn, $mailbox, $id, $part='', $mode=1, $file=NULL) {
	/* modes:
        1: return string (or write to $file pointer)
        2: print
        3: base64 and print (or write to $file pointer)
	*/
	
	$fp     = $conn->fp;
	$result = false;

	if (iil_C_Select($conn, $mailbox)) {
    		$reply_key = '* ' . $id;
        
    		// format request
		$key     = 'ftch' . ($c++) . ' ';
		$request = $key . "FETCH $id (BODY.PEEK[$part])";
    		// send request
		if (!iil_PutLine($fp, $request)) {
		    return false;
    		}
        
    		// receive reply line
    		do {
        		$line = chop(iil_ReadLine($fp, 1000));
        		$a    = explode(' ', $line);
    		} while ($a[2] != 'FETCH');
    		$len = strlen($line);

		// handle empty "* X FETCH ()" response
    		if ($line[$len-1] == ')' && $line[$len-2] != '(') {
        		// one line response, get everything between first and last quotes
			if (substr($line, -4, 3) == 'NIL') {
				// NIL response
				$result = '';
			} else {
			        $from = strpos($line, '"') + 1;
        			$to   = strrpos($line, '"');
		        	$len  = $to - $from;
				$result = substr($line, $from, $len);
			}
	    
	                if ($mode == 2) {
        		        echo $result;
	                } else if ($mode == 3) {
				if ($file)
					fwrite($file, base64_decode($result));
        		    	else
					echo base64_decode($result);
			}			     
    		} else if ($line[$len-1] == '}') {
	                //multi-line request, find sizes of content and receive that many bytes
        		$from     = strpos($line, '{') + 1;
	                $to       = strrpos($line, '}');
        		$len      = $to - $from;
	                $sizeStr  = substr($line, $from, $len);
        		$bytes    = (int)$sizeStr;

        		while ($bytes > 0) {
    		                $line      = iil_ReadLine($fp, 1024);
            			$len       = strlen($line);
                
		                if ($len > $bytes) {
            			        $line = substr($line, 0, $bytes);
		                }
            			$bytes -= strlen($line);

		                if ($mode == 1) {
					if ($file)
						fwrite($file, rtrim($line, "\t\r\n\0\x0B") . "\n");
            			        else
						$result .= rtrim($line, "\t\r\n\0\x0B") . "\n";
		                } else if ($mode == 2) {
            			        echo rtrim($line, "\t\r\n\0\x0B") . "\n";
		                } else if ($mode == 3) {
					if ($file)
						fwrite($file, base64_decode($line));
            				else
						echo base64_decode($line);
				}
        		}
    		}
	        // read in anything up until last line
		do {
        		$line = iil_ReadLine($fp, 1024);
		} while (!iil_StartsWith($line, $key, true));
        
		if ($mode == 3 && $file) {
			return true;
		}
	
    		if ($result) {
	    		$result = rtrim($result, "\t\r\n\0\x0B");
			if ($file) {
				fwrite($file, $result);
				return true;
			}	
			return $result; // substr($result, 0, strlen($result)-1);
    		}
    		
		return false;
	} else {
		echo 'Select failed.';
	}
    
	if ($mode==1) {
		if ($file) {
			fwrite($file, $result);
			return true;
		}
    		return $result;
	}
	
	return false;
}

function iil_C_FetchPartBody(&$conn, $mailbox, $id, $part, $file=NULL) {
	return iil_C_HandlePartBody($conn, $mailbox, $id, $part, 1, $file);
}

function iil_C_PrintPartBody(&$conn, $mailbox, $id, $part) {
	iil_C_HandlePartBody($conn, $mailbox, $id, $part, 2);
}

function iil_C_PrintBase64Body(&$conn, $mailbox, $id, $part) {
	iil_C_HandlePartBody($conn, $mailbox, $id, $part, 3);
}

function iil_C_CreateFolder(&$conn, $folder) {
	$fp = $conn->fp;
	if (iil_PutLine($fp, 'c CREATE "' . iil_Escape($folder) . '"')) {
		do {
			$line=iil_ReadLine($fp, 300);
		} while ($line[0] != 'c');
        $conn->error = $line;
		return (iil_ParseResult($line) == 0);
	}
	return false;
}

function iil_C_RenameFolder(&$conn, $from, $to) {
	$fp = $conn->fp;
	if (iil_PutLine($fp, 'r RENAME "' . iil_Escape($from) . '" "' . iil_Escape($to) . '"')) {
		do {
			$line = iil_ReadLine($fp, 300);
		} while ($line[0] != 'r');
		return (iil_ParseResult($line) == 0);
	}
	return false;
}

function iil_C_DeleteFolder(&$conn, $folder) {
	$fp = $conn->fp;
	if (iil_PutLine($fp, 'd DELETE "' . iil_Escape($folder). '"')) {
		do {
			$line=iil_ReadLine($fp, 300);
		} while ($line[0] != 'd');
		return (iil_ParseResult($line) == 0);
	}
	$conn->error = "Couldn't send command\n";
	return false;
}

function iil_C_Append(&$conn, $folder, &$message) {
	if (!$folder) {
    		return false;
	}
	$fp = $conn->fp;

	$message = str_replace("\r", '', $message);
	$message = str_replace("\n", "\r\n", $message);		

	$len = strlen($message);
	if (!$len) {
    		return false;
	}

	$request = 'A APPEND "' . iil_Escape($folder) .'" (\\Seen) {' . $len . '}';
    
	if (iil_PutLine($fp, $request)) {
		$line=iil_ReadLine($fp, 100);		
		$sent = fwrite($fp, $message."\r\n");
		do {
			$line=iil_ReadLine($fp, 1000);
		} while ($line[0] != 'A');
	
		$result = (iil_ParseResult($line) == 0);
		if (!$result) {
		    $conn->error .= $line . "\n";
    		}
		return $result;
	}

	$conn->error .= "Couldn't send command \"$request\"\n";
	return false;
}

function iil_C_AppendFromFile(&$conn, $folder, $path) {
	if (!$folder) {
	    return false;
	}
    
	//open message file
	$in_fp = false;				
	if (file_exists(realpath($path))) {
		$in_fp = fopen($path, 'r');
	}
	if (!$in_fp) { 
		$conn->error .= "Couldn't open $path for reading\n";
		return false;
	}
	
	$fp  = $conn->fp;
	$len = filesize($path);
	if (!$len) {
		return false;
	}
    
	//send APPEND command
	$request    = 'A APPEND "' . iil_Escape($folder) . '" (\\Seen) {' . $len . '}';
	$bytes_sent = 0;
	if (iil_PutLine($fp, $request)) {
		$line = iil_ReadLine($fp, 100);
				
		//send file
		while (!feof($in_fp)) {
			$buffer      = fgets($in_fp, 4096);
			$bytes_sent += strlen($buffer);
			iil_PutLine($fp, $buffer, false);
		}
		fclose($in_fp);

		iil_PutLine($fp, '');

		//read response
		do {
			$line = iil_ReadLine($fp, 1000);
		} while ($line[0] != 'A');
			
		$result = (iil_ParseResult($line) == 0);
		if (!$result) {
		    $conn->error .= $line . "\n";
		}
        
		return $result;
	}
	
	$conn->error .= "Couldn't send command \"$request\"\n";
	return false;
}

function iil_C_FetchStructureString(&$conn, $folder, $id) {
	$fp     = $conn->fp;
	$result = false;
	
	if (iil_C_Select($conn, $folder)) {
		$key = 'F1247';

		if (iil_PutLine($fp, "$key FETCH $id (BODYSTRUCTURE)")) {
			do {
				$line = iil_ReadLine($fp, 5000);
				$line = iil_MultLine($fp, $line);
				list(, $index, $cmd, $rest) = explode(' ', $line);
				if ($cmd != 'FETCH' || $index == $id || preg_match("/^$key/", $line))
					$result .= $line;
			} while (!preg_match("/^$key/", $line));

			$result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -(strlen($result)-strrpos($result, $key)+1)));
		}
	}
	return $result;
}

function iil_C_PrintSource(&$conn, $folder, $id, $part) {
	$header = iil_C_FetchPartHeader($conn, $folder, $id, $part);
	//echo str_replace("\r", '', $header);
	echo $header;
	echo iil_C_PrintPartBody($conn, $folder, $id, $part);
}

function iil_C_GetQuota(&$conn) {
/*
 * GETQUOTAROOT "INBOX"
 * QUOTAROOT INBOX user/rchijiiwa1
 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
 b OK Completed
 */
	$fp         = $conn->fp;
	$result     = false;
	$quota_line = '';
	
	//get line containing quota info
	if (iil_PutLine($fp, 'QUOT1 GETQUOTAROOT "INBOX"')) {
		do {
			$line=chop(iil_ReadLine($fp, 5000));
			if (iil_StartsWith($line, '* QUOTA ')) {
				$quota_line = $line;
        		}
		} while (!iil_StartsWith($line, 'QUOT1', true));
	}
	
	//return false if not found, parse if found
	if (!empty($quota_line)) {
		$quota_line   = eregi_replace('[()]', '', $quota_line);
		$parts        = explode(' ', $quota_line);
		$storage_part = array_search('STORAGE', $parts);
		if ($storage_part > 0) {
			$result['used']    = intval($parts[$storage_part+1]);
			$result['total']   = intval($parts[$storage_part+2]);
			$result['percent'] = min(100, round(($result['used']/max(1,$result['total']))*100));
			$result['free']    = 100 - $result['percent'];
		}
	}
	return $result;
}

function iil_C_ClearFolder(&$conn, $folder) {
	$num_in_trash = iil_C_CountMessages($conn, $folder);
	if ($num_in_trash > 0) {
		iil_C_Delete($conn, $folder, '1:' . $num_in_trash);
	}
	return (iil_C_Expunge($conn, $folder) >= 0);
}

?>