/
Api.php
1629 lines (1491 loc) · 62.9 KB
/
Api.php
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
<?php
/**
* Kronolith external API interface.
*
* This file defines Kronolith's external API interface. Other applications
* can interact with Kronolith through this API.
*
* @package Kronolith
*/
class Kronolith_Api extends Horde_Registry_Api
{
/**
* Links.
*
* @var array
*/
protected $_links = array(
'show' => '%application%/event.php?calendar=|calendar|&eventID=|event|&uid=|uid|'
);
/**
* Returns the share helper prefix
*
* @return string
*/
public function shareHelp()
{
return 'shares';
}
/**
* Returns the last modification timestamp for the given uid.
*
* @param string $uid The uid to look for.
* @param string $calendar The calendar to search in.
*
* @return integer The timestamp for the last modification of $uid.
*/
public function modified($uid, $calendar = null)
{
$modified = $this->getActionTimestamp($uid, 'modify', $calendar);
if (empty($modified)) {
$modified = $this->getActionTimestamp($uid, 'add', $calendar);
}
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
* @throws Kronolith_Exception
*/
public function browse($path = '', $properties = array())
{
// 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)) {
// This request is for a list of all users who have calendars
// visible to the requesting user.
$calendars = Kronolith::listInternalCalendars(false, Horde_Perms::READ);
$owners = array();
foreach ($calendars as $calendar) {
$owners[$calendar->get('owner') ? $calendar->get('owner') : '-system-'] = true;
}
$results = array();
foreach (array_keys($owners) as $owner) {
$path = 'kronolith/' . $owner;
if (in_array('name', $properties)) {
$results[$path]['name'] = $owner;
}
if (in_array('icon', $properties)) {
$results[$path]['icon'] = Horde_Themes::img('user.png');
}
if (in_array('browseable', $properties)) {
$results[$path]['browseable'] = true;
}
if (in_array('read-only', $properties)) {
$results[$path]['read-only'] = true;
}
}
return $results;
} elseif (count($parts) == 1) {
// This request is for all calendars owned by the requested user
$owner = $parts[0] == '-system-' ? '' : $parts[0];
$calendars = $GLOBALS['injector']->getInstance('Kronolith_Shares')->listShares(
$GLOBALS['registry']->getAuth(),
array('perm' => Horde_Perms::SHOW,
'attributes' => $owner));
$results = array();
foreach ($calendars as $calendarId => $calendar) {
if ($parts[0] == '-system-' && $calendar->get('owner')) {
continue;
}
$retpath = 'kronolith/' . $parts[0] . '/' . $calendarId;
if (in_array('name', $properties)) {
$results[$retpath]['name'] = sprintf(_("Events from %s"), Kronolith::getLabel($calendar));
$results[$retpath . '.ics']['name'] = Kronolith::getLabel($calendar);
}
if (in_array('displayname', $properties)) {
$results[$retpath]['displayname'] = rawurlencode(Kronolith::getLabel($calendar));
$results[$retpath . '.ics']['displayname'] = rawurlencode(Kronolith::getLabel($calendar)) . '.ics';
}
if (in_array('icon', $properties)) {
$results[$retpath]['icon'] = Horde_Themes::img('kronolith.png');
$results[$retpath . '.ics']['icon'] = Horde_Themes::img('mime/icalendar.png');
}
if (in_array('browseable', $properties)) {
$results[$retpath]['browseable'] = $calendar->hasPermission($GLOBALS['registry']->getAuth(), Horde_Perms::READ);
$results[$retpath . '.ics']['browseable'] = false;
}
if (in_array('contenttype', $properties)) {
$results[$retpath . '.ics']['contenttype'] = 'text/calendar';
}
}
return $results;
} elseif (count($parts) == 2 &&
array_key_exists($parts[1], Kronolith::listInternalCalendars(false, Horde_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 = Kronolith::getDriver(null, $parts[1]);
$events = $kronolith_driver->listEvents();
$icon = Horde_Themes::img('mime/icalendar.png');
$results = array();
foreach ($events as $dayevents) {
foreach ($dayevents as $event) {
$key = 'kronolith/' . $path . '/' . $event->id;
if (in_array('modified', $properties) ||
in_array('etag', $properties)) {
$modified = $this->modified($event->uid, $parts[1]);
}
if (in_array('name', $properties)) {
$results[$key]['name'] = $event->getTitle();
}
if (in_array('owner', $properties)) {
$results[$key]['owner'] = $calendar->get('owner') ?: '-system-';
}
if (in_array('icon', $properties)) {
$results[$key]['icon'] = $icon;
}
if (in_array('browseable', $properties)) {
$results[$key]['browseable'] = false;
}
if (in_array('read-only', $properties)) {
$results[$key]['read-only'] = !$calendar->hasPermission($currentUser, Horde_Perms::EDIT);
}
if (in_array('contenttype', $properties)) {
$results[$key]['contenttype'] = 'text/calendar';
}
if (in_array('modified', $properties)) {
$results[$key]['modified'] = $modified;
}
if (in_array('created', $properties)) {
$results[$key]['created'] = $this->getActionTimestamp($event->uid, 'add');
}
if (in_array('etag', $properties)) {
$results[$key]['etag'] = '"' . md5($event->id . '|' . $modified) . '"';
}
}
}
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::listInternalCalendars(false, Horde_Perms::READ))) {
// This request is for a specific item within a given calendar.
$event = Kronolith::getDriver(null, $parts[1])->getEvent($parts[2]);
$result = array(
'data' => $this->export($event->uid, 'text/calendar'),
'mimetype' => 'text/calendar');
$modified = $this->modified($event->uid, $parts[1]);
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::listInternalCalendars(false, Horde_Perms::READ))) {
// This request is for an entire calendar (calendar.ics).
$ical_data = $this->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.
* @throws Kronolith_Exception
*/
public function put($path, $content, $content_type)
{
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 text/calendar.
if ($content_type == 'application/octet-stream') {
$content_type = 'text/calendar';
}
} else {
throw new Kronolith_Exception(_("Invalid calendar data supplied."));
}
if (!Kronolith::hasPermission($calendar, Horde_Perms::EDIT)) {
// FIXME: Should we attempt to create a calendar based on the
// filename in the case that the requested calendar does not
// exist?
throw new Kronolith_Exception(_("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($this->listUids($calendar));
switch ($content_type) {
case 'text/calendar':
case 'text/x-vcalendar':
$iCal = new Horde_Icalendar();
if (!($content instanceof Horde_Icalendar_Vevent)) {
if (!$iCal->parsevCalendar($content)) {
throw new Kronolith_Exception(_("There was an error importing the iCalendar data."));
}
} else {
$iCal->addComponent($content);
}
$kronolith_driver = Kronolith::getDriver();
foreach ($iCal->getComponents() as $content) {
if ($content instanceof Horde_Icalendar_Vevent) {
$event = $kronolith_driver->getEvent();
$event->fromiCalendar($content);
$uid = $event->uid;
// Remove from uids_remove list so we won't delete in the
// end.
if (isset($uids_remove[$uid])) {
unset($uids_remove[$uid]);
}
try {
$existing_event = $kronolith_driver->getByUID($uid, array($calendar));
// Check if our event is newer then the existing - get
// the event's history.
$created = $modified = null;
try {
$history = $GLOBALS['injector']->getInstance('Horde_History');
$created = $history->getActionTimestamp(
'kronolith:' . $calendar . ':' . $uid, 'add');
$modified = $history->getActionTimestamp(
'kronolith:' . $calendar . ':' . $uid, 'modify');
/* The history driver returns 0 for not found. If 0
* or null does not matter, strip this */
if ($created == 0) {
$created = null;
}
if ($modified == 0) {
$modified = null;
}
} catch (Horde_Exception $e) {
}
if (empty($modified) && !empty($created)) {
$modified = $created;
}
try {
if (!empty($modified) &&
$modified >= $content->getAttribute('LAST-MODIFIED')) {
// LAST-MODIFIED timestamp of existing entry
// is newer: don't replace it.
continue;
}
} catch (Horde_Icalendar_Exception $e) {
}
// Don't change creator/owner.
$event->creator = $existing_event->creator;
} catch (Horde_Exception_NotFound $e) {
}
// Save entry.
$event->save();
$ids[] = $event->uid;
}
}
break;
default:
throw new Kronolith_Exception(sprintf(_("Unsupported Content-Type: %s"), $content_type));
}
if (Kronolith::hasPermission($calendar, Horde_Perms::DELETE)) {
foreach (array_keys($uids_remove) as $uid) {
$this->delete($uid);
}
}
return $ids;
}
/**
* Deletes a file from the Kronolith tree.
*
* @param string $path The path to the file.
*
* @throws Kronolith_Exception
*/
public function path_delete($path)
{
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) ||
!Kronolith::hasPermission($calendarId, Horde_Perms::DELETE)) {
throw new Kronolith_Exception(_("Calendar does not exist or no permission to delete"));
}
if (count($parts) == 3) {
// Delete just a single entry
Kronolith::getDriver(null, $calendarId)->deleteEvent($parts[2]);
} else {
// Delete the entire calendar
try {
Kronolith::getDriver()->delete($calendarId);
// Remove share and all groups/permissions.
$kronolith_shares = $GLOBALS['injector']->getInstance('Kronolith_Shares');
$share = $kronolith_shares->getShare($calendarId);
$kronolith_shares->removeShare($share);
} catch (Exception $e) {
throw new Kronolith_Exception(sprintf(_("Unable to delete calendar \"%s\": %s"), $calendarId, $e->getMessage()));
}
}
}
/**
* Returns all calendars a user has access to, according to several
* parameters/permission levels.
*
* @param boolean $owneronly Only return calendars that this user owns?
* Defaults to false.
* @param integer $permission The permission to filter calendars by.
*
* @return array The calendar list.
*/
public function listCalendars($owneronly = false, $permission = null)
{
if (is_null($permission)) {
$permission = Horde_Perms::SHOW;
}
return array_keys(Kronolith::listInternalCalendars($owneronly, $permission));
}
/**
* Returns a list of available sources.
*
* @param boolean $writeable If true, limits to writeable sources.
* @param boolean $sync_only Only include syncable sources.
*
* @return array An array of the available sources. Keys are source IDs,
* values are source titles.
* @since 4.2.0
*/
public function sources($writeable = false, $sync_only = false)
{
$out = array();
foreach (Kronolith::listInternalCalendars(false, $writeable ? Horde_Perms::EDIT : Horde_Perms::READ) as $id => $data) {
$out[$id] = $data->get('name');
}
if ($sync_only) {
$syncable = Kronolith::getSyncCalendars();
$out = array_intersect_key($out, array_flip($syncable));
}
return $out;
}
/**
* Retrieve the UID for the current user's default calendar.
*
* @return string UID.
* @since 4.2.0
*/
public function getDefaultShare()
{
return Kronolith::getDefaultCalendar(Horde_Perms::EDIT, true);
}
/**
* Returns the ids of all the events that happen within a time period.
* Only includes recurring events once per time period, and does not include
* events that represent exceptions, making this method useful for syncing
* purposes. For more control, use the listEvents method.
*
* @param string|array $calendars 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 event ids happening in this time period.
* @throws Kronolith_Exception
*/
public function listUids($calendars = null, $startstamp = 0, $endstamp = 0)
{
if (empty($calendars)) {
$calendars = Kronolith::getSyncCalendars();
} elseif (!is_array($calendars)) {
$calendars = array($calendars);
}
$driver = Kronolith::getDriver();
$results = array();
foreach ($calendars as $calendar) {
if (!Kronolith::hasPermission($calendar, Horde_Perms::READ)) {
Horde::log(sprintf(
_("Permission Denied or Calendar Not Found: %s - skipping."),
$calendar));
continue;
}
try {
$driver->open($calendar);
$events = $driver->listEvents(
$startstamp ? new Horde_Date($startstamp) : null,
$endstamp ? new Horde_Date($endstamp) : null,
array('cover_dates' => false,
'hide_exceptions' => true)
);
Kronolith::mergeEvents($results, $events);
} catch (Kronolith_Exception $e) {
Horde::log($e);
}
}
$uids = array();
foreach ($results as $dayevents) {
foreach ($dayevents as $event) {
$uids[] = $event->uid;
}
}
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.
* @param integer $end The optional ending timestamp
* @param boolean $isModSeq If true, $timestamp and $end are modification
* sequences and not timestamps. @since 4.1.1
*
* @return array An array of UIDs matching the action and time criteria.
*
* @throws Kronolith_Exception
* @throws Horde_History_Exception
* @throws InvalidArgumentException
*/
public function listBy($action, $timestamp, $calendar = null, $end = null, $isModSeq = false)
{
if (empty($calendar)) {
$cs = Kronolith::getSyncCalendars($action == 'delete');
$results = array();
foreach ($cs as $c) {
$results = array_merge(
$results, $this->listBy($action, $timestamp, $c, $end, $isModSeq));
}
return $results;
}
$filter = array(array('op' => '=', 'field' => 'action', 'value' => $action));
if (!empty($end) && !$isModSeq) {
$filter[] = array('op' => '<', 'field' => 'ts', 'value' => $end);
}
if (!$isModSeq) {
$histories = $GLOBALS['injector']
->getInstance('Horde_History')
->getByTimestamp('>', $timestamp, $filter, 'kronolith:' . $calendar);
} else {
$histories = $GLOBALS['injector']
->getInstance('Horde_History')
->getByModSeq($timestamp, $end, $filter, 'kronolith:' . $calendar);
}
// Strip leading kronolith:username:.
return preg_replace('/^([^:]*:){2}/', '', array_keys($histories));
}
/**
* Method for obtaining all server changes between two timestamps. Basically
* a wrapper around listBy(), but returns an array containing all adds,
* edits and deletions. If $ignoreExceptions is true, events representing
* recurring event exceptions will not be included in the results.
*
* @param integer $start The starting timestamp
* @param integer $end The ending timestamp.
* @param boolean $ignoreExceptions Do not include exceptions in results.
* @param boolean $isModSeq If true, $timestamp and $end are
* modification sequences and not
* timestamps. @since 4.1.1
* @param string|array $calendars The sources to check. @since 4.2.0
*
* @return array An hash with 'add', 'modify' and 'delete' arrays.
* @throws Horde_Exception_PermissionDenied
* @throws Kronolith_Exception
*/
public function getChanges(
$start, $end, $ignoreExceptions = true, $isModSeq = false, $calendars = null)
{
// Only get the calendar once
if (is_null($calendars)) {
$cs = Kronolith::getSyncCalendars();
} else {
if (!is_array($calendars)) {
$calendars = array($calendars);
}
$cs = $calendars;
}
$changes = array(
'add' => array(),
'modify' => array(),
'delete' => array());
foreach ($cs as $c) {
// New events
$uids = $this->listBy('add', $start, $c, $end, $isModSeq);
if ($ignoreExceptions) {
foreach ($uids as $uid) {
try {
$event = Kronolith::getDriver()->getByUID($uid, array($c));
} catch (Exception $e) {
continue;
}
if (empty($event->baseid)) {
$changes['add'][] = $uid;
}
}
} else {
$changes['add'] = array_keys(array_flip(array_merge($changes['add'], $uids)));
}
// Edits
$uids = $this->listBy('modify', $start, $c, $end, $isModSeq);
if ($ignoreExceptions) {
foreach ($uids as $uid) {
try {
$event = Kronolith::getDriver()->getByUID($uid, array($c));
} catch (Exception $e) {
continue;
}
if (empty($event->baseid)) {
$changes['modify'][] = $uid;
}
}
} else {
$changes['modify'] = array_keys(array_flip(array_merge($changes['modify'], $uids)));
}
// No way to figure out if this was an exception, so we must include all
$changes['delete'] = array_keys(
array_flip(array_merge($changes['delete'], $this->listBy('delete', $start, $c, $end, $isModSeq))));
}
return $changes;
}
/**
* Return all changes occuring between the specified modification
* sequences.
*
* @param integer $start The starting modseq.
* @param integer $end The ending modseq.
* @param string|array $calendars The sources to check. @since 4.2.0
*
* @return array The changes @see getChanges()
* @since 4.1.1
*/
public function getChangesByModSeq($start, $end, $calendars = null)
{
return $this->getChanges($start, $end, true, true, $calendars);
}
/**
* 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.
* @param boolean $modSeq Request a modification sequence instead of a
* timestamp. @since 4.1.1
*
* @return integer The timestamp or modseq for this action.
*
* @throws Kronolith_Exception
* @throws InvalidArgumentException
*/
public function getActionTimestamp($uid, $action, $calendar = null, $modSeq = false)
{
if (empty($calendar)) {
$calendar = Kronolith::getDefaultCalendar();
} elseif (!Kronolith::hasPermission($calendar, Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied();
}
if (!$modSeq) {
return $GLOBALS['injector']->getInstance('Horde_History')->getActionTimestamp('kronolith:' . $calendar . ':' . $uid, $action);
}
return $GLOBALS['injector']->getInstance('Horde_History')->getActionModSeq('kronolith:' . $calendar . ':' . $uid, $action);
}
/**
* Return the largest modification sequence from the history backend.
*
* @param string $id The calendar id to return the hightest MDOSEQ for. If
* null, the highest MODSEQ across all calendars is
* returned. @since 4.2.0
*
* @return integer The MODSEQ value.
* @since 4.1.1
*/
public function getHighestModSeq($id = null)
{
$parent = 'kronolith';
if (!empty($id)) {
$parent .= ':' . $id;
}
return $GLOBALS['injector']->getInstance('Horde_History')->getHighestModSeq($parent);
}
/**
* 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-vcalendar
* activesync
* </pre>
* @param string $calendar What calendar should the event be added to?
*
* @return array The event's UID.
* @throws Kronolith_Exception
*/
public function import($content, $contentType, $calendar = null)
{
if (!isset($calendar)) {
$calendar = Kronolith::getDefaultCalendar(Horde_Perms::EDIT);
} elseif (!Kronolith::hasPermission($calendar, Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
$kronolith_driver = Kronolith::getDriver(null, $calendar);
switch ($contentType) {
case 'text/calendar':
case 'text/x-vcalendar':
$iCal = new Horde_Icalendar();
if (!($content instanceof Horde_Icalendar_Vevent)) {
if (!$iCal->parsevCalendar($content)) {
throw new Kronolith_Exception(_("There was an error importing the iCalendar data."));
}
} else {
$iCal->addComponent($content);
}
$components = $iCal->getComponents();
if (count($components) == 0) {
throw new Kronolith_Exception(_("No iCalendar data was found."));
}
$ids = array();
$recurrences = array();
foreach ($components as $content) {
if ($content instanceof Horde_Icalendar_Vevent) {
// Need to ensure that the original recurring event is
// added before any of the instance exceptions. Easiest way
// to do that is just add all the recurrence-id entries last
try {
$content->getAttribute('RECURRENCE-ID');
$recurrences[] = $content;
} catch (Horde_Icalendar_Exception $e) {
$ids[] = $this->_addiCalEvent($content, $kronolith_driver);
}
}
}
if (count($ids) == 0) {
throw new Kronolith_Exception(_("No iCalendar data was found."));
}
// Now add all the exception instances
foreach ($recurrences as $recurrence) {
$ids[] = $this->_addiCalEvent($recurrence, $kronolith_driver, true);
}
return $ids;
case 'activesync':
$event = $kronolith_driver->getEvent();
$event->fromASAppointment($content);
$event->save();
return $event->uid;
}
throw new Kronolith_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
}
/**
* Imports a single vEvent part to storage.
*
* @param Horde_Icalendar_Vevent $content The vEvent part
* @param Kronolith_Driver $driver The kronolith driver
* @param boolean $exception Content represents an exception
* in a recurrence series.
*
* @return string The new event's uid
*/
protected function _addiCalEvent($content, $driver, $exception = false)
{
$event = $driver->getEvent();
$event->fromiCalendar($content);
// Check if the entry already exists in the data source,
// first by UID.
if (!$exception) {
try {
$driver->getByUID($uid, array($driver->calendar));
throw new Kronolith_Exception(sprintf(_("%s Already Exists"), $event->uid));
} catch (Horde_Exception $e) {}
}
$result = $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(Horde_Perms::EDIT)) {
throw new Kronolith_Exception(sprintf(_("%s Already Exists"), $match->uid));
}
}
}
$event->save();
return $event->uid;
}
/**
* Imports an event parsed from a string.
*
* @param string $text The text to parse into an event
* @param string $calendar The calendar into which the event will be
* imported. If 'null', the user's default
* calendar will be used.
*
* @return array The UID of all events that were added.
* @throws Kronolith_Exception
*/
public function quickAdd($text, $calendar = null)
{
if (!isset($calendar)) {
$calendar = Kronolith::getDefaultCalendar(Horde_Perms::EDIT);
} elseif (!Kronolith::hasPermission($calendar, Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
$event = Kronolith::quickAdd($text, $calendar);
return $event->uid;
}
/**
* 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-vcalendar (old VCALENDAR 1.0 format.
* Still in wide use)
* activesync (Horde_ActiveSync_Message_Appointment)
* </pre>
* @param array $options Any additional options to be passed to the
* exporter.
* @param array $calendars Require event to be in these calendars.
* @since 4.2.0
*
* @return string The requested data.
* @throws Kronolith_Exception
* @throws Horde_Exception_NotFound
*/
public function export($uid, $contentType, array $options = array(), array $calendars = null)
{
$event = Kronolith::getDriver()->getByUID($uid, $calendars);
if (!$event->hasPermission(Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied();
}
$version = '2.0';
switch ($contentType) {
case 'text/x-vcalendar':
$version = '1.0';
case 'text/calendar':
$share = $GLOBALS['injector']->getInstance('Kronolith_Shares')->getShare($event->calendar);
$iCal = new Horde_Icalendar($version);
$iCal->setAttribute('X-WR-CALNAME', $share->get('name'));
// Create a new vEvent.
$iCal->addComponent($event->toiCalendar($iCal));
return $iCal->exportvCalendar();
case 'activesync':
return $event->toASAppointment($options);
}
throw new Kronolith_Exception(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-vcalendar (old VCALENDAR 1.0 format.
* Still in wide use)
* </pre>
*
* @return string The iCalendar representation of the calendar.
* @throws Kronolith_Exception
*/
public function exportCalendar($calendar, $contentType)
{
if (!Kronolith::hasPermission($calendar, Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied();
}
$kronolith_driver = Kronolith::getDriver(null, $calendar);
$events = $kronolith_driver->listEvents(null, null, array(
'cover_dates' => false,
'hide_exceptions' => true)
);
$version = '2.0';
switch ($contentType) {
case 'text/x-vcalendar':
$version = '1.0';
case 'text/calendar':
$share = $GLOBALS['injector']
->getInstance('Kronolith_Shares')
->getShare($calendar);
$iCal = new Horde_Icalendar($version);
$iCal->setAttribute('X-WR-CALNAME', $share->get('name'));
if (strlen($share->get('desc'))) {
$iCal->setAttribute('X-WR-CALDESC', $share->get('desc'));
}
foreach ($events as $dayevents) {
foreach ($dayevents as $event) {
$iCal->addComponent($event->toiCalendar($iCal));
}
}
return $iCal->exportvCalendar();
}
throw new Kronolith_Exception(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.
*
* @param string $recurrenceId The reccurenceId for the event instance, if
* this is a deletion of a recurring event
* instance ($uid must not be an array).
* @param string $range The range value if deleting a recurring
* event instance. Only supported values are
* null or Kronolith::RANGE_THISANDFUTURE.
* @since 4.1.5
*
* @throws Kronolith_Exception
*/
public function delete($uid, $recurrenceId = null, $range = null)
{
// Handle an array of UIDs for convenience of deleting multiple events
// at once.
if (is_array($uid)) {
foreach ($uid as $g) {
$this->delete($g);
}
return;
}
$kronolith_driver = Kronolith::getDriver();
$events = $kronolith_driver->getByUID($uid, null, true);
$event = null;
if ($GLOBALS['registry']->isAdmin()) {
$event = $events[0];
}
// First try the user's own calendars.
if (empty($event)) {
$ownerCalendars = Kronolith::listInternalCalendars(true, Horde_Perms::DELETE);
foreach ($events as $ev) {
if (isset($ownerCalendars[$ev->calendar])) {
$kronolith_driver->open($ev->calendar);
$event = $ev;
break;
}
}
}
// If not successful, try all calendars the user has access to.
if (empty($event)) {
$deletableCalendars = Kronolith::listInternalCalendars(false, Horde_Perms::DELETE);
foreach ($events as $ev) {
if (isset($deletableCalendars[$ev->calendar])) {
$kronolith_driver->open($ev->calendar);
$event = $ev;
break;
}
}
}
if (empty($event)) {
throw new Horde_Exception_PermissionDenied();
}
if ($recurrenceId && $event->recurs() && empty($range)) {
$deleteDate = new Horde_Date($recurrenceId);
$event->recurrence->addException($deleteDate->format('Y'), $deleteDate->format('m'), $deleteDate->format('d'));
$event->save();
} elseif ($range == Kronolith::RANGE_THISANDFUTURE) {
// Deleting the instance and remaining series.