summaryrefslogtreecommitdiff
path: root/lib/kolab_sync_data.php
blob: 9589b73f253a2c0e1589bc3917b09f31968b8436 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
<?php

/**
 +--------------------------------------------------------------------------+
 | Kolab Sync (ActiveSync for Kolab)                                        |
 |                                                                          |
 | Copyright (C) 2011-2012, Kolab Systems AG <contact@kolabsys.com>         |
 |                                                                          |
 | This program is free software: you can redistribute it and/or modify     |
 | it under the terms of the GNU Affero General Public License as published |
 | by the Free Software Foundation, either version 3 of the License, or     |
 | (at your option) any later version.                                      |
 |                                                                          |
 | This program is distributed in the hope that it will be useful,          |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the             |
 | GNU Affero General Public License for more details.                      |
 |                                                                          |
 | You should have received a copy of the GNU Affero General Public License |
 | along with this program. If not, see <http://www.gnu.org/licenses/>      |
 +--------------------------------------------------------------------------+
 | Author: Aleksander Machniak <machniak@kolabsys.com>                      |
 +--------------------------------------------------------------------------+
*/

/**
 * Base class for Syncroton data backends
 */
abstract class kolab_sync_data implements Syncroton_Data_IData
{
    /**
     * ActiveSync protocol version
     *
     * @var int
     */
    protected $asversion = 0;

    /**
     * information about the current device
     *
     * @var Syncroton_Model_IDevice
     */
    protected $device;

    /**
     * timestamp to use for all sync requests
     *
     * @var DateTime
     */
    protected $syncTimeStamp;

    /**
     * name of model to use
     *
     * @var string
     */
    protected $modelName;

    /**
     * type of the default folder
     *
     * @var int
     */
    protected $defaultFolderType;

    /**
     * default container for new entries
     *
     * @var string
     */
    protected $defaultFolder;

    /**
     * type of user created folders
     *
     * @var int
     */
    protected $folderType;

    /**
     * Internal cache for kolab_storage folder objects
     *
     * @var array
     */
    protected $folders = array();

    /**
     * Internal cache for IMAP folders list
     *
     * @var array
     */
    protected $imap_folders = array();

    /**
     * Timezone
     *
     * @var string
     */
    protected $timezone;

    /**
     * List of device types with multiple folders support
     *
     * @var array
     */
    protected $ext_devices = array(
        'iphone',
        'ipad',
        'thundertine',
        'windowsphone',
        'wp',
        'wp8',
        'playbook',
    );

    const RESULT_OBJECT = 0;
    const RESULT_UID    = 1;
    const RESULT_COUNT  = 2;


    /**
     * Recurrence types
     */
    const RECUR_TYPE_DAILY          = 0;     // Recurs daily.
    const RECUR_TYPE_WEEKLY         = 1;     // Recurs weekly
    const RECUR_TYPE_MONTHLY        = 2;     // Recurs monthly
    const RECUR_TYPE_MONTHLY_DAYN   = 3;     // Recurs monthly on the nth day
    const RECUR_TYPE_YEARLY         = 5;     // Recurs yearly
    const RECUR_TYPE_YEARLY_DAYN    = 6;     // Recurs yearly on the nth day

    /**
     * Day of week constants
     */
    const RECUR_DOW_SUNDAY      = 1;
    const RECUR_DOW_MONDAY      = 2;
    const RECUR_DOW_TUESDAY     = 4;
    const RECUR_DOW_WEDNESDAY   = 8;
    const RECUR_DOW_THURSDAY    = 16;
    const RECUR_DOW_FRIDAY      = 32;
    const RECUR_DOW_SATURDAY    = 64;
    const RECUR_DOW_LAST        = 127;      //  The last day of the month. Used as a special value in monthly or yearly recurrences.

    /**
     * Mapping of recurrence types
     *
     * @var array
     */
    protected $recurTypeMap = array(
        self::RECUR_TYPE_DAILY        => 'DAILY',
        self::RECUR_TYPE_WEEKLY       => 'WEEKLY',
        self::RECUR_TYPE_MONTHLY      => 'MONTHLY',
        self::RECUR_TYPE_MONTHLY_DAYN => 'MONTHLY',
        self::RECUR_TYPE_YEARLY       => 'YEARLY',
        self::RECUR_TYPE_YEARLY_DAYN  => 'YEARLY',
    );

    /**
     * Mapping of weekdays
     * NOTE: ActiveSync uses a bitmask
     *
     * @var array
     */
    protected $recurDayMap = array(
        'SU'  => self::RECUR_DOW_SUNDAY,
        'MO'  => self::RECUR_DOW_MONDAY,
        'TU'  => self::RECUR_DOW_TUESDAY,
        'WE'  => self::RECUR_DOW_WEDNESDAY,
        'TH'  => self::RECUR_DOW_THURSDAY,
        'FR'  => self::RECUR_DOW_FRIDAY,
        'SA'  => self::RECUR_DOW_SATURDAY,
    );


    /**
     * the constructor
     *
     * @param Syncroton_Model_IDevice $device
     * @param DateTime                $syncTimeStamp
     */
    public function __construct(Syncroton_Model_IDevice $device, DateTime $syncTimeStamp)
    {
        $this->backend       = kolab_sync_backend::get_instance();
        $this->device        = $device;
        $this->asversion     = floatval($device->acsversion);
        $this->syncTimeStamp = $syncTimeStamp;

        $this->defaultRootFolder = $this->defaultFolder . '::Syncroton';

        // set internal timezone of kolab_format to user timezone
        try {
            $this->timezone = rcube::get_instance()->config->get('timezone', 'GMT');
            kolab_format::$timezone = new DateTimeZone($this->timezone);
        }
        catch (Exception $e) {
            //rcube::raise_error($e, true);
            $this->timezone = 'GMT';
            kolab_format::$timezone = new DateTimeZone('GMT');
        }
    }

    /**
     * return list of supported folders for this backend
     *
     * @return array
     */
    public function getAllFolders()
    {
        $list = array();

        // device supports multiple folders ?
        if (in_array(strtolower($this->device->devicetype), $this->ext_devices)) {
            // get the folders the user has access to
            $list = $this->listFolders();
        }
        else if ($default = $this->getDefaultFolder()) {
            $list = array($default['serverId'] => $default);
        }

        // getAllFolders() is called only in FolderSync
        // throw Syncroton_Exception_Status_FolderSync exception
        if (!is_array($list)) {
            throw new Syncroton_Exception_Status_FolderSync(Syncroton_Exception_Status_FolderSync::FOLDER_SERVER_ERROR);
        }

        foreach ($list as $idx => $folder) {
            $list[$idx] = new Syncroton_Model_Folder($folder);
        }

        return $list;
    }

    /**
     * Retrieve folders which were modified since last sync
     *
     * @param DateTime $startTimeStamp
     * @param DateTime $endTimeStamp
     *
     * @return array List of folders
     */
    public function getChangedFolders(DateTime $startTimeStamp, DateTime $endTimeStamp)
    {
        return array();
    }

    /**
     * Returns default folder for current class type.
     */
    protected function getDefaultFolder()
    {
        // Check if there's any folder configured for sync
        $folders = $this->listFolders();

        if (empty($folders)) {
            return $folders;
        }

        foreach ($folders as $folder) {
            if ($folder['type'] == $this->defaultFolderType) {
                $default = $folder;
                break;
            }
        }

        // Return first on the list if there's no default
        if (empty($default)) {
            $key     = array_shift(array_keys($folders));
            $default = $folders[$key];
            // make sure the type is default here
            $default['type'] = $this->defaultFolderType;
        }

        // Remember real folder ID and set ID/name to root folder
        $default['realid']      = $default['serverId'];
        $default['serverId']    = $this->defaultRootFolder;
        $default['displayName'] = $this->defaultFolder;

        return $default;
    }

    /**
     * Creates a folder
     */
    public function createFolder(Syncroton_Model_IFolder $folder)
    {
        $parentid     = $folder->parentId;
        $type         = $folder->type;
        $display_name = $folder->displayName;

        if ($parentid) {
            $parent = $this->backend->folder_id2name($parentid, $this->device->deviceid);
        }

        $name = rcube_charset::convert($display_name, kolab_sync::CHARSET, 'UTF7-IMAP');

        if ($parent !== null) {
            $rcube   = rcube::get_instance();
            $storage = $rcube->get_storage();
            $delim   = $storage->get_hierarchy_delimiter();
            $name    = $parent . $delim . $name;
        }

        // Create IMAP folder
        $result = $this->backend->folder_create($name, $type, $this->device->deviceid);

        if ($result) {
            $folder->serverId = $this->backend->folder_id($name);
            return $folder;
        }

        // @TODO: throw exception
    }

    /**
     * Updates a folder
     */
    public function updateFolder(Syncroton_Model_IFolder $folder)
    {
        $parentid     = $folder->parentId;
        $type         = $folder->type;
        $display_name = $folder->displayName;
        $old_name     = $this->backend->folder_id2name($folder->serverId, $this->device->deviceid);

        if ($parentid) {
            $parent = $this->backend->folder_id2name($parentid, $this->device->deviceid);
        }

        $name = rcube_charset::convert($display_name, kolab_sync::CHARSET, 'UTF7-IMAP');

        if ($parent !== null) {
            $rcube   = rcube::get_instance();
            $storage = $rcube->get_storage();
            $delim   = $storage->get_hierarchy_delimiter();
            $name    = $parent . $delim . $name;
        }

        // Rename/move IMAP folder
        if ($name == $old_name) {
            $result = true;
            // @TODO: folder type change?
        }
        else {
            $result = $this->backend->folder_rename($old_name, $name, $type, $this->device->deviceid);
        }

        if ($result) {
            $folder->serverId = $this->backend->folder_id($name);
            return $folder;
        }

        // @TODO: throw exception
    }

    /**
     * Deletes a folder
     */
    public function deleteFolder($folder)
    {
        if ($folder instanceof Syncroton_Model_IFolder) {
            $folder = $folder->serverId;
        }

        $name = $this->backend->folder_id2name($folder, $this->device->deviceid);

        // @TODO: throw exception
        return $this->backend->folder_delete($name, $this->device->deviceid);
    }

    /**
     * Empty folder (remove all entries and optionally subfolders)
     *
     * @param string $folderId Folder identifier
     * @param array  $options  Options
     */
    public function emptyFolderContents($folderid, $options)
    {
        $folders = $this->extractFolders($folderid);

        foreach ($folders as $folderid) {
            $foldername = $this->backend->folder_id2name($folderid, $this->device->deviceid);

            if ($foldername === null) {
                continue;
            }

            $folder = $this->getFolderObject($foldername);

            // Remove all entries
            $folder->delete_all();

            // Remove subfolders
            if (!empty($options['deleteSubFolders'])) {
                $list = $this->listFolders($folderid);
                foreach ($list as $folderid => $folder) {
                    $foldername = $this->backend->folder_id2name($folderid, $this->device->deviceid);

                    if ($foldername === null) {
                        continue;
                    }

                    $folder = $this->getFolderObject($foldername);

                    // Remove all entries
                    $folder->delete_all();
                }
            }
        }
    }

    /**
     * Moves object into another location (folder)
     *
     * @param string $srcFolderId Source folder identifier
     * @param string $serverId    Object identifier
     * @param string $dstFolderId Destination folder identifier
     *
     * @throws Syncroton_Exception_Status
     * @return string New object identifier
     */
    public function moveItem($srcFolderId, $serverId, $dstFolderId)
    {
        $item = $this->getObject($srcFolderId, $serverId, $folder);

        if (!$item || !$folder) {
            throw new Syncroton_Exception_Status_MoveItems(Syncroton_Exception_Status_MoveItems::INVALID_SOURCE);
        }

        $dstname = $this->backend->folder_id2name($dstFolderId, $this->device->deviceid);

        if ($dstname === null) {
            throw new Syncroton_Exception_Status_MoveItems(Syncroton_Exception_Status_MoveItems::INVALID_DESTINATION);
        }

        if (!$folder->move($serverId, $dstname)) {
            throw new Syncroton_Exception_Status_MoveItems(Syncroton_Exception_Status_MoveItems::INVALID_SOURCE);
        }

        return $item['uid'];
    }

    /**
     * Add entry
     *
     * @param string                 $folderId Folder identifier
     * @param Syncroton_Model_IEntry $entry    Entry object
     *
     * @return string ID of the created entry
     */
    public function createEntry($folderId, Syncroton_Model_IEntry $entry)
    {
        $entry = $this->toKolab($entry, $folderId);
        $entry = $this->createObject($folderId, $entry);

        if (empty($entry)) {
            throw new Syncroton_Exception_Status_Sync(Syncroton_Exception_Status_Sync::SYNC_SERVER_ERROR);
        }

        return $entry['uid'];
    }

    /**
     * update existing entry
     *
     * @param string           $folderId
     * @param string           $serverId
     * @param SimpleXMLElement $entry
     *
     * @return string ID of the updated entry
     */
    public function updateEntry($folderId, $serverId, Syncroton_Model_IEntry $entry)
    {
        $oldEntry = $this->getObject($folderId, $serverId);

        if (empty($oldEntry)) {
            throw new Syncroton_Exception_NotFound('id not found');
        }

        $entry = $this->toKolab($entry, $folderId, $oldEntry);
        $entry = $this->updateObject($folderId, $serverId,  $entry);

        if (empty($entry)) {
            throw new Syncroton_Exception_Status_Sync(Syncroton_Exception_Status_Sync::SYNC_SERVER_ERROR);
        }

        return $entry['uid'];
    }

    /**
     * delete entry
     *
     * @param  string  $folderId
     * @param  string  $serverId
     * @param  array   $collectionData
     */
    public function deleteEntry($folderId, $serverId, $collectionData)
    {
        $deleted = $this->deleteObject($folderId, $serverId);

        if (!$deleted) {
            throw new Syncroton_Exception_Status_Sync(Syncroton_Exception_Status_Sync::SYNC_SERVER_ERROR);
        }
    }


    public function getFileReference($fileReference)
    {
        // to be implemented by Email data class
        // @TODO: throw "unimplemented" exception here?
    }


    /**
     * Search for existing entries
     *
     * @param string $folderid    Folder identifier
     * @param array  $filter      Search filter
     * @param int    $result_type Type of the result (see RESULT_* constants)
     *
     * @return array|int  Search result as count or array of uids/objects
     */
    protected function searchEntries($folderid, $filter = array(), $result_type = self::RESULT_UID)
    {
        if ($folderid == $this->defaultRootFolder) {
            $folders = $this->listFolders();

            if (!is_array($folders)) {
                throw new Syncroton_Exception_Status(Syncroton_Exception_Status::SERVER_ERROR);
            }

            $folders = array_keys($folders);
        }
        else {
            $folders = array($folderid);
        }

        // there's a PHP Warning from kolab_storage if $filter isn't an array
        if (empty($filter)) {
            $filter = array();
        }
        else {
            $changed_objects = $this->getChangesByRelations($folderid, $filter);
        }

        $result = $result_type == self::RESULT_COUNT ? 0 : array();
        $found  = 0;

        foreach ($folders as $folder_id) {
            $foldername = $this->backend->folder_id2name($folder_id, $this->device->deviceid);

            if ($foldername === null || !($folder = $this->getFolderObject($foldername))) {
                continue;
            }

            $found++;
            $error = false;

            switch ($result_type) {
            case self::RESULT_COUNT:
                $count = $folder->count($filter);

                if ($count === null || $count === false) {
                    $error = true;
                }
                else {
                    $result += (int) $count;
                }
                break;

            case self::RESULT_UID:
                $uids = $folder->get_uids($filter);

                if (!is_array($uids)) {
                    $error = true;
                }
                else {
                    $result = array_merge($result, $uids);
                }
                break;
            }

            if ($error) {
                throw new Syncroton_Exception_Status(Syncroton_Exception_Status::SERVER_ERROR);
            }

            // handle tag modifications
            if (!empty($changed_objects)) {
                // build new filter
                // search objects mathing current filter,
                // relations may contain members of many types, we need to
                // search them by UID in all requested folders to get
                // only these with requested type (and that really exist
                // in specified folders)
                $tag_filter = array(array('uid', '=', $changed_objects));
                foreach ($filter as $f) {
                    if ($f[0] != 'changed') {
                        $tag_filter[] = $f;
                    }
                }

                switch ($result_type) {
                case self::RESULT_COUNT:
                    // Note: this way we're potentally counting the same objects twice
                    // I'm not sure if this is a problem, we most likely do not
                    // need a precise result here
                    $count = $folder->count($tag_filter);
                    if ($count !== null && $count !== false) {
                        $result += (int) $count;
                    }

                    break;

                case self::RESULT_UID:
                    $uids = $folder->get_uids($tag_filter);
                    if (is_array($uids)) {
                        $result = array_unique(array_merge($result, $uids));
                    }

                    break;
                }
            }
        }

        if (!$found) {
            throw new Syncroton_Exception_Status(Syncroton_Exception_Status::SERVER_ERROR);
        }

        return $result;
    }

    /**
     * Detect changes of relation (tag) objects data and assigned objects
     * Returns relation member identifiers
     */
    protected function getChangesByRelations($folderid, $filter)
    {
        if (!$this->tag_categories) {
            return;
        }

        // get period filter, create new objects filter
        foreach ($filter as $f) {
            if ($f[0] == 'changed' && $f[1] == '>') {
                $since = $f[2];
            }
        }

        // this is not search for changes, do nothing
        if (empty($since)) {
            return;
        }

        // get relations state from the last sync
        $last_state = (array) $this->backend->relations_state_get($this->device->id, $folderid, $since);

        // get current relations state
        $config  = kolab_storage_config::get_instance();
        $default = true;
        $filter  = array(
            array('type', '=', 'relation'),
            array('category', '=', 'tag')
        );

        $relations = $config->get_objects($filter, $default, 100);

        $result  = array();
        $changed = false;

        // compare states, get members of changed relations
        foreach ($relations as $idx => $relation) {
            $rel_id = $relation['uid'];

            if ($relation['changed']) {
                $relation['changed']->setTimezone(new DateTimeZone('UTC'));
            }

            // last state unknown...
            if (empty($last_state[$rel_id])) {
                // ...get all members
                if (!empty($relation['members'])) {
                    $changed = true;
                    $result  = array_merge($result, $relation['members']);
                }
            }
            // last state known, changed tag name...
            else if ($last_state[$rel_id]['name'] != $relation['name']) {
                // ...get all (old and new) members
                $members_old = explode("\n", $last_state[$rel_id]['members']);
                $changed = true;
                $members = array_unique(array_merge($relation['members'], $members_old));
                $result  = array_merge($result, $members);
            }
            // last state known, any other change change...
            else if ($last_state[$rel_id]['changed'] < $relation['changed']->format('U')) {
                // ...find new and removed members
                $members_old = explode("\n", $last_state[$rel_id]['members']);
                $new     = array_diff($relation['members'], $members_old);
                $removed = array_diff($members_old, $relation['members']);

                if (!empty($new) || !empty($removed)) {
                    $changed = true;
                    $result  = array_merge($result, $new, $removed);
                }
            }

            unset($last_state[$rel_id]);
        }

        // get members of deleted relations
        if (!empty($last_state)) {
            $changed = true;
            foreach ($last_state as $relation) {
                $members = explode("\n", $relation['members']);
                $result  = array_merge($result, $members);
            }
        }

        // save current state
        if ($changed) {
            $data = array();
            foreach ($relations as $relation) {
                $data[$relation['uid']] = array(
                    'name'    => $relation['name'],
                    'changed' => $relation['changed']->format('U'),
                    'members' => implode("\n", $relation['members']),
                );
            }

            $now = new DateTime('now', new DateTimeZone('UTC'));

            $this->backend->relations_state_set($this->device->id, $folderid, $now, $data);
        }

        // in mail mode return only message URIs
        if ($this->modelName == 'mail') {
            // lambda function to skip email members
            $filter_func = function($value) {
                return strpos($value, 'imap://') === 0;
            };

            $result = array_filter(array_unique($result), $filter_func);
        }
        // otherwise return only object UIDs
        else {
            // lambda function to skip email members
            $filter_func = function($value) {
                return strpos($value, 'urn:uuid:') === 0;
            };

            // lambda function to parse member URI
            $member_func = function($value) {
                if (strpos($value, 'urn:uuid:') === 0) {
                    $value = substr($value, 9);
                }
                return $value;
            };

            $result = array_map($member_func, array_filter(array_unique($result), $filter_func));
        }

        return $result;
    }

    /**
     * Returns filter query array according to specified ActiveSync FilterType
     *
     * @param int $filter_type  Filter type
     *
     * @param array  Filter query
     */
    protected function filter($filter_type = 0)
    {
        // overwrite by child class according to specified type
        return array();
    }

    /**
     * get all entries changed between two dates
     *
     * @param string   $folderId
     * @param DateTime $start
     * @param DateTime $end
     * @param int      $filterType
     *
     * @return array
     */
    public function getChangedEntries($folderId, DateTime $start, DateTime $end = null, $filter_type = null)
    {
        $filter   = $this->filter($filter_type);
        $filter[] = array('changed', '>', $start);

        if ($end) {
            $filter[] = array('changed', '<=', $end);
        }

        return $this->searchEntries($folderId, $filter, self::RESULT_UID);
    }

    /**
     * Get count of entries changed between two dates
     *
     * @param string   $folderId
     * @param DateTime $start
     * @param DateTime $end
     * @param int      $filterType
     *
     * @return int
     */
    public function getChangedEntriesCount($folderId, DateTime $start, DateTime $end = null, $filter_type = null)
    {
        $filter   = $this->filter($filter_type);
        $filter[] = array('changed', '>', $start);

        if ($end) {
            $filter[] = array('changed', '<=', $end);
        }

        return $this->searchEntries($folderId, $filter, self::RESULT_COUNT);
    }

    /**
     * get id's of all entries available on the server
     *
     * @param string $folderId
     * @param int    $filterType
     *
     * @return array
     */
    public function getServerEntries($folder_id, $filter_type)
    {
        $filter = $this->filter($filter_type);
        $result = $this->searchEntries($folder_id, $filter, self::RESULT_UID);

        return $result;
    }

    /**
     * get count of all entries available on the server
     *
     * @param string $folderId
     * @param int $filterType
     *
     * @return int
     */
    public function getServerEntriesCount($folder_id, $filter_type)
    {
        $filter = $this->filter($filter_type);
        $result = $this->searchEntries($folder_id, $filter, self::RESULT_COUNT);

        return $result;
    }

    /**
     * Returns number of changed objects in the backend folder
     *
     * @param Syncroton_Backend_IContent $contentBackend
     * @param Syncroton_Model_IFolder    $folder
     * @param Syncroton_Model_ISyncState $syncState
     *
     * @return int
     */
    public function getCountOfChanges(Syncroton_Backend_IContent $contentBackend, Syncroton_Model_IFolder $folder, Syncroton_Model_ISyncState $syncState)
    {
        $allClientEntries = $contentBackend->getFolderState($this->device, $folder);
        $allServerEntries = $this->getServerEntries($folder->serverId, $folder->lastfiltertype);
        $changedEntries   = $this->getChangedEntriesCount($folder->serverId, $syncState->lastsync, null, $folder->lastfiltertype);
        $addedEntries     = array_diff($allServerEntries, $allClientEntries);
        $deletedEntries   = array_diff($allClientEntries, $allServerEntries);

        return count($addedEntries) + count($deletedEntries) + $changedEntries;
    }

    /**
     * Returns true if any data got modified in the backend folder
     *
     * @param Syncroton_Backend_IContent $contentBackend
     * @param Syncroton_Model_IFolder    $folder
     * @param Syncroton_Model_ISyncState $syncState
     *
     * @return bool
     */
    public function hasChanges(Syncroton_Backend_IContent $contentBackend, Syncroton_Model_IFolder $folder, Syncroton_Model_ISyncState $syncState)
    {
        try {
            if ($this->getChangedEntriesCount($folder->serverId, $syncState->lastsync, null, $folder->lastfiltertype)) {
                return true;
            }

            $allClientEntries = $contentBackend->getFolderState($this->device, $folder);

            // @TODO: Consider looping over all folders here, not in getServerEntries() and
            // getChangedEntriesCount(). This way we could break the loop and not check all folders
            // or at least skip redundant cache sync of the same folder
            $allServerEntries = $this->getServerEntries($folder->serverId, $folder->lastfiltertype);

            $addedEntries   = array_diff($allServerEntries, $allClientEntries);
            $deletedEntries = array_diff($allClientEntries, $allServerEntries);

            return count($addedEntries) > 0 || count($deletedEntries) > 0;
        }
        catch (Exception $e) {
            // return "no changes" if something failed
            return false;
        }
    }

    /**
     * Fetches the entry from the backend
     */
    protected function getObject($folderid, $entryid, &$folder = null)
    {
        $folders = $this->extractFolders($folderid);

        foreach ($folders as $folderid) {
            $foldername = $this->backend->folder_id2name($folderid, $this->device->deviceid);

            if ($foldername === null) {
                continue;
            }

            $folder = $this->getFolderObject($foldername);

            if ($folder && ($object = $folder->get_object($entryid))) {
                $object['_folderid'] = $folderid;

                return $object;
            }
        }
    }

    /**
     * Saves the entry on the backend
     */
    protected function createObject($folderid, $data)
    {
        if ($folderid == $this->defaultRootFolder) {
            $default  = $this->getDefaultFolder();

            if (!is_array($default)) {
                return null;
            }

            $folderid = isset($default['realid']) ? $default['realid'] : $default['serverId'];
        }

        // convert categories into tags, save them after creating an object
        if ($this->tag_categories) {
            $tags = $data['categories'];
            unset($data['categories']);
        }

        $foldername = $this->backend->folder_id2name($folderid, $this->device->deviceid);
        $folder     = $this->getFolderObject($foldername);

        if ($folder && $folder->save($data)) {
            if (!empty($tags)) {
                $this->setKolabTags($data['uid'], $tags);
            }

            return $data;
        }
    }

    /**
     * Updates the entry on the backend
     */
    protected function updateObject($folderid, $entryid, $data)
    {
        $object = $this->getObject($folderid, $entryid);

        if ($object) {
            $folder = $this->getFolderObject($object['_mailbox']);

            // convert categories into tags, save them after updating an object
            if ($this->tag_categories && array_key_exists('categories', $data)) {
                $tags = (array) $data['categories'];
                unset($data['categories']);
            }

            if ($folder && $folder->save($data)) {
                if (isset($tags)) {
                    $this->setKolabTags($data['uid'], $tags);
                }

                return $data;
            }
        }
    }

    /**
     * Removes the entry from the backend
     */
    protected function deleteObject($folderid, $entryid)
    {
        $object = $this->getObject($folderid, $entryid);

        if ($object) {
            $folder = $this->getFolderObject($object['_mailbox']);

            if ($folder && $folder->delete($entryid)) {
                if ($this->tag_categories) {
                    $this->setKolabTags($object['uid'], null);
                }

                return true;
            }

            return false;
        }

        // object doesn't exist, confirm deletion
        return true;
    }

    /**
     * Returns internal folder IDs
     *
     * @param string $folderid Folder identifier
     *
     * @return array List of folder identifiers
     */
    protected function extractFolders($folderid)
    {
        if ($folderid instanceof Syncroton_Model_IFolder) {
            $folderid = $folderid->serverId;
        }

        if ($folderid == $this->defaultRootFolder) {
            $folders = $this->listFolders();

            if (!is_array($folders)) {
                return null;
            }

            $folders = array_keys($folders);
        }
        else {
            $folders = array($folderid);
        }

        return $folders;
    }

    /**
     * List of all IMAP folders (or subtree)
     *
     * @param string $parentid Parent folder identifier
     *
     * @return array List of folder identifiers
     */
    protected function listFolders($parentid = null)
    {
        if (empty($this->imap_folders)) {
            $this->imap_folders = $this->backend->folders_list($this->device->deviceid, $this->modelName);
        }

        if ($parentid === null) {
            return $this->imap_folders;
        }

        $folders = array();
        $parents = array($parentid);

        foreach ($this->imap_folders as $folder_id => $folder) {
            if ($folder['parentId'] && in_array($folder['parentId'], $parents)) {
                $folders[$folder_id] = $folder;
                $parents[] = $folder_id;
            }
        }

        return $folders;
    }

    /**
     * Returns Folder object (uses internal cache)
     *
     * @param string $name  Folder name (UTF7-IMAP)
     *
     * @return kolab_storage_folder Folder object
     */
    protected function getFolderObject($name)
    {
        if ($name === null) {
            return null;
        }

        if (!isset($this->folders[$name])) {
            $this->folders[$name] = kolab_storage::get_folder($name);
        }

        return $this->folders[$name];
    }

    /**
     * Returns ActiveSync settings of specified folder
     *
     * @param string $name Folder name (UTF7-IMAP)
     *
     * @return array Folder settings
     */
    protected function getFolderConfig($name)
    {
        $metadata = $this->backend->folder_meta();

        if (!is_array($metadata)) {
            return array();
        }

        $deviceid = $this->device->deviceid;
        $config   = $metadata[$name]['FOLDER'][$deviceid];

        return array(
            'ALARMS' => $config['S'] == 2,
        );
    }

    /**
     * Returns real folder name for specified folder ID
     */
    protected function getFolderName($folderid)
    {
        if ($folderid == $this->defaultRootFolder) {
            $default  = $this->getDefaultFolder();

            if (!is_array($default)) {
                return null;
            }

            $folderid = isset($default['realid']) ? $default['realid'] : $default['serverId'];
        }

        return $this->backend->folder_id2name($folderid, $this->device->deviceid);
    }

    /**
     * Convert contact from xml to kolab format
     *
     * @param Syncroton_Model_IEntry $data     Contact data
     * @param string                 $folderId Folder identifier
     * @param array                  $entry    Old Contact data for merge
     *
     * @return array
     */
    abstract function toKolab(Syncroton_Model_IEntry $data, $folderId, $entry = null);

    /**
     * Extracts data from kolab data array
     */
    protected function getKolabDataItem($data, $name)
    {
        $name_items = explode('.', $name);
        $count      = count($name_items);

        // multi-level array (e.g. address, phone)
        if ($count == 3) {
            $name     = $name_items[0];
            $type     = $name_items[1];
            $key_name = $name_items[2];

            if (!empty($data[$name]) && is_array($data[$name])) {
                foreach ($data[$name] as $element) {
                    if ($element['type'] == $type) {
                        return $element[$key_name];
                    }
                }
            }

            return null;
        }
/*
        // hash array e.g. organizer
        else if ($count == 2) {
            $name     = $name_items[0];
            $type     = $name_items[1];
            $key_name = $name_items[2];

            if (!empty($data[$name]) && is_array($data[$name])) {
                foreach ($data[$name] as $element) {
                    if ($element['type'] == $type) {
                        return $element[$key_name];
                    }
                }
            }

            return null;
        }
*/
        $name_items = explode(':', $name);
        $name       = $name_items[0];

        if (empty($data[$name])) {
            return null;
        }

        // simple array (e.g. email)
        if (count($name_items) == 2) {
            return $data[$name][$name_items[1]];
        }

        return $data[$name];
    }

    /**
     * Saves data in kolab data array
     */
    protected function setKolabDataItem(&$data, $name, $value)
    {
        if (empty($value)) {
            return $this->unsetKolabDataItem($data, $name);
        }

        $name_items = explode('.', $name);

        // multi-level array (e.g. address, phone)
        if (count($name_items) == 3) {
            $name     = $name_items[0];
            $type     = $name_items[1];
            $key_name = $name_items[2];

            if (!isset($data[$name])) {
                $data[$name] = array();
            }

            foreach ($data[$name] as $idx => $element) {
                if ($element['type'] == $type) {
                    $found = $idx;
                    break;
                }
            }

            if (!isset($found)) {
                $data[$name] = array_values($data[$name]);
                $found = count($data[$name]);
                $data[$name][$found] = array('type' => $type);
            }

            $data[$name][$found][$key_name] = $value;

            return;
        }

        $name_items = explode(':', $name);
        $name       = $name_items[0];

        // simple array (e.g. email)
        if (count($name_items) == 2) {
            $data[$name][$name_items[1]] = $value;
            return;
        }

        $data[$name] = $value;
    }

    /**
     * Unsets data item in kolab data array
     */
    protected function unsetKolabDataItem(&$data, $name)
    {
        $name_items = explode('.', $name);

        // multi-level array (e.g. address, phone)
        if (count($name_items) == 3) {
            $name     = $name_items[0];
            $type     = $name_items[1];
            $key_name = $name_items[2];

            if (!isset($data[$name])) {
                return;
            }

            foreach ($data[$name] as $idx => $element) {
                if ($element['type'] == $type) {
                    $found = $idx;
                    break;
                }
            }

            if (!isset($found)) {
                return;
            }

            unset($data[$name][$found][$key_name]);

            // if there's only one element and it's 'type', remove it
            if (count($data[$name][$found]) == 1 && isset($data[$name][$found]['type'])) {
                unset($data[$name][$found]['type']);
            }
            if (empty($data[$name][$found])) {
                unset($data[$name][$found]);
            }
            if (empty($data[$name])) {
                unset($data[$name]);
            }

            return;
        }

        $name_items = explode(':', $name);
        $name       = $name_items[0];

        // simple array (e.g. email)
        if (count($name_items) == 2) {
            unset($data[$name][$name_items[1]]);
            if (empty($data[$name])) {
                unset($data[$name]);
            }
            return;
        }

        unset($data[$name]);
    }

    /**
     * Setter for Body attribute according to client version
     *
     * @param string $value Body
     * @param array  $param Body parameters
     *
     * @reurn Syncroton_Model_EmailBody Body element
     */
    protected function setBody($value, $params = array())
    {
        if (empty($value) && empty($params)) {
            return;
        }

        // Old protocol version doesn't support AirSyncBase:Body, it's eg. WindowsCE
        if ($this->asversion < 12) {
            return;
        }

        if (!empty($value)) {
            // cast to string to workaround issue described in Bug #1635
            $params['data'] = (string) $value;
        }

        if (!isset($params['type'])) {
            $params['type'] = Syncroton_Model_EmailBody::TYPE_PLAINTEXT;
        }

        return new Syncroton_Model_EmailBody($params);
    }

    /**
     * Getter for Body attribute value according to client version
     *
     * @param mixed $body Body element
     * @param int   $type Result data type (to which the body will be converted, if specified).
     *                    One or array of Syncroton_Model_EmailBody constants.
     *
     * @return string Body value
     */
    protected function getBody($body, $type = null)
    {
        if ($body && $body->data) {
            $data = $body->data;
        }

        if (!$data || empty($type)) {
            return;
        }

        $type = (array) $type;

        // Convert to specified type
        if (!in_array($body->type, $type)) {
            $converter = new kolab_sync_body_converter($data, $body->type);
            $data      = $converter->convert($type[0]);
        }

        return $data;
    }

    /**
     * Converts text (plain or html) into ActiveSync Body element.
     * Takes bodyPreferences into account and detects if the text is plain or html.
     */
    protected function body_from_kolab($body, $collection)
    {
        if (empty($body)) {
            return;
        }

        $opts      = $collection->options;
        $prefs     = $opts['bodyPreferences'];
        $html_type = Syncroton_Command_Sync::BODY_TYPE_HTML;
        $type      = Syncroton_Command_Sync::BODY_TYPE_PLAIN_TEXT;
        $params    = array();

        // HTML? check for opening and closing <html> or <body> tags
        $is_html = preg_match('/<(html|body)(\s+[a-z]|>)/', $body, $m) && strpos($body, '</'.$m[1].'>') > 0;

        // here we assume that all devices support plain text
        if ($is_html) {
            // device supports HTML...
            if (!empty($prefs[$html_type])) {
                $type = $html_type;
            }
            // ...else convert to plain text
            else {
                $txt  = new rcube_html2text($body, false, true);
                $body = $txt->get_text();
            }
        }

        // strip out any non utf-8 characters
        $body        = rcube_charset::clean($body);
        $real_length = $body_length = strlen($body);

        // truncate the body if needed
        if (($truncateAt = $prefs[$type]['truncationSize']) && $body_length > $truncateAt) {
            $body        = mb_strcut($body, 0, $truncateAt);
            $body_length = strlen($body);

            $params['truncated']         = 1;
            $params['estimatedDataSize'] = $real_length;
        }

        $params['type'] = $type;

        return $this->setBody($body, $params);
    }


    /**
     * Converts PHP DateTime, date (YYYY-MM-DD) or unixtimestamp into PHP DateTime in UTC
     *
     * @param DateTime|int|string $date Unix timestamp, date (YYYY-MM-DD) or PHP DateTime object
     *
     * @return DateTime Datetime object
     */
    protected static function date_from_kolab($date)
    {
        if (!empty($date)) {
            if (is_numeric($date)) {
                $date = new DateTime('@' . $date);
            }
            else if (is_string($date)) {
                $date = new DateTime($date, new DateTimeZone('UTC'));
            }
            else if ($date instanceof DateTime) {
                $date    = clone $date;
                $tz      = $date->getTimezone();
                $tz_name = $tz->getName();

                // convert to UTC if needed
                if ($tz_name != 'UTC') {
                    $utc = new DateTimeZone('UTC');
                    // safe dateonly object conversion to UTC
                    // note: _dateonly flag is set by libkolab e.g. for birthdays
                    if ($date->_dateonly) {
                        // avoid time change
                        $date = new DateTime($date->format('Y-m-d'), $utc);
                        // set time to noon to avoid timezone troubles
                        $date->setTime(12, 0, 0);
                    }
                    else {
                        $date->setTimezone($utc);
                    }
                }
            }
            else {
                return null; // invalid input
            }

            return $date;
        }
    }

    /**
     * Convert Kolab event/task recurrence into ActiveSync
     */
    protected function recurrence_from_kolab($collection, $data, &$result, $type = 'Event')
    {
        if (empty($data['recurrence'])) {
            return;
        }

        $recurrence = array();
        $r          = $data['recurrence'];

        // required fields
        switch($r['FREQ']) {
        case 'DAILY':
            $recurrence['type'] = self::RECUR_TYPE_DAILY;
            break;

        case 'WEEKLY':
            $recurrence['type'] = self::RECUR_TYPE_WEEKLY;
            $recurrence['dayOfWeek'] = $this->day2bitmask($r['BYDAY']);
            break;

        case 'MONTHLY':
            if (!empty($r['BYMONTHDAY'])) {
                // @TODO: ActiveSync doesn't support multi-valued month days,
                // should we replicate the recurrence element for each day of month?
                $month_day = array_shift(explode(',', $r['BYMONTHDAY']));
                $recurrence['type'] = self::RECUR_TYPE_MONTHLY;
                $recurrence['dayOfMonth'] = $month_day;
            }
            else {
                $week = (int) substr($r['BYDAY'], 0, -2);
                $week = ($week == -1) ? 5 : $week;
                $day  = substr($r['BYDAY'], -2);
                $recurrence['type'] = self::RECUR_TYPE_MONTHLY_DAYN;
                $recurrence['weekOfMonth'] = $week;
                $recurrence['dayOfWeek'] = $this->day2bitmask($day);
            }
            break;

        case 'YEARLY':
            // @TODO: ActiveSync doesn't support multi-valued months,
            // should we replicate the recurrence element for each month?
            $month = array_shift(explode(',', $r['BYMONTH']));

            if (!empty($r['BYDAY'])) {
                $week = (int) substr($r['BYDAY'], 0, -2);
                $week = ($week == -1) ? 5 : $week;
                $day  = substr($r['BYDAY'], -2);
                $recurrence['type'] = self::RECUR_TYPE_YEARLY_DAYN;
                $recurrence['weekOfMonth'] = $week;
                $recurrence['dayOfWeek'] = $this->day2bitmask($day);
                $recurrence['monthOfYear'] = $month;
            }
            else if (!empty($r['BYMONTHDAY'])) {
                // @TODO: ActiveSync doesn't support multi-valued month days,
                // should we replicate the recurrence element for each day of month?
                $month_day = array_shift(explode(',', $r['BYMONTHDAY']));
                $recurrence['type'] = self::RECUR_TYPE_YEARLY;
                $recurrence['dayOfMonth'] = $month_day;
                $recurrence['monthOfYear'] = $month;
            }
            else {
                $recurrence['type'] = self::RECUR_TYPE_YEARLY;
                $recurrence['monthOfYear'] = $month;
            }
            break;
        }

        // required field
        $recurrence['interval'] = $r['INTERVAL'] ? $r['INTERVAL'] : 1;

        if (!empty($r['UNTIL'])) {
            $recurrence['until'] = self::date_from_kolab($r['UNTIL']);
        }
        else if (!empty($r['COUNT'])) {
            $recurrence['occurrences'] = $r['COUNT'];
        }

        $class = 'Syncroton_Model_' . $type . 'Recurrence';

        $result['recurrence'] = new $class($recurrence);

        // Tasks do not support exceptions
        if ($type == 'Event') {
            $result['exceptions'] = $this->exceptions_from_kolab($collection, $data, $result);
        }
    }

    /**
     * Convert ActiveSync event/task recurrence into Kolab
     */
    protected function recurrence_to_kolab($data, $folderid, $timezone = null)
    {
        if (!($data->recurrence instanceof Syncroton_Model_EventRecurrence) || !isset($data->recurrence->type)) {
            return null;
        }

        $recurrence = $data->recurrence;
        $type       = $recurrence->type;

        switch ($type) {
        case self::RECUR_TYPE_DAILY:
            break;

        case self::RECUR_TYPE_WEEKLY:
            $rrule['BYDAY'] = $this->bitmask2day($recurrence->dayOfWeek);
            break;

        case self::RECUR_TYPE_MONTHLY:
            $rrule['BYMONTHDAY'] = $recurrence->dayOfMonth;
            break;

        case self::RECUR_TYPE_MONTHLY_DAYN:
            $week = $recurrence->weekOfMonth;
            $day  = $recurrence->dayOfWeek;
            $byDay  = $week == 5 ? -1 : $week;
            $byDay .= $this->bitmask2day($day);

            $rrule['BYDAY'] = $byDay;
            break;

        case self::RECUR_TYPE_YEARLY:
            $rrule['BYMONTH']    = $recurrence->monthOfYear;
            $rrule['BYMONTHDAY'] = $recurrence->dayOfMonth;
            break;

        case self::RECUR_TYPE_YEARLY_DAYN:
            $rrule['BYMONTH'] = $recurrence->monthOfYear;

            $week = $recurrence->weekOfMonth;
            $day  = $recurrence->dayOfWeek;
            $byDay  = $week == 5 ? -1 : $week;
            $byDay .= $this->bitmask2day($day);

            $rrule['BYDAY'] = $byDay;
            break;
        }

        $rrule['FREQ']     = $this->recurTypeMap[$type];
        $rrule['INTERVAL'] = isset($recurrence->interval) ? $recurrence->interval : 1;

        if (isset($recurrence->until)) {
            if ($timezone) {
                $recurrence->until->setTimezone($timezone);
            }
            $rrule['UNTIL'] = $recurrence->until;
        }
        else if (!empty($recurrence->occurrences)) {
            $rrule['COUNT'] = $recurrence->occurrences;
        }

        // recurrence exceptions (not supported by Tasks)
        if ($data instanceof Syncroton_Model_Event) {
            $this->exceptions_to_kolab($data, $rrule, $folderid, $timezone);
        }

        return $rrule;
    }

    /**
     * Convert Kolab event recurrence exceptions into ActiveSync
     */
    protected function exceptions_from_kolab($collection, $data, $result)
    {
        if (empty($data['recurrence']['EXCEPTIONS']) && empty($data['recurrence']['EXDATE'])) {
            return null;
        }

        $ex_list = array();

        // exceptions (modified occurences)
        foreach ((array)$data['recurrence']['EXCEPTIONS'] as $exception) {
            $exception['_mailbox'] = $data['_mailbox'];
            $ex = $this->getEntry($collection, $exception, true);

            $ex['exceptionStartTime'] = clone $ex['startTime'];

            // remove fields not supported by Syncroton_Model_EventException
            unset($ex['uID']);

            // @TODO: 'thisandfuture=true' is not supported in Activesync
            // we'd need to slit the event into two separate events

            $ex_list[] = new Syncroton_Model_EventException($ex);
        }

        // exdate (deleted occurences)
        foreach ((array)$data['recurrence']['EXDATE'] as $exception) {
            if (!($exception instanceof DateTime)) {
                continue;
            }

            // set event start time to exception date
            // that can't be any time, tested with Android
            $hour   = $data['_start']->format('H');
            $minute = $data['_start']->format('i');
            $second = $data['_start']->format('s');
            $exception->setTime($hour, $minute, $second);
            $exception->_dateonly = false;

            $ex = array(
                'deleted'            => 1,
                'exceptionStartTime' => self::date_from_kolab($exception),
            );

            $ex_list[] = new Syncroton_Model_EventException($ex);
        }

        return $ex_list;
    }

    /**
     * Convert ActiveSync event recurrence exceptions into Kolab
     */
    protected function exceptions_to_kolab($data, &$rrule, $folderid, $timezone = null)
    {
        $rrule['EXDATE']     = array();
        $rrule['EXCEPTIONS'] = array();

        // handle exceptions from recurrence
        if (!empty($data->exceptions)) {
            foreach ($data->exceptions as $exception) {
                if ($exception->deleted) {
                    $date = clone $exception->exceptionStartTime;
                    if ($timezone) {
                        $date->setTimezone($timezone);
                    }
                    $date->setTime(0, 0, 0);
                    $rrule['EXDATE'][] = $date;
                }
                else if (!$exception->deleted) {
                    $ex = $this->toKolab($exception, $folderid, null, $timezone);

                    if ($data->allDayEvent) {
                        $ex['allday'] = 1;
                    }

                    $rrule['EXCEPTIONS'][] = $ex;
                }
            }
        }
    }

    /**
     * Returns list of tag names assigned to kolab object
     */
    protected function getKolabTags($uid, $categories = null)
    {
        $config = kolab_storage_config::get_instance();
        $tags   = $config->get_tags($uid);
        $tags   = array_filter(array_map(function($v) { return $v['name']; }, $tags));

        // merge result with old categories
        if (!empty($categories)) {
            $tags = array_unique(array_merge($tags, (array) $categories));
        }

        return $tags;
    }

    /**
     * Set tags to kolab object
     */
    protected function setKolabTags($uid, $tags)
    {
        if (isset($data->categories)) {
            $config = kolab_storage_config::get_instance();
            $config->save_tags($uid, $tags);
        }
    }

    /**
     * Converts string of days (TU,TH) to bitmask used by ActiveSync
     *
     * @param string $days
     *
     * @return int
     */
    protected function day2bitmask($days)
    {
        $days   = explode(',', $days);
        $result = 0;

        foreach ($days as $day) {
            $result = $result + $this->recurDayMap[$day];
        }

        return $result;
    }

    /**
     * Convert bitmask used by ActiveSync to string of days (TU,TH)
     *
     * @param int $days
     *
     * @return string
     */
    protected function bitmask2day($days)
    {
        $days_arr = array();

        for ($bitmask = 1; $bitmask <= self::RECUR_DOW_SATURDAY; $bitmask = $bitmask << 1) {
            $dayMatch = $days & $bitmask;
            if ($dayMatch === $bitmask) {
                $days_arr[] = array_search($bitmask, $this->recurDayMap);
            }
        }
        $result = implode(',', $days_arr);

        return $result;
    }
}