Completed
Push — master ( 4185df...75edec )
by
unknown
27:24
created
apps/dav/lib/CalDAV/Import/ImportService.php 1 patch
Indentation   +309 added lines, -309 removed lines patch added patch discarded remove patch
@@ -23,322 +23,322 @@
 block discarded – undo
23 23
  */
24 24
 class ImportService {
25 25
 
26
-	public function __construct(
27
-		private CalDavBackend $backend,
28
-	) {
29
-	}
26
+    public function __construct(
27
+        private CalDavBackend $backend,
28
+    ) {
29
+    }
30 30
 
31
-	/**
32
-	 * Executes import with appropriate object generator based on format
33
-	 *
34
-	 * @param resource $source
35
-	 *
36
-	 * @return array<string,array<string,string|array<string>>>
37
-	 *
38
-	 * @throws \InvalidArgumentException
39
-	 */
40
-	public function import($source, CalendarImpl $calendar, CalendarImportOptions $options): array {
41
-		if (!is_resource($source)) {
42
-			throw new InvalidArgumentException('Invalid import source must be a file resource');
43
-		}
44
-		switch ($options->getFormat()) {
45
-			case 'ical':
46
-				return $this->importProcess($source, $calendar, $options, $this->importText(...));
47
-				break;
48
-			case 'jcal':
49
-				return $this->importProcess($source, $calendar, $options, $this->importJson(...));
50
-				break;
51
-			case 'xcal':
52
-				return $this->importProcess($source, $calendar, $options, $this->importXml(...));
53
-				break;
54
-			default:
55
-				throw new InvalidArgumentException('Invalid import format');
56
-		}
57
-	}
31
+    /**
32
+     * Executes import with appropriate object generator based on format
33
+     *
34
+     * @param resource $source
35
+     *
36
+     * @return array<string,array<string,string|array<string>>>
37
+     *
38
+     * @throws \InvalidArgumentException
39
+     */
40
+    public function import($source, CalendarImpl $calendar, CalendarImportOptions $options): array {
41
+        if (!is_resource($source)) {
42
+            throw new InvalidArgumentException('Invalid import source must be a file resource');
43
+        }
44
+        switch ($options->getFormat()) {
45
+            case 'ical':
46
+                return $this->importProcess($source, $calendar, $options, $this->importText(...));
47
+                break;
48
+            case 'jcal':
49
+                return $this->importProcess($source, $calendar, $options, $this->importJson(...));
50
+                break;
51
+            case 'xcal':
52
+                return $this->importProcess($source, $calendar, $options, $this->importXml(...));
53
+                break;
54
+            default:
55
+                throw new InvalidArgumentException('Invalid import format');
56
+        }
57
+    }
58 58
 
59
-	/**
60
-	 * Generates object stream from a text formatted source (ical)
61
-	 *
62
-	 * @param resource $source
63
-	 *
64
-	 * @return Generator<\Sabre\VObject\Component\VCalendar>
65
-	 */
66
-	public function importText($source): Generator {
67
-		if (!is_resource($source)) {
68
-			throw new InvalidArgumentException('Invalid import source must be a file resource');
69
-		}
70
-		$importer = new TextImporter($source);
71
-		$structure = $importer->structure();
72
-		$sObjectPrefix = $importer::OBJECT_PREFIX;
73
-		$sObjectSuffix = $importer::OBJECT_SUFFIX;
74
-		// calendar properties
75
-		foreach ($structure['VCALENDAR'] as $entry) {
76
-			if (!str_ends_with($entry, "\n") || !str_ends_with($entry, "\r\n")) {
77
-				$sObjectPrefix .= PHP_EOL;
78
-			}
79
-		}
80
-		// calendar time zones
81
-		$timezones = [];
82
-		foreach ($structure['VTIMEZONE'] as $tid => $collection) {
83
-			$instance = $collection[0];
84
-			$sObjectContents = $importer->extract((int)$instance[2], (int)$instance[3]);
85
-			$vObject = Reader::read($sObjectPrefix . $sObjectContents . $sObjectSuffix);
86
-			$timezones[$tid] = clone $vObject->VTIMEZONE;
87
-		}
88
-		// calendar components
89
-		// for each component type, construct a full calendar object with all components
90
-		// that match the same UID and appropriate time zones that are used in the components
91
-		foreach (['VEVENT', 'VTODO', 'VJOURNAL'] as $type) {
92
-			foreach ($structure[$type] as $cid => $instances) {
93
-				/** @var array<int,VCalendar> $instances */
94
-				// extract all instances of component and unserialize to object
95
-				$sObjectContents = '';
96
-				foreach ($instances as $instance) {
97
-					$sObjectContents .= $importer->extract($instance[2], $instance[3]);
98
-				}
99
-				/** @var VCalendar $vObject */
100
-				$vObject = Reader::read($sObjectPrefix . $sObjectContents . $sObjectSuffix);
101
-				// add time zones to object
102
-				foreach ($this->findTimeZones($vObject) as $zone) {
103
-					if (isset($timezones[$zone])) {
104
-						$vObject->add(clone $timezones[$zone]);
105
-					}
106
-				}
107
-				yield $vObject;
108
-			}
109
-		}
110
-	}
59
+    /**
60
+     * Generates object stream from a text formatted source (ical)
61
+     *
62
+     * @param resource $source
63
+     *
64
+     * @return Generator<\Sabre\VObject\Component\VCalendar>
65
+     */
66
+    public function importText($source): Generator {
67
+        if (!is_resource($source)) {
68
+            throw new InvalidArgumentException('Invalid import source must be a file resource');
69
+        }
70
+        $importer = new TextImporter($source);
71
+        $structure = $importer->structure();
72
+        $sObjectPrefix = $importer::OBJECT_PREFIX;
73
+        $sObjectSuffix = $importer::OBJECT_SUFFIX;
74
+        // calendar properties
75
+        foreach ($structure['VCALENDAR'] as $entry) {
76
+            if (!str_ends_with($entry, "\n") || !str_ends_with($entry, "\r\n")) {
77
+                $sObjectPrefix .= PHP_EOL;
78
+            }
79
+        }
80
+        // calendar time zones
81
+        $timezones = [];
82
+        foreach ($structure['VTIMEZONE'] as $tid => $collection) {
83
+            $instance = $collection[0];
84
+            $sObjectContents = $importer->extract((int)$instance[2], (int)$instance[3]);
85
+            $vObject = Reader::read($sObjectPrefix . $sObjectContents . $sObjectSuffix);
86
+            $timezones[$tid] = clone $vObject->VTIMEZONE;
87
+        }
88
+        // calendar components
89
+        // for each component type, construct a full calendar object with all components
90
+        // that match the same UID and appropriate time zones that are used in the components
91
+        foreach (['VEVENT', 'VTODO', 'VJOURNAL'] as $type) {
92
+            foreach ($structure[$type] as $cid => $instances) {
93
+                /** @var array<int,VCalendar> $instances */
94
+                // extract all instances of component and unserialize to object
95
+                $sObjectContents = '';
96
+                foreach ($instances as $instance) {
97
+                    $sObjectContents .= $importer->extract($instance[2], $instance[3]);
98
+                }
99
+                /** @var VCalendar $vObject */
100
+                $vObject = Reader::read($sObjectPrefix . $sObjectContents . $sObjectSuffix);
101
+                // add time zones to object
102
+                foreach ($this->findTimeZones($vObject) as $zone) {
103
+                    if (isset($timezones[$zone])) {
104
+                        $vObject->add(clone $timezones[$zone]);
105
+                    }
106
+                }
107
+                yield $vObject;
108
+            }
109
+        }
110
+    }
111 111
 
112
-	/**
113
-	 * Generates object stream from a xml formatted source (xcal)
114
-	 *
115
-	 * @param resource $source
116
-	 *
117
-	 * @return Generator<\Sabre\VObject\Component\VCalendar>
118
-	 */
119
-	public function importXml($source): Generator {
120
-		if (!is_resource($source)) {
121
-			throw new InvalidArgumentException('Invalid import source must be a file resource');
122
-		}
123
-		$importer = new XmlImporter($source);
124
-		$structure = $importer->structure();
125
-		$sObjectPrefix = $importer::OBJECT_PREFIX;
126
-		$sObjectSuffix = $importer::OBJECT_SUFFIX;
127
-		// calendar time zones
128
-		$timezones = [];
129
-		foreach ($structure['VTIMEZONE'] as $tid => $collection) {
130
-			$instance = $collection[0];
131
-			$sObjectContents = $importer->extract((int)$instance[2], (int)$instance[3]);
132
-			$vObject = Reader::readXml($sObjectPrefix . $sObjectContents . $sObjectSuffix);
133
-			$timezones[$tid] = clone $vObject->VTIMEZONE;
134
-		}
135
-		// calendar components
136
-		// for each component type, construct a full calendar object with all components
137
-		// that match the same UID and appropriate time zones that are used in the components
138
-		foreach (['VEVENT', 'VTODO', 'VJOURNAL'] as $type) {
139
-			foreach ($structure[$type] as $cid => $instances) {
140
-				/** @var array<int,VCalendar> $instances */
141
-				// extract all instances of component and unserialize to object
142
-				$sObjectContents = '';
143
-				foreach ($instances as $instance) {
144
-					$sObjectContents .= $importer->extract($instance[2], $instance[3]);
145
-				}
146
-				/** @var VCalendar $vObject */
147
-				$vObject = Reader::readXml($sObjectPrefix . $sObjectContents . $sObjectSuffix);
148
-				// add time zones to object
149
-				foreach ($this->findTimeZones($vObject) as $zone) {
150
-					if (isset($timezones[$zone])) {
151
-						$vObject->add(clone $timezones[$zone]);
152
-					}
153
-				}
154
-				yield $vObject;
155
-			}
156
-		}
157
-	}
112
+    /**
113
+     * Generates object stream from a xml formatted source (xcal)
114
+     *
115
+     * @param resource $source
116
+     *
117
+     * @return Generator<\Sabre\VObject\Component\VCalendar>
118
+     */
119
+    public function importXml($source): Generator {
120
+        if (!is_resource($source)) {
121
+            throw new InvalidArgumentException('Invalid import source must be a file resource');
122
+        }
123
+        $importer = new XmlImporter($source);
124
+        $structure = $importer->structure();
125
+        $sObjectPrefix = $importer::OBJECT_PREFIX;
126
+        $sObjectSuffix = $importer::OBJECT_SUFFIX;
127
+        // calendar time zones
128
+        $timezones = [];
129
+        foreach ($structure['VTIMEZONE'] as $tid => $collection) {
130
+            $instance = $collection[0];
131
+            $sObjectContents = $importer->extract((int)$instance[2], (int)$instance[3]);
132
+            $vObject = Reader::readXml($sObjectPrefix . $sObjectContents . $sObjectSuffix);
133
+            $timezones[$tid] = clone $vObject->VTIMEZONE;
134
+        }
135
+        // calendar components
136
+        // for each component type, construct a full calendar object with all components
137
+        // that match the same UID and appropriate time zones that are used in the components
138
+        foreach (['VEVENT', 'VTODO', 'VJOURNAL'] as $type) {
139
+            foreach ($structure[$type] as $cid => $instances) {
140
+                /** @var array<int,VCalendar> $instances */
141
+                // extract all instances of component and unserialize to object
142
+                $sObjectContents = '';
143
+                foreach ($instances as $instance) {
144
+                    $sObjectContents .= $importer->extract($instance[2], $instance[3]);
145
+                }
146
+                /** @var VCalendar $vObject */
147
+                $vObject = Reader::readXml($sObjectPrefix . $sObjectContents . $sObjectSuffix);
148
+                // add time zones to object
149
+                foreach ($this->findTimeZones($vObject) as $zone) {
150
+                    if (isset($timezones[$zone])) {
151
+                        $vObject->add(clone $timezones[$zone]);
152
+                    }
153
+                }
154
+                yield $vObject;
155
+            }
156
+        }
157
+    }
158 158
 
159
-	/**
160
-	 * Generates object stream from a json formatted source (jcal)
161
-	 *
162
-	 * @param resource $source
163
-	 *
164
-	 * @return Generator<\Sabre\VObject\Component\VCalendar>
165
-	 */
166
-	public function importJson($source): Generator {
167
-		if (!is_resource($source)) {
168
-			throw new InvalidArgumentException('Invalid import source must be a file resource');
169
-		}
170
-		/** @var VCALENDAR $importer */
171
-		$importer = Reader::readJson($source);
172
-		// calendar time zones
173
-		$timezones = [];
174
-		foreach ($importer->VTIMEZONE as $timezone) {
175
-			$tzid = $timezone->TZID?->getValue();
176
-			if ($tzid !== null) {
177
-				$timezones[$tzid] = clone $timezone;
178
-			}
179
-		}
180
-		// calendar components
181
-		foreach ($importer->getBaseComponents() as $base) {
182
-			$vObject = new VCalendar;
183
-			$vObject->VERSION = clone $importer->VERSION;
184
-			$vObject->PRODID = clone $importer->PRODID;
185
-			// extract all instances of component
186
-			foreach ($importer->getByUID($base->UID->getValue()) as $instance) {
187
-				$vObject->add(clone $instance);
188
-			}
189
-			// add time zones to object
190
-			foreach ($this->findTimeZones($vObject) as $zone) {
191
-				if (isset($timezones[$zone])) {
192
-					$vObject->add(clone $timezones[$zone]);
193
-				}
194
-			}
195
-			yield $vObject;
196
-		}
197
-	}
159
+    /**
160
+     * Generates object stream from a json formatted source (jcal)
161
+     *
162
+     * @param resource $source
163
+     *
164
+     * @return Generator<\Sabre\VObject\Component\VCalendar>
165
+     */
166
+    public function importJson($source): Generator {
167
+        if (!is_resource($source)) {
168
+            throw new InvalidArgumentException('Invalid import source must be a file resource');
169
+        }
170
+        /** @var VCALENDAR $importer */
171
+        $importer = Reader::readJson($source);
172
+        // calendar time zones
173
+        $timezones = [];
174
+        foreach ($importer->VTIMEZONE as $timezone) {
175
+            $tzid = $timezone->TZID?->getValue();
176
+            if ($tzid !== null) {
177
+                $timezones[$tzid] = clone $timezone;
178
+            }
179
+        }
180
+        // calendar components
181
+        foreach ($importer->getBaseComponents() as $base) {
182
+            $vObject = new VCalendar;
183
+            $vObject->VERSION = clone $importer->VERSION;
184
+            $vObject->PRODID = clone $importer->PRODID;
185
+            // extract all instances of component
186
+            foreach ($importer->getByUID($base->UID->getValue()) as $instance) {
187
+                $vObject->add(clone $instance);
188
+            }
189
+            // add time zones to object
190
+            foreach ($this->findTimeZones($vObject) as $zone) {
191
+                if (isset($timezones[$zone])) {
192
+                    $vObject->add(clone $timezones[$zone]);
193
+                }
194
+            }
195
+            yield $vObject;
196
+        }
197
+    }
198 198
 
199
-	/**
200
-	 * Searches through all component properties looking for defined timezones
201
-	 *
202
-	 * @return array<string>
203
-	 */
204
-	private function findTimeZones(VCalendar $vObject): array {
205
-		$timezones = [];
206
-		foreach ($vObject->getComponents() as $vComponent) {
207
-			if ($vComponent->name !== 'VTIMEZONE') {
208
-				foreach (['DTSTART', 'DTEND', 'DUE', 'RDATE', 'EXDATE'] as $property) {
209
-					if (isset($vComponent->$property?->parameters['TZID'])) {
210
-						$tid = $vComponent->$property->parameters['TZID']->getValue();
211
-						$timezones[$tid] = true;
212
-					}
213
-				}
214
-			}
215
-		}
216
-		return array_keys($timezones);
217
-	}
199
+    /**
200
+     * Searches through all component properties looking for defined timezones
201
+     *
202
+     * @return array<string>
203
+     */
204
+    private function findTimeZones(VCalendar $vObject): array {
205
+        $timezones = [];
206
+        foreach ($vObject->getComponents() as $vComponent) {
207
+            if ($vComponent->name !== 'VTIMEZONE') {
208
+                foreach (['DTSTART', 'DTEND', 'DUE', 'RDATE', 'EXDATE'] as $property) {
209
+                    if (isset($vComponent->$property?->parameters['TZID'])) {
210
+                        $tid = $vComponent->$property->parameters['TZID']->getValue();
211
+                        $timezones[$tid] = true;
212
+                    }
213
+                }
214
+            }
215
+        }
216
+        return array_keys($timezones);
217
+    }
218 218
 
219
-	/**
220
-	 * Import objects
221
-	 *
222
-	 * @since 32.0.0
223
-	 *
224
-	 * @param resource $source
225
-	 * @param CalendarImportOptions $options
226
-	 * @param callable $generator<CalendarImportOptions>: Generator<\Sabre\VObject\Component\VCalendar>
227
-	 *
228
-	 * @return array<string,array<string,string|array<string>>>
229
-	 */
230
-	public function importProcess($source, CalendarImpl $calendar, CalendarImportOptions $options, callable $generator): array {
231
-		$calendarId = $calendar->getKey();
232
-		$calendarUri = $calendar->getUri();
233
-		$principalUri = $calendar->getPrincipalUri();
234
-		$outcome = [];
235
-		foreach ($generator($source) as $vObject) {
236
-			$components = $vObject->getBaseComponents();
237
-			// determine if the object has no base component types
238
-			if (count($components) === 0) {
239
-				$errorMessage = 'One or more objects discovered with no base component types';
240
-				if ($options->getErrors() === $options::ERROR_FAIL) {
241
-					throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
242
-				}
243
-				$outcome['nbct'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
244
-				continue;
245
-			}
246
-			// determine if the object has more than one base component type
247
-			// object can have multiple base components with the same uid
248
-			// but we need to make sure they are of the same type
249
-			if (count($components) > 1) {
250
-				$type = $components[0]->name;
251
-				foreach ($components as $entry) {
252
-					if ($type !== $entry->name) {
253
-						$errorMessage = 'One or more objects discovered with multiple base component types';
254
-						if ($options->getErrors() === $options::ERROR_FAIL) {
255
-							throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
256
-						}
257
-						$outcome['mbct'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
258
-						continue 2;
259
-					}
260
-				}
261
-			}
262
-			// determine if the object has a uid
263
-			if (!isset($components[0]->UID)) {
264
-				$errorMessage = 'One or more objects discovered without a UID';
265
-				if ($options->getErrors() === $options::ERROR_FAIL) {
266
-					throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
267
-				}
268
-				$outcome['noid'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
269
-				continue;
270
-			}
271
-			$uid = $components[0]->UID->getValue();
272
-			// validate object
273
-			if ($options->getValidate() !== $options::VALIDATE_NONE) {
274
-				$issues = $this->componentValidate($vObject, true, 3);
275
-				if ($options->getValidate() === $options::VALIDATE_SKIP && $issues !== []) {
276
-					$outcome[$uid] = ['outcome' => 'error', 'errors' => $issues];
277
-					continue;
278
-				} elseif ($options->getValidate() === $options::VALIDATE_FAIL && $issues !== []) {
279
-					throw new InvalidArgumentException('Error importing calendar data: UID <' . $uid . '> - ' . $issues[0]);
280
-				}
281
-			}
282
-			// create or update object in the data store
283
-			$objectId = $this->backend->getCalendarObjectByUID($principalUri, $uid, $calendarUri);
284
-			$objectData = $vObject->serialize();
285
-			try {
286
-				if ($objectId === null) {
287
-					$objectId = UUIDUtil::getUUID();
288
-					$this->backend->createCalendarObject(
289
-						$calendarId,
290
-						$objectId,
291
-						$objectData
292
-					);
293
-					$outcome[$uid] = ['outcome' => 'created'];
294
-				} else {
295
-					[$cid, $oid] = explode('/', $objectId);
296
-					if ($options->getSupersede()) {
297
-						$this->backend->updateCalendarObject(
298
-							$calendarId,
299
-							$oid,
300
-							$objectData
301
-						);
302
-						$outcome[$uid] = ['outcome' => 'updated'];
303
-					} else {
304
-						$outcome[$uid] = ['outcome' => 'exists'];
305
-					}
306
-				}
307
-			} catch (Exception $e) {
308
-				$errorMessage = $e->getMessage();
309
-				if ($options->getErrors() === $options::ERROR_FAIL) {
310
-					throw new Exception('Error importing calendar data: UID <' . $uid . '> - ' . $errorMessage, 0, $e);
311
-				}
312
-				$outcome[$uid] = ['outcome' => 'error', 'errors' => [$errorMessage]];
313
-			}
314
-		}
219
+    /**
220
+     * Import objects
221
+     *
222
+     * @since 32.0.0
223
+     *
224
+     * @param resource $source
225
+     * @param CalendarImportOptions $options
226
+     * @param callable $generator<CalendarImportOptions>: Generator<\Sabre\VObject\Component\VCalendar>
227
+     *
228
+     * @return array<string,array<string,string|array<string>>>
229
+     */
230
+    public function importProcess($source, CalendarImpl $calendar, CalendarImportOptions $options, callable $generator): array {
231
+        $calendarId = $calendar->getKey();
232
+        $calendarUri = $calendar->getUri();
233
+        $principalUri = $calendar->getPrincipalUri();
234
+        $outcome = [];
235
+        foreach ($generator($source) as $vObject) {
236
+            $components = $vObject->getBaseComponents();
237
+            // determine if the object has no base component types
238
+            if (count($components) === 0) {
239
+                $errorMessage = 'One or more objects discovered with no base component types';
240
+                if ($options->getErrors() === $options::ERROR_FAIL) {
241
+                    throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
242
+                }
243
+                $outcome['nbct'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
244
+                continue;
245
+            }
246
+            // determine if the object has more than one base component type
247
+            // object can have multiple base components with the same uid
248
+            // but we need to make sure they are of the same type
249
+            if (count($components) > 1) {
250
+                $type = $components[0]->name;
251
+                foreach ($components as $entry) {
252
+                    if ($type !== $entry->name) {
253
+                        $errorMessage = 'One or more objects discovered with multiple base component types';
254
+                        if ($options->getErrors() === $options::ERROR_FAIL) {
255
+                            throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
256
+                        }
257
+                        $outcome['mbct'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
258
+                        continue 2;
259
+                    }
260
+                }
261
+            }
262
+            // determine if the object has a uid
263
+            if (!isset($components[0]->UID)) {
264
+                $errorMessage = 'One or more objects discovered without a UID';
265
+                if ($options->getErrors() === $options::ERROR_FAIL) {
266
+                    throw new InvalidArgumentException('Error importing calendar data: ' . $errorMessage);
267
+                }
268
+                $outcome['noid'] = ['outcome' => 'error', 'errors' => [$errorMessage]];
269
+                continue;
270
+            }
271
+            $uid = $components[0]->UID->getValue();
272
+            // validate object
273
+            if ($options->getValidate() !== $options::VALIDATE_NONE) {
274
+                $issues = $this->componentValidate($vObject, true, 3);
275
+                if ($options->getValidate() === $options::VALIDATE_SKIP && $issues !== []) {
276
+                    $outcome[$uid] = ['outcome' => 'error', 'errors' => $issues];
277
+                    continue;
278
+                } elseif ($options->getValidate() === $options::VALIDATE_FAIL && $issues !== []) {
279
+                    throw new InvalidArgumentException('Error importing calendar data: UID <' . $uid . '> - ' . $issues[0]);
280
+                }
281
+            }
282
+            // create or update object in the data store
283
+            $objectId = $this->backend->getCalendarObjectByUID($principalUri, $uid, $calendarUri);
284
+            $objectData = $vObject->serialize();
285
+            try {
286
+                if ($objectId === null) {
287
+                    $objectId = UUIDUtil::getUUID();
288
+                    $this->backend->createCalendarObject(
289
+                        $calendarId,
290
+                        $objectId,
291
+                        $objectData
292
+                    );
293
+                    $outcome[$uid] = ['outcome' => 'created'];
294
+                } else {
295
+                    [$cid, $oid] = explode('/', $objectId);
296
+                    if ($options->getSupersede()) {
297
+                        $this->backend->updateCalendarObject(
298
+                            $calendarId,
299
+                            $oid,
300
+                            $objectData
301
+                        );
302
+                        $outcome[$uid] = ['outcome' => 'updated'];
303
+                    } else {
304
+                        $outcome[$uid] = ['outcome' => 'exists'];
305
+                    }
306
+                }
307
+            } catch (Exception $e) {
308
+                $errorMessage = $e->getMessage();
309
+                if ($options->getErrors() === $options::ERROR_FAIL) {
310
+                    throw new Exception('Error importing calendar data: UID <' . $uid . '> - ' . $errorMessage, 0, $e);
311
+                }
312
+                $outcome[$uid] = ['outcome' => 'error', 'errors' => [$errorMessage]];
313
+            }
314
+        }
315 315
 
316
-		return $outcome;
317
-	}
316
+        return $outcome;
317
+    }
318 318
 
319
-	/**
320
-	 * Validate a component
321
-	 *
322
-	 * @param VCalendar $vObject
323
-	 * @param bool $repair attempt to repair the component
324
-	 * @param int $level minimum level of issues to return
325
-	 * @return list<mixed>
326
-	 */
327
-	private function componentValidate(VCalendar $vObject, bool $repair, int $level): array {
328
-		// validate component(S)
329
-		$issues = $vObject->validate(Node::PROFILE_CALDAV);
330
-		// attempt to repair
331
-		if ($repair && count($issues) > 0) {
332
-			$issues = $vObject->validate(Node::REPAIR);
333
-		}
334
-		// filter out messages based on level
335
-		$result = [];
336
-		foreach ($issues as $key => $issue) {
337
-			if (isset($issue['level']) && $issue['level'] >= $level) {
338
-				$result[] = $issue['message'];
339
-			}
340
-		}
319
+    /**
320
+     * Validate a component
321
+     *
322
+     * @param VCalendar $vObject
323
+     * @param bool $repair attempt to repair the component
324
+     * @param int $level minimum level of issues to return
325
+     * @return list<mixed>
326
+     */
327
+    private function componentValidate(VCalendar $vObject, bool $repair, int $level): array {
328
+        // validate component(S)
329
+        $issues = $vObject->validate(Node::PROFILE_CALDAV);
330
+        // attempt to repair
331
+        if ($repair && count($issues) > 0) {
332
+            $issues = $vObject->validate(Node::REPAIR);
333
+        }
334
+        // filter out messages based on level
335
+        $result = [];
336
+        foreach ($issues as $key => $issue) {
337
+            if (isset($issue['level']) && $issue['level'] >= $level) {
338
+                $result[] = $issue['message'];
339
+            }
340
+        }
341 341
 
342
-		return $result;
343
-	}
342
+        return $result;
343
+    }
344 344
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +3662 added lines, -3662 removed lines patch added patch discarded remove patch
@@ -110,3666 +110,3666 @@
 block discarded – undo
110 110
  * }
111 111
  */
112 112
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
113
-	use TTransactional;
114
-
115
-	public const CALENDAR_TYPE_CALENDAR = 0;
116
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
117
-	public const CALENDAR_TYPE_FEDERATED = 2;
118
-
119
-	public const PERSONAL_CALENDAR_URI = 'personal';
120
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
121
-
122
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
123
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
124
-
125
-	/**
126
-	 * We need to specify a max date, because we need to stop *somewhere*
127
-	 *
128
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
129
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
130
-	 * in 2038-01-19 to avoid problems when the date is converted
131
-	 * to a unix timestamp.
132
-	 */
133
-	public const MAX_DATE = '2038-01-01';
134
-
135
-	public const ACCESS_PUBLIC = 4;
136
-	public const CLASSIFICATION_PUBLIC = 0;
137
-	public const CLASSIFICATION_PRIVATE = 1;
138
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
139
-
140
-	/**
141
-	 * List of CalDAV properties, and how they map to database field names and their type
142
-	 * Add your own properties by simply adding on to this array.
143
-	 *
144
-	 * @var array
145
-	 * @psalm-var array<string, string[]>
146
-	 */
147
-	public array $propertyMap = [
148
-		'{DAV:}displayname' => ['displayname', 'string'],
149
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
150
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
154
-	];
155
-
156
-	/**
157
-	 * List of subscription properties, and how they map to database field names.
158
-	 *
159
-	 * @var array
160
-	 */
161
-	public array $subscriptionPropertyMap = [
162
-		'{DAV:}displayname' => ['displayname', 'string'],
163
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
164
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
165
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
166
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
167
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
168
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
169
-	];
170
-
171
-	/**
172
-	 * properties to index
173
-	 *
174
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
175
-	 *
176
-	 * @see \OCP\Calendar\ICalendarQuery
177
-	 */
178
-	private const INDEXED_PROPERTIES = [
179
-		'CATEGORIES',
180
-		'COMMENT',
181
-		'DESCRIPTION',
182
-		'LOCATION',
183
-		'RESOURCES',
184
-		'STATUS',
185
-		'SUMMARY',
186
-		'ATTENDEE',
187
-		'CONTACT',
188
-		'ORGANIZER'
189
-	];
190
-
191
-	/** @var array parameters to index */
192
-	public static array $indexParameters = [
193
-		'ATTENDEE' => ['CN'],
194
-		'ORGANIZER' => ['CN'],
195
-	];
196
-
197
-	/**
198
-	 * @var string[] Map of uid => display name
199
-	 */
200
-	protected array $userDisplayNames;
201
-
202
-	private string $dbObjectsTable = 'calendarobjects';
203
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
204
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
205
-	private array $cachedObjects = [];
206
-
207
-	private readonly ICache $publishStatusCache;
208
-
209
-	public function __construct(
210
-		private IDBConnection $db,
211
-		private Principal $principalBackend,
212
-		private IUserManager $userManager,
213
-		private ISecureRandom $random,
214
-		private LoggerInterface $logger,
215
-		private IEventDispatcher $dispatcher,
216
-		private IConfig $config,
217
-		private Sharing\Backend $calendarSharingBackend,
218
-		private FederatedCalendarMapper $federatedCalendarMapper,
219
-		ICacheFactory $cacheFactory,
220
-		private bool $legacyEndpoint = false,
221
-	) {
222
-		$this->publishStatusCache = $cacheFactory->createInMemory();
223
-	}
224
-
225
-	/**
226
-	 * Return the number of calendars owned by the given principal.
227
-	 *
228
-	 * Calendars shared with the given principal are not counted!
229
-	 *
230
-	 * By default, this excludes the automatically generated birthday calendar.
231
-	 */
232
-	public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
233
-		$principalUri = $this->convertPrincipal($principalUri, true);
234
-		$query = $this->db->getQueryBuilder();
235
-		$query->select($query->func()->count('*'))
236
-			->from('calendars');
237
-
238
-		if ($principalUri === '') {
239
-			$query->where($query->expr()->emptyString('principaluri'));
240
-		} else {
241
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
242
-		}
243
-
244
-		if ($excludeBirthday) {
245
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
246
-		}
247
-
248
-		$result = $query->executeQuery();
249
-		$column = (int)$result->fetchOne();
250
-		$result->closeCursor();
251
-		return $column;
252
-	}
253
-
254
-	/**
255
-	 * Return the number of subscriptions for a principal
256
-	 */
257
-	public function getSubscriptionsForUserCount(string $principalUri): int {
258
-		$principalUri = $this->convertPrincipal($principalUri, true);
259
-		$query = $this->db->getQueryBuilder();
260
-		$query->select($query->func()->count('*'))
261
-			->from('calendarsubscriptions');
262
-
263
-		if ($principalUri === '') {
264
-			$query->where($query->expr()->emptyString('principaluri'));
265
-		} else {
266
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
267
-		}
268
-
269
-		$result = $query->executeQuery();
270
-		$column = (int)$result->fetchOne();
271
-		$result->closeCursor();
272
-		return $column;
273
-	}
274
-
275
-	/**
276
-	 * @return array{id: int, deleted_at: int}[]
277
-	 */
278
-	public function getDeletedCalendars(int $deletedBefore): array {
279
-		$qb = $this->db->getQueryBuilder();
280
-		$qb->select(['id', 'deleted_at'])
281
-			->from('calendars')
282
-			->where($qb->expr()->isNotNull('deleted_at'))
283
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
284
-		$result = $qb->executeQuery();
285
-		$calendars = [];
286
-		while (($row = $result->fetchAssociative()) !== false) {
287
-			$calendars[] = [
288
-				'id' => (int)$row['id'],
289
-				'deleted_at' => (int)$row['deleted_at'],
290
-			];
291
-		}
292
-		$result->closeCursor();
293
-		return $calendars;
294
-	}
295
-
296
-	/**
297
-	 * Returns a list of calendars for a principal.
298
-	 *
299
-	 * Every project is an array with the following keys:
300
-	 *  * id, a unique id that will be used by other functions to modify the
301
-	 *    calendar. This can be the same as the uri or a database key.
302
-	 *  * uri, which the basename of the uri with which the calendar is
303
-	 *    accessed.
304
-	 *  * principaluri. The owner of the calendar. Almost always the same as
305
-	 *    principalUri passed to this method.
306
-	 *
307
-	 * Furthermore it can contain webdav properties in clark notation. A very
308
-	 * common one is '{DAV:}displayname'.
309
-	 *
310
-	 * Many clients also require:
311
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
312
-	 * For this property, you can just return an instance of
313
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
314
-	 *
315
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
316
-	 * ACL will automatically be put in read-only mode.
317
-	 *
318
-	 * @param string $principalUri
319
-	 * @return array
320
-	 */
321
-	public function getCalendarsForUser($principalUri) {
322
-		return $this->atomic(function () use ($principalUri) {
323
-			$principalUriOriginal = $principalUri;
324
-			$principalUri = $this->convertPrincipal($principalUri, true);
325
-			$fields = array_column($this->propertyMap, 0);
326
-			$fields[] = 'id';
327
-			$fields[] = 'uri';
328
-			$fields[] = 'synctoken';
329
-			$fields[] = 'components';
330
-			$fields[] = 'principaluri';
331
-			$fields[] = 'transparent';
332
-
333
-			// Making fields a comma-delimited list
334
-			$query = $this->db->getQueryBuilder();
335
-			$query->select($fields)
336
-				->from('calendars')
337
-				->orderBy('calendarorder', 'ASC');
338
-
339
-			if ($principalUri === '') {
340
-				$query->where($query->expr()->emptyString('principaluri'));
341
-			} else {
342
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
343
-			}
344
-
345
-			$result = $query->executeQuery();
346
-
347
-			$calendars = [];
348
-			while ($row = $result->fetchAssociative()) {
349
-				$row['principaluri'] = (string)$row['principaluri'];
350
-				$components = [];
351
-				if ($row['components']) {
352
-					$components = explode(',', $row['components']);
353
-				}
354
-
355
-				$calendar = [
356
-					'id' => $row['id'],
357
-					'uri' => $row['uri'],
358
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
360
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				];
365
-
366
-				$calendar = $this->rowToCalendar($row, $calendar);
367
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
368
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
369
-
370
-				if (!isset($calendars[$calendar['id']])) {
371
-					$calendars[$calendar['id']] = $calendar;
372
-				}
373
-			}
374
-			$result->closeCursor();
375
-
376
-			// query for shared calendars
377
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
378
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
379
-			$principals[] = $principalUri;
380
-
381
-			$fields = array_column($this->propertyMap, 0);
382
-			$fields = array_map(function (string $field) {
383
-				return 'a.' . $field;
384
-			}, $fields);
385
-			$fields[] = 'a.id';
386
-			$fields[] = 'a.uri';
387
-			$fields[] = 'a.synctoken';
388
-			$fields[] = 'a.components';
389
-			$fields[] = 'a.principaluri';
390
-			$fields[] = 'a.transparent';
391
-			$fields[] = 's.access';
392
-
393
-			$select = $this->db->getQueryBuilder();
394
-			$subSelect = $this->db->getQueryBuilder();
395
-
396
-			$subSelect->select('resourceid')
397
-				->from('dav_shares', 'd')
398
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
399
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
400
-
401
-			$select->select($fields)
402
-				->from('dav_shares', 's')
403
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
404
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
405
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
406
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
407
-
408
-			$results = $select->executeQuery();
409
-
410
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
411
-			while ($row = $results->fetchAssociative()) {
412
-				$row['principaluri'] = (string)$row['principaluri'];
413
-				if ($row['principaluri'] === $principalUri) {
414
-					continue;
415
-				}
416
-
417
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
418
-				if (isset($calendars[$row['id']])) {
419
-					if ($readOnly) {
420
-						// New share can not have more permissions than the old one.
421
-						continue;
422
-					}
423
-					if (isset($calendars[$row['id']][$readOnlyPropertyName])
424
-						&& $calendars[$row['id']][$readOnlyPropertyName] === 0) {
425
-						// Old share is already read-write, no more permissions can be gained
426
-						continue;
427
-					}
428
-				}
429
-
430
-				[, $name] = Uri\split($row['principaluri']);
431
-				$uri = $row['uri'] . '_shared_by_' . $name;
432
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
433
-				$components = [];
434
-				if ($row['components']) {
435
-					$components = explode(',', $row['components']);
436
-				}
437
-				$calendar = [
438
-					'id' => $row['id'],
439
-					'uri' => $uri,
440
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
442
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446
-					$readOnlyPropertyName => $readOnly,
447
-				];
448
-
449
-				$calendar = $this->rowToCalendar($row, $calendar);
450
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
451
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
452
-
453
-				$calendars[$calendar['id']] = $calendar;
454
-			}
455
-			$result->closeCursor();
456
-
457
-			return array_values($calendars);
458
-		}, $this->db);
459
-	}
460
-
461
-	/**
462
-	 * @param $principalUri
463
-	 * @return array
464
-	 */
465
-	public function getUsersOwnCalendars($principalUri) {
466
-		$principalUri = $this->convertPrincipal($principalUri, true);
467
-		$fields = array_column($this->propertyMap, 0);
468
-		$fields[] = 'id';
469
-		$fields[] = 'uri';
470
-		$fields[] = 'synctoken';
471
-		$fields[] = 'components';
472
-		$fields[] = 'principaluri';
473
-		$fields[] = 'transparent';
474
-		// Making fields a comma-delimited list
475
-		$query = $this->db->getQueryBuilder();
476
-		$query->select($fields)->from('calendars')
477
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
478
-			->orderBy('calendarorder', 'ASC');
479
-		$stmt = $query->executeQuery();
480
-		$calendars = [];
481
-		while ($row = $stmt->fetchAssociative()) {
482
-			$row['principaluri'] = (string)$row['principaluri'];
483
-			$components = [];
484
-			if ($row['components']) {
485
-				$components = explode(',', $row['components']);
486
-			}
487
-			$calendar = [
488
-				'id' => $row['id'],
489
-				'uri' => $row['uri'],
490
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
492
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
-			];
496
-
497
-			$calendar = $this->rowToCalendar($row, $calendar);
498
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
499
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
500
-
501
-			if (!isset($calendars[$calendar['id']])) {
502
-				$calendars[$calendar['id']] = $calendar;
503
-			}
504
-		}
505
-		$stmt->closeCursor();
506
-		return array_values($calendars);
507
-	}
508
-
509
-	/**
510
-	 * @return array
511
-	 */
512
-	public function getPublicCalendars() {
513
-		$fields = array_column($this->propertyMap, 0);
514
-		$fields[] = 'a.id';
515
-		$fields[] = 'a.uri';
516
-		$fields[] = 'a.synctoken';
517
-		$fields[] = 'a.components';
518
-		$fields[] = 'a.principaluri';
519
-		$fields[] = 'a.transparent';
520
-		$fields[] = 's.access';
521
-		$fields[] = 's.publicuri';
522
-		$calendars = [];
523
-		$query = $this->db->getQueryBuilder();
524
-		$result = $query->select($fields)
525
-			->from('dav_shares', 's')
526
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
527
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
528
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
529
-			->executeQuery();
530
-
531
-		while ($row = $result->fetchAssociative()) {
532
-			$row['principaluri'] = (string)$row['principaluri'];
533
-			[, $name] = Uri\split($row['principaluri']);
534
-			$row['displayname'] = $row['displayname'] . "($name)";
535
-			$components = [];
536
-			if ($row['components']) {
537
-				$components = explode(',', $row['components']);
538
-			}
539
-			$calendar = [
540
-				'id' => $row['id'],
541
-				'uri' => $row['publicuri'],
542
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
544
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
550
-			];
551
-
552
-			$calendar = $this->rowToCalendar($row, $calendar);
553
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
554
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
555
-
556
-			if (!isset($calendars[$calendar['id']])) {
557
-				$calendars[$calendar['id']] = $calendar;
558
-			}
559
-		}
560
-		$result->closeCursor();
561
-
562
-		return array_values($calendars);
563
-	}
564
-
565
-	/**
566
-	 * @param string $uri
567
-	 * @return array
568
-	 * @throws NotFound
569
-	 */
570
-	public function getPublicCalendar($uri) {
571
-		$fields = array_column($this->propertyMap, 0);
572
-		$fields[] = 'a.id';
573
-		$fields[] = 'a.uri';
574
-		$fields[] = 'a.synctoken';
575
-		$fields[] = 'a.components';
576
-		$fields[] = 'a.principaluri';
577
-		$fields[] = 'a.transparent';
578
-		$fields[] = 's.access';
579
-		$fields[] = 's.publicuri';
580
-		$query = $this->db->getQueryBuilder();
581
-		$result = $query->select($fields)
582
-			->from('dav_shares', 's')
583
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
584
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
585
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
586
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
587
-			->executeQuery();
588
-
589
-		$row = $result->fetchAssociative();
590
-
591
-		$result->closeCursor();
592
-
593
-		if ($row === false) {
594
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
595
-		}
596
-
597
-		$row['principaluri'] = (string)$row['principaluri'];
598
-		[, $name] = Uri\split($row['principaluri']);
599
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
600
-		$components = [];
601
-		if ($row['components']) {
602
-			$components = explode(',', $row['components']);
603
-		}
604
-		$calendar = [
605
-			'id' => $row['id'],
606
-			'uri' => $row['publicuri'],
607
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
609
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
615
-		];
616
-
617
-		$calendar = $this->rowToCalendar($row, $calendar);
618
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
619
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
620
-
621
-		return $calendar;
622
-	}
623
-
624
-	/**
625
-	 * @param string $principal
626
-	 * @param string $uri
627
-	 * @return array|null
628
-	 */
629
-	public function getCalendarByUri($principal, $uri) {
630
-		$fields = array_column($this->propertyMap, 0);
631
-		$fields[] = 'id';
632
-		$fields[] = 'uri';
633
-		$fields[] = 'synctoken';
634
-		$fields[] = 'components';
635
-		$fields[] = 'principaluri';
636
-		$fields[] = 'transparent';
637
-
638
-		// Making fields a comma-delimited list
639
-		$query = $this->db->getQueryBuilder();
640
-		$query->select($fields)->from('calendars')
641
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
642
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
643
-			->setMaxResults(1);
644
-		$stmt = $query->executeQuery();
645
-
646
-		$row = $stmt->fetchAssociative();
647
-		$stmt->closeCursor();
648
-		if ($row === false) {
649
-			return null;
650
-		}
651
-
652
-		$row['principaluri'] = (string)$row['principaluri'];
653
-		$components = [];
654
-		if ($row['components']) {
655
-			$components = explode(',', $row['components']);
656
-		}
657
-
658
-		$calendar = [
659
-			'id' => $row['id'],
660
-			'uri' => $row['uri'],
661
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
663
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
666
-		];
667
-
668
-		$calendar = $this->rowToCalendar($row, $calendar);
669
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
670
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
671
-
672
-		return $calendar;
673
-	}
674
-
675
-	/**
676
-	 * @psalm-return CalendarInfo|null
677
-	 * @return array|null
678
-	 */
679
-	public function getCalendarById(int $calendarId): ?array {
680
-		$fields = array_column($this->propertyMap, 0);
681
-		$fields[] = 'id';
682
-		$fields[] = 'uri';
683
-		$fields[] = 'synctoken';
684
-		$fields[] = 'components';
685
-		$fields[] = 'principaluri';
686
-		$fields[] = 'transparent';
687
-
688
-		// Making fields a comma-delimited list
689
-		$query = $this->db->getQueryBuilder();
690
-		$query->select($fields)->from('calendars')
691
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
692
-			->setMaxResults(1);
693
-		$stmt = $query->executeQuery();
694
-
695
-		$row = $stmt->fetchAssociative();
696
-		$stmt->closeCursor();
697
-		if ($row === false) {
698
-			return null;
699
-		}
700
-
701
-		$row['principaluri'] = (string)$row['principaluri'];
702
-		$components = [];
703
-		if ($row['components']) {
704
-			$components = explode(',', $row['components']);
705
-		}
706
-
707
-		$calendar = [
708
-			'id' => $row['id'],
709
-			'uri' => $row['uri'],
710
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
712
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
715
-		];
716
-
717
-		$calendar = $this->rowToCalendar($row, $calendar);
718
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
719
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
720
-
721
-		return $calendar;
722
-	}
723
-
724
-	/**
725
-	 * @param $subscriptionId
726
-	 */
727
-	public function getSubscriptionById($subscriptionId) {
728
-		$fields = array_column($this->subscriptionPropertyMap, 0);
729
-		$fields[] = 'id';
730
-		$fields[] = 'uri';
731
-		$fields[] = 'source';
732
-		$fields[] = 'synctoken';
733
-		$fields[] = 'principaluri';
734
-		$fields[] = 'lastmodified';
735
-
736
-		$query = $this->db->getQueryBuilder();
737
-		$query->select($fields)
738
-			->from('calendarsubscriptions')
739
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
740
-			->orderBy('calendarorder', 'asc');
741
-		$stmt = $query->executeQuery();
742
-
743
-		$row = $stmt->fetchAssociative();
744
-		$stmt->closeCursor();
745
-		if ($row === false) {
746
-			return null;
747
-		}
748
-
749
-		$row['principaluri'] = (string)$row['principaluri'];
750
-		$subscription = [
751
-			'id' => $row['id'],
752
-			'uri' => $row['uri'],
753
-			'principaluri' => $row['principaluri'],
754
-			'source' => $row['source'],
755
-			'lastmodified' => $row['lastmodified'],
756
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758
-		];
759
-
760
-		return $this->rowToSubscription($row, $subscription);
761
-	}
762
-
763
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
764
-		$fields = array_column($this->subscriptionPropertyMap, 0);
765
-		$fields[] = 'id';
766
-		$fields[] = 'uri';
767
-		$fields[] = 'source';
768
-		$fields[] = 'synctoken';
769
-		$fields[] = 'principaluri';
770
-		$fields[] = 'lastmodified';
771
-
772
-		$query = $this->db->getQueryBuilder();
773
-		$query->select($fields)
774
-			->from('calendarsubscriptions')
775
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
776
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
777
-			->setMaxResults(1);
778
-		$stmt = $query->executeQuery();
779
-
780
-		$row = $stmt->fetchAssociative();
781
-		$stmt->closeCursor();
782
-		if ($row === false) {
783
-			return null;
784
-		}
785
-
786
-		$row['principaluri'] = (string)$row['principaluri'];
787
-		$subscription = [
788
-			'id' => $row['id'],
789
-			'uri' => $row['uri'],
790
-			'principaluri' => $row['principaluri'],
791
-			'source' => $row['source'],
792
-			'lastmodified' => $row['lastmodified'],
793
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795
-		];
796
-
797
-		return $this->rowToSubscription($row, $subscription);
798
-	}
799
-
800
-	/**
801
-	 * Creates a new calendar for a principal.
802
-	 *
803
-	 * If the creation was a success, an id must be returned that can be used to reference
804
-	 * this calendar in other methods, such as updateCalendar.
805
-	 *
806
-	 * @param string $principalUri
807
-	 * @param string $calendarUri
808
-	 * @param array $properties
809
-	 * @return int
810
-	 *
811
-	 * @throws CalendarException
812
-	 */
813
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
814
-		if (strlen($calendarUri) > 255) {
815
-			throw new CalendarException('URI too long. Calendar not created');
816
-		}
817
-
818
-		$values = [
819
-			'principaluri' => $this->convertPrincipal($principalUri, true),
820
-			'uri' => $calendarUri,
821
-			'synctoken' => 1,
822
-			'transparent' => 0,
823
-			'components' => 'VEVENT,VTODO,VJOURNAL',
824
-			'displayname' => $calendarUri
825
-		];
826
-
827
-		// Default value
828
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829
-		if (isset($properties[$sccs])) {
830
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832
-			}
833
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
834
-		} elseif (isset($properties['components'])) {
835
-			// Allow to provide components internally without having
836
-			// to create a SupportedCalendarComponentSet object
837
-			$values['components'] = $properties['components'];
838
-		}
839
-
840
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
-		if (isset($properties[$transp])) {
842
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
843
-		}
844
-
845
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
846
-			if (isset($properties[$xmlName])) {
847
-				$values[$dbName] = $properties[$xmlName];
848
-			}
849
-		}
850
-
851
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
852
-			$query = $this->db->getQueryBuilder();
853
-			$query->insert('calendars');
854
-			foreach ($values as $column => $value) {
855
-				$query->setValue($column, $query->createNamedParameter($value));
856
-			}
857
-			$query->executeStatement();
858
-			$calendarId = $query->getLastInsertId();
859
-
860
-			$calendarData = $this->getCalendarById($calendarId);
861
-			return [$calendarId, $calendarData];
862
-		}, $this->db);
863
-
864
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
865
-
866
-		return $calendarId;
867
-	}
868
-
869
-	/**
870
-	 * Updates properties for a calendar.
871
-	 *
872
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
873
-	 * To do the actual updates, you must tell this object which properties
874
-	 * you're going to process with the handle() method.
875
-	 *
876
-	 * Calling the handle method is like telling the PropPatch object "I
877
-	 * promise I can handle updating this property".
878
-	 *
879
-	 * Read the PropPatch documentation for more info and examples.
880
-	 *
881
-	 * @param mixed $calendarId
882
-	 * @param PropPatch $propPatch
883
-	 * @return void
884
-	 */
885
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
886
-		$supportedProperties = array_keys($this->propertyMap);
887
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
888
-
889
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
890
-			$newValues = [];
891
-			foreach ($mutations as $propertyName => $propertyValue) {
892
-				switch ($propertyName) {
893
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
894
-						$fieldName = 'transparent';
895
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
896
-						break;
897
-					default:
898
-						$fieldName = $this->propertyMap[$propertyName][0];
899
-						$newValues[$fieldName] = $propertyValue;
900
-						break;
901
-				}
902
-			}
903
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
904
-				$query = $this->db->getQueryBuilder();
905
-				$query->update('calendars');
906
-				foreach ($newValues as $fieldName => $value) {
907
-					$query->set($fieldName, $query->createNamedParameter($value));
908
-				}
909
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
910
-				$query->executeStatement();
911
-
912
-				$this->addChanges($calendarId, [''], 2);
913
-
914
-				$calendarData = $this->getCalendarById($calendarId);
915
-				$shares = $this->getShares($calendarId);
916
-				return [$calendarData, $shares];
917
-			}, $this->db);
918
-
919
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
920
-
921
-			return true;
922
-		});
923
-	}
924
-
925
-	/**
926
-	 * Delete a calendar and all it's objects
927
-	 *
928
-	 * @param mixed $calendarId
929
-	 * @return void
930
-	 */
931
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
-		$this->publishStatusCache->remove((string)$calendarId);
933
-
934
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
935
-			// The calendar is deleted right away if this is either enforced by the caller
936
-			// or the special contacts birthday calendar or when the preference of an empty
937
-			// retention (0 seconds) is set, which signals a disabled trashbin.
938
-			$calendarData = $this->getCalendarById($calendarId);
939
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
940
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
941
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
942
-				$calendarData = $this->getCalendarById($calendarId);
943
-				$shares = $this->getShares($calendarId);
944
-
945
-				$this->purgeCalendarInvitations($calendarId);
946
-
947
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
948
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
949
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
950
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
-					->executeStatement();
952
-
953
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
954
-				$qbDeleteCalendarObjects->delete('calendarobjects')
955
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
956
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
957
-					->executeStatement();
958
-
959
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
960
-				$qbDeleteCalendarChanges->delete('calendarchanges')
961
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
962
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
963
-					->executeStatement();
964
-
965
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
966
-
967
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
968
-				$qbDeleteCalendar->delete('calendars')
969
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
970
-					->executeStatement();
971
-
972
-				// Only dispatch if we actually deleted anything
973
-				if ($calendarData) {
974
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
975
-				}
976
-			} else {
977
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
978
-				$qbMarkCalendarDeleted->update('calendars')
979
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
980
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
981
-					->executeStatement();
982
-
983
-				$calendarData = $this->getCalendarById($calendarId);
984
-				$shares = $this->getShares($calendarId);
985
-				if ($calendarData) {
986
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
987
-						$calendarId,
988
-						$calendarData,
989
-						$shares
990
-					));
991
-				}
992
-			}
993
-		}, $this->db);
994
-	}
995
-
996
-	public function restoreCalendar(int $id): void {
997
-		$this->atomic(function () use ($id): void {
998
-			$qb = $this->db->getQueryBuilder();
999
-			$update = $qb->update('calendars')
1000
-				->set('deleted_at', $qb->createNamedParameter(null))
1001
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1002
-			$update->executeStatement();
1003
-
1004
-			$calendarData = $this->getCalendarById($id);
1005
-			$shares = $this->getShares($id);
1006
-			if ($calendarData === null) {
1007
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1008
-			}
1009
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1010
-				$id,
1011
-				$calendarData,
1012
-				$shares
1013
-			));
1014
-		}, $this->db);
1015
-	}
1016
-
1017
-	/**
1018
-	 * Returns all calendar entries as a stream of data
1019
-	 *
1020
-	 * @since 32.0.0
1021
-	 *
1022
-	 * @return Generator<array>
1023
-	 */
1024
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1025
-		// extract options
1026
-		$rangeStart = $options?->getRangeStart();
1027
-		$rangeCount = $options?->getRangeCount();
1028
-		// construct query
1029
-		$qb = $this->db->getQueryBuilder();
1030
-		$qb->select('*')
1031
-			->from('calendarobjects')
1032
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1033
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1034
-			->andWhere($qb->expr()->isNull('deleted_at'));
1035
-		if ($rangeStart !== null) {
1036
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1037
-		}
1038
-		if ($rangeCount !== null) {
1039
-			$qb->setMaxResults($rangeCount);
1040
-		}
1041
-		if ($rangeStart !== null || $rangeCount !== null) {
1042
-			$qb->orderBy('uid', 'ASC');
1043
-		}
1044
-		$rs = $qb->executeQuery();
1045
-		// iterate through results
1046
-		try {
1047
-			while (($row = $rs->fetchAssociative()) !== false) {
1048
-				yield $row;
1049
-			}
1050
-		} finally {
1051
-			$rs->closeCursor();
1052
-		}
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns all calendar objects with limited metadata for a calendar
1057
-	 *
1058
-	 * Every item contains an array with the following keys:
1059
-	 *   * id - the table row id
1060
-	 *   * etag - An arbitrary string
1061
-	 *   * uri - a unique key which will be used to construct the uri. This can
1062
-	 *     be any arbitrary string.
1063
-	 *   * calendardata - The iCalendar-compatible calendar data
1064
-	 *
1065
-	 * @param mixed $calendarId
1066
-	 * @param int $calendarType
1067
-	 * @return array
1068
-	 */
1069
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, array $fields = []):array {
1070
-		$query = $this->db->getQueryBuilder();
1071
-		$query->select($fields ?: ['id', 'uid', 'etag', 'uri', 'calendardata'])
1072
-			->from('calendarobjects')
1073
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1074
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1075
-			->andWhere($query->expr()->isNull('deleted_at'));
1076
-		$stmt = $query->executeQuery();
1077
-
1078
-		$result = [];
1079
-		while (($row = $stmt->fetchAssociative()) !== false) {
1080
-			$result[$row['uid']] = $row;
1081
-		}
1082
-		$stmt->closeCursor();
1083
-
1084
-		return $result;
1085
-	}
1086
-
1087
-	/**
1088
-	 * Delete all of an user's shares
1089
-	 *
1090
-	 * @param string $principaluri
1091
-	 * @return void
1092
-	 */
1093
-	public function deleteAllSharesByUser($principaluri) {
1094
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1095
-	}
1096
-
1097
-	/**
1098
-	 * Returns all calendar objects within a calendar.
1099
-	 *
1100
-	 * Every item contains an array with the following keys:
1101
-	 *   * calendardata - The iCalendar-compatible calendar data
1102
-	 *   * uri - a unique key which will be used to construct the uri. This can
1103
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1104
-	 *     good idea. This is only the basename, or filename, not the full
1105
-	 *     path.
1106
-	 *   * lastmodified - a timestamp of the last modification time
1107
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1108
-	 *   '"abcdef"')
1109
-	 *   * size - The size of the calendar objects, in bytes.
1110
-	 *   * component - optional, a string containing the type of object, such
1111
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1112
-	 *     the Content-Type header.
1113
-	 *
1114
-	 * Note that the etag is optional, but it's highly encouraged to return for
1115
-	 * speed reasons.
1116
-	 *
1117
-	 * The calendardata is also optional. If it's not returned
1118
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1119
-	 * calendardata.
1120
-	 *
1121
-	 * If neither etag or size are specified, the calendardata will be
1122
-	 * used/fetched to determine these numbers. If both are specified the
1123
-	 * amount of times this is needed is reduced by a great degree.
1124
-	 *
1125
-	 * @param mixed $calendarId
1126
-	 * @param int $calendarType
1127
-	 * @return array
1128
-	 */
1129
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1130
-		$query = $this->db->getQueryBuilder();
1131
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1132
-			->from('calendarobjects')
1133
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1134
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1135
-			->andWhere($query->expr()->isNull('deleted_at'));
1136
-		$stmt = $query->executeQuery();
1137
-
1138
-		$result = [];
1139
-		while (($row = $stmt->fetchAssociative()) !== false) {
1140
-			$result[] = [
1141
-				'id' => $row['id'],
1142
-				'uri' => $row['uri'],
1143
-				'lastmodified' => $row['lastmodified'],
1144
-				'etag' => '"' . $row['etag'] . '"',
1145
-				'calendarid' => $row['calendarid'],
1146
-				'size' => (int)$row['size'],
1147
-				'component' => strtolower($row['componenttype']),
1148
-				'classification' => (int)$row['classification']
1149
-			];
1150
-		}
1151
-		$stmt->closeCursor();
1152
-
1153
-		return $result;
1154
-	}
1155
-
1156
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1157
-		$query = $this->db->getQueryBuilder();
1158
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1159
-			->from('calendarobjects', 'co')
1160
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1161
-			->where($query->expr()->isNotNull('co.deleted_at'))
1162
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1163
-		$stmt = $query->executeQuery();
1164
-
1165
-		$result = [];
1166
-		while (($row = $stmt->fetchAssociative()) !== false) {
1167
-			$result[] = [
1168
-				'id' => $row['id'],
1169
-				'uri' => $row['uri'],
1170
-				'lastmodified' => $row['lastmodified'],
1171
-				'etag' => '"' . $row['etag'] . '"',
1172
-				'calendarid' => (int)$row['calendarid'],
1173
-				'calendartype' => (int)$row['calendartype'],
1174
-				'size' => (int)$row['size'],
1175
-				'component' => strtolower($row['componenttype']),
1176
-				'classification' => (int)$row['classification'],
1177
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1178
-			];
1179
-		}
1180
-		$stmt->closeCursor();
1181
-
1182
-		return $result;
1183
-	}
1184
-
1185
-	/**
1186
-	 * Return all deleted calendar objects by the given principal that are not
1187
-	 * in deleted calendars.
1188
-	 *
1189
-	 * @param string $principalUri
1190
-	 * @return array
1191
-	 * @throws Exception
1192
-	 */
1193
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1194
-		$query = $this->db->getQueryBuilder();
1195
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1196
-			->selectAlias('c.uri', 'calendaruri')
1197
-			->from('calendarobjects', 'co')
1198
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1199
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1200
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1201
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1202
-		$stmt = $query->executeQuery();
1203
-
1204
-		$result = [];
1205
-		while ($row = $stmt->fetchAssociative()) {
1206
-			$result[] = [
1207
-				'id' => $row['id'],
1208
-				'uri' => $row['uri'],
1209
-				'lastmodified' => $row['lastmodified'],
1210
-				'etag' => '"' . $row['etag'] . '"',
1211
-				'calendarid' => $row['calendarid'],
1212
-				'calendaruri' => $row['calendaruri'],
1213
-				'size' => (int)$row['size'],
1214
-				'component' => strtolower($row['componenttype']),
1215
-				'classification' => (int)$row['classification'],
1216
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1217
-			];
1218
-		}
1219
-		$stmt->closeCursor();
1220
-
1221
-		return $result;
1222
-	}
1223
-
1224
-	/**
1225
-	 * Returns information from a single calendar object, based on it's object
1226
-	 * uri.
1227
-	 *
1228
-	 * The object uri is only the basename, or filename and not a full path.
1229
-	 *
1230
-	 * The returned array must have the same keys as getCalendarObjects. The
1231
-	 * 'calendardata' object is required here though, while it's not required
1232
-	 * for getCalendarObjects.
1233
-	 *
1234
-	 * This method must return null if the object did not exist.
1235
-	 *
1236
-	 * @param mixed $calendarId
1237
-	 * @param string $objectUri
1238
-	 * @param int $calendarType
1239
-	 * @return array|null
1240
-	 */
1241
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1242
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1243
-		if (isset($this->cachedObjects[$key])) {
1244
-			return $this->cachedObjects[$key];
1245
-		}
1246
-		$query = $this->db->getQueryBuilder();
1247
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1248
-			->from('calendarobjects')
1249
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1250
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1251
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1252
-		$stmt = $query->executeQuery();
1253
-		$row = $stmt->fetchAssociative();
1254
-		$stmt->closeCursor();
1255
-
1256
-		if (!$row) {
1257
-			return null;
1258
-		}
1259
-
1260
-		$object = $this->rowToCalendarObject($row);
1261
-		$this->cachedObjects[$key] = $object;
1262
-		return $object;
1263
-	}
1264
-
1265
-	private function rowToCalendarObject(array $row): array {
1266
-		return [
1267
-			'id' => $row['id'],
1268
-			'uri' => $row['uri'],
1269
-			'uid' => $row['uid'],
1270
-			'lastmodified' => $row['lastmodified'],
1271
-			'etag' => '"' . $row['etag'] . '"',
1272
-			'calendarid' => $row['calendarid'],
1273
-			'size' => (int)$row['size'],
1274
-			'calendardata' => $this->readBlob($row['calendardata']),
1275
-			'component' => strtolower($row['componenttype']),
1276
-			'classification' => (int)$row['classification'],
1277
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1278
-		];
1279
-	}
1280
-
1281
-	/**
1282
-	 * Returns a list of calendar objects.
1283
-	 *
1284
-	 * This method should work identical to getCalendarObject, but instead
1285
-	 * return all the calendar objects in the list as an array.
1286
-	 *
1287
-	 * If the backend supports this, it may allow for some speed-ups.
1288
-	 *
1289
-	 * @param mixed $calendarId
1290
-	 * @param string[] $uris
1291
-	 * @param int $calendarType
1292
-	 * @return array
1293
-	 */
1294
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1295
-		if (empty($uris)) {
1296
-			return [];
1297
-		}
1298
-
1299
-		$chunks = array_chunk($uris, 100);
1300
-		$objects = [];
1301
-
1302
-		$query = $this->db->getQueryBuilder();
1303
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1304
-			->from('calendarobjects')
1305
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1306
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1307
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1308
-			->andWhere($query->expr()->isNull('deleted_at'));
1309
-
1310
-		foreach ($chunks as $uris) {
1311
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1312
-			$result = $query->executeQuery();
1313
-
1314
-			while ($row = $result->fetchAssociative()) {
1315
-				$objects[] = [
1316
-					'id' => $row['id'],
1317
-					'uri' => $row['uri'],
1318
-					'lastmodified' => $row['lastmodified'],
1319
-					'etag' => '"' . $row['etag'] . '"',
1320
-					'calendarid' => $row['calendarid'],
1321
-					'size' => (int)$row['size'],
1322
-					'calendardata' => $this->readBlob($row['calendardata']),
1323
-					'component' => strtolower($row['componenttype']),
1324
-					'classification' => (int)$row['classification']
1325
-				];
1326
-			}
1327
-			$result->closeCursor();
1328
-		}
1329
-
1330
-		return $objects;
1331
-	}
1332
-
1333
-	/**
1334
-	 * Creates a new calendar object.
1335
-	 *
1336
-	 * The object uri is only the basename, or filename and not a full path.
1337
-	 *
1338
-	 * It is possible return an etag from this function, which will be used in
1339
-	 * the response to this PUT request. Note that the ETag must be surrounded
1340
-	 * by double-quotes.
1341
-	 *
1342
-	 * However, you should only really return this ETag if you don't mangle the
1343
-	 * calendar-data. If the result of a subsequent GET to this object is not
1344
-	 * the exact same as this request body, you should omit the ETag.
1345
-	 *
1346
-	 * @param mixed $calendarId
1347
-	 * @param string $objectUri
1348
-	 * @param string $calendarData
1349
-	 * @param int $calendarType
1350
-	 * @return string
1351
-	 */
1352
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1353
-		$this->cachedObjects = [];
1354
-		$extraData = $this->getDenormalizedData($calendarData);
1355
-
1356
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1357
-			// Try to detect duplicates
1358
-			$qb = $this->db->getQueryBuilder();
1359
-			$qb->select($qb->func()->count('*'))
1360
-				->from('calendarobjects')
1361
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1362
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1363
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1364
-				->andWhere($qb->expr()->isNull('deleted_at'));
1365
-			$result = $qb->executeQuery();
1366
-			$count = (int)$result->fetchOne();
1367
-			$result->closeCursor();
1368
-
1369
-			if ($count !== 0) {
1370
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1371
-			}
1372
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1373
-			$qbDel = $this->db->getQueryBuilder();
1374
-			$qbDel->select('*')
1375
-				->from('calendarobjects')
1376
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1377
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1378
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1379
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1380
-			$result = $qbDel->executeQuery();
1381
-			$found = $result->fetchAssociative();
1382
-			$result->closeCursor();
1383
-			if ($found !== false) {
1384
-				// the object existed previously but has been deleted
1385
-				// remove the trashbin entry and continue as if it was a new object
1386
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1387
-			}
1388
-
1389
-			$query = $this->db->getQueryBuilder();
1390
-			$query->insert('calendarobjects')
1391
-				->values([
1392
-					'calendarid' => $query->createNamedParameter($calendarId),
1393
-					'uri' => $query->createNamedParameter($objectUri),
1394
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1395
-					'lastmodified' => $query->createNamedParameter(time()),
1396
-					'etag' => $query->createNamedParameter($extraData['etag']),
1397
-					'size' => $query->createNamedParameter($extraData['size']),
1398
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1399
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1400
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1401
-					'classification' => $query->createNamedParameter($extraData['classification']),
1402
-					'uid' => $query->createNamedParameter($extraData['uid']),
1403
-					'calendartype' => $query->createNamedParameter($calendarType),
1404
-				])
1405
-				->executeStatement();
1406
-
1407
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1408
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1409
-
1410
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1411
-			assert($objectRow !== null);
1412
-
1413
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1414
-				$calendarRow = $this->getCalendarById($calendarId);
1415
-				$shares = $this->getShares($calendarId);
1416
-
1417
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1418
-			} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1419
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1420
-
1421
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1422
-			} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1423
-				// TODO: implement custom event for federated calendars
1424
-			}
1425
-
1426
-			return '"' . $extraData['etag'] . '"';
1427
-		}, $this->db);
1428
-	}
1429
-
1430
-	/**
1431
-	 * Updates an existing calendarobject, based on it's uri.
1432
-	 *
1433
-	 * The object uri is only the basename, or filename and not a full path.
1434
-	 *
1435
-	 * It is possible return an etag from this function, which will be used in
1436
-	 * the response to this PUT request. Note that the ETag must be surrounded
1437
-	 * by double-quotes.
1438
-	 *
1439
-	 * However, you should only really return this ETag if you don't mangle the
1440
-	 * calendar-data. If the result of a subsequent GET to this object is not
1441
-	 * the exact same as this request body, you should omit the ETag.
1442
-	 *
1443
-	 * @param mixed $calendarId
1444
-	 * @param string $objectUri
1445
-	 * @param string $calendarData
1446
-	 * @param int $calendarType
1447
-	 * @return string
1448
-	 */
1449
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1450
-		$this->cachedObjects = [];
1451
-		$extraData = $this->getDenormalizedData($calendarData);
1452
-
1453
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1454
-			$query = $this->db->getQueryBuilder();
1455
-			$query->update('calendarobjects')
1456
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1457
-				->set('lastmodified', $query->createNamedParameter(time()))
1458
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1459
-				->set('size', $query->createNamedParameter($extraData['size']))
1460
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1461
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1462
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1463
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1464
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1465
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1466
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1467
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1468
-				->executeStatement();
1469
-
1470
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1471
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1472
-
1473
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1474
-			if (is_array($objectRow)) {
1475
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1476
-					$calendarRow = $this->getCalendarById($calendarId);
1477
-					$shares = $this->getShares($calendarId);
1478
-
1479
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1480
-				} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1481
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1482
-
1483
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1484
-				} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1485
-					// TODO: implement custom event for federated calendars
1486
-				}
1487
-			}
1488
-
1489
-			return '"' . $extraData['etag'] . '"';
1490
-		}, $this->db);
1491
-	}
1492
-
1493
-	/**
1494
-	 * Moves a calendar object from calendar to calendar.
1495
-	 *
1496
-	 * @param string $sourcePrincipalUri
1497
-	 * @param int $sourceObjectId
1498
-	 * @param string $targetPrincipalUri
1499
-	 * @param int $targetCalendarId
1500
-	 * @param string $tragetObjectUri
1501
-	 * @param int $calendarType
1502
-	 * @return bool
1503
-	 * @throws Exception
1504
-	 */
1505
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1506
-		$this->cachedObjects = [];
1507
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1508
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1509
-			if (empty($object)) {
1510
-				return false;
1511
-			}
1512
-
1513
-			$sourceCalendarId = $object['calendarid'];
1514
-			$sourceObjectUri = $object['uri'];
1515
-
1516
-			$query = $this->db->getQueryBuilder();
1517
-			$query->update('calendarobjects')
1518
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1519
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1520
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1521
-				->executeStatement();
1522
-
1523
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1524
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1525
-
1526
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1527
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1528
-
1529
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1530
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1531
-			if (empty($object)) {
1532
-				return false;
1533
-			}
1534
-
1535
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1536
-			// the calendar this event is being moved to does not exist any longer
1537
-			if (empty($targetCalendarRow)) {
1538
-				return false;
1539
-			}
1540
-
1541
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1542
-				$sourceShares = $this->getShares($sourceCalendarId);
1543
-				$targetShares = $this->getShares($targetCalendarId);
1544
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1545
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1546
-			}
1547
-			return true;
1548
-		}, $this->db);
1549
-	}
1550
-
1551
-	/**
1552
-	 * Deletes an existing calendar object.
1553
-	 *
1554
-	 * The object uri is only the basename, or filename and not a full path.
1555
-	 *
1556
-	 * @param mixed $calendarId
1557
-	 * @param string $objectUri
1558
-	 * @param int $calendarType
1559
-	 * @param bool $forceDeletePermanently
1560
-	 * @return void
1561
-	 */
1562
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1563
-		$this->cachedObjects = [];
1564
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1565
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1566
-
1567
-			if ($data === null) {
1568
-				// Nothing to delete
1569
-				return;
1570
-			}
1571
-
1572
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1573
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1574
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1575
-
1576
-				$this->purgeProperties($calendarId, $data['id']);
1577
-
1578
-				$this->purgeObjectInvitations($data['uid']);
1579
-
1580
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1581
-					$calendarRow = $this->getCalendarById($calendarId);
1582
-					$shares = $this->getShares($calendarId);
1583
-
1584
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1585
-				} else {
1586
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1587
-
1588
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1589
-				}
1590
-			} else {
1591
-				$pathInfo = pathinfo($data['uri']);
1592
-				if (!empty($pathInfo['extension'])) {
1593
-					// Append a suffix to "free" the old URI for recreation
1594
-					$newUri = sprintf(
1595
-						'%s-deleted.%s',
1596
-						$pathInfo['filename'],
1597
-						$pathInfo['extension']
1598
-					);
1599
-				} else {
1600
-					$newUri = sprintf(
1601
-						'%s-deleted',
1602
-						$pathInfo['filename']
1603
-					);
1604
-				}
1605
-
1606
-				// Try to detect conflicts before the DB does
1607
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1608
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1609
-				if ($newObject !== null) {
1610
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1611
-				}
1612
-
1613
-				$qb = $this->db->getQueryBuilder();
1614
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1615
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1616
-					->set('uri', $qb->createNamedParameter($newUri))
1617
-					->where(
1618
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1619
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1620
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1621
-					);
1622
-				$markObjectDeletedQuery->executeStatement();
1623
-
1624
-				$calendarData = $this->getCalendarById($calendarId);
1625
-				if ($calendarData !== null) {
1626
-					$this->dispatcher->dispatchTyped(
1627
-						new CalendarObjectMovedToTrashEvent(
1628
-							$calendarId,
1629
-							$calendarData,
1630
-							$this->getShares($calendarId),
1631
-							$data
1632
-						)
1633
-					);
1634
-				}
1635
-			}
1636
-
1637
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1638
-		}, $this->db);
1639
-	}
1640
-
1641
-	/**
1642
-	 * @param mixed $objectData
1643
-	 *
1644
-	 * @throws Forbidden
1645
-	 */
1646
-	public function restoreCalendarObject(array $objectData): void {
1647
-		$this->cachedObjects = [];
1648
-		$this->atomic(function () use ($objectData): void {
1649
-			$id = (int)$objectData['id'];
1650
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1651
-			$targetObject = $this->getCalendarObject(
1652
-				$objectData['calendarid'],
1653
-				$restoreUri
1654
-			);
1655
-			if ($targetObject !== null) {
1656
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1657
-			}
1658
-
1659
-			$qb = $this->db->getQueryBuilder();
1660
-			$update = $qb->update('calendarobjects')
1661
-				->set('uri', $qb->createNamedParameter($restoreUri))
1662
-				->set('deleted_at', $qb->createNamedParameter(null))
1663
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1664
-			$update->executeStatement();
1665
-
1666
-			// Make sure this change is tracked in the changes table
1667
-			$qb2 = $this->db->getQueryBuilder();
1668
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1669
-				->selectAlias('componenttype', 'component')
1670
-				->from('calendarobjects')
1671
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1672
-			$result = $selectObject->executeQuery();
1673
-			$row = $result->fetchAssociative();
1674
-			$result->closeCursor();
1675
-			if ($row === false) {
1676
-				// Welp, this should possibly not have happened, but let's ignore
1677
-				return;
1678
-			}
1679
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1680
-
1681
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1682
-			if ($calendarRow === null) {
1683
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1684
-			}
1685
-			$this->dispatcher->dispatchTyped(
1686
-				new CalendarObjectRestoredEvent(
1687
-					(int)$objectData['calendarid'],
1688
-					$calendarRow,
1689
-					$this->getShares((int)$row['calendarid']),
1690
-					$row
1691
-				)
1692
-			);
1693
-		}, $this->db);
1694
-	}
1695
-
1696
-	/**
1697
-	 * Performs a calendar-query on the contents of this calendar.
1698
-	 *
1699
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1700
-	 * calendar-query it is possible for a client to request a specific set of
1701
-	 * object, based on contents of iCalendar properties, date-ranges and
1702
-	 * iCalendar component types (VTODO, VEVENT).
1703
-	 *
1704
-	 * This method should just return a list of (relative) urls that match this
1705
-	 * query.
1706
-	 *
1707
-	 * The list of filters are specified as an array. The exact array is
1708
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1709
-	 *
1710
-	 * Note that it is extremely likely that getCalendarObject for every path
1711
-	 * returned from this method will be called almost immediately after. You
1712
-	 * may want to anticipate this to speed up these requests.
1713
-	 *
1714
-	 * This method provides a default implementation, which parses *all* the
1715
-	 * iCalendar objects in the specified calendar.
1716
-	 *
1717
-	 * This default may well be good enough for personal use, and calendars
1718
-	 * that aren't very large. But if you anticipate high usage, big calendars
1719
-	 * or high loads, you are strongly advised to optimize certain paths.
1720
-	 *
1721
-	 * The best way to do so is override this method and to optimize
1722
-	 * specifically for 'common filters'.
1723
-	 *
1724
-	 * Requests that are extremely common are:
1725
-	 *   * requests for just VEVENTS
1726
-	 *   * requests for just VTODO
1727
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1728
-	 *
1729
-	 * ..and combinations of these requests. It may not be worth it to try to
1730
-	 * handle every possible situation and just rely on the (relatively
1731
-	 * easy to use) CalendarQueryValidator to handle the rest.
1732
-	 *
1733
-	 * Note that especially time-range-filters may be difficult to parse. A
1734
-	 * time-range filter specified on a VEVENT must for instance also handle
1735
-	 * recurrence rules correctly.
1736
-	 * A good example of how to interpret all these filters can also simply
1737
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1738
-	 * as possible, so it gives you a good idea on what type of stuff you need
1739
-	 * to think of.
1740
-	 *
1741
-	 * @param mixed $calendarId
1742
-	 * @param array $filters
1743
-	 * @param int $calendarType
1744
-	 * @return array
1745
-	 */
1746
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1747
-		$componentType = null;
1748
-		$requirePostFilter = true;
1749
-		$timeRange = null;
1750
-
1751
-		// if no filters were specified, we don't need to filter after a query
1752
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1753
-			$requirePostFilter = false;
1754
-		}
1755
-
1756
-		// Figuring out if there's a component filter
1757
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1758
-			$componentType = $filters['comp-filters'][0]['name'];
1759
-
1760
-			// Checking if we need post-filters
1761
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1762
-				$requirePostFilter = false;
1763
-			}
1764
-			// There was a time-range filter
1765
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1766
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1767
-
1768
-				// If start time OR the end time is not specified, we can do a
1769
-				// 100% accurate mysql query.
1770
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1771
-					$requirePostFilter = false;
1772
-				}
1773
-			}
1774
-		}
1775
-		$query = $this->db->getQueryBuilder();
1776
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1777
-			->from('calendarobjects')
1778
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1779
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1780
-			->andWhere($query->expr()->isNull('deleted_at'));
1781
-
1782
-		if ($componentType) {
1783
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1784
-		}
1785
-
1786
-		if ($timeRange && $timeRange['start']) {
1787
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1788
-		}
1789
-		if ($timeRange && $timeRange['end']) {
1790
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1791
-		}
1792
-
1793
-		$stmt = $query->executeQuery();
1794
-
1795
-		$result = [];
1796
-		while ($row = $stmt->fetchAssociative()) {
1797
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1798
-			if (isset($row['calendardata'])) {
1799
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1800
-			}
1801
-
1802
-			if ($requirePostFilter) {
1803
-				// validateFilterForObject will parse the calendar data
1804
-				// catch parsing errors
1805
-				try {
1806
-					$matches = $this->validateFilterForObject($row, $filters);
1807
-				} catch (ParseException $ex) {
1808
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1809
-						'app' => 'dav',
1810
-						'exception' => $ex,
1811
-					]);
1812
-					continue;
1813
-				} catch (InvalidDataException $ex) {
1814
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1815
-						'app' => 'dav',
1816
-						'exception' => $ex,
1817
-					]);
1818
-					continue;
1819
-				} catch (MaxInstancesExceededException $ex) {
1820
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1821
-						'app' => 'dav',
1822
-						'exception' => $ex,
1823
-					]);
1824
-					continue;
1825
-				}
1826
-
1827
-				if (!$matches) {
1828
-					continue;
1829
-				}
1830
-			}
1831
-			$result[] = $row['uri'];
1832
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1833
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1834
-		}
1835
-
1836
-		return $result;
1837
-	}
1838
-
1839
-	/**
1840
-	 * custom Nextcloud search extension for CalDAV
1841
-	 *
1842
-	 * TODO - this should optionally cover cached calendar objects as well
1843
-	 *
1844
-	 * @param string $principalUri
1845
-	 * @param array $filters
1846
-	 * @param integer|null $limit
1847
-	 * @param integer|null $offset
1848
-	 * @return array
1849
-	 */
1850
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1851
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1852
-			$calendars = $this->getCalendarsForUser($principalUri);
1853
-			$ownCalendars = [];
1854
-			$sharedCalendars = [];
1855
-
1856
-			$uriMapper = [];
1857
-
1858
-			foreach ($calendars as $calendar) {
1859
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1860
-					$ownCalendars[] = $calendar['id'];
1861
-				} else {
1862
-					$sharedCalendars[] = $calendar['id'];
1863
-				}
1864
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1865
-			}
1866
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1867
-				return [];
1868
-			}
1869
-
1870
-			$query = $this->db->getQueryBuilder();
1871
-			// Calendar id expressions
1872
-			$calendarExpressions = [];
1873
-			foreach ($ownCalendars as $id) {
1874
-				$calendarExpressions[] = $query->expr()->andX(
1875
-					$query->expr()->eq('c.calendarid',
1876
-						$query->createNamedParameter($id)),
1877
-					$query->expr()->eq('c.calendartype',
1878
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1879
-			}
1880
-			foreach ($sharedCalendars as $id) {
1881
-				$calendarExpressions[] = $query->expr()->andX(
1882
-					$query->expr()->eq('c.calendarid',
1883
-						$query->createNamedParameter($id)),
1884
-					$query->expr()->eq('c.classification',
1885
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1886
-					$query->expr()->eq('c.calendartype',
1887
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1888
-			}
1889
-
1890
-			if (count($calendarExpressions) === 1) {
1891
-				$calExpr = $calendarExpressions[0];
1892
-			} else {
1893
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1894
-			}
1895
-
1896
-			// Component expressions
1897
-			$compExpressions = [];
1898
-			foreach ($filters['comps'] as $comp) {
1899
-				$compExpressions[] = $query->expr()
1900
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1901
-			}
1902
-
1903
-			if (count($compExpressions) === 1) {
1904
-				$compExpr = $compExpressions[0];
1905
-			} else {
1906
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1907
-			}
1908
-
1909
-			if (!isset($filters['props'])) {
1910
-				$filters['props'] = [];
1911
-			}
1912
-			if (!isset($filters['params'])) {
1913
-				$filters['params'] = [];
1914
-			}
1915
-
1916
-			$propParamExpressions = [];
1917
-			foreach ($filters['props'] as $prop) {
1918
-				$propParamExpressions[] = $query->expr()->andX(
1919
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1920
-					$query->expr()->isNull('i.parameter')
1921
-				);
1922
-			}
1923
-			foreach ($filters['params'] as $param) {
1924
-				$propParamExpressions[] = $query->expr()->andX(
1925
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1926
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1927
-				);
1928
-			}
1929
-
1930
-			if (count($propParamExpressions) === 1) {
1931
-				$propParamExpr = $propParamExpressions[0];
1932
-			} else {
1933
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1934
-			}
1935
-
1936
-			$query->select(['c.calendarid', 'c.uri'])
1937
-				->from($this->dbObjectPropertiesTable, 'i')
1938
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1939
-				->where($calExpr)
1940
-				->andWhere($compExpr)
1941
-				->andWhere($propParamExpr)
1942
-				->andWhere($query->expr()->iLike('i.value',
1943
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1944
-				->andWhere($query->expr()->isNull('deleted_at'));
1945
-
1946
-			if ($offset) {
1947
-				$query->setFirstResult($offset);
1948
-			}
1949
-			if ($limit) {
1950
-				$query->setMaxResults($limit);
1951
-			}
1952
-
1953
-			$stmt = $query->executeQuery();
1954
-
1955
-			$result = [];
1956
-			while ($row = $stmt->fetchAssociative()) {
1957
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1958
-				if (!in_array($path, $result)) {
1959
-					$result[] = $path;
1960
-				}
1961
-			}
1962
-
1963
-			return $result;
1964
-		}, $this->db);
1965
-	}
1966
-
1967
-	/**
1968
-	 * used for Nextcloud's calendar API
1969
-	 *
1970
-	 * @param array $calendarInfo
1971
-	 * @param string $pattern
1972
-	 * @param array $searchProperties
1973
-	 * @param array $options
1974
-	 * @param integer|null $limit
1975
-	 * @param integer|null $offset
1976
-	 *
1977
-	 * @return array
1978
-	 */
1979
-	public function search(
1980
-		array $calendarInfo,
1981
-		$pattern,
1982
-		array $searchProperties,
1983
-		array $options,
1984
-		$limit,
1985
-		$offset,
1986
-	) {
1987
-		$outerQuery = $this->db->getQueryBuilder();
1988
-		$innerQuery = $this->db->getQueryBuilder();
1989
-
1990
-		if (isset($calendarInfo['source'])) {
1991
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1992
-		} elseif (isset($calendarInfo['federated'])) {
1993
-			$calendarType = self::CALENDAR_TYPE_FEDERATED;
1994
-		} else {
1995
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
1996
-		}
1997
-
1998
-		$innerQuery->selectDistinct('op.objectid')
1999
-			->from($this->dbObjectPropertiesTable, 'op')
2000
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
2001
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
2002
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
2003
-				$outerQuery->createNamedParameter($calendarType)));
2004
-
2005
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2006
-			->from('calendarobjects', 'c')
2007
-			->where($outerQuery->expr()->isNull('deleted_at'));
2008
-
2009
-		// only return public items for shared calendars for now
2010
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2011
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2012
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2013
-		}
2014
-
2015
-		if (!empty($searchProperties)) {
2016
-			$or = [];
2017
-			foreach ($searchProperties as $searchProperty) {
2018
-				$or[] = $innerQuery->expr()->eq('op.name',
2019
-					$outerQuery->createNamedParameter($searchProperty));
2020
-			}
2021
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2022
-		}
2023
-
2024
-		if ($pattern !== '') {
2025
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2026
-				$outerQuery->createNamedParameter('%'
2027
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2028
-		}
2029
-
2030
-		$start = null;
2031
-		$end = null;
2032
-
2033
-		$hasLimit = is_int($limit);
2034
-		$hasTimeRange = false;
2035
-
2036
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2037
-			/** @var DateTimeInterface $start */
2038
-			$start = $options['timerange']['start'];
2039
-			$outerQuery->andWhere(
2040
-				$outerQuery->expr()->gt(
2041
-					'lastoccurence',
2042
-					$outerQuery->createNamedParameter($start->getTimestamp())
2043
-				)
2044
-			);
2045
-			$hasTimeRange = true;
2046
-		}
2047
-
2048
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2049
-			/** @var DateTimeInterface $end */
2050
-			$end = $options['timerange']['end'];
2051
-			$outerQuery->andWhere(
2052
-				$outerQuery->expr()->lt(
2053
-					'firstoccurence',
2054
-					$outerQuery->createNamedParameter($end->getTimestamp())
2055
-				)
2056
-			);
2057
-			$hasTimeRange = true;
2058
-		}
2059
-
2060
-		if (isset($options['uid'])) {
2061
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2062
-		}
2063
-
2064
-		if (!empty($options['types'])) {
2065
-			$or = [];
2066
-			foreach ($options['types'] as $type) {
2067
-				$or[] = $outerQuery->expr()->eq('componenttype',
2068
-					$outerQuery->createNamedParameter($type));
2069
-			}
2070
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2071
-		}
2072
-
2073
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2074
-
2075
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2076
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2077
-		$outerQuery->addOrderBy('id');
2078
-
2079
-		$offset = (int)$offset;
2080
-		$outerQuery->setFirstResult($offset);
2081
-
2082
-		$calendarObjects = [];
2083
-
2084
-		if ($hasLimit && $hasTimeRange) {
2085
-			/**
2086
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2087
-			 *
2088
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2089
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2090
-			 *
2091
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2092
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2093
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2094
-			 *
2095
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2096
-			 * and retrying if we have not reached the limit.
2097
-			 *
2098
-			 * 25 rows and 3 retries is entirely arbitrary.
2099
-			 */
2100
-			$maxResults = (int)max($limit, 25);
2101
-			$outerQuery->setMaxResults($maxResults);
2102
-
2103
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2104
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2105
-				$outerQuery->setFirstResult($offset += $maxResults);
2106
-			}
2107
-
2108
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2109
-		} else {
2110
-			$outerQuery->setMaxResults($limit);
2111
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2112
-		}
2113
-
2114
-		$calendarObjects = array_map(function ($o) use ($options) {
2115
-			$calendarData = Reader::read($o['calendardata']);
2116
-
2117
-			// Expand recurrences if an explicit time range is requested
2118
-			if ($calendarData instanceof VCalendar
2119
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2120
-				$calendarData = $calendarData->expand(
2121
-					$options['timerange']['start'],
2122
-					$options['timerange']['end'],
2123
-				);
2124
-			}
2125
-
2126
-			$comps = $calendarData->getComponents();
2127
-			$objects = [];
2128
-			$timezones = [];
2129
-			foreach ($comps as $comp) {
2130
-				if ($comp instanceof VTimeZone) {
2131
-					$timezones[] = $comp;
2132
-				} else {
2133
-					$objects[] = $comp;
2134
-				}
2135
-			}
2136
-
2137
-			return [
2138
-				'id' => $o['id'],
2139
-				'type' => $o['componenttype'],
2140
-				'uid' => $o['uid'],
2141
-				'uri' => $o['uri'],
2142
-				'objects' => array_map(function ($c) {
2143
-					return $this->transformSearchData($c);
2144
-				}, $objects),
2145
-				'timezones' => array_map(function ($c) {
2146
-					return $this->transformSearchData($c);
2147
-				}, $timezones),
2148
-			];
2149
-		}, $calendarObjects);
2150
-
2151
-		usort($calendarObjects, function (array $a, array $b) {
2152
-			/** @var DateTimeImmutable $startA */
2153
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2154
-			/** @var DateTimeImmutable $startB */
2155
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2156
-
2157
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2158
-		});
2159
-
2160
-		return $calendarObjects;
2161
-	}
2162
-
2163
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2164
-		$calendarObjects = [];
2165
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2166
-
2167
-		$result = $query->executeQuery();
2168
-
2169
-		while (($row = $result->fetchAssociative()) !== false) {
2170
-			if ($filterByTimeRange === false) {
2171
-				// No filter required
2172
-				$calendarObjects[] = $row;
2173
-				continue;
2174
-			}
2175
-
2176
-			try {
2177
-				$isValid = $this->validateFilterForObject($row, [
2178
-					'name' => 'VCALENDAR',
2179
-					'comp-filters' => [
2180
-						[
2181
-							'name' => 'VEVENT',
2182
-							'comp-filters' => [],
2183
-							'prop-filters' => [],
2184
-							'is-not-defined' => false,
2185
-							'time-range' => [
2186
-								'start' => $start,
2187
-								'end' => $end,
2188
-							],
2189
-						],
2190
-					],
2191
-					'prop-filters' => [],
2192
-					'is-not-defined' => false,
2193
-					'time-range' => null,
2194
-				]);
2195
-			} catch (MaxInstancesExceededException $ex) {
2196
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2197
-					'app' => 'dav',
2198
-					'exception' => $ex,
2199
-				]);
2200
-				continue;
2201
-			}
2202
-
2203
-			if (is_resource($row['calendardata'])) {
2204
-				// Put the stream back to the beginning so it can be read another time
2205
-				rewind($row['calendardata']);
2206
-			}
2207
-
2208
-			if ($isValid) {
2209
-				$calendarObjects[] = $row;
2210
-			}
2211
-		}
2212
-
2213
-		$result->closeCursor();
2214
-
2215
-		return $calendarObjects;
2216
-	}
2217
-
2218
-	/**
2219
-	 * @param Component $comp
2220
-	 * @return array
2221
-	 */
2222
-	private function transformSearchData(Component $comp) {
2223
-		$data = [];
2224
-		/** @var Component[] $subComponents */
2225
-		$subComponents = $comp->getComponents();
2226
-		/** @var Property[] $properties */
2227
-		$properties = array_filter($comp->children(), function ($c) {
2228
-			return $c instanceof Property;
2229
-		});
2230
-		$validationRules = $comp->getValidationRules();
2231
-
2232
-		foreach ($subComponents as $subComponent) {
2233
-			$name = $subComponent->name;
2234
-			if (!isset($data[$name])) {
2235
-				$data[$name] = [];
2236
-			}
2237
-			$data[$name][] = $this->transformSearchData($subComponent);
2238
-		}
2239
-
2240
-		foreach ($properties as $property) {
2241
-			$name = $property->name;
2242
-			if (!isset($validationRules[$name])) {
2243
-				$validationRules[$name] = '*';
2244
-			}
2245
-
2246
-			$rule = $validationRules[$property->name];
2247
-			if ($rule === '+' || $rule === '*') { // multiple
2248
-				if (!isset($data[$name])) {
2249
-					$data[$name] = [];
2250
-				}
2251
-
2252
-				$data[$name][] = $this->transformSearchProperty($property);
2253
-			} else { // once
2254
-				$data[$name] = $this->transformSearchProperty($property);
2255
-			}
2256
-		}
2257
-
2258
-		return $data;
2259
-	}
2260
-
2261
-	/**
2262
-	 * @param Property $prop
2263
-	 * @return array
2264
-	 */
2265
-	private function transformSearchProperty(Property $prop) {
2266
-		// No need to check Date, as it extends DateTime
2267
-		if ($prop instanceof Property\ICalendar\DateTime) {
2268
-			$value = $prop->getDateTime();
2269
-		} else {
2270
-			$value = $prop->getValue();
2271
-		}
2272
-
2273
-		return [
2274
-			$value,
2275
-			$prop->parameters()
2276
-		];
2277
-	}
2278
-
2279
-	/**
2280
-	 * @param string $principalUri
2281
-	 * @param string $pattern
2282
-	 * @param array $componentTypes
2283
-	 * @param array $searchProperties
2284
-	 * @param array $searchParameters
2285
-	 * @param array $options
2286
-	 * @return array
2287
-	 */
2288
-	public function searchPrincipalUri(string $principalUri,
2289
-		string $pattern,
2290
-		array $componentTypes,
2291
-		array $searchProperties,
2292
-		array $searchParameters,
2293
-		array $options = [],
2294
-	): array {
2295
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2296
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2297
-
2298
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2299
-			$calendarOr = [];
2300
-			$searchOr = [];
2301
-
2302
-			// Fetch calendars and subscription
2303
-			$calendars = $this->getCalendarsForUser($principalUri);
2304
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2305
-			foreach ($calendars as $calendar) {
2306
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2307
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2308
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2309
-				);
2310
-
2311
-				// If it's shared, limit search to public events
2312
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2313
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2314
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2315
-				}
2316
-
2317
-				$calendarOr[] = $calendarAnd;
2318
-			}
2319
-			foreach ($subscriptions as $subscription) {
2320
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2321
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2322
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2323
-				);
2324
-
2325
-				// If it's shared, limit search to public events
2326
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2327
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2328
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2329
-				}
2330
-
2331
-				$calendarOr[] = $subscriptionAnd;
2332
-			}
2333
-
2334
-			foreach ($searchProperties as $property) {
2335
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2336
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2337
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2338
-				);
2339
-
2340
-				$searchOr[] = $propertyAnd;
2341
-			}
2342
-			foreach ($searchParameters as $property => $parameter) {
2343
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2344
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2345
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2346
-				);
2347
-
2348
-				$searchOr[] = $parameterAnd;
2349
-			}
2350
-
2351
-			if (empty($calendarOr)) {
2352
-				return [];
2353
-			}
2354
-			if (empty($searchOr)) {
2355
-				return [];
2356
-			}
2357
-
2358
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2359
-				->from($this->dbObjectPropertiesTable, 'cob')
2360
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2361
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2362
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2363
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2364
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2365
-
2366
-			if ($pattern !== '') {
2367
-				if (!$escapePattern) {
2368
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2369
-				} else {
2370
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2371
-				}
2372
-			}
2373
-
2374
-			if (isset($options['limit'])) {
2375
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2376
-			}
2377
-			if (isset($options['offset'])) {
2378
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2379
-			}
2380
-			if (isset($options['timerange'])) {
2381
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2382
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2383
-						'lastoccurence',
2384
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2385
-					));
2386
-				}
2387
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2388
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2389
-						'firstoccurence',
2390
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2391
-					));
2392
-				}
2393
-			}
2394
-
2395
-			$result = $calendarObjectIdQuery->executeQuery();
2396
-			$matches = [];
2397
-			while (($row = $result->fetchAssociative()) !== false) {
2398
-				$matches[] = (int)$row['objectid'];
2399
-			}
2400
-			$result->closeCursor();
2401
-
2402
-			$query = $this->db->getQueryBuilder();
2403
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2404
-				->from('calendarobjects')
2405
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2406
-
2407
-			$result = $query->executeQuery();
2408
-			$calendarObjects = [];
2409
-			while (($array = $result->fetchAssociative()) !== false) {
2410
-				$array['calendarid'] = (int)$array['calendarid'];
2411
-				$array['calendartype'] = (int)$array['calendartype'];
2412
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2413
-
2414
-				$calendarObjects[] = $array;
2415
-			}
2416
-			$result->closeCursor();
2417
-			return $calendarObjects;
2418
-		}, $this->db);
2419
-	}
2420
-
2421
-	/**
2422
-	 * Searches through all of a users calendars and calendar objects to find
2423
-	 * an object with a specific UID.
2424
-	 *
2425
-	 * This method should return the path to this object, relative to the
2426
-	 * calendar home, so this path usually only contains two parts:
2427
-	 *
2428
-	 * calendarpath/objectpath.ics
2429
-	 *
2430
-	 * If the uid is not found, return null.
2431
-	 *
2432
-	 * This method should only consider * objects that the principal owns, so
2433
-	 * any calendars owned by other principals that also appear in this
2434
-	 * collection should be ignored.
2435
-	 *
2436
-	 * @param string $principalUri
2437
-	 * @param string $uid
2438
-	 * @return string|null
2439
-	 */
2440
-	public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2441
-		$query = $this->db->getQueryBuilder();
2442
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2443
-			->from('calendarobjects', 'co')
2444
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2445
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2446
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2447
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2448
-
2449
-		if ($calendarUri !== null) {
2450
-			$query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2451
-		}
2452
-
2453
-		$stmt = $query->executeQuery();
2454
-		$row = $stmt->fetchAssociative();
2455
-		$stmt->closeCursor();
2456
-		if ($row) {
2457
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2458
-		}
2459
-
2460
-		return null;
2461
-	}
2462
-
2463
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2464
-		$query = $this->db->getQueryBuilder();
2465
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2466
-			->selectAlias('c.uri', 'calendaruri')
2467
-			->from('calendarobjects', 'co')
2468
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2469
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2470
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2471
-		$stmt = $query->executeQuery();
2472
-		$row = $stmt->fetchAssociative();
2473
-		$stmt->closeCursor();
2474
-
2475
-		if (!$row) {
2476
-			return null;
2477
-		}
2478
-
2479
-		return [
2480
-			'id' => $row['id'],
2481
-			'uri' => $row['uri'],
2482
-			'lastmodified' => $row['lastmodified'],
2483
-			'etag' => '"' . $row['etag'] . '"',
2484
-			'calendarid' => $row['calendarid'],
2485
-			'calendaruri' => $row['calendaruri'],
2486
-			'size' => (int)$row['size'],
2487
-			'calendardata' => $this->readBlob($row['calendardata']),
2488
-			'component' => strtolower($row['componenttype']),
2489
-			'classification' => (int)$row['classification'],
2490
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2491
-		];
2492
-	}
2493
-
2494
-	/**
2495
-	 * The getChanges method returns all the changes that have happened, since
2496
-	 * the specified syncToken in the specified calendar.
2497
-	 *
2498
-	 * This function should return an array, such as the following:
2499
-	 *
2500
-	 * [
2501
-	 *   'syncToken' => 'The current synctoken',
2502
-	 *   'added'   => [
2503
-	 *      'new.txt',
2504
-	 *   ],
2505
-	 *   'modified'   => [
2506
-	 *      'modified.txt',
2507
-	 *   ],
2508
-	 *   'deleted' => [
2509
-	 *      'foo.php.bak',
2510
-	 *      'old.txt'
2511
-	 *   ]
2512
-	 * );
2513
-	 *
2514
-	 * The returned syncToken property should reflect the *current* syncToken
2515
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2516
-	 * property This is * needed here too, to ensure the operation is atomic.
2517
-	 *
2518
-	 * If the $syncToken argument is specified as null, this is an initial
2519
-	 * sync, and all members should be reported.
2520
-	 *
2521
-	 * The modified property is an array of nodenames that have changed since
2522
-	 * the last token.
2523
-	 *
2524
-	 * The deleted property is an array with nodenames, that have been deleted
2525
-	 * from collection.
2526
-	 *
2527
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2528
-	 * 1, you only have to report changes that happened only directly in
2529
-	 * immediate descendants. If it's 2, it should also include changes from
2530
-	 * the nodes below the child collections. (grandchildren)
2531
-	 *
2532
-	 * The $limit argument allows a client to specify how many results should
2533
-	 * be returned at most. If the limit is not specified, it should be treated
2534
-	 * as infinite.
2535
-	 *
2536
-	 * If the limit (infinite or not) is higher than you're willing to return,
2537
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2538
-	 *
2539
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2540
-	 * return null.
2541
-	 *
2542
-	 * The limit is 'suggestive'. You are free to ignore it.
2543
-	 *
2544
-	 * @param string $calendarId
2545
-	 * @param string $syncToken
2546
-	 * @param int $syncLevel
2547
-	 * @param int|null $limit
2548
-	 * @param int $calendarType
2549
-	 * @return ?array
2550
-	 */
2551
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2552
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2553
-
2554
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2555
-			// Current synctoken
2556
-			$qb = $this->db->getQueryBuilder();
2557
-			$qb->select('synctoken')
2558
-				->from($table)
2559
-				->where(
2560
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2561
-				);
2562
-			$stmt = $qb->executeQuery();
2563
-			$currentToken = $stmt->fetchOne();
2564
-			$initialSync = !is_numeric($syncToken);
2565
-
2566
-			if ($currentToken === false) {
2567
-				return null;
2568
-			}
2569
-
2570
-			// evaluate if this is a initial sync and construct appropriate command
2571
-			if ($initialSync) {
2572
-				$qb = $this->db->getQueryBuilder();
2573
-				$qb->select('uri')
2574
-					->from('calendarobjects')
2575
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2576
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2577
-					->andWhere($qb->expr()->isNull('deleted_at'));
2578
-			} else {
2579
-				$qb = $this->db->getQueryBuilder();
2580
-				$qb->select('uri', $qb->func()->max('operation'))
2581
-					->from('calendarchanges')
2582
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2583
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2584
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2585
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2586
-					->groupBy('uri');
2587
-			}
2588
-			// evaluate if limit exists
2589
-			if (is_numeric($limit)) {
2590
-				$qb->setMaxResults($limit);
2591
-			}
2592
-			// execute command
2593
-			$stmt = $qb->executeQuery();
2594
-			// build results
2595
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2596
-			// retrieve results
2597
-			if ($initialSync) {
2598
-				$result['added'] = $stmt->fetchFirstColumn();
2599
-			} else {
2600
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2601
-				// produced by doctrine for MAX() with different databases
2602
-				while ($entry = $stmt->fetchNumeric()) {
2603
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2604
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2605
-					match ((int)$entry[1]) {
2606
-						1 => $result['added'][] = $entry[0],
2607
-						2 => $result['modified'][] = $entry[0],
2608
-						3 => $result['deleted'][] = $entry[0],
2609
-						default => $this->logger->debug('Unknown calendar change operation detected')
2610
-					};
2611
-				}
2612
-			}
2613
-			$stmt->closeCursor();
2614
-
2615
-			return $result;
2616
-		}, $this->db);
2617
-	}
2618
-
2619
-	/**
2620
-	 * Returns a list of subscriptions for a principal.
2621
-	 *
2622
-	 * Every subscription is an array with the following keys:
2623
-	 *  * id, a unique id that will be used by other functions to modify the
2624
-	 *    subscription. This can be the same as the uri or a database key.
2625
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2626
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2627
-	 *    principalUri passed to this method.
2628
-	 *
2629
-	 * Furthermore, all the subscription info must be returned too:
2630
-	 *
2631
-	 * 1. {DAV:}displayname
2632
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2633
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2634
-	 *    should not be stripped).
2635
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2636
-	 *    should not be stripped).
2637
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2638
-	 *    attachments should not be stripped).
2639
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2640
-	 *     Sabre\DAV\Property\Href).
2641
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2642
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2643
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2644
-	 *    (should just be an instance of
2645
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2646
-	 *    default components).
2647
-	 *
2648
-	 * @param string $principalUri
2649
-	 * @return array
2650
-	 */
2651
-	public function getSubscriptionsForUser($principalUri) {
2652
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2653
-		$fields[] = 'id';
2654
-		$fields[] = 'uri';
2655
-		$fields[] = 'source';
2656
-		$fields[] = 'principaluri';
2657
-		$fields[] = 'lastmodified';
2658
-		$fields[] = 'synctoken';
2659
-
2660
-		$query = $this->db->getQueryBuilder();
2661
-		$query->select($fields)
2662
-			->from('calendarsubscriptions')
2663
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2664
-			->orderBy('calendarorder', 'asc');
2665
-		$stmt = $query->executeQuery();
2666
-
2667
-		$subscriptions = [];
2668
-		while ($row = $stmt->fetchAssociative()) {
2669
-			$subscription = [
2670
-				'id' => $row['id'],
2671
-				'uri' => $row['uri'],
2672
-				'principaluri' => $row['principaluri'],
2673
-				'source' => $row['source'],
2674
-				'lastmodified' => $row['lastmodified'],
2675
-
2676
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2677
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2678
-			];
2679
-
2680
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2681
-		}
2682
-
2683
-		return $subscriptions;
2684
-	}
2685
-
2686
-	/**
2687
-	 * Creates a new subscription for a principal.
2688
-	 *
2689
-	 * If the creation was a success, an id must be returned that can be used to reference
2690
-	 * this subscription in other methods, such as updateSubscription.
2691
-	 *
2692
-	 * @param string $principalUri
2693
-	 * @param string $uri
2694
-	 * @param array $properties
2695
-	 * @return mixed
2696
-	 */
2697
-	public function createSubscription($principalUri, $uri, array $properties) {
2698
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2699
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2700
-		}
2701
-
2702
-		$values = [
2703
-			'principaluri' => $principalUri,
2704
-			'uri' => $uri,
2705
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2706
-			'lastmodified' => time(),
2707
-		];
2708
-
2709
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2710
-
2711
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2712
-			if (array_key_exists($xmlName, $properties)) {
2713
-				$values[$dbName] = $properties[$xmlName];
2714
-				if (in_array($dbName, $propertiesBoolean)) {
2715
-					$values[$dbName] = true;
2716
-				}
2717
-			}
2718
-		}
2719
-
2720
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2721
-			$valuesToInsert = [];
2722
-			$query = $this->db->getQueryBuilder();
2723
-			foreach (array_keys($values) as $name) {
2724
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2725
-			}
2726
-			$query->insert('calendarsubscriptions')
2727
-				->values($valuesToInsert)
2728
-				->executeStatement();
2729
-
2730
-			$subscriptionId = $query->getLastInsertId();
2731
-
2732
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2733
-			return [$subscriptionId, $subscriptionRow];
2734
-		}, $this->db);
2735
-
2736
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2737
-
2738
-		return $subscriptionId;
2739
-	}
2740
-
2741
-	/**
2742
-	 * Updates a subscription
2743
-	 *
2744
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2745
-	 * To do the actual updates, you must tell this object which properties
2746
-	 * you're going to process with the handle() method.
2747
-	 *
2748
-	 * Calling the handle method is like telling the PropPatch object "I
2749
-	 * promise I can handle updating this property".
2750
-	 *
2751
-	 * Read the PropPatch documentation for more info and examples.
2752
-	 *
2753
-	 * @param mixed $subscriptionId
2754
-	 * @param PropPatch $propPatch
2755
-	 * @return void
2756
-	 */
2757
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2758
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2759
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2760
-
2761
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2762
-			$newValues = [];
2763
-
2764
-			foreach ($mutations as $propertyName => $propertyValue) {
2765
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2766
-					$newValues['source'] = $propertyValue->getHref();
2767
-				} else {
2768
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2769
-					$newValues[$fieldName] = $propertyValue;
2770
-				}
2771
-			}
2772
-
2773
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2774
-				$query = $this->db->getQueryBuilder();
2775
-				$query->update('calendarsubscriptions')
2776
-					->set('lastmodified', $query->createNamedParameter(time()));
2777
-				foreach ($newValues as $fieldName => $value) {
2778
-					$query->set($fieldName, $query->createNamedParameter($value));
2779
-				}
2780
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2781
-					->executeStatement();
2782
-
2783
-				return $this->getSubscriptionById($subscriptionId);
2784
-			}, $this->db);
2785
-
2786
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2787
-
2788
-			return true;
2789
-		});
2790
-	}
2791
-
2792
-	/**
2793
-	 * Deletes a subscription.
2794
-	 *
2795
-	 * @param mixed $subscriptionId
2796
-	 * @return void
2797
-	 */
2798
-	public function deleteSubscription($subscriptionId) {
2799
-		$this->atomic(function () use ($subscriptionId): void {
2800
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2801
-
2802
-			$query = $this->db->getQueryBuilder();
2803
-			$query->delete('calendarsubscriptions')
2804
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2805
-				->executeStatement();
2806
-
2807
-			$query = $this->db->getQueryBuilder();
2808
-			$query->delete('calendarobjects')
2809
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2810
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2811
-				->executeStatement();
2812
-
2813
-			$query->delete('calendarchanges')
2814
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2815
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2816
-				->executeStatement();
2817
-
2818
-			$query->delete($this->dbObjectPropertiesTable)
2819
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2820
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2821
-				->executeStatement();
2822
-
2823
-			if ($subscriptionRow) {
2824
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2825
-			}
2826
-		}, $this->db);
2827
-	}
2828
-
2829
-	/**
2830
-	 * Returns a single scheduling object for the inbox collection.
2831
-	 *
2832
-	 * The returned array should contain the following elements:
2833
-	 *   * uri - A unique basename for the object. This will be used to
2834
-	 *           construct a full uri.
2835
-	 *   * calendardata - The iCalendar object
2836
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2837
-	 *                    timestamp, or a PHP DateTime object.
2838
-	 *   * etag - A unique token that must change if the object changed.
2839
-	 *   * size - The size of the object, in bytes.
2840
-	 *
2841
-	 * @param string $principalUri
2842
-	 * @param string $objectUri
2843
-	 * @return array
2844
-	 */
2845
-	public function getSchedulingObject($principalUri, $objectUri) {
2846
-		$query = $this->db->getQueryBuilder();
2847
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2848
-			->from('schedulingobjects')
2849
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2850
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2851
-			->executeQuery();
2852
-
2853
-		$row = $stmt->fetchAssociative();
2854
-
2855
-		if (!$row) {
2856
-			return null;
2857
-		}
2858
-
2859
-		return [
2860
-			'uri' => $row['uri'],
2861
-			'calendardata' => $row['calendardata'],
2862
-			'lastmodified' => $row['lastmodified'],
2863
-			'etag' => '"' . $row['etag'] . '"',
2864
-			'size' => (int)$row['size'],
2865
-		];
2866
-	}
2867
-
2868
-	/**
2869
-	 * Returns all scheduling objects for the inbox collection.
2870
-	 *
2871
-	 * These objects should be returned as an array. Every item in the array
2872
-	 * should follow the same structure as returned from getSchedulingObject.
2873
-	 *
2874
-	 * The main difference is that 'calendardata' is optional.
2875
-	 *
2876
-	 * @param string $principalUri
2877
-	 * @return array
2878
-	 */
2879
-	public function getSchedulingObjects($principalUri) {
2880
-		$query = $this->db->getQueryBuilder();
2881
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2882
-			->from('schedulingobjects')
2883
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2884
-			->executeQuery();
2885
-
2886
-		$results = [];
2887
-		while (($row = $stmt->fetchAssociative()) !== false) {
2888
-			$results[] = [
2889
-				'calendardata' => $row['calendardata'],
2890
-				'uri' => $row['uri'],
2891
-				'lastmodified' => $row['lastmodified'],
2892
-				'etag' => '"' . $row['etag'] . '"',
2893
-				'size' => (int)$row['size'],
2894
-			];
2895
-		}
2896
-		$stmt->closeCursor();
2897
-
2898
-		return $results;
2899
-	}
2900
-
2901
-	/**
2902
-	 * Deletes a scheduling object from the inbox collection.
2903
-	 *
2904
-	 * @param string $principalUri
2905
-	 * @param string $objectUri
2906
-	 * @return void
2907
-	 */
2908
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2909
-		$this->cachedObjects = [];
2910
-		$query = $this->db->getQueryBuilder();
2911
-		$query->delete('schedulingobjects')
2912
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2913
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2914
-			->executeStatement();
2915
-	}
2916
-
2917
-	/**
2918
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2919
-	 *
2920
-	 * @param int $modifiedBefore
2921
-	 * @param int $limit
2922
-	 * @return void
2923
-	 */
2924
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2925
-		$query = $this->db->getQueryBuilder();
2926
-		$query->select('id')
2927
-			->from('schedulingobjects')
2928
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2929
-			->setMaxResults($limit);
2930
-		$result = $query->executeQuery();
2931
-		$count = $result->rowCount();
2932
-		if ($count === 0) {
2933
-			return;
2934
-		}
2935
-		$ids = array_map(static function (array $id) {
2936
-			return (int)$id[0];
2937
-		}, $result->fetchAllNumeric());
2938
-		$result->closeCursor();
2939
-
2940
-		$numDeleted = 0;
2941
-		$deleteQuery = $this->db->getQueryBuilder();
2942
-		$deleteQuery->delete('schedulingobjects')
2943
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2944
-		foreach (array_chunk($ids, 1000) as $chunk) {
2945
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2946
-			$numDeleted += $deleteQuery->executeStatement();
2947
-		}
2948
-
2949
-		if ($numDeleted === $limit) {
2950
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2951
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2952
-		}
2953
-	}
2954
-
2955
-	/**
2956
-	 * Creates a new scheduling object. This should land in a users' inbox.
2957
-	 *
2958
-	 * @param string $principalUri
2959
-	 * @param string $objectUri
2960
-	 * @param string $objectData
2961
-	 * @return void
2962
-	 */
2963
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2964
-		$this->cachedObjects = [];
2965
-		$query = $this->db->getQueryBuilder();
2966
-		$query->insert('schedulingobjects')
2967
-			->values([
2968
-				'principaluri' => $query->createNamedParameter($principalUri),
2969
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2970
-				'uri' => $query->createNamedParameter($objectUri),
2971
-				'lastmodified' => $query->createNamedParameter(time()),
2972
-				'etag' => $query->createNamedParameter(md5($objectData)),
2973
-				'size' => $query->createNamedParameter(strlen($objectData))
2974
-			])
2975
-			->executeStatement();
2976
-	}
2977
-
2978
-	/**
2979
-	 * Adds a change record to the calendarchanges table.
2980
-	 *
2981
-	 * @param mixed $calendarId
2982
-	 * @param string[] $objectUris
2983
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2984
-	 * @param int $calendarType
2985
-	 * @return void
2986
-	 */
2987
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2988
-		$this->cachedObjects = [];
2989
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2990
-
2991
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2992
-			$query = $this->db->getQueryBuilder();
2993
-			$query->select('synctoken')
2994
-				->from($table)
2995
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2996
-			$result = $query->executeQuery();
2997
-			$syncToken = (int)$result->fetchOne();
2998
-			$result->closeCursor();
2999
-
3000
-			$query = $this->db->getQueryBuilder();
3001
-			$query->insert('calendarchanges')
3002
-				->values([
3003
-					'uri' => $query->createParameter('uri'),
3004
-					'synctoken' => $query->createNamedParameter($syncToken),
3005
-					'calendarid' => $query->createNamedParameter($calendarId),
3006
-					'operation' => $query->createNamedParameter($operation),
3007
-					'calendartype' => $query->createNamedParameter($calendarType),
3008
-					'created_at' => $query->createNamedParameter(time()),
3009
-				]);
3010
-			foreach ($objectUris as $uri) {
3011
-				$query->setParameter('uri', $uri);
3012
-				$query->executeStatement();
3013
-			}
3014
-
3015
-			$query = $this->db->getQueryBuilder();
3016
-			$query->update($table)
3017
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3018
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3019
-				->executeStatement();
3020
-		}, $this->db);
3021
-	}
3022
-
3023
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3024
-		$this->cachedObjects = [];
3025
-
3026
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3027
-			$qbAdded = $this->db->getQueryBuilder();
3028
-			$qbAdded->select('uri')
3029
-				->from('calendarobjects')
3030
-				->where(
3031
-					$qbAdded->expr()->andX(
3032
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3033
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3034
-						$qbAdded->expr()->isNull('deleted_at'),
3035
-					)
3036
-				);
3037
-			$resultAdded = $qbAdded->executeQuery();
3038
-			$addedUris = $resultAdded->fetchFirstColumn();
3039
-			$resultAdded->closeCursor();
3040
-			// Track everything as changed
3041
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3042
-			// only returns the last change per object.
3043
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3044
-
3045
-			$qbDeleted = $this->db->getQueryBuilder();
3046
-			$qbDeleted->select('uri')
3047
-				->from('calendarobjects')
3048
-				->where(
3049
-					$qbDeleted->expr()->andX(
3050
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3051
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3052
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3053
-					)
3054
-				);
3055
-			$resultDeleted = $qbDeleted->executeQuery();
3056
-			$deletedUris = array_map(function (string $uri) {
3057
-				return str_replace('-deleted.ics', '.ics', $uri);
3058
-			}, $resultDeleted->fetchFirstColumn());
3059
-			$resultDeleted->closeCursor();
3060
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3061
-		}, $this->db);
3062
-	}
3063
-
3064
-	/**
3065
-	 * Parses some information from calendar objects, used for optimized
3066
-	 * calendar-queries.
3067
-	 *
3068
-	 * Returns an array with the following keys:
3069
-	 *   * etag - An md5 checksum of the object without the quotes.
3070
-	 *   * size - Size of the object in bytes
3071
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3072
-	 *   * firstOccurence
3073
-	 *   * lastOccurence
3074
-	 *   * uid - value of the UID property
3075
-	 *
3076
-	 * @param string $calendarData
3077
-	 * @return array
3078
-	 */
3079
-	public function getDenormalizedData(string $calendarData): array {
3080
-		$vObject = Reader::read($calendarData);
3081
-		$vEvents = [];
3082
-		$componentType = null;
3083
-		$component = null;
3084
-		$firstOccurrence = null;
3085
-		$lastOccurrence = null;
3086
-		$uid = null;
3087
-		$classification = self::CLASSIFICATION_PUBLIC;
3088
-		$hasDTSTART = false;
3089
-		foreach ($vObject->getComponents() as $component) {
3090
-			if ($component->name !== 'VTIMEZONE') {
3091
-				// Finding all VEVENTs, and track them
3092
-				if ($component->name === 'VEVENT') {
3093
-					$vEvents[] = $component;
3094
-					if ($component->DTSTART) {
3095
-						$hasDTSTART = true;
3096
-					}
3097
-				}
3098
-				// Track first component type and uid
3099
-				if ($uid === null) {
3100
-					$componentType = $component->name;
3101
-					$uid = (string)$component->UID;
3102
-				}
3103
-			}
3104
-		}
3105
-		if (!$componentType) {
3106
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3107
-		}
3108
-
3109
-		if ($hasDTSTART) {
3110
-			$component = $vEvents[0];
3111
-
3112
-			// Finding the last occurrence is a bit harder
3113
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3114
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3115
-				if (isset($component->DTEND)) {
3116
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3117
-				} elseif (isset($component->DURATION)) {
3118
-					$endDate = clone $component->DTSTART->getDateTime();
3119
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3120
-					$lastOccurrence = $endDate->getTimeStamp();
3121
-				} elseif (!$component->DTSTART->hasTime()) {
3122
-					$endDate = clone $component->DTSTART->getDateTime();
3123
-					$endDate->modify('+1 day');
3124
-					$lastOccurrence = $endDate->getTimeStamp();
3125
-				} else {
3126
-					$lastOccurrence = $firstOccurrence;
3127
-				}
3128
-			} else {
3129
-				try {
3130
-					$it = new EventIterator($vEvents);
3131
-				} catch (NoInstancesException $e) {
3132
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3133
-						'app' => 'dav',
3134
-						'exception' => $e,
3135
-					]);
3136
-					throw new Forbidden($e->getMessage());
3137
-				}
3138
-				$maxDate = new DateTime(self::MAX_DATE);
3139
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3140
-				if ($it->isInfinite()) {
3141
-					$lastOccurrence = $maxDate->getTimestamp();
3142
-				} else {
3143
-					$end = $it->getDtEnd();
3144
-					while ($it->valid() && $end < $maxDate) {
3145
-						$end = $it->getDtEnd();
3146
-						$it->next();
3147
-					}
3148
-					$lastOccurrence = $end->getTimestamp();
3149
-				}
3150
-			}
3151
-		}
3152
-
3153
-		if ($component->CLASS) {
3154
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3155
-			switch ($component->CLASS->getValue()) {
3156
-				case 'PUBLIC':
3157
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3158
-					break;
3159
-				case 'CONFIDENTIAL':
3160
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3161
-					break;
3162
-			}
3163
-		}
3164
-		return [
3165
-			'etag' => md5($calendarData),
3166
-			'size' => strlen($calendarData),
3167
-			'componentType' => $componentType,
3168
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3169
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3170
-			'uid' => $uid,
3171
-			'classification' => $classification
3172
-		];
3173
-	}
3174
-
3175
-	/**
3176
-	 * @param $cardData
3177
-	 * @return bool|string
3178
-	 */
3179
-	private function readBlob($cardData) {
3180
-		if (is_resource($cardData)) {
3181
-			return stream_get_contents($cardData);
3182
-		}
3183
-
3184
-		return $cardData;
3185
-	}
3186
-
3187
-	/**
3188
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3189
-	 * @param list<string> $remove
3190
-	 */
3191
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3192
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3193
-			$calendarId = $shareable->getResourceId();
3194
-			$calendarRow = $this->getCalendarById($calendarId);
3195
-			if ($calendarRow === null) {
3196
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3197
-			}
3198
-			$oldShares = $this->getShares($calendarId);
3199
-
3200
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3201
-
3202
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3203
-		}, $this->db);
3204
-	}
3205
-
3206
-	/**
3207
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3208
-	 */
3209
-	public function getShares(int $resourceId): array {
3210
-		return $this->calendarSharingBackend->getShares($resourceId);
3211
-	}
3212
-
3213
-	public function getSharesByShareePrincipal(string $principal): array {
3214
-		return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3215
-	}
3216
-
3217
-	public function preloadShares(array $resourceIds): void {
3218
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3219
-	}
3220
-
3221
-	/**
3222
-	 * @param boolean $value
3223
-	 * @param Calendar $calendar
3224
-	 * @return string|null
3225
-	 */
3226
-	public function setPublishStatus($value, $calendar) {
3227
-		$publishStatus = $this->atomic(function () use ($value, $calendar) {
3228
-			$calendarId = $calendar->getResourceId();
3229
-			$calendarData = $this->getCalendarById($calendarId);
3230
-
3231
-			$query = $this->db->getQueryBuilder();
3232
-			if ($value) {
3233
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3234
-				$query->insert('dav_shares')
3235
-					->values([
3236
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3237
-						'type' => $query->createNamedParameter('calendar'),
3238
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3239
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3240
-						'publicuri' => $query->createNamedParameter($publicUri)
3241
-					]);
3242
-				$query->executeStatement();
3243
-
3244
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3245
-				return $publicUri;
3246
-			}
3247
-			$query->delete('dav_shares')
3248
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3249
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3250
-			$query->executeStatement();
3251
-
3252
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3253
-			return null;
3254
-		}, $this->db);
3255
-
3256
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3257
-		return $publishStatus;
3258
-	}
3259
-
3260
-	/**
3261
-	 * @param Calendar $calendar
3262
-	 * @return string|false
3263
-	 */
3264
-	public function getPublishStatus($calendar) {
3265
-		$cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3266
-		if ($cached !== null) {
3267
-			return $cached;
3268
-		}
3269
-
3270
-		$query = $this->db->getQueryBuilder();
3271
-		$result = $query->select('publicuri')
3272
-			->from('dav_shares')
3273
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3274
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3275
-			->executeQuery();
3276
-
3277
-		$publishStatus = $result->fetchOne();
3278
-		$result->closeCursor();
3279
-
3280
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3281
-		return $publishStatus;
3282
-	}
3283
-
3284
-	/**
3285
-	 * @param int[] $resourceIds
3286
-	 */
3287
-	public function preloadPublishStatuses(array $resourceIds): void {
3288
-		$query = $this->db->getQueryBuilder();
3289
-		$result = $query->select('resourceid', 'publicuri')
3290
-			->from('dav_shares')
3291
-			->where($query->expr()->in(
3292
-				'resourceid',
3293
-				$query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY),
3294
-				IQueryBuilder::PARAM_INT_ARRAY,
3295
-			))
3296
-			->andWhere($query->expr()->eq(
3297
-				'access',
3298
-				$query->createNamedParameter(self::ACCESS_PUBLIC, IQueryBuilder::PARAM_INT),
3299
-				IQueryBuilder::PARAM_INT,
3300
-			))
3301
-			->executeQuery();
3302
-
3303
-		$hasPublishStatuses = [];
3304
-		while ($row = $result->fetchAssociative()) {
3305
-			$this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3306
-			$hasPublishStatuses[(int)$row['resourceid']] = true;
3307
-		}
3308
-
3309
-		// Also remember resources with no publish status
3310
-		foreach ($resourceIds as $resourceId) {
3311
-			if (!isset($hasPublishStatuses[$resourceId])) {
3312
-				$this->publishStatusCache->set((string)$resourceId, false);
3313
-			}
3314
-		}
3315
-
3316
-		$result->closeCursor();
3317
-	}
3318
-
3319
-	/**
3320
-	 * @param int $resourceId
3321
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3322
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3323
-	 */
3324
-	public function applyShareAcl(int $resourceId, array $acl): array {
3325
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3326
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3327
-	}
3328
-
3329
-	/**
3330
-	 * update properties table
3331
-	 *
3332
-	 * @param int $calendarId
3333
-	 * @param string $objectUri
3334
-	 * @param string $calendarData
3335
-	 * @param int $calendarType
3336
-	 */
3337
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3338
-		$this->cachedObjects = [];
3339
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3340
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3341
-
3342
-			try {
3343
-				$vCalendar = $this->readCalendarData($calendarData);
3344
-			} catch (\Exception $ex) {
3345
-				return;
3346
-			}
3347
-
3348
-			$this->purgeProperties($calendarId, $objectId);
3349
-
3350
-			$query = $this->db->getQueryBuilder();
3351
-			$query->insert($this->dbObjectPropertiesTable)
3352
-				->values(
3353
-					[
3354
-						'calendarid' => $query->createNamedParameter($calendarId),
3355
-						'calendartype' => $query->createNamedParameter($calendarType),
3356
-						'objectid' => $query->createNamedParameter($objectId),
3357
-						'name' => $query->createParameter('name'),
3358
-						'parameter' => $query->createParameter('parameter'),
3359
-						'value' => $query->createParameter('value'),
3360
-					]
3361
-				);
3362
-
3363
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3364
-			foreach ($vCalendar->getComponents() as $component) {
3365
-				if (!in_array($component->name, $indexComponents)) {
3366
-					continue;
3367
-				}
3368
-
3369
-				foreach ($component->children() as $property) {
3370
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3371
-						$value = $property->getValue();
3372
-						// is this a shitty db?
3373
-						if (!$this->db->supports4ByteText()) {
3374
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3375
-						}
3376
-						$value = mb_strcut($value, 0, 254);
3377
-
3378
-						$query->setParameter('name', $property->name);
3379
-						$query->setParameter('parameter', null);
3380
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3381
-						$query->executeStatement();
3382
-					}
3383
-
3384
-					if (array_key_exists($property->name, self::$indexParameters)) {
3385
-						$parameters = $property->parameters();
3386
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3387
-
3388
-						foreach ($parameters as $key => $value) {
3389
-							if (in_array($key, $indexedParametersForProperty)) {
3390
-								// is this a shitty db?
3391
-								if ($this->db->supports4ByteText()) {
3392
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3393
-								}
3394
-
3395
-								$query->setParameter('name', $property->name);
3396
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3397
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3398
-								$query->executeStatement();
3399
-							}
3400
-						}
3401
-					}
3402
-				}
3403
-			}
3404
-		}, $this->db);
3405
-	}
3406
-
3407
-	/**
3408
-	 * deletes all birthday calendars
3409
-	 */
3410
-	public function deleteAllBirthdayCalendars() {
3411
-		$this->atomic(function (): void {
3412
-			$query = $this->db->getQueryBuilder();
3413
-			$result = $query->select(['id'])->from('calendars')
3414
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3415
-				->executeQuery();
3416
-
3417
-			while (($row = $result->fetchAssociative()) !== false) {
3418
-				$this->deleteCalendar(
3419
-					$row['id'],
3420
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3421
-				);
3422
-			}
3423
-			$result->closeCursor();
3424
-		}, $this->db);
3425
-	}
3426
-
3427
-	/**
3428
-	 * @param $subscriptionId
3429
-	 */
3430
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3431
-		$this->atomic(function () use ($subscriptionId): void {
3432
-			$query = $this->db->getQueryBuilder();
3433
-			$query->select('uri')
3434
-				->from('calendarobjects')
3435
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3436
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3437
-			$stmt = $query->executeQuery();
3438
-
3439
-			$uris = [];
3440
-			while (($row = $stmt->fetchAssociative()) !== false) {
3441
-				$uris[] = $row['uri'];
3442
-			}
3443
-			$stmt->closeCursor();
3444
-
3445
-			$query = $this->db->getQueryBuilder();
3446
-			$query->delete('calendarobjects')
3447
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3448
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3449
-				->executeStatement();
3450
-
3451
-			$query = $this->db->getQueryBuilder();
3452
-			$query->delete('calendarchanges')
3453
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3454
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3455
-				->executeStatement();
3456
-
3457
-			$query = $this->db->getQueryBuilder();
3458
-			$query->delete($this->dbObjectPropertiesTable)
3459
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3460
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3461
-				->executeStatement();
3462
-
3463
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3464
-		}, $this->db);
3465
-	}
3466
-
3467
-	/**
3468
-	 * @param int $subscriptionId
3469
-	 * @param array<int> $calendarObjectIds
3470
-	 * @param array<string> $calendarObjectUris
3471
-	 */
3472
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3473
-		if (empty($calendarObjectUris)) {
3474
-			return;
3475
-		}
3476
-
3477
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3478
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3479
-				$query = $this->db->getQueryBuilder();
3480
-				$query->delete($this->dbObjectPropertiesTable)
3481
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3482
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3483
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3484
-					->executeStatement();
3485
-
3486
-				$query = $this->db->getQueryBuilder();
3487
-				$query->delete('calendarobjects')
3488
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3489
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3490
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3491
-					->executeStatement();
3492
-			}
3493
-
3494
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3495
-				$query = $this->db->getQueryBuilder();
3496
-				$query->delete('calendarchanges')
3497
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3498
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3499
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3500
-					->executeStatement();
3501
-			}
3502
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3503
-		}, $this->db);
3504
-	}
3505
-
3506
-	/**
3507
-	 * Move a calendar from one user to another
3508
-	 *
3509
-	 * @param string $uriName
3510
-	 * @param string $uriOrigin
3511
-	 * @param string $uriDestination
3512
-	 * @param string $newUriName (optional) the new uriName
3513
-	 */
3514
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3515
-		$query = $this->db->getQueryBuilder();
3516
-		$query->update('calendars')
3517
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3518
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3519
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3520
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3521
-			->executeStatement();
3522
-	}
3523
-
3524
-	/**
3525
-	 * read VCalendar data into a VCalendar object
3526
-	 *
3527
-	 * @param string $objectData
3528
-	 * @return VCalendar
3529
-	 */
3530
-	protected function readCalendarData($objectData) {
3531
-		return Reader::read($objectData);
3532
-	}
3533
-
3534
-	/**
3535
-	 * delete all properties from a given calendar object
3536
-	 *
3537
-	 * @param int $calendarId
3538
-	 * @param int $objectId
3539
-	 */
3540
-	protected function purgeProperties($calendarId, $objectId) {
3541
-		$this->cachedObjects = [];
3542
-		$query = $this->db->getQueryBuilder();
3543
-		$query->delete($this->dbObjectPropertiesTable)
3544
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3545
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3546
-		$query->executeStatement();
3547
-	}
3548
-
3549
-	/**
3550
-	 * get ID from a given calendar object
3551
-	 *
3552
-	 * @param int $calendarId
3553
-	 * @param string $uri
3554
-	 * @param int $calendarType
3555
-	 * @return int
3556
-	 */
3557
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3558
-		$query = $this->db->getQueryBuilder();
3559
-		$query->select('id')
3560
-			->from('calendarobjects')
3561
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3562
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3563
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3564
-
3565
-		$result = $query->executeQuery();
3566
-		$objectIds = $result->fetchAssociative();
3567
-		$result->closeCursor();
3568
-
3569
-		if (!isset($objectIds['id'])) {
3570
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3571
-		}
3572
-
3573
-		return (int)$objectIds['id'];
3574
-	}
3575
-
3576
-	/**
3577
-	 * @throws \InvalidArgumentException
3578
-	 */
3579
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3580
-		if ($keep < 0) {
3581
-			throw new \InvalidArgumentException();
3582
-		}
3583
-
3584
-		$query = $this->db->getQueryBuilder();
3585
-		$query->select($query->func()->max('id'))
3586
-			->from('calendarchanges');
3587
-
3588
-		$result = $query->executeQuery();
3589
-		$maxId = (int)$result->fetchOne();
3590
-		$result->closeCursor();
3591
-		if (!$maxId || $maxId < $keep) {
3592
-			return 0;
3593
-		}
3594
-
3595
-		$query = $this->db->getQueryBuilder();
3596
-		$query->delete('calendarchanges')
3597
-			->where(
3598
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3599
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3600
-			);
3601
-		return $query->executeStatement();
3602
-	}
3603
-
3604
-	/**
3605
-	 * return legacy endpoint principal name to new principal name
3606
-	 *
3607
-	 * @param $principalUri
3608
-	 * @param $toV2
3609
-	 * @return string
3610
-	 */
3611
-	private function convertPrincipal($principalUri, $toV2) {
3612
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3613
-			[, $name] = Uri\split($principalUri);
3614
-			if ($toV2 === true) {
3615
-				return "principals/users/$name";
3616
-			}
3617
-			return "principals/$name";
3618
-		}
3619
-		return $principalUri;
3620
-	}
3621
-
3622
-	/**
3623
-	 * adds information about an owner to the calendar data
3624
-	 *
3625
-	 */
3626
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3627
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3628
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3629
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3630
-			$uri = $calendarInfo[$ownerPrincipalKey];
3631
-		} else {
3632
-			$uri = $calendarInfo['principaluri'];
3633
-		}
3634
-
3635
-		$principalInformation = $this->principalBackend->getPrincipalPropertiesByPath($uri, [
3636
-			'{DAV:}displayname',
3637
-		]);
3638
-		if (isset($principalInformation['{DAV:}displayname'])) {
3639
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3640
-		}
3641
-		return $calendarInfo;
3642
-	}
3643
-
3644
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3645
-		if (isset($row['deleted_at'])) {
3646
-			// Columns is set and not null -> this is a deleted calendar
3647
-			// we send a custom resourcetype to hide the deleted calendar
3648
-			// from ordinary DAV clients, but the Calendar app will know
3649
-			// how to handle this special resource.
3650
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3651
-				'{DAV:}collection',
3652
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3653
-			]);
3654
-		}
3655
-		return $calendar;
3656
-	}
3657
-
3658
-	/**
3659
-	 * Amend the calendar info with database row data
3660
-	 *
3661
-	 * @param array $row
3662
-	 * @param array $calendar
3663
-	 *
3664
-	 * @return array
3665
-	 */
3666
-	private function rowToCalendar($row, array $calendar): array {
3667
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3668
-			$value = $row[$dbName];
3669
-			if ($value !== null) {
3670
-				settype($value, $type);
3671
-			}
3672
-			$calendar[$xmlName] = $value;
3673
-		}
3674
-		return $calendar;
3675
-	}
3676
-
3677
-	/**
3678
-	 * Amend the subscription info with database row data
3679
-	 *
3680
-	 * @param array $row
3681
-	 * @param array $subscription
3682
-	 *
3683
-	 * @return array
3684
-	 */
3685
-	private function rowToSubscription($row, array $subscription): array {
3686
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3687
-			$value = $row[$dbName];
3688
-			if ($value !== null) {
3689
-				settype($value, $type);
3690
-			}
3691
-			$subscription[$xmlName] = $value;
3692
-		}
3693
-		return $subscription;
3694
-	}
3695
-
3696
-	/**
3697
-	 * delete all invitations from a given calendar
3698
-	 *
3699
-	 * @since 31.0.0
3700
-	 *
3701
-	 * @param int $calendarId
3702
-	 *
3703
-	 * @return void
3704
-	 */
3705
-	protected function purgeCalendarInvitations(int $calendarId): void {
3706
-		// select all calendar object uid's
3707
-		$cmd = $this->db->getQueryBuilder();
3708
-		$cmd->select('uid')
3709
-			->from($this->dbObjectsTable)
3710
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3711
-		$allIds = $cmd->executeQuery()->fetchFirstColumn();
3712
-		// delete all links that match object uid's
3713
-		$cmd = $this->db->getQueryBuilder();
3714
-		$cmd->delete($this->dbObjectInvitationsTable)
3715
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3716
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3717
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3718
-			$cmd->executeStatement();
3719
-		}
3720
-	}
3721
-
3722
-	/**
3723
-	 * Delete all invitations from a given calendar event
3724
-	 *
3725
-	 * @since 31.0.0
3726
-	 *
3727
-	 * @param string $eventId UID of the event
3728
-	 *
3729
-	 * @return void
3730
-	 */
3731
-	protected function purgeObjectInvitations(string $eventId): void {
3732
-		$cmd = $this->db->getQueryBuilder();
3733
-		$cmd->delete($this->dbObjectInvitationsTable)
3734
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3735
-		$cmd->executeStatement();
3736
-	}
3737
-
3738
-	public function unshare(IShareable $shareable, string $principal): void {
3739
-		$this->atomic(function () use ($shareable, $principal): void {
3740
-			$calendarData = $this->getCalendarById($shareable->getResourceId());
3741
-			if ($calendarData === null) {
3742
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3743
-			}
3744
-
3745
-			$oldShares = $this->getShares($shareable->getResourceId());
3746
-			$unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3747
-
3748
-			if ($unshare) {
3749
-				$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3750
-					$shareable->getResourceId(),
3751
-					$calendarData,
3752
-					$oldShares,
3753
-					[],
3754
-					[$principal]
3755
-				));
3756
-			}
3757
-		}, $this->db);
3758
-	}
3759
-
3760
-	/**
3761
-	 * @return array<string, mixed>[]
3762
-	 */
3763
-	public function getFederatedCalendarsForUser(string $principalUri): array {
3764
-		$federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3765
-		return array_map(
3766
-			static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3767
-			$federatedCalendars,
3768
-		);
3769
-	}
3770
-
3771
-	public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3772
-		$federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3773
-		return $federatedCalendar?->toCalendarInfo();
3774
-	}
113
+    use TTransactional;
114
+
115
+    public const CALENDAR_TYPE_CALENDAR = 0;
116
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
117
+    public const CALENDAR_TYPE_FEDERATED = 2;
118
+
119
+    public const PERSONAL_CALENDAR_URI = 'personal';
120
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
121
+
122
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
123
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
124
+
125
+    /**
126
+     * We need to specify a max date, because we need to stop *somewhere*
127
+     *
128
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
129
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
130
+     * in 2038-01-19 to avoid problems when the date is converted
131
+     * to a unix timestamp.
132
+     */
133
+    public const MAX_DATE = '2038-01-01';
134
+
135
+    public const ACCESS_PUBLIC = 4;
136
+    public const CLASSIFICATION_PUBLIC = 0;
137
+    public const CLASSIFICATION_PRIVATE = 1;
138
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
139
+
140
+    /**
141
+     * List of CalDAV properties, and how they map to database field names and their type
142
+     * Add your own properties by simply adding on to this array.
143
+     *
144
+     * @var array
145
+     * @psalm-var array<string, string[]>
146
+     */
147
+    public array $propertyMap = [
148
+        '{DAV:}displayname' => ['displayname', 'string'],
149
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
150
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
154
+    ];
155
+
156
+    /**
157
+     * List of subscription properties, and how they map to database field names.
158
+     *
159
+     * @var array
160
+     */
161
+    public array $subscriptionPropertyMap = [
162
+        '{DAV:}displayname' => ['displayname', 'string'],
163
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
164
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
165
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
166
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
167
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
168
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
169
+    ];
170
+
171
+    /**
172
+     * properties to index
173
+     *
174
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
175
+     *
176
+     * @see \OCP\Calendar\ICalendarQuery
177
+     */
178
+    private const INDEXED_PROPERTIES = [
179
+        'CATEGORIES',
180
+        'COMMENT',
181
+        'DESCRIPTION',
182
+        'LOCATION',
183
+        'RESOURCES',
184
+        'STATUS',
185
+        'SUMMARY',
186
+        'ATTENDEE',
187
+        'CONTACT',
188
+        'ORGANIZER'
189
+    ];
190
+
191
+    /** @var array parameters to index */
192
+    public static array $indexParameters = [
193
+        'ATTENDEE' => ['CN'],
194
+        'ORGANIZER' => ['CN'],
195
+    ];
196
+
197
+    /**
198
+     * @var string[] Map of uid => display name
199
+     */
200
+    protected array $userDisplayNames;
201
+
202
+    private string $dbObjectsTable = 'calendarobjects';
203
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
204
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
205
+    private array $cachedObjects = [];
206
+
207
+    private readonly ICache $publishStatusCache;
208
+
209
+    public function __construct(
210
+        private IDBConnection $db,
211
+        private Principal $principalBackend,
212
+        private IUserManager $userManager,
213
+        private ISecureRandom $random,
214
+        private LoggerInterface $logger,
215
+        private IEventDispatcher $dispatcher,
216
+        private IConfig $config,
217
+        private Sharing\Backend $calendarSharingBackend,
218
+        private FederatedCalendarMapper $federatedCalendarMapper,
219
+        ICacheFactory $cacheFactory,
220
+        private bool $legacyEndpoint = false,
221
+    ) {
222
+        $this->publishStatusCache = $cacheFactory->createInMemory();
223
+    }
224
+
225
+    /**
226
+     * Return the number of calendars owned by the given principal.
227
+     *
228
+     * Calendars shared with the given principal are not counted!
229
+     *
230
+     * By default, this excludes the automatically generated birthday calendar.
231
+     */
232
+    public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
233
+        $principalUri = $this->convertPrincipal($principalUri, true);
234
+        $query = $this->db->getQueryBuilder();
235
+        $query->select($query->func()->count('*'))
236
+            ->from('calendars');
237
+
238
+        if ($principalUri === '') {
239
+            $query->where($query->expr()->emptyString('principaluri'));
240
+        } else {
241
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
242
+        }
243
+
244
+        if ($excludeBirthday) {
245
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
246
+        }
247
+
248
+        $result = $query->executeQuery();
249
+        $column = (int)$result->fetchOne();
250
+        $result->closeCursor();
251
+        return $column;
252
+    }
253
+
254
+    /**
255
+     * Return the number of subscriptions for a principal
256
+     */
257
+    public function getSubscriptionsForUserCount(string $principalUri): int {
258
+        $principalUri = $this->convertPrincipal($principalUri, true);
259
+        $query = $this->db->getQueryBuilder();
260
+        $query->select($query->func()->count('*'))
261
+            ->from('calendarsubscriptions');
262
+
263
+        if ($principalUri === '') {
264
+            $query->where($query->expr()->emptyString('principaluri'));
265
+        } else {
266
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
267
+        }
268
+
269
+        $result = $query->executeQuery();
270
+        $column = (int)$result->fetchOne();
271
+        $result->closeCursor();
272
+        return $column;
273
+    }
274
+
275
+    /**
276
+     * @return array{id: int, deleted_at: int}[]
277
+     */
278
+    public function getDeletedCalendars(int $deletedBefore): array {
279
+        $qb = $this->db->getQueryBuilder();
280
+        $qb->select(['id', 'deleted_at'])
281
+            ->from('calendars')
282
+            ->where($qb->expr()->isNotNull('deleted_at'))
283
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
284
+        $result = $qb->executeQuery();
285
+        $calendars = [];
286
+        while (($row = $result->fetchAssociative()) !== false) {
287
+            $calendars[] = [
288
+                'id' => (int)$row['id'],
289
+                'deleted_at' => (int)$row['deleted_at'],
290
+            ];
291
+        }
292
+        $result->closeCursor();
293
+        return $calendars;
294
+    }
295
+
296
+    /**
297
+     * Returns a list of calendars for a principal.
298
+     *
299
+     * Every project is an array with the following keys:
300
+     *  * id, a unique id that will be used by other functions to modify the
301
+     *    calendar. This can be the same as the uri or a database key.
302
+     *  * uri, which the basename of the uri with which the calendar is
303
+     *    accessed.
304
+     *  * principaluri. The owner of the calendar. Almost always the same as
305
+     *    principalUri passed to this method.
306
+     *
307
+     * Furthermore it can contain webdav properties in clark notation. A very
308
+     * common one is '{DAV:}displayname'.
309
+     *
310
+     * Many clients also require:
311
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
312
+     * For this property, you can just return an instance of
313
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
314
+     *
315
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
316
+     * ACL will automatically be put in read-only mode.
317
+     *
318
+     * @param string $principalUri
319
+     * @return array
320
+     */
321
+    public function getCalendarsForUser($principalUri) {
322
+        return $this->atomic(function () use ($principalUri) {
323
+            $principalUriOriginal = $principalUri;
324
+            $principalUri = $this->convertPrincipal($principalUri, true);
325
+            $fields = array_column($this->propertyMap, 0);
326
+            $fields[] = 'id';
327
+            $fields[] = 'uri';
328
+            $fields[] = 'synctoken';
329
+            $fields[] = 'components';
330
+            $fields[] = 'principaluri';
331
+            $fields[] = 'transparent';
332
+
333
+            // Making fields a comma-delimited list
334
+            $query = $this->db->getQueryBuilder();
335
+            $query->select($fields)
336
+                ->from('calendars')
337
+                ->orderBy('calendarorder', 'ASC');
338
+
339
+            if ($principalUri === '') {
340
+                $query->where($query->expr()->emptyString('principaluri'));
341
+            } else {
342
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
343
+            }
344
+
345
+            $result = $query->executeQuery();
346
+
347
+            $calendars = [];
348
+            while ($row = $result->fetchAssociative()) {
349
+                $row['principaluri'] = (string)$row['principaluri'];
350
+                $components = [];
351
+                if ($row['components']) {
352
+                    $components = explode(',', $row['components']);
353
+                }
354
+
355
+                $calendar = [
356
+                    'id' => $row['id'],
357
+                    'uri' => $row['uri'],
358
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
360
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
+                ];
365
+
366
+                $calendar = $this->rowToCalendar($row, $calendar);
367
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
368
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
369
+
370
+                if (!isset($calendars[$calendar['id']])) {
371
+                    $calendars[$calendar['id']] = $calendar;
372
+                }
373
+            }
374
+            $result->closeCursor();
375
+
376
+            // query for shared calendars
377
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
378
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
379
+            $principals[] = $principalUri;
380
+
381
+            $fields = array_column($this->propertyMap, 0);
382
+            $fields = array_map(function (string $field) {
383
+                return 'a.' . $field;
384
+            }, $fields);
385
+            $fields[] = 'a.id';
386
+            $fields[] = 'a.uri';
387
+            $fields[] = 'a.synctoken';
388
+            $fields[] = 'a.components';
389
+            $fields[] = 'a.principaluri';
390
+            $fields[] = 'a.transparent';
391
+            $fields[] = 's.access';
392
+
393
+            $select = $this->db->getQueryBuilder();
394
+            $subSelect = $this->db->getQueryBuilder();
395
+
396
+            $subSelect->select('resourceid')
397
+                ->from('dav_shares', 'd')
398
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
399
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
400
+
401
+            $select->select($fields)
402
+                ->from('dav_shares', 's')
403
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
404
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
405
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
406
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
407
+
408
+            $results = $select->executeQuery();
409
+
410
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
411
+            while ($row = $results->fetchAssociative()) {
412
+                $row['principaluri'] = (string)$row['principaluri'];
413
+                if ($row['principaluri'] === $principalUri) {
414
+                    continue;
415
+                }
416
+
417
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
418
+                if (isset($calendars[$row['id']])) {
419
+                    if ($readOnly) {
420
+                        // New share can not have more permissions than the old one.
421
+                        continue;
422
+                    }
423
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName])
424
+                        && $calendars[$row['id']][$readOnlyPropertyName] === 0) {
425
+                        // Old share is already read-write, no more permissions can be gained
426
+                        continue;
427
+                    }
428
+                }
429
+
430
+                [, $name] = Uri\split($row['principaluri']);
431
+                $uri = $row['uri'] . '_shared_by_' . $name;
432
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
433
+                $components = [];
434
+                if ($row['components']) {
435
+                    $components = explode(',', $row['components']);
436
+                }
437
+                $calendar = [
438
+                    'id' => $row['id'],
439
+                    'uri' => $uri,
440
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
442
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446
+                    $readOnlyPropertyName => $readOnly,
447
+                ];
448
+
449
+                $calendar = $this->rowToCalendar($row, $calendar);
450
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
451
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
452
+
453
+                $calendars[$calendar['id']] = $calendar;
454
+            }
455
+            $result->closeCursor();
456
+
457
+            return array_values($calendars);
458
+        }, $this->db);
459
+    }
460
+
461
+    /**
462
+     * @param $principalUri
463
+     * @return array
464
+     */
465
+    public function getUsersOwnCalendars($principalUri) {
466
+        $principalUri = $this->convertPrincipal($principalUri, true);
467
+        $fields = array_column($this->propertyMap, 0);
468
+        $fields[] = 'id';
469
+        $fields[] = 'uri';
470
+        $fields[] = 'synctoken';
471
+        $fields[] = 'components';
472
+        $fields[] = 'principaluri';
473
+        $fields[] = 'transparent';
474
+        // Making fields a comma-delimited list
475
+        $query = $this->db->getQueryBuilder();
476
+        $query->select($fields)->from('calendars')
477
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
478
+            ->orderBy('calendarorder', 'ASC');
479
+        $stmt = $query->executeQuery();
480
+        $calendars = [];
481
+        while ($row = $stmt->fetchAssociative()) {
482
+            $row['principaluri'] = (string)$row['principaluri'];
483
+            $components = [];
484
+            if ($row['components']) {
485
+                $components = explode(',', $row['components']);
486
+            }
487
+            $calendar = [
488
+                'id' => $row['id'],
489
+                'uri' => $row['uri'],
490
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
492
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
+            ];
496
+
497
+            $calendar = $this->rowToCalendar($row, $calendar);
498
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
499
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
500
+
501
+            if (!isset($calendars[$calendar['id']])) {
502
+                $calendars[$calendar['id']] = $calendar;
503
+            }
504
+        }
505
+        $stmt->closeCursor();
506
+        return array_values($calendars);
507
+    }
508
+
509
+    /**
510
+     * @return array
511
+     */
512
+    public function getPublicCalendars() {
513
+        $fields = array_column($this->propertyMap, 0);
514
+        $fields[] = 'a.id';
515
+        $fields[] = 'a.uri';
516
+        $fields[] = 'a.synctoken';
517
+        $fields[] = 'a.components';
518
+        $fields[] = 'a.principaluri';
519
+        $fields[] = 'a.transparent';
520
+        $fields[] = 's.access';
521
+        $fields[] = 's.publicuri';
522
+        $calendars = [];
523
+        $query = $this->db->getQueryBuilder();
524
+        $result = $query->select($fields)
525
+            ->from('dav_shares', 's')
526
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
527
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
528
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
529
+            ->executeQuery();
530
+
531
+        while ($row = $result->fetchAssociative()) {
532
+            $row['principaluri'] = (string)$row['principaluri'];
533
+            [, $name] = Uri\split($row['principaluri']);
534
+            $row['displayname'] = $row['displayname'] . "($name)";
535
+            $components = [];
536
+            if ($row['components']) {
537
+                $components = explode(',', $row['components']);
538
+            }
539
+            $calendar = [
540
+                'id' => $row['id'],
541
+                'uri' => $row['publicuri'],
542
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
544
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
550
+            ];
551
+
552
+            $calendar = $this->rowToCalendar($row, $calendar);
553
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
554
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
555
+
556
+            if (!isset($calendars[$calendar['id']])) {
557
+                $calendars[$calendar['id']] = $calendar;
558
+            }
559
+        }
560
+        $result->closeCursor();
561
+
562
+        return array_values($calendars);
563
+    }
564
+
565
+    /**
566
+     * @param string $uri
567
+     * @return array
568
+     * @throws NotFound
569
+     */
570
+    public function getPublicCalendar($uri) {
571
+        $fields = array_column($this->propertyMap, 0);
572
+        $fields[] = 'a.id';
573
+        $fields[] = 'a.uri';
574
+        $fields[] = 'a.synctoken';
575
+        $fields[] = 'a.components';
576
+        $fields[] = 'a.principaluri';
577
+        $fields[] = 'a.transparent';
578
+        $fields[] = 's.access';
579
+        $fields[] = 's.publicuri';
580
+        $query = $this->db->getQueryBuilder();
581
+        $result = $query->select($fields)
582
+            ->from('dav_shares', 's')
583
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
584
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
585
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
586
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
587
+            ->executeQuery();
588
+
589
+        $row = $result->fetchAssociative();
590
+
591
+        $result->closeCursor();
592
+
593
+        if ($row === false) {
594
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
595
+        }
596
+
597
+        $row['principaluri'] = (string)$row['principaluri'];
598
+        [, $name] = Uri\split($row['principaluri']);
599
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
600
+        $components = [];
601
+        if ($row['components']) {
602
+            $components = explode(',', $row['components']);
603
+        }
604
+        $calendar = [
605
+            'id' => $row['id'],
606
+            'uri' => $row['publicuri'],
607
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
609
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
615
+        ];
616
+
617
+        $calendar = $this->rowToCalendar($row, $calendar);
618
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
619
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
620
+
621
+        return $calendar;
622
+    }
623
+
624
+    /**
625
+     * @param string $principal
626
+     * @param string $uri
627
+     * @return array|null
628
+     */
629
+    public function getCalendarByUri($principal, $uri) {
630
+        $fields = array_column($this->propertyMap, 0);
631
+        $fields[] = 'id';
632
+        $fields[] = 'uri';
633
+        $fields[] = 'synctoken';
634
+        $fields[] = 'components';
635
+        $fields[] = 'principaluri';
636
+        $fields[] = 'transparent';
637
+
638
+        // Making fields a comma-delimited list
639
+        $query = $this->db->getQueryBuilder();
640
+        $query->select($fields)->from('calendars')
641
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
642
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
643
+            ->setMaxResults(1);
644
+        $stmt = $query->executeQuery();
645
+
646
+        $row = $stmt->fetchAssociative();
647
+        $stmt->closeCursor();
648
+        if ($row === false) {
649
+            return null;
650
+        }
651
+
652
+        $row['principaluri'] = (string)$row['principaluri'];
653
+        $components = [];
654
+        if ($row['components']) {
655
+            $components = explode(',', $row['components']);
656
+        }
657
+
658
+        $calendar = [
659
+            'id' => $row['id'],
660
+            'uri' => $row['uri'],
661
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
663
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
666
+        ];
667
+
668
+        $calendar = $this->rowToCalendar($row, $calendar);
669
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
670
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
671
+
672
+        return $calendar;
673
+    }
674
+
675
+    /**
676
+     * @psalm-return CalendarInfo|null
677
+     * @return array|null
678
+     */
679
+    public function getCalendarById(int $calendarId): ?array {
680
+        $fields = array_column($this->propertyMap, 0);
681
+        $fields[] = 'id';
682
+        $fields[] = 'uri';
683
+        $fields[] = 'synctoken';
684
+        $fields[] = 'components';
685
+        $fields[] = 'principaluri';
686
+        $fields[] = 'transparent';
687
+
688
+        // Making fields a comma-delimited list
689
+        $query = $this->db->getQueryBuilder();
690
+        $query->select($fields)->from('calendars')
691
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
692
+            ->setMaxResults(1);
693
+        $stmt = $query->executeQuery();
694
+
695
+        $row = $stmt->fetchAssociative();
696
+        $stmt->closeCursor();
697
+        if ($row === false) {
698
+            return null;
699
+        }
700
+
701
+        $row['principaluri'] = (string)$row['principaluri'];
702
+        $components = [];
703
+        if ($row['components']) {
704
+            $components = explode(',', $row['components']);
705
+        }
706
+
707
+        $calendar = [
708
+            'id' => $row['id'],
709
+            'uri' => $row['uri'],
710
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
712
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
715
+        ];
716
+
717
+        $calendar = $this->rowToCalendar($row, $calendar);
718
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
719
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
720
+
721
+        return $calendar;
722
+    }
723
+
724
+    /**
725
+     * @param $subscriptionId
726
+     */
727
+    public function getSubscriptionById($subscriptionId) {
728
+        $fields = array_column($this->subscriptionPropertyMap, 0);
729
+        $fields[] = 'id';
730
+        $fields[] = 'uri';
731
+        $fields[] = 'source';
732
+        $fields[] = 'synctoken';
733
+        $fields[] = 'principaluri';
734
+        $fields[] = 'lastmodified';
735
+
736
+        $query = $this->db->getQueryBuilder();
737
+        $query->select($fields)
738
+            ->from('calendarsubscriptions')
739
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
740
+            ->orderBy('calendarorder', 'asc');
741
+        $stmt = $query->executeQuery();
742
+
743
+        $row = $stmt->fetchAssociative();
744
+        $stmt->closeCursor();
745
+        if ($row === false) {
746
+            return null;
747
+        }
748
+
749
+        $row['principaluri'] = (string)$row['principaluri'];
750
+        $subscription = [
751
+            'id' => $row['id'],
752
+            'uri' => $row['uri'],
753
+            'principaluri' => $row['principaluri'],
754
+            'source' => $row['source'],
755
+            'lastmodified' => $row['lastmodified'],
756
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758
+        ];
759
+
760
+        return $this->rowToSubscription($row, $subscription);
761
+    }
762
+
763
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
764
+        $fields = array_column($this->subscriptionPropertyMap, 0);
765
+        $fields[] = 'id';
766
+        $fields[] = 'uri';
767
+        $fields[] = 'source';
768
+        $fields[] = 'synctoken';
769
+        $fields[] = 'principaluri';
770
+        $fields[] = 'lastmodified';
771
+
772
+        $query = $this->db->getQueryBuilder();
773
+        $query->select($fields)
774
+            ->from('calendarsubscriptions')
775
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
776
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
777
+            ->setMaxResults(1);
778
+        $stmt = $query->executeQuery();
779
+
780
+        $row = $stmt->fetchAssociative();
781
+        $stmt->closeCursor();
782
+        if ($row === false) {
783
+            return null;
784
+        }
785
+
786
+        $row['principaluri'] = (string)$row['principaluri'];
787
+        $subscription = [
788
+            'id' => $row['id'],
789
+            'uri' => $row['uri'],
790
+            'principaluri' => $row['principaluri'],
791
+            'source' => $row['source'],
792
+            'lastmodified' => $row['lastmodified'],
793
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795
+        ];
796
+
797
+        return $this->rowToSubscription($row, $subscription);
798
+    }
799
+
800
+    /**
801
+     * Creates a new calendar for a principal.
802
+     *
803
+     * If the creation was a success, an id must be returned that can be used to reference
804
+     * this calendar in other methods, such as updateCalendar.
805
+     *
806
+     * @param string $principalUri
807
+     * @param string $calendarUri
808
+     * @param array $properties
809
+     * @return int
810
+     *
811
+     * @throws CalendarException
812
+     */
813
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
814
+        if (strlen($calendarUri) > 255) {
815
+            throw new CalendarException('URI too long. Calendar not created');
816
+        }
817
+
818
+        $values = [
819
+            'principaluri' => $this->convertPrincipal($principalUri, true),
820
+            'uri' => $calendarUri,
821
+            'synctoken' => 1,
822
+            'transparent' => 0,
823
+            'components' => 'VEVENT,VTODO,VJOURNAL',
824
+            'displayname' => $calendarUri
825
+        ];
826
+
827
+        // Default value
828
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829
+        if (isset($properties[$sccs])) {
830
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832
+            }
833
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
834
+        } elseif (isset($properties['components'])) {
835
+            // Allow to provide components internally without having
836
+            // to create a SupportedCalendarComponentSet object
837
+            $values['components'] = $properties['components'];
838
+        }
839
+
840
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
+        if (isset($properties[$transp])) {
842
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
843
+        }
844
+
845
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
846
+            if (isset($properties[$xmlName])) {
847
+                $values[$dbName] = $properties[$xmlName];
848
+            }
849
+        }
850
+
851
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
852
+            $query = $this->db->getQueryBuilder();
853
+            $query->insert('calendars');
854
+            foreach ($values as $column => $value) {
855
+                $query->setValue($column, $query->createNamedParameter($value));
856
+            }
857
+            $query->executeStatement();
858
+            $calendarId = $query->getLastInsertId();
859
+
860
+            $calendarData = $this->getCalendarById($calendarId);
861
+            return [$calendarId, $calendarData];
862
+        }, $this->db);
863
+
864
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
865
+
866
+        return $calendarId;
867
+    }
868
+
869
+    /**
870
+     * Updates properties for a calendar.
871
+     *
872
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
873
+     * To do the actual updates, you must tell this object which properties
874
+     * you're going to process with the handle() method.
875
+     *
876
+     * Calling the handle method is like telling the PropPatch object "I
877
+     * promise I can handle updating this property".
878
+     *
879
+     * Read the PropPatch documentation for more info and examples.
880
+     *
881
+     * @param mixed $calendarId
882
+     * @param PropPatch $propPatch
883
+     * @return void
884
+     */
885
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
886
+        $supportedProperties = array_keys($this->propertyMap);
887
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
888
+
889
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
890
+            $newValues = [];
891
+            foreach ($mutations as $propertyName => $propertyValue) {
892
+                switch ($propertyName) {
893
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
894
+                        $fieldName = 'transparent';
895
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
896
+                        break;
897
+                    default:
898
+                        $fieldName = $this->propertyMap[$propertyName][0];
899
+                        $newValues[$fieldName] = $propertyValue;
900
+                        break;
901
+                }
902
+            }
903
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
904
+                $query = $this->db->getQueryBuilder();
905
+                $query->update('calendars');
906
+                foreach ($newValues as $fieldName => $value) {
907
+                    $query->set($fieldName, $query->createNamedParameter($value));
908
+                }
909
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
910
+                $query->executeStatement();
911
+
912
+                $this->addChanges($calendarId, [''], 2);
913
+
914
+                $calendarData = $this->getCalendarById($calendarId);
915
+                $shares = $this->getShares($calendarId);
916
+                return [$calendarData, $shares];
917
+            }, $this->db);
918
+
919
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
920
+
921
+            return true;
922
+        });
923
+    }
924
+
925
+    /**
926
+     * Delete a calendar and all it's objects
927
+     *
928
+     * @param mixed $calendarId
929
+     * @return void
930
+     */
931
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
+        $this->publishStatusCache->remove((string)$calendarId);
933
+
934
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
935
+            // The calendar is deleted right away if this is either enforced by the caller
936
+            // or the special contacts birthday calendar or when the preference of an empty
937
+            // retention (0 seconds) is set, which signals a disabled trashbin.
938
+            $calendarData = $this->getCalendarById($calendarId);
939
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
940
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
941
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
942
+                $calendarData = $this->getCalendarById($calendarId);
943
+                $shares = $this->getShares($calendarId);
944
+
945
+                $this->purgeCalendarInvitations($calendarId);
946
+
947
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
948
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
949
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
950
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
+                    ->executeStatement();
952
+
953
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
954
+                $qbDeleteCalendarObjects->delete('calendarobjects')
955
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
956
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
957
+                    ->executeStatement();
958
+
959
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
960
+                $qbDeleteCalendarChanges->delete('calendarchanges')
961
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
962
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
963
+                    ->executeStatement();
964
+
965
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
966
+
967
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
968
+                $qbDeleteCalendar->delete('calendars')
969
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
970
+                    ->executeStatement();
971
+
972
+                // Only dispatch if we actually deleted anything
973
+                if ($calendarData) {
974
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
975
+                }
976
+            } else {
977
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
978
+                $qbMarkCalendarDeleted->update('calendars')
979
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
980
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
981
+                    ->executeStatement();
982
+
983
+                $calendarData = $this->getCalendarById($calendarId);
984
+                $shares = $this->getShares($calendarId);
985
+                if ($calendarData) {
986
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
987
+                        $calendarId,
988
+                        $calendarData,
989
+                        $shares
990
+                    ));
991
+                }
992
+            }
993
+        }, $this->db);
994
+    }
995
+
996
+    public function restoreCalendar(int $id): void {
997
+        $this->atomic(function () use ($id): void {
998
+            $qb = $this->db->getQueryBuilder();
999
+            $update = $qb->update('calendars')
1000
+                ->set('deleted_at', $qb->createNamedParameter(null))
1001
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1002
+            $update->executeStatement();
1003
+
1004
+            $calendarData = $this->getCalendarById($id);
1005
+            $shares = $this->getShares($id);
1006
+            if ($calendarData === null) {
1007
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1008
+            }
1009
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1010
+                $id,
1011
+                $calendarData,
1012
+                $shares
1013
+            ));
1014
+        }, $this->db);
1015
+    }
1016
+
1017
+    /**
1018
+     * Returns all calendar entries as a stream of data
1019
+     *
1020
+     * @since 32.0.0
1021
+     *
1022
+     * @return Generator<array>
1023
+     */
1024
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1025
+        // extract options
1026
+        $rangeStart = $options?->getRangeStart();
1027
+        $rangeCount = $options?->getRangeCount();
1028
+        // construct query
1029
+        $qb = $this->db->getQueryBuilder();
1030
+        $qb->select('*')
1031
+            ->from('calendarobjects')
1032
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1033
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1034
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1035
+        if ($rangeStart !== null) {
1036
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1037
+        }
1038
+        if ($rangeCount !== null) {
1039
+            $qb->setMaxResults($rangeCount);
1040
+        }
1041
+        if ($rangeStart !== null || $rangeCount !== null) {
1042
+            $qb->orderBy('uid', 'ASC');
1043
+        }
1044
+        $rs = $qb->executeQuery();
1045
+        // iterate through results
1046
+        try {
1047
+            while (($row = $rs->fetchAssociative()) !== false) {
1048
+                yield $row;
1049
+            }
1050
+        } finally {
1051
+            $rs->closeCursor();
1052
+        }
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns all calendar objects with limited metadata for a calendar
1057
+     *
1058
+     * Every item contains an array with the following keys:
1059
+     *   * id - the table row id
1060
+     *   * etag - An arbitrary string
1061
+     *   * uri - a unique key which will be used to construct the uri. This can
1062
+     *     be any arbitrary string.
1063
+     *   * calendardata - The iCalendar-compatible calendar data
1064
+     *
1065
+     * @param mixed $calendarId
1066
+     * @param int $calendarType
1067
+     * @return array
1068
+     */
1069
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, array $fields = []):array {
1070
+        $query = $this->db->getQueryBuilder();
1071
+        $query->select($fields ?: ['id', 'uid', 'etag', 'uri', 'calendardata'])
1072
+            ->from('calendarobjects')
1073
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1074
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1075
+            ->andWhere($query->expr()->isNull('deleted_at'));
1076
+        $stmt = $query->executeQuery();
1077
+
1078
+        $result = [];
1079
+        while (($row = $stmt->fetchAssociative()) !== false) {
1080
+            $result[$row['uid']] = $row;
1081
+        }
1082
+        $stmt->closeCursor();
1083
+
1084
+        return $result;
1085
+    }
1086
+
1087
+    /**
1088
+     * Delete all of an user's shares
1089
+     *
1090
+     * @param string $principaluri
1091
+     * @return void
1092
+     */
1093
+    public function deleteAllSharesByUser($principaluri) {
1094
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1095
+    }
1096
+
1097
+    /**
1098
+     * Returns all calendar objects within a calendar.
1099
+     *
1100
+     * Every item contains an array with the following keys:
1101
+     *   * calendardata - The iCalendar-compatible calendar data
1102
+     *   * uri - a unique key which will be used to construct the uri. This can
1103
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1104
+     *     good idea. This is only the basename, or filename, not the full
1105
+     *     path.
1106
+     *   * lastmodified - a timestamp of the last modification time
1107
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1108
+     *   '"abcdef"')
1109
+     *   * size - The size of the calendar objects, in bytes.
1110
+     *   * component - optional, a string containing the type of object, such
1111
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1112
+     *     the Content-Type header.
1113
+     *
1114
+     * Note that the etag is optional, but it's highly encouraged to return for
1115
+     * speed reasons.
1116
+     *
1117
+     * The calendardata is also optional. If it's not returned
1118
+     * 'getCalendarObject' will be called later, which *is* expected to return
1119
+     * calendardata.
1120
+     *
1121
+     * If neither etag or size are specified, the calendardata will be
1122
+     * used/fetched to determine these numbers. If both are specified the
1123
+     * amount of times this is needed is reduced by a great degree.
1124
+     *
1125
+     * @param mixed $calendarId
1126
+     * @param int $calendarType
1127
+     * @return array
1128
+     */
1129
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1130
+        $query = $this->db->getQueryBuilder();
1131
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1132
+            ->from('calendarobjects')
1133
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1134
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1135
+            ->andWhere($query->expr()->isNull('deleted_at'));
1136
+        $stmt = $query->executeQuery();
1137
+
1138
+        $result = [];
1139
+        while (($row = $stmt->fetchAssociative()) !== false) {
1140
+            $result[] = [
1141
+                'id' => $row['id'],
1142
+                'uri' => $row['uri'],
1143
+                'lastmodified' => $row['lastmodified'],
1144
+                'etag' => '"' . $row['etag'] . '"',
1145
+                'calendarid' => $row['calendarid'],
1146
+                'size' => (int)$row['size'],
1147
+                'component' => strtolower($row['componenttype']),
1148
+                'classification' => (int)$row['classification']
1149
+            ];
1150
+        }
1151
+        $stmt->closeCursor();
1152
+
1153
+        return $result;
1154
+    }
1155
+
1156
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1157
+        $query = $this->db->getQueryBuilder();
1158
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1159
+            ->from('calendarobjects', 'co')
1160
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1161
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1162
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1163
+        $stmt = $query->executeQuery();
1164
+
1165
+        $result = [];
1166
+        while (($row = $stmt->fetchAssociative()) !== false) {
1167
+            $result[] = [
1168
+                'id' => $row['id'],
1169
+                'uri' => $row['uri'],
1170
+                'lastmodified' => $row['lastmodified'],
1171
+                'etag' => '"' . $row['etag'] . '"',
1172
+                'calendarid' => (int)$row['calendarid'],
1173
+                'calendartype' => (int)$row['calendartype'],
1174
+                'size' => (int)$row['size'],
1175
+                'component' => strtolower($row['componenttype']),
1176
+                'classification' => (int)$row['classification'],
1177
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1178
+            ];
1179
+        }
1180
+        $stmt->closeCursor();
1181
+
1182
+        return $result;
1183
+    }
1184
+
1185
+    /**
1186
+     * Return all deleted calendar objects by the given principal that are not
1187
+     * in deleted calendars.
1188
+     *
1189
+     * @param string $principalUri
1190
+     * @return array
1191
+     * @throws Exception
1192
+     */
1193
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1194
+        $query = $this->db->getQueryBuilder();
1195
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1196
+            ->selectAlias('c.uri', 'calendaruri')
1197
+            ->from('calendarobjects', 'co')
1198
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1199
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1200
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1201
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1202
+        $stmt = $query->executeQuery();
1203
+
1204
+        $result = [];
1205
+        while ($row = $stmt->fetchAssociative()) {
1206
+            $result[] = [
1207
+                'id' => $row['id'],
1208
+                'uri' => $row['uri'],
1209
+                'lastmodified' => $row['lastmodified'],
1210
+                'etag' => '"' . $row['etag'] . '"',
1211
+                'calendarid' => $row['calendarid'],
1212
+                'calendaruri' => $row['calendaruri'],
1213
+                'size' => (int)$row['size'],
1214
+                'component' => strtolower($row['componenttype']),
1215
+                'classification' => (int)$row['classification'],
1216
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1217
+            ];
1218
+        }
1219
+        $stmt->closeCursor();
1220
+
1221
+        return $result;
1222
+    }
1223
+
1224
+    /**
1225
+     * Returns information from a single calendar object, based on it's object
1226
+     * uri.
1227
+     *
1228
+     * The object uri is only the basename, or filename and not a full path.
1229
+     *
1230
+     * The returned array must have the same keys as getCalendarObjects. The
1231
+     * 'calendardata' object is required here though, while it's not required
1232
+     * for getCalendarObjects.
1233
+     *
1234
+     * This method must return null if the object did not exist.
1235
+     *
1236
+     * @param mixed $calendarId
1237
+     * @param string $objectUri
1238
+     * @param int $calendarType
1239
+     * @return array|null
1240
+     */
1241
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1242
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1243
+        if (isset($this->cachedObjects[$key])) {
1244
+            return $this->cachedObjects[$key];
1245
+        }
1246
+        $query = $this->db->getQueryBuilder();
1247
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1248
+            ->from('calendarobjects')
1249
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1250
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1251
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1252
+        $stmt = $query->executeQuery();
1253
+        $row = $stmt->fetchAssociative();
1254
+        $stmt->closeCursor();
1255
+
1256
+        if (!$row) {
1257
+            return null;
1258
+        }
1259
+
1260
+        $object = $this->rowToCalendarObject($row);
1261
+        $this->cachedObjects[$key] = $object;
1262
+        return $object;
1263
+    }
1264
+
1265
+    private function rowToCalendarObject(array $row): array {
1266
+        return [
1267
+            'id' => $row['id'],
1268
+            'uri' => $row['uri'],
1269
+            'uid' => $row['uid'],
1270
+            'lastmodified' => $row['lastmodified'],
1271
+            'etag' => '"' . $row['etag'] . '"',
1272
+            'calendarid' => $row['calendarid'],
1273
+            'size' => (int)$row['size'],
1274
+            'calendardata' => $this->readBlob($row['calendardata']),
1275
+            'component' => strtolower($row['componenttype']),
1276
+            'classification' => (int)$row['classification'],
1277
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1278
+        ];
1279
+    }
1280
+
1281
+    /**
1282
+     * Returns a list of calendar objects.
1283
+     *
1284
+     * This method should work identical to getCalendarObject, but instead
1285
+     * return all the calendar objects in the list as an array.
1286
+     *
1287
+     * If the backend supports this, it may allow for some speed-ups.
1288
+     *
1289
+     * @param mixed $calendarId
1290
+     * @param string[] $uris
1291
+     * @param int $calendarType
1292
+     * @return array
1293
+     */
1294
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1295
+        if (empty($uris)) {
1296
+            return [];
1297
+        }
1298
+
1299
+        $chunks = array_chunk($uris, 100);
1300
+        $objects = [];
1301
+
1302
+        $query = $this->db->getQueryBuilder();
1303
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1304
+            ->from('calendarobjects')
1305
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1306
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1307
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1308
+            ->andWhere($query->expr()->isNull('deleted_at'));
1309
+
1310
+        foreach ($chunks as $uris) {
1311
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1312
+            $result = $query->executeQuery();
1313
+
1314
+            while ($row = $result->fetchAssociative()) {
1315
+                $objects[] = [
1316
+                    'id' => $row['id'],
1317
+                    'uri' => $row['uri'],
1318
+                    'lastmodified' => $row['lastmodified'],
1319
+                    'etag' => '"' . $row['etag'] . '"',
1320
+                    'calendarid' => $row['calendarid'],
1321
+                    'size' => (int)$row['size'],
1322
+                    'calendardata' => $this->readBlob($row['calendardata']),
1323
+                    'component' => strtolower($row['componenttype']),
1324
+                    'classification' => (int)$row['classification']
1325
+                ];
1326
+            }
1327
+            $result->closeCursor();
1328
+        }
1329
+
1330
+        return $objects;
1331
+    }
1332
+
1333
+    /**
1334
+     * Creates a new calendar object.
1335
+     *
1336
+     * The object uri is only the basename, or filename and not a full path.
1337
+     *
1338
+     * It is possible return an etag from this function, which will be used in
1339
+     * the response to this PUT request. Note that the ETag must be surrounded
1340
+     * by double-quotes.
1341
+     *
1342
+     * However, you should only really return this ETag if you don't mangle the
1343
+     * calendar-data. If the result of a subsequent GET to this object is not
1344
+     * the exact same as this request body, you should omit the ETag.
1345
+     *
1346
+     * @param mixed $calendarId
1347
+     * @param string $objectUri
1348
+     * @param string $calendarData
1349
+     * @param int $calendarType
1350
+     * @return string
1351
+     */
1352
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1353
+        $this->cachedObjects = [];
1354
+        $extraData = $this->getDenormalizedData($calendarData);
1355
+
1356
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1357
+            // Try to detect duplicates
1358
+            $qb = $this->db->getQueryBuilder();
1359
+            $qb->select($qb->func()->count('*'))
1360
+                ->from('calendarobjects')
1361
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1362
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1363
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1364
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1365
+            $result = $qb->executeQuery();
1366
+            $count = (int)$result->fetchOne();
1367
+            $result->closeCursor();
1368
+
1369
+            if ($count !== 0) {
1370
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1371
+            }
1372
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1373
+            $qbDel = $this->db->getQueryBuilder();
1374
+            $qbDel->select('*')
1375
+                ->from('calendarobjects')
1376
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1377
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1378
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1379
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1380
+            $result = $qbDel->executeQuery();
1381
+            $found = $result->fetchAssociative();
1382
+            $result->closeCursor();
1383
+            if ($found !== false) {
1384
+                // the object existed previously but has been deleted
1385
+                // remove the trashbin entry and continue as if it was a new object
1386
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1387
+            }
1388
+
1389
+            $query = $this->db->getQueryBuilder();
1390
+            $query->insert('calendarobjects')
1391
+                ->values([
1392
+                    'calendarid' => $query->createNamedParameter($calendarId),
1393
+                    'uri' => $query->createNamedParameter($objectUri),
1394
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1395
+                    'lastmodified' => $query->createNamedParameter(time()),
1396
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1397
+                    'size' => $query->createNamedParameter($extraData['size']),
1398
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1399
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1400
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1401
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1402
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1403
+                    'calendartype' => $query->createNamedParameter($calendarType),
1404
+                ])
1405
+                ->executeStatement();
1406
+
1407
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1408
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1409
+
1410
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1411
+            assert($objectRow !== null);
1412
+
1413
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1414
+                $calendarRow = $this->getCalendarById($calendarId);
1415
+                $shares = $this->getShares($calendarId);
1416
+
1417
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1418
+            } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1419
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1420
+
1421
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1422
+            } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1423
+                // TODO: implement custom event for federated calendars
1424
+            }
1425
+
1426
+            return '"' . $extraData['etag'] . '"';
1427
+        }, $this->db);
1428
+    }
1429
+
1430
+    /**
1431
+     * Updates an existing calendarobject, based on it's uri.
1432
+     *
1433
+     * The object uri is only the basename, or filename and not a full path.
1434
+     *
1435
+     * It is possible return an etag from this function, which will be used in
1436
+     * the response to this PUT request. Note that the ETag must be surrounded
1437
+     * by double-quotes.
1438
+     *
1439
+     * However, you should only really return this ETag if you don't mangle the
1440
+     * calendar-data. If the result of a subsequent GET to this object is not
1441
+     * the exact same as this request body, you should omit the ETag.
1442
+     *
1443
+     * @param mixed $calendarId
1444
+     * @param string $objectUri
1445
+     * @param string $calendarData
1446
+     * @param int $calendarType
1447
+     * @return string
1448
+     */
1449
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1450
+        $this->cachedObjects = [];
1451
+        $extraData = $this->getDenormalizedData($calendarData);
1452
+
1453
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1454
+            $query = $this->db->getQueryBuilder();
1455
+            $query->update('calendarobjects')
1456
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1457
+                ->set('lastmodified', $query->createNamedParameter(time()))
1458
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1459
+                ->set('size', $query->createNamedParameter($extraData['size']))
1460
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1461
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1462
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1463
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1464
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1465
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1466
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1467
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1468
+                ->executeStatement();
1469
+
1470
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1471
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1472
+
1473
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1474
+            if (is_array($objectRow)) {
1475
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1476
+                    $calendarRow = $this->getCalendarById($calendarId);
1477
+                    $shares = $this->getShares($calendarId);
1478
+
1479
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1480
+                } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1481
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1482
+
1483
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1484
+                } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1485
+                    // TODO: implement custom event for federated calendars
1486
+                }
1487
+            }
1488
+
1489
+            return '"' . $extraData['etag'] . '"';
1490
+        }, $this->db);
1491
+    }
1492
+
1493
+    /**
1494
+     * Moves a calendar object from calendar to calendar.
1495
+     *
1496
+     * @param string $sourcePrincipalUri
1497
+     * @param int $sourceObjectId
1498
+     * @param string $targetPrincipalUri
1499
+     * @param int $targetCalendarId
1500
+     * @param string $tragetObjectUri
1501
+     * @param int $calendarType
1502
+     * @return bool
1503
+     * @throws Exception
1504
+     */
1505
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1506
+        $this->cachedObjects = [];
1507
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1508
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1509
+            if (empty($object)) {
1510
+                return false;
1511
+            }
1512
+
1513
+            $sourceCalendarId = $object['calendarid'];
1514
+            $sourceObjectUri = $object['uri'];
1515
+
1516
+            $query = $this->db->getQueryBuilder();
1517
+            $query->update('calendarobjects')
1518
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1519
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1520
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1521
+                ->executeStatement();
1522
+
1523
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1524
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1525
+
1526
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1527
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1528
+
1529
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1530
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1531
+            if (empty($object)) {
1532
+                return false;
1533
+            }
1534
+
1535
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1536
+            // the calendar this event is being moved to does not exist any longer
1537
+            if (empty($targetCalendarRow)) {
1538
+                return false;
1539
+            }
1540
+
1541
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1542
+                $sourceShares = $this->getShares($sourceCalendarId);
1543
+                $targetShares = $this->getShares($targetCalendarId);
1544
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1545
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1546
+            }
1547
+            return true;
1548
+        }, $this->db);
1549
+    }
1550
+
1551
+    /**
1552
+     * Deletes an existing calendar object.
1553
+     *
1554
+     * The object uri is only the basename, or filename and not a full path.
1555
+     *
1556
+     * @param mixed $calendarId
1557
+     * @param string $objectUri
1558
+     * @param int $calendarType
1559
+     * @param bool $forceDeletePermanently
1560
+     * @return void
1561
+     */
1562
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1563
+        $this->cachedObjects = [];
1564
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1565
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1566
+
1567
+            if ($data === null) {
1568
+                // Nothing to delete
1569
+                return;
1570
+            }
1571
+
1572
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1573
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1574
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1575
+
1576
+                $this->purgeProperties($calendarId, $data['id']);
1577
+
1578
+                $this->purgeObjectInvitations($data['uid']);
1579
+
1580
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1581
+                    $calendarRow = $this->getCalendarById($calendarId);
1582
+                    $shares = $this->getShares($calendarId);
1583
+
1584
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1585
+                } else {
1586
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1587
+
1588
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1589
+                }
1590
+            } else {
1591
+                $pathInfo = pathinfo($data['uri']);
1592
+                if (!empty($pathInfo['extension'])) {
1593
+                    // Append a suffix to "free" the old URI for recreation
1594
+                    $newUri = sprintf(
1595
+                        '%s-deleted.%s',
1596
+                        $pathInfo['filename'],
1597
+                        $pathInfo['extension']
1598
+                    );
1599
+                } else {
1600
+                    $newUri = sprintf(
1601
+                        '%s-deleted',
1602
+                        $pathInfo['filename']
1603
+                    );
1604
+                }
1605
+
1606
+                // Try to detect conflicts before the DB does
1607
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1608
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1609
+                if ($newObject !== null) {
1610
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1611
+                }
1612
+
1613
+                $qb = $this->db->getQueryBuilder();
1614
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1615
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1616
+                    ->set('uri', $qb->createNamedParameter($newUri))
1617
+                    ->where(
1618
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1619
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1620
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1621
+                    );
1622
+                $markObjectDeletedQuery->executeStatement();
1623
+
1624
+                $calendarData = $this->getCalendarById($calendarId);
1625
+                if ($calendarData !== null) {
1626
+                    $this->dispatcher->dispatchTyped(
1627
+                        new CalendarObjectMovedToTrashEvent(
1628
+                            $calendarId,
1629
+                            $calendarData,
1630
+                            $this->getShares($calendarId),
1631
+                            $data
1632
+                        )
1633
+                    );
1634
+                }
1635
+            }
1636
+
1637
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1638
+        }, $this->db);
1639
+    }
1640
+
1641
+    /**
1642
+     * @param mixed $objectData
1643
+     *
1644
+     * @throws Forbidden
1645
+     */
1646
+    public function restoreCalendarObject(array $objectData): void {
1647
+        $this->cachedObjects = [];
1648
+        $this->atomic(function () use ($objectData): void {
1649
+            $id = (int)$objectData['id'];
1650
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1651
+            $targetObject = $this->getCalendarObject(
1652
+                $objectData['calendarid'],
1653
+                $restoreUri
1654
+            );
1655
+            if ($targetObject !== null) {
1656
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1657
+            }
1658
+
1659
+            $qb = $this->db->getQueryBuilder();
1660
+            $update = $qb->update('calendarobjects')
1661
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1662
+                ->set('deleted_at', $qb->createNamedParameter(null))
1663
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1664
+            $update->executeStatement();
1665
+
1666
+            // Make sure this change is tracked in the changes table
1667
+            $qb2 = $this->db->getQueryBuilder();
1668
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1669
+                ->selectAlias('componenttype', 'component')
1670
+                ->from('calendarobjects')
1671
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1672
+            $result = $selectObject->executeQuery();
1673
+            $row = $result->fetchAssociative();
1674
+            $result->closeCursor();
1675
+            if ($row === false) {
1676
+                // Welp, this should possibly not have happened, but let's ignore
1677
+                return;
1678
+            }
1679
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1680
+
1681
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1682
+            if ($calendarRow === null) {
1683
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1684
+            }
1685
+            $this->dispatcher->dispatchTyped(
1686
+                new CalendarObjectRestoredEvent(
1687
+                    (int)$objectData['calendarid'],
1688
+                    $calendarRow,
1689
+                    $this->getShares((int)$row['calendarid']),
1690
+                    $row
1691
+                )
1692
+            );
1693
+        }, $this->db);
1694
+    }
1695
+
1696
+    /**
1697
+     * Performs a calendar-query on the contents of this calendar.
1698
+     *
1699
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1700
+     * calendar-query it is possible for a client to request a specific set of
1701
+     * object, based on contents of iCalendar properties, date-ranges and
1702
+     * iCalendar component types (VTODO, VEVENT).
1703
+     *
1704
+     * This method should just return a list of (relative) urls that match this
1705
+     * query.
1706
+     *
1707
+     * The list of filters are specified as an array. The exact array is
1708
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1709
+     *
1710
+     * Note that it is extremely likely that getCalendarObject for every path
1711
+     * returned from this method will be called almost immediately after. You
1712
+     * may want to anticipate this to speed up these requests.
1713
+     *
1714
+     * This method provides a default implementation, which parses *all* the
1715
+     * iCalendar objects in the specified calendar.
1716
+     *
1717
+     * This default may well be good enough for personal use, and calendars
1718
+     * that aren't very large. But if you anticipate high usage, big calendars
1719
+     * or high loads, you are strongly advised to optimize certain paths.
1720
+     *
1721
+     * The best way to do so is override this method and to optimize
1722
+     * specifically for 'common filters'.
1723
+     *
1724
+     * Requests that are extremely common are:
1725
+     *   * requests for just VEVENTS
1726
+     *   * requests for just VTODO
1727
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1728
+     *
1729
+     * ..and combinations of these requests. It may not be worth it to try to
1730
+     * handle every possible situation and just rely on the (relatively
1731
+     * easy to use) CalendarQueryValidator to handle the rest.
1732
+     *
1733
+     * Note that especially time-range-filters may be difficult to parse. A
1734
+     * time-range filter specified on a VEVENT must for instance also handle
1735
+     * recurrence rules correctly.
1736
+     * A good example of how to interpret all these filters can also simply
1737
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1738
+     * as possible, so it gives you a good idea on what type of stuff you need
1739
+     * to think of.
1740
+     *
1741
+     * @param mixed $calendarId
1742
+     * @param array $filters
1743
+     * @param int $calendarType
1744
+     * @return array
1745
+     */
1746
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1747
+        $componentType = null;
1748
+        $requirePostFilter = true;
1749
+        $timeRange = null;
1750
+
1751
+        // if no filters were specified, we don't need to filter after a query
1752
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1753
+            $requirePostFilter = false;
1754
+        }
1755
+
1756
+        // Figuring out if there's a component filter
1757
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1758
+            $componentType = $filters['comp-filters'][0]['name'];
1759
+
1760
+            // Checking if we need post-filters
1761
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1762
+                $requirePostFilter = false;
1763
+            }
1764
+            // There was a time-range filter
1765
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1766
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1767
+
1768
+                // If start time OR the end time is not specified, we can do a
1769
+                // 100% accurate mysql query.
1770
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1771
+                    $requirePostFilter = false;
1772
+                }
1773
+            }
1774
+        }
1775
+        $query = $this->db->getQueryBuilder();
1776
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1777
+            ->from('calendarobjects')
1778
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1779
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1780
+            ->andWhere($query->expr()->isNull('deleted_at'));
1781
+
1782
+        if ($componentType) {
1783
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1784
+        }
1785
+
1786
+        if ($timeRange && $timeRange['start']) {
1787
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1788
+        }
1789
+        if ($timeRange && $timeRange['end']) {
1790
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1791
+        }
1792
+
1793
+        $stmt = $query->executeQuery();
1794
+
1795
+        $result = [];
1796
+        while ($row = $stmt->fetchAssociative()) {
1797
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1798
+            if (isset($row['calendardata'])) {
1799
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1800
+            }
1801
+
1802
+            if ($requirePostFilter) {
1803
+                // validateFilterForObject will parse the calendar data
1804
+                // catch parsing errors
1805
+                try {
1806
+                    $matches = $this->validateFilterForObject($row, $filters);
1807
+                } catch (ParseException $ex) {
1808
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1809
+                        'app' => 'dav',
1810
+                        'exception' => $ex,
1811
+                    ]);
1812
+                    continue;
1813
+                } catch (InvalidDataException $ex) {
1814
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1815
+                        'app' => 'dav',
1816
+                        'exception' => $ex,
1817
+                    ]);
1818
+                    continue;
1819
+                } catch (MaxInstancesExceededException $ex) {
1820
+                    $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1821
+                        'app' => 'dav',
1822
+                        'exception' => $ex,
1823
+                    ]);
1824
+                    continue;
1825
+                }
1826
+
1827
+                if (!$matches) {
1828
+                    continue;
1829
+                }
1830
+            }
1831
+            $result[] = $row['uri'];
1832
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1833
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1834
+        }
1835
+
1836
+        return $result;
1837
+    }
1838
+
1839
+    /**
1840
+     * custom Nextcloud search extension for CalDAV
1841
+     *
1842
+     * TODO - this should optionally cover cached calendar objects as well
1843
+     *
1844
+     * @param string $principalUri
1845
+     * @param array $filters
1846
+     * @param integer|null $limit
1847
+     * @param integer|null $offset
1848
+     * @return array
1849
+     */
1850
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1851
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1852
+            $calendars = $this->getCalendarsForUser($principalUri);
1853
+            $ownCalendars = [];
1854
+            $sharedCalendars = [];
1855
+
1856
+            $uriMapper = [];
1857
+
1858
+            foreach ($calendars as $calendar) {
1859
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1860
+                    $ownCalendars[] = $calendar['id'];
1861
+                } else {
1862
+                    $sharedCalendars[] = $calendar['id'];
1863
+                }
1864
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1865
+            }
1866
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1867
+                return [];
1868
+            }
1869
+
1870
+            $query = $this->db->getQueryBuilder();
1871
+            // Calendar id expressions
1872
+            $calendarExpressions = [];
1873
+            foreach ($ownCalendars as $id) {
1874
+                $calendarExpressions[] = $query->expr()->andX(
1875
+                    $query->expr()->eq('c.calendarid',
1876
+                        $query->createNamedParameter($id)),
1877
+                    $query->expr()->eq('c.calendartype',
1878
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1879
+            }
1880
+            foreach ($sharedCalendars as $id) {
1881
+                $calendarExpressions[] = $query->expr()->andX(
1882
+                    $query->expr()->eq('c.calendarid',
1883
+                        $query->createNamedParameter($id)),
1884
+                    $query->expr()->eq('c.classification',
1885
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1886
+                    $query->expr()->eq('c.calendartype',
1887
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1888
+            }
1889
+
1890
+            if (count($calendarExpressions) === 1) {
1891
+                $calExpr = $calendarExpressions[0];
1892
+            } else {
1893
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1894
+            }
1895
+
1896
+            // Component expressions
1897
+            $compExpressions = [];
1898
+            foreach ($filters['comps'] as $comp) {
1899
+                $compExpressions[] = $query->expr()
1900
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1901
+            }
1902
+
1903
+            if (count($compExpressions) === 1) {
1904
+                $compExpr = $compExpressions[0];
1905
+            } else {
1906
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1907
+            }
1908
+
1909
+            if (!isset($filters['props'])) {
1910
+                $filters['props'] = [];
1911
+            }
1912
+            if (!isset($filters['params'])) {
1913
+                $filters['params'] = [];
1914
+            }
1915
+
1916
+            $propParamExpressions = [];
1917
+            foreach ($filters['props'] as $prop) {
1918
+                $propParamExpressions[] = $query->expr()->andX(
1919
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1920
+                    $query->expr()->isNull('i.parameter')
1921
+                );
1922
+            }
1923
+            foreach ($filters['params'] as $param) {
1924
+                $propParamExpressions[] = $query->expr()->andX(
1925
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1926
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1927
+                );
1928
+            }
1929
+
1930
+            if (count($propParamExpressions) === 1) {
1931
+                $propParamExpr = $propParamExpressions[0];
1932
+            } else {
1933
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1934
+            }
1935
+
1936
+            $query->select(['c.calendarid', 'c.uri'])
1937
+                ->from($this->dbObjectPropertiesTable, 'i')
1938
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1939
+                ->where($calExpr)
1940
+                ->andWhere($compExpr)
1941
+                ->andWhere($propParamExpr)
1942
+                ->andWhere($query->expr()->iLike('i.value',
1943
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1944
+                ->andWhere($query->expr()->isNull('deleted_at'));
1945
+
1946
+            if ($offset) {
1947
+                $query->setFirstResult($offset);
1948
+            }
1949
+            if ($limit) {
1950
+                $query->setMaxResults($limit);
1951
+            }
1952
+
1953
+            $stmt = $query->executeQuery();
1954
+
1955
+            $result = [];
1956
+            while ($row = $stmt->fetchAssociative()) {
1957
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1958
+                if (!in_array($path, $result)) {
1959
+                    $result[] = $path;
1960
+                }
1961
+            }
1962
+
1963
+            return $result;
1964
+        }, $this->db);
1965
+    }
1966
+
1967
+    /**
1968
+     * used for Nextcloud's calendar API
1969
+     *
1970
+     * @param array $calendarInfo
1971
+     * @param string $pattern
1972
+     * @param array $searchProperties
1973
+     * @param array $options
1974
+     * @param integer|null $limit
1975
+     * @param integer|null $offset
1976
+     *
1977
+     * @return array
1978
+     */
1979
+    public function search(
1980
+        array $calendarInfo,
1981
+        $pattern,
1982
+        array $searchProperties,
1983
+        array $options,
1984
+        $limit,
1985
+        $offset,
1986
+    ) {
1987
+        $outerQuery = $this->db->getQueryBuilder();
1988
+        $innerQuery = $this->db->getQueryBuilder();
1989
+
1990
+        if (isset($calendarInfo['source'])) {
1991
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1992
+        } elseif (isset($calendarInfo['federated'])) {
1993
+            $calendarType = self::CALENDAR_TYPE_FEDERATED;
1994
+        } else {
1995
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
1996
+        }
1997
+
1998
+        $innerQuery->selectDistinct('op.objectid')
1999
+            ->from($this->dbObjectPropertiesTable, 'op')
2000
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
2001
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
2002
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
2003
+                $outerQuery->createNamedParameter($calendarType)));
2004
+
2005
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2006
+            ->from('calendarobjects', 'c')
2007
+            ->where($outerQuery->expr()->isNull('deleted_at'));
2008
+
2009
+        // only return public items for shared calendars for now
2010
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2011
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2012
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2013
+        }
2014
+
2015
+        if (!empty($searchProperties)) {
2016
+            $or = [];
2017
+            foreach ($searchProperties as $searchProperty) {
2018
+                $or[] = $innerQuery->expr()->eq('op.name',
2019
+                    $outerQuery->createNamedParameter($searchProperty));
2020
+            }
2021
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2022
+        }
2023
+
2024
+        if ($pattern !== '') {
2025
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2026
+                $outerQuery->createNamedParameter('%'
2027
+                    . $this->db->escapeLikeParameter($pattern) . '%')));
2028
+        }
2029
+
2030
+        $start = null;
2031
+        $end = null;
2032
+
2033
+        $hasLimit = is_int($limit);
2034
+        $hasTimeRange = false;
2035
+
2036
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2037
+            /** @var DateTimeInterface $start */
2038
+            $start = $options['timerange']['start'];
2039
+            $outerQuery->andWhere(
2040
+                $outerQuery->expr()->gt(
2041
+                    'lastoccurence',
2042
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2043
+                )
2044
+            );
2045
+            $hasTimeRange = true;
2046
+        }
2047
+
2048
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2049
+            /** @var DateTimeInterface $end */
2050
+            $end = $options['timerange']['end'];
2051
+            $outerQuery->andWhere(
2052
+                $outerQuery->expr()->lt(
2053
+                    'firstoccurence',
2054
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2055
+                )
2056
+            );
2057
+            $hasTimeRange = true;
2058
+        }
2059
+
2060
+        if (isset($options['uid'])) {
2061
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2062
+        }
2063
+
2064
+        if (!empty($options['types'])) {
2065
+            $or = [];
2066
+            foreach ($options['types'] as $type) {
2067
+                $or[] = $outerQuery->expr()->eq('componenttype',
2068
+                    $outerQuery->createNamedParameter($type));
2069
+            }
2070
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2071
+        }
2072
+
2073
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2074
+
2075
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2076
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2077
+        $outerQuery->addOrderBy('id');
2078
+
2079
+        $offset = (int)$offset;
2080
+        $outerQuery->setFirstResult($offset);
2081
+
2082
+        $calendarObjects = [];
2083
+
2084
+        if ($hasLimit && $hasTimeRange) {
2085
+            /**
2086
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2087
+             *
2088
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2089
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2090
+             *
2091
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2092
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2093
+             * the next 14 days and end up with an empty result even if there are two events to show.
2094
+             *
2095
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2096
+             * and retrying if we have not reached the limit.
2097
+             *
2098
+             * 25 rows and 3 retries is entirely arbitrary.
2099
+             */
2100
+            $maxResults = (int)max($limit, 25);
2101
+            $outerQuery->setMaxResults($maxResults);
2102
+
2103
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2104
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2105
+                $outerQuery->setFirstResult($offset += $maxResults);
2106
+            }
2107
+
2108
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2109
+        } else {
2110
+            $outerQuery->setMaxResults($limit);
2111
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2112
+        }
2113
+
2114
+        $calendarObjects = array_map(function ($o) use ($options) {
2115
+            $calendarData = Reader::read($o['calendardata']);
2116
+
2117
+            // Expand recurrences if an explicit time range is requested
2118
+            if ($calendarData instanceof VCalendar
2119
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2120
+                $calendarData = $calendarData->expand(
2121
+                    $options['timerange']['start'],
2122
+                    $options['timerange']['end'],
2123
+                );
2124
+            }
2125
+
2126
+            $comps = $calendarData->getComponents();
2127
+            $objects = [];
2128
+            $timezones = [];
2129
+            foreach ($comps as $comp) {
2130
+                if ($comp instanceof VTimeZone) {
2131
+                    $timezones[] = $comp;
2132
+                } else {
2133
+                    $objects[] = $comp;
2134
+                }
2135
+            }
2136
+
2137
+            return [
2138
+                'id' => $o['id'],
2139
+                'type' => $o['componenttype'],
2140
+                'uid' => $o['uid'],
2141
+                'uri' => $o['uri'],
2142
+                'objects' => array_map(function ($c) {
2143
+                    return $this->transformSearchData($c);
2144
+                }, $objects),
2145
+                'timezones' => array_map(function ($c) {
2146
+                    return $this->transformSearchData($c);
2147
+                }, $timezones),
2148
+            ];
2149
+        }, $calendarObjects);
2150
+
2151
+        usort($calendarObjects, function (array $a, array $b) {
2152
+            /** @var DateTimeImmutable $startA */
2153
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2154
+            /** @var DateTimeImmutable $startB */
2155
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2156
+
2157
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2158
+        });
2159
+
2160
+        return $calendarObjects;
2161
+    }
2162
+
2163
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2164
+        $calendarObjects = [];
2165
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2166
+
2167
+        $result = $query->executeQuery();
2168
+
2169
+        while (($row = $result->fetchAssociative()) !== false) {
2170
+            if ($filterByTimeRange === false) {
2171
+                // No filter required
2172
+                $calendarObjects[] = $row;
2173
+                continue;
2174
+            }
2175
+
2176
+            try {
2177
+                $isValid = $this->validateFilterForObject($row, [
2178
+                    'name' => 'VCALENDAR',
2179
+                    'comp-filters' => [
2180
+                        [
2181
+                            'name' => 'VEVENT',
2182
+                            'comp-filters' => [],
2183
+                            'prop-filters' => [],
2184
+                            'is-not-defined' => false,
2185
+                            'time-range' => [
2186
+                                'start' => $start,
2187
+                                'end' => $end,
2188
+                            ],
2189
+                        ],
2190
+                    ],
2191
+                    'prop-filters' => [],
2192
+                    'is-not-defined' => false,
2193
+                    'time-range' => null,
2194
+                ]);
2195
+            } catch (MaxInstancesExceededException $ex) {
2196
+                $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2197
+                    'app' => 'dav',
2198
+                    'exception' => $ex,
2199
+                ]);
2200
+                continue;
2201
+            }
2202
+
2203
+            if (is_resource($row['calendardata'])) {
2204
+                // Put the stream back to the beginning so it can be read another time
2205
+                rewind($row['calendardata']);
2206
+            }
2207
+
2208
+            if ($isValid) {
2209
+                $calendarObjects[] = $row;
2210
+            }
2211
+        }
2212
+
2213
+        $result->closeCursor();
2214
+
2215
+        return $calendarObjects;
2216
+    }
2217
+
2218
+    /**
2219
+     * @param Component $comp
2220
+     * @return array
2221
+     */
2222
+    private function transformSearchData(Component $comp) {
2223
+        $data = [];
2224
+        /** @var Component[] $subComponents */
2225
+        $subComponents = $comp->getComponents();
2226
+        /** @var Property[] $properties */
2227
+        $properties = array_filter($comp->children(), function ($c) {
2228
+            return $c instanceof Property;
2229
+        });
2230
+        $validationRules = $comp->getValidationRules();
2231
+
2232
+        foreach ($subComponents as $subComponent) {
2233
+            $name = $subComponent->name;
2234
+            if (!isset($data[$name])) {
2235
+                $data[$name] = [];
2236
+            }
2237
+            $data[$name][] = $this->transformSearchData($subComponent);
2238
+        }
2239
+
2240
+        foreach ($properties as $property) {
2241
+            $name = $property->name;
2242
+            if (!isset($validationRules[$name])) {
2243
+                $validationRules[$name] = '*';
2244
+            }
2245
+
2246
+            $rule = $validationRules[$property->name];
2247
+            if ($rule === '+' || $rule === '*') { // multiple
2248
+                if (!isset($data[$name])) {
2249
+                    $data[$name] = [];
2250
+                }
2251
+
2252
+                $data[$name][] = $this->transformSearchProperty($property);
2253
+            } else { // once
2254
+                $data[$name] = $this->transformSearchProperty($property);
2255
+            }
2256
+        }
2257
+
2258
+        return $data;
2259
+    }
2260
+
2261
+    /**
2262
+     * @param Property $prop
2263
+     * @return array
2264
+     */
2265
+    private function transformSearchProperty(Property $prop) {
2266
+        // No need to check Date, as it extends DateTime
2267
+        if ($prop instanceof Property\ICalendar\DateTime) {
2268
+            $value = $prop->getDateTime();
2269
+        } else {
2270
+            $value = $prop->getValue();
2271
+        }
2272
+
2273
+        return [
2274
+            $value,
2275
+            $prop->parameters()
2276
+        ];
2277
+    }
2278
+
2279
+    /**
2280
+     * @param string $principalUri
2281
+     * @param string $pattern
2282
+     * @param array $componentTypes
2283
+     * @param array $searchProperties
2284
+     * @param array $searchParameters
2285
+     * @param array $options
2286
+     * @return array
2287
+     */
2288
+    public function searchPrincipalUri(string $principalUri,
2289
+        string $pattern,
2290
+        array $componentTypes,
2291
+        array $searchProperties,
2292
+        array $searchParameters,
2293
+        array $options = [],
2294
+    ): array {
2295
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2296
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2297
+
2298
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2299
+            $calendarOr = [];
2300
+            $searchOr = [];
2301
+
2302
+            // Fetch calendars and subscription
2303
+            $calendars = $this->getCalendarsForUser($principalUri);
2304
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2305
+            foreach ($calendars as $calendar) {
2306
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2307
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2308
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2309
+                );
2310
+
2311
+                // If it's shared, limit search to public events
2312
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2313
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2314
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2315
+                }
2316
+
2317
+                $calendarOr[] = $calendarAnd;
2318
+            }
2319
+            foreach ($subscriptions as $subscription) {
2320
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2321
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2322
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2323
+                );
2324
+
2325
+                // If it's shared, limit search to public events
2326
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2327
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2328
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2329
+                }
2330
+
2331
+                $calendarOr[] = $subscriptionAnd;
2332
+            }
2333
+
2334
+            foreach ($searchProperties as $property) {
2335
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2336
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2337
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2338
+                );
2339
+
2340
+                $searchOr[] = $propertyAnd;
2341
+            }
2342
+            foreach ($searchParameters as $property => $parameter) {
2343
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2344
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2345
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2346
+                );
2347
+
2348
+                $searchOr[] = $parameterAnd;
2349
+            }
2350
+
2351
+            if (empty($calendarOr)) {
2352
+                return [];
2353
+            }
2354
+            if (empty($searchOr)) {
2355
+                return [];
2356
+            }
2357
+
2358
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2359
+                ->from($this->dbObjectPropertiesTable, 'cob')
2360
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2361
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2362
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2363
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2364
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2365
+
2366
+            if ($pattern !== '') {
2367
+                if (!$escapePattern) {
2368
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2369
+                } else {
2370
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2371
+                }
2372
+            }
2373
+
2374
+            if (isset($options['limit'])) {
2375
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2376
+            }
2377
+            if (isset($options['offset'])) {
2378
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2379
+            }
2380
+            if (isset($options['timerange'])) {
2381
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2382
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2383
+                        'lastoccurence',
2384
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2385
+                    ));
2386
+                }
2387
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2388
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2389
+                        'firstoccurence',
2390
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2391
+                    ));
2392
+                }
2393
+            }
2394
+
2395
+            $result = $calendarObjectIdQuery->executeQuery();
2396
+            $matches = [];
2397
+            while (($row = $result->fetchAssociative()) !== false) {
2398
+                $matches[] = (int)$row['objectid'];
2399
+            }
2400
+            $result->closeCursor();
2401
+
2402
+            $query = $this->db->getQueryBuilder();
2403
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2404
+                ->from('calendarobjects')
2405
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2406
+
2407
+            $result = $query->executeQuery();
2408
+            $calendarObjects = [];
2409
+            while (($array = $result->fetchAssociative()) !== false) {
2410
+                $array['calendarid'] = (int)$array['calendarid'];
2411
+                $array['calendartype'] = (int)$array['calendartype'];
2412
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2413
+
2414
+                $calendarObjects[] = $array;
2415
+            }
2416
+            $result->closeCursor();
2417
+            return $calendarObjects;
2418
+        }, $this->db);
2419
+    }
2420
+
2421
+    /**
2422
+     * Searches through all of a users calendars and calendar objects to find
2423
+     * an object with a specific UID.
2424
+     *
2425
+     * This method should return the path to this object, relative to the
2426
+     * calendar home, so this path usually only contains two parts:
2427
+     *
2428
+     * calendarpath/objectpath.ics
2429
+     *
2430
+     * If the uid is not found, return null.
2431
+     *
2432
+     * This method should only consider * objects that the principal owns, so
2433
+     * any calendars owned by other principals that also appear in this
2434
+     * collection should be ignored.
2435
+     *
2436
+     * @param string $principalUri
2437
+     * @param string $uid
2438
+     * @return string|null
2439
+     */
2440
+    public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2441
+        $query = $this->db->getQueryBuilder();
2442
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2443
+            ->from('calendarobjects', 'co')
2444
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2445
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2446
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2447
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2448
+
2449
+        if ($calendarUri !== null) {
2450
+            $query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2451
+        }
2452
+
2453
+        $stmt = $query->executeQuery();
2454
+        $row = $stmt->fetchAssociative();
2455
+        $stmt->closeCursor();
2456
+        if ($row) {
2457
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2458
+        }
2459
+
2460
+        return null;
2461
+    }
2462
+
2463
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2464
+        $query = $this->db->getQueryBuilder();
2465
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2466
+            ->selectAlias('c.uri', 'calendaruri')
2467
+            ->from('calendarobjects', 'co')
2468
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2469
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2470
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2471
+        $stmt = $query->executeQuery();
2472
+        $row = $stmt->fetchAssociative();
2473
+        $stmt->closeCursor();
2474
+
2475
+        if (!$row) {
2476
+            return null;
2477
+        }
2478
+
2479
+        return [
2480
+            'id' => $row['id'],
2481
+            'uri' => $row['uri'],
2482
+            'lastmodified' => $row['lastmodified'],
2483
+            'etag' => '"' . $row['etag'] . '"',
2484
+            'calendarid' => $row['calendarid'],
2485
+            'calendaruri' => $row['calendaruri'],
2486
+            'size' => (int)$row['size'],
2487
+            'calendardata' => $this->readBlob($row['calendardata']),
2488
+            'component' => strtolower($row['componenttype']),
2489
+            'classification' => (int)$row['classification'],
2490
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2491
+        ];
2492
+    }
2493
+
2494
+    /**
2495
+     * The getChanges method returns all the changes that have happened, since
2496
+     * the specified syncToken in the specified calendar.
2497
+     *
2498
+     * This function should return an array, such as the following:
2499
+     *
2500
+     * [
2501
+     *   'syncToken' => 'The current synctoken',
2502
+     *   'added'   => [
2503
+     *      'new.txt',
2504
+     *   ],
2505
+     *   'modified'   => [
2506
+     *      'modified.txt',
2507
+     *   ],
2508
+     *   'deleted' => [
2509
+     *      'foo.php.bak',
2510
+     *      'old.txt'
2511
+     *   ]
2512
+     * );
2513
+     *
2514
+     * The returned syncToken property should reflect the *current* syncToken
2515
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2516
+     * property This is * needed here too, to ensure the operation is atomic.
2517
+     *
2518
+     * If the $syncToken argument is specified as null, this is an initial
2519
+     * sync, and all members should be reported.
2520
+     *
2521
+     * The modified property is an array of nodenames that have changed since
2522
+     * the last token.
2523
+     *
2524
+     * The deleted property is an array with nodenames, that have been deleted
2525
+     * from collection.
2526
+     *
2527
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2528
+     * 1, you only have to report changes that happened only directly in
2529
+     * immediate descendants. If it's 2, it should also include changes from
2530
+     * the nodes below the child collections. (grandchildren)
2531
+     *
2532
+     * The $limit argument allows a client to specify how many results should
2533
+     * be returned at most. If the limit is not specified, it should be treated
2534
+     * as infinite.
2535
+     *
2536
+     * If the limit (infinite or not) is higher than you're willing to return,
2537
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2538
+     *
2539
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2540
+     * return null.
2541
+     *
2542
+     * The limit is 'suggestive'. You are free to ignore it.
2543
+     *
2544
+     * @param string $calendarId
2545
+     * @param string $syncToken
2546
+     * @param int $syncLevel
2547
+     * @param int|null $limit
2548
+     * @param int $calendarType
2549
+     * @return ?array
2550
+     */
2551
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2552
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2553
+
2554
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2555
+            // Current synctoken
2556
+            $qb = $this->db->getQueryBuilder();
2557
+            $qb->select('synctoken')
2558
+                ->from($table)
2559
+                ->where(
2560
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2561
+                );
2562
+            $stmt = $qb->executeQuery();
2563
+            $currentToken = $stmt->fetchOne();
2564
+            $initialSync = !is_numeric($syncToken);
2565
+
2566
+            if ($currentToken === false) {
2567
+                return null;
2568
+            }
2569
+
2570
+            // evaluate if this is a initial sync and construct appropriate command
2571
+            if ($initialSync) {
2572
+                $qb = $this->db->getQueryBuilder();
2573
+                $qb->select('uri')
2574
+                    ->from('calendarobjects')
2575
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2576
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2577
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2578
+            } else {
2579
+                $qb = $this->db->getQueryBuilder();
2580
+                $qb->select('uri', $qb->func()->max('operation'))
2581
+                    ->from('calendarchanges')
2582
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2583
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2584
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2585
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2586
+                    ->groupBy('uri');
2587
+            }
2588
+            // evaluate if limit exists
2589
+            if (is_numeric($limit)) {
2590
+                $qb->setMaxResults($limit);
2591
+            }
2592
+            // execute command
2593
+            $stmt = $qb->executeQuery();
2594
+            // build results
2595
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2596
+            // retrieve results
2597
+            if ($initialSync) {
2598
+                $result['added'] = $stmt->fetchFirstColumn();
2599
+            } else {
2600
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2601
+                // produced by doctrine for MAX() with different databases
2602
+                while ($entry = $stmt->fetchNumeric()) {
2603
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2604
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2605
+                    match ((int)$entry[1]) {
2606
+                        1 => $result['added'][] = $entry[0],
2607
+                        2 => $result['modified'][] = $entry[0],
2608
+                        3 => $result['deleted'][] = $entry[0],
2609
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2610
+                    };
2611
+                }
2612
+            }
2613
+            $stmt->closeCursor();
2614
+
2615
+            return $result;
2616
+        }, $this->db);
2617
+    }
2618
+
2619
+    /**
2620
+     * Returns a list of subscriptions for a principal.
2621
+     *
2622
+     * Every subscription is an array with the following keys:
2623
+     *  * id, a unique id that will be used by other functions to modify the
2624
+     *    subscription. This can be the same as the uri or a database key.
2625
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2626
+     *  * principaluri. The owner of the subscription. Almost always the same as
2627
+     *    principalUri passed to this method.
2628
+     *
2629
+     * Furthermore, all the subscription info must be returned too:
2630
+     *
2631
+     * 1. {DAV:}displayname
2632
+     * 2. {http://apple.com/ns/ical/}refreshrate
2633
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2634
+     *    should not be stripped).
2635
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2636
+     *    should not be stripped).
2637
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2638
+     *    attachments should not be stripped).
2639
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2640
+     *     Sabre\DAV\Property\Href).
2641
+     * 7. {http://apple.com/ns/ical/}calendar-color
2642
+     * 8. {http://apple.com/ns/ical/}calendar-order
2643
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2644
+     *    (should just be an instance of
2645
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2646
+     *    default components).
2647
+     *
2648
+     * @param string $principalUri
2649
+     * @return array
2650
+     */
2651
+    public function getSubscriptionsForUser($principalUri) {
2652
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2653
+        $fields[] = 'id';
2654
+        $fields[] = 'uri';
2655
+        $fields[] = 'source';
2656
+        $fields[] = 'principaluri';
2657
+        $fields[] = 'lastmodified';
2658
+        $fields[] = 'synctoken';
2659
+
2660
+        $query = $this->db->getQueryBuilder();
2661
+        $query->select($fields)
2662
+            ->from('calendarsubscriptions')
2663
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2664
+            ->orderBy('calendarorder', 'asc');
2665
+        $stmt = $query->executeQuery();
2666
+
2667
+        $subscriptions = [];
2668
+        while ($row = $stmt->fetchAssociative()) {
2669
+            $subscription = [
2670
+                'id' => $row['id'],
2671
+                'uri' => $row['uri'],
2672
+                'principaluri' => $row['principaluri'],
2673
+                'source' => $row['source'],
2674
+                'lastmodified' => $row['lastmodified'],
2675
+
2676
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2677
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2678
+            ];
2679
+
2680
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2681
+        }
2682
+
2683
+        return $subscriptions;
2684
+    }
2685
+
2686
+    /**
2687
+     * Creates a new subscription for a principal.
2688
+     *
2689
+     * If the creation was a success, an id must be returned that can be used to reference
2690
+     * this subscription in other methods, such as updateSubscription.
2691
+     *
2692
+     * @param string $principalUri
2693
+     * @param string $uri
2694
+     * @param array $properties
2695
+     * @return mixed
2696
+     */
2697
+    public function createSubscription($principalUri, $uri, array $properties) {
2698
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2699
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2700
+        }
2701
+
2702
+        $values = [
2703
+            'principaluri' => $principalUri,
2704
+            'uri' => $uri,
2705
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2706
+            'lastmodified' => time(),
2707
+        ];
2708
+
2709
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2710
+
2711
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2712
+            if (array_key_exists($xmlName, $properties)) {
2713
+                $values[$dbName] = $properties[$xmlName];
2714
+                if (in_array($dbName, $propertiesBoolean)) {
2715
+                    $values[$dbName] = true;
2716
+                }
2717
+            }
2718
+        }
2719
+
2720
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2721
+            $valuesToInsert = [];
2722
+            $query = $this->db->getQueryBuilder();
2723
+            foreach (array_keys($values) as $name) {
2724
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2725
+            }
2726
+            $query->insert('calendarsubscriptions')
2727
+                ->values($valuesToInsert)
2728
+                ->executeStatement();
2729
+
2730
+            $subscriptionId = $query->getLastInsertId();
2731
+
2732
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2733
+            return [$subscriptionId, $subscriptionRow];
2734
+        }, $this->db);
2735
+
2736
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2737
+
2738
+        return $subscriptionId;
2739
+    }
2740
+
2741
+    /**
2742
+     * Updates a subscription
2743
+     *
2744
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2745
+     * To do the actual updates, you must tell this object which properties
2746
+     * you're going to process with the handle() method.
2747
+     *
2748
+     * Calling the handle method is like telling the PropPatch object "I
2749
+     * promise I can handle updating this property".
2750
+     *
2751
+     * Read the PropPatch documentation for more info and examples.
2752
+     *
2753
+     * @param mixed $subscriptionId
2754
+     * @param PropPatch $propPatch
2755
+     * @return void
2756
+     */
2757
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2758
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2759
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2760
+
2761
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2762
+            $newValues = [];
2763
+
2764
+            foreach ($mutations as $propertyName => $propertyValue) {
2765
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2766
+                    $newValues['source'] = $propertyValue->getHref();
2767
+                } else {
2768
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2769
+                    $newValues[$fieldName] = $propertyValue;
2770
+                }
2771
+            }
2772
+
2773
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2774
+                $query = $this->db->getQueryBuilder();
2775
+                $query->update('calendarsubscriptions')
2776
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2777
+                foreach ($newValues as $fieldName => $value) {
2778
+                    $query->set($fieldName, $query->createNamedParameter($value));
2779
+                }
2780
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2781
+                    ->executeStatement();
2782
+
2783
+                return $this->getSubscriptionById($subscriptionId);
2784
+            }, $this->db);
2785
+
2786
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2787
+
2788
+            return true;
2789
+        });
2790
+    }
2791
+
2792
+    /**
2793
+     * Deletes a subscription.
2794
+     *
2795
+     * @param mixed $subscriptionId
2796
+     * @return void
2797
+     */
2798
+    public function deleteSubscription($subscriptionId) {
2799
+        $this->atomic(function () use ($subscriptionId): void {
2800
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2801
+
2802
+            $query = $this->db->getQueryBuilder();
2803
+            $query->delete('calendarsubscriptions')
2804
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2805
+                ->executeStatement();
2806
+
2807
+            $query = $this->db->getQueryBuilder();
2808
+            $query->delete('calendarobjects')
2809
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2810
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2811
+                ->executeStatement();
2812
+
2813
+            $query->delete('calendarchanges')
2814
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2815
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2816
+                ->executeStatement();
2817
+
2818
+            $query->delete($this->dbObjectPropertiesTable)
2819
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2820
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2821
+                ->executeStatement();
2822
+
2823
+            if ($subscriptionRow) {
2824
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2825
+            }
2826
+        }, $this->db);
2827
+    }
2828
+
2829
+    /**
2830
+     * Returns a single scheduling object for the inbox collection.
2831
+     *
2832
+     * The returned array should contain the following elements:
2833
+     *   * uri - A unique basename for the object. This will be used to
2834
+     *           construct a full uri.
2835
+     *   * calendardata - The iCalendar object
2836
+     *   * lastmodified - The last modification date. Can be an int for a unix
2837
+     *                    timestamp, or a PHP DateTime object.
2838
+     *   * etag - A unique token that must change if the object changed.
2839
+     *   * size - The size of the object, in bytes.
2840
+     *
2841
+     * @param string $principalUri
2842
+     * @param string $objectUri
2843
+     * @return array
2844
+     */
2845
+    public function getSchedulingObject($principalUri, $objectUri) {
2846
+        $query = $this->db->getQueryBuilder();
2847
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2848
+            ->from('schedulingobjects')
2849
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2850
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2851
+            ->executeQuery();
2852
+
2853
+        $row = $stmt->fetchAssociative();
2854
+
2855
+        if (!$row) {
2856
+            return null;
2857
+        }
2858
+
2859
+        return [
2860
+            'uri' => $row['uri'],
2861
+            'calendardata' => $row['calendardata'],
2862
+            'lastmodified' => $row['lastmodified'],
2863
+            'etag' => '"' . $row['etag'] . '"',
2864
+            'size' => (int)$row['size'],
2865
+        ];
2866
+    }
2867
+
2868
+    /**
2869
+     * Returns all scheduling objects for the inbox collection.
2870
+     *
2871
+     * These objects should be returned as an array. Every item in the array
2872
+     * should follow the same structure as returned from getSchedulingObject.
2873
+     *
2874
+     * The main difference is that 'calendardata' is optional.
2875
+     *
2876
+     * @param string $principalUri
2877
+     * @return array
2878
+     */
2879
+    public function getSchedulingObjects($principalUri) {
2880
+        $query = $this->db->getQueryBuilder();
2881
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2882
+            ->from('schedulingobjects')
2883
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2884
+            ->executeQuery();
2885
+
2886
+        $results = [];
2887
+        while (($row = $stmt->fetchAssociative()) !== false) {
2888
+            $results[] = [
2889
+                'calendardata' => $row['calendardata'],
2890
+                'uri' => $row['uri'],
2891
+                'lastmodified' => $row['lastmodified'],
2892
+                'etag' => '"' . $row['etag'] . '"',
2893
+                'size' => (int)$row['size'],
2894
+            ];
2895
+        }
2896
+        $stmt->closeCursor();
2897
+
2898
+        return $results;
2899
+    }
2900
+
2901
+    /**
2902
+     * Deletes a scheduling object from the inbox collection.
2903
+     *
2904
+     * @param string $principalUri
2905
+     * @param string $objectUri
2906
+     * @return void
2907
+     */
2908
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2909
+        $this->cachedObjects = [];
2910
+        $query = $this->db->getQueryBuilder();
2911
+        $query->delete('schedulingobjects')
2912
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2913
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2914
+            ->executeStatement();
2915
+    }
2916
+
2917
+    /**
2918
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2919
+     *
2920
+     * @param int $modifiedBefore
2921
+     * @param int $limit
2922
+     * @return void
2923
+     */
2924
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2925
+        $query = $this->db->getQueryBuilder();
2926
+        $query->select('id')
2927
+            ->from('schedulingobjects')
2928
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2929
+            ->setMaxResults($limit);
2930
+        $result = $query->executeQuery();
2931
+        $count = $result->rowCount();
2932
+        if ($count === 0) {
2933
+            return;
2934
+        }
2935
+        $ids = array_map(static function (array $id) {
2936
+            return (int)$id[0];
2937
+        }, $result->fetchAllNumeric());
2938
+        $result->closeCursor();
2939
+
2940
+        $numDeleted = 0;
2941
+        $deleteQuery = $this->db->getQueryBuilder();
2942
+        $deleteQuery->delete('schedulingobjects')
2943
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2944
+        foreach (array_chunk($ids, 1000) as $chunk) {
2945
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2946
+            $numDeleted += $deleteQuery->executeStatement();
2947
+        }
2948
+
2949
+        if ($numDeleted === $limit) {
2950
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2951
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2952
+        }
2953
+    }
2954
+
2955
+    /**
2956
+     * Creates a new scheduling object. This should land in a users' inbox.
2957
+     *
2958
+     * @param string $principalUri
2959
+     * @param string $objectUri
2960
+     * @param string $objectData
2961
+     * @return void
2962
+     */
2963
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2964
+        $this->cachedObjects = [];
2965
+        $query = $this->db->getQueryBuilder();
2966
+        $query->insert('schedulingobjects')
2967
+            ->values([
2968
+                'principaluri' => $query->createNamedParameter($principalUri),
2969
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2970
+                'uri' => $query->createNamedParameter($objectUri),
2971
+                'lastmodified' => $query->createNamedParameter(time()),
2972
+                'etag' => $query->createNamedParameter(md5($objectData)),
2973
+                'size' => $query->createNamedParameter(strlen($objectData))
2974
+            ])
2975
+            ->executeStatement();
2976
+    }
2977
+
2978
+    /**
2979
+     * Adds a change record to the calendarchanges table.
2980
+     *
2981
+     * @param mixed $calendarId
2982
+     * @param string[] $objectUris
2983
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2984
+     * @param int $calendarType
2985
+     * @return void
2986
+     */
2987
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2988
+        $this->cachedObjects = [];
2989
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2990
+
2991
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2992
+            $query = $this->db->getQueryBuilder();
2993
+            $query->select('synctoken')
2994
+                ->from($table)
2995
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2996
+            $result = $query->executeQuery();
2997
+            $syncToken = (int)$result->fetchOne();
2998
+            $result->closeCursor();
2999
+
3000
+            $query = $this->db->getQueryBuilder();
3001
+            $query->insert('calendarchanges')
3002
+                ->values([
3003
+                    'uri' => $query->createParameter('uri'),
3004
+                    'synctoken' => $query->createNamedParameter($syncToken),
3005
+                    'calendarid' => $query->createNamedParameter($calendarId),
3006
+                    'operation' => $query->createNamedParameter($operation),
3007
+                    'calendartype' => $query->createNamedParameter($calendarType),
3008
+                    'created_at' => $query->createNamedParameter(time()),
3009
+                ]);
3010
+            foreach ($objectUris as $uri) {
3011
+                $query->setParameter('uri', $uri);
3012
+                $query->executeStatement();
3013
+            }
3014
+
3015
+            $query = $this->db->getQueryBuilder();
3016
+            $query->update($table)
3017
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3018
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3019
+                ->executeStatement();
3020
+        }, $this->db);
3021
+    }
3022
+
3023
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3024
+        $this->cachedObjects = [];
3025
+
3026
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3027
+            $qbAdded = $this->db->getQueryBuilder();
3028
+            $qbAdded->select('uri')
3029
+                ->from('calendarobjects')
3030
+                ->where(
3031
+                    $qbAdded->expr()->andX(
3032
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3033
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3034
+                        $qbAdded->expr()->isNull('deleted_at'),
3035
+                    )
3036
+                );
3037
+            $resultAdded = $qbAdded->executeQuery();
3038
+            $addedUris = $resultAdded->fetchFirstColumn();
3039
+            $resultAdded->closeCursor();
3040
+            // Track everything as changed
3041
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3042
+            // only returns the last change per object.
3043
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3044
+
3045
+            $qbDeleted = $this->db->getQueryBuilder();
3046
+            $qbDeleted->select('uri')
3047
+                ->from('calendarobjects')
3048
+                ->where(
3049
+                    $qbDeleted->expr()->andX(
3050
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3051
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3052
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3053
+                    )
3054
+                );
3055
+            $resultDeleted = $qbDeleted->executeQuery();
3056
+            $deletedUris = array_map(function (string $uri) {
3057
+                return str_replace('-deleted.ics', '.ics', $uri);
3058
+            }, $resultDeleted->fetchFirstColumn());
3059
+            $resultDeleted->closeCursor();
3060
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3061
+        }, $this->db);
3062
+    }
3063
+
3064
+    /**
3065
+     * Parses some information from calendar objects, used for optimized
3066
+     * calendar-queries.
3067
+     *
3068
+     * Returns an array with the following keys:
3069
+     *   * etag - An md5 checksum of the object without the quotes.
3070
+     *   * size - Size of the object in bytes
3071
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3072
+     *   * firstOccurence
3073
+     *   * lastOccurence
3074
+     *   * uid - value of the UID property
3075
+     *
3076
+     * @param string $calendarData
3077
+     * @return array
3078
+     */
3079
+    public function getDenormalizedData(string $calendarData): array {
3080
+        $vObject = Reader::read($calendarData);
3081
+        $vEvents = [];
3082
+        $componentType = null;
3083
+        $component = null;
3084
+        $firstOccurrence = null;
3085
+        $lastOccurrence = null;
3086
+        $uid = null;
3087
+        $classification = self::CLASSIFICATION_PUBLIC;
3088
+        $hasDTSTART = false;
3089
+        foreach ($vObject->getComponents() as $component) {
3090
+            if ($component->name !== 'VTIMEZONE') {
3091
+                // Finding all VEVENTs, and track them
3092
+                if ($component->name === 'VEVENT') {
3093
+                    $vEvents[] = $component;
3094
+                    if ($component->DTSTART) {
3095
+                        $hasDTSTART = true;
3096
+                    }
3097
+                }
3098
+                // Track first component type and uid
3099
+                if ($uid === null) {
3100
+                    $componentType = $component->name;
3101
+                    $uid = (string)$component->UID;
3102
+                }
3103
+            }
3104
+        }
3105
+        if (!$componentType) {
3106
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3107
+        }
3108
+
3109
+        if ($hasDTSTART) {
3110
+            $component = $vEvents[0];
3111
+
3112
+            // Finding the last occurrence is a bit harder
3113
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3114
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3115
+                if (isset($component->DTEND)) {
3116
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3117
+                } elseif (isset($component->DURATION)) {
3118
+                    $endDate = clone $component->DTSTART->getDateTime();
3119
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3120
+                    $lastOccurrence = $endDate->getTimeStamp();
3121
+                } elseif (!$component->DTSTART->hasTime()) {
3122
+                    $endDate = clone $component->DTSTART->getDateTime();
3123
+                    $endDate->modify('+1 day');
3124
+                    $lastOccurrence = $endDate->getTimeStamp();
3125
+                } else {
3126
+                    $lastOccurrence = $firstOccurrence;
3127
+                }
3128
+            } else {
3129
+                try {
3130
+                    $it = new EventIterator($vEvents);
3131
+                } catch (NoInstancesException $e) {
3132
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3133
+                        'app' => 'dav',
3134
+                        'exception' => $e,
3135
+                    ]);
3136
+                    throw new Forbidden($e->getMessage());
3137
+                }
3138
+                $maxDate = new DateTime(self::MAX_DATE);
3139
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3140
+                if ($it->isInfinite()) {
3141
+                    $lastOccurrence = $maxDate->getTimestamp();
3142
+                } else {
3143
+                    $end = $it->getDtEnd();
3144
+                    while ($it->valid() && $end < $maxDate) {
3145
+                        $end = $it->getDtEnd();
3146
+                        $it->next();
3147
+                    }
3148
+                    $lastOccurrence = $end->getTimestamp();
3149
+                }
3150
+            }
3151
+        }
3152
+
3153
+        if ($component->CLASS) {
3154
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3155
+            switch ($component->CLASS->getValue()) {
3156
+                case 'PUBLIC':
3157
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3158
+                    break;
3159
+                case 'CONFIDENTIAL':
3160
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3161
+                    break;
3162
+            }
3163
+        }
3164
+        return [
3165
+            'etag' => md5($calendarData),
3166
+            'size' => strlen($calendarData),
3167
+            'componentType' => $componentType,
3168
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3169
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3170
+            'uid' => $uid,
3171
+            'classification' => $classification
3172
+        ];
3173
+    }
3174
+
3175
+    /**
3176
+     * @param $cardData
3177
+     * @return bool|string
3178
+     */
3179
+    private function readBlob($cardData) {
3180
+        if (is_resource($cardData)) {
3181
+            return stream_get_contents($cardData);
3182
+        }
3183
+
3184
+        return $cardData;
3185
+    }
3186
+
3187
+    /**
3188
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3189
+     * @param list<string> $remove
3190
+     */
3191
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3192
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3193
+            $calendarId = $shareable->getResourceId();
3194
+            $calendarRow = $this->getCalendarById($calendarId);
3195
+            if ($calendarRow === null) {
3196
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3197
+            }
3198
+            $oldShares = $this->getShares($calendarId);
3199
+
3200
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3201
+
3202
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3203
+        }, $this->db);
3204
+    }
3205
+
3206
+    /**
3207
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3208
+     */
3209
+    public function getShares(int $resourceId): array {
3210
+        return $this->calendarSharingBackend->getShares($resourceId);
3211
+    }
3212
+
3213
+    public function getSharesByShareePrincipal(string $principal): array {
3214
+        return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3215
+    }
3216
+
3217
+    public function preloadShares(array $resourceIds): void {
3218
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3219
+    }
3220
+
3221
+    /**
3222
+     * @param boolean $value
3223
+     * @param Calendar $calendar
3224
+     * @return string|null
3225
+     */
3226
+    public function setPublishStatus($value, $calendar) {
3227
+        $publishStatus = $this->atomic(function () use ($value, $calendar) {
3228
+            $calendarId = $calendar->getResourceId();
3229
+            $calendarData = $this->getCalendarById($calendarId);
3230
+
3231
+            $query = $this->db->getQueryBuilder();
3232
+            if ($value) {
3233
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3234
+                $query->insert('dav_shares')
3235
+                    ->values([
3236
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3237
+                        'type' => $query->createNamedParameter('calendar'),
3238
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3239
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3240
+                        'publicuri' => $query->createNamedParameter($publicUri)
3241
+                    ]);
3242
+                $query->executeStatement();
3243
+
3244
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3245
+                return $publicUri;
3246
+            }
3247
+            $query->delete('dav_shares')
3248
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3249
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3250
+            $query->executeStatement();
3251
+
3252
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3253
+            return null;
3254
+        }, $this->db);
3255
+
3256
+        $this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3257
+        return $publishStatus;
3258
+    }
3259
+
3260
+    /**
3261
+     * @param Calendar $calendar
3262
+     * @return string|false
3263
+     */
3264
+    public function getPublishStatus($calendar) {
3265
+        $cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3266
+        if ($cached !== null) {
3267
+            return $cached;
3268
+        }
3269
+
3270
+        $query = $this->db->getQueryBuilder();
3271
+        $result = $query->select('publicuri')
3272
+            ->from('dav_shares')
3273
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3274
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3275
+            ->executeQuery();
3276
+
3277
+        $publishStatus = $result->fetchOne();
3278
+        $result->closeCursor();
3279
+
3280
+        $this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3281
+        return $publishStatus;
3282
+    }
3283
+
3284
+    /**
3285
+     * @param int[] $resourceIds
3286
+     */
3287
+    public function preloadPublishStatuses(array $resourceIds): void {
3288
+        $query = $this->db->getQueryBuilder();
3289
+        $result = $query->select('resourceid', 'publicuri')
3290
+            ->from('dav_shares')
3291
+            ->where($query->expr()->in(
3292
+                'resourceid',
3293
+                $query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY),
3294
+                IQueryBuilder::PARAM_INT_ARRAY,
3295
+            ))
3296
+            ->andWhere($query->expr()->eq(
3297
+                'access',
3298
+                $query->createNamedParameter(self::ACCESS_PUBLIC, IQueryBuilder::PARAM_INT),
3299
+                IQueryBuilder::PARAM_INT,
3300
+            ))
3301
+            ->executeQuery();
3302
+
3303
+        $hasPublishStatuses = [];
3304
+        while ($row = $result->fetchAssociative()) {
3305
+            $this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3306
+            $hasPublishStatuses[(int)$row['resourceid']] = true;
3307
+        }
3308
+
3309
+        // Also remember resources with no publish status
3310
+        foreach ($resourceIds as $resourceId) {
3311
+            if (!isset($hasPublishStatuses[$resourceId])) {
3312
+                $this->publishStatusCache->set((string)$resourceId, false);
3313
+            }
3314
+        }
3315
+
3316
+        $result->closeCursor();
3317
+    }
3318
+
3319
+    /**
3320
+     * @param int $resourceId
3321
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3322
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3323
+     */
3324
+    public function applyShareAcl(int $resourceId, array $acl): array {
3325
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3326
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3327
+    }
3328
+
3329
+    /**
3330
+     * update properties table
3331
+     *
3332
+     * @param int $calendarId
3333
+     * @param string $objectUri
3334
+     * @param string $calendarData
3335
+     * @param int $calendarType
3336
+     */
3337
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3338
+        $this->cachedObjects = [];
3339
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3340
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3341
+
3342
+            try {
3343
+                $vCalendar = $this->readCalendarData($calendarData);
3344
+            } catch (\Exception $ex) {
3345
+                return;
3346
+            }
3347
+
3348
+            $this->purgeProperties($calendarId, $objectId);
3349
+
3350
+            $query = $this->db->getQueryBuilder();
3351
+            $query->insert($this->dbObjectPropertiesTable)
3352
+                ->values(
3353
+                    [
3354
+                        'calendarid' => $query->createNamedParameter($calendarId),
3355
+                        'calendartype' => $query->createNamedParameter($calendarType),
3356
+                        'objectid' => $query->createNamedParameter($objectId),
3357
+                        'name' => $query->createParameter('name'),
3358
+                        'parameter' => $query->createParameter('parameter'),
3359
+                        'value' => $query->createParameter('value'),
3360
+                    ]
3361
+                );
3362
+
3363
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3364
+            foreach ($vCalendar->getComponents() as $component) {
3365
+                if (!in_array($component->name, $indexComponents)) {
3366
+                    continue;
3367
+                }
3368
+
3369
+                foreach ($component->children() as $property) {
3370
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3371
+                        $value = $property->getValue();
3372
+                        // is this a shitty db?
3373
+                        if (!$this->db->supports4ByteText()) {
3374
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3375
+                        }
3376
+                        $value = mb_strcut($value, 0, 254);
3377
+
3378
+                        $query->setParameter('name', $property->name);
3379
+                        $query->setParameter('parameter', null);
3380
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3381
+                        $query->executeStatement();
3382
+                    }
3383
+
3384
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3385
+                        $parameters = $property->parameters();
3386
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3387
+
3388
+                        foreach ($parameters as $key => $value) {
3389
+                            if (in_array($key, $indexedParametersForProperty)) {
3390
+                                // is this a shitty db?
3391
+                                if ($this->db->supports4ByteText()) {
3392
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3393
+                                }
3394
+
3395
+                                $query->setParameter('name', $property->name);
3396
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3397
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3398
+                                $query->executeStatement();
3399
+                            }
3400
+                        }
3401
+                    }
3402
+                }
3403
+            }
3404
+        }, $this->db);
3405
+    }
3406
+
3407
+    /**
3408
+     * deletes all birthday calendars
3409
+     */
3410
+    public function deleteAllBirthdayCalendars() {
3411
+        $this->atomic(function (): void {
3412
+            $query = $this->db->getQueryBuilder();
3413
+            $result = $query->select(['id'])->from('calendars')
3414
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3415
+                ->executeQuery();
3416
+
3417
+            while (($row = $result->fetchAssociative()) !== false) {
3418
+                $this->deleteCalendar(
3419
+                    $row['id'],
3420
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3421
+                );
3422
+            }
3423
+            $result->closeCursor();
3424
+        }, $this->db);
3425
+    }
3426
+
3427
+    /**
3428
+     * @param $subscriptionId
3429
+     */
3430
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3431
+        $this->atomic(function () use ($subscriptionId): void {
3432
+            $query = $this->db->getQueryBuilder();
3433
+            $query->select('uri')
3434
+                ->from('calendarobjects')
3435
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3436
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3437
+            $stmt = $query->executeQuery();
3438
+
3439
+            $uris = [];
3440
+            while (($row = $stmt->fetchAssociative()) !== false) {
3441
+                $uris[] = $row['uri'];
3442
+            }
3443
+            $stmt->closeCursor();
3444
+
3445
+            $query = $this->db->getQueryBuilder();
3446
+            $query->delete('calendarobjects')
3447
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3448
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3449
+                ->executeStatement();
3450
+
3451
+            $query = $this->db->getQueryBuilder();
3452
+            $query->delete('calendarchanges')
3453
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3454
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3455
+                ->executeStatement();
3456
+
3457
+            $query = $this->db->getQueryBuilder();
3458
+            $query->delete($this->dbObjectPropertiesTable)
3459
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3460
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3461
+                ->executeStatement();
3462
+
3463
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3464
+        }, $this->db);
3465
+    }
3466
+
3467
+    /**
3468
+     * @param int $subscriptionId
3469
+     * @param array<int> $calendarObjectIds
3470
+     * @param array<string> $calendarObjectUris
3471
+     */
3472
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3473
+        if (empty($calendarObjectUris)) {
3474
+            return;
3475
+        }
3476
+
3477
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3478
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3479
+                $query = $this->db->getQueryBuilder();
3480
+                $query->delete($this->dbObjectPropertiesTable)
3481
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3482
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3483
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3484
+                    ->executeStatement();
3485
+
3486
+                $query = $this->db->getQueryBuilder();
3487
+                $query->delete('calendarobjects')
3488
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3489
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3490
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3491
+                    ->executeStatement();
3492
+            }
3493
+
3494
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3495
+                $query = $this->db->getQueryBuilder();
3496
+                $query->delete('calendarchanges')
3497
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3498
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3499
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3500
+                    ->executeStatement();
3501
+            }
3502
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3503
+        }, $this->db);
3504
+    }
3505
+
3506
+    /**
3507
+     * Move a calendar from one user to another
3508
+     *
3509
+     * @param string $uriName
3510
+     * @param string $uriOrigin
3511
+     * @param string $uriDestination
3512
+     * @param string $newUriName (optional) the new uriName
3513
+     */
3514
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3515
+        $query = $this->db->getQueryBuilder();
3516
+        $query->update('calendars')
3517
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3518
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3519
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3520
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3521
+            ->executeStatement();
3522
+    }
3523
+
3524
+    /**
3525
+     * read VCalendar data into a VCalendar object
3526
+     *
3527
+     * @param string $objectData
3528
+     * @return VCalendar
3529
+     */
3530
+    protected function readCalendarData($objectData) {
3531
+        return Reader::read($objectData);
3532
+    }
3533
+
3534
+    /**
3535
+     * delete all properties from a given calendar object
3536
+     *
3537
+     * @param int $calendarId
3538
+     * @param int $objectId
3539
+     */
3540
+    protected function purgeProperties($calendarId, $objectId) {
3541
+        $this->cachedObjects = [];
3542
+        $query = $this->db->getQueryBuilder();
3543
+        $query->delete($this->dbObjectPropertiesTable)
3544
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3545
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3546
+        $query->executeStatement();
3547
+    }
3548
+
3549
+    /**
3550
+     * get ID from a given calendar object
3551
+     *
3552
+     * @param int $calendarId
3553
+     * @param string $uri
3554
+     * @param int $calendarType
3555
+     * @return int
3556
+     */
3557
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3558
+        $query = $this->db->getQueryBuilder();
3559
+        $query->select('id')
3560
+            ->from('calendarobjects')
3561
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3562
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3563
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3564
+
3565
+        $result = $query->executeQuery();
3566
+        $objectIds = $result->fetchAssociative();
3567
+        $result->closeCursor();
3568
+
3569
+        if (!isset($objectIds['id'])) {
3570
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3571
+        }
3572
+
3573
+        return (int)$objectIds['id'];
3574
+    }
3575
+
3576
+    /**
3577
+     * @throws \InvalidArgumentException
3578
+     */
3579
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3580
+        if ($keep < 0) {
3581
+            throw new \InvalidArgumentException();
3582
+        }
3583
+
3584
+        $query = $this->db->getQueryBuilder();
3585
+        $query->select($query->func()->max('id'))
3586
+            ->from('calendarchanges');
3587
+
3588
+        $result = $query->executeQuery();
3589
+        $maxId = (int)$result->fetchOne();
3590
+        $result->closeCursor();
3591
+        if (!$maxId || $maxId < $keep) {
3592
+            return 0;
3593
+        }
3594
+
3595
+        $query = $this->db->getQueryBuilder();
3596
+        $query->delete('calendarchanges')
3597
+            ->where(
3598
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3599
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3600
+            );
3601
+        return $query->executeStatement();
3602
+    }
3603
+
3604
+    /**
3605
+     * return legacy endpoint principal name to new principal name
3606
+     *
3607
+     * @param $principalUri
3608
+     * @param $toV2
3609
+     * @return string
3610
+     */
3611
+    private function convertPrincipal($principalUri, $toV2) {
3612
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3613
+            [, $name] = Uri\split($principalUri);
3614
+            if ($toV2 === true) {
3615
+                return "principals/users/$name";
3616
+            }
3617
+            return "principals/$name";
3618
+        }
3619
+        return $principalUri;
3620
+    }
3621
+
3622
+    /**
3623
+     * adds information about an owner to the calendar data
3624
+     *
3625
+     */
3626
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3627
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3628
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3629
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3630
+            $uri = $calendarInfo[$ownerPrincipalKey];
3631
+        } else {
3632
+            $uri = $calendarInfo['principaluri'];
3633
+        }
3634
+
3635
+        $principalInformation = $this->principalBackend->getPrincipalPropertiesByPath($uri, [
3636
+            '{DAV:}displayname',
3637
+        ]);
3638
+        if (isset($principalInformation['{DAV:}displayname'])) {
3639
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3640
+        }
3641
+        return $calendarInfo;
3642
+    }
3643
+
3644
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3645
+        if (isset($row['deleted_at'])) {
3646
+            // Columns is set and not null -> this is a deleted calendar
3647
+            // we send a custom resourcetype to hide the deleted calendar
3648
+            // from ordinary DAV clients, but the Calendar app will know
3649
+            // how to handle this special resource.
3650
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3651
+                '{DAV:}collection',
3652
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3653
+            ]);
3654
+        }
3655
+        return $calendar;
3656
+    }
3657
+
3658
+    /**
3659
+     * Amend the calendar info with database row data
3660
+     *
3661
+     * @param array $row
3662
+     * @param array $calendar
3663
+     *
3664
+     * @return array
3665
+     */
3666
+    private function rowToCalendar($row, array $calendar): array {
3667
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3668
+            $value = $row[$dbName];
3669
+            if ($value !== null) {
3670
+                settype($value, $type);
3671
+            }
3672
+            $calendar[$xmlName] = $value;
3673
+        }
3674
+        return $calendar;
3675
+    }
3676
+
3677
+    /**
3678
+     * Amend the subscription info with database row data
3679
+     *
3680
+     * @param array $row
3681
+     * @param array $subscription
3682
+     *
3683
+     * @return array
3684
+     */
3685
+    private function rowToSubscription($row, array $subscription): array {
3686
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3687
+            $value = $row[$dbName];
3688
+            if ($value !== null) {
3689
+                settype($value, $type);
3690
+            }
3691
+            $subscription[$xmlName] = $value;
3692
+        }
3693
+        return $subscription;
3694
+    }
3695
+
3696
+    /**
3697
+     * delete all invitations from a given calendar
3698
+     *
3699
+     * @since 31.0.0
3700
+     *
3701
+     * @param int $calendarId
3702
+     *
3703
+     * @return void
3704
+     */
3705
+    protected function purgeCalendarInvitations(int $calendarId): void {
3706
+        // select all calendar object uid's
3707
+        $cmd = $this->db->getQueryBuilder();
3708
+        $cmd->select('uid')
3709
+            ->from($this->dbObjectsTable)
3710
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3711
+        $allIds = $cmd->executeQuery()->fetchFirstColumn();
3712
+        // delete all links that match object uid's
3713
+        $cmd = $this->db->getQueryBuilder();
3714
+        $cmd->delete($this->dbObjectInvitationsTable)
3715
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3716
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3717
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3718
+            $cmd->executeStatement();
3719
+        }
3720
+    }
3721
+
3722
+    /**
3723
+     * Delete all invitations from a given calendar event
3724
+     *
3725
+     * @since 31.0.0
3726
+     *
3727
+     * @param string $eventId UID of the event
3728
+     *
3729
+     * @return void
3730
+     */
3731
+    protected function purgeObjectInvitations(string $eventId): void {
3732
+        $cmd = $this->db->getQueryBuilder();
3733
+        $cmd->delete($this->dbObjectInvitationsTable)
3734
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3735
+        $cmd->executeStatement();
3736
+    }
3737
+
3738
+    public function unshare(IShareable $shareable, string $principal): void {
3739
+        $this->atomic(function () use ($shareable, $principal): void {
3740
+            $calendarData = $this->getCalendarById($shareable->getResourceId());
3741
+            if ($calendarData === null) {
3742
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3743
+            }
3744
+
3745
+            $oldShares = $this->getShares($shareable->getResourceId());
3746
+            $unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3747
+
3748
+            if ($unshare) {
3749
+                $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3750
+                    $shareable->getResourceId(),
3751
+                    $calendarData,
3752
+                    $oldShares,
3753
+                    [],
3754
+                    [$principal]
3755
+                ));
3756
+            }
3757
+        }, $this->db);
3758
+    }
3759
+
3760
+    /**
3761
+     * @return array<string, mixed>[]
3762
+     */
3763
+    public function getFederatedCalendarsForUser(string $principalUri): array {
3764
+        $federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3765
+        return array_map(
3766
+            static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3767
+            $federatedCalendars,
3768
+        );
3769
+    }
3770
+
3771
+    public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3772
+        $federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3773
+        return $federatedCalendar?->toCalendarInfo();
3774
+    }
3775 3775
 }
Please login to merge, or discard this patch.
Spacing   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151 151
 		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152 152
 		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
153
+		'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => ['deleted_at', 'int'],
154 154
 	];
155 155
 
156 156
 	/**
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		}
247 247
 
248 248
 		$result = $query->executeQuery();
249
-		$column = (int)$result->fetchOne();
249
+		$column = (int) $result->fetchOne();
250 250
 		$result->closeCursor();
251 251
 		return $column;
252 252
 	}
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 		}
268 268
 
269 269
 		$result = $query->executeQuery();
270
-		$column = (int)$result->fetchOne();
270
+		$column = (int) $result->fetchOne();
271 271
 		$result->closeCursor();
272 272
 		return $column;
273 273
 	}
@@ -285,8 +285,8 @@  discard block
 block discarded – undo
285 285
 		$calendars = [];
286 286
 		while (($row = $result->fetchAssociative()) !== false) {
287 287
 			$calendars[] = [
288
-				'id' => (int)$row['id'],
289
-				'deleted_at' => (int)$row['deleted_at'],
288
+				'id' => (int) $row['id'],
289
+				'deleted_at' => (int) $row['deleted_at'],
290 290
 			];
291 291
 		}
292 292
 		$result->closeCursor();
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 	 * @return array
320 320
 	 */
321 321
 	public function getCalendarsForUser($principalUri) {
322
-		return $this->atomic(function () use ($principalUri) {
322
+		return $this->atomic(function() use ($principalUri) {
323 323
 			$principalUriOriginal = $principalUri;
324 324
 			$principalUri = $this->convertPrincipal($principalUri, true);
325 325
 			$fields = array_column($this->propertyMap, 0);
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 
347 347
 			$calendars = [];
348 348
 			while ($row = $result->fetchAssociative()) {
349
-				$row['principaluri'] = (string)$row['principaluri'];
349
+				$row['principaluri'] = (string) $row['principaluri'];
350 350
 				$components = [];
351 351
 				if ($row['components']) {
352 352
 					$components = explode(',', $row['components']);
@@ -356,11 +356,11 @@  discard block
 block discarded – undo
356 356
 					'id' => $row['id'],
357 357
 					'uri' => $row['uri'],
358 358
 					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
359
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
360 360
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
363
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364 364
 				];
365 365
 
366 366
 				$calendar = $this->rowToCalendar($row, $calendar);
@@ -379,8 +379,8 @@  discard block
 block discarded – undo
379 379
 			$principals[] = $principalUri;
380 380
 
381 381
 			$fields = array_column($this->propertyMap, 0);
382
-			$fields = array_map(function (string $field) {
383
-				return 'a.' . $field;
382
+			$fields = array_map(function(string $field) {
383
+				return 'a.'.$field;
384 384
 			}, $fields);
385 385
 			$fields[] = 'a.id';
386 386
 			$fields[] = 'a.uri';
@@ -407,14 +407,14 @@  discard block
 block discarded – undo
407 407
 
408 408
 			$results = $select->executeQuery();
409 409
 
410
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
410
+			$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
411 411
 			while ($row = $results->fetchAssociative()) {
412
-				$row['principaluri'] = (string)$row['principaluri'];
412
+				$row['principaluri'] = (string) $row['principaluri'];
413 413
 				if ($row['principaluri'] === $principalUri) {
414 414
 					continue;
415 415
 				}
416 416
 
417
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
417
+				$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
418 418
 				if (isset($calendars[$row['id']])) {
419 419
 					if ($readOnly) {
420 420
 						// New share can not have more permissions than the old one.
@@ -428,8 +428,8 @@  discard block
 block discarded – undo
428 428
 				}
429 429
 
430 430
 				[, $name] = Uri\split($row['principaluri']);
431
-				$uri = $row['uri'] . '_shared_by_' . $name;
432
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
431
+				$uri = $row['uri'].'_shared_by_'.$name;
432
+				$row['displayname'] = $row['displayname'].' ('.($this->userManager->getDisplayName($name) ?? ($name ?? '')).')';
433 433
 				$components = [];
434 434
 				if ($row['components']) {
435 435
 					$components = explode(',', $row['components']);
@@ -438,11 +438,11 @@  discard block
 block discarded – undo
438 438
 					'id' => $row['id'],
439 439
 					'uri' => $uri,
440 440
 					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
441
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
442 442
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
443
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446 446
 					$readOnlyPropertyName => $readOnly,
447 447
 				];
448 448
 
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 		$stmt = $query->executeQuery();
480 480
 		$calendars = [];
481 481
 		while ($row = $stmt->fetchAssociative()) {
482
-			$row['principaluri'] = (string)$row['principaluri'];
482
+			$row['principaluri'] = (string) $row['principaluri'];
483 483
 			$components = [];
484 484
 			if ($row['components']) {
485 485
 				$components = explode(',', $row['components']);
@@ -488,10 +488,10 @@  discard block
 block discarded – undo
488 488
 				'id' => $row['id'],
489 489
 				'uri' => $row['uri'],
490 490
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
491
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
492 492
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
493
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
495 495
 			];
496 496
 
497 497
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -529,9 +529,9 @@  discard block
 block discarded – undo
529 529
 			->executeQuery();
530 530
 
531 531
 		while ($row = $result->fetchAssociative()) {
532
-			$row['principaluri'] = (string)$row['principaluri'];
532
+			$row['principaluri'] = (string) $row['principaluri'];
533 533
 			[, $name] = Uri\split($row['principaluri']);
534
-			$row['displayname'] = $row['displayname'] . "($name)";
534
+			$row['displayname'] = $row['displayname']."($name)";
535 535
 			$components = [];
536 536
 			if ($row['components']) {
537 537
 				$components = explode(',', $row['components']);
@@ -540,13 +540,13 @@  discard block
 block discarded – undo
540 540
 				'id' => $row['id'],
541 541
 				'uri' => $row['publicuri'],
542 542
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
543
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
544 544
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
545
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
547
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
549
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
550 550
 			];
551 551
 
552 552
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -591,12 +591,12 @@  discard block
 block discarded – undo
591 591
 		$result->closeCursor();
592 592
 
593 593
 		if ($row === false) {
594
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
594
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
595 595
 		}
596 596
 
597
-		$row['principaluri'] = (string)$row['principaluri'];
597
+		$row['principaluri'] = (string) $row['principaluri'];
598 598
 		[, $name] = Uri\split($row['principaluri']);
599
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
599
+		$row['displayname'] = $row['displayname'].' '."($name)";
600 600
 		$components = [];
601 601
 		if ($row['components']) {
602 602
 			$components = explode(',', $row['components']);
@@ -605,13 +605,13 @@  discard block
 block discarded – undo
605 605
 			'id' => $row['id'],
606 606
 			'uri' => $row['publicuri'],
607 607
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
608
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
609 609
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
610
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
612
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
614
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
615 615
 		];
616 616
 
617 617
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 			return null;
650 650
 		}
651 651
 
652
-		$row['principaluri'] = (string)$row['principaluri'];
652
+		$row['principaluri'] = (string) $row['principaluri'];
653 653
 		$components = [];
654 654
 		if ($row['components']) {
655 655
 			$components = explode(',', $row['components']);
@@ -659,10 +659,10 @@  discard block
 block discarded – undo
659 659
 			'id' => $row['id'],
660 660
 			'uri' => $row['uri'],
661 661
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
662
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
663 663
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
664
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
666 666
 		];
667 667
 
668 668
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 			return null;
699 699
 		}
700 700
 
701
-		$row['principaluri'] = (string)$row['principaluri'];
701
+		$row['principaluri'] = (string) $row['principaluri'];
702 702
 		$components = [];
703 703
 		if ($row['components']) {
704 704
 			$components = explode(',', $row['components']);
@@ -708,10 +708,10 @@  discard block
 block discarded – undo
708 708
 			'id' => $row['id'],
709 709
 			'uri' => $row['uri'],
710 710
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
711
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
712 712
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
713
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
715 715
 		];
716 716
 
717 717
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -746,14 +746,14 @@  discard block
 block discarded – undo
746 746
 			return null;
747 747
 		}
748 748
 
749
-		$row['principaluri'] = (string)$row['principaluri'];
749
+		$row['principaluri'] = (string) $row['principaluri'];
750 750
 		$subscription = [
751 751
 			'id' => $row['id'],
752 752
 			'uri' => $row['uri'],
753 753
 			'principaluri' => $row['principaluri'],
754 754
 			'source' => $row['source'],
755 755
 			'lastmodified' => $row['lastmodified'],
756
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
756
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757 757
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758 758
 		];
759 759
 
@@ -783,14 +783,14 @@  discard block
 block discarded – undo
783 783
 			return null;
784 784
 		}
785 785
 
786
-		$row['principaluri'] = (string)$row['principaluri'];
786
+		$row['principaluri'] = (string) $row['principaluri'];
787 787
 		$subscription = [
788 788
 			'id' => $row['id'],
789 789
 			'uri' => $row['uri'],
790 790
 			'principaluri' => $row['principaluri'],
791 791
 			'source' => $row['source'],
792 792
 			'lastmodified' => $row['lastmodified'],
793
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
793
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794 794
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795 795
 		];
796 796
 
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829 829
 		if (isset($properties[$sccs])) {
830 830
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
831
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832 832
 			}
833 833
 			$values['components'] = implode(',', $properties[$sccs]->getValue());
834 834
 		} elseif (isset($properties['components'])) {
@@ -837,9 +837,9 @@  discard block
 block discarded – undo
837 837
 			$values['components'] = $properties['components'];
838 838
 		}
839 839
 
840
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
840
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
841 841
 		if (isset($properties[$transp])) {
842
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
842
+			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
843 843
 		}
844 844
 
845 845
 		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 			}
849 849
 		}
850 850
 
851
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
851
+		[$calendarId, $calendarData] = $this->atomic(function() use ($values) {
852 852
 			$query = $this->db->getQueryBuilder();
853 853
 			$query->insert('calendars');
854 854
 			foreach ($values as $column => $value) {
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 			return [$calendarId, $calendarData];
862 862
 		}, $this->db);
863 863
 
864
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
864
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
865 865
 
866 866
 		return $calendarId;
867 867
 	}
@@ -884,15 +884,15 @@  discard block
 block discarded – undo
884 884
 	 */
885 885
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
886 886
 		$supportedProperties = array_keys($this->propertyMap);
887
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
887
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
888 888
 
889
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
889
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
890 890
 			$newValues = [];
891 891
 			foreach ($mutations as $propertyName => $propertyValue) {
892 892
 				switch ($propertyName) {
893
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
893
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
894 894
 						$fieldName = 'transparent';
895
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
895
+						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
896 896
 						break;
897 897
 					default:
898 898
 						$fieldName = $this->propertyMap[$propertyName][0];
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 						break;
901 901
 				}
902 902
 			}
903
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
903
+			[$calendarData, $shares] = $this->atomic(function() use ($calendarId, $newValues) {
904 904
 				$query = $this->db->getQueryBuilder();
905 905
 				$query->update('calendars');
906 906
 				foreach ($newValues as $fieldName => $value) {
@@ -929,9 +929,9 @@  discard block
 block discarded – undo
929 929
 	 * @return void
930 930
 	 */
931 931
 	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
-		$this->publishStatusCache->remove((string)$calendarId);
932
+		$this->publishStatusCache->remove((string) $calendarId);
933 933
 
934
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
934
+		$this->atomic(function() use ($calendarId, $forceDeletePermanently): void {
935 935
 			// The calendar is deleted right away if this is either enforced by the caller
936 936
 			// or the special contacts birthday calendar or when the preference of an empty
937 937
 			// retention (0 seconds) is set, which signals a disabled trashbin.
@@ -994,7 +994,7 @@  discard block
 block discarded – undo
994 994
 	}
995 995
 
996 996
 	public function restoreCalendar(int $id): void {
997
-		$this->atomic(function () use ($id): void {
997
+		$this->atomic(function() use ($id): void {
998 998
 			$qb = $this->db->getQueryBuilder();
999 999
 			$update = $qb->update('calendars')
1000 1000
 				->set('deleted_at', $qb->createNamedParameter(null))
@@ -1141,11 +1141,11 @@  discard block
 block discarded – undo
1141 1141
 				'id' => $row['id'],
1142 1142
 				'uri' => $row['uri'],
1143 1143
 				'lastmodified' => $row['lastmodified'],
1144
-				'etag' => '"' . $row['etag'] . '"',
1144
+				'etag' => '"'.$row['etag'].'"',
1145 1145
 				'calendarid' => $row['calendarid'],
1146
-				'size' => (int)$row['size'],
1146
+				'size' => (int) $row['size'],
1147 1147
 				'component' => strtolower($row['componenttype']),
1148
-				'classification' => (int)$row['classification']
1148
+				'classification' => (int) $row['classification']
1149 1149
 			];
1150 1150
 		}
1151 1151
 		$stmt->closeCursor();
@@ -1168,13 +1168,13 @@  discard block
 block discarded – undo
1168 1168
 				'id' => $row['id'],
1169 1169
 				'uri' => $row['uri'],
1170 1170
 				'lastmodified' => $row['lastmodified'],
1171
-				'etag' => '"' . $row['etag'] . '"',
1172
-				'calendarid' => (int)$row['calendarid'],
1173
-				'calendartype' => (int)$row['calendartype'],
1174
-				'size' => (int)$row['size'],
1171
+				'etag' => '"'.$row['etag'].'"',
1172
+				'calendarid' => (int) $row['calendarid'],
1173
+				'calendartype' => (int) $row['calendartype'],
1174
+				'size' => (int) $row['size'],
1175 1175
 				'component' => strtolower($row['componenttype']),
1176
-				'classification' => (int)$row['classification'],
1177
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1176
+				'classification' => (int) $row['classification'],
1177
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1178 1178
 			];
1179 1179
 		}
1180 1180
 		$stmt->closeCursor();
@@ -1207,13 +1207,13 @@  discard block
 block discarded – undo
1207 1207
 				'id' => $row['id'],
1208 1208
 				'uri' => $row['uri'],
1209 1209
 				'lastmodified' => $row['lastmodified'],
1210
-				'etag' => '"' . $row['etag'] . '"',
1210
+				'etag' => '"'.$row['etag'].'"',
1211 1211
 				'calendarid' => $row['calendarid'],
1212 1212
 				'calendaruri' => $row['calendaruri'],
1213
-				'size' => (int)$row['size'],
1213
+				'size' => (int) $row['size'],
1214 1214
 				'component' => strtolower($row['componenttype']),
1215
-				'classification' => (int)$row['classification'],
1216
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1215
+				'classification' => (int) $row['classification'],
1216
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1217 1217
 			];
1218 1218
 		}
1219 1219
 		$stmt->closeCursor();
@@ -1239,7 +1239,7 @@  discard block
 block discarded – undo
1239 1239
 	 * @return array|null
1240 1240
 	 */
1241 1241
 	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1242
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1242
+		$key = $calendarId.'::'.$objectUri.'::'.$calendarType;
1243 1243
 		if (isset($this->cachedObjects[$key])) {
1244 1244
 			return $this->cachedObjects[$key];
1245 1245
 		}
@@ -1268,13 +1268,13 @@  discard block
 block discarded – undo
1268 1268
 			'uri' => $row['uri'],
1269 1269
 			'uid' => $row['uid'],
1270 1270
 			'lastmodified' => $row['lastmodified'],
1271
-			'etag' => '"' . $row['etag'] . '"',
1271
+			'etag' => '"'.$row['etag'].'"',
1272 1272
 			'calendarid' => $row['calendarid'],
1273
-			'size' => (int)$row['size'],
1273
+			'size' => (int) $row['size'],
1274 1274
 			'calendardata' => $this->readBlob($row['calendardata']),
1275 1275
 			'component' => strtolower($row['componenttype']),
1276
-			'classification' => (int)$row['classification'],
1277
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1276
+			'classification' => (int) $row['classification'],
1277
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1278 1278
 		];
1279 1279
 	}
1280 1280
 
@@ -1316,12 +1316,12 @@  discard block
 block discarded – undo
1316 1316
 					'id' => $row['id'],
1317 1317
 					'uri' => $row['uri'],
1318 1318
 					'lastmodified' => $row['lastmodified'],
1319
-					'etag' => '"' . $row['etag'] . '"',
1319
+					'etag' => '"'.$row['etag'].'"',
1320 1320
 					'calendarid' => $row['calendarid'],
1321
-					'size' => (int)$row['size'],
1321
+					'size' => (int) $row['size'],
1322 1322
 					'calendardata' => $this->readBlob($row['calendardata']),
1323 1323
 					'component' => strtolower($row['componenttype']),
1324
-					'classification' => (int)$row['classification']
1324
+					'classification' => (int) $row['classification']
1325 1325
 				];
1326 1326
 			}
1327 1327
 			$result->closeCursor();
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
 		$this->cachedObjects = [];
1354 1354
 		$extraData = $this->getDenormalizedData($calendarData);
1355 1355
 
1356
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1356
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1357 1357
 			// Try to detect duplicates
1358 1358
 			$qb = $this->db->getQueryBuilder();
1359 1359
 			$qb->select($qb->func()->count('*'))
@@ -1363,7 +1363,7 @@  discard block
 block discarded – undo
1363 1363
 				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1364 1364
 				->andWhere($qb->expr()->isNull('deleted_at'));
1365 1365
 			$result = $qb->executeQuery();
1366
-			$count = (int)$result->fetchOne();
1366
+			$count = (int) $result->fetchOne();
1367 1367
 			$result->closeCursor();
1368 1368
 
1369 1369
 			if ($count !== 0) {
@@ -1423,7 +1423,7 @@  discard block
 block discarded – undo
1423 1423
 				// TODO: implement custom event for federated calendars
1424 1424
 			}
1425 1425
 
1426
-			return '"' . $extraData['etag'] . '"';
1426
+			return '"'.$extraData['etag'].'"';
1427 1427
 		}, $this->db);
1428 1428
 	}
1429 1429
 
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
 		$this->cachedObjects = [];
1451 1451
 		$extraData = $this->getDenormalizedData($calendarData);
1452 1452
 
1453
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1453
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1454 1454
 			$query = $this->db->getQueryBuilder();
1455 1455
 			$query->update('calendarobjects')
1456 1456
 				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
 				}
1487 1487
 			}
1488 1488
 
1489
-			return '"' . $extraData['etag'] . '"';
1489
+			return '"'.$extraData['etag'].'"';
1490 1490
 		}, $this->db);
1491 1491
 	}
1492 1492
 
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 	 */
1505 1505
 	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1506 1506
 		$this->cachedObjects = [];
1507
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1507
+		return $this->atomic(function() use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1508 1508
 			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1509 1509
 			if (empty($object)) {
1510 1510
 				return false;
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
 	 */
1562 1562
 	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1563 1563
 		$this->cachedObjects = [];
1564
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1564
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1565 1565
 			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1566 1566
 
1567 1567
 			if ($data === null) {
@@ -1645,8 +1645,8 @@  discard block
 block discarded – undo
1645 1645
 	 */
1646 1646
 	public function restoreCalendarObject(array $objectData): void {
1647 1647
 		$this->cachedObjects = [];
1648
-		$this->atomic(function () use ($objectData): void {
1649
-			$id = (int)$objectData['id'];
1648
+		$this->atomic(function() use ($objectData): void {
1649
+			$id = (int) $objectData['id'];
1650 1650
 			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1651 1651
 			$targetObject = $this->getCalendarObject(
1652 1652
 				$objectData['calendarid'],
@@ -1676,17 +1676,17 @@  discard block
 block discarded – undo
1676 1676
 				// Welp, this should possibly not have happened, but let's ignore
1677 1677
 				return;
1678 1678
 			}
1679
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1679
+			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int) $row['calendartype']);
1680 1680
 
1681
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1681
+			$calendarRow = $this->getCalendarById((int) $row['calendarid']);
1682 1682
 			if ($calendarRow === null) {
1683 1683
 				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1684 1684
 			}
1685 1685
 			$this->dispatcher->dispatchTyped(
1686 1686
 				new CalendarObjectRestoredEvent(
1687
-					(int)$objectData['calendarid'],
1687
+					(int) $objectData['calendarid'],
1688 1688
 					$calendarRow,
1689
-					$this->getShares((int)$row['calendarid']),
1689
+					$this->getShares((int) $row['calendarid']),
1690 1690
 					$row
1691 1691
 				)
1692 1692
 			);
@@ -1805,19 +1805,19 @@  discard block
 block discarded – undo
1805 1805
 				try {
1806 1806
 					$matches = $this->validateFilterForObject($row, $filters);
1807 1807
 				} catch (ParseException $ex) {
1808
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1808
+					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1809 1809
 						'app' => 'dav',
1810 1810
 						'exception' => $ex,
1811 1811
 					]);
1812 1812
 					continue;
1813 1813
 				} catch (InvalidDataException $ex) {
1814
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1814
+					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1815 1815
 						'app' => 'dav',
1816 1816
 						'exception' => $ex,
1817 1817
 					]);
1818 1818
 					continue;
1819 1819
 				} catch (MaxInstancesExceededException $ex) {
1820
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1820
+					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
1821 1821
 						'app' => 'dav',
1822 1822
 						'exception' => $ex,
1823 1823
 					]);
@@ -1829,7 +1829,7 @@  discard block
 block discarded – undo
1829 1829
 				}
1830 1830
 			}
1831 1831
 			$result[] = $row['uri'];
1832
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1832
+			$key = $calendarId.'::'.$row['uri'].'::'.$calendarType;
1833 1833
 			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1834 1834
 		}
1835 1835
 
@@ -1848,7 +1848,7 @@  discard block
 block discarded – undo
1848 1848
 	 * @return array
1849 1849
 	 */
1850 1850
 	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1851
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1851
+		return $this->atomic(function() use ($principalUri, $filters, $limit, $offset) {
1852 1852
 			$calendars = $this->getCalendarsForUser($principalUri);
1853 1853
 			$ownCalendars = [];
1854 1854
 			$sharedCalendars = [];
@@ -1940,7 +1940,7 @@  discard block
 block discarded – undo
1940 1940
 				->andWhere($compExpr)
1941 1941
 				->andWhere($propParamExpr)
1942 1942
 				->andWhere($query->expr()->iLike('i.value',
1943
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1943
+					$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
1944 1944
 				->andWhere($query->expr()->isNull('deleted_at'));
1945 1945
 
1946 1946
 			if ($offset) {
@@ -1954,7 +1954,7 @@  discard block
 block discarded – undo
1954 1954
 
1955 1955
 			$result = [];
1956 1956
 			while ($row = $stmt->fetchAssociative()) {
1957
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1957
+				$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1958 1958
 				if (!in_array($path, $result)) {
1959 1959
 					$result[] = $path;
1960 1960
 				}
@@ -2024,7 +2024,7 @@  discard block
 block discarded – undo
2024 2024
 		if ($pattern !== '') {
2025 2025
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2026 2026
 				$outerQuery->createNamedParameter('%'
2027
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2027
+					. $this->db->escapeLikeParameter($pattern).'%')));
2028 2028
 		}
2029 2029
 
2030 2030
 		$start = null;
@@ -2076,7 +2076,7 @@  discard block
 block discarded – undo
2076 2076
 		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2077 2077
 		$outerQuery->addOrderBy('id');
2078 2078
 
2079
-		$offset = (int)$offset;
2079
+		$offset = (int) $offset;
2080 2080
 		$outerQuery->setFirstResult($offset);
2081 2081
 
2082 2082
 		$calendarObjects = [];
@@ -2097,7 +2097,7 @@  discard block
 block discarded – undo
2097 2097
 			 *
2098 2098
 			 * 25 rows and 3 retries is entirely arbitrary.
2099 2099
 			 */
2100
-			$maxResults = (int)max($limit, 25);
2100
+			$maxResults = (int) max($limit, 25);
2101 2101
 			$outerQuery->setMaxResults($maxResults);
2102 2102
 
2103 2103
 			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
@@ -2111,7 +2111,7 @@  discard block
 block discarded – undo
2111 2111
 			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2112 2112
 		}
2113 2113
 
2114
-		$calendarObjects = array_map(function ($o) use ($options) {
2114
+		$calendarObjects = array_map(function($o) use ($options) {
2115 2115
 			$calendarData = Reader::read($o['calendardata']);
2116 2116
 
2117 2117
 			// Expand recurrences if an explicit time range is requested
@@ -2139,16 +2139,16 @@  discard block
 block discarded – undo
2139 2139
 				'type' => $o['componenttype'],
2140 2140
 				'uid' => $o['uid'],
2141 2141
 				'uri' => $o['uri'],
2142
-				'objects' => array_map(function ($c) {
2142
+				'objects' => array_map(function($c) {
2143 2143
 					return $this->transformSearchData($c);
2144 2144
 				}, $objects),
2145
-				'timezones' => array_map(function ($c) {
2145
+				'timezones' => array_map(function($c) {
2146 2146
 					return $this->transformSearchData($c);
2147 2147
 				}, $timezones),
2148 2148
 			];
2149 2149
 		}, $calendarObjects);
2150 2150
 
2151
-		usort($calendarObjects, function (array $a, array $b) {
2151
+		usort($calendarObjects, function(array $a, array $b) {
2152 2152
 			/** @var DateTimeImmutable $startA */
2153 2153
 			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2154 2154
 			/** @var DateTimeImmutable $startB */
@@ -2193,7 +2193,7 @@  discard block
 block discarded – undo
2193 2193
 					'time-range' => null,
2194 2194
 				]);
2195 2195
 			} catch (MaxInstancesExceededException $ex) {
2196
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2196
+				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
2197 2197
 					'app' => 'dav',
2198 2198
 					'exception' => $ex,
2199 2199
 				]);
@@ -2224,7 +2224,7 @@  discard block
 block discarded – undo
2224 2224
 		/** @var Component[] $subComponents */
2225 2225
 		$subComponents = $comp->getComponents();
2226 2226
 		/** @var Property[] $properties */
2227
-		$properties = array_filter($comp->children(), function ($c) {
2227
+		$properties = array_filter($comp->children(), function($c) {
2228 2228
 			return $c instanceof Property;
2229 2229
 		});
2230 2230
 		$validationRules = $comp->getValidationRules();
@@ -2292,7 +2292,7 @@  discard block
 block discarded – undo
2292 2292
 		array $searchParameters,
2293 2293
 		array $options = [],
2294 2294
 	): array {
2295
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2295
+		return $this->atomic(function() use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2296 2296
 			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2297 2297
 
2298 2298
 			$calendarObjectIdQuery = $this->db->getQueryBuilder();
@@ -2304,7 +2304,7 @@  discard block
 block discarded – undo
2304 2304
 			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2305 2305
 			foreach ($calendars as $calendar) {
2306 2306
 				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2307
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2307
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])),
2308 2308
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2309 2309
 				);
2310 2310
 
@@ -2318,7 +2318,7 @@  discard block
 block discarded – undo
2318 2318
 			}
2319 2319
 			foreach ($subscriptions as $subscription) {
2320 2320
 				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2321
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2321
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])),
2322 2322
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2323 2323
 				);
2324 2324
 
@@ -2367,7 +2367,7 @@  discard block
 block discarded – undo
2367 2367
 				if (!$escapePattern) {
2368 2368
 					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2369 2369
 				} else {
2370
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2370
+					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
2371 2371
 				}
2372 2372
 			}
2373 2373
 
@@ -2395,7 +2395,7 @@  discard block
 block discarded – undo
2395 2395
 			$result = $calendarObjectIdQuery->executeQuery();
2396 2396
 			$matches = [];
2397 2397
 			while (($row = $result->fetchAssociative()) !== false) {
2398
-				$matches[] = (int)$row['objectid'];
2398
+				$matches[] = (int) $row['objectid'];
2399 2399
 			}
2400 2400
 			$result->closeCursor();
2401 2401
 
@@ -2407,8 +2407,8 @@  discard block
 block discarded – undo
2407 2407
 			$result = $query->executeQuery();
2408 2408
 			$calendarObjects = [];
2409 2409
 			while (($array = $result->fetchAssociative()) !== false) {
2410
-				$array['calendarid'] = (int)$array['calendarid'];
2411
-				$array['calendartype'] = (int)$array['calendartype'];
2410
+				$array['calendarid'] = (int) $array['calendarid'];
2411
+				$array['calendartype'] = (int) $array['calendartype'];
2412 2412
 				$array['calendardata'] = $this->readBlob($array['calendardata']);
2413 2413
 
2414 2414
 				$calendarObjects[] = $array;
@@ -2454,7 +2454,7 @@  discard block
 block discarded – undo
2454 2454
 		$row = $stmt->fetchAssociative();
2455 2455
 		$stmt->closeCursor();
2456 2456
 		if ($row) {
2457
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2457
+			return $row['calendaruri'].'/'.$row['objecturi'];
2458 2458
 		}
2459 2459
 
2460 2460
 		return null;
@@ -2480,14 +2480,14 @@  discard block
 block discarded – undo
2480 2480
 			'id' => $row['id'],
2481 2481
 			'uri' => $row['uri'],
2482 2482
 			'lastmodified' => $row['lastmodified'],
2483
-			'etag' => '"' . $row['etag'] . '"',
2483
+			'etag' => '"'.$row['etag'].'"',
2484 2484
 			'calendarid' => $row['calendarid'],
2485 2485
 			'calendaruri' => $row['calendaruri'],
2486
-			'size' => (int)$row['size'],
2486
+			'size' => (int) $row['size'],
2487 2487
 			'calendardata' => $this->readBlob($row['calendardata']),
2488 2488
 			'component' => strtolower($row['componenttype']),
2489
-			'classification' => (int)$row['classification'],
2490
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2489
+			'classification' => (int) $row['classification'],
2490
+			'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2491 2491
 		];
2492 2492
 	}
2493 2493
 
@@ -2549,9 +2549,9 @@  discard block
 block discarded – undo
2549 2549
 	 * @return ?array
2550 2550
 	 */
2551 2551
 	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2552
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2552
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2553 2553
 
2554
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2554
+		return $this->atomic(function() use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2555 2555
 			// Current synctoken
2556 2556
 			$qb = $this->db->getQueryBuilder();
2557 2557
 			$qb->select('synctoken')
@@ -2602,7 +2602,7 @@  discard block
 block discarded – undo
2602 2602
 				while ($entry = $stmt->fetchNumeric()) {
2603 2603
 					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2604 2604
 					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2605
-					match ((int)$entry[1]) {
2605
+					match ((int) $entry[1]) {
2606 2606
 						1 => $result['added'][] = $entry[0],
2607 2607
 						2 => $result['modified'][] = $entry[0],
2608 2608
 						3 => $result['deleted'][] = $entry[0],
@@ -2673,7 +2673,7 @@  discard block
 block discarded – undo
2673 2673
 				'source' => $row['source'],
2674 2674
 				'lastmodified' => $row['lastmodified'],
2675 2675
 
2676
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2676
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2677 2677
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2678 2678
 			];
2679 2679
 
@@ -2717,7 +2717,7 @@  discard block
 block discarded – undo
2717 2717
 			}
2718 2718
 		}
2719 2719
 
2720
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2720
+		[$subscriptionId, $subscriptionRow] = $this->atomic(function() use ($values) {
2721 2721
 			$valuesToInsert = [];
2722 2722
 			$query = $this->db->getQueryBuilder();
2723 2723
 			foreach (array_keys($values) as $name) {
@@ -2758,7 +2758,7 @@  discard block
 block discarded – undo
2758 2758
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2759 2759
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2760 2760
 
2761
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2761
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2762 2762
 			$newValues = [];
2763 2763
 
2764 2764
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2770,7 +2770,7 @@  discard block
 block discarded – undo
2770 2770
 				}
2771 2771
 			}
2772 2772
 
2773
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2773
+			$subscriptionRow = $this->atomic(function() use ($subscriptionId, $newValues) {
2774 2774
 				$query = $this->db->getQueryBuilder();
2775 2775
 				$query->update('calendarsubscriptions')
2776 2776
 					->set('lastmodified', $query->createNamedParameter(time()));
@@ -2783,7 +2783,7 @@  discard block
 block discarded – undo
2783 2783
 				return $this->getSubscriptionById($subscriptionId);
2784 2784
 			}, $this->db);
2785 2785
 
2786
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2786
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2787 2787
 
2788 2788
 			return true;
2789 2789
 		});
@@ -2796,7 +2796,7 @@  discard block
 block discarded – undo
2796 2796
 	 * @return void
2797 2797
 	 */
2798 2798
 	public function deleteSubscription($subscriptionId) {
2799
-		$this->atomic(function () use ($subscriptionId): void {
2799
+		$this->atomic(function() use ($subscriptionId): void {
2800 2800
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2801 2801
 
2802 2802
 			$query = $this->db->getQueryBuilder();
@@ -2821,7 +2821,7 @@  discard block
 block discarded – undo
2821 2821
 				->executeStatement();
2822 2822
 
2823 2823
 			if ($subscriptionRow) {
2824
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2824
+				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2825 2825
 			}
2826 2826
 		}, $this->db);
2827 2827
 	}
@@ -2860,8 +2860,8 @@  discard block
 block discarded – undo
2860 2860
 			'uri' => $row['uri'],
2861 2861
 			'calendardata' => $row['calendardata'],
2862 2862
 			'lastmodified' => $row['lastmodified'],
2863
-			'etag' => '"' . $row['etag'] . '"',
2864
-			'size' => (int)$row['size'],
2863
+			'etag' => '"'.$row['etag'].'"',
2864
+			'size' => (int) $row['size'],
2865 2865
 		];
2866 2866
 	}
2867 2867
 
@@ -2889,8 +2889,8 @@  discard block
 block discarded – undo
2889 2889
 				'calendardata' => $row['calendardata'],
2890 2890
 				'uri' => $row['uri'],
2891 2891
 				'lastmodified' => $row['lastmodified'],
2892
-				'etag' => '"' . $row['etag'] . '"',
2893
-				'size' => (int)$row['size'],
2892
+				'etag' => '"'.$row['etag'].'"',
2893
+				'size' => (int) $row['size'],
2894 2894
 			];
2895 2895
 		}
2896 2896
 		$stmt->closeCursor();
@@ -2932,8 +2932,8 @@  discard block
 block discarded – undo
2932 2932
 		if ($count === 0) {
2933 2933
 			return;
2934 2934
 		}
2935
-		$ids = array_map(static function (array $id) {
2936
-			return (int)$id[0];
2935
+		$ids = array_map(static function(array $id) {
2936
+			return (int) $id[0];
2937 2937
 		}, $result->fetchAllNumeric());
2938 2938
 		$result->closeCursor();
2939 2939
 
@@ -2986,15 +2986,15 @@  discard block
 block discarded – undo
2986 2986
 	 */
2987 2987
 	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2988 2988
 		$this->cachedObjects = [];
2989
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2989
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2990 2990
 
2991
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2991
+		$this->atomic(function() use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2992 2992
 			$query = $this->db->getQueryBuilder();
2993 2993
 			$query->select('synctoken')
2994 2994
 				->from($table)
2995 2995
 				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2996 2996
 			$result = $query->executeQuery();
2997
-			$syncToken = (int)$result->fetchOne();
2997
+			$syncToken = (int) $result->fetchOne();
2998 2998
 			$result->closeCursor();
2999 2999
 
3000 3000
 			$query = $this->db->getQueryBuilder();
@@ -3023,7 +3023,7 @@  discard block
 block discarded – undo
3023 3023
 	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3024 3024
 		$this->cachedObjects = [];
3025 3025
 
3026
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3026
+		$this->atomic(function() use ($calendarId, $calendarType): void {
3027 3027
 			$qbAdded = $this->db->getQueryBuilder();
3028 3028
 			$qbAdded->select('uri')
3029 3029
 				->from('calendarobjects')
@@ -3053,7 +3053,7 @@  discard block
 block discarded – undo
3053 3053
 					)
3054 3054
 				);
3055 3055
 			$resultDeleted = $qbDeleted->executeQuery();
3056
-			$deletedUris = array_map(function (string $uri) {
3056
+			$deletedUris = array_map(function(string $uri) {
3057 3057
 				return str_replace('-deleted.ics', '.ics', $uri);
3058 3058
 			}, $resultDeleted->fetchFirstColumn());
3059 3059
 			$resultDeleted->closeCursor();
@@ -3098,7 +3098,7 @@  discard block
 block discarded – undo
3098 3098
 				// Track first component type and uid
3099 3099
 				if ($uid === null) {
3100 3100
 					$componentType = $component->name;
3101
-					$uid = (string)$component->UID;
3101
+					$uid = (string) $component->UID;
3102 3102
 				}
3103 3103
 			}
3104 3104
 		}
@@ -3189,11 +3189,11 @@  discard block
 block discarded – undo
3189 3189
 	 * @param list<string> $remove
3190 3190
 	 */
3191 3191
 	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3192
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3192
+		$this->atomic(function() use ($shareable, $add, $remove): void {
3193 3193
 			$calendarId = $shareable->getResourceId();
3194 3194
 			$calendarRow = $this->getCalendarById($calendarId);
3195 3195
 			if ($calendarRow === null) {
3196
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3196
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$calendarId);
3197 3197
 			}
3198 3198
 			$oldShares = $this->getShares($calendarId);
3199 3199
 
@@ -3224,7 +3224,7 @@  discard block
 block discarded – undo
3224 3224
 	 * @return string|null
3225 3225
 	 */
3226 3226
 	public function setPublishStatus($value, $calendar) {
3227
-		$publishStatus = $this->atomic(function () use ($value, $calendar) {
3227
+		$publishStatus = $this->atomic(function() use ($value, $calendar) {
3228 3228
 			$calendarId = $calendar->getResourceId();
3229 3229
 			$calendarData = $this->getCalendarById($calendarId);
3230 3230
 
@@ -3253,7 +3253,7 @@  discard block
 block discarded – undo
3253 3253
 			return null;
3254 3254
 		}, $this->db);
3255 3255
 
3256
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3256
+		$this->publishStatusCache->set((string) $calendar->getResourceId(), $publishStatus ?? false);
3257 3257
 		return $publishStatus;
3258 3258
 	}
3259 3259
 
@@ -3262,7 +3262,7 @@  discard block
 block discarded – undo
3262 3262
 	 * @return string|false
3263 3263
 	 */
3264 3264
 	public function getPublishStatus($calendar) {
3265
-		$cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3265
+		$cached = $this->publishStatusCache->get((string) $calendar->getResourceId());
3266 3266
 		if ($cached !== null) {
3267 3267
 			return $cached;
3268 3268
 		}
@@ -3277,7 +3277,7 @@  discard block
 block discarded – undo
3277 3277
 		$publishStatus = $result->fetchOne();
3278 3278
 		$result->closeCursor();
3279 3279
 
3280
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3280
+		$this->publishStatusCache->set((string) $calendar->getResourceId(), $publishStatus);
3281 3281
 		return $publishStatus;
3282 3282
 	}
3283 3283
 
@@ -3302,14 +3302,14 @@  discard block
 block discarded – undo
3302 3302
 
3303 3303
 		$hasPublishStatuses = [];
3304 3304
 		while ($row = $result->fetchAssociative()) {
3305
-			$this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3306
-			$hasPublishStatuses[(int)$row['resourceid']] = true;
3305
+			$this->publishStatusCache->set((string) $row['resourceid'], $row['publicuri']);
3306
+			$hasPublishStatuses[(int) $row['resourceid']] = true;
3307 3307
 		}
3308 3308
 
3309 3309
 		// Also remember resources with no publish status
3310 3310
 		foreach ($resourceIds as $resourceId) {
3311 3311
 			if (!isset($hasPublishStatuses[$resourceId])) {
3312
-				$this->publishStatusCache->set((string)$resourceId, false);
3312
+				$this->publishStatusCache->set((string) $resourceId, false);
3313 3313
 			}
3314 3314
 		}
3315 3315
 
@@ -3336,7 +3336,7 @@  discard block
 block discarded – undo
3336 3336
 	 */
3337 3337
 	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3338 3338
 		$this->cachedObjects = [];
3339
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3339
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3340 3340
 			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3341 3341
 
3342 3342
 			try {
@@ -3408,7 +3408,7 @@  discard block
 block discarded – undo
3408 3408
 	 * deletes all birthday calendars
3409 3409
 	 */
3410 3410
 	public function deleteAllBirthdayCalendars() {
3411
-		$this->atomic(function (): void {
3411
+		$this->atomic(function(): void {
3412 3412
 			$query = $this->db->getQueryBuilder();
3413 3413
 			$result = $query->select(['id'])->from('calendars')
3414 3414
 				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
@@ -3428,7 +3428,7 @@  discard block
 block discarded – undo
3428 3428
 	 * @param $subscriptionId
3429 3429
 	 */
3430 3430
 	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3431
-		$this->atomic(function () use ($subscriptionId): void {
3431
+		$this->atomic(function() use ($subscriptionId): void {
3432 3432
 			$query = $this->db->getQueryBuilder();
3433 3433
 			$query->select('uri')
3434 3434
 				->from('calendarobjects')
@@ -3474,7 +3474,7 @@  discard block
 block discarded – undo
3474 3474
 			return;
3475 3475
 		}
3476 3476
 
3477
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3477
+		$this->atomic(function() use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3478 3478
 			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3479 3479
 				$query = $this->db->getQueryBuilder();
3480 3480
 				$query->delete($this->dbObjectPropertiesTable)
@@ -3567,10 +3567,10 @@  discard block
 block discarded – undo
3567 3567
 		$result->closeCursor();
3568 3568
 
3569 3569
 		if (!isset($objectIds['id'])) {
3570
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3570
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
3571 3571
 		}
3572 3572
 
3573
-		return (int)$objectIds['id'];
3573
+		return (int) $objectIds['id'];
3574 3574
 	}
3575 3575
 
3576 3576
 	/**
@@ -3586,7 +3586,7 @@  discard block
 block discarded – undo
3586 3586
 			->from('calendarchanges');
3587 3587
 
3588 3588
 		$result = $query->executeQuery();
3589
-		$maxId = (int)$result->fetchOne();
3589
+		$maxId = (int) $result->fetchOne();
3590 3590
 		$result->closeCursor();
3591 3591
 		if (!$maxId || $maxId < $keep) {
3592 3592
 			return 0;
@@ -3624,8 +3624,8 @@  discard block
 block discarded – undo
3624 3624
 	 *
3625 3625
 	 */
3626 3626
 	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3627
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3628
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3627
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
3628
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
3629 3629
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
3630 3630
 			$uri = $calendarInfo[$ownerPrincipalKey];
3631 3631
 		} else {
@@ -3736,10 +3736,10 @@  discard block
 block discarded – undo
3736 3736
 	}
3737 3737
 
3738 3738
 	public function unshare(IShareable $shareable, string $principal): void {
3739
-		$this->atomic(function () use ($shareable, $principal): void {
3739
+		$this->atomic(function() use ($shareable, $principal): void {
3740 3740
 			$calendarData = $this->getCalendarById($shareable->getResourceId());
3741 3741
 			if ($calendarData === null) {
3742
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3742
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$shareable->getResourceId());
3743 3743
 			}
3744 3744
 
3745 3745
 			$oldShares = $this->getShares($shareable->getResourceId());
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php 2 patches
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -22,196 +22,196 @@
 block discarded – undo
22 22
 
23 23
 class RefreshWebcalService {
24 24
 
25
-	public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
26
-	public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
27
-	public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
28
-	public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
29
-
30
-	public function __construct(
31
-		private CalDavBackend $calDavBackend,
32
-		private LoggerInterface $logger,
33
-		private Connection $connection,
34
-		private ITimeFactory $time,
35
-		private ImportService $importService,
36
-	) {
37
-	}
38
-
39
-	public function refreshSubscription(string $principalUri, string $uri) {
40
-		$subscription = $this->getSubscription($principalUri, $uri);
41
-		if (!$subscription) {
42
-			return;
43
-		}
44
-
45
-		// Check the refresh rate if there is any
46
-		if (!empty($subscription[self::REFRESH_RATE])) {
47
-			// add the refresh interval to the last modified timestamp
48
-			$refreshInterval = new \DateInterval($subscription[self::REFRESH_RATE]);
49
-			$updateTime = $this->time->getDateTime();
50
-			$updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval);
51
-			if ($updateTime->getTimestamp() > $this->time->getTime()) {
52
-				return;
53
-			}
54
-		}
55
-
56
-		$result = $this->connection->queryWebcalFeed($subscription);
57
-		if (!$result) {
58
-			return;
59
-		}
60
-
61
-		$data = $result['data'];
62
-		$format = $result['format'];
63
-
64
-		$stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
65
-		$stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
66
-		$stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
67
-
68
-		try {
69
-			$existingObjects = $this->calDavBackend->getLimitedCalendarObjects((int)$subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION, ['id', 'uid', 'etag', 'uri']);
70
-
71
-			$generator = match ($format) {
72
-				'xcal' => $this->importService->importXml(...),
73
-				'jcal' => $this->importService->importJson(...),
74
-				default => $this->importService->importText(...)
75
-			};
76
-
77
-			foreach ($generator($data) as $vObject) {
78
-				/** @var Component\VCalendar $vObject */
79
-				$vBase = $vObject->getBaseComponent();
80
-
81
-				if (!$vBase->UID) {
82
-					continue;
83
-				}
84
-
85
-				// Some calendar providers (e.g. Google, MS) use very long UIDs
86
-				if (strlen($vBase->UID->getValue()) > 512) {
87
-					$this->logger->warning('Skipping calendar object with overly long UID from subscription "{subscriptionId}"', [
88
-						'subscriptionId' => $subscription['id'],
89
-						'uid' => $vBase->UID->getValue(),
90
-					]);
91
-					continue;
92
-				}
93
-
94
-				if ($stripTodos && $vBase->name === 'VTODO') {
95
-					continue;
96
-				}
97
-
98
-				if ($stripAlarms || $stripAttachments) {
99
-					foreach ($vObject->getComponents() as $component) {
100
-						if ($component->name === 'VTIMEZONE') {
101
-							continue;
102
-						}
103
-						if ($stripAlarms) {
104
-							$component->remove('VALARM');
105
-						}
106
-						if ($stripAttachments) {
107
-							$component->remove('ATTACH');
108
-						}
109
-					}
110
-				}
111
-
112
-				$sObject = $vObject->serialize();
113
-				$uid = $vBase->UID->getValue();
114
-				$etag = md5($sObject);
115
-
116
-				// No existing object with this UID, create it
117
-				if (!isset($existingObjects[$uid])) {
118
-					try {
119
-						$this->calDavBackend->createCalendarObject(
120
-							$subscription['id'],
121
-							UUIDUtil::getUUID() . '.ics',
122
-							$sObject,
123
-							CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
124
-						);
125
-					} catch (\Exception $ex) {
126
-						$this->logger->warning('Unable to create calendar object from subscription {subscriptionId}', [
127
-							'exception' => $ex,
128
-							'subscriptionId' => $subscription['id'],
129
-							'source' => $subscription['source'],
130
-						]);
131
-					}
132
-				} elseif ($existingObjects[$uid]['etag'] !== $etag) {
133
-					// Existing object with this UID but different etag, update it
134
-					$this->calDavBackend->updateCalendarObject(
135
-						$subscription['id'],
136
-						$existingObjects[$uid]['uri'],
137
-						$sObject,
138
-						CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
139
-					);
140
-					unset($existingObjects[$uid]);
141
-				} else {
142
-					// Existing object with same etag, just remove from tracking
143
-					unset($existingObjects[$uid]);
144
-				}
145
-			}
146
-
147
-			// Clean up objects that no longer exist in the remote feed
148
-			// The only events left over should be those not found upstream
149
-			if (!empty($existingObjects)) {
150
-				$ids = array_map('intval', array_column($existingObjects, 'id'));
151
-				$uris = array_column($existingObjects, 'uri');
152
-				$this->calDavBackend->purgeCachedEventsForSubscription((int)$subscription['id'], $ids, $uris);
153
-			}
154
-
155
-			// Update refresh rate from the last processed object
156
-			if (isset($vObject)) {
157
-				$this->updateRefreshRate($subscription, $vObject);
158
-			}
159
-		} catch (ParseException $ex) {
160
-			$this->logger->error('Subscription {subscriptionId} could not be refreshed due to a parsing error', ['exception' => $ex, 'subscriptionId' => $subscription['id']]);
161
-		} finally {
162
-			// Close the data stream to free resources
163
-			if (is_resource($data)) {
164
-				fclose($data);
165
-			}
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * loads subscription from backend
171
-	 */
172
-	public function getSubscription(string $principalUri, string $uri): ?array {
173
-		$subscriptions = array_values(array_filter(
174
-			$this->calDavBackend->getSubscriptionsForUser($principalUri),
175
-			function ($sub) use ($uri) {
176
-				return $sub['uri'] === $uri;
177
-			}
178
-		));
179
-
180
-		if (count($subscriptions) === 0) {
181
-			return null;
182
-		}
183
-
184
-		return $subscriptions[0];
185
-	}
186
-
187
-	/**
188
-	 * Update refresh rate from calendar object if:
189
-	 *  - current subscription does not store a refreshrate
190
-	 *  - the webcal feed suggests a valid refreshrate
191
-	 */
192
-	private function updateRefreshRate(array $subscription, Component\VCalendar $vCalendar): void {
193
-		// if there is already a refreshrate stored in the database, don't override it
194
-		if (!empty($subscription[self::REFRESH_RATE])) {
195
-			return;
196
-		}
197
-
198
-		$refreshRate = $vCalendar->{'REFRESH-INTERVAL'}?->getValue()
199
-			?? $vCalendar->{'X-PUBLISHED-TTL'}?->getValue();
200
-
201
-		if ($refreshRate === null) {
202
-			return;
203
-		}
204
-
205
-		// check if refresh rate is valid
206
-		try {
207
-			DateTimeParser::parseDuration($refreshRate);
208
-		} catch (InvalidDataException) {
209
-			return;
210
-		}
211
-
212
-		$propPatch = new PropPatch([self::REFRESH_RATE => $refreshRate]);
213
-		$this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
214
-		$propPatch->commit();
215
-	}
25
+    public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate';
26
+    public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms';
27
+    public const STRIP_ATTACHMENTS = '{http://calendarserver.org/ns/}subscribed-strip-attachments';
28
+    public const STRIP_TODOS = '{http://calendarserver.org/ns/}subscribed-strip-todos';
29
+
30
+    public function __construct(
31
+        private CalDavBackend $calDavBackend,
32
+        private LoggerInterface $logger,
33
+        private Connection $connection,
34
+        private ITimeFactory $time,
35
+        private ImportService $importService,
36
+    ) {
37
+    }
38
+
39
+    public function refreshSubscription(string $principalUri, string $uri) {
40
+        $subscription = $this->getSubscription($principalUri, $uri);
41
+        if (!$subscription) {
42
+            return;
43
+        }
44
+
45
+        // Check the refresh rate if there is any
46
+        if (!empty($subscription[self::REFRESH_RATE])) {
47
+            // add the refresh interval to the last modified timestamp
48
+            $refreshInterval = new \DateInterval($subscription[self::REFRESH_RATE]);
49
+            $updateTime = $this->time->getDateTime();
50
+            $updateTime->setTimestamp($subscription['lastmodified'])->add($refreshInterval);
51
+            if ($updateTime->getTimestamp() > $this->time->getTime()) {
52
+                return;
53
+            }
54
+        }
55
+
56
+        $result = $this->connection->queryWebcalFeed($subscription);
57
+        if (!$result) {
58
+            return;
59
+        }
60
+
61
+        $data = $result['data'];
62
+        $format = $result['format'];
63
+
64
+        $stripTodos = ($subscription[self::STRIP_TODOS] ?? 1) === 1;
65
+        $stripAlarms = ($subscription[self::STRIP_ALARMS] ?? 1) === 1;
66
+        $stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
67
+
68
+        try {
69
+            $existingObjects = $this->calDavBackend->getLimitedCalendarObjects((int)$subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION, ['id', 'uid', 'etag', 'uri']);
70
+
71
+            $generator = match ($format) {
72
+                'xcal' => $this->importService->importXml(...),
73
+                'jcal' => $this->importService->importJson(...),
74
+                default => $this->importService->importText(...)
75
+            };
76
+
77
+            foreach ($generator($data) as $vObject) {
78
+                /** @var Component\VCalendar $vObject */
79
+                $vBase = $vObject->getBaseComponent();
80
+
81
+                if (!$vBase->UID) {
82
+                    continue;
83
+                }
84
+
85
+                // Some calendar providers (e.g. Google, MS) use very long UIDs
86
+                if (strlen($vBase->UID->getValue()) > 512) {
87
+                    $this->logger->warning('Skipping calendar object with overly long UID from subscription "{subscriptionId}"', [
88
+                        'subscriptionId' => $subscription['id'],
89
+                        'uid' => $vBase->UID->getValue(),
90
+                    ]);
91
+                    continue;
92
+                }
93
+
94
+                if ($stripTodos && $vBase->name === 'VTODO') {
95
+                    continue;
96
+                }
97
+
98
+                if ($stripAlarms || $stripAttachments) {
99
+                    foreach ($vObject->getComponents() as $component) {
100
+                        if ($component->name === 'VTIMEZONE') {
101
+                            continue;
102
+                        }
103
+                        if ($stripAlarms) {
104
+                            $component->remove('VALARM');
105
+                        }
106
+                        if ($stripAttachments) {
107
+                            $component->remove('ATTACH');
108
+                        }
109
+                    }
110
+                }
111
+
112
+                $sObject = $vObject->serialize();
113
+                $uid = $vBase->UID->getValue();
114
+                $etag = md5($sObject);
115
+
116
+                // No existing object with this UID, create it
117
+                if (!isset($existingObjects[$uid])) {
118
+                    try {
119
+                        $this->calDavBackend->createCalendarObject(
120
+                            $subscription['id'],
121
+                            UUIDUtil::getUUID() . '.ics',
122
+                            $sObject,
123
+                            CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
124
+                        );
125
+                    } catch (\Exception $ex) {
126
+                        $this->logger->warning('Unable to create calendar object from subscription {subscriptionId}', [
127
+                            'exception' => $ex,
128
+                            'subscriptionId' => $subscription['id'],
129
+                            'source' => $subscription['source'],
130
+                        ]);
131
+                    }
132
+                } elseif ($existingObjects[$uid]['etag'] !== $etag) {
133
+                    // Existing object with this UID but different etag, update it
134
+                    $this->calDavBackend->updateCalendarObject(
135
+                        $subscription['id'],
136
+                        $existingObjects[$uid]['uri'],
137
+                        $sObject,
138
+                        CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
139
+                    );
140
+                    unset($existingObjects[$uid]);
141
+                } else {
142
+                    // Existing object with same etag, just remove from tracking
143
+                    unset($existingObjects[$uid]);
144
+                }
145
+            }
146
+
147
+            // Clean up objects that no longer exist in the remote feed
148
+            // The only events left over should be those not found upstream
149
+            if (!empty($existingObjects)) {
150
+                $ids = array_map('intval', array_column($existingObjects, 'id'));
151
+                $uris = array_column($existingObjects, 'uri');
152
+                $this->calDavBackend->purgeCachedEventsForSubscription((int)$subscription['id'], $ids, $uris);
153
+            }
154
+
155
+            // Update refresh rate from the last processed object
156
+            if (isset($vObject)) {
157
+                $this->updateRefreshRate($subscription, $vObject);
158
+            }
159
+        } catch (ParseException $ex) {
160
+            $this->logger->error('Subscription {subscriptionId} could not be refreshed due to a parsing error', ['exception' => $ex, 'subscriptionId' => $subscription['id']]);
161
+        } finally {
162
+            // Close the data stream to free resources
163
+            if (is_resource($data)) {
164
+                fclose($data);
165
+            }
166
+        }
167
+    }
168
+
169
+    /**
170
+     * loads subscription from backend
171
+     */
172
+    public function getSubscription(string $principalUri, string $uri): ?array {
173
+        $subscriptions = array_values(array_filter(
174
+            $this->calDavBackend->getSubscriptionsForUser($principalUri),
175
+            function ($sub) use ($uri) {
176
+                return $sub['uri'] === $uri;
177
+            }
178
+        ));
179
+
180
+        if (count($subscriptions) === 0) {
181
+            return null;
182
+        }
183
+
184
+        return $subscriptions[0];
185
+    }
186
+
187
+    /**
188
+     * Update refresh rate from calendar object if:
189
+     *  - current subscription does not store a refreshrate
190
+     *  - the webcal feed suggests a valid refreshrate
191
+     */
192
+    private function updateRefreshRate(array $subscription, Component\VCalendar $vCalendar): void {
193
+        // if there is already a refreshrate stored in the database, don't override it
194
+        if (!empty($subscription[self::REFRESH_RATE])) {
195
+            return;
196
+        }
197
+
198
+        $refreshRate = $vCalendar->{'REFRESH-INTERVAL'}?->getValue()
199
+            ?? $vCalendar->{'X-PUBLISHED-TTL'}?->getValue();
200
+
201
+        if ($refreshRate === null) {
202
+            return;
203
+        }
204
+
205
+        // check if refresh rate is valid
206
+        try {
207
+            DateTimeParser::parseDuration($refreshRate);
208
+        } catch (InvalidDataException) {
209
+            return;
210
+        }
211
+
212
+        $propPatch = new PropPatch([self::REFRESH_RATE => $refreshRate]);
213
+        $this->calDavBackend->updateSubscription($subscription['id'], $propPatch);
214
+        $propPatch->commit();
215
+    }
216 216
 
217 217
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 		$stripAttachments = ($subscription[self::STRIP_ATTACHMENTS] ?? 1) === 1;
67 67
 
68 68
 		try {
69
-			$existingObjects = $this->calDavBackend->getLimitedCalendarObjects((int)$subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION, ['id', 'uid', 'etag', 'uri']);
69
+			$existingObjects = $this->calDavBackend->getLimitedCalendarObjects((int) $subscription['id'], CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION, ['id', 'uid', 'etag', 'uri']);
70 70
 
71 71
 			$generator = match ($format) {
72 72
 				'xcal' => $this->importService->importXml(...),
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 					try {
119 119
 						$this->calDavBackend->createCalendarObject(
120 120
 							$subscription['id'],
121
-							UUIDUtil::getUUID() . '.ics',
121
+							UUIDUtil::getUUID().'.ics',
122 122
 							$sObject,
123 123
 							CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
124 124
 						);
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 			if (!empty($existingObjects)) {
150 150
 				$ids = array_map('intval', array_column($existingObjects, 'id'));
151 151
 				$uris = array_column($existingObjects, 'uri');
152
-				$this->calDavBackend->purgeCachedEventsForSubscription((int)$subscription['id'], $ids, $uris);
152
+				$this->calDavBackend->purgeCachedEventsForSubscription((int) $subscription['id'], $ids, $uris);
153 153
 			}
154 154
 
155 155
 			// Update refresh rate from the last processed object
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 	public function getSubscription(string $principalUri, string $uri): ?array {
173 173
 		$subscriptions = array_values(array_filter(
174 174
 			$this->calDavBackend->getSubscriptionsForUser($principalUri),
175
-			function ($sub) use ($uri) {
175
+			function($sub) use ($uri) {
176 176
 				return $sub['uri'] === $uri;
177 177
 			}
178 178
 		));
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/WebcalCaching/Connection.php 1 patch
Indentation   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -16,120 +16,120 @@
 block discarded – undo
16 16
 use Psr\Log\LoggerInterface;
17 17
 
18 18
 class Connection {
19
-	public function __construct(
20
-		private IClientService $clientService,
21
-		private IAppConfig $config,
22
-		private LoggerInterface $logger,
23
-	) {
24
-	}
25
-
26
-	/**
27
-	 * gets webcal feed from remote server
28
-	 *
29
-	 * @return array{data: resource, format: string}|null
30
-	 */
31
-	public function queryWebcalFeed(array $subscription): ?array {
32
-		$subscriptionId = $subscription['id'];
33
-		$url = $this->cleanURL($subscription['source']);
34
-		if ($url === null) {
35
-			return null;
36
-		}
37
-
38
-		// ICS feeds hosted on O365 can return HTTP 500 when the UA string isn't satisfactory
39
-		// Ref https://github.com/nextcloud/calendar/issues/7234
40
-		$uaString = 'Nextcloud Webcal Service';
41
-		if (parse_url($url, PHP_URL_HOST) === 'outlook.office365.com') {
42
-			// The required format/values here are not documented.
43
-			// Instead, this string based on research.
44
-			// Ref https://github.com/bitfireAT/icsx5/discussions/654#discussioncomment-14158051
45
-			$uaString = 'Nextcloud (Linux) Chrome/66';
46
-		}
47
-
48
-		$allowLocalAccess = $this->config->getValueString('dav', 'webcalAllowLocalAccess', 'no');
49
-
50
-		$params = [
51
-			'nextcloud' => [
52
-				'allow_local_address' => $allowLocalAccess === 'yes',
53
-			],
54
-			RequestOptions::HEADERS => [
55
-				'User-Agent' => $uaString,
56
-				'Accept' => 'text/calendar, application/calendar+json, application/calendar+xml',
57
-			],
58
-			'stream' => true,
59
-		];
60
-
61
-		$user = parse_url($subscription['source'], PHP_URL_USER);
62
-		$pass = parse_url($subscription['source'], PHP_URL_PASS);
63
-		if ($user !== null && $pass !== null) {
64
-			$params[RequestOptions::AUTH] = [$user, $pass];
65
-		}
66
-
67
-		try {
68
-			$client = $this->clientService->newClient();
69
-			$response = $client->get($url, $params);
70
-		} catch (LocalServerException $ex) {
71
-			$this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [
72
-				'exception' => $ex,
73
-			]);
74
-			return null;
75
-		} catch (Exception $ex) {
76
-			$this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [
77
-				'exception' => $ex,
78
-			]);
79
-			return null;
80
-		}
81
-
82
-		$contentType = $response->getHeader('Content-Type');
83
-		$contentType = explode(';', $contentType, 2)[0];
84
-
85
-		$format = match ($contentType) {
86
-			'application/calendar+json' => 'jcal',
87
-			'application/calendar+xml' => 'xcal',
88
-			default => 'ical',
89
-		};
90
-
91
-		// With 'stream' => true, getBody() returns the underlying stream resource
92
-		$stream = $response->getBody();
93
-		if (!is_resource($stream)) {
94
-			return null;
95
-		}
96
-
97
-		return ['data' => $stream, 'format' => $format];
98
-	}
99
-
100
-	/**
101
-	 * This method will strip authentication information and replace the
102
-	 * 'webcal' or 'webcals' protocol scheme
103
-	 *
104
-	 * @param string $url
105
-	 * @return string|null
106
-	 */
107
-	private function cleanURL(string $url): ?string {
108
-		$parsed = parse_url($url);
109
-		if ($parsed === false) {
110
-			return null;
111
-		}
112
-
113
-		if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
114
-			$scheme = 'http';
115
-		} else {
116
-			$scheme = 'https';
117
-		}
118
-
119
-		$host = $parsed['host'] ?? '';
120
-		$port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
121
-		$path = $parsed['path'] ?? '';
122
-		$query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
123
-		$fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
124
-
125
-		$cleanURL = "$scheme://$host$port$path$query$fragment";
126
-		// parse_url is giving some weird results if no url and no :// is given,
127
-		// so let's test the url again
128
-		$parsedClean = parse_url($cleanURL);
129
-		if ($parsedClean === false || !isset($parsedClean['host'])) {
130
-			return null;
131
-		}
132
-
133
-		return $cleanURL;
134
-	}
19
+    public function __construct(
20
+        private IClientService $clientService,
21
+        private IAppConfig $config,
22
+        private LoggerInterface $logger,
23
+    ) {
24
+    }
25
+
26
+    /**
27
+     * gets webcal feed from remote server
28
+     *
29
+     * @return array{data: resource, format: string}|null
30
+     */
31
+    public function queryWebcalFeed(array $subscription): ?array {
32
+        $subscriptionId = $subscription['id'];
33
+        $url = $this->cleanURL($subscription['source']);
34
+        if ($url === null) {
35
+            return null;
36
+        }
37
+
38
+        // ICS feeds hosted on O365 can return HTTP 500 when the UA string isn't satisfactory
39
+        // Ref https://github.com/nextcloud/calendar/issues/7234
40
+        $uaString = 'Nextcloud Webcal Service';
41
+        if (parse_url($url, PHP_URL_HOST) === 'outlook.office365.com') {
42
+            // The required format/values here are not documented.
43
+            // Instead, this string based on research.
44
+            // Ref https://github.com/bitfireAT/icsx5/discussions/654#discussioncomment-14158051
45
+            $uaString = 'Nextcloud (Linux) Chrome/66';
46
+        }
47
+
48
+        $allowLocalAccess = $this->config->getValueString('dav', 'webcalAllowLocalAccess', 'no');
49
+
50
+        $params = [
51
+            'nextcloud' => [
52
+                'allow_local_address' => $allowLocalAccess === 'yes',
53
+            ],
54
+            RequestOptions::HEADERS => [
55
+                'User-Agent' => $uaString,
56
+                'Accept' => 'text/calendar, application/calendar+json, application/calendar+xml',
57
+            ],
58
+            'stream' => true,
59
+        ];
60
+
61
+        $user = parse_url($subscription['source'], PHP_URL_USER);
62
+        $pass = parse_url($subscription['source'], PHP_URL_PASS);
63
+        if ($user !== null && $pass !== null) {
64
+            $params[RequestOptions::AUTH] = [$user, $pass];
65
+        }
66
+
67
+        try {
68
+            $client = $this->clientService->newClient();
69
+            $response = $client->get($url, $params);
70
+        } catch (LocalServerException $ex) {
71
+            $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [
72
+                'exception' => $ex,
73
+            ]);
74
+            return null;
75
+        } catch (Exception $ex) {
76
+            $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [
77
+                'exception' => $ex,
78
+            ]);
79
+            return null;
80
+        }
81
+
82
+        $contentType = $response->getHeader('Content-Type');
83
+        $contentType = explode(';', $contentType, 2)[0];
84
+
85
+        $format = match ($contentType) {
86
+            'application/calendar+json' => 'jcal',
87
+            'application/calendar+xml' => 'xcal',
88
+            default => 'ical',
89
+        };
90
+
91
+        // With 'stream' => true, getBody() returns the underlying stream resource
92
+        $stream = $response->getBody();
93
+        if (!is_resource($stream)) {
94
+            return null;
95
+        }
96
+
97
+        return ['data' => $stream, 'format' => $format];
98
+    }
99
+
100
+    /**
101
+     * This method will strip authentication information and replace the
102
+     * 'webcal' or 'webcals' protocol scheme
103
+     *
104
+     * @param string $url
105
+     * @return string|null
106
+     */
107
+    private function cleanURL(string $url): ?string {
108
+        $parsed = parse_url($url);
109
+        if ($parsed === false) {
110
+            return null;
111
+        }
112
+
113
+        if (isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
114
+            $scheme = 'http';
115
+        } else {
116
+            $scheme = 'https';
117
+        }
118
+
119
+        $host = $parsed['host'] ?? '';
120
+        $port = isset($parsed['port']) ? ':' . $parsed['port'] : '';
121
+        $path = $parsed['path'] ?? '';
122
+        $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
123
+        $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
124
+
125
+        $cleanURL = "$scheme://$host$port$path$query$fragment";
126
+        // parse_url is giving some weird results if no url and no :// is given,
127
+        // so let's test the url again
128
+        $parsedClean = parse_url($cleanURL);
129
+        if ($parsedClean === false || !isset($parsedClean['host'])) {
130
+            return null;
131
+        }
132
+
133
+        return $cleanURL;
134
+    }
135 135
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php 2 patches
Indentation   +469 added lines, -469 removed lines patch added patch discarded remove patch
@@ -21,473 +21,473 @@
 block discarded – undo
21 21
 use Test\TestCase;
22 22
 
23 23
 class RefreshWebcalServiceTest extends TestCase {
24
-	private CalDavBackend&MockObject $caldavBackend;
25
-	private Connection&MockObject $connection;
26
-	private LoggerInterface&MockObject $logger;
27
-	private ImportService&MockObject $importService;
28
-	private ITimeFactory&MockObject $timeFactory;
29
-
30
-	protected function setUp(): void {
31
-		parent::setUp();
32
-
33
-		$this->caldavBackend = $this->createMock(CalDavBackend::class);
34
-		$this->connection = $this->createMock(Connection::class);
35
-		$this->logger = $this->createMock(LoggerInterface::class);
36
-		$this->importService = $this->createMock(ImportService::class);
37
-		$this->timeFactory = $this->createMock(ITimeFactory::class);
38
-		// Default time factory behavior: current time is far in the future so refresh always happens
39
-		$this->timeFactory->method('getTime')->willReturn(PHP_INT_MAX);
40
-		$this->timeFactory->method('getDateTime')->willReturn(new \DateTime());
41
-	}
42
-
43
-	/**
44
-	 * Helper to create a resource stream from string content
45
-	 */
46
-	private function createStreamFromString(string $content) {
47
-		$stream = fopen('php://temp', 'r+');
48
-		fwrite($stream, $content);
49
-		rewind($stream);
50
-		return $stream;
51
-	}
52
-
53
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
54
-	public function testRun(string $body, string $format, string $result): void {
55
-		$refreshWebcalService = new RefreshWebcalService(
56
-			$this->caldavBackend,
57
-			$this->logger,
58
-			$this->connection,
59
-			$this->timeFactory,
60
-			$this->importService
61
-		);
62
-
63
-		$this->caldavBackend->expects(self::once())
64
-			->method('getSubscriptionsForUser')
65
-			->with('principals/users/testuser')
66
-			->willReturn([
67
-				[
68
-					'id' => '99',
69
-					'uri' => 'sub456',
70
-					RefreshWebcalService::REFRESH_RATE => 'P1D',
71
-					RefreshWebcalService::STRIP_TODOS => '1',
72
-					RefreshWebcalService::STRIP_ALARMS => '1',
73
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
74
-					'source' => 'webcal://foo.bar/bla',
75
-					'lastmodified' => 0,
76
-				],
77
-				[
78
-					'id' => '42',
79
-					'uri' => 'sub123',
80
-					RefreshWebcalService::REFRESH_RATE => 'PT1H',
81
-					RefreshWebcalService::STRIP_TODOS => '1',
82
-					RefreshWebcalService::STRIP_ALARMS => '1',
83
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
84
-					'source' => 'webcal://foo.bar/bla2',
85
-					'lastmodified' => 0,
86
-				],
87
-			]);
88
-
89
-		$stream = $this->createStreamFromString($body);
90
-
91
-		$this->connection->expects(self::once())
92
-			->method('queryWebcalFeed')
93
-			->willReturn(['data' => $stream, 'format' => $format]);
94
-
95
-		$this->caldavBackend->expects(self::once())
96
-			->method('getLimitedCalendarObjects')
97
-			->willReturn([]);
98
-
99
-		// Create a VCalendar object that will be yielded by the import service
100
-		$vCalendar = VObject\Reader::read($result);
101
-
102
-		$generator = function () use ($vCalendar) {
103
-			yield $vCalendar;
104
-		};
105
-
106
-		$this->importService->expects(self::once())
107
-			->method('importText')
108
-			->willReturn($generator());
109
-
110
-		$this->caldavBackend->expects(self::once())
111
-			->method('createCalendarObject')
112
-			->with(
113
-				'42',
114
-				self::matchesRegularExpression('/^[a-f0-9-]+\.ics$/'),
115
-				$result,
116
-				CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
117
-			);
118
-
119
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
120
-	}
121
-
122
-	#[\PHPUnit\Framework\Attributes\DataProvider('identicalDataProvider')]
123
-	public function testRunIdentical(string $uid, array $calendarObject, string $body, string $format, string $result): void {
124
-		$refreshWebcalService = new RefreshWebcalService(
125
-			$this->caldavBackend,
126
-			$this->logger,
127
-			$this->connection,
128
-			$this->timeFactory,
129
-			$this->importService
130
-		);
131
-
132
-		$this->caldavBackend->expects(self::once())
133
-			->method('getSubscriptionsForUser')
134
-			->with('principals/users/testuser')
135
-			->willReturn([
136
-				[
137
-					'id' => '99',
138
-					'uri' => 'sub456',
139
-					RefreshWebcalService::REFRESH_RATE => 'P1D',
140
-					RefreshWebcalService::STRIP_TODOS => '1',
141
-					RefreshWebcalService::STRIP_ALARMS => '1',
142
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
143
-					'source' => 'webcal://foo.bar/bla',
144
-					'lastmodified' => 0,
145
-				],
146
-				[
147
-					'id' => '42',
148
-					'uri' => 'sub123',
149
-					RefreshWebcalService::REFRESH_RATE => 'PT1H',
150
-					RefreshWebcalService::STRIP_TODOS => '1',
151
-					RefreshWebcalService::STRIP_ALARMS => '1',
152
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
153
-					'source' => 'webcal://foo.bar/bla2',
154
-					'lastmodified' => 0,
155
-				],
156
-			]);
157
-
158
-		$stream = $this->createStreamFromString($body);
159
-
160
-		$this->connection->expects(self::once())
161
-			->method('queryWebcalFeed')
162
-			->willReturn(['data' => $stream, 'format' => $format]);
163
-
164
-		$this->caldavBackend->expects(self::once())
165
-			->method('getLimitedCalendarObjects')
166
-			->willReturn($calendarObject);
167
-
168
-		// Create a VCalendar object that will be yielded by the import service
169
-		$vCalendar = VObject\Reader::read($result);
170
-
171
-		$generator = function () use ($vCalendar) {
172
-			yield $vCalendar;
173
-		};
174
-
175
-		$this->importService->expects(self::once())
176
-			->method('importText')
177
-			->willReturn($generator());
178
-
179
-		$this->caldavBackend->expects(self::never())
180
-			->method('createCalendarObject');
181
-
182
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
183
-	}
184
-
185
-	public function testSubscriptionNotFound(): void {
186
-		$refreshWebcalService = new RefreshWebcalService(
187
-			$this->caldavBackend,
188
-			$this->logger,
189
-			$this->connection,
190
-			$this->timeFactory,
191
-			$this->importService
192
-		);
193
-
194
-		$this->caldavBackend->expects(self::once())
195
-			->method('getSubscriptionsForUser')
196
-			->with('principals/users/testuser')
197
-			->willReturn([]);
198
-
199
-		$this->connection->expects(self::never())
200
-			->method('queryWebcalFeed');
201
-
202
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
203
-	}
204
-
205
-	public function testConnectionReturnsNull(): void {
206
-		$refreshWebcalService = new RefreshWebcalService(
207
-			$this->caldavBackend,
208
-			$this->logger,
209
-			$this->connection,
210
-			$this->timeFactory,
211
-			$this->importService
212
-		);
213
-
214
-		$this->caldavBackend->expects(self::once())
215
-			->method('getSubscriptionsForUser')
216
-			->with('principals/users/testuser')
217
-			->willReturn([
218
-				[
219
-					'id' => '42',
220
-					'uri' => 'sub123',
221
-					RefreshWebcalService::STRIP_TODOS => '1',
222
-					RefreshWebcalService::STRIP_ALARMS => '1',
223
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
224
-					'source' => 'webcal://foo.bar/bla2',
225
-					'lastmodified' => 0,
226
-				],
227
-			]);
228
-
229
-		$this->connection->expects(self::once())
230
-			->method('queryWebcalFeed')
231
-			->willReturn(null);
232
-
233
-		$this->importService->expects(self::never())
234
-			->method('importText');
235
-
236
-		$this->caldavBackend->expects(self::never())
237
-			->method('createCalendarObject');
238
-
239
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
240
-	}
241
-
242
-	public function testDeletedObjectsArePurged(): void {
243
-		$refreshWebcalService = new RefreshWebcalService(
244
-			$this->caldavBackend,
245
-			$this->logger,
246
-			$this->connection,
247
-			$this->timeFactory,
248
-			$this->importService
249
-		);
250
-
251
-		$this->caldavBackend->expects(self::once())
252
-			->method('getSubscriptionsForUser')
253
-			->with('principals/users/testuser')
254
-			->willReturn([
255
-				[
256
-					'id' => '42',
257
-					'uri' => 'sub123',
258
-					RefreshWebcalService::STRIP_TODOS => '1',
259
-					RefreshWebcalService::STRIP_ALARMS => '1',
260
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
261
-					'source' => 'webcal://foo.bar/bla2',
262
-					'lastmodified' => 0,
263
-				],
264
-			]);
265
-
266
-		$body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//Test//EN\r\nBEGIN:VEVENT\r\nUID:new-event\r\nDTSTAMP:20160218T133704Z\r\nDTSTART:20160218T133704Z\r\nSUMMARY:New Event\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
267
-		$stream = $this->createStreamFromString($body);
268
-
269
-		$this->connection->expects(self::once())
270
-			->method('queryWebcalFeed')
271
-			->willReturn(['data' => $stream, 'format' => 'ical']);
272
-
273
-		// Existing objects include one that won't be in the feed
274
-		$this->caldavBackend->expects(self::once())
275
-			->method('getLimitedCalendarObjects')
276
-			->willReturn([
277
-				'old-deleted-event' => [
278
-					'id' => 99,
279
-					'uid' => 'old-deleted-event',
280
-					'etag' => 'old-etag',
281
-					'uri' => 'old-event.ics',
282
-				],
283
-			]);
284
-
285
-		$vCalendar = VObject\Reader::read($body);
286
-		$generator = function () use ($vCalendar) {
287
-			yield $vCalendar;
288
-		};
289
-
290
-		$this->importService->expects(self::once())
291
-			->method('importText')
292
-			->willReturn($generator());
293
-
294
-		$this->caldavBackend->expects(self::once())
295
-			->method('createCalendarObject');
296
-
297
-		$this->caldavBackend->expects(self::once())
298
-			->method('purgeCachedEventsForSubscription')
299
-			->with(42, [99], ['old-event.ics']);
300
-
301
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
302
-	}
303
-
304
-	public function testLongUidIsSkipped(): void {
305
-		$refreshWebcalService = new RefreshWebcalService(
306
-			$this->caldavBackend,
307
-			$this->logger,
308
-			$this->connection,
309
-			$this->timeFactory,
310
-			$this->importService
311
-		);
312
-
313
-		$this->caldavBackend->expects(self::once())
314
-			->method('getSubscriptionsForUser')
315
-			->with('principals/users/testuser')
316
-			->willReturn([
317
-				[
318
-					'id' => '42',
319
-					'uri' => 'sub123',
320
-					RefreshWebcalService::STRIP_TODOS => '1',
321
-					RefreshWebcalService::STRIP_ALARMS => '1',
322
-					RefreshWebcalService::STRIP_ATTACHMENTS => '1',
323
-					'source' => 'webcal://foo.bar/bla2',
324
-					'lastmodified' => 0,
325
-				],
326
-			]);
327
-
328
-		// Create a UID that is longer than 512 characters
329
-		$longUid = str_repeat('a', 513);
330
-		$body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//Test//EN\r\nBEGIN:VEVENT\r\nUID:$longUid\r\nDTSTAMP:20160218T133704Z\r\nDTSTART:20160218T133704Z\r\nSUMMARY:Event with long UID\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
331
-		$stream = $this->createStreamFromString($body);
332
-
333
-		$this->connection->expects(self::once())
334
-			->method('queryWebcalFeed')
335
-			->willReturn(['data' => $stream, 'format' => 'ical']);
336
-
337
-		$this->caldavBackend->expects(self::once())
338
-			->method('getLimitedCalendarObjects')
339
-			->willReturn([]);
340
-
341
-		$vCalendar = VObject\Reader::read($body);
342
-		$generator = function () use ($vCalendar) {
343
-			yield $vCalendar;
344
-		};
345
-
346
-		$this->importService->expects(self::once())
347
-			->method('importText')
348
-			->willReturn($generator());
349
-
350
-		// Event with long UID should be skipped, so createCalendarObject should never be called
351
-		$this->caldavBackend->expects(self::never())
352
-			->method('createCalendarObject');
353
-
354
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
355
-	}
356
-
357
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
358
-	public function testRunCreateCalendarNoException(string $body, string $format, string $result): void {
359
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
360
-			->onlyMethods(['getSubscription'])
361
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->timeFactory, $this->importService])
362
-			->getMock();
363
-
364
-		$refreshWebcalService
365
-			->method('getSubscription')
366
-			->willReturn([
367
-				'id' => '42',
368
-				'uri' => 'sub123',
369
-				RefreshWebcalService::REFRESH_RATE => 'PT1H',
370
-				RefreshWebcalService::STRIP_TODOS => '1',
371
-				RefreshWebcalService::STRIP_ALARMS => '1',
372
-				RefreshWebcalService::STRIP_ATTACHMENTS => '1',
373
-				'source' => 'webcal://foo.bar/bla2',
374
-				'lastmodified' => 0,
375
-			]);
376
-
377
-		$stream = $this->createStreamFromString($body);
378
-
379
-		$this->connection->expects(self::once())
380
-			->method('queryWebcalFeed')
381
-			->willReturn(['data' => $stream, 'format' => $format]);
382
-
383
-		$this->caldavBackend->expects(self::once())
384
-			->method('getLimitedCalendarObjects')
385
-			->willReturn([]);
386
-
387
-		// Create a VCalendar object that will be yielded by the import service
388
-		$vCalendar = VObject\Reader::read($result);
389
-
390
-		$generator = function () use ($vCalendar) {
391
-			yield $vCalendar;
392
-		};
393
-
394
-		$this->importService->expects(self::once())
395
-			->method('importText')
396
-			->willReturn($generator());
397
-
398
-		$noInstanceException = new NoInstancesException("can't add calendar object");
399
-		$this->caldavBackend->expects(self::once())
400
-			->method('createCalendarObject')
401
-			->willThrowException($noInstanceException);
402
-
403
-		$this->logger->expects(self::once())
404
-			->method('warning')
405
-			->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $noInstanceException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
406
-
407
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
408
-	}
409
-
410
-	#[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
411
-	public function testRunCreateCalendarBadRequest(string $body, string $format, string $result): void {
412
-		$refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
413
-			->onlyMethods(['getSubscription'])
414
-			->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->timeFactory, $this->importService])
415
-			->getMock();
416
-
417
-		$refreshWebcalService
418
-			->method('getSubscription')
419
-			->willReturn([
420
-				'id' => '42',
421
-				'uri' => 'sub123',
422
-				RefreshWebcalService::REFRESH_RATE => 'PT1H',
423
-				RefreshWebcalService::STRIP_TODOS => '1',
424
-				RefreshWebcalService::STRIP_ALARMS => '1',
425
-				RefreshWebcalService::STRIP_ATTACHMENTS => '1',
426
-				'source' => 'webcal://foo.bar/bla2',
427
-				'lastmodified' => 0,
428
-			]);
429
-
430
-		$stream = $this->createStreamFromString($body);
431
-
432
-		$this->connection->expects(self::once())
433
-			->method('queryWebcalFeed')
434
-			->willReturn(['data' => $stream, 'format' => $format]);
435
-
436
-		$this->caldavBackend->expects(self::once())
437
-			->method('getLimitedCalendarObjects')
438
-			->willReturn([]);
439
-
440
-		// Create a VCalendar object that will be yielded by the import service
441
-		$vCalendar = VObject\Reader::read($result);
442
-
443
-		$generator = function () use ($vCalendar) {
444
-			yield $vCalendar;
445
-		};
446
-
447
-		$this->importService->expects(self::once())
448
-			->method('importText')
449
-			->willReturn($generator());
450
-
451
-		$badRequestException = new BadRequest("can't add reach calendar url");
452
-		$this->caldavBackend->expects(self::once())
453
-			->method('createCalendarObject')
454
-			->willThrowException($badRequestException);
455
-
456
-		$this->logger->expects(self::once())
457
-			->method('warning')
458
-			->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $badRequestException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
459
-
460
-		$refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
461
-	}
462
-
463
-	public static function identicalDataProvider(): array {
464
-		$icalBody = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
465
-		$etag = md5($icalBody);
466
-
467
-		return [
468
-			[
469
-				'12345',
470
-				[
471
-					'12345' => [
472
-						'id' => 42,
473
-						'etag' => $etag,
474
-						'uri' => 'sub456.ics',
475
-					],
476
-				],
477
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
478
-				'ical',
479
-				$icalBody,
480
-			],
481
-		];
482
-	}
483
-
484
-	public static function runDataProvider(): array {
485
-		return [
486
-			[
487
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
488
-				'ical',
489
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
490
-			],
491
-		];
492
-	}
24
+    private CalDavBackend&MockObject $caldavBackend;
25
+    private Connection&MockObject $connection;
26
+    private LoggerInterface&MockObject $logger;
27
+    private ImportService&MockObject $importService;
28
+    private ITimeFactory&MockObject $timeFactory;
29
+
30
+    protected function setUp(): void {
31
+        parent::setUp();
32
+
33
+        $this->caldavBackend = $this->createMock(CalDavBackend::class);
34
+        $this->connection = $this->createMock(Connection::class);
35
+        $this->logger = $this->createMock(LoggerInterface::class);
36
+        $this->importService = $this->createMock(ImportService::class);
37
+        $this->timeFactory = $this->createMock(ITimeFactory::class);
38
+        // Default time factory behavior: current time is far in the future so refresh always happens
39
+        $this->timeFactory->method('getTime')->willReturn(PHP_INT_MAX);
40
+        $this->timeFactory->method('getDateTime')->willReturn(new \DateTime());
41
+    }
42
+
43
+    /**
44
+     * Helper to create a resource stream from string content
45
+     */
46
+    private function createStreamFromString(string $content) {
47
+        $stream = fopen('php://temp', 'r+');
48
+        fwrite($stream, $content);
49
+        rewind($stream);
50
+        return $stream;
51
+    }
52
+
53
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
54
+    public function testRun(string $body, string $format, string $result): void {
55
+        $refreshWebcalService = new RefreshWebcalService(
56
+            $this->caldavBackend,
57
+            $this->logger,
58
+            $this->connection,
59
+            $this->timeFactory,
60
+            $this->importService
61
+        );
62
+
63
+        $this->caldavBackend->expects(self::once())
64
+            ->method('getSubscriptionsForUser')
65
+            ->with('principals/users/testuser')
66
+            ->willReturn([
67
+                [
68
+                    'id' => '99',
69
+                    'uri' => 'sub456',
70
+                    RefreshWebcalService::REFRESH_RATE => 'P1D',
71
+                    RefreshWebcalService::STRIP_TODOS => '1',
72
+                    RefreshWebcalService::STRIP_ALARMS => '1',
73
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
74
+                    'source' => 'webcal://foo.bar/bla',
75
+                    'lastmodified' => 0,
76
+                ],
77
+                [
78
+                    'id' => '42',
79
+                    'uri' => 'sub123',
80
+                    RefreshWebcalService::REFRESH_RATE => 'PT1H',
81
+                    RefreshWebcalService::STRIP_TODOS => '1',
82
+                    RefreshWebcalService::STRIP_ALARMS => '1',
83
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
84
+                    'source' => 'webcal://foo.bar/bla2',
85
+                    'lastmodified' => 0,
86
+                ],
87
+            ]);
88
+
89
+        $stream = $this->createStreamFromString($body);
90
+
91
+        $this->connection->expects(self::once())
92
+            ->method('queryWebcalFeed')
93
+            ->willReturn(['data' => $stream, 'format' => $format]);
94
+
95
+        $this->caldavBackend->expects(self::once())
96
+            ->method('getLimitedCalendarObjects')
97
+            ->willReturn([]);
98
+
99
+        // Create a VCalendar object that will be yielded by the import service
100
+        $vCalendar = VObject\Reader::read($result);
101
+
102
+        $generator = function () use ($vCalendar) {
103
+            yield $vCalendar;
104
+        };
105
+
106
+        $this->importService->expects(self::once())
107
+            ->method('importText')
108
+            ->willReturn($generator());
109
+
110
+        $this->caldavBackend->expects(self::once())
111
+            ->method('createCalendarObject')
112
+            ->with(
113
+                '42',
114
+                self::matchesRegularExpression('/^[a-f0-9-]+\.ics$/'),
115
+                $result,
116
+                CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION
117
+            );
118
+
119
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
120
+    }
121
+
122
+    #[\PHPUnit\Framework\Attributes\DataProvider('identicalDataProvider')]
123
+    public function testRunIdentical(string $uid, array $calendarObject, string $body, string $format, string $result): void {
124
+        $refreshWebcalService = new RefreshWebcalService(
125
+            $this->caldavBackend,
126
+            $this->logger,
127
+            $this->connection,
128
+            $this->timeFactory,
129
+            $this->importService
130
+        );
131
+
132
+        $this->caldavBackend->expects(self::once())
133
+            ->method('getSubscriptionsForUser')
134
+            ->with('principals/users/testuser')
135
+            ->willReturn([
136
+                [
137
+                    'id' => '99',
138
+                    'uri' => 'sub456',
139
+                    RefreshWebcalService::REFRESH_RATE => 'P1D',
140
+                    RefreshWebcalService::STRIP_TODOS => '1',
141
+                    RefreshWebcalService::STRIP_ALARMS => '1',
142
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
143
+                    'source' => 'webcal://foo.bar/bla',
144
+                    'lastmodified' => 0,
145
+                ],
146
+                [
147
+                    'id' => '42',
148
+                    'uri' => 'sub123',
149
+                    RefreshWebcalService::REFRESH_RATE => 'PT1H',
150
+                    RefreshWebcalService::STRIP_TODOS => '1',
151
+                    RefreshWebcalService::STRIP_ALARMS => '1',
152
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
153
+                    'source' => 'webcal://foo.bar/bla2',
154
+                    'lastmodified' => 0,
155
+                ],
156
+            ]);
157
+
158
+        $stream = $this->createStreamFromString($body);
159
+
160
+        $this->connection->expects(self::once())
161
+            ->method('queryWebcalFeed')
162
+            ->willReturn(['data' => $stream, 'format' => $format]);
163
+
164
+        $this->caldavBackend->expects(self::once())
165
+            ->method('getLimitedCalendarObjects')
166
+            ->willReturn($calendarObject);
167
+
168
+        // Create a VCalendar object that will be yielded by the import service
169
+        $vCalendar = VObject\Reader::read($result);
170
+
171
+        $generator = function () use ($vCalendar) {
172
+            yield $vCalendar;
173
+        };
174
+
175
+        $this->importService->expects(self::once())
176
+            ->method('importText')
177
+            ->willReturn($generator());
178
+
179
+        $this->caldavBackend->expects(self::never())
180
+            ->method('createCalendarObject');
181
+
182
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
183
+    }
184
+
185
+    public function testSubscriptionNotFound(): void {
186
+        $refreshWebcalService = new RefreshWebcalService(
187
+            $this->caldavBackend,
188
+            $this->logger,
189
+            $this->connection,
190
+            $this->timeFactory,
191
+            $this->importService
192
+        );
193
+
194
+        $this->caldavBackend->expects(self::once())
195
+            ->method('getSubscriptionsForUser')
196
+            ->with('principals/users/testuser')
197
+            ->willReturn([]);
198
+
199
+        $this->connection->expects(self::never())
200
+            ->method('queryWebcalFeed');
201
+
202
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
203
+    }
204
+
205
+    public function testConnectionReturnsNull(): void {
206
+        $refreshWebcalService = new RefreshWebcalService(
207
+            $this->caldavBackend,
208
+            $this->logger,
209
+            $this->connection,
210
+            $this->timeFactory,
211
+            $this->importService
212
+        );
213
+
214
+        $this->caldavBackend->expects(self::once())
215
+            ->method('getSubscriptionsForUser')
216
+            ->with('principals/users/testuser')
217
+            ->willReturn([
218
+                [
219
+                    'id' => '42',
220
+                    'uri' => 'sub123',
221
+                    RefreshWebcalService::STRIP_TODOS => '1',
222
+                    RefreshWebcalService::STRIP_ALARMS => '1',
223
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
224
+                    'source' => 'webcal://foo.bar/bla2',
225
+                    'lastmodified' => 0,
226
+                ],
227
+            ]);
228
+
229
+        $this->connection->expects(self::once())
230
+            ->method('queryWebcalFeed')
231
+            ->willReturn(null);
232
+
233
+        $this->importService->expects(self::never())
234
+            ->method('importText');
235
+
236
+        $this->caldavBackend->expects(self::never())
237
+            ->method('createCalendarObject');
238
+
239
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
240
+    }
241
+
242
+    public function testDeletedObjectsArePurged(): void {
243
+        $refreshWebcalService = new RefreshWebcalService(
244
+            $this->caldavBackend,
245
+            $this->logger,
246
+            $this->connection,
247
+            $this->timeFactory,
248
+            $this->importService
249
+        );
250
+
251
+        $this->caldavBackend->expects(self::once())
252
+            ->method('getSubscriptionsForUser')
253
+            ->with('principals/users/testuser')
254
+            ->willReturn([
255
+                [
256
+                    'id' => '42',
257
+                    'uri' => 'sub123',
258
+                    RefreshWebcalService::STRIP_TODOS => '1',
259
+                    RefreshWebcalService::STRIP_ALARMS => '1',
260
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
261
+                    'source' => 'webcal://foo.bar/bla2',
262
+                    'lastmodified' => 0,
263
+                ],
264
+            ]);
265
+
266
+        $body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//Test//EN\r\nBEGIN:VEVENT\r\nUID:new-event\r\nDTSTAMP:20160218T133704Z\r\nDTSTART:20160218T133704Z\r\nSUMMARY:New Event\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
267
+        $stream = $this->createStreamFromString($body);
268
+
269
+        $this->connection->expects(self::once())
270
+            ->method('queryWebcalFeed')
271
+            ->willReturn(['data' => $stream, 'format' => 'ical']);
272
+
273
+        // Existing objects include one that won't be in the feed
274
+        $this->caldavBackend->expects(self::once())
275
+            ->method('getLimitedCalendarObjects')
276
+            ->willReturn([
277
+                'old-deleted-event' => [
278
+                    'id' => 99,
279
+                    'uid' => 'old-deleted-event',
280
+                    'etag' => 'old-etag',
281
+                    'uri' => 'old-event.ics',
282
+                ],
283
+            ]);
284
+
285
+        $vCalendar = VObject\Reader::read($body);
286
+        $generator = function () use ($vCalendar) {
287
+            yield $vCalendar;
288
+        };
289
+
290
+        $this->importService->expects(self::once())
291
+            ->method('importText')
292
+            ->willReturn($generator());
293
+
294
+        $this->caldavBackend->expects(self::once())
295
+            ->method('createCalendarObject');
296
+
297
+        $this->caldavBackend->expects(self::once())
298
+            ->method('purgeCachedEventsForSubscription')
299
+            ->with(42, [99], ['old-event.ics']);
300
+
301
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
302
+    }
303
+
304
+    public function testLongUidIsSkipped(): void {
305
+        $refreshWebcalService = new RefreshWebcalService(
306
+            $this->caldavBackend,
307
+            $this->logger,
308
+            $this->connection,
309
+            $this->timeFactory,
310
+            $this->importService
311
+        );
312
+
313
+        $this->caldavBackend->expects(self::once())
314
+            ->method('getSubscriptionsForUser')
315
+            ->with('principals/users/testuser')
316
+            ->willReturn([
317
+                [
318
+                    'id' => '42',
319
+                    'uri' => 'sub123',
320
+                    RefreshWebcalService::STRIP_TODOS => '1',
321
+                    RefreshWebcalService::STRIP_ALARMS => '1',
322
+                    RefreshWebcalService::STRIP_ATTACHMENTS => '1',
323
+                    'source' => 'webcal://foo.bar/bla2',
324
+                    'lastmodified' => 0,
325
+                ],
326
+            ]);
327
+
328
+        // Create a UID that is longer than 512 characters
329
+        $longUid = str_repeat('a', 513);
330
+        $body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Test//Test//EN\r\nBEGIN:VEVENT\r\nUID:$longUid\r\nDTSTAMP:20160218T133704Z\r\nDTSTART:20160218T133704Z\r\nSUMMARY:Event with long UID\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
331
+        $stream = $this->createStreamFromString($body);
332
+
333
+        $this->connection->expects(self::once())
334
+            ->method('queryWebcalFeed')
335
+            ->willReturn(['data' => $stream, 'format' => 'ical']);
336
+
337
+        $this->caldavBackend->expects(self::once())
338
+            ->method('getLimitedCalendarObjects')
339
+            ->willReturn([]);
340
+
341
+        $vCalendar = VObject\Reader::read($body);
342
+        $generator = function () use ($vCalendar) {
343
+            yield $vCalendar;
344
+        };
345
+
346
+        $this->importService->expects(self::once())
347
+            ->method('importText')
348
+            ->willReturn($generator());
349
+
350
+        // Event with long UID should be skipped, so createCalendarObject should never be called
351
+        $this->caldavBackend->expects(self::never())
352
+            ->method('createCalendarObject');
353
+
354
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
355
+    }
356
+
357
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
358
+    public function testRunCreateCalendarNoException(string $body, string $format, string $result): void {
359
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
360
+            ->onlyMethods(['getSubscription'])
361
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->timeFactory, $this->importService])
362
+            ->getMock();
363
+
364
+        $refreshWebcalService
365
+            ->method('getSubscription')
366
+            ->willReturn([
367
+                'id' => '42',
368
+                'uri' => 'sub123',
369
+                RefreshWebcalService::REFRESH_RATE => 'PT1H',
370
+                RefreshWebcalService::STRIP_TODOS => '1',
371
+                RefreshWebcalService::STRIP_ALARMS => '1',
372
+                RefreshWebcalService::STRIP_ATTACHMENTS => '1',
373
+                'source' => 'webcal://foo.bar/bla2',
374
+                'lastmodified' => 0,
375
+            ]);
376
+
377
+        $stream = $this->createStreamFromString($body);
378
+
379
+        $this->connection->expects(self::once())
380
+            ->method('queryWebcalFeed')
381
+            ->willReturn(['data' => $stream, 'format' => $format]);
382
+
383
+        $this->caldavBackend->expects(self::once())
384
+            ->method('getLimitedCalendarObjects')
385
+            ->willReturn([]);
386
+
387
+        // Create a VCalendar object that will be yielded by the import service
388
+        $vCalendar = VObject\Reader::read($result);
389
+
390
+        $generator = function () use ($vCalendar) {
391
+            yield $vCalendar;
392
+        };
393
+
394
+        $this->importService->expects(self::once())
395
+            ->method('importText')
396
+            ->willReturn($generator());
397
+
398
+        $noInstanceException = new NoInstancesException("can't add calendar object");
399
+        $this->caldavBackend->expects(self::once())
400
+            ->method('createCalendarObject')
401
+            ->willThrowException($noInstanceException);
402
+
403
+        $this->logger->expects(self::once())
404
+            ->method('warning')
405
+            ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $noInstanceException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
406
+
407
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
408
+    }
409
+
410
+    #[\PHPUnit\Framework\Attributes\DataProvider('runDataProvider')]
411
+    public function testRunCreateCalendarBadRequest(string $body, string $format, string $result): void {
412
+        $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class)
413
+            ->onlyMethods(['getSubscription'])
414
+            ->setConstructorArgs([$this->caldavBackend, $this->logger, $this->connection, $this->timeFactory, $this->importService])
415
+            ->getMock();
416
+
417
+        $refreshWebcalService
418
+            ->method('getSubscription')
419
+            ->willReturn([
420
+                'id' => '42',
421
+                'uri' => 'sub123',
422
+                RefreshWebcalService::REFRESH_RATE => 'PT1H',
423
+                RefreshWebcalService::STRIP_TODOS => '1',
424
+                RefreshWebcalService::STRIP_ALARMS => '1',
425
+                RefreshWebcalService::STRIP_ATTACHMENTS => '1',
426
+                'source' => 'webcal://foo.bar/bla2',
427
+                'lastmodified' => 0,
428
+            ]);
429
+
430
+        $stream = $this->createStreamFromString($body);
431
+
432
+        $this->connection->expects(self::once())
433
+            ->method('queryWebcalFeed')
434
+            ->willReturn(['data' => $stream, 'format' => $format]);
435
+
436
+        $this->caldavBackend->expects(self::once())
437
+            ->method('getLimitedCalendarObjects')
438
+            ->willReturn([]);
439
+
440
+        // Create a VCalendar object that will be yielded by the import service
441
+        $vCalendar = VObject\Reader::read($result);
442
+
443
+        $generator = function () use ($vCalendar) {
444
+            yield $vCalendar;
445
+        };
446
+
447
+        $this->importService->expects(self::once())
448
+            ->method('importText')
449
+            ->willReturn($generator());
450
+
451
+        $badRequestException = new BadRequest("can't add reach calendar url");
452
+        $this->caldavBackend->expects(self::once())
453
+            ->method('createCalendarObject')
454
+            ->willThrowException($badRequestException);
455
+
456
+        $this->logger->expects(self::once())
457
+            ->method('warning')
458
+            ->with('Unable to create calendar object from subscription {subscriptionId}', ['exception' => $badRequestException, 'subscriptionId' => '42', 'source' => 'webcal://foo.bar/bla2']);
459
+
460
+        $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123');
461
+    }
462
+
463
+    public static function identicalDataProvider(): array {
464
+        $icalBody = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
465
+        $etag = md5($icalBody);
466
+
467
+        return [
468
+            [
469
+                '12345',
470
+                [
471
+                    '12345' => [
472
+                        'id' => 42,
473
+                        'etag' => $etag,
474
+                        'uri' => 'sub456.ics',
475
+                    ],
476
+                ],
477
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
478
+                'ical',
479
+                $icalBody,
480
+            ],
481
+        ];
482
+    }
483
+
484
+    public static function runDataProvider(): array {
485
+        return [
486
+            [
487
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
488
+                'ical',
489
+                "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
490
+            ],
491
+        ];
492
+    }
493 493
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 		// Create a VCalendar object that will be yielded by the import service
100 100
 		$vCalendar = VObject\Reader::read($result);
101 101
 
102
-		$generator = function () use ($vCalendar) {
102
+		$generator = function() use ($vCalendar) {
103 103
 			yield $vCalendar;
104 104
 		};
105 105
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 		// Create a VCalendar object that will be yielded by the import service
169 169
 		$vCalendar = VObject\Reader::read($result);
170 170
 
171
-		$generator = function () use ($vCalendar) {
171
+		$generator = function() use ($vCalendar) {
172 172
 			yield $vCalendar;
173 173
 		};
174 174
 
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
 			]);
284 284
 
285 285
 		$vCalendar = VObject\Reader::read($body);
286
-		$generator = function () use ($vCalendar) {
286
+		$generator = function() use ($vCalendar) {
287 287
 			yield $vCalendar;
288 288
 		};
289 289
 
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 			->willReturn([]);
340 340
 
341 341
 		$vCalendar = VObject\Reader::read($body);
342
-		$generator = function () use ($vCalendar) {
342
+		$generator = function() use ($vCalendar) {
343 343
 			yield $vCalendar;
344 344
 		};
345 345
 
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
 		// Create a VCalendar object that will be yielded by the import service
388 388
 		$vCalendar = VObject\Reader::read($result);
389 389
 
390
-		$generator = function () use ($vCalendar) {
390
+		$generator = function() use ($vCalendar) {
391 391
 			yield $vCalendar;
392 392
 		};
393 393
 
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 		// Create a VCalendar object that will be yielded by the import service
441 441
 		$vCalendar = VObject\Reader::read($result);
442 442
 
443
-		$generator = function () use ($vCalendar) {
443
+		$generator = function() use ($vCalendar) {
444 444
 			yield $vCalendar;
445 445
 		};
446 446
 
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
 	}
462 462
 
463 463
 	public static function identicalDataProvider(): array {
464
-		$icalBody = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
464
+		$icalBody = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject ".VObject\Version::VERSION."//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";
465 465
 		$etag = md5($icalBody);
466 466
 
467 467
 		return [
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
 			[
487 487
 				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
488 488
 				'ical',
489
-				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject " . VObject\Version::VERSION . "//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
489
+				"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject ".VObject\Version::VERSION."//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n",
490 490
 			],
491 491
 		];
492 492
 	}
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/WebcalCaching/ConnectionTest.php 1 patch
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -20,201 +20,201 @@
 block discarded – undo
20 20
 
21 21
 class ConnectionTest extends TestCase {
22 22
 
23
-	private IClientService&MockObject $clientService;
24
-	private IAppConfig&MockObject $config;
25
-	private LoggerInterface&MockObject $logger;
26
-	private Connection $connection;
27
-
28
-	public function setUp(): void {
29
-		$this->clientService = $this->createMock(IClientService::class);
30
-		$this->config = $this->createMock(IAppConfig::class);
31
-		$this->logger = $this->createMock(LoggerInterface::class);
32
-		$this->connection = new Connection($this->clientService, $this->config, $this->logger);
33
-	}
34
-
35
-	#[\PHPUnit\Framework\Attributes\DataProvider('runLocalURLDataProvider')]
36
-	public function testLocalUrl($source): void {
37
-		$subscription = [
38
-			'id' => 42,
39
-			'uri' => 'sub123',
40
-			'refreshreate' => 'P1H',
41
-			'striptodos' => 1,
42
-			'stripalarms' => 1,
43
-			'stripattachments' => 1,
44
-			'source' => $source,
45
-			'lastmodified' => 0,
46
-		];
47
-
48
-		$client = $this->createMock(IClient::class);
49
-		$this->clientService->expects(self::once())
50
-			->method('newClient')
51
-			->with()
52
-			->willReturn($client);
53
-
54
-		$this->config->expects(self::once())
55
-			->method('getValueString')
56
-			->with('dav', 'webcalAllowLocalAccess', 'no')
57
-			->willReturn('no');
58
-
59
-		$localServerException = new LocalServerException();
60
-		$client->expects(self::once())
61
-			->method('get')
62
-			->willThrowException($localServerException);
63
-		$this->logger->expects(self::once())
64
-			->method('warning')
65
-			->with('Subscription 42 was not refreshed because it violates local access rules', ['exception' => $localServerException]);
66
-
67
-		$this->connection->queryWebcalFeed($subscription);
68
-	}
69
-
70
-	public function testInvalidUrl(): void {
71
-		$subscription = [
72
-			'id' => 42,
73
-			'uri' => 'sub123',
74
-			'refreshreate' => 'P1H',
75
-			'striptodos' => 1,
76
-			'stripalarms' => 1,
77
-			'stripattachments' => 1,
78
-			'source' => '!@#$',
79
-			'lastmodified' => 0,
80
-		];
81
-
82
-		$client = $this->createMock(IClient::class);
83
-		$this->config->expects(self::never())
84
-			->method('getValueString');
85
-		$client->expects(self::never())
86
-			->method('get');
87
-
88
-		$this->connection->queryWebcalFeed($subscription);
89
-
90
-	}
91
-
92
-	#[\PHPUnit\Framework\Attributes\DataProvider('urlDataProvider')]
93
-	public function testConnection(string $url, string $contentType, string $expectedFormat): void {
94
-		$client = $this->createMock(IClient::class);
95
-		$response = $this->createMock(IResponse::class);
96
-		$subscription = [
97
-			'id' => 42,
98
-			'uri' => 'sub123',
99
-			'refreshreate' => 'P1H',
100
-			'striptodos' => 1,
101
-			'stripalarms' => 1,
102
-			'stripattachments' => 1,
103
-			'source' => $url,
104
-			'lastmodified' => 0,
105
-		];
106
-
107
-		$this->clientService->expects($this->once())
108
-			->method('newClient')
109
-			->with()
110
-			->willReturn($client);
111
-
112
-		$this->config->expects($this->once())
113
-			->method('getValueString')
114
-			->with('dav', 'webcalAllowLocalAccess', 'no')
115
-			->willReturn('no');
116
-
117
-		$client->expects($this->once())
118
-			->method('get')
119
-			->with('https://foo.bar/bla2')
120
-			->willReturn($response);
121
-
122
-		$response->expects($this->once())
123
-			->method('getHeader')
124
-			->with('Content-Type')
125
-			->willReturn($contentType);
126
-
127
-		// Create a stream resource to simulate streaming response
128
-		$stream = fopen('php://temp', 'r+');
129
-		fwrite($stream, 'test calendar data');
130
-		rewind($stream);
131
-
132
-		$response->expects($this->once())
133
-			->method('getBody')
134
-			->willReturn($stream);
135
-
136
-		$output = $this->connection->queryWebcalFeed($subscription);
137
-
138
-		$this->assertIsArray($output);
139
-		$this->assertArrayHasKey('data', $output);
140
-		$this->assertArrayHasKey('format', $output);
141
-		$this->assertIsResource($output['data']);
142
-		$this->assertEquals($expectedFormat, $output['format']);
143
-
144
-		// Cleanup
145
-		if (is_resource($output['data'])) {
146
-			fclose($output['data']);
147
-		}
148
-	}
149
-
150
-	public function testConnectionReturnsNullWhenBodyIsNotResource(): void {
151
-		$client = $this->createMock(IClient::class);
152
-		$response = $this->createMock(IResponse::class);
153
-		$subscription = [
154
-			'id' => 42,
155
-			'uri' => 'sub123',
156
-			'refreshreate' => 'P1H',
157
-			'striptodos' => 1,
158
-			'stripalarms' => 1,
159
-			'stripattachments' => 1,
160
-			'source' => 'https://foo.bar/bla2',
161
-			'lastmodified' => 0,
162
-		];
163
-
164
-		$this->clientService->expects($this->once())
165
-			->method('newClient')
166
-			->with()
167
-			->willReturn($client);
168
-
169
-		$this->config->expects($this->once())
170
-			->method('getValueString')
171
-			->with('dav', 'webcalAllowLocalAccess', 'no')
172
-			->willReturn('no');
173
-
174
-		$client->expects($this->once())
175
-			->method('get')
176
-			->with('https://foo.bar/bla2')
177
-			->willReturn($response);
178
-
179
-		$response->expects($this->once())
180
-			->method('getHeader')
181
-			->with('Content-Type')
182
-			->willReturn('text/calendar');
183
-
184
-		// Return a string instead of a resource
185
-		$response->expects($this->once())
186
-			->method('getBody')
187
-			->willReturn('not a resource');
188
-
189
-		$output = $this->connection->queryWebcalFeed($subscription);
190
-
191
-		$this->assertNull($output);
192
-	}
193
-
194
-	public static function runLocalURLDataProvider(): array {
195
-		return [
196
-			['localhost/foo.bar'],
197
-			['localHost/foo.bar'],
198
-			['random-host/foo.bar'],
199
-			['[::1]/bla.blub'],
200
-			['[::]/bla.blub'],
201
-			['192.168.0.1'],
202
-			['172.16.42.1'],
203
-			['[fdf8:f53b:82e4::53]/secret.ics'],
204
-			['[fe80::200:5aee:feaa:20a2]/secret.ics'],
205
-			['[0:0:0:0:0:0:10.0.0.1]/secret.ics'],
206
-			['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'],
207
-			['10.0.0.1'],
208
-			['another-host.local'],
209
-			['service.localhost'],
210
-		];
211
-	}
212
-
213
-	public static function urlDataProvider(): array {
214
-		return [
215
-			['https://foo.bar/bla2', 'text/calendar;charset=utf8', 'ical'],
216
-			['https://foo.bar/bla2', 'application/calendar+json', 'jcal'],
217
-			['https://foo.bar/bla2', 'application/calendar+xml', 'xcal'],
218
-		];
219
-	}
23
+    private IClientService&MockObject $clientService;
24
+    private IAppConfig&MockObject $config;
25
+    private LoggerInterface&MockObject $logger;
26
+    private Connection $connection;
27
+
28
+    public function setUp(): void {
29
+        $this->clientService = $this->createMock(IClientService::class);
30
+        $this->config = $this->createMock(IAppConfig::class);
31
+        $this->logger = $this->createMock(LoggerInterface::class);
32
+        $this->connection = new Connection($this->clientService, $this->config, $this->logger);
33
+    }
34
+
35
+    #[\PHPUnit\Framework\Attributes\DataProvider('runLocalURLDataProvider')]
36
+    public function testLocalUrl($source): void {
37
+        $subscription = [
38
+            'id' => 42,
39
+            'uri' => 'sub123',
40
+            'refreshreate' => 'P1H',
41
+            'striptodos' => 1,
42
+            'stripalarms' => 1,
43
+            'stripattachments' => 1,
44
+            'source' => $source,
45
+            'lastmodified' => 0,
46
+        ];
47
+
48
+        $client = $this->createMock(IClient::class);
49
+        $this->clientService->expects(self::once())
50
+            ->method('newClient')
51
+            ->with()
52
+            ->willReturn($client);
53
+
54
+        $this->config->expects(self::once())
55
+            ->method('getValueString')
56
+            ->with('dav', 'webcalAllowLocalAccess', 'no')
57
+            ->willReturn('no');
58
+
59
+        $localServerException = new LocalServerException();
60
+        $client->expects(self::once())
61
+            ->method('get')
62
+            ->willThrowException($localServerException);
63
+        $this->logger->expects(self::once())
64
+            ->method('warning')
65
+            ->with('Subscription 42 was not refreshed because it violates local access rules', ['exception' => $localServerException]);
66
+
67
+        $this->connection->queryWebcalFeed($subscription);
68
+    }
69
+
70
+    public function testInvalidUrl(): void {
71
+        $subscription = [
72
+            'id' => 42,
73
+            'uri' => 'sub123',
74
+            'refreshreate' => 'P1H',
75
+            'striptodos' => 1,
76
+            'stripalarms' => 1,
77
+            'stripattachments' => 1,
78
+            'source' => '!@#$',
79
+            'lastmodified' => 0,
80
+        ];
81
+
82
+        $client = $this->createMock(IClient::class);
83
+        $this->config->expects(self::never())
84
+            ->method('getValueString');
85
+        $client->expects(self::never())
86
+            ->method('get');
87
+
88
+        $this->connection->queryWebcalFeed($subscription);
89
+
90
+    }
91
+
92
+    #[\PHPUnit\Framework\Attributes\DataProvider('urlDataProvider')]
93
+    public function testConnection(string $url, string $contentType, string $expectedFormat): void {
94
+        $client = $this->createMock(IClient::class);
95
+        $response = $this->createMock(IResponse::class);
96
+        $subscription = [
97
+            'id' => 42,
98
+            'uri' => 'sub123',
99
+            'refreshreate' => 'P1H',
100
+            'striptodos' => 1,
101
+            'stripalarms' => 1,
102
+            'stripattachments' => 1,
103
+            'source' => $url,
104
+            'lastmodified' => 0,
105
+        ];
106
+
107
+        $this->clientService->expects($this->once())
108
+            ->method('newClient')
109
+            ->with()
110
+            ->willReturn($client);
111
+
112
+        $this->config->expects($this->once())
113
+            ->method('getValueString')
114
+            ->with('dav', 'webcalAllowLocalAccess', 'no')
115
+            ->willReturn('no');
116
+
117
+        $client->expects($this->once())
118
+            ->method('get')
119
+            ->with('https://foo.bar/bla2')
120
+            ->willReturn($response);
121
+
122
+        $response->expects($this->once())
123
+            ->method('getHeader')
124
+            ->with('Content-Type')
125
+            ->willReturn($contentType);
126
+
127
+        // Create a stream resource to simulate streaming response
128
+        $stream = fopen('php://temp', 'r+');
129
+        fwrite($stream, 'test calendar data');
130
+        rewind($stream);
131
+
132
+        $response->expects($this->once())
133
+            ->method('getBody')
134
+            ->willReturn($stream);
135
+
136
+        $output = $this->connection->queryWebcalFeed($subscription);
137
+
138
+        $this->assertIsArray($output);
139
+        $this->assertArrayHasKey('data', $output);
140
+        $this->assertArrayHasKey('format', $output);
141
+        $this->assertIsResource($output['data']);
142
+        $this->assertEquals($expectedFormat, $output['format']);
143
+
144
+        // Cleanup
145
+        if (is_resource($output['data'])) {
146
+            fclose($output['data']);
147
+        }
148
+    }
149
+
150
+    public function testConnectionReturnsNullWhenBodyIsNotResource(): void {
151
+        $client = $this->createMock(IClient::class);
152
+        $response = $this->createMock(IResponse::class);
153
+        $subscription = [
154
+            'id' => 42,
155
+            'uri' => 'sub123',
156
+            'refreshreate' => 'P1H',
157
+            'striptodos' => 1,
158
+            'stripalarms' => 1,
159
+            'stripattachments' => 1,
160
+            'source' => 'https://foo.bar/bla2',
161
+            'lastmodified' => 0,
162
+        ];
163
+
164
+        $this->clientService->expects($this->once())
165
+            ->method('newClient')
166
+            ->with()
167
+            ->willReturn($client);
168
+
169
+        $this->config->expects($this->once())
170
+            ->method('getValueString')
171
+            ->with('dav', 'webcalAllowLocalAccess', 'no')
172
+            ->willReturn('no');
173
+
174
+        $client->expects($this->once())
175
+            ->method('get')
176
+            ->with('https://foo.bar/bla2')
177
+            ->willReturn($response);
178
+
179
+        $response->expects($this->once())
180
+            ->method('getHeader')
181
+            ->with('Content-Type')
182
+            ->willReturn('text/calendar');
183
+
184
+        // Return a string instead of a resource
185
+        $response->expects($this->once())
186
+            ->method('getBody')
187
+            ->willReturn('not a resource');
188
+
189
+        $output = $this->connection->queryWebcalFeed($subscription);
190
+
191
+        $this->assertNull($output);
192
+    }
193
+
194
+    public static function runLocalURLDataProvider(): array {
195
+        return [
196
+            ['localhost/foo.bar'],
197
+            ['localHost/foo.bar'],
198
+            ['random-host/foo.bar'],
199
+            ['[::1]/bla.blub'],
200
+            ['[::]/bla.blub'],
201
+            ['192.168.0.1'],
202
+            ['172.16.42.1'],
203
+            ['[fdf8:f53b:82e4::53]/secret.ics'],
204
+            ['[fe80::200:5aee:feaa:20a2]/secret.ics'],
205
+            ['[0:0:0:0:0:0:10.0.0.1]/secret.ics'],
206
+            ['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'],
207
+            ['10.0.0.1'],
208
+            ['another-host.local'],
209
+            ['service.localhost'],
210
+        ];
211
+    }
212
+
213
+    public static function urlDataProvider(): array {
214
+        return [
215
+            ['https://foo.bar/bla2', 'text/calendar;charset=utf8', 'ical'],
216
+            ['https://foo.bar/bla2', 'application/calendar+json', 'jcal'],
217
+            ['https://foo.bar/bla2', 'application/calendar+xml', 'xcal'],
218
+        ];
219
+    }
220 220
 }
Please login to merge, or discard this patch.