File: api.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 (1432 lines) | stat: -rw-r--r-- 50,150 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
<?php
/**
 * Kronolith external API interface.
 *
 * $Horde: kronolith/lib/api.php,v 1.126.2.43 2008/05/25 16:57:57 jan Exp $
 *
 * This file defines Kronolith's external API interface. Other applications
 * can interact with Kronolith through this API.
 *
 * @package Kronolith
 */

$_services['perms'] = array(
    'args' => array(),
    'type' => '{urn:horde}stringArray'
);

$_services['removeUserData'] = array(
    'args' => array('user' => 'string'),
    'type' => 'boolean'
);

$_services['shareHelp'] = array(
    'args' => array(),
    'type' => 'string');

$_services['show'] = array(
    'link' => '%application%/event.php?calendar=|calendar|' .
              '&eventID=|event|&uid=|uid|'
);

$_services['browse'] = array(
    'args' => array('path' => 'string'),
    'type' => '{urn:horde}hashHash',
);

$_services['put'] = array(
    'args' => array('path' => 'string', 'content' => 'string', 'content_type' => 'string'),
    'type' => '{urn:horde}stringArray',
);

$_services['path_delete'] = array(
    'args' => array('path' => 'string'),
    'type' => 'boolean',
);

$_services['getFreeBusy'] = array(
    'args' => array('startstamp' => 'int', 'endstamp' => 'int', 'calendar' => 'string'),
    'type' => '{urn:horde}stringArray'
);

$_services['listCalendars'] = array(
    'args' => array('owneronly' => 'boolean', 'permission' => 'int'),
    'type' => '{urn:horde}stringArray'
);

$_services['listEvents'] = array(
    'args' => array('startstamp' => 'int', 'endstamp' => 'int', 'calendar' => 'string', 'showRecurrence' => 'string', 'alarmsOnly' => 'boolean'),
    'type' => '{urn:horde}hashHash'
);

$_services['listAlarms'] = array(
    'args' => array('time' => 'int', 'user' => 'string'),
    'type' => '{urn:horde}hashHash'
);

$_services['list'] = array(
    'args' => array(),
    'type' => '{urn:horde}stringArray'
);

$_services['listBy'] = array(
    'args' => array('action' => 'string', 'timestamp' => 'int'),
    'type' => '{urn:horde}stringArray'
);

$_services['getActionTimestamp'] = array(
    'args' => array('uid' => 'string', 'timestamp' => 'int'),
    'type' => 'int',
);

$_services['import'] = array(
    'args' => array('content' => 'string', 'contentType' => 'string', 'calendar' => 'string'),
    'type' => 'int'
);

$_services['export'] = array(
    'args' => array('uid' => 'string', 'contentType' => 'string'),
    'type' => 'string'
);

$_services['exportCalendar'] = array(
    'args' => array('calendar' => 'string', 'contentType' => 'string'),
    'type' => 'string'
);

$_services['delete'] = array(
    'args' => array('uid' => 'string'),
    'type' => 'boolean'
);

$_services['replace'] = array(
    'args' => array('uid' => 'string', 'content' => 'string', 'contentType' => 'string'),
    'type' => 'boolean'
);

// FIXME: create complex type definition for SOAP calls.
$_services['eventFromUID'] = array(
    'args' => array('uid' => 'string'),
    'type' => 'object'
);

// FIXME: create complex type definition for SOAP calls.
$_services['updateAttendee'] = array(
    'args' => array('response' => 'object', 'sender' => 'string'),
    'type' => 'boolean'
);

$_services['subscribe'] = array(
    'args' => array('calendar' => '{urn:horde}stringArray'),
    'type' => 'boolean',
);

$_services['unsubscribe'] = array(
    'args' => array('calendar' => '{urn:horde}stringArray'),
    'type' => 'boolean',
);

/**
 * Returns a list of available permissions.
 *
 * @return array  An array describing all available permissions.
 */
function _kronolith_perms()
{
    $perms = array();
    $perms['tree']['kronolith']['max_events'] = false;
    $perms['title']['kronolith:max_events'] = _("Maximum Number of Events");
    $perms['type']['kronolith:max_events'] = 'int';

    return $perms;
}

/**
 * Removes user data.
 *
 * @param string $user  Name of user to remove data for.
 *
 * @return mixed  true on success | PEAR_Error on failure
 */
function _kronolith_removeUserData($user)
{
    if (!Auth::isAdmin() && $user != Auth::getAuth()) {
        return PEAR::raiseError(_("You are not allowed to remove user data."));
    }

    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    /* Remove all events owned by the user in all calendars. */
    $result = $kronolith_driver->removeUserData($user);

    /* Now delete history as well. */
    $history = &Horde_History::singleton();
    if (method_exists($history, 'removeByParent')) {
        $histories = $history->removeByParent('kronolith:' . $user);
    } else {
        /* Remove entries 100 at a time. */
        $all = array_keys($history->getByTimestamp('>', 0, array(), 'kronolith:' . $user));
        while (count($d = array_splice($all, 0, 100)) > 0) {
            $history->removebyNames($d);
        }
    }

    if (is_a($result, 'PEAR_Error')) {
        return $result;
    }

    return true;
}

/**
 * Returns the share helper prefix
 *
 * @return string
 */
function _kronolith_shareHelp()
{
    return 'shares';
}

/**
 * Returns the last modification timestamp for the given uid.
 *
 * @param string $uid      The uid to look for.
 *
 * @return integer  The timestamp for the last modification of $uid.
 */
function __kronolith_modified($uid)
{
    $modified = _kronolith_getActionTimestamp($uid, 'modify');
    if (empty($modified)) {
        $modified = _kronolith_getActionTimestamp($uid, 'add');
    }
    return $modified;
}

/**
 * Browse through Kronolith's object tree.
 *
 * @param string $path       The level of the tree to browse.
 * @param array $properties  The item properties to return. Defaults to 'name',
 *                           'icon', and 'browseable'.
 *
 * @return array  The contents of $path
 */
function _kronolith_browse($path = '', $properties = array())
{
    require_once dirname(__FILE__) . '/base.php';
    global $registry, $kronolith_driver;

    // Default properties.
    if (!$properties) {
        $properties = array('name', 'icon', 'browseable');
    }

    if (substr($path, 0, 9) == 'kronolith') {
        $path = substr($path, 9);
    }
    $path = trim($path, '/');
    $parts = explode('/', $path);

    if (empty($path)) {
        $owners = array();
        foreach ($calendars as $calendar) {
            $owners[$calendar->get('owner')] = true;
        }

        $results = array();
        foreach (array_keys($owners) as $owner) {
            if (in_array('name', $properties)) {
                $results['kronolith/' . $owner]['name'] = $owner;
            }
            if (in_array('icon', $properties)) {
                $results['kronolith/' . $owner]['icon'] =
                    $registry->getImageDir('horde') . '/user.png';
            }
            if (in_array('browseable', $properties)) {
                $results['kronolith/' . $owner]['browseable'] = true;
            }
            if (in_array('contenttype', $properties)) {
                $results['kronolith/' . $owner]['contenttype'] =
                    'httpd/unix-directory';
            }
            if (in_array('contentlength', $properties)) {
                $results['kronolith/' . $owner]['contentlength'] = 0;
            }
            if (in_array('modified', $properties)) {
                $results['kronolith/' . $owner]['modified'] =
                    $_SERVER['REQUEST_TIME'];
            }
            if (in_array('created', $properties)) {
                $results['kronolith/' . $owner]['created'] = 0;
            }
        }
        return $results;

    } elseif (count($parts) == 1) {
        //
        // This request is for all calendars owned by the requested user
        //
        $calendars = $GLOBALS['kronolith_shares']->listShares(Auth::getAuth(),
                                                              PERMS_SHOW,
                                                              $parts[0]);
        $results = array();
        foreach ($calendars as $calendarId => $calendar) {
            $retpath = 'kronolith/' . $parts[0] . '/' . $calendarId;
            if (in_array('name', $properties)) {
                $results[$retpath]['name'] = sprintf(_("Events from %s"), $calendar->get('name'));
                $results[$retpath . '.ics']['name'] = $calendar->get('name');
            }
            if (in_array('displayname', $properties)) {
                $results[$retpath]['displayname'] = rawurlencode($calendar->get('name'));
                $results[$retpath . '.ics']['displayname'] = rawurlencode($calendar->get('name')) . '.ics';
            }
            if (in_array('icon', $properties)) {
                $results[$retpath]['icon'] = $registry->getImageDir() . '/kronolith.png';
                $results[$retpath . '.ics']['icon'] = $registry->getImageDir() . '/mime/icalendar.png';
            }
            if (in_array('browseable', $properties)) {
                $results[$retpath]['browseable'] = $calendar->hasPermission(Auth::getAuth(), PERMS_READ);
                $results[$retpath . '.ics']['browseable'] = false;
            }
            if (in_array('contenttype', $properties)) {
                $results[$retpath]['contenttype'] = 'httpd/unix-directory';
                $results[$retpath . '.ics']['contenttype'] = 'text/calendar';
            }
            if (in_array('contentlength', $properties)) {
                $results[$retpath]['contentlength'] = 0;
                // FIXME:  This is a hack.  If the content length is longer
                // than the actual data then some WebDAV clients will report
                // an error when the file EOF is received.  Ideally we should
                // determine the actual size of the .ics and report it here, but
                // the performance hit may be prohibitive.  This requires
                // further investigation.
                $results[$retpath . '.ics']['contentlength'] = 1;
            }
            if (in_array('modified', $properties)) {
                $results[$retpath]['modified'] = $_SERVER['REQUEST_TIME'];
                $results[$retpath . '.ics']['modified'] = $_SERVER['REQUEST_TIME'];
            }
            if (in_array('created', $properties)) {
                $results[$retpath]['created'] = 0;
                $results[$retpath . '.ics']['created'] = 0;
            }
        }
        return $results;

    } elseif (count($parts) == 2 &&
              array_key_exists($parts[1],
                               Kronolith::listCalendars(false, PERMS_READ))) {
        //
        // This request is browsing into a specific calendar.  Generate the list
        // of items and represent them as files within the directory.
        //
        $kronolith_driver->open($parts[1]);
        $events = $kronolith_driver->listEvents();
        if (is_a($events, 'PEAR_Error')) {
            return $events;
        }

        $icon = $registry->getImageDir('horde') . '/mime/icalendar.png';
        $results = array();
        foreach ($events as $uid => $eventId) {
            $event = $kronolith_driver->getEvent($eventId);
            if (is_a($event, 'PEAR_Error')) {
                continue;
            }
            $key = 'kronolith/' . $path . '/' . $eventId;
            if (in_array('name', $properties)) {
                $results[$key]['name'] = $event->getTitle();
            }
            if (in_array('icon', $properties)) {
                $results[$key]['icon'] = $icon;
            }
            if (in_array('browseable', $properties)) {
                $results[$key]['browseable'] = false;
            }
            if (in_array('contenttype', $properties)) {
                $results[$key]['contenttype'] = 'text/calendar';
            }
            if (in_array('contentlength', $properties)) {
                // FIXME:  This is a hack.  If the content length is longer
                // than the actual data then some WebDAV clients will report
                // an error when the file EOF is received.  Ideally we should
                // determine the actual size of the data and report it here, but
                // the performance hit may be prohibitive.  This requires
                // further investigation.
                $results[$key]['contentlength'] = 1;
            }
            if (in_array('modified', $properties)) {
                $results[$key]['modified'] = __kronolith_modified($uid);
            }
            if (in_array('created', $properties)) {
                $results[$key]['created'] = _kronolith_getActionTimestamp($uid, 'add');
            }
        }
        return $results;
    } else {
        //
        // The only valid request left is for either a specific event
        // or for the entire calendar.
        //
        if (count($parts) == 3 &&
            array_key_exists($parts[1],
                             Kronolith::listCalendars(false, PERMS_READ))) {
            //
            // This request is for a specific item within a given calendar.
            //
            global $kronolith_driver;
            if ($kronolith_driver->getCalendar() != $parts[1]) {
                $kronolith_driver->open($parts[1]);
            }
            $event = &$kronolith_driver->getEvent($parts[2]);
            if (is_a($event, 'PEAR_Error')) {
                return $event;
            }

            $result = array(
                'data' => _kronolith_export($event->getUID(), 'text/calendar'),
                'mimetype' => 'text/calendar');
            $modified = __kronolith_modified($event->getUID());
            if (!empty($modified)) {
                $result['mtime'] = $modified;
            }
            return $result;
        } elseif (count($parts) == 2 &&
                  substr($parts[1], -4, 4) == '.ics' &&
                  array_key_exists(
                      substr($parts[1], 0, -4),
                      Kronolith::listCalendars(false, PERMS_READ))) {
            //
            // This request is for an entire calendar (calendar.ics).
            //
            $ical_data = _kronolith_exportCalendar(substr($parts[1], 0, -4), 'text/calendar');
            $result = array('data'          => $ical_data,
                            'mimetype'      => 'text/calendar',
                            'contentlength' => strlen($ical_data),
                            'mtime'         => $_SERVER['REQUEST_TIME']);

            return $result;
        } else {
            //
            // All other requests are a 404: Not Found
            //
            return false;
        }
    }
}

/**
 * Saves a file into the Kronolith tree.
 *
 * @param string $path          The path where to PUT the file.
 * @param string $content       The file content.
 * @param string $content_type  The file's content type.
 *
 * @return array  The event UIDs, or a PEAR_Error on failure.
 */
function _kronolith_put($path, $content, $content_type)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    if (substr($path, 0, 9) == 'kronolith') {
        $path = substr($path, 9);
    }
    $path = trim($path, '/');
    $parts = explode('/', $path);

    if (count($parts) == 2 &&
        substr($parts[1], -4) == '.ics') {

        // Workaround for WebDAV clients that are not smart enough to send
        // the right content type.  Assume text/calendar.
        if ($content_type == 'application/octet-stream') {
            $content_type = 'text/calendar';
        }
        $calendar = substr($parts[1], 0, -4);
    } elseif (count($parts) == 3) {
        $calendar = $parts[1];

        // Workaround for WebDAV clients that are not smart enough to send
        // the right content type.  Assume the same format we send individual
        // calendar items: text/x-vevent
        if ($content_type == 'application/octet-stream') {
            $content_type = 'text/x-vevent';
        }
    } else {
        return PEAR::raiseError("Invalid calendar data supplied.");
    }

    if (!array_key_exists($calendar, Kronolith::listCalendars(false, PERMS_EDIT))) {
        // FIXME: Should we attempt to create a calendar based on the filename
        // in the case that the requested calendar does not exist?
        return PEAR::raiseError("Calendar does not exist or no permission to edit");
    }

    // Store all currently existings UIDs. Use this info to delete UIDs not
    // present in $content after processing.
    $ids = array();
    $uids_remove = array_flip(_kronolith_list($calendar));

    switch ($content_type) {
    case 'text/calendar':
    case 'text/x-icalendar':
    case 'text/x-vcalendar':
    case 'text/x-vevent':
        require_once 'Horde/iCalendar.php';
        $iCal = new Horde_iCalendar();
        if (!is_a($content, 'Horde_iCalendar_vevent')) {
            if (!$iCal->parsevCalendar($content)) {
                return PEAR::raiseError(_("There was an error importing the iCalendar data."));
            }
        } else {
            $iCal->addComponent($content);
        }

        $components = $iCal->getComponents();
        if (count($components) == 0) {
            return PEAR::raiseError(_("No iCalendar data was found."));
        }

        foreach ($components as $content) {
            if (is_a($content, 'Horde_iCalendar_vevent')) {
                $event = &$kronolith_driver->getEvent();
                $event->fromiCalendar($content);
                $event->setCalendar($calendar);
                $uid = $event->getUID();
                // Remove from uids_remove list so we won't delete in
                // the end.
                if (isset($uids_remove[$uid])) {
                    unset($uids_remove[$uid]);
                }
                $existing_event = &$kronolith_driver->getByUID($uid, $calendar);
                if (!is_a($existing_event, 'PEAR_Error')) {
                    // Check if our event is newer then the existing - get the
                    // event's history.
                    $history = &Horde_History::singleton();
                    $created = $modified = null;
                    $log = $history->getHistory('kronolith:' . $calendar . ':' . $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($modified) && !empty($add)) {
                        $modified = $add;
                    }
                    if (!empty($modified) &&
                        $modified >= $content->getAttribute('LAST-MODIFIED')) {
                        // LAST-MODIFIED timestamp of existing entry is newer:
                        // don't replace it.
                        continue;
                    }

                    // Don't change creator/owner.
                    $event->setCreatorId($existing_event->getCreatorId());
                }

                // Save entry.
                $saved = $event->save();
                if (is_a($saved, 'PEAR_Error')) {
                    return $saved;
                }
                $ids[] = $event->getUID();
            }
        }
        break;

    default:
        return PEAR::raiseError(sprintf(_("Unsupported Content-Type: %s"), $content_type));
    }

    if (array_key_exists($calendar, Kronolith::listCalendars(false, PERMS_DELETE))) {
        foreach (array_keys($uids_remove) as $uid) {
            _kronolith_delete($uid);
        }
    }

    return $ids;
}

/**
 * Deletes a file from the Kronolith tree.
 *
 * @param string $path  The path to the file.
 *
 * @return mixed  The event's UID, or a PEAR_Error on failure.
 */
function _kronolith_path_delete($path)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    if (substr($path, 0, 9) == 'kronolith') {
        $path = substr($path, 9);
    }
    $path = trim($path, '/');
    $parts = explode('/', $path);

    if (substr($parts[1], -4) == '.ics') {
        $calendarId = substr($parts[1], 0, -4);
    } else {
        $calendarId = $parts[1];
    }

    if (!(count($parts) == 2 || count($parts) == 3) ||
        !array_key_exists($calendarId, Kronolith::listCalendars(false, PERMS_DELETE))) {
        return PEAR::raiseError("Calendar does not exist or no permission to delete");
    }

    if (count($parts) == 3) {
        // Delete just a single entry
        $kronolith_driver->open($calendarId);
        return $kronolith_driver->deleteEvent($parts[2]);
    } else {
        // Delete the entire calendar
        $result = $kronolith_driver->delete($calendarId);
        if (is_a($result, 'PEAR_Error')) {
            return PEAR::raiseError(sprintf(_("Unable to delete calendar \"%s\": %s"), $calendarId, $result->getMessage()));
        } else {
            // Remove share and all groups/permissions.
            $share = $GLOBALS['kronolith_shares']->getShare($calendarId);
            $result = $GLOBALS['kronolith_shares']->removeShare($share);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
        }
    }
}

/**
 * Returns all calendars a user has access to, according to several
 * parameters/permission levels.
 *
 * @param boolean $owneronly   Only return calenders that this user owns?
 *                             Defaults to false.
 * @param integer $permission  The permission to filter calendars by.
 *
 * @return array  The calendar list.
 */
function _kronolith_listCalendars($owneronly = false, $permission = null)
{
    require_once dirname(__FILE__) . '/base.php';
    if (is_null($permission)) {
        $permission = PERMS_SHOW;
    }
    return array_keys(Kronolith::listCalendars($owneronly, $permission));
}

/**
 * Returns all the events that happen within a time period.
 *
 * @param string $calendar      The calendar to check for events.
 * @param object $startstamp    The start of the time range.
 * @param object $endstamp      The end of the time range.
 *
 * @return array  The events happening in this time period.
 */
function _kronolith_list($calendar = null, $startstamp = 0, $endstamp = 0)
{
    require_once dirname(__FILE__) . '/base.php';

    if (empty($calendar)) {
        $calendar = Kronolith::getDefaultCalendar();
    }
    if (!array_key_exists($calendar,
                          Kronolith::listCalendars(false, PERMS_READ))) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    if (empty($startstamp)) {
        $startstamp = new Horde_Date(array('mday' => 1, 'month' => 1, 'year' => 0000));
    }

    if (empty($endstamp)) {
        $endstamp = new Horde_Date(array('year' => 9999, 'month' => 12, 'day' => 31));
    }

    $ids = Kronolith::listEventIds($startstamp, $endstamp, $calendar);
    if (is_a($ids, 'PEAR_Error')) {
        return $ids;
    }

    $uids = array();
    foreach ($ids as $cal) {
        $uids = array_merge($uids, array_keys($cal));
    }

    return $uids;
}

/**
 * Returns an array of UIDs for events that have had $action happen since
 * $timestamp.
 *
 * @param string  $action     The action to check for - add, modify, or delete.
 * @param integer $timestamp  The time to start the search.
 * @param string  $calendar   The calendar to search in.
 *
 * @return array  An array of UIDs matching the action and time criteria.
 */
function _kronolith_listBy($action, $timestamp, $calendar = null)
{
    require_once dirname(__FILE__) . '/base.php';

    if (empty($calendar)) {
        $calendar = Kronolith::getDefaultCalendar();
    }

    if (!array_key_exists($calendar,
                          Kronolith::listCalendars(false, PERMS_READ))) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    $history = &Horde_History::singleton();
    $histories = $history->getByTimestamp('>', $timestamp, array(array('op' => '=', 'field' => 'action', 'value' => $action)), 'kronolith:' . $calendar);
    if (is_a($histories, 'PEAR_Error')) {
        return $histories;
    }

    // Strip leading kronolith:username:.
    return preg_replace('/^([^:]*:){2}/', '', array_keys($histories));
}

/**
 * Returns the timestamp of an operation for a given uid an action
 *
 * @param string $uid      The uid to look for.
 * @param string $action   The action to check for - add, modify, or delete.
 * @param string $calendar The calendar to search in.
 *
 * @return integer  The timestamp for this action.
 */
function _kronolith_getActionTimestamp($uid, $action, $calendar = null)
{
    require_once dirname(__FILE__) . '/base.php';

    if (empty($calendar)) {
        $calendar = Kronolith::getDefaultCalendar();
    }

    if (!array_key_exists($calendar,
                          Kronolith::listCalendars(false, PERMS_READ))) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    $history = &Horde_History::singleton();
    return $history->getActionTimestamp('kronolith:' . $calendar . ':' .
                                        $uid, $action);
}

/**
 * Imports an event represented in the specified content type.
 *
 * @param string $content      The content of the event.
 * @param string $contentType  What format is the data in? Currently supports:
 *                             <pre>
 *                             text/calendar
 *                             text/x-icalendar
 *                             text/x-vcalendar
 *                             text/x-vevent
 *                             </pre>
 * @param string $calendar     What calendar should the event be added to?
 *
 * @return mixed  The event's UID, or a PEAR_Error on failure.
 */
function _kronolith_import($content, $contentType, $calendar = null)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    if (!isset($calendar)) {
        $calendar = Kronolith::getDefaultCalendar(PERMS_EDIT);
    }
    if (!array_key_exists($calendar,
                          Kronolith::listCalendars(false, PERMS_EDIT))) {
        return PEAR::raiseError(_("Permission Denied"));
    }
    $kronolith_driver->open($calendar);

    switch ($contentType) {
    case 'text/calendar':
    case 'text/x-icalendar':
    case 'text/x-vcalendar':
    case 'text/x-vevent':
        require_once 'Horde/iCalendar.php';
        $iCal = new Horde_iCalendar();
        if (!is_a($content, 'Horde_iCalendar_vevent')) {
            if (!$iCal->parsevCalendar($content)) {
                return PEAR::raiseError(_("There was an error importing the iCalendar data."));
            }
        } else {
            $iCal->addComponent($content);
        }

        $components = $iCal->getComponents();
        if (count($components) == 0) {
            return PEAR::raiseError(_("No iCalendar data was found."));
        }

        $ids = array();
        foreach ($components as $content) {
            if (is_a($content, 'Horde_iCalendar_vevent')) {
                $event = &$kronolith_driver->getEvent();
                $event->fromiCalendar($content);
                $event->setCalendar($calendar);
                // Check if the entry already exists in the data source, first
                // by UID.
                $uid = $event->getUID();
                $existing_event = &$kronolith_driver->getByUID($uid, $calendar);
                if (!is_a($existing_event, 'PEAR_Error')) {
                    return PEAR::raiseError(_("Already Exists"), 'horde.message', null, null, $uid);
                }
                $result = $kronolith_driver->search($event);
                // Check if the match really is an exact match:
                if (is_array($result) && count($result) > 0) {
                    foreach($result as $match) {
                        if ($match->start == $event->start &&
                            $match->end == $event->end &&
                            $match->title == $event->title &&
                            $match->location == $event->location &&
                            $match->hasPermission(PERMS_EDIT)) {
                            return PEAR::raiseError(_("Already Exists"), 'horde.message', null, null, $match->getUID());
                        }
                    }
                }

                $eventId = $event->save();
                if (is_a($eventId, 'PEAR_Error')) {
                    return $eventId;
                }
                $ids[] = $event->getUID();
            }
        }
        if (count($ids) == 0) {
            return PEAR::raiseError(_("No iCalendar data was found."));
        } else if (count($ids) == 1) {
            return $ids[0];
        }
        return $ids;
    }

    return PEAR::raiseError(sprintf(_("Unsupported Content-Type: %s"), $contentType));

}

/**
 * Exports an event, identified by UID, in the requested content type.
 *
 * @param string $uid         Identify the event to export.
 * @param string $contentType  What format should the data be in?
 *                            A string with one of:
 *                            <pre>
 *                             text/calendar (VCALENDAR 2.0. Recommended as
 *                                            this is specified in rfc2445)
 *                             text/x-vtodo    Seems to be used by horde only.
 *                                             Do we need this?
 *                             text/x-vcalendar (old VCALENDAR 1.0 format.
 *                                              Still in wide use)
 *                             text/x-icalendar
 *                            </pre>
 *
 * @return string  The requested data.
 */
function _kronolith_export($uid, $contentType)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver, $kronolith_shares;

    $event = $kronolith_driver->getByUID($uid);
    if (is_a($event, 'PEAR_Error')) {
        return $event;
    }
    if (!$event->hasPermission(PERMS_READ)) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    $version = '2.0';
    switch ($contentType) {
    case 'text/x-vcalendar':
        $version = '1.0';
    case 'text/calendar':
    case 'text/x-icalendar':
    case 'text/x-vtodo':
        $share = &$kronolith_shares->getShare($event->getCalendar());

        require_once 'Horde/iCalendar.php';
        $iCal = new Horde_iCalendar($version);
        $iCal->setAttribute('X-WR-CALNAME', String::convertCharset($share->get('name'), NLS::getCharset(), 'utf-8'));

        // Create a new vEvent.
        $vEvent = &$event->toiCalendar($iCal);
        $iCal->addComponent($vEvent);

        return $iCal->exportvCalendar();

    }

    return PEAR::raiseError(sprintf(_("Unsupported Content-Type: %s"), $contentType));;

}

/**
 * Exports a calendar in the requested content type.
 *
 * @param string $calendar    The calendar to export.
 * @param string $contentType  What format should the data be in?
 *                             A string with one of:
 *                             <pre>
 *                             text/calendar (VCALENDAR 2.0. Recommended as
 *                                            this is specified in rfc2445)
 *                             text/x-vtodo    Seems to be used by horde only.
 *                                             Do we need this?
 *                             text/x-vcalendar (old VCALENDAR 1.0 format.
 *                                              Still in wide use)
 *                             text/x-icalendar
 *                             </pre>
 *
 * @return string  The iCalendar representation of the calendar.
 */
function _kronolith_exportCalendar($calendar, $contentType)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver, $kronolith_shares;

    if (!array_key_exists($calendar,
                          Kronolith::listCalendars(false, PERMS_READ))) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    if ($kronolith_driver->getCalendar() != $calendar) {
        $kronolith_driver->open($calendar);
    }

    $events = $kronolith_driver->listEvents(null, null);

    $version = '2.0';
    switch ($contentType) {
    case 'text/x-vcalendar':
        $version = '1.0';
    case 'text/calendar':
    case 'text/x-icalendar':
    case 'text/x-vtodo':
        $share = &$kronolith_shares->getShare($calendar);

        require_once 'Horde/iCalendar.php';
        $iCal = new Horde_iCalendar($version);
        $iCal->setAttribute('X-WR-CALNAME', String::convertCharset($share->get('name'), NLS::getCharset(), 'utf-8'));

        foreach ($events as $id) {
            $event = &$kronolith_driver->getEvent($id);
            if (is_a($event, 'PEAR_Error')) {
                return $event;
            }
            $vEvent = &$event->toiCalendar($iCal);
            $iCal->addComponent($vEvent);
        }

        return $iCal->exportvCalendar();
    }

    return PEAR::raiseError(sprintf(_("Unsupported Content-Type: %s"), $contentType));

}

/**
 * Deletes an event identified by UID.
 *
 * @param string|array $uid  A single UID or an array identifying the event(s)
 *                           to delete.
 *
 * @return boolean  Success or failure.
 */
function _kronolith_delete($uid)
{
    /* Handle an array of UIDs for convenience of deleting multiple events at
     * once. */
    if (is_array($uid)) {
        foreach ($uid as $g) {
            $result = _kronolith_delete($g);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
        }

        return true;
    }

    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    $events = $kronolith_driver->getByUID($uid, null, true);
    if (is_a($events, 'PEAR_Error')) {
        return $events;
    }

    $event = null;
    if (Auth::isAdmin()) {
        $event = $events[0];
    }

    /* First try the user's own calendars. */
    if (empty($event)) {
        $ownerCalendars = Kronolith::listCalendars(true, PERMS_DELETE);
        foreach ($events as $ev) {
            if (Auth::isAdmin() || isset($ownerCalendars[$ev->getCalendar()])) {
                $event = $ev;
                break;
            }
        }
    }

    /* If not successful, try all calendars the user has access too. */
    if (empty($event)) {
        $deletableCalendars = Kronolith::listCalendars(false, PERMS_DELETE);
        foreach ($events as $ev) {
            if (isset($deletableCalendars[$ev->getCalendar()])) {
                $kronolith_driver->open($ev->getCalendar());
                $event = $ev;
                break;
            }
        }
    }

    if (empty($event)) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    return $kronolith_driver->deleteEvent($event->getId());
}

/**
 * Replaces the event identified by UID with the content represented in the
 * specified contentType.
 *
 * @param string $uid          Idenfity the event to replace.
 * @param mixed  $content      The content of the event. String or
 *                             Horde_iCalendar_vevent
 * @param string $contentType  What format is the data in? Currently supports:
 *                             text/calendar
 *                             text/x-icalendar
 *                             text/x-vcalendar
 *                             text/x-vevent
 *                             (Ignored if content is Horde_iCalendar_vevent)
 *
 * @return mixed  True on success, PEAR_Error otherwise.
 */
function _kronolith_replace($uid, $content, $contentType)
{
    require_once dirname(__FILE__) . '/base.php';
    global $kronolith_driver;

    $event = $kronolith_driver->getByUID($uid);
    if (is_a($event, 'PEAR_Error')) {
        return $event;
    }

    if (!$event->hasPermission(PERMS_EDIT) ||
        ($event->isPrivate() && $event->getCreatorId() != Auth::getAuth())) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    if (is_a($content, 'Horde_iCalendar_vevent')) {
        $component = $content;
    } else {
        switch ($contentType) {
        case 'text/calendar':
        case 'text/x-icalendar':
        case 'text/x-vcalendar':
        case 'text/x-vevent':
            if (!is_a($content, 'Horde_iCalendar_vevent')) {
                require_once 'Horde/iCalendar.php';
                $iCal = new Horde_iCalendar();
                if (!$iCal->parsevCalendar($content)) {
                    return PEAR::raiseError(_("There was an error importing the iCalendar data."));
                }

                $components = $iCal->getComponents();
                $component = null;
                foreach ($components as $content) {
                    if (is_a($content, 'Horde_iCalendar_vevent')) {
                        if ($component !== null) {
                            return PEAR::raiseError(_("Multiple iCalendar components found; only one vEvent is supported."));
                        }
                        $component = $content;
                    }

                }
                if ($component === null) {
                    return PEAR::raiseError(_("No iCalendar data was found."));
                }
            }
            break;
        default:
            return PEAR::raiseError(sprintf(_("Unsupported Content-Type: %s"), $contentType));
        }
    }

    $event->fromiCalendar($component);
    /* Ensure we keep the original UID, even when content does not
     * contain one and fromiCalendar creates a new one. */
    $event->setUID($uid);
    $eventId = $event->save();

    return is_a($eventId, 'PEAR_Error') ? $eventId : true;
}

/**
 * Generates free/busy information for a given time period.
 *
 * @param integer $startstamp  The start of the time period to retrieve.
 * @param integer $endstamp    The end of the time period to retrieve.
 * @param string $calendar     The calendar to view free/busy slots for.
 *                             Defaults to the user's default calendar.
 *
 * @return Horde_iCalendar_vfreebusy  A freebusy object that covers the
 *                                    specified time period.
 */
function _kronolith_getFreeBusy($startstamp = null, $endstamp = null,
                                $calendar = null)
{
    require_once dirname(__FILE__) . '/base.php';
    require_once KRONOLITH_BASE . '/lib/FreeBusy.php';

    if (is_null($calendar)) {
        $calendar = Kronolith::getDefaultCalendar();
    }
    // Free/Busy information is globally available; no permission
    // check is needed.

    return Kronolith_FreeBusy::generate($calendar, $startstamp, $endstamp, true);
}

/**
 * Retrieves a Kronolith_Event object, given an event UID.
 *
 * @param string $uid  The event's UID.
 *
 * @return Kronolith_Event  A valid Kronolith_Event on success, or a PEAR_Error
 *                          on failure.
 */
function &_kronolith_eventFromUID($uid)
{
    require_once dirname(__FILE__) . '/base.php';

    $event = $GLOBALS['kronolith_driver']->getByUID($uid);
    if (is_a($event, 'PEAR_Error')) {
        return $event;
    }
    if (!$event->hasPermission(PERMS_SHOW)) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    return $event;
}

/**
 * Updates an attendee's response status for a specified event.
 *
 * @param Horde_iCalender_vevent $response  A Horde_iCalender_vevent object,
 *                                          with a valid UID attribute that
 *                                          points to an existing event.
 *                                          This is typically the vEvent
 *                                          portion of an iTip meeting-request
 *                                          response, with the attendee's
 *                                          response in an ATTENDEE parameter.
 * @param string $sender                    The email address of the person
 *                                          initiating the update. Attendees
 *                                          are only updated if this address
 *                                          matches.
 *
 * @return mixed  True on success, PEAR_Error on failure.
 */
function _kronolith_updateAttendee($response, $sender = null)
{
    require_once dirname(__FILE__) . '/base.php';

    $uid = $response->getAttribute('UID');
    if (is_a($uid, 'PEAR_Error')) {
        return $uid;
    }

    $events = $GLOBALS['kronolith_driver']->getByUID($uid, null, true);
    if (is_a($events, 'PEAR_Error')) {
        return $events;
    }

    /* First try the user's own calendars. */
    $ownerCalendars = Kronolith::listCalendars(true, PERMS_EDIT);
    $event = null;
    foreach ($events as $ev) {
        if (isset($ownerCalendars[$ev->getCalendar()])) {
            $event = $ev;
            break;
        }
    }

    /* If not successful, try all calendars the user has access to. */
    if (empty($event)) {
        $editableCalendars = Kronolith::listCalendars(false, PERMS_EDIT);
        foreach ($events as $ev) {
            if (isset($editableCalendars[$ev->getCalendar()])) {
                $event = $ev;
                break;
            }
        }
    }

    if (empty($event) ||
        ($event->isPrivate() && $event->getCreatorId() != Auth::getAuth())) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    $atnames = $response->getAttribute('ATTENDEE');
    if (!is_array($atnames)) {
        $atnames = array($atnames);
    }
    $atparms = $response->getAttribute('ATTENDEE', true);

    $found = false;
    $error = _("No attendees have been updated because none of the provided email addresses have been found in the event's attendees list.");
    foreach ($atnames as $index => $attendee) {
        $attendee = str_replace('mailto:', '', String::lower($attendee));
        $name = isset($atparms[$index]['CN']) ? $atparms[$index]['CN'] : null;
        if ($event->hasAttendee($attendee)) {
            if (is_null($sender) || $sender == $attendee) {
                $event->addAttendee($attendee, KRONOLITH_PART_IGNORE, Kronolith::responseFromICal($atparms[$index]['PARTSTAT']), $name);
                $found = true;
            } else {
                $error = _("The attendee hasn't been updated because the update was not sent from the attendee.");
            }
        }
    }

    $result = $event->save();
    if (is_a($result, 'PEAR_Error')) {
        return $result;
    }

    if (!$found) {
        return PEAR::raiseError($error);
    }

    return true;
}

/**
 * Lists events for a given time period.
 *
 * @param integer $startstamp      The start of the time period to retrieve.
 * @param integer $endstamp        The end of the time period to retrieve.
 * @param array   $calendars       The calendars to view events from.
 *                                 Defaults to the user's default calendar.
 * @param boolean $showRecurrence  Return every instance of a recurring event?
 *                                 If false, will only return recurring events
 *                                 once inside the $startDate - $endDate range.
 * @param boolean $alarmsOnly      Filter results for events with alarms.
 *                                 Defaults to false.
 *
 * @return array  A list of event hashes.
 */
function _kronolith_listEvents($startstamp = null, $endstamp = null,
                               $calendars = null, $showRecurrence = true,
                               $alarmsOnly = false)
{
    require_once dirname(__FILE__) . '/base.php';

    if (!isset($calendars)) {
        $calendars = array($GLOBALS['prefs']->getValue('default_share'));
    } elseif (!is_array($calendars)) {
        $calendars = array($calendars);
    }
    $allowed_calendars = Kronolith::listCalendars(false, PERMS_READ);
    foreach ($calendars as $calendar) {
        if (!array_key_exists($calendar, $allowed_calendars)) {
            return PEAR::raiseError(_("Permission Denied"));
        }
    }

    // Check to see if either start or endstamp wasn't specified.
    if (empty($startstamp) && $startstamp !== 0) {
        $startstamp = null;
    }
    if (empty($endstamp) && $endstamp !== 0) {
        $endstamp = null;
    }

    return Kronolith::listEvents($startstamp, $endstamp, $calendars, $showRecurrence, $alarmsOnly);
}

/**
 * Lists alarms for a given moment.
 *
 * @param integer $time  The time to retrieve alarms for.
 * @param string $user   The user to retrieve alarms for. All users if null.
 *
 * @return array  An array of UIDs
 */
function _kronolith_listAlarms($time, $user = null)
{
    require_once dirname(__FILE__) . '/base.php';
    require_once 'Horde/Group.php';

    $current_user = Auth::getAuth();
    if ((empty($user) || $user != $current_user) && !Auth::isAdmin()) {
        return PEAR::raiseError(_("Permission Denied"));
    }

    $group = &Group::singleton();
    $alarm_list = array();
    $time = new Horde_Date($time);
    $calendars = is_null($user) ? array_keys($GLOBALS['kronolith_shares']->listAllShares()) : $GLOBALS['display_calendars'];
    $alarms = Kronolith::listAlarms($time, $calendars, true);
    if (is_a($alarms, 'PEAR_Error')) {
        return $alarms;
    }
    foreach ($alarms as $calendar => $cal_alarms) {
        $share = $GLOBALS['kronolith_shares']->getShare($calendar);
        if (is_a($share, 'PEAR_Error')) {
            continue;
        }
        if (empty($user)) {
            $users = $share->listUsers(PERMS_READ);
            $groups = $share->listGroups(PERMS_READ);
            foreach ($groups as $gid) {
                $group_users = $group->listUsers($gid);
                if (!is_a($group_users, 'PEAR_Error')) {
                    $users = array_merge($users, $group_users);
                }
            }
            $users = array_unique($users);
        } else {
            $users = array($user);
        }
        $owner = $share->get('owner');
        foreach ($cal_alarms as $event) {
            foreach ($users as $alarm_user) {
                if ($alarm_user == $current_user) {
                    $prefs = &$GLOBALS['prefs'];
                } else {
                    $prefs = &Prefs::singleton($GLOBALS['conf']['prefs']['driver'],
                                               'kronolith', $alarm_user, null,
                                               null, false);
                }
                $shown_calendars = unserialize($prefs->getValue('display_cals'));
                $reminder = $prefs->getValue('event_reminder');
                if (($reminder == 'owner' && $alarm_user == $owner) ||
                    ($reminder == 'show' && in_array($calendar, $shown_calendars)) ||
                    $reminder == 'read') {
                    NLS::setLang($prefs->getValue('language'));
                    NLS::setTextdomain('kronolith', KRONOLITH_BASE . '/locale', NLS::getCharset());
                    String::setDefaultCharset(NLS::getCharset());
                    $alarm = $event->toAlarm($time, $alarm_user, $prefs);
                    if ($alarm) {
                        $alarm_list[] = $alarm;
                    }
                }
            }
        }
    }

    return $alarm_list;
}

/**
 * Subscribe to a calendar.
 *
 * @param array $calendar  Calendar description hash, with required 'type'
 *                         parameter. Currently supports 'http' and 'webcal'
 *                         for remote calendars.
 */
function _kronolith_subscribe($calendar)
{
    if (!isset($calendar['type'])) {
        return PEAR::raiseError(_("Unknown calendar protocol"));
    }

    switch ($calendar['type']) {
    case 'http':
    case 'webcal':
        $username = isset($calendar['username']) ? $calendar['username'] : null;
        $password = isset($calendar['password']) ? $calendar['password'] : null;

        $cals = unserialize($GLOBALS['prefs']->getValue('remote_cals'));
        if (!is_array($cals)) {
            $cals = array();
        }
        $array_key = count($cals);
        foreach ($cals as $key => $cal) {
            if ($cal['url'] == $calendar['url']) {
                $array_key = $key;
                break;
            }
        }

        $cals[$array_key] = array('name' => $calendar['name'],
                                  'url'  => $calendar['url'],
                                  'user' => $username,
                                  'password' => $password);
        $GLOBALS['prefs']->setValue('remote_cals', serialize($cals));
        break;

    case 'external':
        $cals = unserialize($GLOBALS['prefs']->getValue('display_external_cals'));
        if (array_search($calendar['name'], $cals) === false) {
            $cals[] = $calendar['name'];
            $GLOBALS['prefs']->setValue('display_external_cals', serialize($cals));
        }

    default:
        return PEAR::raiseError(_("Unknown calendar protocol"));
    }
}

/**
 * Unsubscribe from a calendar.
 *
 * @param array $calendar  Calendar description array, with required 'type'
 *                         parameter. Currently supports 'http' and 'webcal'
 *                         for remote calendars.
 */
function _kronolith_unsubscribe($calendar)
{
    if (!isset($calendar['type'])) {
        return PEAR::raiseError('Unknown calendar specification');
    }

    switch ($calendar['type']) {
    case 'http':
    case 'webcal':
        $cals = unserialize($GLOBALS['prefs']->getValue('remote_cals'));
        foreach ($cals as $key => $cal) {
            if ($cal['url'] == $calendar['url']) {
                unset($cals[$key]);
                break;
            }
        }

        $GLOBALS['prefs']->setValue('remote_cals', serialize($cals));
        break;

    case 'external':
        $cals = unserialize($GLOBALS['prefs']->getValue('display_external_cals'));
        if (($key = array_search($calendar['name'], $cals)) !== false) {
            unset($cals[$key]);
            $GLOBALS['prefs']->setValue('display_external_cals', serialize($cals));
        }

    default:
        return PEAR::raiseError('Unknown calendar specification');
    }
}