/
Api.php
1545 lines (1416 loc) · 57.6 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
/**
* Nag external API interface.
*
* This file defines Nag's external API interface. Other applications can
* interact with Nag through this API.
*
* @package Nag
*/
class Nag_Api extends Horde_Registry_Api
{
/**
* Links.
*
* @var array
*/
protected $_links = array(
'show' => '%application%/view.php?tasklist=|tasklist|&task=|task|&uid=|uid|'
);
/**
* Returns a number of defaults necessary for the ajax view.
*
* @return array A hash with default values.
*/
public function ajaxDefaults()
{
return array(
'URI_TASKLIST_EXPORT' => str_replace(
array('%23', '%2523', '%7B', '%257B', '%7D', '%257D'),
array('#', '#', '{', '{', '}', '}'),
strval($GLOBALS['registry']->downloadUrl('#{tasklist}.ics', array('actionID' => 'export', 'exportTasks' => 1, 'exportID' => Horde_Data::EXPORT_ICALENDAR, 'exportList' => '#{tasklist}'))->setRaw(true))),
'default_tasklist' => Nag::getDefaultTasklist(Horde_Perms::EDIT),
'default_due' => (bool)$GLOBALS['prefs']->getValue('default_due'),
'default_due_days' => (int)$GLOBALS['prefs']->getValue('default_due_days'),
'default_due_time' => $GLOBALS['prefs']->getValue('default_due_time'),
'prefs_url' => strval($GLOBALS['registry']->getServiceLink('prefs', 'nag')->setRaw(true)),
);
}
/**
* Retrieves the current user's task list from storage.
*
* This function will also sort the resulting list, if requested.
* @param arary $options Options array:
* - altsortby: (string) The secondary sort field. Same values as sortdir.
* DEFAULT: altsortby pref is used.
* - completed: (integer) Which task to retrieve.
* DEFAULT: show_completed pref is used.
* - sortby: (string) A Nag::SORT_* constant for the field to sort by.
* DEFAULT: sortby pref is used.
* - sortdir: (string) Direction of sort. NAG::SORT_ASCEND or NAG::SORT_DESCEND.
* DEFAULT: sortdir pref is used.
* - include_tags: (boolean) Autoload all tags.
* DEFAULT: false (Tags are lazy loaded as needed.)
* - json: (boolean) Return data as JSON.
* DEFAULT: false (Data is returned as Nag_Task)
* - tasklists: (array) An array of tasklists to include.
* DEFAULT: Use $GLOBALS['display_tasklists'];
*
* @return array An array of the requested tasks.
*/
public function listTasks(array $options = array())
{
global $prefs;
$completedArray = array(
'incomplete' => Nag::VIEW_INCOMPLETE,
'all' => Nag::VIEW_ALL,
'complete' => Nag::VIEW_COMPLETE,
'future' => Nag::VIEW_FUTURE,
'future_incomplete' => Nag::VIEW_FUTURE_INCOMPLETE);
// Prevent null tasklists value from obscuring the default value.
if (array_key_exists('tasklists', $options) && empty($options['tasklists'])) {
unset($options['tasklists']);
}
if (is_null($options['completed']) || !isset($completedArray[$options['completed']])) {
$options['completed'] = $prefs->getValue('show_completed');
} else {
$options['completed'] = $completedArray[$options['completed']];
}
$options = array_merge(
array(
'sortby' => $prefs->getValue('sortby'),
'sortdir' => $prefs->getValue('sortdir'),
'altsortby' => $prefs->getValue('altsortby'),
'tasklists' => $GLOBALS['display_tasklists'],
'include_tags' => false,
'external' => false,
'json' => false
),
$options
);
$tasks = Nag::listTasks($options);
$tasks->reset();
$list = array();
while ($task = $tasks->each()) {
$list[$task->id] = $options['json'] ? $task->toJson() : $task->toHash();
}
return $list;
}
/**
* Returns a list of task lists.
*
* @param boolean $owneronly Only return tasklists that this user owns?
* Defaults to false.
* @param integer $permission The permission to filter tasklists by.
* @param boolean $smart Include smart tasklists in results.
*
* @return array The task lists.
*/
public function listTasklists($owneronly = false, $permission = Horde_Perms::SHOW, $smart = true)
{
return Nag::listTasklists($owneronly, $permission, $smart);
}
/**
* Returns a task list.
*
* @param string $name A task list name.
*
* @return Horde_Share_Object The task list.
*/
public function getTasklist($name)
{
try {
$tasklist = $GLOBALS['nag_shares']->getShare($name);
} catch (Horde_Share_Exception $e) {
Horde::log($e->getMessage(), 'ERR');
throw new Nag_Exception($e);
}
if (!$tasklist->hasPermission($GLOBALS['registry']->getAuth(), Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied(_("You are not allowed to retrieve this task list."));
}
return $tasklist;
}
/**
* Adds a new task list.
*
* @param string $name Task list name.
* @param string $description Task list description.
* @param string $color Task list color.
* @param array $params Any addtional parameters needed. @since 4.2.1
* - synchronize: (boolean) If true, add task list to the list of
* task lists to syncronize.
* DEFAULT: false (do not add to the list).
*
* @return string The new tasklist's id.
*/
public function addTasklist($name, $description = '', $color = '', array $params = array())
{
$tasklist = Nag::addTasklist(array('name' => $name, 'description' => $description, 'color' => $color));
$name = $tasklist->getName();
if (!empty($params['synchronize'])) {
$sync = @unserialize($prefs->getValue('sync_lists'));
$sync[] = $name;
$prefs->setValue('sync_lists', serialize($sync));
}
return $name;
}
/**
* Updates an existing task list.
*
* @param string $name A task list name.
* @param array $info Hash with task list information.
*/
public static function updateTasklist($name, $info)
{
try {
$tasklist = $GLOBALS['nag_shares']->getShare($name);
} catch (Horde_Share_Exception $e) {
Horde::log($e->getMessage(), 'ERR');
throw new Nag_Exception($e);
}
return Nag::updateTasklist($tasklist, $info);
}
/**
* Deletes a task list.
*
* @param string $id A task list id.
*/
public function deleteTasklist($id)
{
$tasklist = $GLOBALS['nag_shares']->getShare($id);
return Nag::deleteTasklist($tasklist);
}
/**
* Returns the displayed task lists.
*
* @return array Displayed tasklists.
*/
public function getDisplayedTasklists()
{
return $GLOBALS['display_tasklists'];
}
/**
* Sets the displayed task lists.
*
* @param array $list Displayed tasklists.
*/
public function setDisplayedTasklists($list)
{
$GLOBALS['display_tasklists'] = $list;
$GLOBALS['prefs']->setValue('display_tasklists', serialize($list));
}
/**
* Returns the last modification timestamp of a given uid.
*
* @param string $uid The uid to look for.
* @param string $tasklist The tasklist to look in.
*
* @return integer The timestamp for the last modification of $uid.
*/
public function modified($uid, $tasklist = null)
{
$modified = $this->getActionTimestamp($uid, 'modify', $tasklist);
if (empty($modified)) {
$modified = $this->getActionTimestamp($uid, 'add', $tasklist);
}
return $modified;
}
/**
* Browse through Nag'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
*/
public function browse($path = '', $properties = array())
{
global $registry;
// Default properties.
if (!$properties) {
$properties = array('name', 'icon', 'browseable');
}
if (substr($path, 0, 3) == 'nag') {
$path = substr($path, 3);
}
$path = trim($path, '/');
$parts = explode('/', $path);
if (empty($path)) {
// This request is for a list of all users who have tasklists
// visible to the requesting user.
$tasklists = Nag::listTasklists(false, Horde_Perms::READ);
$owners = array();
foreach ($tasklists as $tasklist) {
$owners[$tasklist->get('owner') ? $tasklist->get('owner') : '-system-'] = true;
}
$results = array();
foreach (array_keys($owners) as $owner) {
if (in_array('name', $properties)) {
$results['nag/' . $owner]['name'] = $owner;
}
if (in_array('icon', $properties)) {
$results['nag/' . $owner]['icon'] = Horde_Themes::img('user.png');
}
if (in_array('browseable', $properties)) {
$results['nag/' . $owner]['browseable'] = true;
}
if (in_array('contenttype', $properties)) {
$results['nag/' . $owner]['contenttype'] =
'httpd/unix-directory';
}
if (in_array('contentlength', $properties)) {
$results['nag/' . $owner]['contentlength'] = 0;
}
if (in_array('modified', $properties)) {
$results['nag/' . $owner]['modified'] =
$_SERVER['REQUEST_TIME'];
}
if (in_array('created', $properties)) {
$results['nag/' . $owner]['created'] = 0;
}
}
return $results;
} elseif (count($parts) == 1) {
// This request is for all tasklists owned by the requested user
$owner = $parts[0] == '-system-' ? '' : $parts[0];
$tasklists = $GLOBALS['nag_shares']->listShares(
$GLOBALS['registry']->getAuth(),
array('perm' => Horde_Perms::SHOW,
'attributes' => $owner));
$results = array();
foreach ($tasklists as $tasklistId => $tasklist) {
if ($parts[0] == '-system-' && $tasklist->get('owner')) {
continue;
}
$retpath = 'nag/' . $parts[0] . '/' . $tasklistId;
if (in_array('name', $properties)) {
$results[$retpath]['name'] = sprintf(_("Tasks from %s"), Nag::getLabel($tasklist));
$results[$retpath . '.ics']['name'] = Nag::getLabel($tasklist);
}
if (in_array('icon', $properties)) {
$results[$retpath]['icon'] = Horde_Themes::img('nag.png');
$results[$retpath . '.ics']['icon'] = Horde_Themes::img('mime/icalendar.png');
}
if (in_array('browseable', $properties)) {
$results[$retpath]['browseable'] = $tasklist->hasPermission($GLOBALS['registry']->getAuth(), Horde_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;
$results[$retpath . '.ics']['contentlength'] = strlen($this->exportTasklist($tasklistId, 'text/calendar'));
}
if (in_array('modified', $properties)) {
// @TODO Find a way to get the actual modification times
$results[$retpath]['modified'] = $_SERVER['REQUEST_TIME'];
$results[$retpath . '.ics']['modified'] = $_SERVER['REQUEST_TIME'];
}
if (in_array('created', $properties)) {
// @TODO Find a way to get the actual creation times
$results[$retpath]['created'] = 0;
$results[$retpath . '.ics']['created'] = 0;
}
}
return $results;
} elseif (count($parts) == 2 && substr($parts[1], -4) == '.ics') {
//
// This is a request for the entire tasklist in iCalendar format.
//
$tasklist = substr($parts[1], 0, -4);
if (!Nag::hasPermission($tasklist, Horde_Perms::READ)) {
throw new Nag_Exception(_("Invalid task list file requested."), 404);
}
$ical_data = $this->exportTasklist($tasklist, 'text/calendar');
return array(
'data' => $ical_data,
'mimetype' => 'text/calendar',
'contentlength' => strlen($ical_data),
'mtime' => $_SERVER['REQUEST_TIME']
);
} elseif (count($parts) == 2) {
//
// This request is browsing into a specific tasklist. Generate the list
// of items and represent them as files within the directory.
//
if (!Nag::hasPermission($parts[1], Horde_Perms::READ)) {
throw new Nag_Exception(_("Invalid task list requested."), 404);
}
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($parts[1]);
try {
$storage->retrieve();
} catch (Nag_Exception $e) {
throw new Nag_Exception($e->getMessage, 500);
}
$icon = Horde_Themes::img('nag.png');
$results = array();
$storage->tasks->reset();
while ($task = $storage->tasks->each()) {
$key = 'nag/' . $parts[0] . '/' . $parts[1] . '/' . $task->id;
if (in_array('modified', $properties) ||
in_array('etag', $properties)) {
$modified = $this->modified($task->uid, $parts[1]);
}
if (in_array('name', $properties)) {
$results[$key]['name'] = $task->name;
}
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'] = $modified;
}
if (in_array('created', $properties)) {
$results[$key]['created'] = $this->getActionTimestamp($task->uid, 'add', $parts[1]);
}
if (in_array('etag', $properties)) {
$results[$key]['etag'] = '"' . md5($task->id . '|' . $modified) . '"';
}
}
return $results;
} else {
//
// The only valid request left is for either a specific task item.
//
if (count($parts) == 3 &&
Nag::hasPermission($parts[1], Horde_Perms::READ)) {
//
// This request is for a specific item within a given task list.
//
/* Create a Nag storage instance. */
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($parts[1]);
$storage->retrieve();
try {
$task = $storage->get($parts[2]);
} catch (Nag_Exception $e) {
throw new Nag_Exception($e->getMessage(), 500);
}
$result = array(
'data' => $this->export($task->uid, 'text/calendar'),
'mimetype' => 'text/calendar');
$modified = $this->modified($task->uid, $parts[1]);
if (!empty($modified)) {
$result['mtime'] = $modified;
}
return $result;
} elseif (count($parts) == 2 &&
substr($parts[1], -4) == '.ics' &&
Nag::hasPermission(substr($parts[1], 0, -4), Horde_Perms::READ)) {
// ??
} else {
//
// All other requests are a 404: Not Found
//
return false;
}
}
}
/**
* Saves a file into the Nag 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
*/
public function put($path, $content, $content_type)
{
if (substr($path, 0, 3) == 'nag') {
$path = substr($path, 3);
}
$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';
}
$tasklist = substr($parts[1], 0, -4);
} elseif (count($parts) == 3) {
$tasklist = $parts[1];
// Workaround for WebDAV clients that are not smart enough to send
// the right content type. Assume the same format we send
// individual tasklist items: text/calendar
if ($content_type == 'application/octet-stream') {
$content_type = 'text/calendar';
}
} else {
throw new Nag_Exception(_("Invalid task list name supplied."), 403);
}
if (!Nag::hasPermission($tasklist, Horde_Perms::EDIT)) {
// FIXME: Should we attempt to create a tasklist based on the
// filename in the case that the requested tasklist does not exist?
throw new Nag_Exception(_("Task list does not exist or no permission to edit"), 403);
}
// 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($tasklist));
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($tasklist);
switch ($content_type) {
case 'text/calendar':
case 'text/x-vcalendar':
$iCal = new Horde_Icalendar();
if (!($content instanceof Horde_Icalendar_Vtodo)) {
if (!$iCal->parsevCalendar($content)) {
throw new Nag_Exception(_("There was an error importing the iCalendar data."), 400);
}
} else {
$iCal->addComponent($content);
}
foreach ($iCal->getComponents() as $content) {
if (!($content instanceof Horde_Icalendar_Vtodo)) {
continue;
}
$task = new Nag_Task();
$task->fromiCalendar($content);
$task->tasklist = $tasklist;
$create = true;
if (isset($task->uid)) {
try {
$existing = $storage->getByUID($task->uid);
$create = false;
} catch (Horde_Exception_NotFound $e) {
}
}
if (!$create) {
// Entry exists, remove from uids_remove list so we
// won't delete in the end.
if (isset($uids_remove[$task->uid])) {
unset($uids_remove[$task->uid]);
}
if ($existing->private &&
$existing->owner != $GLOBALS['registry']->getAuth()) {
continue;
}
// Check if our task is newer then the existing - get
// the task's history.
$history = $GLOBALS['injector']->getInstance('Horde_History');
$created = $modified = null;
try {
$log = $history->getHistory('nag:' . $tasklist . ':' . $task->uid);
foreach ($log as $entry) {
switch ($entry['action']) {
case 'add':
$created = $entry['ts'];
break;
case 'modify':
$modified = $entry['ts'];
break;
}
}
} catch (Exception $e) {}
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.
$task->owner = $existing->owner;
try {
$storage->modify($existing->id, $task->toHash());
} catch (Nag_Exception $e) {
throw new Nag_Exception($e->getMessage(), 500);
}
$ids[] = $task->uid;
} else {
try {
$newTask = $storage->add($task->toHash());
} catch (Nag_Exception $e) {
throw new Nag_Exception($e->getMessage(), 500);
}
// use UID rather than ID
$ids[] = $newTask[1];
}
}
break;
default:
throw new Nag_Exception(sprintf(_("Unsupported Content-Type: %s"), $content_type), 400);
}
if (Nag::hasPermission($tasklist, Horde_Perms::DELETE)) {
foreach (array_keys($uids_remove) as $uid) {
$this->delete($uid);
}
}
return $ids;
}
/**
* Deletes a file from the Nag tree.
*
* @param string $path The path to the file.
*
* @return string The event's UID
* @throws Nag_Exception
*/
public function path_delete($path)
{
if (substr($path, 0, 3) == 'nag') {
$path = substr($path, 3);
}
$path = trim($path, '/');
$parts = explode('/', $path);
if (count($parts) == 2) {
// @TODO Deny deleting of the entire tasklist for now.
// Allow users to delete tasklists but not create them via WebDAV
// will be more confusing than helpful. They are, however, still
// able to delete individual task items within the tasklist folder.
throw Nag_Exception(_("Deleting entire task lists is not supported."), 403);
// To re-enable the functionality just remove this if {} block.
}
if (substr($parts[1], -4) == '.ics') {
$tasklistID = substr($parts[1], 0, -4);
} else {
$tasklistID = $parts[1];
}
if (!(count($parts) == 2 || count($parts) == 3) ||
!Nag::hasPermission($tasklistID, Horde_Perms::DELETE)) {
throw new Nag_Exception(_("Task list does not exist or no permission to delete"), 403);
}
/* Create a Nag storage instance. */
try {
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($tasklistID);
$storage->retrieve();
} catch (Nag_Exception $e) {
throw new Nag_Exception(sprintf(_("Connection failed: %s"), $e->getMessage()), 500);
}
if (count($parts) == 3) {
// Delete just a single entry
return $storage->delete($parts[2]);
} else {
// Delete the entire task list
try {
$storage->deleteAll();
} catch (Nag_Exception $e) {
throw new Nag_Exception(sprintf(_("Unable to delete task list \"%s\": %s"), $tasklistID, $e->getMessage()), 500);
}
// Remove share and all groups/permissions.
$share = $GLOBALS['nag_shares']->getShare($tasklistID);
try {
$GLOBALS['nag_shares']->removeShare($share);
} catch (Horde_Share_Exception $e) {
throw new Nag_Exception($e->getMessage());
}
}
}
/**
* Returns an array of UIDs for all tasks that the current user is authorized
* to see.
*
* @param mixed $tasklists The tasklist or an array of taskslists to list.
*
* @return array An array of UIDs for all tasks
* the user can access.
*
* @throws Horde_Exception_PermissionDenied
* @throws Nag_Exception
*/
public function listUids($tasklists = null)
{
if (!isset($GLOBALS['conf']['storage']['driver'])) {
throw new Nag_Exception(_("Not configured"));
}
if (empty($tasklists)) {
$tasklists = Nag::getSyncLists();
} else {
if (!is_array($tasklists)) {
$tasklists = array($tasklists);
}
foreach ($tasklists as $list) {
if (!Nag::hasPermission($list, Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied();
}
}
}
$tasks = Nag::listTasks(array(
'tasklists' => $tasklists,
'completed' => Nag::VIEW_ALL,
'include_history' => false)
);
$uids = array();
$tasks->reset();
while ($task = $tasks->each()) {
$uids[] = $task->uid;
}
return $uids;
}
/**
* Returns an array of UIDs for tasks 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 mixed $tasklists The tasklists to be used. If 'null', the
* user's default tasklist will be used.
* @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 Horde_History_Exception
* @throws InvalidArgumentException
*/
public function listBy($action, $timestamp, $tasklist = null, $end = null, $isModSeq = false)
{
if (empty($tasklist)) {
$tasklist = Nag::getSyncLists();
$results = array();
foreach ($tasklist as $list) {
$results = array_merge($results, $this->listBy($action, $timestamp, $list, $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, 'nag:' . $tasklist);
} else {
$histories = $GLOBALS['injector']
->getInstance('Horde_History')
->getByModSeq($timestamp, $end, $filter, 'nag:' . $tasklist);
}
// Strip leading nag: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.
*
* @param integer $start The starting timestamp
* @param integer $end The ending timestamp.
* @param boolean $isModSeq If true, $timestamp and $end are
* modification sequences and not
* timestamps. @since 4.1.1
* @param string|array $tasklists The sources to check. @since 4.2.0
*
* @return array An hash with 'add', 'modify' and 'delete' arrays.
*/
public function getChanges($start, $end, $isModSeq = false, $tasklists = null)
{
return array(
'add' => $this->listBy('add', $start, $tasklists, $end, $isModSeq),
'modify' => $this->listBy('modify', $start, $tasklists, $end, $isModSeq),
'delete' => $this->listBy('delete', $start, $tasklists, $end, $isModSeq));
}
/**
* Return all changes occuring between the specified modification
* sequences.
*
* @param integer $start The starting modseq.
* @param integer $end The ending modseq.
* @param string|array $tasklists The sources to check. @since 4.2.0
*
* @return array The changes @see getChanges()
* @since 4.1.1
*/
public function getChangesByModSeq($start, $end, $tasklists = null)
{
return $this->getChanges($start, $end, true, $tasklists);
}
/**
* 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 $tasklist The tasklist to be used. If 'null', the
* user's default tasklist will be used.
* @param boolean $modSeq Request a modification sequence instead of a
* timestamp. @since 4.1.1
*
* @return integer The timestamp for this action.
*
* @throws InvalidArgumentException
* @throws Horde_Exception_PermissionDenied
* @thorws Horde_History_Exception
*/
public function getActionTimestamp($uid, $action, $tasklist = null, $modSeq = false)
{
if ($tasklist === null) {
$tasklist = Nag::getDefaultTasklist(Horde_Perms::READ);
} elseif (!Nag::hasPermission($tasklist, Horde_Perms::READ)) {
throw new Horde_Exception_PermissionDenied();
}
if (!$modSeq) {
return $GLOBALS['injector']
->getInstance('Horde_History')
->getActionTimestamp('nag:' . $tasklist . ':' . $uid, $action);
} else {
return $GLOBALS['injector']
->getInstance('Horde_History')
->getActionModSeq('nag:' . $tasklist . ':' . $uid, $action);
}
}
/**
* Return the largest modification sequence from the history backend.
*
* @param string $id Limit the check to this tasklist. @since 4.2.0
*
* @return integer The modseq.
* @since 4.1.1
*/
public function getHighestModSeq($id = null)
{
$parent = 'nag';
if (!empty($id)) {
$parent .= ':' . $id;
}
return $GLOBALS['injector']->getInstance('Horde_History')->getHighestModSeq($parent);
}
/**
* Imports one or more tasks represented in the specified content type.
*
* If a UID is present in the content and the task is already in the
* database, a replace is performed rather than an add.
*
* @param string $content The content of the task.
* @param string $contentType What format is the data in? Currently supports:
* text/calendar
* text/x-vcalendar
* @param string $tasklist The tasklist into which the task will be
* imported. If 'null', the user's default
* tasklist will be used.
*
* @return string The new UID on one import, an array of UIDs on multiple imports,
*/
public function import($content, $contentType, $tasklist = null)
{
if ($tasklist === null) {
$tasklist = Nag::getDefaultTasklist(Horde_Perms::EDIT);
} elseif (!Nag::hasPermission($tasklist, Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
/* Create a Nag_Driver instance. */
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($tasklist);
switch ($contentType) {
case 'text/x-vcalendar':
case 'text/calendar':
case 'text/x-vtodo':
$iCal = new Horde_Icalendar();
if (!($content instanceof Horde_Icalendar_Vtodo)) {
if (!$iCal->parsevCalendar($content)) {
throw new Nag_Exception(_("There was an error importing the iCalendar data."));
}
} else {
$iCal->addComponent($content);
}
$components = $iCal->getComponents();
if (count($components) == 0) {
throw new Nag_Exception(_("No iCalendar data was found."));
}
$ids = array();
foreach ($components as $content) {
if ($content instanceof Horde_Icalendar_Vtodo) {
$task = new Nag_Task($storage);
$task->fromiCalendar($content);
if (isset($task->uid)) {
try {
$existing = $storage->getByUID($task->uid);
$task->owner = $existing->owner;
$storage->modify($existing->id, $task->toHash());
} catch ( Horde_Exception_NotFound $e ) {
$storage->add($task->toHash());
}
$ids[] = $task->uid;
} else {
$hash = $task->toHash();
unset($hash['uid']);
$newTask = $storage->add($hash);
// use UID rather than ID
$ids[] = $newTask[1];
}
}
}
if (count($ids) == 0) {
throw new Nag_Exception(_("No iCalendar data was found."));
} else if (count($ids) == 1) {
return $ids[0];
}
return $ids;
case 'activesync':
$task = new Nag_Task();
$task->fromASTask($content);
$hash = $task->toHash();
unset($hash['uid']);
$results = $storage->add($hash);
/* array index 0 is id, 1 is uid */
return $results[1];
}
throw new Nag_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
}
/**
* Adds a task.
*
* @param array $task A hash with task information.
*
* @throws Horde_Exception_PermissionDenied
*/
public function addTask(array $task)
{
if (!$GLOBALS['registry']->isAdmin() &&
!Nag::hasPermission($task['tasklist'], Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
$storage = $GLOBALS['injector']->getInstance('Nag_Factory_Driver')->create($task['tasklist']);
return $storage->add($task);
}
/**
* Imports one or more tasks parsed from a string.
*
* @param string $text The text to parse into
* @param string $tasklist The tasklist into which the task will be
* imported. If 'null', the user's default
* tasklist will be used.
*
* @return array The UIDs of all tasks that were added.
* @throws Horde_Exception_PermissionDenied
*/
public function quickAdd($text, $tasklist = null)
{
if ($tasklist === null) {
$tasklist = Nag::getDefaultTasklist(Horde_Perms::EDIT);
} elseif (!Nag::hasPermission($tasklist, Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
return Nag::createTasksFromText($text, $tasklist);
}
/**
* Toggles the task completion flag.
*
* @param string $task_id The task ID.
* @param string $tasklist_id The tasklist that contains the task.
*
* @return boolean|string True if the task has been toggled, a due date if
* there are still incomplete recurrences.
*/
public function toggleCompletion($task_id, $tasklist_id)
{
if (!Nag::hasPermission($tasklist_id, Horde_Perms::EDIT)) {
throw new Horde_Exception_PermissionDenied();
}
try {
$share = $GLOBALS['nag_shares']->getShare($tasklist_id);
} catch (Horde_Share_Exception $e) {
Horde::log($e->getMessage(), 'ERR');
throw new Nag_Exception($e);
}
$task = Nag::getTask($tasklist_id, $task_id);