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
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
|
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
* @copyright Copyright (c) 2018 Georg Ehrke
* @copyright Copyright (c) 2020, leith abdulla (<online-nextcloud@eleith.com>)
*
* @author Chih-Hsuan Yen <yan12125@gmail.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author dartcafe <github@dartcafe.de>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author leith abdulla <online-nextcloud@eleith.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Simon Spannagel <simonspa@kth.se>
* @author Stefan Weil <sw@weilnetz.de>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vinicius Cubas Brand <vinicius@eita.org.br>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\DAV\CalDAV;
use DateTime;
use DateTimeInterface;
use OCA\DAV\AppInfo\Application;
use OCA\DAV\Connector\Sabre\Principal;
use OCA\DAV\DAV\Sharing\Backend;
use OCA\DAV\DAV\Sharing\IShareable;
use OCA\DAV\Events\CachedCalendarObjectCreatedEvent;
use OCA\DAV\Events\CachedCalendarObjectDeletedEvent;
use OCA\DAV\Events\CachedCalendarObjectUpdatedEvent;
use OCA\DAV\Events\CalendarCreatedEvent;
use OCA\DAV\Events\CalendarDeletedEvent;
use OCA\DAV\Events\CalendarMovedToTrashEvent;
use OCA\DAV\Events\CalendarObjectCreatedEvent;
use OCA\DAV\Events\CalendarObjectDeletedEvent;
use OCA\DAV\Events\CalendarObjectMovedEvent;
use OCA\DAV\Events\CalendarObjectMovedToTrashEvent;
use OCA\DAV\Events\CalendarObjectRestoredEvent;
use OCA\DAV\Events\CalendarObjectUpdatedEvent;
use OCA\DAV\Events\CalendarPublishedEvent;
use OCA\DAV\Events\CalendarRestoredEvent;
use OCA\DAV\Events\CalendarShareUpdatedEvent;
use OCA\DAV\Events\CalendarUnpublishedEvent;
use OCA\DAV\Events\CalendarUpdatedEvent;
use OCA\DAV\Events\SubscriptionCreatedEvent;
use OCA\DAV\Events\SubscriptionDeletedEvent;
use OCA\DAV\Events\SubscriptionUpdatedEvent;
use OCP\AppFramework\Db\TTransactional;
use OCP\Calendar\Exceptions\CalendarException;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Security\ISecureRandom;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Sabre\CalDAV\Backend\AbstractBackend;
use Sabre\CalDAV\Backend\SchedulingSupport;
use Sabre\CalDAV\Backend\SubscriptionSupport;
use Sabre\CalDAV\Backend\SyncSupport;
use Sabre\CalDAV\Xml\Property\ScheduleCalendarTransp;
use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet;
use Sabre\DAV;
use Sabre\DAV\Exception\BadRequest;
use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\PropPatch;
use Sabre\Uri;
use Sabre\VObject\Component;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VTimeZone;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\ParseException;
use Sabre\VObject\Property;
use Sabre\VObject\Reader;
use Sabre\VObject\Recur\EventIterator;
use function array_column;
use function array_merge;
use function array_values;
use function explode;
use function is_array;
use function is_resource;
use function pathinfo;
use function rewind;
use function settype;
use function sprintf;
use function str_replace;
use function strtolower;
use function time;
/**
* Class CalDavBackend
*
* Code is heavily inspired by https://github.com/fruux/sabre-dav/blob/master/lib/CalDAV/Backend/PDO.php
*
* @package OCA\DAV\CalDAV
*/
class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
use TTransactional;
public const CALENDAR_TYPE_CALENDAR = 0;
public const CALENDAR_TYPE_SUBSCRIPTION = 1;
public const PERSONAL_CALENDAR_URI = 'personal';
public const PERSONAL_CALENDAR_NAME = 'Personal';
public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
/**
* We need to specify a max date, because we need to stop *somewhere*
*
* On 32 bit system the maximum for a signed integer is 2147483647, so
* MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
* in 2038-01-19 to avoid problems when the date is converted
* to a unix timestamp.
*/
public const MAX_DATE = '2038-01-01';
public const ACCESS_PUBLIC = 4;
public const CLASSIFICATION_PUBLIC = 0;
public const CLASSIFICATION_PRIVATE = 1;
public const CLASSIFICATION_CONFIDENTIAL = 2;
/**
* List of CalDAV properties, and how they map to database field names and their type
* Add your own properties by simply adding on to this array.
*
* @var array
* @psalm-var array<string, string[]>
*/
public array $propertyMap = [
'{DAV:}displayname' => ['displayname', 'string'],
'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
];
/**
* List of subscription properties, and how they map to database field names.
*
* @var array
*/
public array $subscriptionPropertyMap = [
'{DAV:}displayname' => ['displayname', 'string'],
'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
];
/**
* properties to index
*
* This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
*
* @see \OCP\Calendar\ICalendarQuery
*/
private const INDEXED_PROPERTIES = [
'CATEGORIES',
'COMMENT',
'DESCRIPTION',
'LOCATION',
'RESOURCES',
'STATUS',
'SUMMARY',
'ATTENDEE',
'CONTACT',
'ORGANIZER'
];
/** @var array parameters to index */
public static array $indexParameters = [
'ATTENDEE' => ['CN'],
'ORGANIZER' => ['CN'],
];
/**
* @var string[] Map of uid => display name
*/
protected array $userDisplayNames;
private IDBConnection $db;
private Backend $calendarSharingBackend;
private Principal $principalBackend;
private IUserManager $userManager;
private ISecureRandom $random;
private LoggerInterface $logger;
private IEventDispatcher $dispatcher;
private IConfig $config;
private bool $legacyEndpoint;
private string $dbObjectPropertiesTable = 'calendarobjects_props';
public function __construct(IDBConnection $db,
Principal $principalBackend,
IUserManager $userManager,
IGroupManager $groupManager,
ISecureRandom $random,
LoggerInterface $logger,
IEventDispatcher $dispatcher,
IConfig $config,
bool $legacyEndpoint = false) {
$this->db = $db;
$this->principalBackend = $principalBackend;
$this->userManager = $userManager;
$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
$this->random = $random;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
$this->config = $config;
$this->legacyEndpoint = $legacyEndpoint;
}
/**
* Return the number of calendars for a principal
*
* By default this excludes the automatically generated birthday calendar
*
* @param $principalUri
* @param bool $excludeBirthday
* @return int
*/
public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
$principalUri = $this->convertPrincipal($principalUri, true);
$query = $this->db->getQueryBuilder();
$query->select($query->func()->count('*'))
->from('calendars');
if ($principalUri === '') {
$query->where($query->expr()->emptyString('principaluri'));
} else {
$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
}
if ($excludeBirthday) {
$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
}
$result = $query->executeQuery();
$column = (int)$result->fetchOne();
$result->closeCursor();
return $column;
}
/**
* @return array{id: int, deleted_at: int}[]
*/
public function getDeletedCalendars(int $deletedBefore): array {
$qb = $this->db->getQueryBuilder();
$qb->select(['id', 'deleted_at'])
->from('calendars')
->where($qb->expr()->isNotNull('deleted_at'))
->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
$result = $qb->executeQuery();
$raw = $result->fetchAll();
$result->closeCursor();
return array_map(function ($row) {
return [
'id' => (int) $row['id'],
'deleted_at' => (int) $row['deleted_at'],
];
}, $raw);
}
/**
* Returns a list of calendars for a principal.
*
* Every project is an array with the following keys:
* * id, a unique id that will be used by other functions to modify the
* calendar. This can be the same as the uri or a database key.
* * uri, which the basename of the uri with which the calendar is
* accessed.
* * principaluri. The owner of the calendar. Almost always the same as
* principalUri passed to this method.
*
* Furthermore it can contain webdav properties in clark notation. A very
* common one is '{DAV:}displayname'.
*
* Many clients also require:
* {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
* For this property, you can just return an instance of
* Sabre\CalDAV\Property\SupportedCalendarComponentSet.
*
* If you return {http://sabredav.org/ns}read-only and set the value to 1,
* ACL will automatically be put in read-only mode.
*
* @param string $principalUri
* @return array
*/
public function getCalendarsForUser($principalUri) {
$principalUriOriginal = $principalUri;
$principalUri = $this->convertPrincipal($principalUri, true);
$fields = array_column($this->propertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'synctoken';
$fields[] = 'components';
$fields[] = 'principaluri';
$fields[] = 'transparent';
// Making fields a comma-delimited list
$query = $this->db->getQueryBuilder();
$query->select($fields)
->from('calendars')
->orderBy('calendarorder', 'ASC');
if ($principalUri === '') {
$query->where($query->expr()->emptyString('principaluri'));
} else {
$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
}
$result = $query->executeQuery();
$calendars = [];
while ($row = $result->fetch()) {
$row['principaluri'] = (string) $row['principaluri'];
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
if (!isset($calendars[$calendar['id']])) {
$calendars[$calendar['id']] = $calendar;
}
}
$result->closeCursor();
// query for shared calendars
$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
$principals[] = $principalUri;
$fields = array_column($this->propertyMap, 0);
$fields[] = 'a.id';
$fields[] = 'a.uri';
$fields[] = 'a.synctoken';
$fields[] = 'a.components';
$fields[] = 'a.principaluri';
$fields[] = 'a.transparent';
$fields[] = 's.access';
$query = $this->db->getQueryBuilder();
$query->select($fields)
->from('dav_shares', 's')
->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
->setParameter('type', 'calendar')
->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
$result = $query->executeQuery();
$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
while ($row = $result->fetch()) {
$row['principaluri'] = (string) $row['principaluri'];
if ($row['principaluri'] === $principalUri) {
continue;
}
$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
if (isset($calendars[$row['id']])) {
if ($readOnly) {
// New share can not have more permissions then the old one.
continue;
}
if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
$calendars[$row['id']][$readOnlyPropertyName] === 0) {
// Old share is already read-write, no more permissions can be gained
continue;
}
}
[, $name] = Uri\split($row['principaluri']);
$uri = $row['uri'] . '_shared_by_' . $name;
$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $uri,
'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
$readOnlyPropertyName => $readOnly,
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
$calendars[$calendar['id']] = $calendar;
}
$result->closeCursor();
return array_values($calendars);
}
/**
* @param $principalUri
* @return array
*/
public function getUsersOwnCalendars($principalUri) {
$principalUri = $this->convertPrincipal($principalUri, true);
$fields = array_column($this->propertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'synctoken';
$fields[] = 'components';
$fields[] = 'principaluri';
$fields[] = 'transparent';
// Making fields a comma-delimited list
$query = $this->db->getQueryBuilder();
$query->select($fields)->from('calendars')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->orderBy('calendarorder', 'ASC');
$stmt = $query->executeQuery();
$calendars = [];
while ($row = $stmt->fetch()) {
$row['principaluri'] = (string) $row['principaluri'];
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
if (!isset($calendars[$calendar['id']])) {
$calendars[$calendar['id']] = $calendar;
}
}
$stmt->closeCursor();
return array_values($calendars);
}
/**
* @return array
*/
public function getPublicCalendars() {
$fields = array_column($this->propertyMap, 0);
$fields[] = 'a.id';
$fields[] = 'a.uri';
$fields[] = 'a.synctoken';
$fields[] = 'a.components';
$fields[] = 'a.principaluri';
$fields[] = 'a.transparent';
$fields[] = 's.access';
$fields[] = 's.publicuri';
$calendars = [];
$query = $this->db->getQueryBuilder();
$result = $query->select($fields)
->from('dav_shares', 's')
->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
->executeQuery();
while ($row = $result->fetch()) {
$row['principaluri'] = (string) $row['principaluri'];
[, $name] = Uri\split($row['principaluri']);
$row['displayname'] = $row['displayname'] . "($name)";
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['publicuri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
if (!isset($calendars[$calendar['id']])) {
$calendars[$calendar['id']] = $calendar;
}
}
$result->closeCursor();
return array_values($calendars);
}
/**
* @param string $uri
* @return array
* @throws NotFound
*/
public function getPublicCalendar($uri) {
$fields = array_column($this->propertyMap, 0);
$fields[] = 'a.id';
$fields[] = 'a.uri';
$fields[] = 'a.synctoken';
$fields[] = 'a.components';
$fields[] = 'a.principaluri';
$fields[] = 'a.transparent';
$fields[] = 's.access';
$fields[] = 's.publicuri';
$query = $this->db->getQueryBuilder();
$result = $query->select($fields)
->from('dav_shares', 's')
->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
->executeQuery();
$row = $result->fetch();
$result->closeCursor();
if ($row === false) {
throw new NotFound('Node with name \'' . $uri . '\' could not be found');
}
$row['principaluri'] = (string) $row['principaluri'];
[, $name] = Uri\split($row['principaluri']);
$row['displayname'] = $row['displayname'] . ' ' . "($name)";
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['publicuri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
return $calendar;
}
/**
* @param string $principal
* @param string $uri
* @return array|null
*/
public function getCalendarByUri($principal, $uri) {
$fields = array_column($this->propertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'synctoken';
$fields[] = 'components';
$fields[] = 'principaluri';
$fields[] = 'transparent';
// Making fields a comma-delimited list
$query = $this->db->getQueryBuilder();
$query->select($fields)->from('calendars')
->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
->setMaxResults(1);
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if ($row === false) {
return null;
}
$row['principaluri'] = (string) $row['principaluri'];
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
return $calendar;
}
/**
* @return array{id: int, uri: string, '{http://calendarserver.org/ns/}getctag': string, '{http://sabredav.org/ns}sync-token': int, '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set': SupportedCalendarComponentSet, '{urn:ietf:params:xml:ns:caldav}schedule-calendar-transp': ScheduleCalendarTransp }|null
*/
public function getCalendarById(int $calendarId): ?array {
$fields = array_column($this->propertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'synctoken';
$fields[] = 'components';
$fields[] = 'principaluri';
$fields[] = 'transparent';
// Making fields a comma-delimited list
$query = $this->db->getQueryBuilder();
$query->select($fields)->from('calendars')
->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
->setMaxResults(1);
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if ($row === false) {
return null;
}
$row['principaluri'] = (string) $row['principaluri'];
$components = [];
if ($row['components']) {
$components = explode(',',$row['components']);
}
$calendar = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
];
$calendar = $this->rowToCalendar($row, $calendar);
$calendar = $this->addOwnerPrincipalToCalendar($calendar);
$calendar = $this->addResourceTypeToCalendar($row, $calendar);
return $calendar;
}
/**
* @param $subscriptionId
*/
public function getSubscriptionById($subscriptionId) {
$fields = array_column($this->subscriptionPropertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'source';
$fields[] = 'synctoken';
$fields[] = 'principaluri';
$fields[] = 'lastmodified';
$query = $this->db->getQueryBuilder();
$query->select($fields)
->from('calendarsubscriptions')
->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
->orderBy('calendarorder', 'asc');
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if ($row === false) {
return null;
}
$row['principaluri'] = (string) $row['principaluri'];
$subscription = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $row['principaluri'],
'source' => $row['source'],
'lastmodified' => $row['lastmodified'],
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
];
return $this->rowToSubscription($row, $subscription);
}
/**
* Creates a new calendar for a principal.
*
* If the creation was a success, an id must be returned that can be used to reference
* this calendar in other methods, such as updateCalendar.
*
* @param string $principalUri
* @param string $calendarUri
* @param array $properties
* @return int
*
* @throws CalendarException
*/
public function createCalendar($principalUri, $calendarUri, array $properties) {
if (strlen($calendarUri) > 255) {
throw new CalendarException('URI too long. Calendar not created');
}
$values = [
'principaluri' => $this->convertPrincipal($principalUri, true),
'uri' => $calendarUri,
'synctoken' => 1,
'transparent' => 0,
'components' => 'VEVENT,VTODO',
'displayname' => $calendarUri
];
// Default value
$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
if (isset($properties[$sccs])) {
if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
}
$values['components'] = implode(',',$properties[$sccs]->getValue());
} elseif (isset($properties['components'])) {
// Allow to provide components internally without having
// to create a SupportedCalendarComponentSet object
$values['components'] = $properties['components'];
}
$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
if (isset($properties[$transp])) {
$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
}
foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
if (isset($properties[$xmlName])) {
$values[$dbName] = $properties[$xmlName];
}
}
[$calendarId, $calendarData] = $this->atomic(function() use ($values) {
$query = $this->db->getQueryBuilder();
$query->insert('calendars');
foreach ($values as $column => $value) {
$query->setValue($column, $query->createNamedParameter($value));
}
$query->executeStatement();
$calendarId = $query->getLastInsertId();
$calendarData = $this->getCalendarById($calendarId);
return [$calendarId, $calendarData];
}, $this->db);
$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
return $calendarId;
}
/**
* Updates properties for a calendar.
*
* The list of mutations is stored in a Sabre\DAV\PropPatch object.
* To do the actual updates, you must tell this object which properties
* you're going to process with the handle() method.
*
* Calling the handle method is like telling the PropPatch object "I
* promise I can handle updating this property".
*
* Read the PropPatch documentation for more info and examples.
*
* @param mixed $calendarId
* @param PropPatch $propPatch
* @return void
*/
public function updateCalendar($calendarId, PropPatch $propPatch) {
$supportedProperties = array_keys($this->propertyMap);
$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
$newValues = [];
foreach ($mutations as $propertyName => $propertyValue) {
switch ($propertyName) {
case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
$fieldName = 'transparent';
$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
break;
default:
$fieldName = $this->propertyMap[$propertyName][0];
$newValues[$fieldName] = $propertyValue;
break;
}
}
$query = $this->db->getQueryBuilder();
$query->update('calendars');
foreach ($newValues as $fieldName => $value) {
$query->set($fieldName, $query->createNamedParameter($value));
}
$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
$query->executeStatement();
$this->addChange($calendarId, "", 2);
$calendarData = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
return true;
});
}
/**
* Delete a calendar and all it's objects
*
* @param mixed $calendarId
* @return void
*/
public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
// The calendar is deleted right away if this is either enforced by the caller
// or the special contacts birthday calendar or when the preference of an empty
// retention (0 seconds) is set, which signals a disabled trashbin.
$calendarData = $this->getCalendarById($calendarId);
$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
$calendarData = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
->executeStatement();
$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
$qbDeleteCalendarObjects->delete('calendarobjects')
->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
->executeStatement();
$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
$qbDeleteCalendarObjects->delete('calendarchanges')
->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
->executeStatement();
$this->calendarSharingBackend->deleteAllShares($calendarId);
$qbDeleteCalendar = $this->db->getQueryBuilder();
$qbDeleteCalendarObjects->delete('calendars')
->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
->executeStatement();
// Only dispatch if we actually deleted anything
if ($calendarData) {
$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
}
} else {
$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
$qbMarkCalendarDeleted->update('calendars')
->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
->executeStatement();
$calendarData = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
if ($calendarData) {
$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
$calendarId,
$calendarData,
$shares
));
}
}
}
public function restoreCalendar(int $id): void {
$qb = $this->db->getQueryBuilder();
$update = $qb->update('calendars')
->set('deleted_at', $qb->createNamedParameter(null))
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
$update->executeStatement();
$calendarData = $this->getCalendarById($id);
$shares = $this->getShares($id);
if ($calendarData === null) {
throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
}
$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
$id,
$calendarData,
$shares
));
}
/**
* Delete all of an user's shares
*
* @param string $principaluri
* @return void
*/
public function deleteAllSharesByUser($principaluri) {
$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
}
/**
* Returns all calendar objects within a calendar.
*
* Every item contains an array with the following keys:
* * calendardata - The iCalendar-compatible calendar data
* * uri - a unique key which will be used to construct the uri. This can
* be any arbitrary string, but making sure it ends with '.ics' is a
* good idea. This is only the basename, or filename, not the full
* path.
* * lastmodified - a timestamp of the last modification time
* * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
* '"abcdef"')
* * size - The size of the calendar objects, in bytes.
* * component - optional, a string containing the type of object, such
* as 'vevent' or 'vtodo'. If specified, this will be used to populate
* the Content-Type header.
*
* Note that the etag is optional, but it's highly encouraged to return for
* speed reasons.
*
* The calendardata is also optional. If it's not returned
* 'getCalendarObject' will be called later, which *is* expected to return
* calendardata.
*
* If neither etag or size are specified, the calendardata will be
* used/fetched to determine these numbers. If both are specified the
* amount of times this is needed is reduced by a great degree.
*
* @param mixed $calendarId
* @param int $calendarType
* @return array
*/
public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
$query = $this->db->getQueryBuilder();
$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
->from('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
->andWhere($query->expr()->isNull('deleted_at'));
$stmt = $query->executeQuery();
$result = [];
foreach ($stmt->fetchAll() as $row) {
$result[] = [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => $row['calendarid'],
'size' => (int)$row['size'],
'component' => strtolower($row['componenttype']),
'classification' => (int)$row['classification']
];
}
$stmt->closeCursor();
return $result;
}
public function getDeletedCalendarObjects(int $deletedBefore): array {
$query = $this->db->getQueryBuilder();
$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
->from('calendarobjects', 'co')
->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
->where($query->expr()->isNotNull('co.deleted_at'))
->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
$stmt = $query->executeQuery();
$result = [];
foreach ($stmt->fetchAll() as $row) {
$result[] = [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => (int) $row['calendarid'],
'calendartype' => (int) $row['calendartype'],
'size' => (int) $row['size'],
'component' => strtolower($row['componenttype']),
'classification' => (int) $row['classification'],
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
];
}
$stmt->closeCursor();
return $result;
}
/**
* Return all deleted calendar objects by the given principal that are not
* in deleted calendars.
*
* @param string $principalUri
* @return array
* @throws Exception
*/
public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
$query = $this->db->getQueryBuilder();
$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
->selectAlias('c.uri', 'calendaruri')
->from('calendarobjects', 'co')
->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->andWhere($query->expr()->isNotNull('co.deleted_at'))
->andWhere($query->expr()->isNull('c.deleted_at'));
$stmt = $query->executeQuery();
$result = [];
while ($row = $stmt->fetch()) {
$result[] = [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => $row['calendarid'],
'calendaruri' => $row['calendaruri'],
'size' => (int)$row['size'],
'component' => strtolower($row['componenttype']),
'classification' => (int)$row['classification'],
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
];
}
$stmt->closeCursor();
return $result;
}
/**
* Returns information from a single calendar object, based on it's object
* uri.
*
* The object uri is only the basename, or filename and not a full path.
*
* The returned array must have the same keys as getCalendarObjects. The
* 'calendardata' object is required here though, while it's not required
* for getCalendarObjects.
*
* This method must return null if the object did not exist.
*
* @param mixed $calendarId
* @param string $objectUri
* @param int $calendarType
* @return array|null
*/
public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
$query = $this->db->getQueryBuilder();
$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
->from('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if (!$row) {
return null;
}
return [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => $row['calendarid'],
'size' => (int)$row['size'],
'calendardata' => $this->readBlob($row['calendardata']),
'component' => strtolower($row['componenttype']),
'classification' => (int)$row['classification'],
'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
];
}
/**
* Returns a list of calendar objects.
*
* This method should work identical to getCalendarObject, but instead
* return all the calendar objects in the list as an array.
*
* If the backend supports this, it may allow for some speed-ups.
*
* @param mixed $calendarId
* @param string[] $uris
* @param int $calendarType
* @return array
*/
public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
if (empty($uris)) {
return [];
}
$chunks = array_chunk($uris, 100);
$objects = [];
$query = $this->db->getQueryBuilder();
$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
->from('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
->andWhere($query->expr()->isNull('deleted_at'));
foreach ($chunks as $uris) {
$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
$result = $query->executeQuery();
while ($row = $result->fetch()) {
$objects[] = [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => $row['calendarid'],
'size' => (int)$row['size'],
'calendardata' => $this->readBlob($row['calendardata']),
'component' => strtolower($row['componenttype']),
'classification' => (int)$row['classification']
];
}
$result->closeCursor();
}
return $objects;
}
/**
* Creates a new calendar object.
*
* The object uri is only the basename, or filename and not a full path.
*
* It is possible return an etag from this function, which will be used in
* the response to this PUT request. Note that the ETag must be surrounded
* by double-quotes.
*
* However, you should only really return this ETag if you don't mangle the
* calendar-data. If the result of a subsequent GET to this object is not
* the exact same as this request body, you should omit the ETag.
*
* @param mixed $calendarId
* @param string $objectUri
* @param string $calendarData
* @param int $calendarType
* @return string
*/
public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
$extraData = $this->getDenormalizedData($calendarData);
// Try to detect duplicates
$qb = $this->db->getQueryBuilder();
$qb->select($qb->func()->count('*'))
->from('calendarobjects')
->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
->andWhere($qb->expr()->isNull('deleted_at'));
$result = $qb->executeQuery();
$count = (int) $result->fetchOne();
$result->closeCursor();
if ($count !== 0) {
throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
}
// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
$qbDel = $this->db->getQueryBuilder();
$qbDel->select($qb->func()->count('*'))
->from('calendarobjects')
->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
->andWhere($qbDel->expr()->isNotNull('deleted_at'));
$result = $qbDel->executeQuery();
$count = (int) $result->fetchOne();
$result->closeCursor();
if ($count !== 0) {
throw new BadRequest('Deleted calendar object with uid already exists in this calendar collection.');
}
$query = $this->db->getQueryBuilder();
$query->insert('calendarobjects')
->values([
'calendarid' => $query->createNamedParameter($calendarId),
'uri' => $query->createNamedParameter($objectUri),
'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
'lastmodified' => $query->createNamedParameter(time()),
'etag' => $query->createNamedParameter($extraData['etag']),
'size' => $query->createNamedParameter($extraData['size']),
'componenttype' => $query->createNamedParameter($extraData['componentType']),
'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
'classification' => $query->createNamedParameter($extraData['classification']),
'uid' => $query->createNamedParameter($extraData['uid']),
'calendartype' => $query->createNamedParameter($calendarType),
])
->executeStatement();
$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
$this->addChange($calendarId, $objectUri, 1, $calendarType);
$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
assert($objectRow !== null);
if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
$calendarRow = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
} else {
$subscriptionRow = $this->getSubscriptionById($calendarId);
$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
}
return '"' . $extraData['etag'] . '"';
}
/**
* Updates an existing calendarobject, based on it's uri.
*
* The object uri is only the basename, or filename and not a full path.
*
* It is possible return an etag from this function, which will be used in
* the response to this PUT request. Note that the ETag must be surrounded
* by double-quotes.
*
* However, you should only really return this ETag if you don't mangle the
* calendar-data. If the result of a subsequent GET to this object is not
* the exact same as this request body, you should omit the ETag.
*
* @param mixed $calendarId
* @param string $objectUri
* @param string $calendarData
* @param int $calendarType
* @return string
*/
public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
$extraData = $this->getDenormalizedData($calendarData);
$query = $this->db->getQueryBuilder();
$query->update('calendarobjects')
->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
->set('lastmodified', $query->createNamedParameter(time()))
->set('etag', $query->createNamedParameter($extraData['etag']))
->set('size', $query->createNamedParameter($extraData['size']))
->set('componenttype', $query->createNamedParameter($extraData['componentType']))
->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
->set('classification', $query->createNamedParameter($extraData['classification']))
->set('uid', $query->createNamedParameter($extraData['uid']))
->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
->executeStatement();
$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
$this->addChange($calendarId, $objectUri, 2, $calendarType);
$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
if (is_array($objectRow)) {
if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
$calendarRow = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
} else {
$subscriptionRow = $this->getSubscriptionById($calendarId);
$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
}
}
return '"' . $extraData['etag'] . '"';
}
/**
* Moves a calendar object from calendar to calendar.
*
* @param int $sourceCalendarId
* @param int $targetCalendarId
* @param int $objectId
* @param string $oldPrincipalUri
* @param string $newPrincipalUri
* @param int $calendarType
* @return bool
* @throws Exception
*/
public function moveCalendarObject(int $sourceCalendarId, int $targetCalendarId, int $objectId, string $oldPrincipalUri, string $newPrincipalUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
$object = $this->getCalendarObjectById($oldPrincipalUri, $objectId);
if (empty($object)) {
return false;
}
$query = $this->db->getQueryBuilder();
$query->update('calendarobjects')
->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('id', $query->createNamedParameter($objectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
->executeStatement();
$this->purgeProperties($sourceCalendarId, $objectId);
$this->updateProperties($targetCalendarId, $object['uri'], $object['calendardata'], $calendarType);
$this->addChange($sourceCalendarId, $object['uri'], 1, $calendarType);
$this->addChange($targetCalendarId, $object['uri'], 3, $calendarType);
$object = $this->getCalendarObjectById($newPrincipalUri, $objectId);
// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
if (empty($object)) {
return false;
}
$targetCalendarRow = $this->getCalendarById($targetCalendarId);
// the calendar this event is being moved to does not exist any longer
if (empty($targetCalendarRow)) {
return false;
}
if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
$sourceShares = $this->getShares($sourceCalendarId);
$targetShares = $this->getShares($targetCalendarId);
$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
}
return true;
}
/**
* @param int $calendarObjectId
* @param int $classification
*/
public function setClassification($calendarObjectId, $classification) {
if (!in_array($classification, [
self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
])) {
throw new \InvalidArgumentException();
}
$query = $this->db->getQueryBuilder();
$query->update('calendarobjects')
->set('classification', $query->createNamedParameter($classification))
->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
->executeStatement();
}
/**
* Deletes an existing calendar object.
*
* The object uri is only the basename, or filename and not a full path.
*
* @param mixed $calendarId
* @param string $objectUri
* @param int $calendarType
* @param bool $forceDeletePermanently
* @return void
*/
public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
if ($data === null) {
// Nothing to delete
return;
}
if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
$stmt->execute([$calendarId, $objectUri, $calendarType]);
$this->purgeProperties($calendarId, $data['id']);
if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
$calendarRow = $this->getCalendarById($calendarId);
$shares = $this->getShares($calendarId);
$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
} else {
$subscriptionRow = $this->getSubscriptionById($calendarId);
$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
}
} else {
$pathInfo = pathinfo($data['uri']);
if (!empty($pathInfo['extension'])) {
// Append a suffix to "free" the old URI for recreation
$newUri = sprintf(
"%s-deleted.%s",
$pathInfo['filename'],
$pathInfo['extension']
);
} else {
$newUri = sprintf(
"%s-deleted",
$pathInfo['filename']
);
}
// Try to detect conflicts before the DB does
// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
if ($newObject !== null) {
throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
}
$qb = $this->db->getQueryBuilder();
$markObjectDeletedQuery = $qb->update('calendarobjects')
->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
->set('uri', $qb->createNamedParameter($newUri))
->where(
$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
);
$markObjectDeletedQuery->executeStatement();
$calendarData = $this->getCalendarById($calendarId);
if ($calendarData !== null) {
$this->dispatcher->dispatchTyped(
new CalendarObjectMovedToTrashEvent(
$calendarId,
$calendarData,
$this->getShares($calendarId),
$data
)
);
}
}
$this->addChange($calendarId, $objectUri, 3, $calendarType);
}
/**
* @param mixed $objectData
*
* @throws Forbidden
*/
public function restoreCalendarObject(array $objectData): void {
$id = (int) $objectData['id'];
$restoreUri = str_replace("-deleted.ics", ".ics", $objectData['uri']);
$targetObject = $this->getCalendarObject(
$objectData['calendarid'],
$restoreUri
);
if ($targetObject !== null) {
throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
}
$qb = $this->db->getQueryBuilder();
$update = $qb->update('calendarobjects')
->set('uri', $qb->createNamedParameter($restoreUri))
->set('deleted_at', $qb->createNamedParameter(null))
->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
$update->executeStatement();
// Make sure this change is tracked in the changes table
$qb2 = $this->db->getQueryBuilder();
$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
->selectAlias('componenttype', 'component')
->from('calendarobjects')
->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
$result = $selectObject->executeQuery();
$row = $result->fetch();
$result->closeCursor();
if ($row === false) {
// Welp, this should possibly not have happened, but let's ignore
return;
}
$this->addChange($row['calendarid'], $row['uri'], 1, (int) $row['calendartype']);
$calendarRow = $this->getCalendarById((int) $row['calendarid']);
if ($calendarRow === null) {
throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
}
$this->dispatcher->dispatchTyped(
new CalendarObjectRestoredEvent(
(int) $objectData['calendarid'],
$calendarRow,
$this->getShares((int) $row['calendarid']),
$row
)
);
}
/**
* Performs a calendar-query on the contents of this calendar.
*
* The calendar-query is defined in RFC4791 : CalDAV. Using the
* calendar-query it is possible for a client to request a specific set of
* object, based on contents of iCalendar properties, date-ranges and
* iCalendar component types (VTODO, VEVENT).
*
* This method should just return a list of (relative) urls that match this
* query.
*
* The list of filters are specified as an array. The exact array is
* documented by Sabre\CalDAV\CalendarQueryParser.
*
* Note that it is extremely likely that getCalendarObject for every path
* returned from this method will be called almost immediately after. You
* may want to anticipate this to speed up these requests.
*
* This method provides a default implementation, which parses *all* the
* iCalendar objects in the specified calendar.
*
* This default may well be good enough for personal use, and calendars
* that aren't very large. But if you anticipate high usage, big calendars
* or high loads, you are strongly advised to optimize certain paths.
*
* The best way to do so is override this method and to optimize
* specifically for 'common filters'.
*
* Requests that are extremely common are:
* * requests for just VEVENTS
* * requests for just VTODO
* * requests with a time-range-filter on either VEVENT or VTODO.
*
* ..and combinations of these requests. It may not be worth it to try to
* handle every possible situation and just rely on the (relatively
* easy to use) CalendarQueryValidator to handle the rest.
*
* Note that especially time-range-filters may be difficult to parse. A
* time-range filter specified on a VEVENT must for instance also handle
* recurrence rules correctly.
* A good example of how to interpret all these filters can also simply
* be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
* as possible, so it gives you a good idea on what type of stuff you need
* to think of.
*
* @param mixed $calendarId
* @param array $filters
* @param int $calendarType
* @return array
*/
public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
$componentType = null;
$requirePostFilter = true;
$timeRange = null;
// if no filters were specified, we don't need to filter after a query
if (!$filters['prop-filters'] && !$filters['comp-filters']) {
$requirePostFilter = false;
}
// Figuring out if there's a component filter
if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
$componentType = $filters['comp-filters'][0]['name'];
// Checking if we need post-filters
if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
$requirePostFilter = false;
}
// There was a time-range filter
if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
$timeRange = $filters['comp-filters'][0]['time-range'];
// If start time OR the end time is not specified, we can do a
// 100% accurate mysql query.
if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
$requirePostFilter = false;
}
}
}
$columns = ['uri'];
if ($requirePostFilter) {
$columns = ['uri', 'calendardata'];
}
$query = $this->db->getQueryBuilder();
$query->select($columns)
->from('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
->andWhere($query->expr()->isNull('deleted_at'));
if ($componentType) {
$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
}
if ($timeRange && $timeRange['start']) {
$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
}
if ($timeRange && $timeRange['end']) {
$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
}
$stmt = $query->executeQuery();
$result = [];
while ($row = $stmt->fetch()) {
if ($requirePostFilter) {
// validateFilterForObject will parse the calendar data
// catch parsing errors
try {
$matches = $this->validateFilterForObject($row, $filters);
} catch (ParseException $ex) {
$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
'app' => 'dav',
'exception' => $ex,
]);
continue;
} catch (InvalidDataException $ex) {
$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
'app' => 'dav',
'exception' => $ex,
]);
continue;
}
if (!$matches) {
continue;
}
}
$result[] = $row['uri'];
}
return $result;
}
/**
* custom Nextcloud search extension for CalDAV
*
* TODO - this should optionally cover cached calendar objects as well
*
* @param string $principalUri
* @param array $filters
* @param integer|null $limit
* @param integer|null $offset
* @return array
*/
public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
$calendars = $this->getCalendarsForUser($principalUri);
$ownCalendars = [];
$sharedCalendars = [];
$uriMapper = [];
foreach ($calendars as $calendar) {
if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
$ownCalendars[] = $calendar['id'];
} else {
$sharedCalendars[] = $calendar['id'];
}
$uriMapper[$calendar['id']] = $calendar['uri'];
}
if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
return [];
}
$query = $this->db->getQueryBuilder();
// Calendar id expressions
$calendarExpressions = [];
foreach ($ownCalendars as $id) {
$calendarExpressions[] = $query->expr()->andX(
$query->expr()->eq('c.calendarid',
$query->createNamedParameter($id)),
$query->expr()->eq('c.calendartype',
$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
}
foreach ($sharedCalendars as $id) {
$calendarExpressions[] = $query->expr()->andX(
$query->expr()->eq('c.calendarid',
$query->createNamedParameter($id)),
$query->expr()->eq('c.classification',
$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
$query->expr()->eq('c.calendartype',
$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
}
if (count($calendarExpressions) === 1) {
$calExpr = $calendarExpressions[0];
} else {
$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
}
// Component expressions
$compExpressions = [];
foreach ($filters['comps'] as $comp) {
$compExpressions[] = $query->expr()
->eq('c.componenttype', $query->createNamedParameter($comp));
}
if (count($compExpressions) === 1) {
$compExpr = $compExpressions[0];
} else {
$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
}
if (!isset($filters['props'])) {
$filters['props'] = [];
}
if (!isset($filters['params'])) {
$filters['params'] = [];
}
$propParamExpressions = [];
foreach ($filters['props'] as $prop) {
$propParamExpressions[] = $query->expr()->andX(
$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
$query->expr()->isNull('i.parameter')
);
}
foreach ($filters['params'] as $param) {
$propParamExpressions[] = $query->expr()->andX(
$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
);
}
if (count($propParamExpressions) === 1) {
$propParamExpr = $propParamExpressions[0];
} else {
$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
}
$query->select(['c.calendarid', 'c.uri'])
->from($this->dbObjectPropertiesTable, 'i')
->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
->where($calExpr)
->andWhere($compExpr)
->andWhere($propParamExpr)
->andWhere($query->expr()->iLike('i.value',
$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
->andWhere($query->expr()->isNull('deleted_at'));
if ($offset) {
$query->setFirstResult($offset);
}
if ($limit) {
$query->setMaxResults($limit);
}
$stmt = $query->executeQuery();
$result = [];
while ($row = $stmt->fetch()) {
$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
if (!in_array($path, $result)) {
$result[] = $path;
}
}
return $result;
}
/**
* used for Nextcloud's calendar API
*
* @param array $calendarInfo
* @param string $pattern
* @param array $searchProperties
* @param array $options
* @param integer|null $limit
* @param integer|null $offset
*
* @return array
*/
public function search(array $calendarInfo, $pattern, array $searchProperties,
array $options, $limit, $offset) {
$outerQuery = $this->db->getQueryBuilder();
$innerQuery = $this->db->getQueryBuilder();
$innerQuery->selectDistinct('op.objectid')
->from($this->dbObjectPropertiesTable, 'op')
->andWhere($innerQuery->expr()->eq('op.calendarid',
$outerQuery->createNamedParameter($calendarInfo['id'])))
->andWhere($innerQuery->expr()->eq('op.calendartype',
$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
// only return public items for shared calendars for now
if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
}
if (!empty($searchProperties)) {
$or = $innerQuery->expr()->orX();
foreach ($searchProperties as $searchProperty) {
$or->add($innerQuery->expr()->eq('op.name',
$outerQuery->createNamedParameter($searchProperty)));
}
$innerQuery->andWhere($or);
}
if ($pattern !== '') {
$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
$outerQuery->createNamedParameter('%' .
$this->db->escapeLikeParameter($pattern) . '%')));
}
$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
->from('calendarobjects', 'c')
->where($outerQuery->expr()->isNull('deleted_at'));
if (isset($options['timerange'])) {
if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
}
if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
}
}
if(isset($options['uid'])) {
$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
}
if (!empty($options['types'])) {
$or = $outerQuery->expr()->orX();
foreach ($options['types'] as $type) {
$or->add($outerQuery->expr()->eq('componenttype',
$outerQuery->createNamedParameter($type)));
}
$outerQuery->andWhere($or);
}
$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
if ($offset) {
$outerQuery->setFirstResult($offset);
}
if ($limit) {
$outerQuery->setMaxResults($limit);
}
$result = $outerQuery->executeQuery();
$calendarObjects = array_filter($result->fetchAll(), function (array $row) use ($options) {
$start = $options['timerange']['start'] ?? null;
$end = $options['timerange']['end'] ?? null;
if ($start === null || !($start instanceof DateTimeInterface) || $end === null || !($end instanceof DateTimeInterface)) {
// No filter required
return true;
}
$isValid = $this->validateFilterForObject($row, [
'name' => 'VCALENDAR',
'comp-filters' => [
[
'name' => 'VEVENT',
'comp-filters' => [],
'prop-filters' => [],
'is-not-defined' => false,
'time-range' => [
'start' => $start,
'end' => $end,
],
],
],
'prop-filters' => [],
'is-not-defined' => false,
'time-range' => null,
]);
if (is_resource($row['calendardata'])) {
// Put the stream back to the beginning so it can be read another time
rewind($row['calendardata']);
}
return $isValid;
});
$result->closeCursor();
return array_map(function ($o) {
$calendarData = Reader::read($o['calendardata']);
$comps = $calendarData->getComponents();
$objects = [];
$timezones = [];
foreach ($comps as $comp) {
if ($comp instanceof VTimeZone) {
$timezones[] = $comp;
} else {
$objects[] = $comp;
}
}
return [
'id' => $o['id'],
'type' => $o['componenttype'],
'uid' => $o['uid'],
'uri' => $o['uri'],
'objects' => array_map(function ($c) {
return $this->transformSearchData($c);
}, $objects),
'timezones' => array_map(function ($c) {
return $this->transformSearchData($c);
}, $timezones),
];
}, $calendarObjects);
}
/**
* @param Component $comp
* @return array
*/
private function transformSearchData(Component $comp) {
$data = [];
/** @var Component[] $subComponents */
$subComponents = $comp->getComponents();
/** @var Property[] $properties */
$properties = array_filter($comp->children(), function ($c) {
return $c instanceof Property;
});
$validationRules = $comp->getValidationRules();
foreach ($subComponents as $subComponent) {
$name = $subComponent->name;
if (!isset($data[$name])) {
$data[$name] = [];
}
$data[$name][] = $this->transformSearchData($subComponent);
}
foreach ($properties as $property) {
$name = $property->name;
if (!isset($validationRules[$name])) {
$validationRules[$name] = '*';
}
$rule = $validationRules[$property->name];
if ($rule === '+' || $rule === '*') { // multiple
if (!isset($data[$name])) {
$data[$name] = [];
}
$data[$name][] = $this->transformSearchProperty($property);
} else { // once
$data[$name] = $this->transformSearchProperty($property);
}
}
return $data;
}
/**
* @param Property $prop
* @return array
*/
private function transformSearchProperty(Property $prop) {
// No need to check Date, as it extends DateTime
if ($prop instanceof Property\ICalendar\DateTime) {
$value = $prop->getDateTime();
} else {
$value = $prop->getValue();
}
return [
$value,
$prop->parameters()
];
}
/**
* @param string $principalUri
* @param string $pattern
* @param array $componentTypes
* @param array $searchProperties
* @param array $searchParameters
* @param array $options
* @return array
*/
public function searchPrincipalUri(string $principalUri,
string $pattern,
array $componentTypes,
array $searchProperties,
array $searchParameters,
array $options = []): array {
$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
$calendarObjectIdQuery = $this->db->getQueryBuilder();
$calendarOr = $calendarObjectIdQuery->expr()->orX();
$searchOr = $calendarObjectIdQuery->expr()->orX();
// Fetch calendars and subscription
$calendars = $this->getCalendarsForUser($principalUri);
$subscriptions = $this->getSubscriptionsForUser($principalUri);
foreach ($calendars as $calendar) {
$calendarAnd = $calendarObjectIdQuery->expr()->andX();
$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
// If it's shared, limit search to public events
if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
}
$calendarOr->add($calendarAnd);
}
foreach ($subscriptions as $subscription) {
$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
// If it's shared, limit search to public events
if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
}
$calendarOr->add($subscriptionAnd);
}
foreach ($searchProperties as $property) {
$propertyAnd = $calendarObjectIdQuery->expr()->andX();
$propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
$propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
$searchOr->add($propertyAnd);
}
foreach ($searchParameters as $property => $parameter) {
$parameterAnd = $calendarObjectIdQuery->expr()->andX();
$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
$searchOr->add($parameterAnd);
}
if ($calendarOr->count() === 0) {
return [];
}
if ($searchOr->count() === 0) {
return [];
}
$calendarObjectIdQuery->selectDistinct('cob.objectid')
->from($this->dbObjectPropertiesTable, 'cob')
->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
->andWhere($calendarOr)
->andWhere($searchOr)
->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
if ('' !== $pattern) {
if (!$escapePattern) {
$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
} else {
$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
}
}
if (isset($options['limit'])) {
$calendarObjectIdQuery->setMaxResults($options['limit']);
}
if (isset($options['offset'])) {
$calendarObjectIdQuery->setFirstResult($options['offset']);
}
$result = $calendarObjectIdQuery->executeQuery();
$matches = $result->fetchAll();
$result->closeCursor();
$matches = array_map(static function (array $match):int {
return (int) $match['objectid'];
}, $matches);
$query = $this->db->getQueryBuilder();
$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
->from('calendarobjects')
->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
$result = $query->executeQuery();
$calendarObjects = $result->fetchAll();
$result->closeCursor();
return array_map(function (array $array): array {
$array['calendarid'] = (int)$array['calendarid'];
$array['calendartype'] = (int)$array['calendartype'];
$array['calendardata'] = $this->readBlob($array['calendardata']);
return $array;
}, $calendarObjects);
}
/**
* Searches through all of a users calendars and calendar objects to find
* an object with a specific UID.
*
* This method should return the path to this object, relative to the
* calendar home, so this path usually only contains two parts:
*
* calendarpath/objectpath.ics
*
* If the uid is not found, return null.
*
* This method should only consider * objects that the principal owns, so
* any calendars owned by other principals that also appear in this
* collection should be ignored.
*
* @param string $principalUri
* @param string $uid
* @return string|null
*/
public function getCalendarObjectByUID($principalUri, $uid) {
$query = $this->db->getQueryBuilder();
$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
->from('calendarobjects', 'co')
->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
->andWhere($query->expr()->isNull('co.deleted_at'));
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if ($row) {
return $row['calendaruri'] . '/' . $row['objecturi'];
}
return null;
}
public function getCalendarObjectById(string $principalUri, int $id): ?array {
$query = $this->db->getQueryBuilder();
$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
->selectAlias('c.uri', 'calendaruri')
->from('calendarobjects', 'co')
->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
$stmt = $query->executeQuery();
$row = $stmt->fetch();
$stmt->closeCursor();
if (!$row) {
return null;
}
return [
'id' => $row['id'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'calendarid' => $row['calendarid'],
'calendaruri' => $row['calendaruri'],
'size' => (int)$row['size'],
'calendardata' => $this->readBlob($row['calendardata']),
'component' => strtolower($row['componenttype']),
'classification' => (int)$row['classification'],
'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
];
}
/**
* The getChanges method returns all the changes that have happened, since
* the specified syncToken in the specified calendar.
*
* This function should return an array, such as the following:
*
* [
* 'syncToken' => 'The current synctoken',
* 'added' => [
* 'new.txt',
* ],
* 'modified' => [
* 'modified.txt',
* ],
* 'deleted' => [
* 'foo.php.bak',
* 'old.txt'
* ]
* );
*
* The returned syncToken property should reflect the *current* syncToken
* of the calendar, as reported in the {http://sabredav.org/ns}sync-token
* property This is * needed here too, to ensure the operation is atomic.
*
* If the $syncToken argument is specified as null, this is an initial
* sync, and all members should be reported.
*
* The modified property is an array of nodenames that have changed since
* the last token.
*
* The deleted property is an array with nodenames, that have been deleted
* from collection.
*
* The $syncLevel argument is basically the 'depth' of the report. If it's
* 1, you only have to report changes that happened only directly in
* immediate descendants. If it's 2, it should also include changes from
* the nodes below the child collections. (grandchildren)
*
* The $limit argument allows a client to specify how many results should
* be returned at most. If the limit is not specified, it should be treated
* as infinite.
*
* If the limit (infinite or not) is higher than you're willing to return,
* you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
*
* If the syncToken is expired (due to data cleanup) or unknown, you must
* return null.
*
* The limit is 'suggestive'. You are free to ignore it.
*
* @param string $calendarId
* @param string $syncToken
* @param int $syncLevel
* @param int|null $limit
* @param int $calendarType
* @return array
*/
public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
// Current synctoken
$qb = $this->db->getQueryBuilder();
$qb->select('synctoken')
->from('calendars')
->where(
$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
);
$stmt = $qb->executeQuery();
$currentToken = $stmt->fetchOne();
if ($currentToken === false) {
return null;
}
$result = [
'syncToken' => $currentToken,
'added' => [],
'modified' => [],
'deleted' => [],
];
if ($syncToken) {
$qb = $this->db->getQueryBuilder();
$qb->select('uri', 'operation')
->from('calendarchanges')
->where(
$qb->expr()->andX(
$qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
$qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
)
)->orderBy('synctoken');
if (is_int($limit) && $limit > 0) {
$qb->setMaxResults($limit);
}
// Fetching all changes
$stmt = $qb->executeQuery();
$changes = [];
// This loop ensures that any duplicates are overwritten, only the
// last change on a node is relevant.
while ($row = $stmt->fetch()) {
$changes[$row['uri']] = $row['operation'];
}
$stmt->closeCursor();
foreach ($changes as $uri => $operation) {
switch ($operation) {
case 1:
$result['added'][] = $uri;
break;
case 2:
$result['modified'][] = $uri;
break;
case 3:
$result['deleted'][] = $uri;
break;
}
}
} else {
// No synctoken supplied, this is the initial sync.
$qb = $this->db->getQueryBuilder();
$qb->select('uri')
->from('calendarobjects')
->where(
$qb->expr()->andX(
$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
)
);
$stmt = $qb->executeQuery();
$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
$stmt->closeCursor();
}
return $result;
}
/**
* Returns a list of subscriptions for a principal.
*
* Every subscription is an array with the following keys:
* * id, a unique id that will be used by other functions to modify the
* subscription. This can be the same as the uri or a database key.
* * uri. This is just the 'base uri' or 'filename' of the subscription.
* * principaluri. The owner of the subscription. Almost always the same as
* principalUri passed to this method.
*
* Furthermore, all the subscription info must be returned too:
*
* 1. {DAV:}displayname
* 2. {http://apple.com/ns/ical/}refreshrate
* 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
* should not be stripped).
* 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
* should not be stripped).
* 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
* attachments should not be stripped).
* 6. {http://calendarserver.org/ns/}source (Must be a
* Sabre\DAV\Property\Href).
* 7. {http://apple.com/ns/ical/}calendar-color
* 8. {http://apple.com/ns/ical/}calendar-order
* 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
* (should just be an instance of
* Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
* default components).
*
* @param string $principalUri
* @return array
*/
public function getSubscriptionsForUser($principalUri) {
$fields = array_column($this->subscriptionPropertyMap, 0);
$fields[] = 'id';
$fields[] = 'uri';
$fields[] = 'source';
$fields[] = 'principaluri';
$fields[] = 'lastmodified';
$fields[] = 'synctoken';
$query = $this->db->getQueryBuilder();
$query->select($fields)
->from('calendarsubscriptions')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->orderBy('calendarorder', 'asc');
$stmt = $query->executeQuery();
$subscriptions = [];
while ($row = $stmt->fetch()) {
$subscription = [
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $row['principaluri'],
'source' => $row['source'],
'lastmodified' => $row['lastmodified'],
'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
];
$subscriptions[] = $this->rowToSubscription($row, $subscription);
}
return $subscriptions;
}
/**
* Creates a new subscription for a principal.
*
* If the creation was a success, an id must be returned that can be used to reference
* this subscription in other methods, such as updateSubscription.
*
* @param string $principalUri
* @param string $uri
* @param array $properties
* @return mixed
*/
public function createSubscription($principalUri, $uri, array $properties) {
if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
}
$values = [
'principaluri' => $principalUri,
'uri' => $uri,
'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
'lastmodified' => time(),
];
$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
if (array_key_exists($xmlName, $properties)) {
$values[$dbName] = $properties[$xmlName];
if (in_array($dbName, $propertiesBoolean)) {
$values[$dbName] = true;
}
}
}
[$subscriptionId, $subscriptionRow] = $this->atomic(function() use ($values) {
$valuesToInsert = [];
$query = $this->db->getQueryBuilder();
foreach (array_keys($values) as $name) {
$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
}
$query->insert('calendarsubscriptions')
->values($valuesToInsert)
->executeStatement();
$subscriptionId = $query->getLastInsertId();
$subscriptionRow = $this->getSubscriptionById($subscriptionId);
return [$subscriptionId, $subscriptionRow];
}, $this->db);
$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
return $subscriptionId;
}
/**
* Updates a subscription
*
* The list of mutations is stored in a Sabre\DAV\PropPatch object.
* To do the actual updates, you must tell this object which properties
* you're going to process with the handle() method.
*
* Calling the handle method is like telling the PropPatch object "I
* promise I can handle updating this property".
*
* Read the PropPatch documentation for more info and examples.
*
* @param mixed $subscriptionId
* @param PropPatch $propPatch
* @return void
*/
public function updateSubscription($subscriptionId, PropPatch $propPatch) {
$supportedProperties = array_keys($this->subscriptionPropertyMap);
$supportedProperties[] = '{http://calendarserver.org/ns/}source';
$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
$newValues = [];
foreach ($mutations as $propertyName => $propertyValue) {
if ($propertyName === '{http://calendarserver.org/ns/}source') {
$newValues['source'] = $propertyValue->getHref();
} else {
$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
$newValues[$fieldName] = $propertyValue;
}
}
$query = $this->db->getQueryBuilder();
$query->update('calendarsubscriptions')
->set('lastmodified', $query->createNamedParameter(time()));
foreach ($newValues as $fieldName => $value) {
$query->set($fieldName, $query->createNamedParameter($value));
}
$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
->executeStatement();
$subscriptionRow = $this->getSubscriptionById($subscriptionId);
$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
return true;
});
}
/**
* Deletes a subscription.
*
* @param mixed $subscriptionId
* @return void
*/
public function deleteSubscription($subscriptionId) {
$subscriptionRow = $this->getSubscriptionById($subscriptionId);
$query = $this->db->getQueryBuilder();
$query->delete('calendarsubscriptions')
->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
->executeStatement();
$query = $this->db->getQueryBuilder();
$query->delete('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
$query->delete('calendarchanges')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
$query->delete($this->dbObjectPropertiesTable)
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
if ($subscriptionRow) {
$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
}
}
/**
* Returns a single scheduling object for the inbox collection.
*
* The returned array should contain the following elements:
* * uri - A unique basename for the object. This will be used to
* construct a full uri.
* * calendardata - The iCalendar object
* * lastmodified - The last modification date. Can be an int for a unix
* timestamp, or a PHP DateTime object.
* * etag - A unique token that must change if the object changed.
* * size - The size of the object, in bytes.
*
* @param string $principalUri
* @param string $objectUri
* @return array
*/
public function getSchedulingObject($principalUri, $objectUri) {
$query = $this->db->getQueryBuilder();
$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
->from('schedulingobjects')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
->executeQuery();
$row = $stmt->fetch();
if (!$row) {
return null;
}
return [
'uri' => $row['uri'],
'calendardata' => $row['calendardata'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'size' => (int)$row['size'],
];
}
/**
* Returns all scheduling objects for the inbox collection.
*
* These objects should be returned as an array. Every item in the array
* should follow the same structure as returned from getSchedulingObject.
*
* The main difference is that 'calendardata' is optional.
*
* @param string $principalUri
* @return array
*/
public function getSchedulingObjects($principalUri) {
$query = $this->db->getQueryBuilder();
$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
->from('schedulingobjects')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->executeQuery();
$result = [];
foreach ($stmt->fetchAll() as $row) {
$result[] = [
'calendardata' => $row['calendardata'],
'uri' => $row['uri'],
'lastmodified' => $row['lastmodified'],
'etag' => '"' . $row['etag'] . '"',
'size' => (int)$row['size'],
];
}
$stmt->closeCursor();
return $result;
}
/**
* Deletes a scheduling object from the inbox collection.
*
* @param string $principalUri
* @param string $objectUri
* @return void
*/
public function deleteSchedulingObject($principalUri, $objectUri) {
$query = $this->db->getQueryBuilder();
$query->delete('schedulingobjects')
->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
->executeStatement();
}
/**
* Creates a new scheduling object. This should land in a users' inbox.
*
* @param string $principalUri
* @param string $objectUri
* @param string $objectData
* @return void
*/
public function createSchedulingObject($principalUri, $objectUri, $objectData) {
$query = $this->db->getQueryBuilder();
$query->insert('schedulingobjects')
->values([
'principaluri' => $query->createNamedParameter($principalUri),
'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
'uri' => $query->createNamedParameter($objectUri),
'lastmodified' => $query->createNamedParameter(time()),
'etag' => $query->createNamedParameter(md5($objectData)),
'size' => $query->createNamedParameter(strlen($objectData))
])
->executeStatement();
}
/**
* Adds a change record to the calendarchanges table.
*
* @param mixed $calendarId
* @param string $objectUri
* @param int $operation 1 = add, 2 = modify, 3 = delete.
* @param int $calendarType
* @return void
*/
protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
$query = $this->db->getQueryBuilder();
$query->select('synctoken')
->from($table)
->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
$result = $query->executeQuery();
$syncToken = (int)$result->fetchOne();
$result->closeCursor();
$query = $this->db->getQueryBuilder();
$query->insert('calendarchanges')
->values([
'uri' => $query->createNamedParameter($objectUri),
'synctoken' => $query->createNamedParameter($syncToken),
'calendarid' => $query->createNamedParameter($calendarId),
'operation' => $query->createNamedParameter($operation),
'calendartype' => $query->createNamedParameter($calendarType),
])
->executeStatement();
$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
$stmt->execute([
$calendarId
]);
}
/**
* Parses some information from calendar objects, used for optimized
* calendar-queries.
*
* Returns an array with the following keys:
* * etag - An md5 checksum of the object without the quotes.
* * size - Size of the object in bytes
* * componentType - VEVENT, VTODO or VJOURNAL
* * firstOccurence
* * lastOccurence
* * uid - value of the UID property
*
* @param string $calendarData
* @return array
*/
public function getDenormalizedData($calendarData) {
$vObject = Reader::read($calendarData);
$vEvents = [];
$componentType = null;
$component = null;
$firstOccurrence = null;
$lastOccurrence = null;
$uid = null;
$classification = self::CLASSIFICATION_PUBLIC;
$hasDTSTART = false;
foreach ($vObject->getComponents() as $component) {
if ($component->name !== 'VTIMEZONE') {
// Finding all VEVENTs, and track them
if ($component->name === 'VEVENT') {
array_push($vEvents, $component);
if ($component->DTSTART) {
$hasDTSTART = true;
}
}
// Track first component type and uid
if ($uid === null) {
$componentType = $component->name;
$uid = (string)$component->UID;
}
}
}
if (!$componentType) {
throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
}
if ($hasDTSTART) {
$component = $vEvents[0];
// Finding the last occurrence is a bit harder
if (!isset($component->RRULE) && count($vEvents) === 1) {
$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
if (isset($component->DTEND)) {
$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
} elseif (isset($component->DURATION)) {
$endDate = clone $component->DTSTART->getDateTime();
$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
$lastOccurrence = $endDate->getTimeStamp();
} elseif (!$component->DTSTART->hasTime()) {
$endDate = clone $component->DTSTART->getDateTime();
$endDate->modify('+1 day');
$lastOccurrence = $endDate->getTimeStamp();
} else {
$lastOccurrence = $firstOccurrence;
}
} else {
$it = new EventIterator($vEvents);
$maxDate = new DateTime(self::MAX_DATE);
$firstOccurrence = $it->getDtStart()->getTimestamp();
if ($it->isInfinite()) {
$lastOccurrence = $maxDate->getTimestamp();
} else {
$end = $it->getDtEnd();
while ($it->valid() && $end < $maxDate) {
$end = $it->getDtEnd();
$it->next();
}
$lastOccurrence = $end->getTimestamp();
}
}
}
if ($component->CLASS) {
$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
switch ($component->CLASS->getValue()) {
case 'PUBLIC':
$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
break;
case 'CONFIDENTIAL':
$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
break;
}
}
return [
'etag' => md5($calendarData),
'size' => strlen($calendarData),
'componentType' => $componentType,
'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
'lastOccurence' => $lastOccurrence,
'uid' => $uid,
'classification' => $classification
];
}
/**
* @param $cardData
* @return bool|string
*/
private function readBlob($cardData) {
if (is_resource($cardData)) {
return stream_get_contents($cardData);
}
return $cardData;
}
/**
* @param list<array{href: string, commonName: string, readOnly: bool}> $add
* @param list<string> $remove
*/
public function updateShares(IShareable $shareable, array $add, array $remove): void {
$calendarId = $shareable->getResourceId();
$calendarRow = $this->getCalendarById($calendarId);
if ($calendarRow === null) {
throw new \RuntimeException('Trying to update shares for innexistant calendar: ' . $calendarId);
}
$oldShares = $this->getShares($calendarId);
$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
}
/**
* @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
*/
public function getShares(int $resourceId): array {
return $this->calendarSharingBackend->getShares($resourceId);
}
/**
* @param boolean $value
* @param \OCA\DAV\CalDAV\Calendar $calendar
* @return string|null
*/
public function setPublishStatus($value, $calendar) {
$calendarId = $calendar->getResourceId();
$calendarData = $this->getCalendarById($calendarId);
$query = $this->db->getQueryBuilder();
if ($value) {
$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
$query->insert('dav_shares')
->values([
'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
'type' => $query->createNamedParameter('calendar'),
'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
'publicuri' => $query->createNamedParameter($publicUri)
]);
$query->executeStatement();
$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
return $publicUri;
}
$query->delete('dav_shares')
->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
$query->executeStatement();
$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
return null;
}
/**
* @param \OCA\DAV\CalDAV\Calendar $calendar
* @return mixed
*/
public function getPublishStatus($calendar) {
$query = $this->db->getQueryBuilder();
$result = $query->select('publicuri')
->from('dav_shares')
->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
->executeQuery();
$row = $result->fetch();
$result->closeCursor();
return $row ? reset($row) : false;
}
/**
* @param int $resourceId
* @param list<array{privilege: string, principal: string, protected: bool}> $acl
* @return list<array{privilege: string, principal: string, protected: bool}>
*/
public function applyShareAcl(int $resourceId, array $acl): array {
return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
}
/**
* update properties table
*
* @param int $calendarId
* @param string $objectUri
* @param string $calendarData
* @param int $calendarType
*/
public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
try {
$vCalendar = $this->readCalendarData($calendarData);
} catch (\Exception $ex) {
return;
}
$this->purgeProperties($calendarId, $objectId);
$query = $this->db->getQueryBuilder();
$query->insert($this->dbObjectPropertiesTable)
->values(
[
'calendarid' => $query->createNamedParameter($calendarId),
'calendartype' => $query->createNamedParameter($calendarType),
'objectid' => $query->createNamedParameter($objectId),
'name' => $query->createParameter('name'),
'parameter' => $query->createParameter('parameter'),
'value' => $query->createParameter('value'),
]
);
$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
foreach ($vCalendar->getComponents() as $component) {
if (!in_array($component->name, $indexComponents)) {
continue;
}
foreach ($component->children() as $property) {
if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
$value = $property->getValue();
// is this a shitty db?
if (!$this->db->supports4ByteText()) {
$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
}
$value = mb_strcut($value, 0, 254);
$query->setParameter('name', $property->name);
$query->setParameter('parameter', null);
$query->setParameter('value', $value);
$query->executeStatement();
}
if (array_key_exists($property->name, self::$indexParameters)) {
$parameters = $property->parameters();
$indexedParametersForProperty = self::$indexParameters[$property->name];
foreach ($parameters as $key => $value) {
if (in_array($key, $indexedParametersForProperty)) {
// is this a shitty db?
if ($this->db->supports4ByteText()) {
$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
}
$query->setParameter('name', $property->name);
$query->setParameter('parameter', mb_strcut($key, 0, 254));
$query->setParameter('value', mb_strcut($value, 0, 254));
$query->executeStatement();
}
}
}
}
}
}
/**
* deletes all birthday calendars
*/
public function deleteAllBirthdayCalendars() {
$query = $this->db->getQueryBuilder();
$result = $query->select(['id'])->from('calendars')
->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
->executeQuery();
$ids = $result->fetchAll();
$result->closeCursor();
foreach ($ids as $id) {
$this->deleteCalendar(
$id['id'],
true // No data to keep in the trashbin, if the user re-enables then we regenerate
);
}
}
/**
* @param $subscriptionId
*/
public function purgeAllCachedEventsForSubscription($subscriptionId) {
$query = $this->db->getQueryBuilder();
$query->select('uri')
->from('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
$stmt = $query->executeQuery();
$uris = [];
foreach ($stmt->fetchAll() as $row) {
$uris[] = $row['uri'];
}
$stmt->closeCursor();
$query = $this->db->getQueryBuilder();
$query->delete('calendarobjects')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
$query->delete('calendarchanges')
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
$query->delete($this->dbObjectPropertiesTable)
->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
->executeStatement();
foreach ($uris as $uri) {
$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
}
}
/**
* Move a calendar from one user to another
*
* @param string $uriName
* @param string $uriOrigin
* @param string $uriDestination
* @param string $newUriName (optional) the new uriName
*/
public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
$query = $this->db->getQueryBuilder();
$query->update('calendars')
->set('principaluri', $query->createNamedParameter($uriDestination))
->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
->executeStatement();
}
/**
* read VCalendar data into a VCalendar object
*
* @param string $objectData
* @return VCalendar
*/
protected function readCalendarData($objectData) {
return Reader::read($objectData);
}
/**
* delete all properties from a given calendar object
*
* @param int $calendarId
* @param int $objectId
*/
protected function purgeProperties($calendarId, $objectId) {
$query = $this->db->getQueryBuilder();
$query->delete($this->dbObjectPropertiesTable)
->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
$query->executeStatement();
}
/**
* get ID from a given calendar object
*
* @param int $calendarId
* @param string $uri
* @param int $calendarType
* @return int
*/
protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
$query = $this->db->getQueryBuilder();
$query->select('id')
->from('calendarobjects')
->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
$result = $query->executeQuery();
$objectIds = $result->fetch();
$result->closeCursor();
if (!isset($objectIds['id'])) {
throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
}
return (int)$objectIds['id'];
}
/**
* @throws \InvalidArgumentException
*/
public function pruneOutdatedSyncTokens(int $keep = 10_000): int {
if ($keep < 0) {
throw new \InvalidArgumentException();
}
$query = $this->db->getQueryBuilder();
$query->delete('calendarchanges')
->orderBy('id', 'DESC')
->setFirstResult($keep);
return $query->executeStatement();
}
/**
* return legacy endpoint principal name to new principal name
*
* @param $principalUri
* @param $toV2
* @return string
*/
private function convertPrincipal($principalUri, $toV2) {
if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
[, $name] = Uri\split($principalUri);
if ($toV2 === true) {
return "principals/users/$name";
}
return "principals/$name";
}
return $principalUri;
}
/**
* adds information about an owner to the calendar data
*
*/
private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
if (isset($calendarInfo[$ownerPrincipalKey])) {
$uri = $calendarInfo[$ownerPrincipalKey];
} else {
$uri = $calendarInfo['principaluri'];
}
$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
if (isset($principalInformation['{DAV:}displayname'])) {
$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
}
return $calendarInfo;
}
private function addResourceTypeToCalendar(array $row, array $calendar): array {
if (isset($row['deleted_at'])) {
// Columns is set and not null -> this is a deleted calendar
// we send a custom resourcetype to hide the deleted calendar
// from ordinary DAV clients, but the Calendar app will know
// how to handle this special resource.
$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
'{DAV:}collection',
sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
]);
}
return $calendar;
}
/**
* Amend the calendar info with database row data
*
* @param array $row
* @param array $calendar
*
* @return array
*/
private function rowToCalendar($row, array $calendar): array {
foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
$value = $row[$dbName];
if ($value !== null) {
settype($value, $type);
}
$calendar[$xmlName] = $value;
}
return $calendar;
}
/**
* Amend the subscription info with database row data
*
* @param array $row
* @param array $subscription
*
* @return array
*/
private function rowToSubscription($row, array $subscription): array {
foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
$value = $row[$dbName];
if ($value !== null) {
settype($value, $type);
}
$subscription[$xmlName] = $value;
}
return $subscription;
}
}
|