aboutsummaryrefslogtreecommitdiffstats
path: root/calendar/calendar.php
blob: cb32773c011adfc7fda9561734adff98ed266bd8 (plain) (blame)
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
<?php

/**
 * Calendar plugin for Roundcube webmail
 *
 * @author Lazlo Westerhof <hello@lazlo.me>
 * @author Thomas Bruederli <bruederli@kolabsys.com>
 *
 * Copyright (C) 2010, Lazlo Westerhof <hello@lazlo.me>
 * Copyright (C) 2014-2015, Kolab Systems AG <contact@kolabsys.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

class calendar extends rcube_plugin
{
  const FREEBUSY_UNKNOWN = 0;
  const FREEBUSY_FREE = 1;
  const FREEBUSY_BUSY = 2;
  const FREEBUSY_TENTATIVE = 3;
  const FREEBUSY_OOF = 4;

  const SESSION_KEY = 'calendar_temp';

  public $task = '?(?!logout).*';
  public $rc;
  public $lib;
  private $_drivers = null;
  private $_cals = null;
  private $_cal_driver_map = null;
  public $resources_dir;
  public $home;  // declare public to be used in other classes
  public $urlbase;
  public $timezone;
  public $timezone_offset;
  public $gmt_offset;
  public $ui;

  public $defaults = array(
    'calendar_default_view' => "agendaWeek",
    'calendar_timeslots'    => 2,
    'calendar_work_start'   => 6,
    'calendar_work_end'     => 18,
    'calendar_agenda_range' => 60,
    'calendar_agenda_sections' => 'smart',
    'calendar_event_coloring'  => 0,
    'calendar_time_indicator'  => true,
    'calendar_allow_invite_shared' => false,
    'calendar_itip_send_option'    => 3,
    'calendar_itip_after_action'   => 0,
  );

  private $ical;
  private $itip;

  /**
   * Plugin initialization.
   */
  function init()
  {
    $this->require_plugin('libcalendaring');

    $this->rc = rcube::get_instance();
    $this->lib = libcalendaring::get_instance();

    $this->register_task('calendar', 'calendar');

    // load calendar configuration
    $this->load_config();

    // load localizations
    $this->add_texts('localization/', $this->rc->task == 'calendar' && (!$this->rc->action || $this->rc->action == 'print'));

    $this->timezone = $this->lib->timezone;
    $this->gmt_offset = $this->lib->gmt_offset;
    $this->dst_active = $this->lib->dst_active;
    $this->timezone_offset = $this->gmt_offset / 3600 - $this->dst_active;

    require($this->home . '/lib/calendar_ui.php');
    $this->ui = new calendar_ui($this);

    // catch iTIP confirmation requests that don're require a valid session
    if ($this->rc->action == 'attend' && !empty($_REQUEST['_t'])) {
      $this->add_hook('startup', array($this, 'itip_attend_response'));
    }
    else if ($this->rc->action == 'feed' && !empty($_REQUEST['_cal'])) {
      $this->add_hook('startup', array($this, 'ical_feed_export'));
    }
    else {
      // default startup routine
      $this->add_hook('startup', array($this, 'startup'));
    }

    $this->add_hook('user_delete', array($this, 'user_delete'));
  }

  /**
   * Startup hook
   */
  public function startup($args)
  {
    // the calendar module can be enabled/disabled by the kolab_auth plugin
    if ($this->rc->config->get('calendar_disabled', false) || !$this->rc->config->get('calendar_enabled', true))
        return;

    // load Calendar user interface
    if (!$this->rc->output->ajax_call && (!$this->rc->output->env['framed'] || $args['action'] == 'preview')) {
      $this->ui->init();

      // settings are required in (almost) every GUI step
      if ($args['action'] != 'attend')
        $this->rc->output->set_env('calendar_settings', $this->load_settings());
    }

    if ($args['task'] == 'calendar' && $args['action'] != 'save-pref') {
      // Load drivers to register possible hooks.
      $this->load_drivers();

      // register calendar actions
      $this->register_action('index', array($this, 'calendar_view'));
      $this->register_action('event', array($this, 'event_action'));
      $this->register_action('calendar', array($this, 'calendar_action'));
      $this->register_action('count', array($this, 'count_events'));
      $this->register_action('load_events', array($this, 'load_events'));
      $this->register_action('export_events', array($this, 'export_events'));
      $this->register_action('import_events', array($this, 'import_events'));
      $this->register_action('upload', array($this, 'attachment_upload'));
      $this->register_action('get-attachment', array($this, 'attachment_get'));
      $this->register_action('freebusy-status', array($this, 'freebusy_status'));
      $this->register_action('freebusy-times', array($this, 'freebusy_times'));
      $this->register_action('randomdata', array($this, 'generate_randomdata'));
      $this->register_action('print', array($this,'print_view'));
      $this->register_action('mailimportitip', array($this, 'mail_import_itip'));
      $this->register_action('mailimportattach', array($this, 'mail_import_attachment'));
      $this->register_action('mailtoevent', array($this, 'mail_message2event'));
      $this->register_action('inlineui', array($this, 'get_inline_ui'));
      $this->register_action('check-recent', array($this, 'check_recent'));
      $this->register_action('itip-status', array($this, 'event_itip_status'));
      $this->register_action('itip-remove', array($this, 'event_itip_remove'));
      $this->register_action('itip-decline-reply', array($this, 'mail_itip_decline_reply'));
      $this->register_action('itip-delegate', array($this, 'mail_itip_delegate'));
      $this->register_action('resources-list', array($this, 'resources_list'));
      $this->register_action('resources-owner', array($this, 'resources_owner'));
      $this->register_action('resources-calendar', array($this, 'resources_calendar'));
      $this->register_action('resources-autocomplete', array($this, 'resources_autocomplete'));
      $this->add_hook('refresh', array($this, 'refresh'));

      // remove undo information...
      if ($undo = $_SESSION['calendar_event_undo']) {
        // ...after timeout
        $undo_time = $this->rc->config->get('undo_timeout', 0);
        if ($undo['ts'] < time() - $undo_time) {
          $this->rc->session->remove('calendar_event_undo');
          // @TODO: do EXPUNGE on kolab objects?
        }
      }

      // loading preinstalled calendars
      $preinstalled_calendars = $this->rc->config->get('calendar_preinstalled_calendars', FALSE);
      if ($preinstalled_calendars && is_array($preinstalled_calendars)) {
      
          // expanding both caldav url and user with RC (imap) username
          foreach ($preinstalled_calendars as $index => $cal){
              $preinstalled_calendars[$index]['caldav_url'] = str_replace('%u', $this->rc->get_user_name(), $cal['caldav_url']); 
              $preinstalled_calendars[$index]['caldav_user'] = str_replace('%u', $this->rc->get_user_name(), $cal['caldav_user']);
          }
        
          foreach ($this->get_drivers() as $driver_name => $driver) {
              foreach ($preinstalled_calendars as $cal) {
                  if ($driver_name == $cal['driver']) {    
                      if (!$driver->insert_default_calendar($cal)) {
                          $error_msg = 'Unable to add default calendars' . ($driver && $driver->last_error ? ': ' . $driver->last_error :'');
                          $this->rc->output->show_message($error_msg, 'error');
                      }
                  }
              }
          }
      }
    }
    else if ($args['task'] == 'settings') {
      // add hooks for Calendar settings
      $this->add_hook('preferences_sections_list', array($this, 'preferences_sections_list'));
      $this->add_hook('preferences_list', array($this, 'preferences_list'));
      $this->add_hook('preferences_save', array($this, 'preferences_save')); 
    }
    else if ($args['task'] == 'mail') {
      // hooks to catch event invitations on incoming mails
      if ($args['action'] == 'show' || $args['action'] == 'preview') {
        $this->add_hook('template_object_messagebody', array($this, 'mail_messagebody_html'));
      }

      // add 'Create event' item to message menu
      if ($this->api->output->type == 'html') {
        $this->api->add_content(html::tag('li', null, 
          $this->api->output->button(array(
            'command'  => 'calendar-create-from-mail',
            'label'    => 'calendar.createfrommail',
            'type'     => 'link',
            'classact' => 'icon calendarlink active',
            'class'    => 'icon calendarlink',
            'innerclass' => 'icon calendar',
          ))),
          'messagemenu');

        $this->api->output->add_label('calendar.createfrommail');
      }

      $this->add_hook('messages_list', array($this, 'mail_messages_list'));
      $this->add_hook('message_compose', array($this, 'mail_message_compose'));
    }
    else if ($args['task'] == 'addressbook') {
      if ($this->rc->config->get('calendar_contact_birthdays')) {
        $this->add_hook('contact_update', array($this, 'contact_update'));
        $this->add_hook('contact_create', array($this, 'contact_update'));
      }
    }

    // add hooks to display alarms
    $this->add_hook('pending_alarms', array($this, 'pending_alarms'));
    $this->add_hook('dismiss_alarms', array($this, 'dismiss_alarms'));
  }

  /**
   * Helper method to load all configured drivers.
   */
  public function load_drivers()
  {
    if($this->_drivers == null)
    {
      $this->_drivers = array();

      foreach($this->get_driver_names() as $driver_name)
      {
        $driver_name = trim($driver_name);
        $driver_class = $driver_name . '_driver';

        require_once($this->home . '/drivers/calendar_driver.php');
        require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php');

        if($driver_name == "kolab")
          $this->require_plugin('libkolab');

        $driver = new $driver_class($this);

        if ($driver->undelete)
          $driver->undelete = $this->rc->config->get('undo_timeout', 0) > 0;

        $this->_drivers[$driver_name] = $driver;
      }
    }
  }

  /*
   * Helper method to get configured driver names.
   * @return List of driver names.
   */
  public function get_driver_names()
  {
    $driver_names = $this->rc->config->get('calendar_driver', array('kolab'));
    if(!is_array($driver_names)) $driver_names = array($driver_names);
    return $driver_names;
  }

  /**
   * Helpers function to return loaded drivers.
   * @return List of driver objects.
   */
  public function get_drivers()
  {
    $this->load_drivers();
    return $this->_drivers;
  }

  /**
   * Helper method to get driver by name.
   *
   * @param string $name Driver name to get driver object for.
   * @return mixed Driver object or null if no such driver exists.
   */
  public function get_driver_by_name($name)
  {
    $this->load_drivers();
    if(isset($this->_drivers[$name]))
    {
      return $this->_drivers[$name];
    }
    else
    {
      rcube::raise_error("Unknown driver requested \"$name\".", true, true);
      return null;
    }
  }

  /**
   * Helper method to get the driver by GPC input, e.g. "_driver" or "driver"
   * property specified in POST/GET or COOKIE variables.
   *
   * @param boolean $quiet = false Indicates where to raise an error if no driver was found in GPC
   * @return mixed Driver object or null if no such driver exists.
   */
  public function get_driver_by_gpc($quiet = false)
  {
    $this->load_drivers();
    $driver_name = null;
    foreach(array("_driver", "driver") as $input_name)
    {
      $driver_name = get_input_value($input_name, RCUBE_INPUT_GPC);
      if($driver_name != null) break;
    }

    // Remove possible postfix "_driver" from requested driver name.
    $driver_name = str_replace("_driver", "", $driver_name);

    if($driver_name != null)
    {
      if(isset($this->_drivers[$driver_name]))
      {
        return $this->_drivers[$driver_name];
      }
      else
      {
        rcube::raise_error("Unknown driver requested \"$driver_name\".", true, true);
      }
    }
    else
    {
      if(!$quiet) {
        rcube::raise_error("No driver name found in GPC.", true, true);
      }
    }

    return null;
  }

  /**
   * Helper function to retrieve the default driver
   *
   * @return mixed Driver object or null if no default driver could be determined.
   */
  public function get_default_driver()
  {
    $default = $this->rc->config->get("calendar_driver_default", "kolab"); // Fallback to kolab if nothing was configured.
    return $this->get_driver_by_name($default);
  }

  /**
   * Return the driver for the given event.
   *
   * @param $id ID or UID of the event.
   * @return mixed Returns the driver object or null if no driver could be found for this event.
   */
  public function get_driver_by_event($id)
  {
    foreach($this->get_drivers() as $driver) {
      if($driver->get_event($id))
        return $driver;
    }

    return null;
  }

  /**
   * Get driver for given calendar id.
   * @param int Calendar id to get driver for.
   * @return mixed Driver object for given calendar.
   */
  public function get_driver_by_cal($cal_id)
  {
    if ($this->_cal_driver_map == null)
      $this->get_calendars();

    if (!isset($this->_cal_driver_map[$cal_id])){
      rcube::raise_error("No driver found for calendar \"$cal_id\".", true, true);
    }

    return $this->_cal_driver_map[$cal_id];
  }

  /**
   * Helper function to build calendar to driver map and calendar array.
   * @return array List of calendar properties.
   */
  public function get_calendars()
  {
    if ($this->_cals == null || $this->_cal_driver_map == null) {
      $this->_cals = array();
      $this->_cal_driver_map = array();

      $this->load_drivers();
      foreach ($this->get_drivers() as $driver) {
        foreach ((array)$driver->list_calendars() as $id => $prop) {
          $prop["driver"] = get_class($driver);
          $this->_cals[$id] = $prop;
          $this->_cal_driver_map[$id] = $driver;
        }
      }
    }

    return $this->_cals;
  }

  /**
   * Load iTIP functions
   */
  private function load_itip()
  {
    if (!$this->itip) {
      require_once($this->home . '/lib/calendar_itip.php');
      $this->itip = new calendar_itip($this);
      
      if ($this->rc->config->get('kolab_invitation_calendars'))
        $this->itip->set_rsvp_actions(array('accepted','tentative','declined','delegated','needs-action'));
    }

    return $this->itip;
  }

  /**
   * Load iCalendar functions
   */
  public function get_ical()
  {
    if (!$this->ical) {
      $this->ical = libcalendaring::get_ical();
    }
    
    return $this->ical;
  }

  /**
   * Get properties of the calendar this user has specified as default
   */
  public function get_default_calendar($sensitivity = null)
  {
    $default_id = $this->rc->config->get('calendar_default_calendar');
    // TODO: $calendars = $this->driver->list_calendars(calendar_driver::FILTER_PERSONAL | calendar_driver::FILTER_WRITEABLE);

    foreach($this->get_drivers() as $driver){
      $calendars = $driver->list_calendars(false, true);
      if($default_id) {
        $calendar = $calendars[$default_id] ?: null;

        if($calendar && (!$writeable || !$calendar["readonly"])
          && (!$confidential || $calendar["subtype"] != "confidential"))
        {
          //rcmail::console("422: get_default_calendar(): " . print_r($calendar, true));
          return $calendar;
        }
      }
      else
      {
        // No default if, so get first calendar of first driver.
        foreach ($calendars as $calendar) {
          if ($calendar['default']) {
            //rcmail::console("431: get_default_calendar(): " . print_r($calendar, true));
            return $calendar;
          }
          if ((!$writeable || !$calendar['readonly']) && (!$confidential || $calendar["subtype"] != "confidential")) {
            //rcmail::console("435: get_default_calendar(): " . print_r($calendar, true));
            return $calendar;
          }
        }
      }
    }

    return null;
  }
  
  /**
   * Render the main calendar view from skin template
   */
  function calendar_view()
  {
    $this->rc->output->set_pagetitle($this->gettext('calendar'));

    // Add CSS stylesheets to the page header
    $this->ui->addCSS();

    // Add JS files to the page header
    $this->ui->addJS();

    $this->ui->init_templates();
    $this->rc->output->add_label('lowest','low','normal','high','highest','delete','cancel','uploading','noemailwarning','close');
    $this->rc->output->add_label('libcalendaring.itipaccepted','libcalendaring.itiptentative','libcalendaring.itipdeclined','libcalendaring.itipdelegated','libcalendaring.expandattendeegroup','libcalendaring.expandattendeegroupnodata');

    // initialize attendees autocompletion
    rcube_autocomplete_init();

    $this->rc->output->set_env('timezone', $this->timezone->getName());
    $this->rc->output->set_env('calendar_driver', $this->rc->config->get('calendar_driver'), false);
    $this->rc->output->set_env('calendar_resources', (bool)$this->rc->config->get('calendar_resources_driver'));
    $this->rc->output->set_env('mscolors', jqueryui::get_color_values());
    $this->rc->output->set_env('identities-selector', $this->ui->identity_select(array('id' => 'edit-identities-list', 'aria-label' => $this->gettext('roleorganizer'))));

    $view = rcube_utils::get_input_value('view', rcube_utils::INPUT_GPC);
    if (in_array($view, array('agendaWeek', 'agendaDay', 'month', 'table')))
      $this->rc->output->set_env('view', $view);

    if ($date = rcube_utils::get_input_value('date', rcube_utils::INPUT_GPC))
      $this->rc->output->set_env('date', $date);

    if ($msgref = rcube_utils::get_input_value('itip', rcube_utils::INPUT_GPC))
      $this->rc->output->set_env('itip_events', $this->itip_events($msgref));

    $this->rc->output->send("calendar.calendar");
  }

  /**
   * Handler for preferences_sections_list hook.
   * Adds Calendar settings sections into preferences sections list.
   *
   * @param array Original parameters
   * @return array Modified parameters
   */
  function preferences_sections_list($p)
  {
    $p['list']['calendar'] = array(
      'id' => 'calendar', 'section' => $this->gettext('calendar'),
    );

    return $p;
  }

  /**
   * Handler for preferences_list hook.
   * Adds options blocks into Calendar settings sections in Preferences.
   *
   * @param array Original parameters
   * @return array Modified parameters
   */
  function preferences_list($p)
  {
    if ($p['section'] != 'calendar') {
      return $p;
    }

    $no_override = array_flip((array)$this->rc->config->get('dont_override'));

    $p['blocks']['view']['name'] = $this->gettext('mainoptions');

    if (!isset($no_override['calendar_default_view'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_default_view';
      $select = new html_select(array('name' => '_default_view', 'id' => $field_id));
      $select->add($this->gettext('day'), "agendaDay");
      $select->add($this->gettext('week'), "agendaWeek");
      $select->add($this->gettext('month'), "month");
      $select->add($this->gettext('agenda'), "table");
      $p['blocks']['view']['options']['default_view'] = array(
        'title' => html::label($field_id, Q($this->gettext('default_view'))),
        'content' => $select->show($this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view'])),
      );
    }

    if (!isset($no_override['calendar_timeslots'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_timeslot';
      $choices = array('1', '2', '3', '4', '6');
      $select = new html_select(array('name' => '_timeslots', 'id' => $field_id));
      $select->add($choices);
      $p['blocks']['view']['options']['timeslots'] = array(
        'title' => html::label($field_id, Q($this->gettext('timeslots'))),
        'content' => $select->show(strval($this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']))),
      );
    }

    if (!isset($no_override['calendar_first_day'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_firstday';
      $select = new html_select(array('name' => '_first_day', 'id' => $field_id));
      $select->add(rcube_label('sunday'), '0');
      $select->add(rcube_label('monday'), '1');
      $select->add(rcube_label('tuesday'), '2');
      $select->add(rcube_label('wednesday'), '3');
      $select->add(rcube_label('thursday'), '4');
      $select->add(rcube_label('friday'), '5');
      $select->add(rcube_label('saturday'), '6');
      $p['blocks']['view']['options']['first_day'] = array(
        'title' => html::label($field_id, Q($this->gettext('first_day'))),
        'content' => $select->show(strval($this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']))),
      );
    }

    if (!isset($no_override['calendar_first_hour'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $time_format = $this->rc->config->get('time_format', libcalendaring::to_php_date_format($this->rc->config->get('calendar_time_format', $this->defaults['calendar_time_format'])));
      $select_hours = new html_select();
      for ($h = 0; $h < 24; $h++)
        $select_hours->add(date($time_format, mktime($h, 0, 0)), $h);

      $field_id = 'rcmfd_firsthour';
      $p['blocks']['view']['options']['first_hour'] = array(
        'title' => html::label($field_id, Q($this->gettext('first_hour'))),
        'content' => $select_hours->show($this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']), array('name' => '_first_hour', 'id' => $field_id)),
      );
    }

    if (!isset($no_override['calendar_work_start'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_workstart';
      $p['blocks']['view']['options']['workinghours'] = array(
        'title' => html::label($field_id, Q($this->gettext('workinghours'))),
        'content' => $select_hours->show($this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']), array('name' => '_work_start', 'id' => $field_id)) .
        ' &mdash; ' . $select_hours->show($this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']), array('name' => '_work_end', 'id' => $field_id)),
      );
    }

    if (!isset($no_override['calendar_event_coloring'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_coloring';
      $select_colors = new html_select(array('name' => '_event_coloring', 'id' => $field_id));
      $select_colors->add($this->gettext('coloringmode0'), 0);
      $select_colors->add($this->gettext('coloringmode1'), 1);
      $select_colors->add($this->gettext('coloringmode2'), 2);
      $select_colors->add($this->gettext('coloringmode3'), 3);

      $p['blocks']['view']['options']['eventcolors'] = array(
        'title' => html::label($field_id . 'value', Q($this->gettext('eventcoloring'))),
        'content' => $select_colors->show($this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring'])),
      );
    }

    if (!isset($no_override['calendar_default_alarm_type'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_alarm';
      $select_type = new html_select(array('name' => '_alarm_type', 'id' => $field_id));
      $select_type->add($this->gettext('none'), '');
      $types = array();
      foreach ($this->get_drivers() as $driver) {
        foreach ($driver->alarm_types as $type) {
          $types[$type] = $type;
        }
      }
      foreach ($types as $type) {
        $select_type->add(rcube_label(strtolower("alarm{$type}option"), 'libcalendaring'), $type);
      }
      $p['blocks']['view']['options']['alarmtype'] = array(
        'title' => html::label($field_id, Q($this->gettext('defaultalarmtype'))),
        'content' => $select_type->show($this->rc->config->get('calendar_default_alarm_type', '')),
      );
    }

    if (!isset($no_override['calendar_default_alarm_offset'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_alarm';
      $input_value = new html_inputfield(array('name' => '_alarm_value', 'id' => $field_id . 'value', 'size' => 3));
      $select_offset = new html_select(array('name' => '_alarm_offset', 'id' => $field_id . 'offset'));
      foreach (array('-M','-H','-D','+M','+H','+D') as $trigger)
        $select_offset->add(rcube_label('trigger' . $trigger, 'libcalendaring'), $trigger);

      $preset = libcalendaring::parse_alarm_value($this->rc->config->get('calendar_default_alarm_offset', '-15M'));
      $p['blocks']['view']['options']['alarmoffset'] = array(
        'title' => html::label($field_id . 'value', Q($this->gettext('defaultalarmoffset'))),
        'content' => $input_value->show($preset[0]) . ' ' . $select_offset->show($preset[1]),
      );
    }

    if (!isset($no_override['calendar_default_calendar'])) {
      if (!$p['current']) {
        $p['blocks']['view']['content'] = true;
        return $p;
      }
      // default calendar selection
      $field_id = 'rcmfd_default_calendar';
      $select_cal = new html_select(array('name' => '_default_calendar', 'id' => $field_id, 'is_escaped' => true));
      foreach($this->get_drivers() as $driver){
        foreach ((array)$driver->list_calendars(false, true) as $id => $prop) {
          $select_cal->add($prop['name'], strval($id));
          if ($prop['default'])
            $default_calendar = $id;
        }
      }
      $p['blocks']['view']['options']['defaultcalendar'] = array(
        'title' => html::label($field_id . 'value', Q($this->gettext('defaultcalendar'))),
        'content' => $select_cal->show($this->rc->config->get('calendar_default_calendar', $default_calendar)),
      );
    }

    $p['blocks']['itip']['name'] = $this->gettext('itipoptions');

    // Invitations handling
    if (!isset($no_override['calendar_itip_after_action'])) {
      if (!$p['current']) {
        $p['blocks']['itip']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_after_action';
      $select   = new html_select(array('name' => '_after_action', 'id' => $field_id,
        'onchange' => "\$('#{$field_id}_select')[this.value == 4 ? 'show' : 'hide']()"));

      $select->add($this->gettext('afternothing'), '');
      $select->add($this->gettext('aftertrash'), 1);
      $select->add($this->gettext('afterdelete'), 2);
      $select->add($this->gettext('afterflagdeleted'), 3);
      $select->add($this->gettext('aftermoveto'), 4);

      $val = $this->rc->config->get('calendar_itip_after_action', $this->defaults['calendar_itip_after_action']);
      if ($val !== null && $val !== '' && !is_int($val)) {
        $folder = $val;
        $val    = 4;
      }

      $folders = $this->rc->folder_selector(array(
          'id'            => $field_id . '_select',
          'name'          => '_after_action_folder',
          'maxlength'     => 30,
          'folder_filter' => 'mail',
          'folder_rights' => 'w',
          'style'         => $val !== 4 ? 'display:none' : '',
      ));

      $p['blocks']['itip']['options']['after_action'] = array(
        'title'   => html::label($field_id, Q($this->gettext('afteraction'))),
        'content' => $select->show($val) . $folders->show($folder),
      );
    }

    // category definitions
    foreach ($this->get_drivers() as $driver) {
      if (!$driver->nocategories && !isset($no_override['calendar_categories'])) {
        $p['blocks']['categories']['name'] = $this->gettext('categories');

        if (!$p['current']) {
          $p['blocks']['categories']['content'] = true;
          return $p;
        }

        $categories = (array)$driver->list_categories();
        $categories_list = '';
        foreach ($categories as $name => $color) {
          $key = md5($name);
          $field_class = 'rcmfd_category_' . str_replace(' ', '_', $name);
          $category_remove = new html_inputfield(array('type' => 'button', 'value' => 'X', 'class' => 'button', 'onclick' => '$(this).parent().remove()', 'title' => $this->gettext('remove_category')));
          $category_name = new html_inputfield(array('name' => "_categories[$key]", 'class' => $field_class, 'size' => 30, 'disabled' => $driver->categoriesimmutable));
          $category_color = new html_inputfield(array('name' => "_colors[$key]", 'class' => "$field_class colors", 'size' => 6));
          $hidden = $driver->categoriesimmutable ? html::tag('input', array('type' => 'hidden', 'name' => "_categories[$key]", 'value' => $name)) : '';
          $categories_list .= html::div(null, $hidden . $category_name->show($name) . '&nbsp;' . $category_color->show($color) . '&nbsp;' . $category_remove->show());
        }

        $p['blocks']['categories']['options']['category_' . $name] = array(
          'content' => html::div(array('id' => 'calendarcategories'), $categories_list),
        );

        $field_id = 'rcmfd_new_category';
        $new_category = new html_inputfield(array('name' => '_new_category', 'id' => $field_id, 'size' => 30));
        $add_category = new html_inputfield(array('type' => 'button', 'class' => 'button', 'value' => $this->gettext('add_category'), 'onclick' => "rcube_calendar_add_category()"));
        $p['blocks']['categories']['options']['categories'] = array(
          'content' => $new_category->show('') . '&nbsp;' . $add_category->show(),
        );

        $this->rc->output->add_script('function rcube_calendar_add_category(){
          var name = $("#rcmfd_new_category").val();
          if (name.length) {
            var input = $("<input>").attr("type", "text").attr("name", "_categories[]").attr("size", 30).val(name);
            var color = $("<input>").attr("type", "text").attr("name", "_colors[]").attr("size", 6).addClass("colors").val("000000");
            var button = $("<input>").attr("type", "button").attr("value", "X").addClass("button").click(function(){ $(this).parent().remove() });
            $("<div>").append(input).append("&nbsp;").append(color).append("&nbsp;").append(button).appendTo("#calendarcategories");
            color.miniColors({ colorValues:(rcmail.env.mscolors || []) });
            $("#rcmfd_new_category").val("");
          }
        }');

        $this->rc->output->add_script('$("#rcmfd_new_category").keypress(function(event){
          if (event.which == 13) {
            rcube_calendar_add_category();
            event.preventDefault();
          }
        });
        ', 'docready');

        // load miniColors js/css files
        jqueryui::miniColors();
      }
    }

    // virtual birthdays calendar
    if (!isset($no_override['calendar_contact_birthdays'])) {
      $p['blocks']['birthdays']['name'] = $this->gettext('birthdayscalendar');

      if (!$p['current']) {
        $p['blocks']['birthdays']['content'] = true;
        return $p;
      }

      $field_id = 'rcmfd_contact_birthdays';
      $input    = new html_checkbox(array('name' => '_contact_birthdays', 'id' => $field_id, 'value' => 1, 'onclick' => '$(".calendar_birthday_props").prop("disabled",!this.checked)'));

      $p['blocks']['birthdays']['options']['contact_birthdays'] = array(
        'title'   => html::label($field_id, $this->gettext('displaybirthdayscalendar')),
        'content' => $input->show($this->rc->config->get('calendar_contact_birthdays')?1:0),
      );

      $input_attrib = array(
        'class' => 'calendar_birthday_props',
        'disabled' => !$this->rc->config->get('calendar_contact_birthdays'),
      );

      $sources = array();
      $checkbox = new html_checkbox(array('name' => '_birthday_adressbooks[]') + $input_attrib);
      foreach ($this->rc->get_address_sources(false, true) as $source) {
        $active = in_array($source['id'], (array)$this->rc->config->get('calendar_birthday_adressbooks', array())) ? $source['id'] : '';
        $sources[] = html::label(null, $checkbox->show($active, array('value' => $source['id'])) . '&nbsp;' . rcube::Q($source['realname'] ?: $source['name']));
      }

      $p['blocks']['birthdays']['options']['birthday_adressbooks'] = array(
        'title'   => rcube::Q($this->gettext('birthdayscalendarsources')),
        'content' => join(html::br(), $sources),
      );

      $field_id = 'rcmfd_birthdays_alarm';
      $select_type = new html_select(array('name' => '_birthdays_alarm_type', 'id' => $field_id) + $input_attrib);
      $select_type->add($this->gettext('none'), '');
      foreach ($this->get_default_driver()->alarm_types as $type) { // TODO: Replace with dedicated birthday calendar as soon as it is available
        $select_type->add(rcube_label(strtolower("alarm{$type}option"), 'libcalendaring'), $type);
      }

      $input_value = new html_inputfield(array('name' => '_birthdays_alarm_value', 'id' => $field_id . 'value', 'size' => 3) + $input_attrib);
      $select_offset = new html_select(array('name' => '_birthdays_alarm_offset', 'id' => $field_id . 'offset') + $input_attrib);
      foreach (array('-M','-H','-D') as $trigger)
        $select_offset->add(rcube_label('trigger' . $trigger, 'libcalendaring'), $trigger);

      $preset = libcalendaring::parse_alarm_value($this->rc->config->get('calendar_birthdays_alarm_offset', '-1D'));
      $p['blocks']['birthdays']['options']['birthdays_alarmoffset'] = array(
        'title' => html::label($field_id . 'value', rcube::Q($this->gettext('showalarms'))),
        'content' => $select_type->show($this->rc->config->get('calendar_birthdays_alarm_type', '')) . ' ' . $input_value->show($preset[0]) . '&nbsp;' . $select_offset->show($preset[1]),
      );
    }

    return $p;
  }

  /**
   * Handler for preferences_save hook.
   * Executed on Calendar settings form submit.
   *
   * @param array Original parameters
   * @return array Modified parameters
   */
  function preferences_save($p)
  {
    if ($p['section'] == 'calendar') {

      // compose default alarm preset value
      $alarm_offset  = rcube_utils::get_input_value('_alarm_offset', rcube_utils::INPUT_POST);
      $alarm_value   = rcube_utils::get_input_value('_alarm_value', rcube_utils::INPUT_POST);
      $default_alarm = $alarm_offset[0] . intval($alarm_value) . $alarm_offset[1];

      $birthdays_alarm_offset = rcube_utils::get_input_value('_birthdays_alarm_offset', rcube_utils::INPUT_POST);
      $birthdays_alarm_value  = rcube_utils::get_input_value('_birthdays_alarm_value', rcube_utils::INPUT_POST);
      $birthdays_alarm_value  = $birthdays_alarm_offset[0] . intval($birthdays_alarm_value) . $birthdays_alarm_offset[1];

      $p['prefs'] = array(
        'calendar_default_view' => rcube_utils::get_input_value('_default_view', rcube_utils::INPUT_POST),
        'calendar_timeslots'    => intval(rcube_utils::get_input_value('_timeslots', rcube_utils::INPUT_POST)),
        'calendar_first_day'    => intval(rcube_utils::get_input_value('_first_day', rcube_utils::INPUT_POST)),
        'calendar_first_hour'   => intval(rcube_utils::get_input_value('_first_hour', rcube_utils::INPUT_POST)),
        'calendar_work_start'   => intval(rcube_utils::get_input_value('_work_start', rcube_utils::INPUT_POST)),
        'calendar_work_end'     => intval(rcube_utils::get_input_value('_work_end', rcube_utils::INPUT_POST)),
        'calendar_event_coloring'       => intval(rcube_utils::get_input_value('_event_coloring', rcube_utils::INPUT_POST)),
        'calendar_default_alarm_type'   => rcube_utils::get_input_value('_alarm_type', rcube_utils::INPUT_POST),
        'calendar_default_alarm_offset' => $default_alarm,
        'calendar_default_calendar'     => rcube_utils::get_input_value('_default_calendar', rcube_utils::INPUT_POST),
        'calendar_date_format' => null,  // clear previously saved values
        'calendar_time_format' => null,
        'calendar_contact_birthdays'    => rcube_utils::get_input_value('_contact_birthdays', rcube_utils::INPUT_POST) ? true : false,
        'calendar_birthday_adressbooks' => (array) rcube_utils::get_input_value('_birthday_adressbooks', rcube_utils::INPUT_POST),
        'calendar_birthdays_alarm_type'   => rcube_utils::get_input_value('_birthdays_alarm_type', rcube_utils::INPUT_POST),
        'calendar_birthdays_alarm_offset' => $birthdays_alarm_value ?: null,
        'calendar_itip_after_action'      => intval(rcube_utils::get_input_value('_after_action', rcube_utils::INPUT_POST)),
      );

      if ($p['prefs']['calendar_itip_after_action'] == 4) {
        $p['prefs']['calendar_itip_after_action'] = rcube_utils::get_input_value('_after_action_folder', rcube_utils::INPUT_POST, true);
      }

      // categories
      foreach($this->get_drivers() as $driver) {
        if (!$driver->nocategories) {
          $old_categories = $new_categories = array();
          foreach ($driver->list_categories() as $name => $color) {
            $old_categories[md5($name)] = $name;
          }

          $categories = (array)rcube_utils::get_input_value('_categories', rcube_utils::INPUT_POST);
          $colors = (array)rcube_utils::get_input_value('_colors', rcube_utils::INPUT_POST);

          foreach ($categories as $key => $name) {
            $color = preg_replace('/^#/', '', strval($colors[$key]));

            // rename categories in existing events -> driver's job
            if ($oldname = $old_categories[$key]) {
              $driver->replace_category($oldname, $name, $color);
              unset($old_categories[$key]);
            } else
              $driver->add_category($name, $color);

            $new_categories[$name] = $color;
          }

          // these old categories have been removed, alter events accordingly -> driver's job
          foreach ((array)$old_categories[$key] as $key => $name) {
            $driver->remove_category($name);
          }

          $p['prefs']['calendar_categories'] = $new_categories;
        }
      }
    }

    return $p;
  }

  /**
   * Dispatcher for calendar actions initiated by the client
   */
  function calendar_action()
  {
    $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC);
    $cal    = rcube_utils::get_input_value('c', rcube_utils::INPUT_GPC);
    $success = $reload = false;
    $driver = null;

    if (isset($cal['showalarms']))
      $cal['showalarms'] = intval($cal['showalarms']);

    switch ($action) {
      case "form-new":
      case "form-edit":
        echo $this->ui->calendar_editform($action, $cal);
        exit;
      case "new":
        $driver = $this->get_driver_by_gpc();
        $success = $driver->create_calendar($cal);
        $reload = true;
        break;
      case "edit":
        $driver = $this->get_driver_by_cal($cal['id']);
        $success = $driver->edit_calendar($cal);
        $reload = true;
        break;
      case "delete":
        $driver = $this->get_driver_by_cal($cal['id']);
        if ($success = $driver->delete_calendar($cal))
          $this->rc->output->command('plugin.destroy_source', array('id' => $cal['id']));
        break;
      case "subscribe":
        $driver = $this->get_driver_by_cal($cal['id']);
        if (!$driver->subscribe_calendar($cal))
          $this->rc->output->show_message($this->gettext('errorsaving'), 'error');
        return;
      case "search":
        $results    = array();
        $color_mode = $this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']);
        $query      = rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC);
        $source     = rcube_utils::get_input_value('source', rcube_utils::INPUT_GPC);

        $search_more_results = false;
        foreach($this->get_drivers() as $driver) {
          foreach ((array)$driver->search_calendars($query, $source) as $id => $prop) {
            $editname = $prop['editname'];
            unset($prop['editname']);  // force full name to be displayed
            $prop['active'] = false;

            // let the UI generate HTML and CSS representation for this calendar
            $html = $this->ui->calendar_list_item($id, $prop, $jsenv);
            $cal = $jsenv[$id];
            $cal['editname'] = $editname;
            $cal['html'] = $html;
            if (!empty($prop['color']))
              $cal['css'] = $this->ui->calendar_css_classes($id, $prop, $color_mode);

            $results[] = $cal;
          }

          $search_more_results |= $driver->search_more_results;
        }

        // report more results available
        if ($search_more_results)
          $this->rc->output->show_message('autocompletemore', 'info');

        $this->rc->output->command('multi_thread_http_response', $results, rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC));
        return;
    }
    
    if ($success)
      $this->rc->output->show_message('successfullysaved', 'confirmation');
    else {
      $error_msg = $this->gettext('errorsaving') . ($driver && $driver->last_error ? ': ' . $driver->last_error :'');
      $this->rc->output->show_message($error_msg, 'error');
    }

    $this->rc->output->command('plugin.unlock_saving');

    if ($success && $reload)
      $this->rc->output->command('plugin.reload_view');
  }
  
  
  /**
   * Dispatcher for event actions initiated by the client
   */
  function event_action()
  {
    $action = rcube_utils::get_input_value('action', rcube_utils::INPUT_GPC);
    $event  = rcube_utils::get_input_value('e', rcube_utils::INPUT_POST, true);
    $success = $reload = $got_msg = false;

    $driver = null;
    if($event['calendar'])
      $driver = $this->get_driver_by_cal($event['calendar']);

    // This can happen if creating a new event outside the calendar e.g. from an ical file attached to an email.
    if(!$driver)
      $driver = $this->get_default_driver();

    // force notify if hidden + active
    if ((int)$this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']) === 1)
      $event['_notify'] = 1;

    // read old event data in order to find changes
    if (($event['_notify'] || $event['_decline']) && $action != 'new') {
      $old = $this->driver->get_event($event);

    // Support event moving across different drivers
    if(isset($event["_fromcalendar"]) && $event["_fromcalendar"] != $event["calendar"]) {
      $fromdriver = $this->get_driver_by_cal($event["_fromcalendar"]);
      if(get_class($fromdriver) != get_class($driver)) {
        $fromevent = $event;
        $fromevent["calendar"] = $event["_fromcalendar"];
        if($fromdriver->remove_event($fromevent))
          $action = "new";
      }
    }

      // load main event if savemode is 'all' or if deleting 'future' events
      if (($event['_savemode'] == 'all' || ($event['_savemode'] == 'future' && $action == 'remove' && !$event['_decline'])) && $old['recurrence_id']) {
        $old['id'] = $old['recurrence_id'];
        $old = $this->driver->get_event($old);
      }
    }

    switch ($action) {
      case "new":
        // create UID for new event
        $event['uid'] = $this->generate_uid();
        $this->write_preprocess($event, $action);
        if ($success = $driver->new_event($event)) {
          $event['id'] = $event['uid'];
          $event['_savemode'] = 'all';
          $this->cleanup_event($event);
          $this->event_save_success($event, null, $action, true);
        }
        $reload = $success && $event['recurrence'] ? 2 : 1;
        break;
        
      case "edit":
        $this->write_preprocess($event, $action);
        if ($success = $driver->edit_event($event)) {
          $this->cleanup_event($event);
          $this->event_save_success($event, $old, $action, $success);
        }
        $reload = $success && ($event['recurrence'] || $event['_savemode'] || $event['_fromcalendar']) ? 2 : 1;
        break;
      
      case "resize":
        $this->write_preprocess($event, $action);
        if ($success = $driver->resize_event($event)) {
          $this->event_save_success($event, $old, $action, $success);
        }
        $reload = $event['_savemode'] ? 2 : 1;
        break;
      
      case "move":
        $this->write_preprocess($event, $action);
        if ($success = $driver->move_event($event)) {
          $this->event_save_success($event, $old, $action, $success);
        }
        $reload  = $success && $event['_savemode'] ? 2 : 1;
        break;
      
      case "remove":
        // remove previous deletes
        $undo_time = $driver->undelete ? $this->rc->config->get('undo_timeout', 0) : 0;
        $this->rc->session->remove('calendar_event_undo');
        
        // search for event if only UID is given
        if (!isset($event['calendar']) && $event['uid']) {
          if (!($event = $driver->get_event($event, calendar_driver::FILTER_WRITEABLE))) {
            break;
          }
          $undo_time = 0;
        }

        $success = $driver->remove_event($event, $undo_time < 1);
        $reload = (!$success || $event['_savemode']) ? 2 : 1;

        if ($undo_time > 0 && $success) {
          $_SESSION['calendar_event_undo'] = array('ts' => time(), 'data' => $event);
          // display message with Undo link.
          $msg = html::span(null, $this->gettext('successremoval'))
            . ' ' . html::a(array('onclick' => sprintf("%s.http_request('event', 'action=undo', %s.display_message('', 'loading'))",
              JS_OBJECT_NAME, JS_OBJECT_NAME)), rcube_label('undo'));
          $this->rc->output->show_message($msg, 'confirmation', null, true, $undo_time);
          $got_msg = true;
        }
        else if ($success) {
          $this->rc->output->show_message('calendar.successremoval', 'confirmation');
          $got_msg = true;
        }

        // send cancellation for the main event
        if ($event['_savemode'] == 'all') {
          unset($old['_instance'], $old['recurrence_date'], $old['recurrence_id']);
        }
        // send an update for the main event's recurrence rule instead of a cancellation message
        else if ($event['_savemode'] == 'future' && $success !== false && $success !== true) {
          $event['_savemode'] = 'all';  // force event_save_success() to load master event
          $action = 'edit';
          $success = true;
        }

        // send iTIP reply that participant has declined the event
        if ($success && $event['_decline']) {
          $emails = $this->get_user_emails();
          foreach ($old['attendees'] as $i => $attendee) {
            if ($attendee['role'] == 'ORGANIZER')
              $organizer = $attendee;
            else if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
              $old['attendees'][$i]['status'] = 'DECLINED';
              $reply_sender = $attendee['email'];
            }
          }

          if ($event['_savemode'] == 'future' && $event['id'] != $old['id']) {
            $old['thisandfuture'] = true;
          }

          $itip = $this->load_itip();
          $itip->set_sender_email($reply_sender);
          if ($organizer && $itip->send_itip_message($old, 'REPLY', $organizer, 'itipsubjectdeclined', 'itipmailbodydeclined'))
            $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation');
          else
            $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
        }
        else if ($success) {
          $this->event_save_success($event, $old, $action, $success);
        }
        break;

      case "undo":
        // Restore deleted event
        $event  = $_SESSION['calendar_event_undo']['data'];

        if ($event)
          $success = $driver->restore_event($event);

        if ($success) {
          $this->rc->session->remove('calendar_event_undo');
          $this->rc->output->show_message('calendar.successrestore', 'confirmation');
          $got_msg = true;
          $reload = 2;
        }

        break;

      case "rsvp":
        $itip_sending  = $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);
        $status        = rcube_utils::get_input_value('status', rcube_utils::INPUT_POST);
        $attendees     = rcube_utils::get_input_value('attendees', rcube_utils::INPUT_POST);
        $reply_comment = $event['comment'];

        $this->write_preprocess($event, 'edit');
        $ev = $driver->get_event($event);
        $ev['attendees'] = $event['attendees'];
        $ev['free_busy'] = $event['free_busy'];
        $ev['_savemode'] = $event['_savemode'];

        // send invitation to delegatee + add it as attendee
        if ($status == 'delegated' && $event['to']) {
          $itip = $this->load_itip();
          if ($itip->delegate_to($ev, $event['to'], (bool)$event['rsvp'], $attendees)) {
            $this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
            $noreply = false;
          }
        }

        $event = $ev;

        // compose a list of attendees affected by this change
        $updated_attendees = array_filter(array_map(function($j) use ($event) {
          return $event['attendees'][$j];
        }, $attendees));

        if ($success = $driver->edit_rsvp($event, $status, $updated_attendees)) {
          $noreply = rcube_utils::get_input_value('noreply', rcube_utils::INPUT_GPC);
          $noreply = intval($noreply) || $status == 'needs-action' || $itip_sending === 0;
          $reload  = $event['calendar'] != $ev['calendar'] || $event['recurrence'] ? 2 : 1;
          $organizer = null;
          $emails = $this->get_user_emails();

          foreach ($event['attendees'] as $i => $attendee) {
            if ($attendee['role'] == 'ORGANIZER') {
              $organizer = $attendee;
            }
            else if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
              $reply_sender = $attendee['email'];
            }
          }

          if (!$noreply) {
            $itip = $this->load_itip();
            $itip->set_sender_email($reply_sender);
            $event['comment'] = $reply_comment;
            $event['thisandfuture'] = $event['_savemode'] == 'future';
            if ($organizer && $itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status))
              $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation');
            else
              $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
          }

          // refresh all calendars
          if ($event['calendar'] != $ev['calendar']) {
            $this->rc->output->command('plugin.refresh_calendar', array('source' => null, 'refetch' => true));
            $reload = 0;
          }
        }
        break;

      case "dismiss":
        $event['ids'] = explode(',', $event['id']);
        $plugin = $this->rc->plugins->exec_hook('dismiss_alarms', $event);
        $success = $plugin['success'];
        foreach ($event['ids'] as $id) {
          if (strpos($id, 'cal:') === 0)
            $success |= $driver->dismiss_alarm(substr($id, 4), $event['snooze']);
        }
        break;

      case "changelog":
        $data = $driver->get_event_changelog($event);
        if (is_array($data) && !empty($data)) {
          $lib = $this->lib;
          $dtformat = $this->rc->config->get('date_format') . ' ' . $this->rc->config->get('time_format');
          array_walk($data, function(&$change) use ($lib, $dtformat) {
            if ($change['date']) {
              $dt = $lib->adjust_timezone($change['date']);
              if ($dt instanceof DateTime)
                $change['date'] = $this->rc->format_date($dt, $dtformat, false);
            }
          });
          $this->rc->output->command('plugin.render_event_changelog', $data);
        }
        else {
          $this->rc->output->command('plugin.render_event_changelog', false);
        }
        $got_msg = true;
        $reload = false;
        break;

      case "diff":
        $data = $driver->get_event_diff($event, $event['rev1'], $event['rev2']);
        if (is_array($data)) {
          // convert some properties, similar to self::_client_event()
          $lib = $this->lib;
          array_walk($data['changes'], function(&$change, $i) use ($event, $lib) {
            // convert date cols
            foreach (array('start','end','created','changed') as $col) {
              if ($change['property'] == $col) {
                $change['old'] = $lib->adjust_timezone($change['old'], strlen($change['old']) == 10)->format('c');
                $change['new'] = $lib->adjust_timezone($change['new'], strlen($change['new']) == 10)->format('c');
              }
            }
            // create textual representation for alarms and recurrence
            if ($change['property'] == 'alarms') {
              if (is_array($change['old']))
                $change['old_'] = libcalendaring::alarm_text($change['old']);
              if (is_array($change['new']))
                $change['new_'] = libcalendaring::alarm_text(array_merge((array)$change['old'], $change['new']));
            }
            if ($change['property'] == 'recurrence') {
              if (is_array($change['old']))
                $change['old_'] = $lib->recurrence_text($change['old']);
              if (is_array($change['new']))
                $change['new_'] = $lib->recurrence_text(array_merge((array)$change['old'], $change['new']));
            }
            if ($change['property'] == 'attachments') {
              if (is_array($change['old']))
                $change['old']['classname'] = rcube_utils::file2class($change['old']['mimetype'], $change['old']['name']);
              if (is_array($change['new']))
                $change['new']['classname'] = rcube_utils::file2class($change['new']['mimetype'], $change['new']['name']);
            }
            // compute a nice diff of description texts
            if ($change['property'] == 'description') {
              $change['diff_'] = libkolab::html_diff($change['old'], $change['new']);
            }
          });
          $this->rc->output->command('plugin.event_show_diff', $data);
        }
        else {
          $this->rc->output->command('display_message', $this->gettext('objectdiffnotavailable'), 'error');
        }
        $got_msg = true;
        $reload = false;
        break;

      case "show":
        if ($event = $driver->get_event_revison($event, $event['rev'])) {
          $this->rc->output->command('plugin.event_show_revision', $this->_client_event($event));
        }
        else {
          $this->rc->output->command('display_message', $this->gettext('objectnotfound'), 'error');
        }
        $got_msg = true;
        $reload = false;
        break;

      case "restore":
        if ($success = $driver->restore_event_revision($event, $event['rev'])) {
          $_event = $driver->get_event($event);
          $reload = $_event['recurrence'] ? 2 : 1;
          $this->rc->output->command('display_message', $this->gettext(array('name' => 'objectrestoresuccess', 'vars' => array('rev' => $event['rev']))), 'confirmation');
          $this->rc->output->command('plugin.close_history_dialog');
        }
        else {
          $this->rc->output->command('display_message', $this->gettext('objectrestoreerror'), 'error');
          $reload = 0;
        }
        $got_msg = true;
        break;
    }

    // show confirmation/error message
    if (!$got_msg) {
      if ($success)
        $this->rc->output->show_message('successfullysaved', 'confirmation');
      else
        $this->rc->output->show_message('calendar.errorsaving', 'error');
    }

    // unlock client
    $this->rc->output->command('plugin.unlock_saving');

    // update event object on the client or trigger a complete refretch if too complicated
    if ($reload) {
      $args = array('source' => $event['calendar']);
      if ($reload > 1)
        $args['refetch'] = true;
      else if ($success && $action != 'remove')
        $args['update'] = $this->_client_event($driver->get_event($event), true);
      $this->rc->output->command('plugin.refresh_calendar', $args);
    }
  }

  /**
   * Helper method sending iTip notifications after successful event updates
   */
  private function event_save_success(&$event, $old, $action, $success)
  {
    // $success is a new event ID
    if ($success !== true) {
      // send update notification on the main event
      if ($event['_savemode'] == 'future' && $event['_notify'] && $old['attendees'] && $old['recurrence_id']) {
        $master = $this->driver->get_event(array('id' => $old['recurrence_id'], 'calendar' => $old['calendar']), 0, true);
        unset($master['_instance'], $master['recurrence_date']);

        $sent = $this->notify_attendees($master, null, $action, $event['_comment']);
        if ($sent < 0)
          $this->rc->output->show_message('calendar.errornotifying', 'error');

        $event['attendees'] = $master['attendees'];  // this tricks us into the next if clause
      }

      // delete old reference if saved as new
      if ($event['_savemode'] == 'future' || $event['_savemode'] == 'new') {
        $old = null;
      }

      $event['id'] = $success;
      $event['_savemode'] = 'all';
    }

    // send out notifications
    if ($event['_notify'] && ($event['attendees'] || $old['attendees'])) {
      $_savemode = $event['_savemode'];

      // send notification for the main event when savemode is 'all'
      if ($action != 'remove' && $_savemode == 'all' && ($event['recurrence_id'] || $old['recurrence_id'] || ($old && $old['id'] != $event['id']))) {
        $event['id'] = $event['recurrence_id'] ?: ($old['recurrence_id'] ?: $old['id']);
        $event = $this->driver->get_event($event, 0, true);
        unset($event['_instance'], $event['recurrence_date']);
      }
      else {
        // make sure we have the complete record
        $event = $action == 'remove' ? $old : $this->driver->get_event($event, 0, true);
      }

      $event['_savemode'] = $_savemode;

      if ($old) {
        $old['thisandfuture'] = $_savemode == 'future';
      }

      // only notify if data really changed (TODO: do diff check on client already)
      if (!$old || $action == 'remove' || self::event_diff($event, $old)) {
        $sent = $this->notify_attendees($event, $old, $action, $event['_comment']);
        if ($sent > 0)
          $this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
        else if ($sent < 0)
          $this->rc->output->show_message('calendar.errornotifying', 'error');
      }
    }
  }

  /**
   * Handler for load-requests from fullcalendar
   * This will return pure JSON formatted output
   */
  function load_events()
  {
    $events = $this->get_driver_by_gpc()->load_events(
      rcube_utils::get_input_value('start', rcube_utils::INPUT_GET),
      rcube_utils::get_input_value('end', rcube_utils::INPUT_GET),
      ($query = rcube_utils::get_input_value('q', rcube_utils::INPUT_GET)),
      rcube_utils::get_input_value('source', rcube_utils::INPUT_GET)
    );
    echo $this->encode($events, !empty($query));
    exit;
  }

  /**
   * Handler for requests fetching event counts for calendars
   */
  public function count_events()
  {
    // don't update session on these requests (avoiding race conditions)
    $this->rc->session->nowrite = true;

    $start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GET);
    if (!$start) {
      $start = new DateTime('today 00:00:00', $this->timezone);
      $start = $start->format('U');
    }

    $counts = 0;
    foreach($this->get_drivers() as $driver) {
      $counts += $driver->count_events(
        rcube_utils::get_input_value('source', rcube_utils::INPUT_GET),
        $start,
        rcube_utils::get_input_value('end', rcube_utils::INPUT_GET)
      );
    }

    $this->rc->output->command('plugin.update_counts', array('counts' => $counts));
  }

  /**
   * Load event data from an iTip message attachment
   */
  public function itip_events($msgref)
  {
    $path = explode('/', $msgref);
    $msg = array_pop($path);
    $mbox = join('/', $path);
    list($uid, $mime_id) = explode('#', $msg);
    $events = array();

    if ($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event')) {
      $partstat = 'NEEDS-ACTION';
/*
      $user_emails = $this->lib->get_user_emails();
      foreach ($event['attendees'] as $attendee) {
        if (in_array($attendee['email'], $user_emails)) {
          $partstat = $attendee['status'];
          break;
        }
      }
*/
      $event['id'] = $event['uid'];
      $event['temporary'] = true;
      $event['readonly'] = true;
      $event['calendar'] = '--invitation--itip';
      $event['className'] = 'fc-invitation-' . strtolower($partstat);
      $event['_mbox'] = $mbox;
      $event['_uid']  = $uid;
      $event['_part'] = $mime_id;

      $events[] = $this->_client_event($event, true);

      // add recurring instances
      if (!empty($event['recurrence'])) {
        foreach ($this->driver->get_recurring_events($event, $event['start']) as $recurring) {
          $recurring['temporary'] = true;
          $recurring['readonly'] = true;
          $recurring['calendar'] = '--invitation--itip';
          $events[] = $this->_client_event($recurring, true);
        }
      }
    }

    return $events;
  }

  /**
   * Handler for keep-alive requests
   * This will check for updated data in active calendars and sync them to the client
   */
  public function refresh($attr)
  {
     // refresh the entire calendar every 10th time to also sync deleted events
    if (rand(0,10) == 10) {
        $this->rc->output->command('plugin.refresh_calendar', array('refetch' => true));
        return;
    }

    $counts = array();

    foreach($this->get_drivers() as $driver) {
      foreach ($driver->list_calendars(calendar_driver::FILTER_ACTIVE) as $cal) {
        $events = $driver->load_events(
          rcube_utils::get_input_value('start', rcube_utils::INPUT_GPC),
          rcube_utils::get_input_value('end', rcube_utils::INPUT_GPC),
          rcube_utils::get_input_value('q', rcube_utils::INPUT_GPC),
          $cal['id'],
          1,
          $attr['last']
        );

        foreach ($events as $event) {
          $this->rc->output->command('plugin.refresh_calendar',
            array('source' => $cal['id'], 'update' => $this->_client_event($event)));
        }

        // refresh count for this calendar
        if ($cal['counts']) {
          $today = new DateTime('today 00:00:00', $this->timezone);
          $counts += $driver->count_events($cal['id'], $today->format('U'));
        }
      }
    }

    if (!empty($counts)) {
      $this->rc->output->command('plugin.update_counts', array('counts' => $counts));
    }
  }

  /**
   * Handler for pending_alarms plugin hook triggered by the calendar module on keep-alive requests.
   * This will check for pending notifications and pass them to the client
   */
  public function pending_alarms($p)
  {
    $time = $p['time'] ?: time();
    foreach($this->get_drivers() as $driver) {
      if ($alarms = $driver->pending_alarms($time)) {
        foreach ($alarms as $alarm) {
          $alarm['id'] = 'cal:' . $alarm['id'];  // prefix ID with cal:
          $p['alarms'][] = $alarm;
        }
      }
    }

    // get alarms for birthdays calendar
    if ($this->rc->config->get('calendar_contact_birthdays') && $this->rc->config->get('calendar_birthdays_alarm_type') == 'DISPLAY') {
      $cache = $this->rc->get_cache('calendar.birthdayalarms', 'db');

      // TODO: Use dedicated birthday calendar as soon as it exists
      foreach ($this->get_default_driver()->load_birthday_events($time, $time + 86400 * 60) as $e) {
        $alarm = libcalendaring::get_next_alarm($e);

        // overwrite alarm time with snooze value (or null if dismissed)
        if ($dismissed = $cache->get($e['id']))
          $alarm['time'] = $dismissed['notifyat'];

        // add to list if alarm is set
        if ($alarm && $alarm['time'] && $alarm['time'] <= $time) {
          $e['id'] = 'cal:bday:' . $e['id'];
          $e['notifyat'] = $alarm['time'];
          $p['alarms'][] = $e;
        }
      }
    }

    return $p;
  }

  /**
   * Handler for alarm dismiss hook triggered by libcalendaring
   */
  public function dismiss_alarms($p)
  {
    foreach($this->get_drivers() as $driver) { // TODO: Maybe use get_driver_by_cal() ?
      foreach ((array)$p['ids'] as $id) { 
        if (strpos($id, 'cal:bday:') === 0) {
          $p['success'] |= $driver->dismiss_birthday_alarm(substr($id, 9), $p['snooze']);
        } else if (strpos($id, 'cal:') === 0) {
          $p['success'] |= $driver->dismiss_alarm(substr($id, 4), $p['snooze']);
        }
      }
    }

    return $p;
  }

  /**
   * Handler for check-recent requests which are accidentally sent to calendar taks
   */
  function check_recent()
  {
    // NOP
    $this->rc->output->send();
  }

  /**
   * Hook triggered when a contact is saved
   */
  function contact_update($p)
  {
    // clear birthdays calendar cache
    if (!empty($p['record']['birthday'])) {
      $cache = $this->rc->get_cache('calendar.birthdays', 'db');
      $cache->remove();
    }
  }

    /**
     *
     */
    function import_events()
    {
      // Upload progress update
      if (!empty($_GET['_progress'])) {
        rcube_upload_progress();
      }

      @set_time_limit(0);

      // process uploaded file if there is no error
      $err = $_FILES['_data']['error'];

      if (!$err && $_FILES['_data']['tmp_name']) {
        $calendar   = rcube_utils::get_input_value('calendar', rcube_utils::INPUT_GPC);
        $rangestart = $_REQUEST['_range'] ? date_create("now -" . intval($_REQUEST['_range']) . " months") : 0;

        // extract zip file
        if ($_FILES['_data']['type'] == 'application/zip') {
          $count = 0;
          if (class_exists('ZipArchive', false)) {
            $zip = new ZipArchive();
            if ($zip->open($_FILES['_data']['tmp_name'])) {
              $randname = uniqid('zip-' . session_id(), true);
              $tmpdir = slashify($this->rc->config->get('temp_dir', sys_get_temp_dir())) . $randname;
              mkdir($tmpdir, 0700);

              // extract each ical file from the archive and import it
              for ($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                if (preg_match('/\.ics$/i', $filename)) {
                  $tmpfile = $tmpdir . '/' . basename($filename);
                  if (copy('zip://' . $_FILES['_data']['tmp_name'] . '#'.$filename, $tmpfile)) {
                    $count += $this->import_from_file($tmpfile, $calendar, $rangestart, $errors);
                    unlink($tmpfile);
                  }
                }
              }

              rmdir($tmpdir);
              $zip->close();
            }
            else {
              $errors = 1;
              $msg = 'Failed to open zip file.';
            }
          }
          else {
            $errors = 1;
            $msg = 'Zip files are not supported for import.';
          }
        }
        else {
          // attempt to import teh uploaded file directly
          $count = $this->import_from_file($_FILES['_data']['tmp_name'], $calendar, $rangestart, $errors);
        }

        if ($count) {
          $this->rc->output->command('display_message', $this->gettext(array('name' => 'importsuccess', 'vars' => array('nr' => $count))), 'confirmation');
          $this->rc->output->command('plugin.import_success', array('source' => $calendar, 'refetch' => true));
        }
        else if (!$errors) {
          $this->rc->output->command('display_message', $this->gettext('importnone'), 'notice');
          $this->rc->output->command('plugin.import_success', array('source' => $calendar));
        }
        else {
          $this->rc->output->command('plugin.import_error', array('message' => $this->gettext('importerror') . ($msg ? ': ' . $msg : '')));
        }
      }
      else {
        if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
          $msg = rcube_label(array('name' => 'filesizeerror', 'vars' => array(
            'size' => show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
        }
        else {
          $msg = rcube_label('fileuploaderror');
        }

        $this->rc->output->command('plugin.import_error', array('message' => $msg));
      }

      $this->rc->output->send('iframe');
    }

  /**
   * Helper function to parse and import a single .ics file
   */
  private function import_from_file($filepath, $calendar, $rangestart, &$errors)
  {
    $user_email = $this->rc->user->get_username();

    $ical = $this->get_ical();
    $errors = !$ical->fopen($filepath);
    $count = $i = 0;
    $driver = $this->get_driver_by_cal($calendar);
    foreach ($ical as $event) {
      // keep the browser connection alive on long import jobs
      if (++$i > 100 && $i % 100 == 0) {
          echo "<!-- -->";
          ob_flush();
      }

      // TODO: correctly handle recurring events which start before $rangestart
      if ($event['end'] < $rangestart && (!$event['recurrence'] || ($event['recurrence']['until'] && $event['recurrence']['until'] < $rangestart)))
        continue;

      $event['_owner'] = $user_email;
      $event['calendar'] = $calendar;
      if ($driver->new_event($event)) {
        $count++;
      }
      else {
        $errors++;
      }
    }

    return $count;
  }

  /**
   * Construct the ics file for exporting events to iCalendar format;
   */
  function export_events($terminate = true)
  {
    $start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GET);
    $end   = rcube_utils::get_input_value('end', rcube_utils::INPUT_GET);

    if (!isset($start))
      $start = 'today -1 year';
    if (!is_numeric($start))
      $start = strtotime($start . ' 00:00:00');
    if (!$end)
      $end = 'today +10 years';
    if (!is_numeric($end))
      $end = strtotime($end . ' 23:59:59');

    $event_id    = rcube_utils::get_input_value('id', rcube_utils::INPUT_GET);
    $attachments = rcube_utils::get_input_value('attachments', rcube_utils::INPUT_GET);
    $calid = $filename = rcube_utils::get_input_value('source', rcube_utils::INPUT_GET);
    $driver = $this->get_driver_by_cal($calid);
    $calendars = $this->driver->list_calendars();
    $events = array();

    if ($calendars[$calid]) {
      $filename = $calendars[$calid]['name'] ? $calendars[$calid]['name'] : $calid;
      $filename = asciiwords(html_entity_decode($filename));  // to 7bit ascii
      if (!empty($event_id)) {
        if ($event = $driver->get_event(array('calendar' => $calid, 'id' => $event_id), 0, true)) {
          if ($event['recurrence_id']) {
            $event = $driver->get_event(array('calendar' => $calid, 'id' => $event['recurrence_id']), 0, true);
          }
          $events = array($event);
          $filename = asciiwords($event['title']);
          if (empty($filename))
            $filename = 'event';
        }
      }
      else {
        $events = $driver->load_events($start, $end, null, $calid, 0);
        if (empty($filename))
          $filename = $calid;
      }
    }

    header("Content-Type: text/calendar");
    header("Content-Disposition: inline; filename=".$filename.'.ics');

    $this->get_ical()->export($events, '', true, $attachments ? array($driver, 'get_attachment_body') : null);

    if ($terminate)
      exit;
  }

  /**
   * Handler for iCal feed requests
   */
  function ical_feed_export()
  {
    $session_exists = !empty($_SESSION['user_id']);

    // process HTTP auth info
    if (!empty($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
      $_POST['_user'] = $_SERVER['PHP_AUTH_USER']; // used for rcmail::autoselect_host()
      $auth = $this->rc->plugins->exec_hook('authenticate', array(
        'host' => $this->rc->autoselect_host(),
        'user' => trim($_SERVER['PHP_AUTH_USER']),
        'pass' => $_SERVER['PHP_AUTH_PW'],
        'cookiecheck' => true,
        'valid' => true,
      ));
      if ($auth['valid'] && !$auth['abort'])
        $this->rc->login($auth['user'], $auth['pass'], $auth['host']);
    }

    // require HTTP auth
    if (empty($_SESSION['user_id'])) {
      header('WWW-Authenticate: Basic realm="Roundcube Calendar"');
      header('HTTP/1.0 401 Unauthorized');
      exit;
    }

    // decode calendar feed hash
    $format = 'ics';
    $calhash = rcube_utils::get_input_value('_cal', rcube_utils::INPUT_GET);
    if (preg_match(($suff_regex = '/\.([a-z0-9]{3,5})$/i'), $calhash, $m)) {
      $format = strtolower($m[1]);
      $calhash = preg_replace($suff_regex, '', $calhash);
    }

    if (!strpos($calhash, ':'))
      $calhash = base64_decode($calhash);

    list($user, $_GET['source']) = explode(':', $calhash, 2);

    // sanity check user
    if ($this->rc->user->get_username() == $user) {
      $this->export_events(false);
    }
    else {
      header('HTTP/1.0 404 Not Found');
    }

    // don't save session data
    if (!$session_exists)
      session_destroy();
    exit;
  }


  /**
   *
   */
  function load_settings()
  {
    $this->lib->load_settings();
    $this->defaults += $this->lib->defaults;

    $settings = array();

    // configuration
    $settings['default_calendar'] = $this->rc->config->get('calendar_default_calendar');
    $settings['default_view'] = (string)$this->rc->config->get('calendar_default_view', $this->defaults['calendar_default_view']);
    $settings['date_agenda'] = (string)$this->rc->config->get('calendar_date_agenda', $this->defaults['calendar_date_agenda']);

    $settings['timeslots'] = (int)$this->rc->config->get('calendar_timeslots', $this->defaults['calendar_timeslots']);
    $settings['first_day'] = (int)$this->rc->config->get('calendar_first_day', $this->defaults['calendar_first_day']);
    $settings['first_hour'] = (int)$this->rc->config->get('calendar_first_hour', $this->defaults['calendar_first_hour']);
    $settings['work_start'] = (int)$this->rc->config->get('calendar_work_start', $this->defaults['calendar_work_start']);
    $settings['work_end'] = (int)$this->rc->config->get('calendar_work_end', $this->defaults['calendar_work_end']);
    $settings['agenda_range'] = (int)$this->rc->config->get('calendar_agenda_range', $this->defaults['calendar_agenda_range']);
    $settings['agenda_sections'] = $this->rc->config->get('calendar_agenda_sections', $this->defaults['calendar_agenda_sections']);
    $settings['event_coloring'] = (int)$this->rc->config->get('calendar_event_coloring', $this->defaults['calendar_event_coloring']);
    $settings['time_indicator'] = (int)$this->rc->config->get('calendar_time_indicator', $this->defaults['calendar_time_indicator']);
    $settings['invite_shared'] = (int)$this->rc->config->get('calendar_allow_invite_shared', $this->defaults['calendar_allow_invite_shared']);
    $settings['invitation_calendars'] = (bool)$this->rc->config->get('kolab_invitation_calendars', false);
    $settings['itip_notify'] = (int)$this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);

    // get user identity to create default attendee
    if ($this->ui->screen == 'calendar') {
      $identity = null;
      foreach ($this->rc->user->list_emails() as $rec) {
        if (!$identity)
          $identity = $rec;
        $identity['emails'][] = $rec['email'];
        $settings['identities'][$rec['identity_id']] = $rec['email'];
      }
      $identity['emails'][] = $this->rc->user->get_username();
      $settings['identity'] = array('name' => $identity['name'], 'email' => strtolower($identity['email']), 'emails' => ';' . strtolower(join(';', $identity['emails'])));
    }

    return $settings;
  }

  /**
   * Encode events as JSON
   *
   * @param  array  Events as array
   * @param  boolean Add CSS class names according to calendar and categories
   * @return string JSON encoded events
   */
  function encode($events, $addcss = false)
  {
    $json = array();
    foreach ($events as $event) {
      $json[] = $this->_client_event($event, $addcss);
    }
    return json_encode($json);
  }

  /**
   * Convert an event object to be used on the client
   */
  private function _client_event($event, $addcss = false)
  {
    // compose a human readable strings for alarms_text and recurrence_text
    if ($event['valarms']) {
      $event['alarms_text'] = libcalendaring::alarms_text($event['valarms']);
      $event['valarms'] = libcalendaring::to_client_alarms($event['valarms']);
    }
    if ($event['recurrence']) {
      $event['recurrence_text'] = $this->lib->recurrence_text($event['recurrence']);
      $event['recurrence'] = $this->lib->to_client_recurrence($event['recurrence'], $event['allday']);
      unset($event['recurrence_date']);
    }

    foreach ((array)$event['attachments'] as $k => $attachment) {
      $event['attachments'][$k]['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']);
    }

    // Get driver for event calendar
    $driver = $this->get_driver_by_cal($event['calendar']);

    // convert link URIs references into structs
    if (array_key_exists('links', $event)) {
      foreach ((array)$event['links'] as $i => $link) {
        if (strpos($link, 'imap://') === 0 && ($msgref = $driver->get_message_reference($link))) {
          $event['links'][$i] = $msgref;
        }
      }
    }

    // check for organizer in attendees list
    $organizer = null;
    foreach ((array)$event['attendees'] as $i => $attendee) {
      if ($attendee['role'] == 'ORGANIZER') {
        $organizer = $attendee;
      }
      if ($attendee['status'] == 'DELEGATED' && $attendee['rsvp'] == false) {
        $event['attendees'][$i]['noreply'] = true;
      }
      else {
        unset($event['attendees'][$i]['noreply']);
      }
    }

    if ($organizer === null && !empty($event['organizer'])) {
      $organizer = $event['organizer'];
      $organizer['role'] = 'ORGANIZER';
      if (!is_array($event['attendees']))
        $event['attendees'] = array();
      array_unshift($event['attendees'], $organizer);
    }

    // mapping url => vurl because of the fullcalendar client script
    $event['vurl'] = $event['url'];
    unset($event['url']);

    return array(
      '_id'   => $event['calendar'] . ':' . $event['id'],  // unique identifier for fullcalendar
      'start' => $this->lib->adjust_timezone($event['start'], $event['allday'])->format('c'),
      'end'   => $this->lib->adjust_timezone($event['end'], $event['allday'])->format('c'),
      // 'changed' might be empty for event recurrences (Bug #2185)
      'changed' => $event['changed'] ? $this->lib->adjust_timezone($event['changed'])->format('c') : null,
      'created' => $event['created'] ? $this->lib->adjust_timezone($event['created'])->format('c') : null,
      'title'       => strval($event['title']),
      'description' => strval($event['description']),
      'location'    => strval($event['location']),
      'className'   => ($addcss ? 'fc-event-cal-'.asciiwords($event['calendar'], true).' ' : '') .
          'fc-event-cat-' . asciiwords(strtolower(join('-', (array)$event['categories'])), true) .
          rtrim(' ' . $event['className']),
      'allDay'      => ($event['allday'] == 1),
    ) + $event;
  }


  /**
   * Generate a unique identifier for an event
   */
  public function generate_uid()
  {
    return strtoupper(md5(time() . uniqid(rand())) . '-' . substr(md5($this->rc->user->get_username()), 0, 16));
  }


  /**
   * TEMPORARY: generate random event data for testing
   * Create events by opening http://<roundcubeurl>/?_task=calendar&_action=randomdata&_driver=kolab&_num=500&_date=2014-08-01&_dev=120
   */
  public function generate_randomdata()
  {
    @set_time_limit(0);

    $driver = $this->get_driver_by_gpc();
    $num   = $_REQUEST['_num'] ? intval($_REQUEST['_num']) : 100;
    $date  = $_REQUEST['_date'] ?: 'now';
    $dev   = $_REQUEST['_dev'] ?: 30;
    $cats  = array_keys($driver->list_categories());
    $cals  = $driver->list_calendars(calendar_driver::FILTER_ACTIVE);
    $count = 0;

    while ($count++ < $num) {
      $spread = intval($dev) * 86400; // days
      $refdate = strtotime($date);
      $start = round(($refdate + rand(-$spread, $spread)) / 600) * 600;
      $duration = round(rand(30, 360) / 30) * 30 * 60;
      $allday = rand(0,20) > 18;
      $alarm = rand(-30,12) * 5;
      $fb = rand(0,2);
      
      if (date('G', $start) > 23)
        $start -= 3600;
      
      if ($allday) {
        $start = strtotime(date('Y-m-d 00:00:00', $start));
        $duration = 86399;
      }
      
      $title = '';
      $len = rand(2, 12);
      $words = explode(" ", "The Hough transform is named after Paul Hough who patented the method in 1962. It is a technique which can be used to isolate features of a particular shape within an image. Because it requires that the desired features be specified in some parametric form, the classical Hough transform is most commonly used for the de- tection of regular curves such as lines, circles, ellipses, etc. A generalized Hough transform can be employed in applications where a simple analytic description of a feature(s) is not possible. Due to the computational complexity of the generalized Hough algorithm, we restrict the main focus of this discussion to the classical Hough transform. Despite its domain restrictions, the classical Hough transform (hereafter referred to without the classical prefix ) retains many applications, as most manufac- tured parts (and many anatomical parts investigated in medical imagery) contain feature boundaries which can be described by regular curves. The main advantage of the Hough transform technique is that it is tolerant of gaps in feature boundary descriptions and is relatively unaffected by image noise.");
//      $chars = "!# abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890";
      for ($i = 0; $i < $len; $i++)
        $title .= $words[rand(0,count($words)-1)] . " ";
      
      $driver->new_event(array(
        'uid' => $this->generate_uid(),
        'start' => new DateTime('@'.$start),
        'end' => new DateTime('@'.($start + $duration)),
        'allday' => $allday,
        'title' => rtrim($title),
        'free_busy' => $fb == 2 ? 'outofoffice' : ($fb ? 'busy' : 'free'),
        'categories' => $cats[array_rand($cats)],
        'calendar' => array_rand($cals),
        'alarms' => $alarm > 0 ? "-{$alarm}M:DISPLAY" : '',
        'priority' => rand(0,9),
      ));
    }
    
    $this->rc->output->redirect('');
  }

  /**
   * Handler for attachments upload
   */
  public function attachment_upload()
  {
    $this->lib->attachment_upload(self::SESSION_KEY, 'cal-');
  }

  /**
   * Handler for attachments download/displaying
   */
  public function attachment_get()
  {
    // show loading page
    if (!empty($_GET['_preload'])) {
        return $this->lib->attachment_loading_page();
    }

    $event_id = rcube_utils::get_input_value('_event', rcube_utils::INPUT_GPC);
    $calendar = rcube_utils::get_input_value('_cal', rcube_utils::INPUT_GPC);
    $id       = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
    $rev      = rcube_utils::get_input_value('_rev', rcube_utils::INPUT_GPC);
    $driver = $this->get_driver_by_cal($calendar);

    $event = array('id' => $event_id, 'calendar' => $calendar, 'rev' => $rev);
    $attachment = $driver->get_attachment($id, $event);

    // show part page
    if (!empty($_GET['_frame'])) {
        $this->lib->attachment = $attachment;
        $this->register_handler('plugin.attachmentframe', array($this->lib, 'attachment_frame'));
        $this->register_handler('plugin.attachmentcontrols', array($this->lib, 'attachment_header'));
        $this->rc->output->send('calendar.attachment');
    }
    // deliver attachment content
    else if ($attachment) {
        $attachment['body'] = $driver->get_attachment_body($id, $event);
        $this->lib->attachment_get($attachment);
    }

    // if we arrive here, the requested part was not found
    header('HTTP/1.1 404 Not Found');
    exit;
  }


  /**
   * Prepares new/edited event properties before save
   */
  private function write_preprocess(&$event, $action)
  {
    // convert dates into DateTime objects in user's current timezone
    $event['start'] = new DateTime($event['start'], $this->timezone);
    $event['end'] = new DateTime($event['end'], $this->timezone);
    $event['allday'] = (bool)$event['allday'];

    // start/end is all we need for 'move' action (#1480)
    if ($action == 'move') {
      return;
    }

    // convert the submitted recurrence settings
    if (is_array($event['recurrence'])) {
      $event['recurrence'] = $this->lib->from_client_recurrence($event['recurrence'], $event['start']);
    }

    // convert the submitted alarm values
    if ($event['valarms']) {
      $event['valarms'] = libcalendaring::from_client_alarms($event['valarms']);
    }

    $attachments = array();
    $eventid     = 'cal-'.$event['id'];

    if (is_array($_SESSION[self::SESSION_KEY]) && $_SESSION[self::SESSION_KEY]['id'] == $eventid) {
      if (!empty($_SESSION[self::SESSION_KEY]['attachments'])) {
        foreach ($_SESSION[self::SESSION_KEY]['attachments'] as $id => $attachment) {
          if (is_array($event['attachments']) && in_array($id, $event['attachments'])) {
            $attachments[$id] = $this->rc->plugins->exec_hook('attachment_get', $attachment);
          }
        }
      }
    }

    $event['attachments'] = $attachments;

    // convert link references into simple URIs
    if (array_key_exists('links', $event)) {
      $event['links'] = array_map(function($link) {
          return is_array($link) ? $link['uri'] : strval($link);
        }, (array)$event['links']);
    }

    // check for organizer in attendees
    if ($action == 'new' || $action == 'edit') {
      if (!$event['attendees'])
        $event['attendees'] = array();

      $emails = $this->get_user_emails();
      $organizer = $owner = false;
      foreach ((array)$event['attendees'] as $i => $attendee) {
        if ($attendee['role'] == 'ORGANIZER')
          $organizer = $i;
        if ($attendee['email'] == in_array(strtolower($attendee['email']), $emails))
          $owner = $i;
        if (!isset($attendee['rsvp']))
          $event['attendees'][$i]['rsvp'] = true;
        else if (is_string($attendee['rsvp']))
          $event['attendees'][$i]['rsvp'] = $attendee['rsvp'] == 'true' || $attendee['rsvp'] == '1';
      }

      // set new organizer identity
      if ($organizer !== false && !empty($event['_identity']) && ($identity = $this->rc->user->get_identity($event['_identity']))) {
        $event['attendees'][$organizer]['name'] = $identity['name'];
        $event['attendees'][$organizer]['email'] = $identity['email'];
      }

      // set owner as organizer if yet missing
      if ($organizer === false && $owner !== false) {
        $event['attendees'][$owner]['role'] = 'ORGANIZER';
        unset($event['attendees'][$owner]['rsvp']);
      }
    }

    // mapping url => vurl because of the fullcalendar client script
    if (array_key_exists('vurl', $event)) {
      $event['url'] = $event['vurl'];
      unset($event['vurl']);
    }
  }

  /**
   * Releases some resources after successful event save
   */
  private function cleanup_event(&$event)
  {
    // remove temp. attachment files
    if (!empty($_SESSION[self::SESSION_KEY]) && ($eventid = $_SESSION[self::SESSION_KEY]['id'])) {
      $this->rc->plugins->exec_hook('attachments_cleanup', array('group' => $eventid));
      $this->rc->session->remove(self::SESSION_KEY);
    }
  }

  /**
   * Send out an invitation/notification to all event attendees
   */
  private function notify_attendees($event, $old, $action = 'edit', $comment = null)
  {
    if ($action == 'remove' || ($event['status'] == 'CANCELLED' && $old['status'] != $event['status'])) {
      $event['cancelled'] = true;
      $is_cancelled = true;
    }

    $itip = $this->load_itip();
    $emails = $this->get_user_emails();
    $itip_notify = (int)$this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);

    // add comment to the iTip attachment
    $event['comment'] = $comment;

    // set a valid recurrence-id if this is a recurrence instance
    libcalendaring::identify_recurrence_instance($event);

    // compose multipart message using PEAR:Mail_Mime
    $method = $action == 'remove' ? 'CANCEL' : 'REQUEST';
    $message = $itip->compose_itip_message($event, $method, !$old || $event['sequence'] > $old['sequence']);

    // list existing attendees from $old event
    $old_attendees = array();
    foreach ((array)$old['attendees'] as $attendee) {
      $old_attendees[] = $attendee['email'];
    }

    // send to every attendee
    $sent = 0; $current = array();
    foreach ((array)$event['attendees'] as $attendee) {
      $current[] = strtolower($attendee['email']);
      
      // skip myself for obvious reasons
      if (!$attendee['email'] || in_array(strtolower($attendee['email']), $emails))
        continue;

      // skip if notification is disabled for this attendee
      if ($attendee['noreply'] && $itip_notify & 2)
        continue;

      // skip if this attendee has delegated and set RSVP=FALSE
      if ($attendee['status'] == 'DELEGATED' && $attendee['rsvp'] === false)
        continue;

      // which template to use for mail text
      $is_new = !in_array($attendee['email'], $old_attendees);
      $is_rsvp = $is_new || $event['sequence'] > $old['sequence'];
      $bodytext = $is_cancelled ? 'eventcancelmailbody' : ($is_new ? 'invitationmailbody' : 'eventupdatemailbody');
      $subject  = $is_cancelled ? 'eventcancelsubject'  : ($is_new ? 'invitationsubject' : ($event['title'] ? 'eventupdatesubject':'eventupdatesubjectempty'));

      $event['comment'] = $comment;

      // finally send the message
      if ($itip->send_itip_message($event, $method, $attendee, $subject, $bodytext, $message, $is_rsvp))
        $sent++;
      else
        $sent = -100;
    }

    // TODO: on change of a recurring (main) event, also send updates to differing attendess of recurrence exceptions

    // send CANCEL message to removed attendees
    foreach ((array)$old['attendees'] as $attendee) {
      if ($attendee['role'] == 'ORGANIZER' || !$attendee['email'] || in_array(strtolower($attendee['email']), $current))
        continue;

      $vevent = $old;
      $vevent['cancelled'] = $is_cancelled;
      $vevent['attendees'] = array($attendee);
      $vevent['comment']   = $comment;
      if ($itip->send_itip_message($vevent, 'CANCEL', $attendee, 'eventcancelsubject', 'eventcancelmailbody'))
        $sent++;
      else
        $sent = -100;
    }

    return $sent;
  }

  private function _get_freebusy_list($email, $start, $end)
  {
    $fblist = array();
    foreach($this->get_drivers() as $driver){
      if($driver->freebusy) {
        $cur = $driver->get_freebusy_list($email, $start, $end);
        if($cur) {
          $fblist = array_merge($fblist, $cur);
        }
      }
    }

    if(sizeof($fblist) == 0) return false;
    else return $fblist;
  }

  /**
   * Echo simple free/busy status text for the given user and time range
   */
  public function freebusy_status()
  {
    $email = rcube_utils::get_input_value('email', rcube_utils::INPUT_GPC);
    $start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GPC);
    $end   = rcube_utils::get_input_value('end', rcube_utils::INPUT_GPC);

    // convert dates into unix timestamps
    if (!empty($start) && !is_numeric($start)) {
      $dts = new DateTime($start, $this->timezone);
      $start = $dts->format('U');
    }
    if (!empty($end) && !is_numeric($end)) {
      $dte = new DateTime($end, $this->timezone);
      $end = $dte->format('U');
    }
    
    if (!$start) $start = time();
    if (!$end) $end = $start + 3600;
    
    $fbtypemap = array(calendar::FREEBUSY_UNKNOWN => 'UNKNOWN', calendar::FREEBUSY_FREE => 'FREE', calendar::FREEBUSY_BUSY => 'BUSY', calendar::FREEBUSY_TENTATIVE => 'TENTATIVE', calendar::FREEBUSY_OOF => 'OUT-OF-OFFICE');
    $status = 'UNKNOWN';
    
    // if the backend has free-busy information
    $fblist = $this->_get_freebusy_list($email, $start, $end);
    if (is_array($fblist)) {
      $status = 'FREE';
      
      foreach ($fblist as $slot) {
        list($from, $to, $type) = $slot;
        if ($from < $end && $to > $start) {
          $status = isset($type) && $fbtypemap[$type] ? $fbtypemap[$type] : 'BUSY';
          break;
        }
      }
    }
    
    // let this information be cached for 5min
    send_future_expire_header(300);
    
    echo $status;
    exit;
  }
  
  /**
   * Return a list of free/busy time slots within the given period
   * Echo data in JSON encoding
   */
  public function freebusy_times()
  {
    $email = rcube_utils::get_input_value('email', rcube_utils::INPUT_GPC);
    $start = rcube_utils::get_input_value('start', rcube_utils::INPUT_GPC);
    $end   = rcube_utils::get_input_value('end', rcube_utils::INPUT_GPC);
    $interval  = intval(rcube_utils::get_input_value('interval', rcube_utils::INPUT_GPC));
    $strformat = $interval > 60 ? 'Ymd' : 'YmdHis';

    // convert dates into unix timestamps
    if (!empty($start) && !is_numeric($start)) {
      $dts = rcube_utils::anytodatetime($start, $this->timezone);
      $start = $dts ? $dts->format('U') : null;
    }
    if (!empty($end) && !is_numeric($end)) {
      $dte = rcube_utils::anytodatetime($end, $this->timezone);
      $end = $dte ? $dte->format('U') : null;
    }

    if (!$start) $start = time();
    if (!$end)   $end = $start + 86400 * 30;
    if (!$interval) $interval = 60;  // 1 hour
    
    if (!$dte) {
      $dts = new DateTime('@'.$start);
      $dts->setTimezone($this->timezone);
    }
    
    $fblist = $this->_get_freebusy_list($email, $start, $end);
    $slots = array();
    
    // build a list from $start till $end with blocks representing the fb-status
    for ($s = 0, $t = $start; $t <= $end; $s++) {
      $status = self::FREEBUSY_UNKNOWN;
      $t_end = $t + $interval * 60;
      $dt = new DateTime('@'.$t);
      $dt->setTimezone($this->timezone);

      // determine attendee's status
      if (is_array($fblist)) {
        $status = self::FREEBUSY_FREE;
        foreach ($fblist as $slot) {
          list($from, $to, $type) = $slot;

          // check for possible all-day times
          if (gmdate('His', $from) == '000000' && gmdate('His', $to) == '235959') {
              // shift into the user's timezone for sane matching
              $from -= $this->gmt_offset;
              $to   -= $this->gmt_offset;
          }

          if ($from < $t_end && $to > $t) {
            $status = isset($type) ? $type : self::FREEBUSY_BUSY;
            if ($status == self::FREEBUSY_BUSY)  // can't get any worse :-)
              break;
          }
        }
      }
      
      $slots[$s] = $status;
      $times[$s] = intval($dt->format($strformat));
      $t = $t_end;
    }
    
    $dte = new DateTime('@'.$t_end);
    $dte->setTimezone($this->timezone);
    
    // let this information be cached for 5min
    send_future_expire_header(300);
    
    echo json_encode(array(
      'email' => $email,
      'start' => $dts->format('c'),
      'end'   => $dte->format('c'),
      'interval' => $interval,
      'slots' => $slots,
      'times' => $times,
    ));
    exit;
  }

  /**
   * Handler for printing calendars
   */
  public function print_view()
  {
    $title = $this->gettext('print');

    $view = rcube_utils::get_input_value('view', rcube_utils::INPUT_GPC);
    if (!in_array($view, array('agendaWeek', 'agendaDay', 'month', 'table')))
      $view = 'agendaDay';

    $this->rc->output->set_env('view',$view);

    if ($date = rcube_utils::get_input_value('date', rcube_utils::INPUT_GPC))
      $this->rc->output->set_env('date', $date);

    if ($range = rcube_utils::get_input_value('range', rcube_utils::INPUT_GPC))
      $this->rc->output->set_env('listRange', intval($range));

    if (isset($_REQUEST['sections']))
      $this->rc->output->set_env('listSections', rcube_utils::get_input_value('sections', rcube_utils::INPUT_GPC));

    if ($search = rcube_utils::get_input_value('search', rcube_utils::INPUT_GPC)) {
      $this->rc->output->set_env('search', $search);
      $title .= ' "' . $search . '"';
    }

    // Add CSS stylesheets to the page header
    $skin_path = $this->local_skin_path();
    $this->include_stylesheet($skin_path . '/fullcalendar.css');
    $this->include_stylesheet($skin_path . '/print.css');
    
    // Add JS files to the page header
    $this->include_script('print.js');
    $this->include_script('lib/js/fullcalendar.js');
    
    $this->register_handler('plugin.calendar_css', array($this->ui, 'calendar_css'));
    $this->register_handler('plugin.calendar_list', array($this->ui, 'calendar_list'));
    
    $this->rc->output->set_pagetitle($title);
    $this->rc->output->send("calendar.print");
  }

  /**
   *
   */
  public function get_inline_ui()
  {
    foreach (array('save','cancel','savingdata') as $label)
      $texts['calendar.'.$label] = $this->gettext($label);
    
    $texts['calendar.new_event'] = $this->gettext('createfrommail');
    
    $this->ui->init_templates();
    $this->ui->calendar_list();  # set env['calendars']
    echo $this->api->output->parse('calendar.eventedit', false, false);
    echo html::tag('script', array('type' => 'text/javascript'),
      "rcmail.set_env('calendars', " . json_encode($this->api->output->env['calendars']) . ");\n".
      "rcmail.set_env('deleteicon', '" . $this->api->output->env['deleteicon'] . "');\n".
      "rcmail.set_env('cancelicon', '" . $this->api->output->env['cancelicon'] . "');\n".
      "rcmail.set_env('loadingicon', '" . $this->api->output->env['loadingicon'] . "');\n".
      "rcmail.gui_object('attachmentlist', '"  . $this->ui->attachmentlist_id . "');\n".
      "rcmail.add_label(" . json_encode($texts) . ");\n"
    );
    exit;
  }

  /**
   * Compare two event objects and return differing properties
   *
   * @param array Event A
   * @param array Event B
   * @return array List of differing event properties
   */
  public static function event_diff($a, $b)
  {
    $diff = array();
    $ignore = array('changed' => 1, 'attachments' => 1);
    foreach (array_unique(array_merge(array_keys($a), array_keys($b))) as $key) {
      if (!$ignore[$key] && $key[0] != '_' && $a[$key] != $b[$key])
        $diff[] = $key;
    }
    
    // only compare number of attachments
    if (count($a['attachments']) != count($b['attachments']))
      $diff[] = 'attachments';
    
    return $diff;
  }

  /**
   * Update attendee properties on the given event object
   *
   * @param array The event object to be altered
   * @param array List of hash arrays each represeting an updated/added attendee
   */
  public static function merge_attendee_data(&$event, $attendees, $removed = null)
  {
    if (!empty($attendees) && !is_array($attendees[0])) {
      $attendees = array($attendees);
    }

    foreach ($attendees as $attendee) {
      $found = false;

      foreach ($event['attendees'] as $i => $candidate) {
        if ($candidate['email'] == $attendee['email']) {
          $event['attendees'][$i] = $attendee;
          $found = true;
          break;
        }
      }

      if (!$found) {
        $event['attendees'][] = $attendee;
      }
    }

    // filter out removed attendees
    if (!empty($removed)) {
      $event['attendees'] = array_filter($event['attendees'], function($attendee) use ($removed) {
        return !in_array($attendee['email'], $removed);
      });
    }
  }


  /****  Resource management functions  ****/

  /**
   * Getter for the configured implementation of the resource directory interface
   */
  private function resources_directory()
  {
    if (is_object($this->resources_dir)) {
      return $this->resources_dir;
    }

    if ($driver_name = $this->rc->config->get('calendar_resources_driver')) {
      $driver_class = 'resources_driver_' . $driver_name;

      require_once($this->home . '/drivers/resources_driver.php');
      require_once($this->home . '/drivers/' . $driver_name . '/' . $driver_class . '.php');

      $this->resources_dir = new $driver_class($this);
    }

    return $this->resources_dir;
  }

  /**
   * Handler for resoruce autocompletion requests
   */
  public function resources_autocomplete()
  {
    $search = rcube_utils::get_input_value('_search', rcube_utils::INPUT_GPC, true);
    $sid    = rcube_utils::get_input_value('_reqid', rcube_utils::INPUT_GPC);
    $maxnum = (int)$this->rc->config->get('autocomplete_max', 15);
    $results = array();

    if ($directory = $this->resources_directory()) {
      foreach ($directory->load_resources($search, $maxnum) as $rec) {
        $results[]  = array(
            'name'  => $rec['name'],
            'email' => $rec['email'],
            'type'  => $rec['_type'],
        );
      }
    }

    $this->rc->output->command('ksearch_query_results', $results, $search, $sid);
    $this->rc->output->send();
  }

  /**
   * Handler for load-requests for resource data
   */
  function resources_list()
  {
    $data = array();

    if ($directory = $this->resources_directory()) {
      foreach ($directory->load_resources() as $rec) {
        $data[] = $rec;
      }
    }

    $this->rc->output->command('plugin.resource_data', $data);
    $this->rc->output->send();
  }

  /**
   * Handler for requests loading resource owner information
   */
  function resources_owner()
  {
    if ($directory = $this->resources_directory()) {
      $id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
      $data = $directory->get_resource_owner($id);
    }

    $this->rc->output->command('plugin.resource_owner', $data);
    $this->rc->output->send();
  }

  /**
   * Deliver event data for a resource's calendar
   */
  function resources_calendar()
  {
    $events = array();

    if ($directory = $this->resources_directory()) {
      $events = $directory->get_resource_calendar(
        rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC),
        rcube_utils::get_input_value('start', rcube_utils::INPUT_GET),
        rcube_utils::get_input_value('end', rcube_utils::INPUT_GET));
    }

    echo $this->encode($events);
    exit;
  }


  /****  Event invitation plugin hooks ****/

  /**
   * Handler for calendar/itip-status requests
   */
  function event_itip_status()
  {
    $data = rcube_utils::get_input_value('data', rcube_utils::INPUT_POST, true);

    // find local copy of the referenced event
    $driver = null;

    if(isset($data["uid"]))
      $driver = $this->get_driver_by_event($data["uid"]);

    if($driver == null)
      $driver = $this->get_default_driver();

    $existing = $driver->get_event($data, calendar_driver::FILTER_WRITEABLE | calendar_driver::FILTER_PERSONAL);

    $itip = $this->load_itip();
    $response = $itip->get_itip_status($data, $existing);

    // get a list of writeable calendars to save new events to
    if (!$existing && !$data['nosave'] && $response['action'] == 'rsvp' || $response['action'] == 'import') {
      $calendars = $driver->list_calendars(calendar_driver::FILTER_PERSONAL);
      $calendar_select = new html_select(array('name' => 'calendar', 'id' => 'itip-saveto', 'is_escaped' => true));
      $calendar_select->add('--', '');
      $numcals = 0;
      foreach ($calendars as $calendar) {
        if ($calendar['editable']) {
          $calendar_select->add($calendar['name'], $calendar['id']);
          $numcals++;
        }
      }
      if ($numcals <= 1)
        $calendar_select = null;
    }

    if ($calendar_select) {
      $default_calendar = $this->get_default_calendar($data['sensitivity']);
      $response['select'] = html::span('folder-select', $this->gettext('saveincalendar') . '&nbsp;' .
        $calendar_select->show($default_calendar['id']));
    }
    else if ($data['nosave']) {
      $response['select'] = html::tag('input', array('type' => 'hidden', 'name' => 'calendar', 'id' => 'itip-saveto', 'value' => ''));
    }

    // render small agenda view for the respective day
    if ($data['method'] == 'REQUEST' && !empty($data['date']) && $response['action'] == 'rsvp') {
      $event_start = rcube_utils::anytodatetime($data['date']);
      $day_start = new Datetime(gmdate('Y-m-d 00:00', $data['date']), $this->lib->timezone);
      $day_end = new Datetime(gmdate('Y-m-d 23:59', $data['date']), $this->lib->timezone);

      // get events on that day from the user's personal calendars
      $calendars = $driver->list_calendars(calendar_driver::FILTER_PERSONAL);
      $events = $driver->load_events($day_start->format('U'), $day_end->format('U'), null, array_keys($calendars));
      usort($events, function($a, $b) { return $a['start'] > $b['start'] ? 1 : -1; });

      $before = $after = array();
      foreach ($events as $event) {
        // TODO: skip events with free_busy == 'free' ?
        if ($event['uid'] == $data['uid'] || $event['end'] < $day_start || $event['start'] > $day_end)
          continue;
        else if ($event['start'] < $event_start)
          $before[] = $this->mail_agenda_event_row($event);
        else
          $after[] = $this->mail_agenda_event_row($event);
      }

      $response['append'] = array(
        'selector' => '.calendar-agenda-preview',
        'replacements' => array(
          '%before%' => !empty($before) ? join("\n", array_slice($before,  -3)) : html::div('event-row no-event', $this->gettext('noearlierevents')),
          '%after%'  => !empty($after)  ? join("\n", array_slice($after, 0, 3)) : html::div('event-row no-event', $this->gettext('nolaterevents')),
        ),
      );
    }

    $this->rc->output->command('plugin.update_itip_object_status', $response);
  }

  /**
   * Handler for calendar/itip-remove requests
   */
  function event_itip_remove()
  {
    $success  = false;
    $uid      = rcube_utils::get_input_value('uid', rcube_utils::INPUT_POST);
    $instance = rcube_utils::get_input_value('_instance', rcube_utils::INPUT_POST);
    $savemode = rcube_utils::get_input_value('_savemode', rcube_utils::INPUT_POST);

    // search for event if only UID is given
    $driver = $this->get_driver_by_event($uid);
    if ($event = $driver->get_event(array('uid' => $uid, '_instance' => $instance), calendar_driver::FILTER_WRITEABLE)) {
      $event['_savemode'] = $savemode;
      $success = $driver->remove_event($event, true);
    }

    if ($success) {
      $this->rc->output->show_message('calendar.successremoval', 'confirmation');
    }
    else {
      $this->rc->output->show_message('calendar.errorsaving', 'error');
    }
  }

  /**
   * Handler for URLs that allow an invitee to respond on his invitation mail
   */
  public function itip_attend_response($p)
  {
    if ($p['action'] == 'attend') {
      $this->ui->init();

      $this->rc->output->set_env('task', 'calendar');  // override some env vars
      $this->rc->output->set_env('refresh_interval', 0);
      $this->rc->output->set_pagetitle($this->gettext('calendar'));

      $itip  = $this->load_itip();
      $token = rcube_utils::get_input_value('_t', rcube_utils::INPUT_GPC);

      // read event info stored under the given token
      if ($invitation = $itip->get_invitation($token)) {
        $this->token = $token;
        $this->event = $invitation['event'];

        // show message about cancellation
        if ($invitation['cancelled']) {
          $this->invitestatus = html::div('rsvp-status declined', $itip->gettext('eventcancelled'));
        }
        // save submitted RSVP status
        else if (!empty($_POST['rsvp'])) {
          $status = null;
          foreach (array('accepted','tentative','declined') as $method) {
            if ($_POST['rsvp'] == $itip->gettext('itip' . $method)) {
              $status = $method;
              break;
            }
          }

          // send itip reply to organizer
          $invitation['event']['comment'] = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);
          if ($status && $itip->update_invitation($invitation, $invitation['attendee'], strtoupper($status))) {
            $this->invitestatus = html::div('rsvp-status ' . strtolower($status), $itip->gettext('youhave'.strtolower($status)));
          }
          else
            $this->rc->output->command('display_message', $this->gettext('errorsaving'), 'error', -1);

          // if user is logged in...
          if ($this->rc->user->ID) {
            $invitation = $itip->get_invitation($token);
            $driver = $this->get_driver_by_cal($invitation['event']['calendar']);

            // save the event to his/her default calendar if not yet present
            if (!$driver->get_event($this->event) && ($calendar = $this->get_default_calendar($invitation['event']['sensitivity']))) {
              $invitation['event']['calendar'] = $calendar['id'];
              if ($driver->new_event($invitation['event']))
                $this->rc->output->command('display_message', $this->gettext(array('name' => 'importedsuccessfully', 'vars' => array('calendar' => $calendar['name']))), 'confirmation');
            }
          }
        }
        
        $this->register_handler('plugin.event_inviteform', array($this, 'itip_event_inviteform'));
        $this->register_handler('plugin.event_invitebox', array($this->ui, 'event_invitebox'));
        
        if (!$this->invitestatus) {
          $this->itip->set_rsvp_actions(array('accepted','tentative','declined'));
          $this->register_handler('plugin.event_rsvp_buttons', array($this->ui, 'event_rsvp_buttons'));
        }
        
        $this->rc->output->set_pagetitle($itip->gettext('itipinvitation') . ' ' . $this->event['title']);
      }
      else
        $this->rc->output->command('display_message', $this->gettext('itipinvalidrequest'), 'error', -1);
      
      $this->rc->output->send('calendar.itipattend');
    }
  }
  
  /**
   *
   */
  public function itip_event_inviteform($attrib)
  {
    $hidden = new html_hiddenfield(array('name' => "_t", 'value' => $this->token));
    return html::tag('form', array('action' => $this->rc->url(array('task' => 'calendar', 'action' => 'attend')), 'method' => 'post', 'noclose' => true) + $attrib) . $hidden->show();
  }

  /**
   * 
   */
  private function mail_agenda_event_row($event, $class = '')
  {
    $time = $event['allday'] ? $this->gettext('all-day') :
      $this->rc->format_date($event['start'], $this->rc->config->get('time_format')) . ' - ' .
        $this->rc->format_date($event['end'], $this->rc->config->get('time_format'));

    return html::div(rtrim('event-row ' . $class),
      html::span('event-date', $time) .
      html::span('event-title', Q($event['title']))
    );
  }
  
  /**
   * 
   */
  public function mail_messages_list($p)
  {
    if (in_array('attachment', (array)$p['cols']) && !empty($p['messages'])) {
      foreach ($p['messages'] as $header) {
        $part = new StdClass;
        $part->mimetype = $header->ctype;
        if (libcalendaring::part_is_vcalendar($part)) {
          $header->list_flags['attachmentClass'] = 'ical';
        }
        else if (in_array($header->ctype, array('multipart/alternative', 'multipart/mixed'))) {
          // TODO: fetch bodystructure and search for ical parts. Maybe too expensive?

          if (!empty($header->structure) && is_array($header->structure->parts)) {
            foreach ($header->structure->parts as $part) {
              if (libcalendaring::part_is_vcalendar($part) && !empty($part->ctype_parameters['method'])) {
                $header->list_flags['attachmentClass'] = 'ical';
                break;
              }
            }
          }
        }
      }
    }
  }

  /**
   * Add UI element to copy event invitations or updates to the calendar
   */
  public function mail_messagebody_html($p)
  {
    // load iCalendar functions (if necessary)
    if (!empty($this->lib->ical_parts)) {
      $this->get_ical();
      $this->load_itip();
    }

    $html = '';
    $has_events = false;
    $ical_objects = $this->lib->get_mail_ical_objects();

    // show a box for every event in the file
    foreach ($ical_objects as $idx => $event) {
      if ($event['_type'] != 'event')  // skip non-event objects (#2928)
        continue;

      $has_events = true;

      // get prepared inline UI for this event object
      if ($ical_objects->method) {
        $append = '';

        // prepare a small agenda preview to be filled with actual event data on async request
        if ($ical_objects->method == 'REQUEST') {
          $append = html::div('calendar-agenda-preview',
            html::tag('h3', 'preview-title', $this->gettext('agenda') . ' ' .
              html::span('date', $this->rc->format_date($event['start'], $this->rc->config->get('date_format')))
            ) . '%before%' . $this->mail_agenda_event_row($event, 'current') . '%after%');
        }

        $html .= html::div('calendar-invitebox',
          $this->itip->mail_itip_inline_ui(
            $event,
            $ical_objects->method,
            $ical_objects->mime_id . ':' . $idx,
            'calendar',
            rcube_utils::anytodatetime($ical_objects->message_date),
            $this->rc->url(array('task' => 'calendar')) . '&view=agendaDay&date=' . $event['start']->format('U')
          ) . $append
        );
      }

      // limit listing
      if ($idx >= 3)
        break;
    }

    // prepend event boxes to message body
    if ($html) {
      $this->ui->init();
      $p['content'] = $html . $p['content'];
      $this->rc->output->add_label('calendar.savingdata','calendar.deleteventconfirm','calendar.declinedeleteconfirm');
    }

    // add "Save to calendar" button into attachment menu
    if ($has_events) {
      $this->add_button(array(
        'id'         => 'attachmentsavecal',
        'name'       => 'attachmentsavecal',
        'type'       => 'link',
        'wrapper'    => 'li',
        'command'    => 'attachment-save-calendar',
        'class'      => 'icon calendarlink',
        'classact'   => 'icon calendarlink active',
        'innerclass' => 'icon calendar',
        'label'      => 'calendar.savetocalendar',
        ), 'attachmentmenu');
    }

    return $p;
  }


  /**
   * Handler for POST request to import an event attached to a mail message
   */
  public function mail_import_itip()
  {
    $itip_sending = $this->rc->config->get('calendar_itip_send_option', $this->defaults['calendar_itip_send_option']);

    $uid     = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
    $mbox    = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
    $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
    $status  = rcube_utils::get_input_value('_status', rcube_utils::INPUT_POST);
    $delete  = intval(rcube_utils::get_input_value('_del', rcube_utils::INPUT_POST));
    $noreply = intval(rcube_utils::get_input_value('_noreply', rcube_utils::INPUT_POST));
    $noreply = $noreply || $status == 'needs-action' || $itip_sending === 0;
    $instance = rcube_utils::get_input_value('_instance', rcube_utils::INPUT_POST);
    $savemode = rcube_utils::get_input_value('_savemode', rcube_utils::INPUT_POST);

    $error_msg = $this->gettext('errorimportingevent');
    $success = false;
    $delegate = null;

    if ($status == 'delegated') {
      $delegates = rcube_mime::decode_address_list(rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST, true), 1, false);
      $delegate  = reset($delegates);

      if (empty($delegate) || empty($delegate['mailto'])) {
        $this->rc->output->command('display_message', $this->gettext('libcalendaring.delegateinvalidaddress'), 'error');
        return;
      }
    }

    // successfully parsed events?
    if ($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event')) {
      // forward iTip request to delegatee
      if ($delegate) {
        $rsvpme = intval(rcube_utils::get_input_value('_rsvp', rcube_utils::INPUT_POST));

        $itip = $this->load_itip();
        if ($itip->delegate_to($event, $delegate, $rsvpme ? true : false)) {
          $this->rc->output->show_message('calendar.itipsendsuccess', 'confirmation');
        }
        else {
          $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
        }

        // the delegator is set to non-participant, thus save as non-blocking
        $event['free_busy'] = 'free';
      }

      // find writeable calendar to store event
      $cal_id = !empty($_REQUEST['_folder']) ? rcube_utils::get_input_value('_folder', rcube_utils::INPUT_POST) : null;

      $calendar = null;
      $driver = null;

      if($cal_id) {
        $driver = $this->get_driver_by_cal($cal_id);
        $calendars = $driver->list_calendars(false, true);
        $calendar = $calendars[$cal_id];
      }

      $dontsave = ($_REQUEST['_folder'] === '' && $event['_method'] == 'REQUEST');

      // select default calendar except user explicitly selected 'none'
      if (!$calendar && !$dontsave)
        $calendar = $this->get_default_calendar(true, $event['sensitivity'] == 'confidential');

      if(!$driver) {
        $driver = $this->get_driver_by_cal($calendar["id"]);
      }

      // select default calendar except user explicitly selected 'none'
      if (!$calendar && !$dontsave)
         $calendar = $this->get_default_calendar($event['sensitivity']);

      $metadata = array(
        'uid' => $event['uid'],
        '_instance' => $event['_instance'],
        'changed' => is_object($event['changed']) ? $event['changed']->format('U') : 0,
        'sequence' => intval($event['sequence']),
        'fallback' => strtoupper($status),
        'method' => $event['_method'],
        'task' => 'calendar',
      );

      // update my attendee status according to submitted method
      if (!empty($status)) {
        $organizer = null;
        $emails = $this->get_user_emails();
        foreach ($event['attendees'] as $i => $attendee) {
          if ($attendee['role'] == 'ORGANIZER') {
            $organizer = $attendee;
          }
          else if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
            $event['attendees'][$i]['status'] = strtoupper($status);
            if (!in_array($event['attendees'][$i]['status'], array('NEEDS-ACTION','DELEGATED')))
              $event['attendees'][$i]['rsvp'] = false;  // unset RSVP attribute

            $metadata['attendee'] = $attendee['email'];
            $metadata['rsvp'] = $attendee['role'] != 'NON-PARTICIPANT';
            $reply_sender = $attendee['email'];
            $event_attendee = $attendee;
          }
        }

        // add attendee with this user's default identity if not listed
        if (!$reply_sender) {
          $sender_identity = $this->rc->user->list_emails(true);
          $event['attendees'][] = array(
            'name' => $sender_identity['name'],
            'email' => $sender_identity['email'],
            'role' => 'OPT-PARTICIPANT',
            'status' => strtoupper($status),
          );
          $metadata['attendee'] = $sender_identity['email'];
        }
      }
      
      // save to calendar
      if ($calendar && $calendar['editable']) {
        // check for existing event with the same UID
        $existing = $driver->get_event($event, calendar_driver::FILTER_WRITEABLE | calendar_driver::FILTER_PERSONAL);

        if ($existing) {
          // forward savemode for correct updates of recurring events
          $existing['_savemode'] = $savemode ?: $event['_savemode'];

          // only update attendee status
          if ($event['_method'] == 'REPLY') {
            // try to identify the attendee using the email sender address
            $existing_attendee = -1;
            $existing_attendee_emails = array();
            foreach ($existing['attendees'] as $i => $attendee) {
              $existing_attendee_emails[] = $attendee['email'];
              if ($event['_sender'] && ($attendee['email'] == $event['_sender'] || $attendee['email'] == $event['_sender_utf'])) {
                $existing_attendee = $i;
              }
            }
            $event_attendee = null;
            $update_attendees = array();
            foreach ($event['attendees'] as $attendee) {
              if ($event['_sender'] && ($attendee['email'] == $event['_sender'] || $attendee['email'] == $event['_sender_utf'])) {
                $event_attendee = $attendee;
                $update_attendees[] = $attendee;
                $metadata['fallback'] = $attendee['status'];
                $metadata['attendee'] = $attendee['email'];
                $metadata['rsvp'] = $attendee['rsvp'] || $attendee['role'] != 'NON-PARTICIPANT';
                if ($attendee['status'] != 'DELEGATED') {
                  break;
                }
              }
              // also copy delegate attendee
              else if (!empty($attendee['delegated-from']) &&
                       (stripos($attendee['delegated-from'], $event['_sender']) !== false ||
                        stripos($attendee['delegated-from'], $event['_sender_utf']) !== false)) {
                $update_attendees[] = $attendee;
                if (!in_array($attendee['email'], $existing_attendee_emails)) {
                  $existing['attendees'][] = $attendee;
                }
              }
            }

            // if delegatee has declined, set delegator's RSVP=True
            if ($event_attendee && $event_attendee['status'] == 'DECLINED' && $event_attendee['delegated-from']) {
              foreach ($existing['attendees'] as $i => $attendee) {
                if ($attendee['email'] == $event_attendee['delegated-from']) {
                  $existing['attendees'][$i]['rsvp'] = true;
                  break;
                }
              }
            }

            // found matching attendee entry in both existing and new events
            if ($existing_attendee >= 0 && $event_attendee) {
              $existing['attendees'][$existing_attendee] = $event_attendee;
              $success = $driver->update_attendees($existing, $update_attendees);
            }
            // update the entire attendees block
            else if (($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed']) && $event_attendee) {
              $existing['attendees'][] = $event_attendee;
              $success = $driver->update_attendees($existing, $update_attendees);
            }
            else {
              $error_msg = $this->gettext('newerversionexists');
            }
          }
          // delete the event when declined (#1670)
          else if ($status == 'declined' && $delete) {
             $deleted = $driver->remove_event($existing, true);
             $success = true;
          }
          // import the (newer) event
          else if ($event['sequence'] >= $existing['sequence'] || $event['changed'] >= $existing['changed']) {
            $event['id'] = $existing['id'];
            $event['calendar'] = $existing['calendar'];

            // preserve my participant status for regular updates
            if (empty($status)) {
              $emails = $this->get_user_emails();
              foreach ($event['attendees'] as $i => $attendee) {
                if ($attendee['email'] && in_array(strtolower($attendee['email']), $emails)) {
                  foreach ($existing['attendees'] as $j => $_attendee) {
                    if ($attendee['email'] == $_attendee['email']) {
                      $event['attendees'][$i] = $existing['attendees'][$j];
                      break;
                    }
                  }
                }
              }
            }

            // set status=CANCELLED on CANCEL messages
            if ($event['_method'] == 'CANCEL')
              $event['status'] = 'CANCELLED';
            // show me as free when declined (#1670)
            if ($status == 'declined' || $event['status'] == 'CANCELLED' || $event_attendee['role'] == 'NON-PARTICIPANT')
              $event['free_busy'] = 'free';

            $success = $driver->edit_event($event);
          }
          else if (!empty($status)) {
            $existing['attendees'] = $event['attendees'];
            if ($status == 'declined' || $event_attendee['role'] == 'NON-PARTICIPANT')  // show me as free when declined (#1670)
              $existing['free_busy'] = 'free';
            $success = $driver->edit_event($existing);
          }
          else
            $error_msg = $this->gettext('newerversionexists');
        }
        else if (!$existing && ($status != 'declined' || $this->rc->config->get('kolab_invitation_calendars'))) {
          if ($status == 'declined' || $event['status'] == 'CANCELLED' || $event_attendee['role'] == 'NON-PARTICIPANT') {
            $event['free_busy'] = 'free';
          }

          // if the RSVP reply only refers to a single instance:
          // store unmodified master event with current instance as exception
          if (!empty($instance) && !empty($savemode) && $savemode != 'all') {
            $master = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event');
            if ($master['recurrence'] && !$master['_instance']) {
              // compute recurring events until this instance's date
              if ($recurrence_date = rcube_utils::anytodatetime($instance, $master['start']->getTimezone())) {
                $recurrence_date->setTime(23,59,59);

                foreach ($driver->get_recurring_events($master, $master['start'], $recurrence_date) as $recurring) {
                  if ($recurring['_instance'] == $instance) {
                    // copy attendees block with my partstat to exception
                    $recurring['attendees'] = $event['attendees'];
                    $master['recurrence']['EXCEPTIONS'][] = $recurring;
                    $event = $recurring;  // set reference for iTip reply
                    break;
                  }
                }

                $master['calendar'] = $event['calendar'] = $calendar['id'];
                $success = $driver->new_event($master);
              }
              else {
                $master = null;
              }
            }
            else {
              $master = null;
            }
          }

          // save to the selected/default calendar
          if (!$master) {
            $event['calendar'] = $calendar['id'];
            $success = $driver->new_event($event);
          }
        }
        else if ($status == 'declined')
          $error_msg = null;
      }
      else if ($status == 'declined' || $dontsave)
        $error_msg = null;
      else
        $error_msg = $this->gettext('nowritecalendarfound');
    }

    if ($success) {
      $message = $event['_method'] == 'REPLY' ? 'attendeupdateesuccess' : ($deleted ? 'successremoval' : ($existing ? 'updatedsuccessfully' : 'importedsuccessfully'));
      $this->rc->output->command('display_message', $this->gettext(array('name' => $message, 'vars' => array('calendar' => $calendar['name']))), 'confirmation');
    }

    if ($success || $dontsave) {
      $metadata['calendar'] = $event['calendar'];
      $metadata['nosave'] = $dontsave;
      $metadata['rsvp'] = intval($metadata['rsvp']);
      $metadata['after_action'] = $this->rc->config->get('calendar_itip_after_action', $this->defaults['calendar_itip_after_action']);
      $this->rc->output->command('plugin.itip_message_processed', $metadata);
      $error_msg = null;
    }
    else if ($error_msg) {
      $this->rc->output->command('display_message', $error_msg, 'error');
    }

    // send iTip reply
    if ($event['_method'] == 'REQUEST' && $organizer && !$noreply && !in_array(strtolower($organizer['email']), $emails) && !$error_msg) {
      $event['comment'] = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);
      $itip = $this->load_itip();
      $itip->set_sender_email($reply_sender);
      if ($itip->send_itip_message($event, 'REPLY', $organizer, 'itipsubject' . $status, 'itipmailbody' . $status))
        $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $organizer['name'] ? $organizer['name'] : $organizer['email']))), 'confirmation');
      else
        $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
    }

    $this->rc->output->send();
  }


  /**
   * Handler for calendar/itip-remove requests
   */
  function mail_itip_decline_reply()
  {
    $uid     = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
    $mbox    = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
    $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);

    if (($event = $this->lib->mail_get_itip_object($mbox, $uid, $mime_id, 'event')) && $event['_method'] == 'REPLY') {
      $event['comment'] = rcube_utils::get_input_value('_comment', rcube_utils::INPUT_POST);

      foreach ($event['attendees'] as $_attendee) {
        if ($_attendee['role'] != 'ORGANIZER') {
          $attendee = $_attendee;
          break;
        }
      }

      $itip = $this->load_itip();
      if ($itip->send_itip_message($event, 'CANCEL', $attendee, 'itipsubjectcancel', 'itipmailbodycancel'))
        $this->rc->output->command('display_message', $this->gettext(array('name' => 'sentresponseto', 'vars' => array('mailto' => $attendee['name'] ? $attendee['name'] : $attendee['email']))), 'confirmation');
      else
        $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
    }
    else {
      $this->rc->output->command('display_message', $this->gettext('itipresponseerror'), 'error');
    }
  }

  /**
   * Handler for calendar/itip-delegate requests
   */
  function mail_itip_delegate()
  {
    // forward request to mail_import_itip() with the right status
    $_POST['_status'] = $_REQUEST['_status'] = 'delegated';
    $this->mail_import_itip();
  }

  /**
   * Import the full payload from a mail message attachment
   */
  public function mail_import_attachment()
  {
    $uid     = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
    $mbox    = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
    $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
    $charset = RCMAIL_CHARSET;

    // establish imap connection
    $imap = $this->rc->get_storage();
    $imap->set_mailbox($mbox);

    if ($uid && $mime_id) {
      $part = $imap->get_message_part($uid, $mime_id);
      if ($part->ctype_parameters['charset'])
        $charset = $part->ctype_parameters['charset'];
//      $headers = $imap->get_message_headers($uid);

      if ($part) {
        $events = $this->get_ical()->import($part, $charset);
      }
    }

    $success = $existing = 0;
    if (!empty($events)) {
      // find writeable calendar to store event
      $cal_id = !empty($_REQUEST['_calendar']) ? rcube_utils::get_input_value('_calendar', rcube_utils::INPUT_POST) : null;
      $driver = null;
      if($cal_id) $driver = $this->get_driver_by_cal($cal_id);
      else $driver = $this->get_driver_by_gpc();
      $calendars = $driver->list_calendars(calendar_driver::FILTER_PERSONAL);

      foreach ($events as $event) {
        // save to calendar
        $calendar = $calendars[$cal_id] ?: $this->get_default_calendar($event['sensitivity']);
        if ($calendar && $calendar['editable'] && $event['_type'] == 'event') {
          $event['calendar'] = $calendar['id'];

          if (!$driver->get_event($event['uid'], calendar_driver::FILTER_WRITEABLE)) {
            $success += (bool)$driver->new_event($event);
          }
          else {
            $existing++;
          }
        }
      }
    }

    if ($success) {
      $this->rc->output->command('display_message', $this->gettext(array(
        'name' => 'importsuccess',
        'vars' => array('nr' => $success),
      )), 'confirmation');
    }
    else if ($existing) {
      $this->rc->output->command('display_message', $this->gettext('importwarningexists'), 'warning');
    }
    else {
      $this->rc->output->command('display_message', $this->gettext('errorimportingevent'), 'error');
    }
  }

  /**
   * Read email message and return contents for a new event based on that message
   */
  public function mail_message2event()
  {
    $uid   = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
    $mbox  = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
    $event = array();

    // establish imap connection
    $imap = $this->rc->get_storage();
    $imap->set_mailbox($mbox);
    $message = new rcube_message($uid);

    if ($message->headers) {
      $event['title'] = trim($message->subject);
      $event['description'] = trim($message->first_text_part());

      $driver = $this->get_default_driver();

      // add a reference to the email message
      if ($msgref = $driver->get_message_reference($message->headers, $mbox)) {
        $event['links'] = array($msgref);
      }
      // copy mail attachments to event
      else if ($message->attachments) {
        $eventid = 'cal-';
        if (!is_array($_SESSION[self::SESSION_KEY]) || $_SESSION[self::SESSION_KEY]['id'] != $eventid) {
          $_SESSION[self::SESSION_KEY] = array();
          $_SESSION[self::SESSION_KEY]['id'] = $eventid;
          $_SESSION[self::SESSION_KEY]['attachments'] = array();
        }

        foreach ((array)$message->attachments as $part) {
          $attachment = array(
            'data' => $imap->get_message_part($uid, $part->mime_id, $part),
            'size' => $part->size,
            'name' => $part->filename,
            'mimetype' => $part->mimetype,
            'group' => $eventid,
          );

          $attachment = $this->rc->plugins->exec_hook('attachment_save', $attachment);

          if ($attachment['status'] && !$attachment['abort']) {
            $id = $attachment['id'];
            $attachment['classname'] = rcube_utils::file2class($attachment['mimetype'], $attachment['name']);

            // store new attachment in session
            unset($attachment['status'], $attachment['abort'], $attachment['data']);
            $_SESSION[self::SESSION_KEY]['attachments'][$id] = $attachment;

            $attachment['id'] = 'rcmfile' . $attachment['id'];  // add prefix to consider it 'new'
            $event['attachments'][] = $attachment;
          }
        }
      }
      
      $this->rc->output->command('plugin.mail2event_dialog', $event);
    }
    else {
      $this->rc->output->command('display_message', $this->gettext('messageopenerror'), 'error');
    }
    
    $this->rc->output->send();
  }

  /**
   * Handler for the 'message_compose' plugin hook. This will check for
   * a compose parameter 'calendar_event' and create an attachment with the
   * referenced event in iCal format
   */
  public function mail_message_compose($args)
  {
    // set the submitted event ID as attachment
    if (!empty($args['param']['calendar_event'])) {
      list($cal, $id) = explode(':', $args['param']['calendar_event'], 2);
      $driver = $this->get_driver_by_cal($cal);
      if ($event = $driver->get_event(array('id' => $id, 'calendar' => $cal))) {
        $filename = asciiwords($event['title']);
        if (empty($filename))
          $filename = 'event';

        // save ics to a temp file and register as attachment
        $tmp_path = tempnam($this->rc->config->get('temp_dir'), 'rcmAttmntCal');
        file_put_contents($tmp_path, $this->get_ical()->export(array($event), '', false, array($driver, 'get_attachment_body')));

        $args['attachments'][] = array('path' => $tmp_path, 'name' => $filename . '.ics', 'mimetype' => 'text/calendar');
        $args['param']['subject'] = $event['title'];
      }
    }

    return $args;
  }


  /**
   * Get a list of email addresses of the current user (from login and identities)
   */
  public function get_user_emails()
  {
    return $this->lib->get_user_emails();
  }


  /**
   * Build an absolute URL with the given parameters
   */
  public function get_url($param = array())
  {
    $param += array('task' => 'calendar');
    return $this->rc->url($param, true, true);
  }


  public function ical_feed_hash($source)
  {
    return base64_encode($this->rc->user->get_username() . ':' . $source);
  }

  /**
   * Handler for user_delete plugin hook
   */
  public function user_delete($args)
  {
    // delete itipinvitations entries related to this user
    $db = $this->rc->get_dbh();
    $table_itipinvitations = $db->table_name('itipinvitations', true);
    $db->query("DELETE FROM $table_itipinvitations WHERE `user_id` = ?", $args['user']->ID);

    foreach($this->get_drivers() as $driver)
      if(!$driver->user_delete($args))
        return false;

     return true;
  }

  /**
   * Magic getter for public access to protected members
   */
  public function __get($name)
  {
    switch ($name) {
      case 'ical':
        return $this->get_ical();

      case 'itip':
        return $this->load_itip();

      case 'driver':
        $driver = $this->get_driver_by_gpc(true);
        if(!$driver) $driver = $this->get_default_driver();
        return $driver;
    }

    return null;
  }

}

© 2014-2024 Faster IT GmbH | imprint | privacy policy