File: Driver.php

package info (click to toggle)
kronolith2 2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 7,936 kB
  • ctags: 3,577
  • sloc: php: 14,001; xml: 1,494; sql: 489; makefile: 68
file content (2377 lines) | stat: -rw-r--r-- 79,908 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
<?php
/**
 * Kronolith_Driver defines an API for implementing storage backends for
 * Kronolith.
 *
 * $Horde: kronolith/lib/Driver.php,v 1.116.2.74 2008/04/02 08:42:42 wrobel Exp $
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jan Schneider <jan@horde.org>
 * @since   Kronolith 0.1
 * @package Kronolith
 */
class Kronolith_Driver {

    /**
     * A hash containing any parameters for the current driver.
     *
     * @var array
     */
    var $_params = array();

    /**
     * The current calendar.
     *
     * @var string
     */
    var $_calendar;

    /**
     * An error message to throw when something is wrong.
     *
     * @var string
     */
    var $_errormsg;

    /**
     * Constructor.
     *
     * Just stores the $params in our newly-created object. All other work is
     * done by {@link initialize()}.
     *
     * @param array $params  Any parameters needed for this driver.
     */
    function Kronolith_Driver($params = array(), $errormsg = null)
    {
        $this->_params = $params;
        if ($errormsg === null) {
            $this->_errormsg = _("The Calendar backend is not currently available.");
        } else {
            $this->_errormsg = $errormsg;
        }
    }

    function open($calendar)
    {
        $this->_calendar = $calendar;
    }

    /**
     * Returns the currently open calendar.
     *
     * @return string  The current calendar name.
     */
    function getCalendar()
    {
        return $this->_calendar;
    }

    /**
     * Generates a universal / unique identifier for a task.
     *
     * This is NOT something that we expect to be able to parse into a
     * calendar and an event id.
     *
     * @return string  A nice unique string (should be 255 chars or less).
     */
    function generateUID()
    {
        return date('YmdHis') . '.'
            . substr(str_pad(base_convert(microtime(), 10, 36), 16, uniqid(mt_rand()), STR_PAD_LEFT), -16)
            . '@' . $GLOBALS['conf']['server']['name'];
    }

    /**
     * Renames a calendar.
     *
     * @param string $from  The current name of the calendar.
     * @param string $to    The new name of the calendar.
     *
     * @return mixed  True or a PEAR_Error on failure.
     */
    function rename($from, $to)
    {
        return true;
    }

    /**
     * Searches a calendar.
     *
     * @param object Kronolith_Event $query  A Kronolith_Event object with the
     *                                       criteria to search for.
     *
     * @return mixed  An array of Kronolith_Events or a PEAR_Error.
     */
    function search($query)
    {
        /* Our default implementation first gets <em>all</em> events in a
         * specific period, and then filters based on the actual values that
         * are filled in. Drivers can optimize this behavior if they have the
         * ability. */
        $results = array();

        $events = &$this->listEvents($query->start, $query->end);
        if (is_a($events, 'PEAR_Error')) {
            return $events;
        }

        if (isset($query->start)) {
            $startTime = $query->start->timestamp();
        } else {
            $startTime = null;
        }

        if (isset($query->end)) {
            $endTime = $query->end->timestamp();
        } else {
            $endTime = null;
        }

        foreach ($events as $eventid) {
            $event = &$this->getEvent($eventid);
            if (is_a($event, 'PEAR_Error')) {
                return $event;
            }

            $evStartTime = $event->start->timestamp();
            $evEndTime = $event->end->timestamp();

            if (((($evEndTime > $startTime || !isset($startTime)) &&
                  ($evStartTime < $endTime || !isset($endTime))) ||
                 ($event->recurs() && $evEndTime >= $startTime && $evStartTime <= $endTime)) &&
                (empty($query->title) || stristr($event->getTitle(), $query->title)) &&
                (empty($query->location) || stristr($event->getLocation(), $query->location)) &&
                (empty($query->description) || stristr($event->getDescription(), $query->description)) &&
                (!isset($query->category) || $event->getCategory() == $query->category) &&
                (!isset($query->status) || $event->getStatus() == $query->status)) {
                $results[] = $event;
            }
        }

        return $results;
    }

    /**
     * Finds the next recurrence of $eventId that's after $afterDate.
     *
     * @param string $eventId        The ID of the event to fetch.
     * @param Horde_Date $afterDate  Return events after this date.
     *
     * @return Horde_Date|boolean  The date of the next recurrence or false if
     *                             the event does not recur after $afterDate.
     */
    function nextRecurrence($eventId, $afterDate)
    {
        $event = &$this->getEvent($eventId);
        if (is_a($event, 'PEAR_Error')) {
            return $event;
        }

        return $event->recurs() ? $event->recurrence->nextRecurrence($afterDate) : false;
    }

    /**
     * Attempts to return a concrete Kronolith_Driver instance based on
     * $driver.
     *
     * @param string $driver  The type of concrete Kronolith_Driver subclass
     *                        to return.
     *
     * @param array $params   A hash containing any additional configuration or
     *                        connection parameters a subclass might need.
     *
     * @return Kronolith_Driver  The newly created concrete Kronolith_Driver
     *                           instance, or a PEAR_Error on error.
     */
    function &factory($driver = null, $params = null)
    {
        if ($driver === null) {
            $driver = $GLOBALS['conf']['calendar']['driver'];
        }
        $driver = basename($driver);

        if ($params === null) {
            $params = Horde::getDriverConfig('calendar', $driver);
        }

        include_once dirname(__FILE__) . '/Driver/' . $driver . '.php';
        $class = 'Kronolith_Driver_' . $driver;
        if (class_exists($class)) {
            $driver = &new $class($params);
            $result = $driver->initialize();
            if (is_a($result, 'PEAR_Error')) {
                $driver = new Kronolith_Driver($params, sprintf(_("The Calendar backend is not currently available: %s"), $result->getMessage()));
            }
        } else {
            $driver = new Kronolith_Driver($params, sprintf(_("Unable to load the definition of %s."), $class));
        }

        return $driver;
    }

    /**
     * Stub to initiate a driver.
     */
    function initialize()
    {
        return true;
    }

    /**
     * Stub to be overridden in the child class.
     */
    function &getEvent()
    {
        $error = PEAR::raiseError($this->_errormsg);
        return $error;
    }

    /**
     * Stub to be overridden in the child class.
     */
    function listAlarms($date, $fullevent = false)
    {
        return PEAR::raiseError($this->_errormsg);
    }

    /**
     * Stub to be overridden in the child class.
     */
    function listEvents()
    {
        return PEAR::raiseError($this->_errormsg);
    }

    /**
     * Stub o be overridden in the child class.
     */
    function saveEvent()
    {
        return PEAR::raiseError($this->_errormsg);
    }

    /**
     * Stub for child class to override if it can implement.
     */
    function removeUserData($user)
    {
        return PEAR::raiseError(_("Removing user data is not supported with the current calendar storage backend."));
    }

}

/**
 * Kronolith_Event defines a generic API for events.
 *
 * @author  Chuck Hagenbuch <chuck@horde.org>
 * @author  Jan Schneider <jan@horde.org>
 * @since   Kronolith 0.1
 * @package Kronolith
 */
class Kronolith_Event {

    /**
     * Flag that is set to true if this event has data from either a storage
     * backend or a form or other import method.
     *
     * @var boolean
     */
    var $initialized = false;

    /**
     * Flag that is set to true if this event exists in a storage driver.
     *
     * @var boolean
     */
    var $stored = false;

    /**
     * The driver unique identifier for this event.
     *
     * @var string
     */
    var $eventID = null;

    /**
     * The UID for this event.
     *
     * @var string
     */
    var $_uid = null;

    /**
     * The user id of the creator of the event.
     *
     * @var string
     */
    var $creatorID = null;

    /**
     * The title of this event.
     *
     * @var string
     */
    var $title = '';

    /**
     * The category of this event.
     *
     * @var string
     */
    var $category = '';

    /**
     * The location this event occurs at.
     *
     * @var string
     */
    var $location = '';

    /**
     * The status of this event.
     *
     * @var integer
     */
    var $status = KRONOLITH_STATUS_CONFIRMED;

    /**
     * The description for this event
     *
     * @var string
     */
    var $description = '';

    /**
     * Remote description of this event (URL).
     *
     * @var string
     */
    var $remoteUrl = '';

    /**
     * Remote calendar name.
     *
     * @var string
     */
    var $remoteCal = '';

    /**
     * Whether the event is private.
     *
     * @var boolean
     */
    var $private = false;

    /**
     * All the attendees of this event.
     *
     * This is an associative array where the keys are the email addresses
     * of the attendees, and the values are also associative arrays with
     * keys 'attendance' and 'response' pointing to the attendees' attendance
     * and response values, respectively.
     *
     * @var array
     */
    var $attendees = array();

    /**
     * All the key words associtated with this event.
     *
     * @var array
     */
    var $keywords = array();

    /**
     * The start time of the event.
     *
     * @var Horde_Date
     */
    var $start;

    /**
     * The end time of the event.
     *
     * @var Horde_Date
     */
    var $end;

    /**
     * The duration of this event in minutes
     *
     * @var integer
     */
    var $durMin = 0;

    /**
     * Number of minutes before the event starts to trigger an alarm.
     *
     * @var integer
     */
    var $alarm = 0;

    /**
     * The identifier of the calender this event exists on.
     *
     * @var string
     */
    var $_calendar;

    /**
     * The VarRenderer class to use for printing select elements.
     *
     * @var Horde_UI_VarRenderer
     */
    var $_varRenderer;

    /**
     * Constructor.
     *
     * @param Kronolith_Driver $driver        The backend driver that this
     *                                        event is stored in.
     * @param Kronolith_Event  $eventObject   Backend specific event object
     *                                        that this will represent.
     */
    function Kronolith_Event(&$driver, $eventObject = null)
    {
        /* Set default alarm value. */
        if (isset($GLOBALS['prefs'])) {
            $this->alarm = $GLOBALS['prefs']->getValue('default_alarm');
        }

        $this->_calendar = $driver->getCalendar();
        if ($eventObject !== null) {
            $this->fromDriver($eventObject);
        }
    }

    /**
     * Returns a reference to a driver that's valid for this event.
     *
     * @return Kronolith_Driver  A driver that this event can use to save
     *                           itself, etc.
     */
    function &getDriver()
    {
        global $kronolith_driver;
        if ($kronolith_driver->getCalendar() != $this->_calendar) {
            $kronolith_driver->open($this->_calendar);
        }

        return $kronolith_driver;
    }

    /**
     * Returns the share this event belongs to.
     *
     * @return Horde_Share  This event's share.
     */
    function &getShare()
    {
        if (isset($GLOBALS['all_calendars'][$this->getCalendar()])) {
            $share = $GLOBALS['all_calendars'][$this->getCalendar()];
        } else {
            $share = PEAR::raiseError('Share not found');
        }
        return $share;
    }

    /**
     * Encapsulates permissions checking.
     *
     * @param integer $permission  The permission to check for.
     * @param string $user         The user to check permissions for.
     *
     * @return boolean
     */
    function hasPermission($permission, $user = null)
    {
        if ($user === null) {
            $user = Auth::getAuth();
        }

        if ($this->remoteCal) {
            switch ($permission) {
            case PERMS_SHOW:
            case PERMS_READ:
            case PERMS_EDIT:
                return true;

            default:
                return false;
            }
        }

        return (!is_a($share = &$this->getShare(), 'PEAR_Error') &&
                $share->hasPermission($user, $permission, $this->getCreatorId()));
    }

    /**
     * Saves changes to this event.
     *
     * @return mixed  True or a PEAR_Error on failure.
     */
    function save()
    {
        if (!$this->isInitialized()) {
            return PEAR::raiseError('Event not yet initialized');
        }

        $this->toDriver();
        $driver = &$this->getDriver();
        $result = $driver->saveEvent($this);
        if (!is_a($result, 'PEAR_Error') &&
            !empty($GLOBALS['conf']['alarms']['driver'])) {
            $alarm = $this->toAlarm(new Horde_Date($_SERVER['REQUEST_TIME']));
            if ($alarm) {
                $alarm['start'] = new Horde_Date($alarm['start']);
                $alarm['end'] = new Horde_Date($alarm['end']);
                require_once 'Horde/Alarm.php';
                $horde_alarm = Horde_Alarm::factory();
                $horde_alarm->set($alarm);
            }
        }

        return $result;
    }

    /**
     * Exports this event in iCalendar format.
     *
     * @param Horde_iCalendar &$calendar  A Horde_iCalendar object that acts as
     *                                    a container.
     *
     * @return Horde_iCalendar_vevent  The vEvent object for this event.
     */
    function &toiCalendar(&$calendar)
    {
        $vEvent = &Horde_iCalendar::newComponent('vevent', $calendar);
        $v1 = $calendar->getAttribute('VERSION') == '1.0';

        if ($this->isAllDay()) {
            $vEvent->setAttribute('DTSTART', $this->start, array('VALUE' => 'DATE'));
            $vEvent->setAttribute('DTEND', new Horde_Date($this->end->timestamp()), array('VALUE' => 'DATE'));
        } else {
            $vEvent->setAttribute('DTSTART', $this->start);
            $vEvent->setAttribute('DTEND', $this->end);
        }

        $vEvent->setAttribute('DTSTAMP', $_SERVER['REQUEST_TIME']);
        $vEvent->setAttribute('UID', $this->_uid);

        /* Get the event's history. */
        $history = &Horde_History::singleton();
        $created = $modified = null;
        $log = $history->getHistory('kronolith:' . $this->_calendar . ':' . $this->_uid);
        if ($log && !is_a($log, 'PEAR_Error')) {
            foreach ($log->getData() as $entry) {
                switch ($entry['action']) {
                case 'add':
                    $created = $entry['ts'];
                    break;

                case 'modify':
                    $modified = $entry['ts'];
                    break;
                }
            }
        }
        if (!empty($created)) {
            $vEvent->setAttribute($v1 ? 'DCREATED' : 'CREATED', $created);
            if (empty($modified)) {
                $modified = $created;
            }
        }
        if (!empty($modified)) {
            $vEvent->setAttribute('LAST-MODIFIED', $modified);
        }

        $vEvent->setAttribute('SUMMARY', $v1 ? $this->getTitle() : String::convertCharset($this->getTitle(), NLS::getCharset(), 'utf-8'));
        $name = Kronolith::getUserName($this->getCreatorId());
        if (!$v1) {
            $name = String::convertCharset($name, NLS::getCharset(), 'utf-8');
        }
        $vEvent->setAttribute('ORGANIZER',
                              'mailto:' . Kronolith::getUserEmail($this->getCreatorId()),
                              array('CN' => $name));
        if (!$this->isPrivate() || $this->getCreatorId() == Auth::getAuth()) {
            if (!empty($this->description)) {
                $vEvent->setAttribute('DESCRIPTION', $v1 ? $this->description : String::convertCharset($this->description, NLS::getCharset(), 'utf-8'));
            }
            $categories = $this->getCategory();
            if (!empty($categories)) {
                $vEvent->setAttribute('CATEGORIES', $v1 ? $categories : String::convertCharset($categories, NLS::getCharset(), 'utf-8'));
            }
            if (!empty($this->location)) {
                $vEvent->setAttribute('LOCATION', $v1 ? $this->location : String::convertCharset($this->location, NLS::getCharset(), 'utf-8'));
            }
        }
        $vEvent->setAttribute('CLASS', $this->isPrivate() ? 'PRIVATE' : 'PUBLIC');

        // Status.
        switch ($this->getStatus()) {
        case KRONOLITH_STATUS_FREE:
            // This is not an official iCalendar value, but we need it for
            // synchronization.
            $vEvent->setAttribute('STATUS', 'FREE');
            $vEvent->setAttribute('TRANSP', $v1 ? 1 : 'TRANSPARENT');
            break;
        case KRONOLITH_STATUS_TENTATIVE:
            $vEvent->setAttribute('STATUS', 'TENTATIVE');
            $vEvent->setAttribute('TRANSP', $v1 ? 0 : 'OPAQUE');
            break;
        case KRONOLITH_STATUS_CONFIRMED:
            $vEvent->setAttribute('STATUS', 'CONFIRMED');
            $vEvent->setAttribute('TRANSP', $v1 ? 0 : 'OPAQUE');
            break;
        case KRONOLITH_STATUS_CANCELLED:
            if ($v1) {
                $vEvent->setAttribute('STATUS', 'DECLINED');
                $vEvent->setAttribute('TRANSP', 1);
            } else {
                $vEvent->setAttribute('STATUS', 'CANCELLED');
                $vEvent->setAttribute('TRANSP', 'TRANSPARENT');
            }
            break;
        }

        // Attendees.
        foreach ($this->getAttendees() as $email => $status) {
            $params = array();
            switch ($status['attendance']) {
            case KRONOLITH_PART_REQUIRED:
                if ($v1) {
                    $params['EXPECT'] = 'REQUIRE';
                } else {
                    $params['ROLE'] = 'REQ-PARTICIPANT';
                }
                break;

            case KRONOLITH_PART_OPTIONAL:
                if ($v1) {
                    $params['EXPECT'] = 'REQUEST';
                } else {
                    $params['ROLE'] = 'OPT-PARTICIPANT';
                }
                break;

            case KRONOLITH_PART_NONE:
                if ($v1) {
                    $params['EXPECT'] = 'FYI';
                } else {
                    $params['ROLE'] = 'NON-PARTICIPANT';
                }
                break;
            }

            switch ($status['response']) {
            case KRONOLITH_RESPONSE_NONE:
                if ($v1) {
                    $params['STATUS'] = 'NEEDS ACTION';
                    $params['RSVP'] = 'YES';
                } else {
                    $params['PARTSTAT'] = 'NEEDS-ACTION';
                    $params['RSVP'] = 'TRUE';
                }
                break;

            case KRONOLITH_RESPONSE_ACCEPTED:
                if ($v1) {
                    $params['STATUS'] = 'ACCEPTED';
                } else {
                    $params['PARTSTAT'] = 'ACCEPTED';
                }
                break;

            case KRONOLITH_RESPONSE_DECLINED:
                if ($v1) {
                    $params['STATUS'] = 'DECLINED';
                } else {
                    $params['PARTSTAT'] = 'DECLINED';
                }
                break;

            case KRONOLITH_RESPONSE_TENTATIVE:
                if ($v1) {
                    $params['STATUS'] = 'TENTATIVE';
                } else {
                    $params['PARTSTAT'] = 'TENTATIVE';
                }
                break;
            }

            if (strpos($email, '@') === false) {
                $email = '';
            }
            if ($v1) {
                if (!empty($status['name'])) {
                    require_once 'Horde/MIME.php';
                    if (!empty($email)) {
                        $email = ' <' . $email . '>';
                    }
                    $email = $status['name'] . $email;
                    $email = MIME::trimEmailAddress($email);
                }
            } else {
                if (!empty($status['name'])) {
                    $params['CN'] = String::convertCharset($status['name'], NLS::getCharset(), 'utf-8');
                }
                if (!empty($email)) {
                    $email = 'mailto:' . $email;
                }
            }

            $vEvent->setAttribute('ATTENDEE', $email, $params);
        }

        // Alarms.
        if (!empty($this->alarm)) {
            if ($v1) {
                $vEvent->setAttribute('AALARM', $this->start->timestamp() - $this->alarm * 60);
            } else {
                $vAlarm = &Horde_iCalendar::newComponent('valarm', $vEvent);
                $vAlarm->setAttribute('ACTION', 'DISPLAY');
                $vAlarm->setAttribute('TRIGGER;VALUE=DURATION', '-PT' . $this->alarm . 'M');
                $vEvent->addComponent($vAlarm);
            }
        }

        // Recurrence.
        if ($this->recurs()) {
            if ($v1) {
                $rrule = $this->recurrence->toRRule10($calendar);
            } else {
                $rrule = $this->recurrence->toRRule20($calendar);
            }
            if (!empty($rrule)) {
                $vEvent->setAttribute('RRULE', $rrule);
            }

            // Exceptions.
            $exceptions = $this->recurrence->getExceptions();
            foreach ($exceptions as $exception) {
                if (!empty($exception)) {
                    list($year, $month, $mday) = sscanf($exception, '%04d%02d%02d');
                    $exdate = new Horde_Date(array(
                        'year' => $year,
                        'month' => $month,
                        'mday' => $mday,
                        'hour' => $this->start->hour,
                        'min' => $this->start->min,
                        'sec' => $this->start->sec,
                    ));
                    $vEvent->setAttribute('EXDATE', array($exdate));
                }
            }
        }

        return $vEvent;
    }

    /**
     * Updates the properties of this event from a Horde_iCalendar_vevent
     * object.
     *
     * @param Horde_iCalendar_vevent $vEvent  The iCalendar data to update
     *                                        from.
     */
    function fromiCalendar($vEvent)
    {
        // Unique ID.
        $uid = $vEvent->getAttribute('UID');
        if (!empty($uid) && !is_a($uid, 'PEAR_Error')) {
            $this->setUID($uid);
        }

        // Title, category and description.
        $title = $vEvent->getAttribute('SUMMARY');
        if (!is_array($title) && !is_a($title, 'PEAR_Error')) {
            $this->setTitle($title);
        }

        $categories = $vEvent->getAttribute('CATEGORIES');
        if (!is_array($categories) && !is_a($categories, 'PEAR_Error')) {
            // The CATEGORY attribute is delimited by commas, so split
            // it up.
            $categories = explode(',', $categories);

            // We only support one category per event right now, so
            // arbitrarily take the last one.
            foreach ($categories as $category) {
                $this->setCategory($category);
            }
        }
        $desc = $vEvent->getAttribute('DESCRIPTION');
        if (!is_array($desc) && !is_a($desc, 'PEAR_Error')) {
            $this->setDescription($desc);
        }

        // Remote Url
        $url = $vEvent->getAttribute('URL');
        if (!is_array($url) && !is_a($url, 'PEAR_Error')) {
            $this->remoteUrl = $url;
        }

        // Location
        $location = $vEvent->getAttribute('LOCATION');
        if (!is_array($location) && !is_a($location, 'PEAR_Error')) {
            $this->setLocation($location);
        }

        // Class
        $class = $vEvent->getAttribute('CLASS');
        if (!is_array($class) && !is_a($class, 'PEAR_Error')) {
            $class = String::upper($class);
            if ($class == 'PRIVATE' || $class == 'CONFIDENTIAL') {
                $this->setPrivate(true);
            } else {
                $this->setPrivate(false);
            }
        }

        // Status.
        $status = $vEvent->getAttribute('STATUS');
        if (!is_array($status) && !is_a($status, 'PEAR_Error')) {
            $status = String::upper($status);
            if ($status == 'DECLINED') {
                $status = 'CANCELLED';
            }
            if (defined('KRONOLITH_STATUS_' . $status)) {
                $this->setStatus(constant('KRONOLITH_STATUS_' . $status));
            }
        }

        // Start and end date.
        $start = $vEvent->getAttribute('DTSTART');
        if (!is_a($start, 'PEAR_Error')) {
            if (!is_array($start)) {
                // Date-Time field
                $this->start = new Horde_Date($start);
            } else {
                // Date field
                $this->start = new Horde_Date(
                    array('year'  => (int)$start['year'],
                          'month' => (int)$start['month'],
                          'mday'  => (int)$start['mday']));
            }
        }
        $end = $vEvent->getAttribute('DTEND');
        if (!is_a($end, 'PEAR_Error')) {
            if (!is_array($end)) {
                // Date-Time field
                $this->end = new Horde_Date($end);
                // All day events are transferred by many device as
                // DSTART: YYYYMMDDT000000 DTEND: YYYYMMDDT2359(59|00)
                // Convert accordingly
                if (is_object($this->start) && $this->start->hour == 0 &&
                    $this->start->min == 0 && $this->start->sec == 0 &&
                    $this->end->hour == 23 && $this->end->min == 59) {
                    $this->end = new Horde_Date(
                        array('year'  => (int)$this->end->year,
                              'month' => (int)$this->end->month,
                              'mday'  => (int)$this->end->mday + 1));
                    $this->end->correct();
                }
            } elseif (is_array($end) && !is_a($end, 'PEAR_Error')) {
                // Date field
                $this->end = new Horde_Date(
                    array('year'  => (int)$end['year'],
                          'month' => (int)$end['month'],
                          'mday'  => (int)$end['mday']));
                $this->end->correct();
            }
        } else {
            $duration = $vEvent->getAttribute('DURATION');
            if (!is_array($duration) && !is_a($duration, 'PEAR_Error')) {
                $this->end = new Horde_Date($this->start->timestamp() + $duration);
            } else {
                // End date equal to start date as per RFC 2445.
                $this->end = Util::cloneObject($this->start);
                if (is_array($start)) {
                    // Date field
                    $this->end->mday++;
                    $this->end->correct();
                }
            }
        }

        // vCalendar 1.0 alarms
        $alarm = $vEvent->getAttribute('AALARM');
        if (!is_array($alarm) &&
            !is_a($alarm, 'PEAR_Error') &&
            intval($alarm)) {
            $this->alarm = intval(($this->start->timestamp() - $alarm) / 60);
        }

        // @TODO: vCalendar 2.0 alarms

        // Attendance.
        // Importing attendance may result in confusion: editing an imported
        // copy of an event can cause invitation updates to be sent from
        // people other than the original organizer. So we don't import by
        // default. However to allow updates by SyncML replication, the custom
        // X-ATTENDEE attribute is used which has the same syntax as
        // ATTENDEE.
        $attendee = $vEvent->getAttribute('X-ATTENDEE');
        if (!is_a($attendee, 'PEAR_Error')) {
            require_once 'Horde/MIME.php';

            if (!is_array($attendee)) {
                $attendee = array($attendee);
            }
            $params = $vEvent->getAttribute('X-ATTENDEE', true);
            if (!is_array($params)) {
                $params = array($params);
            }
            for ($i = 0; $i < count($attendee); ++$i) {
                $attendee[$i] = str_replace(array('MAILTO:', 'mailto:'), '',
                                            $attendee[$i]);
                $email = MIME::bareAddress($attendee[$i]);
                // Default according to rfc2445:
                $attendance = KRONOLITH_PART_REQUIRED;
                // vCalendar 2.0 style:
                if (!empty($params[$i]['ROLE'])) {
                    switch($params[$i]['ROLE']) {
                    case 'OPT-PARTICIPANT':
                        $attendance = KRONOLITH_PART_OPTIONAL;
                        break;

                    case 'NON-PARTICIPANT':
                        $attendance = KRONOLITH_PART_NONE;
                        break;
                    }
                }
                // vCalendar 1.0 style;
                if (!empty($params[$i]['EXPECT'])) {
                    switch($params[$i]['EXPECT']) {
                    case 'REQUEST':
                        $attendance = KRONOLITH_PART_OPTIONAL;
                        break;

                    case 'FYI':
                        $attendance = KRONOLITH_PART_NONE;
                        break;
                    }
                }
                $response = KRONOLITH_RESPONSE_NONE;
                if (empty($params[$i]['PARTSTAT']) &&
                    !empty($params[$i]['STATUS'])) {
                    $params[$i]['PARTSTAT']  = $params[$i]['STATUS'];
                }

                if (!empty($params[$i]['PARTSTAT'])) {
                    switch($params[$i]['PARTSTAT']) {
                    case 'ACCEPTED':
                        $response = KRONOLITH_RESPONSE_ACCEPTED;
                        break;

                    case 'DECLINED':
                        $response = KRONOLITH_RESPONSE_DECLINED;
                        break;

                    case 'TENTATIVE':
                        $response = KRONOLITH_RESPONSE_TENTATIVE;
                        break;
                    }
                }
                $name = isset($params[$i]['CN']) ? $params[$i]['CN'] : null;

                $this->addAttendee($email, $attendance, $response, $name);
            }
        }

        // Recurrence.
        $rrule = $vEvent->getAttribute('RRULE');
        if (!is_array($rrule) && !is_a($rrule, 'PEAR_Error')) {
            $this->recurrence = new Horde_Date_Recurrence($this->start);
            if (strpos($rrule, '=') !== false) {
                $this->recurrence->fromRRule20($rrule);
            } else {
                $this->recurrence->fromRRule10($rrule);
            }

            // Exceptions.
            $exdates = $vEvent->getAttribute('EXDATE');
            if (is_array($exdates)) {
                foreach ($exdates as $exdate) {
                    if (is_array($exdate)) {
                        $this->recurrence->addException((int)$exdate['year'],
                                                        (int)$exdate['month'],
                                                        (int)$exdate['mday']);
                    }
                }
            }
        }

        $this->initialized = true;
    }

    /**
     * Imports the values for this event from an array of values.
     *
     * @param array $hash  Array containing all the values.
     */
    function fromHash($hash)
    {
        // See if it's a new event.
        if ($this->getId() === null) {
            $this->setCreatorId(Auth::getAuth());
        }
        if (!empty($hash['title'])) {
            $this->setTitle($hash['title']);
        } else {
            return PEAR::raiseError(_("Events must have a title."));
        }
        if (!empty($hash['description'])) {
            $this->setDescription($hash['description']);
        }
        if (!empty($hash['category'])) {
            global $cManager;
            $categories = $cManager->get();
            if (!in_array($hash['category'], $categories)) {
                $cManager->add($hash['category']);
            }
            $this->setCategory($hash['category']);
        }
        if (!empty($hash['location'])) {
            $this->setLocation($hash['location']);
        }
        if (!empty($hash['keywords'])) {
            $this->setKeywords(explode(',', $hash['keywords']));
        }
        if (!empty($hash['start_date'])) {
            $date = explode('-', $hash['start_date']);
            if (empty($hash['start_time'])) {
                $time = array(0, 0, 0);
            } else {
                $time = explode(':', $hash['start_time']);
                if (count($time) == 2) {
                    $time[2] = 0;
                }
            }
            if (count($time) == 3 && count($date) == 3) {
                $this->start = new Horde_Date(array('year' => $date[0],
                                                    'month' => $date[1],
                                                    'mday' => $date[2],
                                                    'hour' => $time[0],
                                                    'min' => $time[1],
                                                    'sec' => $time[2]));
            }
        } else {
            return PEAR::raiseError(_("Events must have a start date."));
        }
        if (empty($hash['duration'])) {
            if (empty($hash['end_date'])) {
                $hash['end_date'] = $hash['start_date'];
            }
            if (empty($hash['end_time'])) {
                $hash['end_time'] = $hash['start_time'];
            }
        } else {
            $weeks = str_replace('W', '', $hash['duration'][1]);
            $days = str_replace('D', '', $hash['duration'][2]);
            $hours = str_replace('H', '', $hash['duration'][4]);
            $minutes = isset($hash['duration'][5]) ? str_replace('M', '', $hash['duration'][5]) : 0;
            $seconds = isset($hash['duration'][6]) ? str_replace('S', '', $hash['duration'][6]) : 0;
            $hash['duration'] = ($weeks * 60 * 60 * 24 * 7) + ($days * 60 * 60 * 24) + ($hours * 60 * 60) + ($minutes * 60) + $seconds;
            $this->end = new Horde_Date($this->start->timestamp() + $hash['duration']);
        }
        if (!empty($hash['end_date'])) {
            $date = explode('-', $hash['end_date']);
            if (empty($hash['end_time'])) {
                $time = array(0, 0, 0);
            } else {
                $time = explode(':', $hash['end_time']);
                if (count($time) == 2) {
                    $time[2] = 0;
                }
            }
            if (count($time) == 3 && count($date) == 3) {
                $this->end = new Horde_Date(array('year' => $date[0],
                                                  'month' => $date[1],
                                                  'mday' => $date[2],
                                                  'hour' => $time[0],
                                                  'min' => $time[1],
                                                  'sec' => $time[2]));
            }
        }
        if (!empty($hash['alarm'])) {
            $this->setAlarm($hash['alarm']);
        } elseif (!empty($hash['alarm_date']) &&
                  !empty($hash['alarm_time'])) {
            $date = explode('-', $hash['alarm_date']);
            $time = explode(':', $hash['alarm_time']);
            if (count($time) == 2) {
                $time[2] = 0;
            }
            if (count($time) == 3 && count($date) == 3) {
                $this->setAlarm(($this->start->timestamp() - mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0])) / 60);
            }
        }
        if (!empty($hash['recur_type'])) {
            $this->recurrence = new Horde_Date_Recurrence($this->start);
            $this->recurrence->setRecurType($hash['recur_type']);
            if (!empty($hash['recur_end_date'])) {
                $date = explode('-', $hash['recur_end_date']);
                $this->recurrence->setRecurEnd(new Horde_Date(array('year' => $date[0], 'month' => $date[1], 'mday' => $date[2])));
            }
            if (!empty($hash['recur_interval'])) {
                $this->recurrence->setRecurInterval($hash['recur_interval']);
            }
            if (!empty($hash['recur_data'])) {
                $this->recurrence->setRecurOnDay($hash['recur_data']);
            }
        }

        $this->initialized = true;
    }

    /**
     * Returns an alarm hash of this event suitable for Horde_Alarm.
     *
     * @param Horde_Date $time  Time of alarm.
     * @param string $user      The user to return alarms for.
     * @param Prefs $prefs      A Prefs instance.
     *
     * @return array  Alarm hash or null.
     */
    function toAlarm($time, $user = null, $prefs = null)
    {
        if (!$this->getAlarm()) {
            return;
        }

        if ($this->recurs()) {
            $eventDate = $this->recurrence->nextRecurrence($time);
            if ($eventDate && $this->recurrence->hasException($eventDate->year, $eventDate->month, $eventDate->mday)) {
                return;
            }
        }

        if (empty($user)) {
            $user = Auth::getAuth();
        }
        if (empty($prefs)) {
            $prefs = $GLOBALS['prefs'];
        }

        $methods = @unserialize($prefs->getValue('event_alarms'));
        $start = Util::cloneObject($this->start);
        $start->min -= $this->getAlarm();
        $start->correct();
        if (isset($methods['notify'])) {
            $methods['notify']['show'] = array(
                '__app' => $GLOBALS['registry']->getApp(),
                'event' => $this->getId(),
                'calendar' => $this->getCalendar());
            if (!empty($methods['notify']['sound'])) {
                if ($methods['notify']['sound'] == 'on') {
                    // Handle boolean sound preferences.
                    $methods['notify']['sound'] = $GLOBALS['registry']->get('themesuri') . '/sounds/theetone.wav';
                } else {
                    // Else we know we have a sound name that can be
                    // served from Horde.
                    $methods['notify']['sound'] = $GLOBALS['registry']->get('themesuri', 'horde') . '/sounds/' . $methods['notify']['sound'];
                }
            }
        }
        if (isset($methods['popup'])) {
            $methods['popup']['message'] = $this->getTitle($user);
            $description = $this->getDescription();
            if (!empty($description)) {
                $methods['popup']['message'] .= "\n\n" . $description;
            }
        }
        if (isset($methods['mail'])) {
            $methods['mail']['body'] = sprintf(
                _("We would like to remind you of this upcoming event.\n\n%s\n\nLocation: %s\n\nDate: %s\nTime: %s\n\n%s"),
                $this->getTitle($user),
                $this->location,
                strftime($prefs->getValue('date_format'), $this->start->timestamp()),
                date($prefs->getValue('twentyFour') ? 'H:i' : 'h:ia', $this->start->timestamp()),
                $this->getDescription());
        }

        return array(
            'id' => $this->getUID(),
            'user' => $user,
            'start' => $start->timestamp(),
            'end' => $this->end->timestamp(),
            'methods' => array_keys($methods),
            'params' => $methods,
            'title' => $this->getTitle($user),
            'text' => $this->getDescription());
    }

    /**
     * TODO
     */
    function isInitialized()
    {
        return $this->initialized;
    }

    /**
     * TODO
     */
    function isStored()
    {
        return $this->stored;
    }

    /**
     * Checks if the current event is already present in the calendar.
     *
     * Does the check based on the uid.
     *
     * @return boolean  True if event exists, false otherwise.
     */
    function exists()
    {
        if (!isset($this->_uid) || !isset($this->_calendar)) {
            return false;
        }

        $eventID = $GLOBALS['kronolith_driver']->exists($this->_uid, $this->_calendar);
        if (is_a($eventID, 'PEAR_Error') || !$eventID) {
            return false;
        } else {
            $this->eventID = $eventID;
            return true;
        }
    }

    function getDuration()
    {
        static $duration = null;
        if (isset($duration)) {
            return $duration;
        }

        if ($this->isInitialized()) {
            require_once 'Date/Calc.php';
            $dur_day_match = Date_Calc::dateDiff($this->start->mday,
                                                 $this->start->month,
                                                 $this->start->year,
                                                 $this->end->mday,
                                                 $this->end->month,
                                                 $this->end->year);
            $dur_hour_match = $this->end->hour - $this->start->hour;
            $dur_min_match = $this->end->min - $this->start->min;
            while ($dur_min_match < 0) {
                $dur_min_match += 60;
                --$dur_hour_match;
            }
            while ($dur_hour_match < 0) {
                $dur_hour_match += 24;
                --$dur_day_match;
            }
            if ($dur_hour_match == 0 && $dur_min_match == 0
                && $this->end->mday - $this->start->mday == 1) {
                $dur_day_match = 0;
                $dur_hour_match = 23;
                $dur_min_match = 60;
                $whole_day_match = true;
            } else {
                $whole_day_match = false;
            }
        } else {
            $dur_day_match = 0;
            $dur_hour_match = 1;
            $dur_min_match = 0;
            $whole_day_match = false;
        }

        $duration = new stdClass;
        $duration->day = $dur_day_match;
        $duration->hour = $dur_hour_match;
        $duration->min = $dur_min_match;
        $duration->wholeDay = $whole_day_match;

        return $duration;
    }

    /**
     * Returns whether this event is a recurring event.
     *
     * @return boolean  True if this is a recurring event.
     */
    function recurs()
    {
        return isset($this->recurrence) &&
            !$this->recurrence->hasRecurType(HORDE_DATE_RECUR_NONE);
    }

    /**
     * Returns a description of this event's recurring type.
     *
     * @return string  Human readable recurring type.
     */
    function getRecurName()
    {
        return $this->recurs()
            ? $this->recurrence->getRecurName()
            : _("No recurrence");
    }

    /**
     * Returns a correcty formatted exception date for recurring events and a
     * link to delete this exception.
     *
     * @param string $date  Exception in the format Ymd.
     *
     * @return string  The formatted date and delete link.
     */
    function exceptionLink($date)
    {
        $formatted = strftime($GLOBALS['prefs']->getValue('date_format'), strtotime($date));
        return $formatted
            . Horde::link(Util::addParameter(Horde::applicationUrl('edit.php'), array('calendar' => $this->getCalendar(), 'eventID' => $this->eventID, 'del_exception' => $date, 'url' => Util::getFormData('url'))), sprintf(_("Delete exception on %s"), $formatted))
            . Horde::img('delete-small.png', _("Delete"), '', $GLOBALS['registry']->getImageDir('horde'))
            . '</a>';
    }

    /**
     * Returns a list of exception dates for recurring events including links
     * to delete them.
     *
     * @return string  List of exception dates and delete links.
     */
    function exceptionsList()
    {
        return implode(', ', array_map(array($this, 'exceptionLink'), $this->recurrence->getExceptions()));
    }

    function getCalendar()
    {
        return $this->_calendar;
    }

    function setCalendar($calendar)
    {
        $this->_calendar = $calendar;
    }

    function isRemote()
    {
        return (bool)$this->remoteCal;
    }

    /**
     * Returns the locally unique identifier for this event.
     *
     * @return string  The local identifier for this event.
     */
    function getId()
    {
        return $this->eventID;
    }

    /**
     * Sets the locally unique identifier for this event.
     *
     * @param string $eventId  The local identifier for this event.
     */
    function setId($eventId)
    {
        if (substr($eventId, 0, 10) == 'kronolith:') {
            $eventId = substr($eventId, 10);
        }
        $this->eventID = $eventId;
    }

    /**
     * Returns the global UID for this event.
     *
     * @return string  The global UID for this event.
     */
    function getUID()
    {
        return $this->_uid;
    }

    /**
     * Sets the global UID for this event.
     *
     * @param string $uid  The global UID for this event.
     */
    function setUID($uid)
    {
        $this->_uid = $uid;
    }

    /**
     * Returns the id of the user who created the event.
     *
     * @return string  The creator id
     */
    function getCreatorId()
    {
        return !empty($this->creatorID) ? $this->creatorID : Auth::getAuth();
    }

    /**
     * Sets the id of the creator of the event.
     *
     * @param string $creatorID  The user id for the user who created the event
     */
    function setCreatorId($creatorID)
    {
        $this->creatorID = $creatorID;
    }

    /**
     * Returns the title of this event.
     *
     * @param string $user  The current user.
     *
     * @return string  The title of this event.
     */
    function getTitle($user = null)
    {
        if (isset($this->external) ||
            isset($this->contactID) ||
            $this->remoteCal) {
            return !empty($this->title) ? $this->title : _("[Unnamed event]");
        }

        if (!$this->isInitialized()) {
            return '';
        }

        if ($user === null) {
            $user = Auth::getAuth();
        }

        $start = date($GLOBALS['prefs']->getValue('twentyFour') ? 'G:i' : 'g:ia', $this->start->timestamp());
        $end = date($GLOBALS['prefs']->getValue('twentyFour') ? 'G:i' : 'g:ia', $this->end->timestamp());

        // We explicitely allow admin access here for the alarms
        // notifications.
        if (!Auth::isAdmin() && $this->isPrivate() &&
            $this->getCreatorId() != $user) {
            return sprintf(_("Private Event from %s to %s"), $start, $end);
        } elseif (Auth::isAdmin() || $this->hasPermission(PERMS_READ, $user)) {
            return strlen($this->title) ? $this->title : _("[Unnamed event]");
        } else {
            return sprintf(_("Event from %s to %s"), $start, $end);
        }
    }

    /**
     * Sets the title of this event.
     *
     * @param string  The new title for this event.
     */
    function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Returns the description of this event.
     *
     * @return string  The description of this event.
     */
    function getDescription()
    {
        return $this->description;
    }

    /**
     * Sets the description of this event.
     *
     * @param string $description  The new description for this event.
     */
    function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * Returns the category of this event.
     *
     * @return string  The category of this event.
     */
    function getCategory()
    {
        return $this->category;
    }

    /**
     * Sets the category of this event.
     *
     * @param string $category  The category of this event.
     */
    function setCategory($category)
    {
        $this->category = $category;
    }

    /**
     * Returns the location this event occurs at.
     *
     * @return string  The location of this event.
     */
    function getLocation()
    {
        return $this->location;
    }

    /**
     * Sets the location this event occurs at.
     *
     * @param string $location  The new location for this event.
     */
    function setLocation($location)
    {
        $this->location = $location;
    }

    /**
     * Returns whether this event is private.
     *
     * @return boolean  Whether this even is private.
     */
    function isPrivate()
    {
        return $this->private;
    }

    /**
     * Sets the private flag of this event.
     *
     * @param boolean $private  Whether this event should be marked private.
     */
    function setPrivate($private)
    {
        $this->private = !empty($private);
    }

    /**
     * Returns the event status.
     *
     * @return integer  The status of this event.
     */
    function getStatus()
    {
        return $this->status;
    }

    /**
     * Checks whether the events status is the same as the specified value.
     *
     * @param integer $status  The status value to check against.
     *
     * @return boolean  True if the events status is the same as $status.
     */
    function hasStatus($status)
    {
        return ($status == $this->status);
    }

    /**
     * Sets the status of this event.
     *
     * @param integer $status  The new event status.
     */
    function setStatus($status)
    {
        $this->status = $status;
    }

    /**
     * Returns the entire attendees array.
     *
     * @return array  A copy of the attendees array.
     */
    function getAttendees()
    {
        return $this->attendees;
    }

    /**
     * Checks to see whether the specified attendee is associated with the
     * current event.
     *
     * @param string $email  The email address of the attendee.
     *
     * @return boolean  True if the specified attendee is present for this
     *                  event.
     */
    function hasAttendee($email)
    {
        $email = String::lower($email);
        return isset($this->attendees[$email]);
    }

    /**
     * Sets the entire attendee array.
     *
     * @param array $attendees  The new attendees array. This should be of the
     *                          correct format to avoid driver problems.
     */
    function setAttendees($attendees)
    {
        $this->attendees = array_change_key_case($attendees);
    }

    /**
     * Adds a new attendee to the current event.
     *
     * This will overwrite an existing attendee if one exists with the same
     * email address.
     *
     * @param string $email        The email address of the attendee.
     * @param integer $attendance  The attendance code of the attendee.
     * @param integer $response    The response code of the attendee.
     * @param string $name         The name of the attendee.
     */
    function addAttendee($email, $attendance, $response, $name = null)
    {
        $email = String::lower($email);
        if ($attendance == KRONOLITH_PART_IGNORE) {
            if (isset($this->attendees[$email])) {
                $attendance = $this->attendees[$email]['attendance'];
            } else {
                $attendance = KRONOLITH_PART_REQUIRED;
            }
        }
        if (empty($name) && isset($this->attendees[$email]) &&
            !empty($this->attendees[$email]['name'])) {
            $name = $this->attendees[$email]['name'];
        }

        $this->attendees[$email] = array(
            'attendance' => $attendance,
            'response' => $response,
            'name' => $name
        );
    }

    /**
     * Removes the specified attendee from the current event.
     *
     * @param string $email  The email address of the attendee.
     */
    function removeAttendee($email)
    {
        $email = String::lower($email);
        if (isset($this->attendees[$email])) {
            unset($this->attendees[$email]);
        }
    }

    function getKeywords()
    {
        return $this->keywords;
    }

    function hasKeyword($keyword)
    {
        return in_array($keyword, $this->keywords);
    }

    function setKeywords($keywords)
    {
        $this->keywords = $keywords;
    }

    function isAllDay()
    {
        return ($this->start->hour == 0 && $this->start->min == 0 && $this->start->sec == 0 &&
                (($this->end->hour == 0 && $this->end->min == 0 && $this->end->sec == 0) ||
                 ($this->end->hour == 23 && $this->end->min == 59)) &&
                ($this->end->mday > $this->start->mday ||
                 $this->end->month > $this->start->month ||
                 $this->end->year > $this->start->year));
    }

    function getAlarm()
    {
        return $this->alarm;
    }

    function setAlarm($alarm)
    {
        $this->alarm = $alarm;
    }

    function readForm()
    {
        global $prefs, $cManager;

        // Event owner.
        $targetcalendar = Util::getFormData('targetcalendar');
        if (strpos($targetcalendar, ':')) {
            list(, $creator) = explode(':', $targetcalendar, 2);
        } else {
            $creator = isset($this->eventID) ? $this->getCreatorId() : Auth::getAuth();
        }
        $this->setCreatorId($creator);

        // Basic fields.
        $this->setTitle(Util::getFormData('title', $this->title));
        $this->setDescription(Util::getFormData('description', $this->description));
        $this->setLocation(Util::getFormData('location', $this->location));
        $this->setPrivate(Util::getFormData('private'));
        $this->setKeywords(Util::getFormData('keywords', $this->keywords));

        // Category.
        if ($new_category = Util::getFormData('new_category')) {
            $new_category = $cManager->add($new_category);
            $category = $new_category ? $new_category : '';
        } else {
            $category = Util::getFormData('category', $this->category);
        }
        $this->setCategory($category);

        // Status.
        $this->setStatus(Util::getFormData('status', $this->status));

        // Attendees.
        if (isset($_SESSION['kronolith']['attendees']) && is_array($_SESSION['kronolith']['attendees'])) {
            $this->setAttendees($_SESSION['kronolith']['attendees']);
        }

        // Event start.
        $start = Util::getFormData('start');
        $start_year = $start['year'];
        $start_month = $start['month'];
        $start_day = $start['day'];
        $start_hour = Util::getFormData('start_hour');
        $start_min = Util::getFormData('start_min');
        $am_pm = Util::getFormData('am_pm');

        if (!$prefs->getValue('twentyFour')) {
            if ($am_pm == 'PM') {
                if ($start_hour != 12) {
                    $start_hour += 12;
                }
            } elseif ($start_hour == 12) {
                $start_hour = 0;
            }
        }

        if (Util::getFormData('end_or_dur') == 1) {
            if (Util::getFormData('whole_day') == 1) {
                $start_hour = 0;
                $start_min = 0;
                $dur_day = 0;
                $dur_hour = 24;
                $dur_min = 0;
            } else {
                $dur_day = (int)Util::getFormData('dur_day');
                $dur_hour = (int)Util::getFormData('dur_hour');
                $dur_min = (int)Util::getFormData('dur_min');
            }
        }

        $this->start = new Horde_Date(array('hour' => $start_hour,
                                            'min' => $start_min,
                                            'month' => $start_month,
                                            'mday' => $start_day,
                                            'year' => $start_year));
        $this->start->correct();

        if (Util::getFormData('end_or_dur') == 1) {
            // Event duration.
            $this->end = new Horde_Date(array('hour' => $start_hour + $dur_hour,
                                              'min' => $start_min + $dur_min,
                                              'month' => $start_month,
                                              'mday' => $start_day + $dur_day,
                                              'year' => $start_year));
            $this->end->correct();
        } else {
            // Event end.
            $end = Util::getFormData('end');
            $end_year = $end['year'];
            $end_month = $end['month'];
            $end_day = $end['day'];
            $end_hour = Util::getFormData('end_hour');
            $end_min = Util::getFormData('end_min');
            $end_am_pm = Util::getFormData('end_am_pm');

            if (!$prefs->getValue('twentyFour')) {
                if ($end_am_pm == 'PM') {
                    if ($end_hour != 12) {
                        $end_hour += 12;
                    }
                } elseif ($end_hour == 12) {
                    $end_hour = 0;
                }
            }

            $this->end = new Horde_Date(array('hour' => $end_hour,
                                              'min' => $end_min,
                                              'month' => $end_month,
                                              'mday' => $end_day,
                                              'year' => $end_year));
            $this->end->correct();
            if ($this->end->timestamp() < $this->start->timestamp()) {
                $this->end = Util::cloneObject($this->start);
            }
        }

        // Alarm.
        if (Util::getFormData('alarm') == 1) {
            $this->setAlarm(Util::getFormData('alarm_value') * Util::getFormData('alarm_unit'));
        } else {
            $this->setAlarm(0);
        }

        // Recurrence.
        $recur = Util::getFormData('recur');
        if ($recur !== null && $recur !== '') {
            if (!isset($this->recurrence)) {
                $this->recurrence = new Horde_Date_Recurrence($this->start);
            }
            if (Util::getFormData('recur_enddate_type') == 'date') {
                $recur_enddate = Util::getFormData('recur_enddate');
                $this->recurrence->setRecurEnd(new Horde_Date(
                    array('hour' => 1,
                          'min' => 1,
                          'sec' => 1,
                          'month' => $recur_enddate['month'],
                          'mday' => $recur_enddate['day'],
                          'year' => $recur_enddate['year'])));
            } elseif (Util::getFormData('recur_enddate_type') == 'count') {
                $this->recurrence->setRecurCount(Util::getFormData('recur_count'));
            } elseif (Util::getFormData('recur_enddate_type') == 'none') {
                $this->recurrence->setRecurCount(0);
                $this->recurrence->setRecurEnd(null);
            }

            $this->recurrence->setRecurType($recur);
            switch ($recur) {
            case HORDE_DATE_RECUR_DAILY:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_daily_interval', 1));
                break;

            case HORDE_DATE_RECUR_WEEKLY:
                $weekly = Util::getFormData('weekly');
                $weekdays = 0;
                if (is_array($weekly)) {
                    foreach ($weekly as $day) {
                        $weekdays |= $day;
                    }
                }

                if ($weekdays == 0) {
                    // Sunday starts at 0.
                    switch ($this->start->dayOfWeek()) {
                    case 0: $weekdays |= HORDE_DATE_MASK_SUNDAY; break;
                    case 1: $weekdays |= HORDE_DATE_MASK_MONDAY; break;
                    case 2: $weekdays |= HORDE_DATE_MASK_TUESDAY; break;
                    case 3: $weekdays |= HORDE_DATE_MASK_WEDNESDAY; break;
                    case 4: $weekdays |= HORDE_DATE_MASK_THURSDAY; break;
                    case 5: $weekdays |= HORDE_DATE_MASK_FRIDAY; break;
                    case 6: $weekdays |= HORDE_DATE_MASK_SATURDAY; break;
                    }
                }

                $this->recurrence->setRecurInterval(Util::getFormData('recur_weekly_interval', 1));
                $this->recurrence->setRecurOnDay($weekdays);
                break;

            case HORDE_DATE_RECUR_MONTHLY_DATE:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_day_of_month_interval', 1));
                break;

            case HORDE_DATE_RECUR_MONTHLY_WEEKDAY:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_week_of_month_interval', 1));
                break;

            case HORDE_DATE_RECUR_YEARLY_DATE:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_yearly_interval', 1));
                break;

            case HORDE_DATE_RECUR_YEARLY_DAY:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_yearly_day_interval', 1));
                break;

            case HORDE_DATE_RECUR_YEARLY_WEEKDAY:
                $this->recurrence->setRecurInterval(Util::getFormData('recur_yearly_weekday_interval', 1));
                break;
            }
        }

        $this->initialized = true;
    }

    function html($property)
    {
        global $prefs;

        $options = array();
        $attributes = '';
        $sel = false;
        $label = '';

        switch ($property) {
        case 'start[year]':
            return  '<label for="' . $this->_formIDEncode($property) . '" class="hidden">' . _("Start Year") . '</label>' .
                '<input name="' . $property . '" value="' . $this->start->year .
                '" type="text" onchange="' . $this->js($property) .
                '" id="' . $this->_formIDEncode($property) . '" size="4" maxlength="4" />';

        case 'start[month]':
            $sel = $this->start->month;
            for ($i = 1; $i < 13; ++$i) {
                $options[$i] = strftime('%b', mktime(1, 1, 1, $i, 1));
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Start Month");
            break;

        case 'start[day]':
            $sel = $this->start->mday;
            for ($i = 1; $i < 32; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Start Day");
            break;

        case 'start_hour':
            $sel = (int)date($prefs->getValue('twentyFour') ? 'G' : 'g', $this->start->timestamp());
            $hour_min = $prefs->getValue('twentyFour') ? 0 : 1;
            $hour_max = $prefs->getValue('twentyFour') ? 24 : 13;
            for ($i = $hour_min; $i < $hour_max; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="document.eventform.whole_day.checked = false; updateEndDate();"';
            $label = _("Start Hour");
            break;

        case 'start_min':
            $sel = sprintf('%02d', $this->start->min);
            for ($i = 0; $i < 12; ++$i) {
                $min = sprintf('%02d', $i * 5);
                $options[$min] = $min;
            }
            $attributes = ' onchange="document.eventform.whole_day.checked = false; updateEndDate();"';
            $label = _("Start Minute");
            break;

        case 'end[year]':
            return  '<label for="' . $this->_formIDEncode($property) . '" class="hidden">' . _("End Year") . '</label>' .
                '<input name="' . $property . '" value="' . $this->end->year .
                '" type="text" onchange="' . $this->js($property) .
                '" id="' . $this->_formIDEncode($property) . '" size="4" maxlength="4" />';

        case 'end[month]':
            $sel = $this->isInitialized() ? $this->end->month : $this->start->month;
            for ($i = 1; $i < 13; ++$i) {
                $options[$i] = strftime('%b', mktime(1, 1, 1, $i, 1));
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("End Month");
            break;

        case 'end[day]':
            $sel = $this->isInitialized() ? $this->end->mday : $this->start->mday;
            for ($i = 1; $i < 32; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("End Day");
            break;

        case 'end_hour':
            $sel = $this->isInitialized() ?
                (int)date($prefs->getValue('twentyFour') ? 'G' : 'g', $this->end->timestamp()) :
                (int)date($prefs->getValue('twentyFour') ? 'G' : 'g', $this->start->timestamp()) + 1;
            $hour_min = $prefs->getValue('twentyFour') ? 0 : 1;
            $hour_max = $prefs->getValue('twentyFour') ? 24 : 13;
            for ($i = $hour_min; $i < $hour_max; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="updateDuration(); document.eventform.end_or_dur[0].checked = true"';
            $label = _("End Hour");
            break;

        case 'end_min':
            $sel = $this->isInitialized() ? $this->end->min : $this->start->min;
            $sel = sprintf('%02d', $sel);
            for ($i = 0; $i < 12; ++$i) {
                $min = sprintf('%02d', $i * 5);
                $options[$min] = $min;
            }
            $attributes = ' onchange="updateDuration(); document.eventform.end_or_dur[0].checked = true"';
            $label = _("End Minute");
            break;

        case 'dur_day':
            $dur = $this->getDuration();
            return  '<label for="' . $property . '" class="hidden">' . _("Duration Day") . '</label>' .
                '<input name="' . $property . '" value="' . $dur->day .
                '" type="text" onchange="' . $this->js($property) .
                '" id="' . $property . '" size="4" maxlength="4" />';

        case 'dur_hour':
            $dur = $this->getDuration();
            $sel = $dur->hour;
            for ($i = 0; $i < 24; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Duration Hour");
            break;

        case 'dur_min':
            $dur = $this->getDuration();
            $sel = $dur->min;
            for ($i = 0; $i < 13; ++$i) {
                $min = sprintf('%02d', $i * 5);
                $options[$min] = $min;
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Duration Minute");
            break;

        case 'recur_enddate[year]':
            if ($this->isInitialized()) {
                $end = ($this->recurs() && $this->recurrence->hasRecurEnd())
                        ? $this->recurrence->recurEnd->year
                        : $this->end->year;
            } else {
                $end = $this->start->year;
            }
            return  '<label for="' . $this->_formIDEncode($property) . '" class="hidden">' . _("Recurrence End Year") . '</label>' .
                '<input name="' . $property . '" value="' . $end .
                '" type="text" onchange="' . $this->js($property) .
                '" id="' . $this->_formIDEncode($property) . '" size="4" maxlength="4" />';

        case 'recur_enddate[month]':
            if ($this->isInitialized()) {
                $sel = ($this->recurs() && $this->recurrence->hasRecurEnd())
                    ? $this->recurrence->recurEnd->month
                    : $this->end->month;
            } else {
                $sel = $this->start->month;
            }
            for ($i = 1; $i < 13; ++$i) {
                $options[$i] = strftime('%b', mktime(1, 1, 1, $i, 1));
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Recurrence End Month");
            break;

        case 'recur_enddate[day]':
            if ($this->isInitialized()) {
                $sel = ($this->recurs() && $this->recurrence->hasRecurEnd())
                    ? $this->recurrence->recurEnd->mday
                    : $this->end->mday;
            } else {
                $sel = $this->start->mday;
            }
            for ($i = 1; $i < 32; ++$i) {
                $options[$i] = $i;
            }
            $attributes = ' onchange="' . $this->js($property) . '"';
            $label = _("Recurrence End Day");
            break;
        }

        if (!$this->_varRenderer) {
            require_once 'Horde/UI/VarRenderer.php';
            $this->_varRenderer = Horde_UI_VarRenderer::factory('html');
        }

        return '<label for="' . $this->_formIDEncode($property) . '" class="hidden">' . $label . '</label>' .
            '<select name="' . $property . '"' . $attributes . ' id="' . $this->_formIDEncode($property) . '">' .
            $this->_varRenderer->_selectOptions($options, $sel) .
            '</select>';
    }

    function js($property)
    {
        switch ($property) {
        case 'start[month]':
        case 'start[year]':
        case 'start[day]':
        case 'start':
            return 'updateWday(\'start_wday\'); document.eventform.whole_day.checked = false; updateEndDate();';

        case 'end[month]':
        case 'end[year]':
        case 'end[day]':
        case 'end':
            return 'updateWday(\'end_wday\'); updateDuration(); document.eventform.end_or_dur[0].checked = true;';

        case 'recur_enddate[month]':
        case 'recur_enddate[year]':
        case 'recur_enddate[day]':
        case 'recur_enddate':
            return 'updateWday(\'recur_end_wday\'); document.eventform.recur_enddate_type[1].checked = true;';

        case 'dur_day':
        case 'dur_hour':
        case 'dur_min':
            return 'document.eventform.whole_day.checked = false; updateEndDate(); document.eventform.end_or_dur[1].checked = true;';
        }
    }

    /**
     * @param array $params
     *
     * @return string
     */
    function getViewUrl($params = array())
    {
        $params['eventID'] = $this->eventID;
        if ($this->remoteUrl) {
            return $this->remoteUrl;
        } elseif ($this->remoteCal) {
            $params['calendar'] = '**remote';
            $params['remoteCal'] = $this->remoteCal;
        } else {
            $params['calendar'] = $this->getCalendar();
        }

        return Horde::applicationUrl(Util::addParameter('event.php', $params));
    }

    /**
     * @param array $params
     *
     * @return string
     */
    function getEditUrl($params = array())
    {
        $params['view'] = 'EditEvent';
        $params['eventID'] = $this->eventID;
        if ($this->remoteCal) {
            $params['calendar'] = '**remote';
            $params['remoteCal'] = $this->remoteCal;
        } else {
            $params['calendar'] = $this->getCalendar();
        }

        return Horde::applicationUrl(Util::addParameter('event.php', $params));
    }

    /**
     * @param array $params
     *
     * @return string
     */
    function getDeleteUrl($params = array())
    {
        $params['view'] = 'DeleteEvent';
        $params['eventID'] = $this->eventID;
        $params['calendar'] = $this->getCalendar();
        return Horde::applicationUrl(Util::addParameter('event.php', $params));
    }

    /**
     * @param array $params
     *
     * @return string
     */
    function getExportUrl($params = array())
    {
        $params['view'] = 'ExportEvent';
        $params['eventID'] = $this->eventID;
        if ($this->remoteCal) {
            $params['calendar'] = '**remote';
            $params['remoteCal'] = $this->remoteCal;
        } else {
            $params['calendar'] = $this->getCalendar();
        }

        return Horde::applicationUrl(Util::addParameter('event.php', $params));
    }

    function getLink($timestamp = null, $icons = true, $from_url = null)
    {
        global $prefs, $registry;

        if (is_null($timestamp)) {
            $timestamp = $this->start->timestamp();
        }
        if (is_null($from_url)) {
            $from_url = Horde::selfUrl(true, false, true);
        }

        $link = '';
        $event_title = $this->getTitle();
        if (isset($this->external)) {
            $link = $registry->link($this->external . '/show', $this->external_params);
            $link = Horde::linkTooltip(Horde::url($link), '', 'event-tentative', '', '', String::wrap($this->description));
        } elseif (isset($this->eventID) && $this->hasPermission(PERMS_READ)) {
            $link = Horde::linkTooltip($this->getViewUrl(array('timestamp' => $timestamp, 'url' => $from_url)),
                                       $event_title,
                                       $this->getStatusClass(), '', '',
                                       $this->getTooltip());
        }

        $link .= @htmlspecialchars($event_title, ENT_QUOTES, NLS::getCharset());

        if ($this->hasPermission(PERMS_READ) &&
            (isset($this->eventID) ||
             isset($this->external))) {
            $link .= '</a>';
        }

        if ($icons && $prefs->getValue('show_icons')) {
            $icon_color = isset($GLOBALS['cManager_fgColors'][$this->category]) ?
                ($GLOBALS['cManager_fgColors'][$this->category] == '#000' ? '000' : 'fff') :
                ($GLOBALS['cManager_fgColors']['_default_'] == '#000' ? '000' : 'fff');

            $status = '';
            if ($this->alarm) {
                if ($this->alarm % 10080 == 0) {
                    $alarm_value = $this->alarm / 10080;
                    $title = $alarm_value == 1 ?
                        _("Alarm 1 week before") :
                        sprintf(_("Alarm %d weeks before"), $alarm_value);
                } elseif ($this->alarm % 1440 == 0) {
                    $alarm_value = $this->alarm / 1440;
                    $title = $alarm_value == 1 ?
                        _("Alarm 1 day before") :
                        sprintf(_("Alarm %d days before"), $alarm_value);
                } elseif ($this->alarm % 60 == 0) {
                    $alarm_value = $this->alarm / 60;
                    $title = $alarm_value == 1 ?
                        _("Alarm 1 hour before") :
                        sprintf(_("Alarm %d hours before"), $alarm_value);
                } else {
                    $alarm_value = $this->alarm;
                    $title = $alarm_value == 1 ?
                        _("Alarm 1 minute before") :
                        sprintf(_("Alarm %d minutes before"), $alarm_value);
                }
                $status .= Horde::img('alarm-' . $icon_color . '.png', $title,
                                      array('title' => $title,
                                            'class' => 'iconAlarm'));
            }

            if ($this->recurs()) {
                $title = Kronolith::recurToString($this->recurrence->getRecurType());
                $status .= Horde::img('recur-' . $icon_color . '.png', $title,
                                      array('title' => $title,
                                            'class' => 'iconRecur'));
            }

            if ($this->isPrivate()) {
                $status .= Horde::img('locked.png', _("Private event"),
                                      array('title' => _("Private event"),
                                            'class' => 'iconPrivate'),
                                      $registry->getImageDir('horde'));
            }

            if (!empty($this->attendees)) {
                $title = count($this->attendees) == 1
                    ? _("1 attendee")
                    : sprintf(_("%s attendees"), count($this->attendees));
                $status .= Horde::img('attendees.png', $title,
                                      array('title' => $title,
                                            'class' => 'iconPeople'));
            }

            if (!empty($status)) {
                $link .= ' ' . $status;
            }

            if (!$this->eventID || !empty($this->external)) {
                return $link;
            }

            $edit = '';
            $delete = '';
            if ((!$this->isPrivate() || $this->getCreatorId() == Auth::getAuth())
                && $this->hasPermission(PERMS_EDIT)) {
                $editurl = $this->getEditUrl(array('timestamp' => $timestamp,
                                                   'url' => $from_url));
                $edit = Horde::link($editurl, sprintf(_("Edit %s"), $event_title), 'iconEdit')
                    . Horde::img('edit-' . $icon_color . '.png', _("Edit"))
                    . '</a>';
            }
            if ($this->hasPermission(PERMS_DELETE)) {
                $delurl = $this->getDeleteUrl(array('timestamp' => $timestamp,
                                                    'url' => $from_url));
                $delete = Horde::link($delurl, sprintf(_("Delete %s"), $event_title), 'iconDelete')
                    . Horde::img('delete-' . $icon_color . '.png', _("Delete"))
                    . '</a>';
            }

            if ($edit || $delete) {
                $link .= $edit . $delete;
            }
        }

        return $link;
    }

    /**
     * @return string  A tooltip for quick descriptions of this event.
     */
    function getTooltip()
    {
        $tooltip = $this->getTimeRange()
            . "\n" . sprintf(_("Owner: %s"), ($this->getCreatorId() == Auth::getAuth() ?
                                              _("Me") : Kronolith::getUserName($this->getCreatorId())));

        if (!$this->isPrivate() || $this->getCreatorId() == Auth::getAuth()) {
            if ($this->location) {
                $tooltip .= "\n" . _("Location") . ': ' . $this->location;
            }

            if ($this->description) {
                $tooltip .= "\n\n" . String::wrap($this->description);
            }
        }

        return $tooltip;
    }

    /**
     * @return string The time range of the event ("All Day",
     * "1:00pm-3:00pm", "08:00-22:00").
     */
    function getTimeRange()
    {
        if ($this->isAllDay()) {
            return _("All day");
        } elseif (($cmp = $this->start->compareDate($this->end)) > 0) {
            $df = $GLOBALS['prefs']->getValue('date_format');
            if ($cmp > 0) {
                return strftime($df, $this->end->timestamp()) . '-'
                    . strftime($df, $this->start->timestamp());
            } else {
                return strftime($df, $this->start->timestamp()) . '-'
                    . strftime($df, $this->end->timestamp());
            }
        } else {
            $tf = $GLOBALS['prefs']->getValue('twentyFour') ? 'G:i' : 'g:ia';
            return date($tf, $this->start->timestamp()) . '-'
                . date($tf, $this->end->timestamp());
        }
    }

    /**
     * @return string  The CSS class for the event based on its status.
     */
    function getStatusClass()
    {
        switch ($this->status) {
        case KRONOLITH_STATUS_CANCELLED:
            return 'event-cancelled';

        case KRONOLITH_STATUS_TENTATIVE:
        case KRONOLITH_STATUS_FREE:
            return 'event-tentative';
        }

        return 'event';
    }

    function _formIDEncode($id)
    {
        return str_replace(array('[', ']'),
                           array('_', ''),
                           $id);
    }

}