File: kolab.php

package info (click to toggle)
nag2 2.3.4%2Bdebian0-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 6,256 kB
  • ctags: 1,719
  • sloc: php: 6,797; xml: 589; sql: 335; makefile: 75; sh: 26
file content (1110 lines) | stat: -rw-r--r-- 36,523 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
<?php
/**
 * Nag driver classes for the Kolab IMAP server.
 *
 * $Horde: nag/lib/Driver/kolab.php,v 1.6.10.17 2009-10-22 14:24:20 jan Exp $
 *
 * Copyright 2004-2009 The Horde Project (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * @package Nag
 */

/** Kolab */
require_once 'Horde/Kolab.php';

/**
 * Nag driver proxy class for the Kolab IMAP server.
 *
 * @author  Gunnar Wrobel <wrobel@pardus.de>
 * @author  Thomas Jarosch <thomas.jarosch@intra2net.com>
 * @author  Stuart Binge <omicron@mighty.co.za>
 * @package Nag
 */
class Nag_Driver_kolab extends Nag_Driver {

    /**
     * Our Kolab server connection.
     *
     * @var Kolab
     */
    var $_kolab = null;

    /**
     * The wrapper to decide between the Kolab implementation
     *
     * @var Nag_Driver_kolab_wrapper
     */
    var $_wrapper = null;

    /**
     * Constructs a new Kolab storage object.
     *
     * @param string $tasklist  The tasklist to load.
     * @param array $params     A hash containing connection parameters.
     */
    function Nag_Driver_kolab($tasklist, $params = array())
    {
        if (empty($tasklist)) {
            $tasklist = Auth::getAuth();
        }

        $this->_tasklist = $tasklist;

        $this->_kolab = &new Kolab();
        if (empty($this->_kolab->version)) {
            $wrapper = 'Nag_Driver_kolab_wrapper_old';
        } else {
            $wrapper = 'Nag_Driver_kolab_wrapper_new';
        }

        $this->_wrapper = &new $wrapper($this->_tasklist, $this->_kolab);
    }

    /**
     * Attempts to open a Kolab Groupware folder.
     *
     * @return boolean  True on success, PEAR_Error on failure.
     */
    function initialize()
    {
        return $this->_wrapper->connect();
    }

    /**
     * Retrieves one task from the store.
     *
     * @param string $taskId  The id of the task to retrieve.
     *
     * @return array  The array of task attributes.
     */
    function get($taskId)
    {
        return $this->_wrapper->get($taskId);
    }

    /**
     * Retrieves one task from the database by UID.
     *
     * @param string $uid  The UID of the task to retrieve.
     *
     * @return array  The array of task attributes.
     */
    function getByUID($uid)
    {
        return $this->_wrapper->getByUID($uid);
    }

    /**
     * Adds a task to the backend storage.
     *
     * @param string $name        The name (short) of the task.
     * @param string $desc        The description (long) of the task.
     * @param integer $start      The start date of the task.
     * @param integer $due        The due date of the task.
     * @param integer $priority   The priority of the task.
     * @param float $estimate     The estimated time to complete the task.
     * @param integer $completed  The completion state of the task.
     * @param string $category    The category of the task.
     * @param integer $alarm      The alarm associated with the task.
     * @param string $uid         A Unique Identifier for the task.
     * @param string $parent      The parent task id.
     * @param boolean $private    Whether the task is private.
     * @param string $owner       The owner of the event.
     * @param string $assignee    The assignee of the event.
     *
     * @return string  The Nag ID of the new task.
     */
    function _add($name, $desc, $start = 0, $due = 0, $priority = 0,
                  $completed = 0, $estimate = 0.0, $category = '', $alarm = 0,
                  $uid = null, $parent = null, $private = false, $owner = null,
                  $assignee = null)
    {
        return $this->_wrapper->add($name, $desc, $start, $due, $priority,
                                    $completed, $estimate, $category, $alarm,
                                    $uid, $parent, $private, $owner, $assignee);
    }

    /**
     * Modifies an existing task.
     *
     * @param string $taskId           The task to modify.
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     * @param integer $completed_date  The task's completion date.
     *
     * @return boolean  Indicates if the modification was successfull.
     */
    function _modify($taskId, $name, $desc, $start = 0, $due = 0, $priority = 0,
                     $estimate = 0.0, $completed = 0, $category = '',
                     $alarm = 0, $parent = null, $private = false,
                     $owner = null, $assignee = null, $completed_date = null)
    {
        return $this->_wrapper->modify($taskId, $name, $desc, $start, $due,
                                       $priority, $estimate, $completed,
                                       $category, $alarm, $parent, $private,
                                       $owner, $assignee, $completed_date);
    }

    /**
     * Moves a task to a different tasklist.
     *
     * @param string $taskId       The task to move.
     * @param string $newTasklist  The new tasklist.
     */
    function _move($taskId, $newTasklist)
    {
        return $this->_wrapper->move($taskId, $newTasklist);
    }

    /**
     * Deletes a task from the backend.
     *
     * @param string $taskId  The task to delete.
     */
    function _delete($taskId)
    {
        return $this->_wrapper->delete($taskId);
    }

    /**
     * Deletes all tasks from the backend.
     */
    function deleteAll()
    {
        return $this->_wrapper->deleteAll();
    }

    /**
     * Retrieves tasks from the Kolab server.
     *
     * @param integer $completed  Which tasks to retrieve (1 = all tasks,
     *                            0 = incomplete tasks, 2 = complete tasks).
     *
     * @return mixed  True on success, PEAR_Error on failure.
     */
    function retrieve($completed = 1)
    {
        $tasks = $this->_wrapper->retrieve($completed);
        if (is_a($tasks, 'PEAR_Error')) {
            return $tasks;
        }

        $this->tasks = $tasks;

        return true;
    }

    /**
     * Lists all alarms near $date.
     *
     * @param integer $date  The unix epoch time to check for alarms.
     *
     * @return array  An array of tasks that have alarms that match.
     */
    function listAlarms($date)
    {
        return $this->_wrapper->listAlarms($date);
    }

    /**
     * Retrieves sub-tasks from the database.
     *
     * @param string $parentId  The parent id for the sub-tasks to retrieve.
     *
     * @return array  List of sub-tasks.
     */
    function getChildren($parentId)
    {
        return $this->_wrapper->getChildren($parentId);
    }
}

/**
 * Horde Nag wrapper to distinguish between both Kolab driver implementations.
 *
 * @author  Gunnar Wrobel <wrobel@pardus.de>
 * @package Nag
 */

class Nag_Driver_kolab_wrapper {

    /**
     * Indicates if the wrapper has connected or not
     *
     * @var boolean
     */
    var $_connected = false;

    /**
     * String containing the current tasklist name.
     *
     * @var string
     */
    var $_tasklist = '';

    /**
     * Our Kolab server connection.
     *
     * @var Kolab
     */
    var $_kolab = null;

    /**
     * Constructor
     *
     * @param string      $tasklist  The tasklist to load.
     * @param Horde_Kolab $kolab     The Kolab connection object
     */
    function Nag_Driver_kolab_wrapper($tasklist, &$kolab)
    {
        $this->_tasklist = $tasklist;
        $this->_kolab = &$kolab;
    }

    /**
     * Connect to the Kolab backend
     *
     * @param int    $loader         The version of the XML
     *                               loader
     *
     * @return mixed True on success, a PEAR error otherwise
     */
    function connect($loader = 0)
    {
        if ($this->_connected) {
            return true;
        }

        $result = $this->_kolab->open($this->_tasklist, $loader);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $this->_connected = true;

        return true;
    }
}

/**
 * Old Nag driver for the Kolab IMAP server.
 *
 * @author  Gunnar Wrobel <wrobel@pardus.de>
 * @author  Stuart Binge <omicron@mighty.co.za>
 * @package Nag
 */
class Nag_Driver_kolab_wrapper_old extends Nag_Driver_kolab_wrapper {

    function _buildTask()
    {
        $private = String::lower($this->_kolab->getVal('sensitivity'));
        $private = ($private == 'private' || $private == 'confidential');

        return array(
            'tasklist_id' => $this->_tasklist,
            'task_id' => $this->_kolab->getUID(),
            'uid' => $this->_kolab->getUID(),
            'owner' => Auth::getAuth(),
            'name' => $this->_kolab->getStr('summary'),
            'desc' => $this->_kolab->getStr('body'),
            'category' => $this->_kolab->getStr('categories'),
            'due' => Kolab::decodeDateOrDateTime($this->_kolab->getVal('due-date')),
            'priority' => $this->_kolab->getVal('priority'),
            'parent' => $this->_kolab->getVal('parent'),
            'estimate' => (float)$this->_kolab->getVal('priority'),
            'completed' => Kolab::percentageToBoolean($this->_kolab->getVal('completed')),
            'alarm' => $this->_kolab->getVal('alarm'),
            'private' => $private,
        );
    }

    /**
     * Retrieves one task from the store.
     *
     * @param string $taskId  The id of the task to retrieve.
     *
     * @return array  The array of task attributes.
     */
    function get($taskId)
    {
        $result = $this->_kolab->loadObject($taskId);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return new Nag_Task($this->_buildTask());
    }

    /**
     * Retrieves one task from the database by UID.
     *
     * @param string $uid  The UID of the task to retrieve.
     *
     * @return array  The array of task attributes.
     */
    function getByUID($uid)
    {
        return PEAR::raiseError("Not supported");
    }

    /**
     * @todo Utilize $owner, $assignee, and $completed_date
     * parameters.
     *
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     * @param integer $completed_date  The task's completion date.
     *
     * @return string  The ID of the task.
     */
    function _setObject($name, $desc, $start = 0, $due = 0, $priority = 0,
                        $estimate = 0.0, $completed = 0, $category = '',
                        $alarm = 0, $parent = null, $private = false,
                        $owner = null, $assignee = null, $completed_date = null)
    {
        if ($due == 0) {
            $alarm = 0;
        }

        $this->_kolab->setStr('summary', $name);
        $this->_kolab->setStr('body', $desc);
        $this->_kolab->setStr('categories', $category);
        $this->_kolab->setVal('priority', $priority);
        $this->_kolab->setVal('estimate', number_format($priority, 2));
        $this->_kolab->setVal('completed', Kolab::booleanToPercentage($completed));
        $this->_kolab->setVal('start-date', Kolab::encodeDateTime($start));
        $this->_kolab->setVal('due-date', Kolab::encodeDateTime($due));
        $this->_kolab->setVal('alarm', $alarm);
        if ($parent) {
            $this->_kolab->setVal('parent', $parent);
        }
        if ($private) {
            $this->_kolab->setVal('sensitivity', 'private');
        }

        $result = $this->_kolab->saveObject();
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return $this->_kolab->getUID();
    }

    /**
     * Adds a task to the backend storage.
     *
     * @param string $name        The name (short) of the task.
     * @param string $desc        The description (long) of the task.
     * @param integer $start      The start date of the task.
     * @param integer $due        The due date of the task.
     * @param integer $priority   The priority of the task.
     * @param float $estimate     The estimated time to complete the task.
     * @param integer $completed  The completion state of the task.
     * @param string $category    The category of the task.
     * @param integer $alarm      The alarm associated with the task.
     * @param string $uid         A Unique Identifier for the task.
     * @param string $parent      The parent task id.
     * @param boolean $private    Whether the task is private.
     * @param string $owner       The owner of the event.
     * @param string $assignee    The assignee of the event.
     *
     * @return string  The Nag ID of the new task.
     */
    function add($name, $desc, $start = 0, $due = 0, $priority = 0,
                 $completed = 0, $estimate = 0.0, $category = '', $alarm = 0,
                 $uid = null, $parent = null, $private = false, $owner = null,
                 $assignee = null)
    {
        // Usually provided by the generic Driver class
        if ($uid !== null) {
            $uid = $this->generateUID();
        }

        // Load the object into the kolab driver
        $object = $this->_kolab->newObject($uid);
        if (is_a($object, 'PEAR_Error')) {
            return $object;
        }

        return $this->_setObject($name, $desc, $start, $due, $priority,
                                 $completed, $estimate, $category, $alarm,
                                 $parent, $private, $owner, $assignee);
    }

    /**
     * Modifies an existing task.
     *
     * @param string $taskId           The task to modify.
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     * @param integer $completed_date  The task's completion date.
     *
     * @return boolean  Indicates if the modification was successfull.
     */
    function modify($taskId, $name, $desc, $start = 0, $due = 0,
                    $priority = 0, $estimate = 0.0, $completed = 0,
                    $category = '', $alarm = 0, $parent = null,
                    $private = false, $owner = null, $assignee = null,
                    $completed_date = null)
    {
        // Load the object into the kolab driver
        $result = $this->_kolab->loadObject($taskId);
        if (is_a($object, 'PEAR_Error')) {
            return $object;
        }

        $result = $this->_setObject($name, $desc, $start, $due, $priority,
                                    $estimate, $completed, $category, $alarm,
                                    $parent, $private, $owner, $assignee,
                                    $completed_date);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return $result == $taskId;
    }

    /**
     * Moves a task to a different tasklist.
     *
     * @param string $taskId       The task to move.
     * @param string $newTasklist  The new tasklist.
     */
    function move($taskId, $newTasklist)
    {
        return $this->_kolab->moveObject($taskId, $newTasklist);
    }

    /**
     * Deletes a task from the backend.
     *
     * @param string $taskId  The task to delete.
     */
    function delete($taskId)
    {
        return $this->_kolab->removeObjects($taskId);
    }

    /**
     * Deletes all tasks from the backend.
     */
    function deleteAll()
    {
        return $this->_kolab->removeAllObjects();
    }

    /**
     * Retrieves tasks from the Kolab server.
     *
     * @param integer $completed  Which tasks to retrieve (1 = all tasks,
     *                            0 = incomplete tasks, 2 = complete tasks,
     *                            3 = future tasks, 4 = future and incomplete
     *                            tasks).
     *
     * @return mixed  True on success, PEAR_Error on failure.
     */
    function retrieve($completed = 1)
    {
        $tasks = array();

        $msg_list = $this->_kolab->listObjects();
        if (is_a($msg_list, 'PEAR_Error')) {
            return $msg_list;
        }

        if (empty($msg_list)) {
            return true;
        }

        foreach ($msg_list as $msg) {
            $result = &$this->_kolab->loadObject($msg, true);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
            $complete = Kolab::percentageToBoolean($this->_kolab->getVal('completed'));
            $start_date = Kolab::decodeDateOrDateTime($this->_kolab->getVal('start-date'));
            if (($completed == 0 && ($complete || $start_date > time())) ||
                ($completed == 2 && !$complete) ||
                ($completed == 3 &&
                 ($complete || $start_date == 0 || $start_date < time())) ||
                ($completed == 4 && $complete)) {
                continue;
            }
            $tasks[$this->_kolab->getUID()] = new Nag_Task($this->_buildTask());
        }

        return $tasks;
    }

    /**
     * Lists all alarms near $date.
     *
     * @param integer $date  The unix epoch time to check for alarms.
     *
     * @return array  An array of tasks that have alarms that match.
     */
    function listAlarms($date)
    {
        $tasks = array();

        $msg_list = $this->_kolab->listObjects();
        if (is_a($msg_list, 'PEAR_Error')) {
            return $msg_list;
        }

        if (empty($msg_list)) {
            return $tasks;
        }

        foreach ($msg_list as $msg) {
            $result = &$this->_kolab->loadObject($msg, true);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }

            $task = new Nag_Task($this->_buildTask());

            if ($task['alarm'] > 0 && $task['due'] >= time() && $task['due'] - ($task['alarm'] * 60) <= $date) {
                $tasks[$this->_kolab->getUID()] = $task;
            }
        }

        return $tasks;
    }

    /**
     * Retrieves sub-tasks from the database.
     *
     * @param string $parentId  The parent id for the sub-tasks to retrieve.
     *
     * @return array  List of sub-tasks.
     */
    function getChildren($parentId)
    {
        $tasks = array();

        $msg_list = $this->_kolab->listObjects();
        if (is_a($msg_list, 'PEAR_Error')) {
            return $msg_list;
        }

        if (empty($msg_list)) {
            return $tasks;
        }

        foreach ($msg_list as $msg) {
            $result = &$this->_kolab->loadObject($msg, true);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
            if ($this->_kolab->getVal('parent') != $parentId) {
                continue;
            }
            $task = &new Nag_Task($this->_buildTask());
            $children = $this->getChildren($task->id);
            if (is_a($children, 'PEAR_Error')) {
                return $children;
            }
            $task->mergeChildren($children);
            $tasks[] = $task;
        }

        return $tasks;
    }
}


/**
 * New Nag driver for the Kolab IMAP server.
 *
 * @author  Gunnar Wrobel <wrobel@pardus.de>
 * @package Nag
 */
class Nag_Driver_kolab_wrapper_new extends Nag_Driver_kolab_wrapper {

    /**
     * Shortcut to the imap connection
     *
     * @var Kolab_IMAP
     */
    var $_store = null;

    /**
     * Connect to the Kolab backend
     *
     * @return mixed True on success, a PEAR error otherwise
     */
    function connect()
    {
        if ($this->_connected) {
            return true;
        }

        $result = parent::connect(1);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $this->_store = &$this->_kolab->_storage;

        return true;
    }

    /**
     * Split the tasklist name of the id. We use this to make ids
     * unique across folders.
     *
     * @param string $id The ID of the task appended with the tasklist
     *                   name.
     *
     * @return array  The task id and tasklist name
     */
    function _splitId($id)
    {
        $split = split('@', $id, 2);
        if (count($split) == 2) {
            list($id, $tasklist) = $split;
        } else if (count($split) == 1) {
            $tasklist = Auth::getAuth();
        }
        return array($id, $tasklist);
    }

    /**
     * Append the tasklist name to the id. We use this to make ids
     * unique across folders.
     *
     * @param string $id The ID of the task
     *
     * @return string  The task id appended with the tasklist
     *                 name.
     */
    function _uniqueId($id)
    {
        if ($this->_tasklist == Auth::getAuth()) {
            return $id;
        }
        return $id . '@' . $this->_tasklist;
    }

    /**
     * Retrieves one task from the store.
     *
     * @param string $taskId  The id of the task to retrieve.
     *
     * @return Nag_Task  A Nag_Task object.
     */
    function get($taskId)
    {
        list($taskId, $tasklist) = $this->_splitId($taskId);

        if ($this->_store->objectUidExists($taskId)) {
            $task = $this->_store->getObject($taskId);
            return new Nag_Task($this->_buildTask($task));
        } else {
            return PEAR::raiseError(sprintf(_('Nag/kolab: Did not find task %s'), $taskId));
        }
    }

    /**
     * Retrieves one task from the database by UID.
     *
     * @param string $uid  The UID of the task to retrieve.
     *
     * @return Nag_Task  A Nag_Task object.
     */
    function getByUID($uid)
    {
        list($taskId, $tasklist) = $this->_splitId($uid);

        if ($this->_tasklist != $tasklist) {
            $this->_tasklist = $tasklist;
            $this->_connected = false;
            $this->connect();
        }

        return $this->get($taskId);
    }

    /**
     * Add or modify a task.
     *
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $uid              A Unique Identifier for the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     * @param integer $completed_date  The task's completion date.
     *
     * @return mixed The id of the task if successful, a PEAR error
     * otherwise
     */
    function _setObject($name, $desc, $start = 0, $due = 0, $priority = 0,
                        $estimate = 0.0, $completed = 0, $category = '',
                        $alarm = 0, $uid = null, $parent = null,
                        $private = false, $owner = null, $assignee = null,
                        $completed_date = null)
    {
        if (empty($uid)) {
            $task_uid = $this->_store->generateUID();
            $old_uid = null;
        } else {
            list($task_uid, $tasklist) = $this->_splitId($uid);
            $old_uid = $task_uid;
        }

        if ($parent) {
            list($parent,) = $this->_splitId($parent);
        }

        if ($private) {
            $sensitivity = 'private';
        } else {
            $sensitivity = 'public';
        }

        $result = $this->_store->save(array(
                                          'uid' => $task_uid,
                                          'name' => $name,
                                          'body' => $desc,
                                          'start' => $start,
                                          'due' => $due,
                                          'priority' => $priority,
                                          'completed' => $completed,
                                          'categories' => $category,
                                          'alarm' => $alarm,
                                          'parent' => $parent,
                                          'sensitivity' => $sensitivity,
                                          'estimate' => $estimate,
                                          'completed_date' => $completed_date,
                                          'creator' => array(
                                              'smpt-address' => $owner,
                                          ),
                                          'organizer' => array(
                                              'smpt-address' => $assignee,
                                          ),
                                      ),
                                      $old_uid);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return $task_uid;
    }

    /**
     * Adds a task to the backend storage.
     *
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $uid              A Unique Identifier for the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     *
     * @return mixed The id of the task if successful, a PEAR error
     * otherwise
     */
    function add($name, $desc, $start = 0, $due = 0, $priority = 0,
                 $estimate = 0.0, $completed = 0, $category = '', $alarm = 0,
                 $uid = null, $parent = null, $private = false, $owner = null,
                 $assignee = null)
    {
        return $this->_setObject($name, $desc, $start, $due, $priority,
                                 $estimate, $completed, $category, $alarm,
                                 null, $parent, $private, $owner, $assignee);
    }

    /**
     * Modifies an existing task.
     *
     * @param string $taskId           The task to modify.
     * @param string $name             The name (short) of the task.
     * @param string $desc             The description (long) of the task.
     * @param integer $start           The start date of the task.
     * @param integer $due             The due date of the task.
     * @param integer $priority        The priority of the task.
     * @param float $estimate          The estimated time to complete the task.
     * @param integer $completed       The completion state of the task.
     * @param string $category         The category of the task.
     * @param integer $alarm           The alarm associated with the task.
     * @param string $parent           The parent task id.
     * @param boolean $private         Whether the task is private.
     * @param string $owner            The owner of the event.
     * @param string $assignee         The assignee of the event.
     * @param integer $completed_date  The task's completion date.
     *
     * @return mixed The id of the task if successful, a PEAR error
     * otherwise
     */
    function modify($taskId, $name, $desc, $start = 0, $due = 0, $priority = 0,
                    $estimate = 0.0, $completed = 0, $category = '',
                    $alarm = 0, $parent = null, $private = false,
                    $owner = null, $assignee = null, $completed_date = null)
    {
        $result = $this->_setObject($name, $desc, $start, $due, $priority,
                                    $estimate, $completed, $category, $alarm,
                                    $taskId, $parent, $private, $owner, $assignee,
                                    $completed_date);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return $result == $taskId;
    }

    /**
     * Moves a task to a different tasklist.
     *
     * @param string $taskId       The task to move.
     * @param string $newTasklist  The new tasklist.
     *
     * @return mixed  True on success, PEAR_Error on failure.
     */
    function move($taskId, $newTasklist)
    {
        list($taskId, $tasklist) = $this->_splitId($taskId);

        return $this->_store->move($taskId, $newTasklist);
    }

    /**
     * Deletes a task from the backend.
     *
     * @param string $taskId  The task to delete.
     */
    function delete($taskId)
    {
        list($taskId, $tasklist) = $this->_splitId($taskId);

        return $this->_store->delete($taskId);
    }

    /**
     * Deletes all tasks from the backend.
     */
    function deleteAll()
    {
        return $this->_store->deleteAll();
    }

    /**
     * Retrieves tasks from the Kolab server.
     *
     * @param integer $completed  Which tasks to retrieve (1 = all tasks,
     *                            0 = incomplete tasks, 2 = complete tasks,
     *                            3 = future tasks, 4 = future and incomplete
     *                            tasks).
     *
     * @return mixed  True on success, PEAR_Error on failure.
     */
    function retrieve($completed = 1)
    {
        $dict = array();
        $tasks = new Nag_Task();

        $task_list = $this->_store->getObjects();
        if (is_a($task_list, 'PEAR_Error')) {
            return $task_list;
        }

        if (empty($task_list)) {
            return $tasks;
        }

        foreach ($task_list as $task) {
            $tuid = $this->_uniqueId($task['uid']);
            $t = &new Nag_Task($this->_buildTask($task));
            $complete = $t->completed;
            if (empty($t->start)) {
                $start = null;
            } else {
                $start = $t->start;
            }

            if (($completed == 0 && ($complete || $start > time())) ||
                ($completed == 2 && !$complete) ||
                ($completed == 3 &&
                 ($complete || $start == 0 || $start < time())) ||
                ($completed == 4 && $complete)) {
                continue;
            }
            if (empty($t->parent_id)) {
                $tasks->add($t);
            } else {
                $dict[$tuid] = &$t;
            }
        }

        /* Build a tree from the subtasks. */
        foreach (array_keys($dict) as $key) {
            $task = &$tasks->get($dict[$key]->parent_id);
            if ($task) {
                $task->add($dict[$key]);
            } elseif (isset($dict[$dict[$key]->parent_id])) {
                $dict[$dict[$key]->parent_id]->add($dict[$key]);
            } else {
                $tasks->add($dict[$key]);
            }
        }

        return $tasks;
    }

    /**
     * Build a task based a data array
     *
     * @param array  $task     The data for the task
     *
     * @return array  The converted data array representing the task
     */
    function _buildTask($task)
    {
        $task['tasklist_id'] = $this->_tasklist;
        $task['task_id'] = $this->_uniqueId($task['uid']);

        if (!empty($task['parent'])) {
            $task['parent'] = $this->_uniqueId($task['parent']);
        }

        $task['category'] = $task['categories'];
        unset($task['categories']);

        $task['desc'] = $task['body'];
        unset($task['body']);

        if ($task['sensitivity'] == 'public') {
            $task['private'] = false;
        } else {
            $task['private'] = true;
        }
        unset($task['sensitivity']);

        $share = &$GLOBALS['nag_shares']->getShare($this->_tasklist);
        $task['owner'] = $share->get('owner');

        return $task;
    }

    /**
     * Lists all alarms near $date.
     *
     * @param integer $date  The unix epoch time to check for alarms.
     *
     * @return array  An array of tasks that have alarms that match.
     */
    function listAlarms($date)
    {
        $task_list = $this->_store->getObjects();
        if (is_a($task_list, 'PEAR_Error')) {
            return $task_list;
        }

        if (empty($task_list)) {
            return array();
        }

        $tasks = array();
        foreach ($task_list as $task) {
            $tuid = $this->_uniqueId($task['uid']);
            $t = new Nag_Task($this->_buildTask($task));
            if ($t->alarm && $t->due &&
                $t->due - $t->alarm * 60 < $date) {
                $tasks[] = $t;
            }
        }

        return $tasks;
    }

    /**
     * Retrieves sub-tasks from the database.
     *
     * @param string $parentId  The parent id for the sub-tasks to retrieve.
     *
     * @return array  List of sub-tasks.
     */
    function getChildren($parentId)
    {
        list($parentId, $tasklist) = $this->_splitId($parentId);

        $task_list = $this->_store->getObjects();
        if (is_a($task_list, 'PEAR_Error')) {
            return $task_list;
        }

        if (empty($task_list)) {
            return array();
        }

        $tasks = array();

        foreach ($task_list as $task) {
            if ($task['parent'] != $parentId) {
                continue;
            }
            $t = &new Nag_Task($this->_buildTask($task));
            $children = $this->getChildren($t->id);
            if (is_a($children, 'PEAR_Error')) {
                return $children;
            }
            $t->mergeChildren($children);
            $tasks[] = $t;
        }

        return $tasks;
    }
}