Completed
Push — stable12 ( eb1ce1...bc3034 )
by Morris
26:43 queued 12:20
created
apps/dav/lib/CalDAV/Activity/Backend.php 2 patches
Indentation   +429 added lines, -429 removed lines patch added patch discarded remove patch
@@ -39,433 +39,433 @@
 block discarded – undo
39 39
  */
40 40
 class Backend {
41 41
 
42
-	/** @var IActivityManager */
43
-	protected $activityManager;
44
-
45
-	/** @var IGroupManager */
46
-	protected $groupManager;
47
-
48
-	/** @var IUserSession */
49
-	protected $userSession;
50
-
51
-	/**
52
-	 * @param IActivityManager $activityManager
53
-	 * @param IGroupManager $groupManager
54
-	 * @param IUserSession $userSession
55
-	 */
56
-	public function __construct(IActivityManager $activityManager, IGroupManager $groupManager, IUserSession $userSession) {
57
-		$this->activityManager = $activityManager;
58
-		$this->groupManager = $groupManager;
59
-		$this->userSession = $userSession;
60
-	}
61
-
62
-	/**
63
-	 * Creates activities when a calendar was creates
64
-	 *
65
-	 * @param array $calendarData
66
-	 */
67
-	public function onCalendarAdd(array $calendarData) {
68
-		$this->triggerCalendarActivity(Calendar::SUBJECT_ADD, $calendarData);
69
-	}
70
-
71
-	/**
72
-	 * Creates activities when a calendar was updated
73
-	 *
74
-	 * @param array $calendarData
75
-	 * @param array $shares
76
-	 * @param array $properties
77
-	 */
78
-	public function onCalendarUpdate(array $calendarData, array $shares, array $properties) {
79
-		$this->triggerCalendarActivity(Calendar::SUBJECT_UPDATE, $calendarData, $shares, $properties);
80
-	}
81
-
82
-	/**
83
-	 * Creates activities when a calendar was deleted
84
-	 *
85
-	 * @param array $calendarData
86
-	 * @param array $shares
87
-	 */
88
-	public function onCalendarDelete(array $calendarData, array $shares) {
89
-		$this->triggerCalendarActivity(Calendar::SUBJECT_DELETE, $calendarData, $shares);
90
-	}
91
-
92
-	/**
93
-	 * Creates activities for all related users when a calendar was touched
94
-	 *
95
-	 * @param string $action
96
-	 * @param array $calendarData
97
-	 * @param array $shares
98
-	 * @param array $changedProperties
99
-	 */
100
-	protected function triggerCalendarActivity($action, array $calendarData, array $shares = [], array $changedProperties = []) {
101
-		if (!isset($calendarData['principaluri'])) {
102
-			return;
103
-		}
104
-
105
-		$principal = explode('/', $calendarData['principaluri']);
106
-		$owner = array_pop($principal);
107
-
108
-		$currentUser = $this->userSession->getUser();
109
-		if ($currentUser instanceof IUser) {
110
-			$currentUser = $currentUser->getUID();
111
-		} else {
112
-			$currentUser = $owner;
113
-		}
114
-
115
-		$event = $this->activityManager->generateEvent();
116
-		$event->setApp('dav')
117
-			->setObject('calendar', (int) $calendarData['id'])
118
-			->setType('calendar')
119
-			->setAuthor($currentUser);
120
-
121
-		$changedVisibleInformation = array_intersect([
122
-			'{DAV:}displayname',
123
-			'{http://apple.com/ns/ical/}calendar-color'
124
-		], array_keys($changedProperties));
125
-
126
-		if (empty($shares) || ($action === Calendar::SUBJECT_UPDATE && empty($changedVisibleInformation))) {
127
-			$users = [$owner];
128
-		} else {
129
-			$users = $this->getUsersForShares($shares);
130
-			$users[] = $owner;
131
-		}
132
-
133
-		foreach ($users as $user) {
134
-			$event->setAffectedUser($user)
135
-				->setSubject(
136
-					$user === $currentUser ? $action . '_self' : $action,
137
-					[
138
-						$currentUser,
139
-						$calendarData['{DAV:}displayname'],
140
-					]
141
-				);
142
-			$this->activityManager->publish($event);
143
-		}
144
-	}
145
-
146
-	/**
147
-	 * Creates activities for all related users when a calendar was (un-)shared
148
-	 *
149
-	 * @param array $calendarData
150
-	 * @param array $shares
151
-	 * @param array $add
152
-	 * @param array $remove
153
-	 */
154
-	public function onCalendarUpdateShares(array $calendarData, array $shares, array $add, array $remove) {
155
-		$principal = explode('/', $calendarData['principaluri']);
156
-		$owner = $principal[2];
157
-
158
-		$currentUser = $this->userSession->getUser();
159
-		if ($currentUser instanceof IUser) {
160
-			$currentUser = $currentUser->getUID();
161
-		} else {
162
-			$currentUser = $owner;
163
-		}
164
-
165
-		$event = $this->activityManager->generateEvent();
166
-		$event->setApp('dav')
167
-			->setObject('calendar', (int) $calendarData['id'])
168
-			->setType('calendar')
169
-			->setAuthor($currentUser);
170
-
171
-		foreach ($remove as $principal) {
172
-			// principal:principals/users/test
173
-			$parts = explode(':', $principal, 2);
174
-			if ($parts[0] !== 'principal') {
175
-				continue;
176
-			}
177
-			$principal = explode('/', $parts[1]);
178
-
179
-			if ($principal[1] === 'users') {
180
-				$this->triggerActivityUser(
181
-					$principal[2],
182
-					$event,
183
-					$calendarData,
184
-					Calendar::SUBJECT_UNSHARE_USER,
185
-					Calendar::SUBJECT_DELETE . '_self'
186
-				);
187
-
188
-				if ($owner !== $principal[2]) {
189
-					$parameters = [
190
-						$principal[2],
191
-						$calendarData['{DAV:}displayname'],
192
-					];
193
-
194
-					if ($owner === $event->getAuthor()) {
195
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_you';
196
-					} else if ($principal[2] === $event->getAuthor()) {
197
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_self';
198
-					} else {
199
-						$event->setAffectedUser($event->getAuthor())
200
-							->setSubject(Calendar::SUBJECT_UNSHARE_USER . '_you', $parameters);
201
-						$this->activityManager->publish($event);
202
-
203
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_by';
204
-						$parameters[] = $event->getAuthor();
205
-					}
206
-
207
-					$event->setAffectedUser($owner)
208
-						->setSubject($subject, $parameters);
209
-					$this->activityManager->publish($event);
210
-				}
211
-			} else if ($principal[1] === 'groups') {
212
-				$this->triggerActivityGroup($principal[2], $event, $calendarData, Calendar::SUBJECT_UNSHARE_USER);
213
-
214
-				$parameters = [
215
-					$principal[2],
216
-					$calendarData['{DAV:}displayname'],
217
-				];
218
-
219
-				if ($owner === $event->getAuthor()) {
220
-					$subject = Calendar::SUBJECT_UNSHARE_GROUP . '_you';
221
-				} else {
222
-					$event->setAffectedUser($event->getAuthor())
223
-						->setSubject(Calendar::SUBJECT_UNSHARE_GROUP . '_you', $parameters);
224
-					$this->activityManager->publish($event);
225
-
226
-					$subject = Calendar::SUBJECT_UNSHARE_GROUP . '_by';
227
-					$parameters[] = $event->getAuthor();
228
-				}
229
-
230
-				$event->setAffectedUser($owner)
231
-					->setSubject($subject, $parameters);
232
-				$this->activityManager->publish($event);
233
-			}
234
-		}
235
-
236
-		foreach ($add as $share) {
237
-			if ($this->isAlreadyShared($share['href'], $shares)) {
238
-				continue;
239
-			}
240
-
241
-			// principal:principals/users/test
242
-			$parts = explode(':', $share['href'], 2);
243
-			if ($parts[0] !== 'principal') {
244
-				continue;
245
-			}
246
-			$principal = explode('/', $parts[1]);
247
-
248
-			if ($principal[1] === 'users') {
249
-				$this->triggerActivityUser($principal[2], $event, $calendarData, Calendar::SUBJECT_SHARE_USER);
250
-
251
-				if ($owner !== $principal[2]) {
252
-					$parameters = [
253
-						$principal[2],
254
-						$calendarData['{DAV:}displayname'],
255
-					];
256
-
257
-					if ($owner === $event->getAuthor()) {
258
-						$subject = Calendar::SUBJECT_SHARE_USER . '_you';
259
-					} else {
260
-						$event->setAffectedUser($event->getAuthor())
261
-							->setSubject(Calendar::SUBJECT_SHARE_USER . '_you', $parameters);
262
-						$this->activityManager->publish($event);
263
-
264
-						$subject = Calendar::SUBJECT_SHARE_USER . '_by';
265
-						$parameters[] = $event->getAuthor();
266
-					}
267
-
268
-					$event->setAffectedUser($owner)
269
-						->setSubject($subject, $parameters);
270
-					$this->activityManager->publish($event);
271
-				}
272
-			} else if ($principal[1] === 'groups') {
273
-				$this->triggerActivityGroup($principal[2], $event, $calendarData, Calendar::SUBJECT_SHARE_USER);
274
-
275
-				$parameters = [
276
-					$principal[2],
277
-					$calendarData['{DAV:}displayname'],
278
-				];
279
-
280
-				if ($owner === $event->getAuthor()) {
281
-					$subject = Calendar::SUBJECT_SHARE_GROUP . '_you';
282
-				} else {
283
-					$event->setAffectedUser($event->getAuthor())
284
-						->setSubject(Calendar::SUBJECT_SHARE_GROUP . '_you', $parameters);
285
-					$this->activityManager->publish($event);
286
-
287
-					$subject = Calendar::SUBJECT_SHARE_GROUP . '_by';
288
-					$parameters[] = $event->getAuthor();
289
-				}
290
-
291
-				$event->setAffectedUser($owner)
292
-					->setSubject($subject, $parameters);
293
-				$this->activityManager->publish($event);
294
-			}
295
-		}
296
-	}
297
-
298
-	/**
299
-	 * Checks if a calendar is already shared with a principal
300
-	 *
301
-	 * @param string $principal
302
-	 * @param array[] $shares
303
-	 * @return bool
304
-	 */
305
-	protected function isAlreadyShared($principal, $shares) {
306
-		foreach ($shares as $share) {
307
-			if ($principal === $share['href']) {
308
-				return true;
309
-			}
310
-		}
311
-
312
-		return false;
313
-	}
314
-
315
-	/**
316
-	 * Creates the given activity for all members of the given group
317
-	 *
318
-	 * @param string $gid
319
-	 * @param IEvent $event
320
-	 * @param array $properties
321
-	 * @param string $subject
322
-	 */
323
-	protected function triggerActivityGroup($gid, IEvent $event, array $properties, $subject) {
324
-		$group = $this->groupManager->get($gid);
325
-
326
-		if ($group instanceof IGroup) {
327
-			foreach ($group->getUsers() as $user) {
328
-				// Exclude current user
329
-				if ($user->getUID() !== $event->getAuthor()) {
330
-					$this->triggerActivityUser($user->getUID(), $event, $properties, $subject);
331
-				}
332
-			}
333
-		}
334
-	}
335
-
336
-	/**
337
-	 * Creates the given activity for the given user
338
-	 *
339
-	 * @param string $user
340
-	 * @param IEvent $event
341
-	 * @param array $properties
342
-	 * @param string $subject
343
-	 * @param string $subjectSelf
344
-	 */
345
-	protected function triggerActivityUser($user, IEvent $event, array $properties, $subject, $subjectSelf = '') {
346
-		$event->setAffectedUser($user)
347
-			->setSubject(
348
-				$user === $event->getAuthor() && $subjectSelf ? $subjectSelf : $subject,
349
-				[
350
-					$event->getAuthor(),
351
-					$properties['{DAV:}displayname'],
352
-				]
353
-			);
354
-
355
-		$this->activityManager->publish($event);
356
-	}
357
-
358
-	/**
359
-	 * Creates activities when a calendar object was created/updated/deleted
360
-	 *
361
-	 * @param string $action
362
-	 * @param array $calendarData
363
-	 * @param array $shares
364
-	 * @param array $objectData
365
-	 */
366
-	public function onTouchCalendarObject($action, array $calendarData, array $shares, array $objectData) {
367
-		if (!isset($calendarData['principaluri'])) {
368
-			return;
369
-		}
370
-
371
-		$principal = explode('/', $calendarData['principaluri']);
372
-		$owner = array_pop($principal);
373
-
374
-		$currentUser = $this->userSession->getUser();
375
-		if ($currentUser instanceof IUser) {
376
-			$currentUser = $currentUser->getUID();
377
-		} else {
378
-			$currentUser = $owner;
379
-		}
380
-
381
-		$object = $this->getObjectNameAndType($objectData);
382
-		$action = $action . '_' . $object['type'];
383
-
384
-		if ($object['type'] === 'todo' && strpos($action, Event::SUBJECT_OBJECT_UPDATE) === 0 && $object['status'] === 'COMPLETED') {
385
-			$action .= '_completed';
386
-		} else if ($object['type'] === 'todo' && strpos($action, Event::SUBJECT_OBJECT_UPDATE) === 0 && $object['status'] === 'NEEDS-ACTION') {
387
-			$action .= '_needs_action';
388
-		}
389
-
390
-		$event = $this->activityManager->generateEvent();
391
-		$event->setApp('dav')
392
-			->setObject('calendar', (int) $calendarData['id'])
393
-			->setType($object['type'] === 'event' ? 'calendar_event' : 'calendar_todo')
394
-			->setAuthor($currentUser);
395
-
396
-		$users = $this->getUsersForShares($shares);
397
-		$users[] = $owner;
398
-
399
-		foreach ($users as $user) {
400
-			$event->setAffectedUser($user)
401
-				->setSubject(
402
-					$user === $currentUser ? $action . '_self' : $action,
403
-					[
404
-						$currentUser,
405
-						$calendarData['{DAV:}displayname'],
406
-						[
407
-							'id' => $object['id'],
408
-							'name' => $object['name'],
409
-						],
410
-					]
411
-				);
412
-			$this->activityManager->publish($event);
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * @param array $objectData
418
-	 * @return string[]|bool
419
-	 */
420
-	protected function getObjectNameAndType(array $objectData) {
421
-		$vObject = Reader::read($objectData['calendardata']);
422
-		$component = $componentType = null;
423
-		foreach($vObject->getComponents() as $component) {
424
-			if (in_array($component->name, ['VEVENT', 'VTODO'])) {
425
-				$componentType = $component->name;
426
-				break;
427
-			}
428
-		}
429
-
430
-		if (!$componentType) {
431
-			// Calendar objects must have a VEVENT or VTODO component
432
-			return false;
433
-		}
434
-
435
-		if ($componentType === 'VEVENT') {
436
-			return ['id' => (string) $component->UID, 'name' => (string) $component->SUMMARY, 'type' => 'event'];
437
-		}
438
-		return ['id' => (string) $component->UID, 'name' => (string) $component->SUMMARY, 'type' => 'todo', 'status' => (string) $component->STATUS];
439
-	}
440
-
441
-	/**
442
-	 * Get all users that have access to a given calendar
443
-	 *
444
-	 * @param array $shares
445
-	 * @return string[]
446
-	 */
447
-	protected function getUsersForShares(array $shares) {
448
-		$users = $groups = [];
449
-		foreach ($shares as $share) {
450
-			$prinical = explode('/', $share['{http://owncloud.org/ns}principal']);
451
-			if ($prinical[1] === 'users') {
452
-				$users[] = $prinical[2];
453
-			} else if ($prinical[1] === 'groups') {
454
-				$groups[] = $prinical[2];
455
-			}
456
-		}
457
-
458
-		if (!empty($groups)) {
459
-			foreach ($groups as $gid) {
460
-				$group = $this->groupManager->get($gid);
461
-				if ($group instanceof IGroup) {
462
-					foreach ($group->getUsers() as $user) {
463
-						$users[] = $user->getUID();
464
-					}
465
-				}
466
-			}
467
-		}
468
-
469
-		return array_unique($users);
470
-	}
42
+    /** @var IActivityManager */
43
+    protected $activityManager;
44
+
45
+    /** @var IGroupManager */
46
+    protected $groupManager;
47
+
48
+    /** @var IUserSession */
49
+    protected $userSession;
50
+
51
+    /**
52
+     * @param IActivityManager $activityManager
53
+     * @param IGroupManager $groupManager
54
+     * @param IUserSession $userSession
55
+     */
56
+    public function __construct(IActivityManager $activityManager, IGroupManager $groupManager, IUserSession $userSession) {
57
+        $this->activityManager = $activityManager;
58
+        $this->groupManager = $groupManager;
59
+        $this->userSession = $userSession;
60
+    }
61
+
62
+    /**
63
+     * Creates activities when a calendar was creates
64
+     *
65
+     * @param array $calendarData
66
+     */
67
+    public function onCalendarAdd(array $calendarData) {
68
+        $this->triggerCalendarActivity(Calendar::SUBJECT_ADD, $calendarData);
69
+    }
70
+
71
+    /**
72
+     * Creates activities when a calendar was updated
73
+     *
74
+     * @param array $calendarData
75
+     * @param array $shares
76
+     * @param array $properties
77
+     */
78
+    public function onCalendarUpdate(array $calendarData, array $shares, array $properties) {
79
+        $this->triggerCalendarActivity(Calendar::SUBJECT_UPDATE, $calendarData, $shares, $properties);
80
+    }
81
+
82
+    /**
83
+     * Creates activities when a calendar was deleted
84
+     *
85
+     * @param array $calendarData
86
+     * @param array $shares
87
+     */
88
+    public function onCalendarDelete(array $calendarData, array $shares) {
89
+        $this->triggerCalendarActivity(Calendar::SUBJECT_DELETE, $calendarData, $shares);
90
+    }
91
+
92
+    /**
93
+     * Creates activities for all related users when a calendar was touched
94
+     *
95
+     * @param string $action
96
+     * @param array $calendarData
97
+     * @param array $shares
98
+     * @param array $changedProperties
99
+     */
100
+    protected function triggerCalendarActivity($action, array $calendarData, array $shares = [], array $changedProperties = []) {
101
+        if (!isset($calendarData['principaluri'])) {
102
+            return;
103
+        }
104
+
105
+        $principal = explode('/', $calendarData['principaluri']);
106
+        $owner = array_pop($principal);
107
+
108
+        $currentUser = $this->userSession->getUser();
109
+        if ($currentUser instanceof IUser) {
110
+            $currentUser = $currentUser->getUID();
111
+        } else {
112
+            $currentUser = $owner;
113
+        }
114
+
115
+        $event = $this->activityManager->generateEvent();
116
+        $event->setApp('dav')
117
+            ->setObject('calendar', (int) $calendarData['id'])
118
+            ->setType('calendar')
119
+            ->setAuthor($currentUser);
120
+
121
+        $changedVisibleInformation = array_intersect([
122
+            '{DAV:}displayname',
123
+            '{http://apple.com/ns/ical/}calendar-color'
124
+        ], array_keys($changedProperties));
125
+
126
+        if (empty($shares) || ($action === Calendar::SUBJECT_UPDATE && empty($changedVisibleInformation))) {
127
+            $users = [$owner];
128
+        } else {
129
+            $users = $this->getUsersForShares($shares);
130
+            $users[] = $owner;
131
+        }
132
+
133
+        foreach ($users as $user) {
134
+            $event->setAffectedUser($user)
135
+                ->setSubject(
136
+                    $user === $currentUser ? $action . '_self' : $action,
137
+                    [
138
+                        $currentUser,
139
+                        $calendarData['{DAV:}displayname'],
140
+                    ]
141
+                );
142
+            $this->activityManager->publish($event);
143
+        }
144
+    }
145
+
146
+    /**
147
+     * Creates activities for all related users when a calendar was (un-)shared
148
+     *
149
+     * @param array $calendarData
150
+     * @param array $shares
151
+     * @param array $add
152
+     * @param array $remove
153
+     */
154
+    public function onCalendarUpdateShares(array $calendarData, array $shares, array $add, array $remove) {
155
+        $principal = explode('/', $calendarData['principaluri']);
156
+        $owner = $principal[2];
157
+
158
+        $currentUser = $this->userSession->getUser();
159
+        if ($currentUser instanceof IUser) {
160
+            $currentUser = $currentUser->getUID();
161
+        } else {
162
+            $currentUser = $owner;
163
+        }
164
+
165
+        $event = $this->activityManager->generateEvent();
166
+        $event->setApp('dav')
167
+            ->setObject('calendar', (int) $calendarData['id'])
168
+            ->setType('calendar')
169
+            ->setAuthor($currentUser);
170
+
171
+        foreach ($remove as $principal) {
172
+            // principal:principals/users/test
173
+            $parts = explode(':', $principal, 2);
174
+            if ($parts[0] !== 'principal') {
175
+                continue;
176
+            }
177
+            $principal = explode('/', $parts[1]);
178
+
179
+            if ($principal[1] === 'users') {
180
+                $this->triggerActivityUser(
181
+                    $principal[2],
182
+                    $event,
183
+                    $calendarData,
184
+                    Calendar::SUBJECT_UNSHARE_USER,
185
+                    Calendar::SUBJECT_DELETE . '_self'
186
+                );
187
+
188
+                if ($owner !== $principal[2]) {
189
+                    $parameters = [
190
+                        $principal[2],
191
+                        $calendarData['{DAV:}displayname'],
192
+                    ];
193
+
194
+                    if ($owner === $event->getAuthor()) {
195
+                        $subject = Calendar::SUBJECT_UNSHARE_USER . '_you';
196
+                    } else if ($principal[2] === $event->getAuthor()) {
197
+                        $subject = Calendar::SUBJECT_UNSHARE_USER . '_self';
198
+                    } else {
199
+                        $event->setAffectedUser($event->getAuthor())
200
+                            ->setSubject(Calendar::SUBJECT_UNSHARE_USER . '_you', $parameters);
201
+                        $this->activityManager->publish($event);
202
+
203
+                        $subject = Calendar::SUBJECT_UNSHARE_USER . '_by';
204
+                        $parameters[] = $event->getAuthor();
205
+                    }
206
+
207
+                    $event->setAffectedUser($owner)
208
+                        ->setSubject($subject, $parameters);
209
+                    $this->activityManager->publish($event);
210
+                }
211
+            } else if ($principal[1] === 'groups') {
212
+                $this->triggerActivityGroup($principal[2], $event, $calendarData, Calendar::SUBJECT_UNSHARE_USER);
213
+
214
+                $parameters = [
215
+                    $principal[2],
216
+                    $calendarData['{DAV:}displayname'],
217
+                ];
218
+
219
+                if ($owner === $event->getAuthor()) {
220
+                    $subject = Calendar::SUBJECT_UNSHARE_GROUP . '_you';
221
+                } else {
222
+                    $event->setAffectedUser($event->getAuthor())
223
+                        ->setSubject(Calendar::SUBJECT_UNSHARE_GROUP . '_you', $parameters);
224
+                    $this->activityManager->publish($event);
225
+
226
+                    $subject = Calendar::SUBJECT_UNSHARE_GROUP . '_by';
227
+                    $parameters[] = $event->getAuthor();
228
+                }
229
+
230
+                $event->setAffectedUser($owner)
231
+                    ->setSubject($subject, $parameters);
232
+                $this->activityManager->publish($event);
233
+            }
234
+        }
235
+
236
+        foreach ($add as $share) {
237
+            if ($this->isAlreadyShared($share['href'], $shares)) {
238
+                continue;
239
+            }
240
+
241
+            // principal:principals/users/test
242
+            $parts = explode(':', $share['href'], 2);
243
+            if ($parts[0] !== 'principal') {
244
+                continue;
245
+            }
246
+            $principal = explode('/', $parts[1]);
247
+
248
+            if ($principal[1] === 'users') {
249
+                $this->triggerActivityUser($principal[2], $event, $calendarData, Calendar::SUBJECT_SHARE_USER);
250
+
251
+                if ($owner !== $principal[2]) {
252
+                    $parameters = [
253
+                        $principal[2],
254
+                        $calendarData['{DAV:}displayname'],
255
+                    ];
256
+
257
+                    if ($owner === $event->getAuthor()) {
258
+                        $subject = Calendar::SUBJECT_SHARE_USER . '_you';
259
+                    } else {
260
+                        $event->setAffectedUser($event->getAuthor())
261
+                            ->setSubject(Calendar::SUBJECT_SHARE_USER . '_you', $parameters);
262
+                        $this->activityManager->publish($event);
263
+
264
+                        $subject = Calendar::SUBJECT_SHARE_USER . '_by';
265
+                        $parameters[] = $event->getAuthor();
266
+                    }
267
+
268
+                    $event->setAffectedUser($owner)
269
+                        ->setSubject($subject, $parameters);
270
+                    $this->activityManager->publish($event);
271
+                }
272
+            } else if ($principal[1] === 'groups') {
273
+                $this->triggerActivityGroup($principal[2], $event, $calendarData, Calendar::SUBJECT_SHARE_USER);
274
+
275
+                $parameters = [
276
+                    $principal[2],
277
+                    $calendarData['{DAV:}displayname'],
278
+                ];
279
+
280
+                if ($owner === $event->getAuthor()) {
281
+                    $subject = Calendar::SUBJECT_SHARE_GROUP . '_you';
282
+                } else {
283
+                    $event->setAffectedUser($event->getAuthor())
284
+                        ->setSubject(Calendar::SUBJECT_SHARE_GROUP . '_you', $parameters);
285
+                    $this->activityManager->publish($event);
286
+
287
+                    $subject = Calendar::SUBJECT_SHARE_GROUP . '_by';
288
+                    $parameters[] = $event->getAuthor();
289
+                }
290
+
291
+                $event->setAffectedUser($owner)
292
+                    ->setSubject($subject, $parameters);
293
+                $this->activityManager->publish($event);
294
+            }
295
+        }
296
+    }
297
+
298
+    /**
299
+     * Checks if a calendar is already shared with a principal
300
+     *
301
+     * @param string $principal
302
+     * @param array[] $shares
303
+     * @return bool
304
+     */
305
+    protected function isAlreadyShared($principal, $shares) {
306
+        foreach ($shares as $share) {
307
+            if ($principal === $share['href']) {
308
+                return true;
309
+            }
310
+        }
311
+
312
+        return false;
313
+    }
314
+
315
+    /**
316
+     * Creates the given activity for all members of the given group
317
+     *
318
+     * @param string $gid
319
+     * @param IEvent $event
320
+     * @param array $properties
321
+     * @param string $subject
322
+     */
323
+    protected function triggerActivityGroup($gid, IEvent $event, array $properties, $subject) {
324
+        $group = $this->groupManager->get($gid);
325
+
326
+        if ($group instanceof IGroup) {
327
+            foreach ($group->getUsers() as $user) {
328
+                // Exclude current user
329
+                if ($user->getUID() !== $event->getAuthor()) {
330
+                    $this->triggerActivityUser($user->getUID(), $event, $properties, $subject);
331
+                }
332
+            }
333
+        }
334
+    }
335
+
336
+    /**
337
+     * Creates the given activity for the given user
338
+     *
339
+     * @param string $user
340
+     * @param IEvent $event
341
+     * @param array $properties
342
+     * @param string $subject
343
+     * @param string $subjectSelf
344
+     */
345
+    protected function triggerActivityUser($user, IEvent $event, array $properties, $subject, $subjectSelf = '') {
346
+        $event->setAffectedUser($user)
347
+            ->setSubject(
348
+                $user === $event->getAuthor() && $subjectSelf ? $subjectSelf : $subject,
349
+                [
350
+                    $event->getAuthor(),
351
+                    $properties['{DAV:}displayname'],
352
+                ]
353
+            );
354
+
355
+        $this->activityManager->publish($event);
356
+    }
357
+
358
+    /**
359
+     * Creates activities when a calendar object was created/updated/deleted
360
+     *
361
+     * @param string $action
362
+     * @param array $calendarData
363
+     * @param array $shares
364
+     * @param array $objectData
365
+     */
366
+    public function onTouchCalendarObject($action, array $calendarData, array $shares, array $objectData) {
367
+        if (!isset($calendarData['principaluri'])) {
368
+            return;
369
+        }
370
+
371
+        $principal = explode('/', $calendarData['principaluri']);
372
+        $owner = array_pop($principal);
373
+
374
+        $currentUser = $this->userSession->getUser();
375
+        if ($currentUser instanceof IUser) {
376
+            $currentUser = $currentUser->getUID();
377
+        } else {
378
+            $currentUser = $owner;
379
+        }
380
+
381
+        $object = $this->getObjectNameAndType($objectData);
382
+        $action = $action . '_' . $object['type'];
383
+
384
+        if ($object['type'] === 'todo' && strpos($action, Event::SUBJECT_OBJECT_UPDATE) === 0 && $object['status'] === 'COMPLETED') {
385
+            $action .= '_completed';
386
+        } else if ($object['type'] === 'todo' && strpos($action, Event::SUBJECT_OBJECT_UPDATE) === 0 && $object['status'] === 'NEEDS-ACTION') {
387
+            $action .= '_needs_action';
388
+        }
389
+
390
+        $event = $this->activityManager->generateEvent();
391
+        $event->setApp('dav')
392
+            ->setObject('calendar', (int) $calendarData['id'])
393
+            ->setType($object['type'] === 'event' ? 'calendar_event' : 'calendar_todo')
394
+            ->setAuthor($currentUser);
395
+
396
+        $users = $this->getUsersForShares($shares);
397
+        $users[] = $owner;
398
+
399
+        foreach ($users as $user) {
400
+            $event->setAffectedUser($user)
401
+                ->setSubject(
402
+                    $user === $currentUser ? $action . '_self' : $action,
403
+                    [
404
+                        $currentUser,
405
+                        $calendarData['{DAV:}displayname'],
406
+                        [
407
+                            'id' => $object['id'],
408
+                            'name' => $object['name'],
409
+                        ],
410
+                    ]
411
+                );
412
+            $this->activityManager->publish($event);
413
+        }
414
+    }
415
+
416
+    /**
417
+     * @param array $objectData
418
+     * @return string[]|bool
419
+     */
420
+    protected function getObjectNameAndType(array $objectData) {
421
+        $vObject = Reader::read($objectData['calendardata']);
422
+        $component = $componentType = null;
423
+        foreach($vObject->getComponents() as $component) {
424
+            if (in_array($component->name, ['VEVENT', 'VTODO'])) {
425
+                $componentType = $component->name;
426
+                break;
427
+            }
428
+        }
429
+
430
+        if (!$componentType) {
431
+            // Calendar objects must have a VEVENT or VTODO component
432
+            return false;
433
+        }
434
+
435
+        if ($componentType === 'VEVENT') {
436
+            return ['id' => (string) $component->UID, 'name' => (string) $component->SUMMARY, 'type' => 'event'];
437
+        }
438
+        return ['id' => (string) $component->UID, 'name' => (string) $component->SUMMARY, 'type' => 'todo', 'status' => (string) $component->STATUS];
439
+    }
440
+
441
+    /**
442
+     * Get all users that have access to a given calendar
443
+     *
444
+     * @param array $shares
445
+     * @return string[]
446
+     */
447
+    protected function getUsersForShares(array $shares) {
448
+        $users = $groups = [];
449
+        foreach ($shares as $share) {
450
+            $prinical = explode('/', $share['{http://owncloud.org/ns}principal']);
451
+            if ($prinical[1] === 'users') {
452
+                $users[] = $prinical[2];
453
+            } else if ($prinical[1] === 'groups') {
454
+                $groups[] = $prinical[2];
455
+            }
456
+        }
457
+
458
+        if (!empty($groups)) {
459
+            foreach ($groups as $gid) {
460
+                $group = $this->groupManager->get($gid);
461
+                if ($group instanceof IGroup) {
462
+                    foreach ($group->getUsers() as $user) {
463
+                        $users[] = $user->getUID();
464
+                    }
465
+                }
466
+            }
467
+        }
468
+
469
+        return array_unique($users);
470
+    }
471 471
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		foreach ($users as $user) {
134 134
 			$event->setAffectedUser($user)
135 135
 				->setSubject(
136
-					$user === $currentUser ? $action . '_self' : $action,
136
+					$user === $currentUser ? $action.'_self' : $action,
137 137
 					[
138 138
 						$currentUser,
139 139
 						$calendarData['{DAV:}displayname'],
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 					$event,
183 183
 					$calendarData,
184 184
 					Calendar::SUBJECT_UNSHARE_USER,
185
-					Calendar::SUBJECT_DELETE . '_self'
185
+					Calendar::SUBJECT_DELETE.'_self'
186 186
 				);
187 187
 
188 188
 				if ($owner !== $principal[2]) {
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
 					];
193 193
 
194 194
 					if ($owner === $event->getAuthor()) {
195
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_you';
195
+						$subject = Calendar::SUBJECT_UNSHARE_USER.'_you';
196 196
 					} else if ($principal[2] === $event->getAuthor()) {
197
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_self';
197
+						$subject = Calendar::SUBJECT_UNSHARE_USER.'_self';
198 198
 					} else {
199 199
 						$event->setAffectedUser($event->getAuthor())
200
-							->setSubject(Calendar::SUBJECT_UNSHARE_USER . '_you', $parameters);
200
+							->setSubject(Calendar::SUBJECT_UNSHARE_USER.'_you', $parameters);
201 201
 						$this->activityManager->publish($event);
202 202
 
203
-						$subject = Calendar::SUBJECT_UNSHARE_USER . '_by';
203
+						$subject = Calendar::SUBJECT_UNSHARE_USER.'_by';
204 204
 						$parameters[] = $event->getAuthor();
205 205
 					}
206 206
 
@@ -217,13 +217,13 @@  discard block
 block discarded – undo
217 217
 				];
218 218
 
219 219
 				if ($owner === $event->getAuthor()) {
220
-					$subject = Calendar::SUBJECT_UNSHARE_GROUP . '_you';
220
+					$subject = Calendar::SUBJECT_UNSHARE_GROUP.'_you';
221 221
 				} else {
222 222
 					$event->setAffectedUser($event->getAuthor())
223
-						->setSubject(Calendar::SUBJECT_UNSHARE_GROUP . '_you', $parameters);
223
+						->setSubject(Calendar::SUBJECT_UNSHARE_GROUP.'_you', $parameters);
224 224
 					$this->activityManager->publish($event);
225 225
 
226
-					$subject = Calendar::SUBJECT_UNSHARE_GROUP . '_by';
226
+					$subject = Calendar::SUBJECT_UNSHARE_GROUP.'_by';
227 227
 					$parameters[] = $event->getAuthor();
228 228
 				}
229 229
 
@@ -255,13 +255,13 @@  discard block
 block discarded – undo
255 255
 					];
256 256
 
257 257
 					if ($owner === $event->getAuthor()) {
258
-						$subject = Calendar::SUBJECT_SHARE_USER . '_you';
258
+						$subject = Calendar::SUBJECT_SHARE_USER.'_you';
259 259
 					} else {
260 260
 						$event->setAffectedUser($event->getAuthor())
261
-							->setSubject(Calendar::SUBJECT_SHARE_USER . '_you', $parameters);
261
+							->setSubject(Calendar::SUBJECT_SHARE_USER.'_you', $parameters);
262 262
 						$this->activityManager->publish($event);
263 263
 
264
-						$subject = Calendar::SUBJECT_SHARE_USER . '_by';
264
+						$subject = Calendar::SUBJECT_SHARE_USER.'_by';
265 265
 						$parameters[] = $event->getAuthor();
266 266
 					}
267 267
 
@@ -278,13 +278,13 @@  discard block
 block discarded – undo
278 278
 				];
279 279
 
280 280
 				if ($owner === $event->getAuthor()) {
281
-					$subject = Calendar::SUBJECT_SHARE_GROUP . '_you';
281
+					$subject = Calendar::SUBJECT_SHARE_GROUP.'_you';
282 282
 				} else {
283 283
 					$event->setAffectedUser($event->getAuthor())
284
-						->setSubject(Calendar::SUBJECT_SHARE_GROUP . '_you', $parameters);
284
+						->setSubject(Calendar::SUBJECT_SHARE_GROUP.'_you', $parameters);
285 285
 					$this->activityManager->publish($event);
286 286
 
287
-					$subject = Calendar::SUBJECT_SHARE_GROUP . '_by';
287
+					$subject = Calendar::SUBJECT_SHARE_GROUP.'_by';
288 288
 					$parameters[] = $event->getAuthor();
289 289
 				}
290 290
 
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
 		}
380 380
 
381 381
 		$object = $this->getObjectNameAndType($objectData);
382
-		$action = $action . '_' . $object['type'];
382
+		$action = $action.'_'.$object['type'];
383 383
 
384 384
 		if ($object['type'] === 'todo' && strpos($action, Event::SUBJECT_OBJECT_UPDATE) === 0 && $object['status'] === 'COMPLETED') {
385 385
 			$action .= '_completed';
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 		foreach ($users as $user) {
400 400
 			$event->setAffectedUser($user)
401 401
 				->setSubject(
402
-					$user === $currentUser ? $action . '_self' : $action,
402
+					$user === $currentUser ? $action.'_self' : $action,
403 403
 					[
404 404
 						$currentUser,
405 405
 						$calendarData['{DAV:}displayname'],
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 	protected function getObjectNameAndType(array $objectData) {
421 421
 		$vObject = Reader::read($objectData['calendardata']);
422 422
 		$component = $componentType = null;
423
-		foreach($vObject->getComponents() as $component) {
423
+		foreach ($vObject->getComponents() as $component) {
424 424
 			if (in_array($component->name, ['VEVENT', 'VTODO'])) {
425 425
 				$componentType = $component->name;
426 426
 				break;
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Doc Comments   +10 added lines, -4 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 	 *
180 180
 	 * By default this excludes the automatically generated birthday calendar
181 181
 	 *
182
-	 * @param $principalUri
182
+	 * @param string $principalUri
183 183
 	 * @param bool $excludeBirthday
184 184
 	 * @return int
185 185
 	 */
@@ -341,6 +341,9 @@  discard block
 block discarded – undo
341 341
 		return array_values($calendars);
342 342
 	}
343 343
 
344
+	/**
345
+	 * @param string $principalUri
346
+	 */
344 347
 	public function getUsersOwnCalendars($principalUri) {
345 348
 		$principalUri = $this->convertPrincipal($principalUri, true);
346 349
 		$fields = array_values($this->propertyMap);
@@ -920,7 +923,7 @@  discard block
 block discarded – undo
920 923
 	 * calendar-data. If the result of a subsequent GET to this object is not
921 924
 	 * the exact same as this request body, you should omit the ETag.
922 925
 	 *
923
-	 * @param mixed $calendarId
926
+	 * @param integer $calendarId
924 927
 	 * @param string $objectUri
925 928
 	 * @param string $calendarData
926 929
 	 * @return string
@@ -974,7 +977,7 @@  discard block
 block discarded – undo
974 977
 	 * calendar-data. If the result of a subsequent GET to this object is not
975 978
 	 * the exact same as this request body, you should omit the ETag.
976 979
 	 *
977
-	 * @param mixed $calendarId
980
+	 * @param integer $calendarId
978 981
 	 * @param string $objectUri
979 982
 	 * @param string $calendarData
980 983
 	 * @return string
@@ -1551,7 +1554,7 @@  discard block
 block discarded – undo
1551 1554
 	 * @param string $principalUri
1552 1555
 	 * @param string $uri
1553 1556
 	 * @param array $properties
1554
-	 * @return mixed
1557
+	 * @return integer
1555 1558
 	 */
1556 1559
 	function createSubscription($principalUri, $uri, array $properties) {
1557 1560
 
@@ -2087,6 +2090,9 @@  discard block
 block discarded – undo
2087 2090
 		return (int)$objectIds['id'];
2088 2091
 	}
2089 2092
 
2093
+	/**
2094
+	 * @param boolean $toV2
2095
+	 */
2090 2096
 	private function convertPrincipal($principalUri, $toV2) {
2091 2097
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2092 2098
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Spacing   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197 197
 		}
198 198
 
199
-		return (int)$query->execute()->fetchColumn();
199
+		return (int) $query->execute()->fetchColumn();
200 200
 	}
201 201
 
202 202
 	/**
@@ -243,25 +243,25 @@  discard block
 block discarded – undo
243 243
 		$stmt = $query->execute();
244 244
 
245 245
 		$calendars = [];
246
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
246
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247 247
 
248 248
 			$components = [];
249 249
 			if ($row['components']) {
250
-				$components = explode(',',$row['components']);
250
+				$components = explode(',', $row['components']);
251 251
 			}
252 252
 
253 253
 			$calendar = [
254 254
 				'id' => $row['id'],
255 255
 				'uri' => $row['uri'],
256 256
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
257
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
258
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
259
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
261
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262 262
 			];
263 263
 
264
-			foreach($this->propertyMap as $xmlName=>$dbName) {
264
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
265 265
 				$calendar[$xmlName] = $row[$dbName];
266 266
 			}
267 267
 
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		$principals = array_map(function($principal) {
280 280
 			return urldecode($principal);
281 281
 		}, $principals);
282
-		$principals[]= $principalUri;
282
+		$principals[] = $principalUri;
283 283
 
284 284
 		$fields = array_values($this->propertyMap);
285 285
 		$fields[] = 'a.id';
@@ -299,8 +299,8 @@  discard block
 block discarded – undo
299 299
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300 300
 			->execute();
301 301
 
302
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
-		while($row = $result->fetch()) {
302
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
303
+		while ($row = $result->fetch()) {
304 304
 			if ($row['principaluri'] === $principalUri) {
305 305
 				continue;
306 306
 			}
@@ -319,25 +319,25 @@  discard block
 block discarded – undo
319 319
 			}
320 320
 
321 321
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
322
-			$uri = $row['uri'] . '_shared_by_' . $name;
323
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
322
+			$uri = $row['uri'].'_shared_by_'.$name;
323
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
324 324
 			$components = [];
325 325
 			if ($row['components']) {
326
-				$components = explode(',',$row['components']);
326
+				$components = explode(',', $row['components']);
327 327
 			}
328 328
 			$calendar = [
329 329
 				'id' => $row['id'],
330 330
 				'uri' => $uri,
331 331
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
332
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
333
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
334
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
336
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337 337
 				$readOnlyPropertyName => $readOnly,
338 338
 			];
339 339
 
340
-			foreach($this->propertyMap as $xmlName=>$dbName) {
340
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
341 341
 				$calendar[$xmlName] = $row[$dbName];
342 342
 			}
343 343
 
@@ -366,21 +366,21 @@  discard block
 block discarded – undo
366 366
 			->orderBy('calendarorder', 'ASC');
367 367
 		$stmt = $query->execute();
368 368
 		$calendars = [];
369
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
369
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370 370
 			$components = [];
371 371
 			if ($row['components']) {
372
-				$components = explode(',',$row['components']);
372
+				$components = explode(',', $row['components']);
373 373
 			}
374 374
 			$calendar = [
375 375
 				'id' => $row['id'],
376 376
 				'uri' => $row['uri'],
377 377
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
378
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
379
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
380
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
382 382
 			];
383
-			foreach($this->propertyMap as $xmlName=>$dbName) {
383
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
384 384
 				$calendar[$xmlName] = $row[$dbName];
385 385
 			}
386 386
 
@@ -431,27 +431,27 @@  discard block
 block discarded – undo
431 431
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432 432
 			->execute();
433 433
 
434
-		while($row = $result->fetch()) {
434
+		while ($row = $result->fetch()) {
435 435
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
436
-			$row['displayname'] = $row['displayname'] . "($name)";
436
+			$row['displayname'] = $row['displayname']."($name)";
437 437
 			$components = [];
438 438
 			if ($row['components']) {
439
-				$components = explode(',',$row['components']);
439
+				$components = explode(',', $row['components']);
440 440
 			}
441 441
 			$calendar = [
442 442
 				'id' => $row['id'],
443 443
 				'uri' => $row['publicuri'],
444 444
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
445
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
446
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
447
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
449
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
451
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
452 452
 			];
453 453
 
454
-			foreach($this->propertyMap as $xmlName=>$dbName) {
454
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
455 455
 				$calendar[$xmlName] = $row[$dbName];
456 456
 			}
457 457
 
@@ -495,29 +495,29 @@  discard block
 block discarded – undo
495 495
 		$result->closeCursor();
496 496
 
497 497
 		if ($row === false) {
498
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
498
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
499 499
 		}
500 500
 
501 501
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
502
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
502
+		$row['displayname'] = $row['displayname'].' '."($name)";
503 503
 		$components = [];
504 504
 		if ($row['components']) {
505
-			$components = explode(',',$row['components']);
505
+			$components = explode(',', $row['components']);
506 506
 		}
507 507
 		$calendar = [
508 508
 			'id' => $row['id'],
509 509
 			'uri' => $row['publicuri'],
510 510
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
511
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
512
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
513
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
515
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
517
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
518 518
 		];
519 519
 
520
-		foreach($this->propertyMap as $xmlName=>$dbName) {
520
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
521 521
 			$calendar[$xmlName] = $row[$dbName];
522 522
 		}
523 523
 
@@ -557,20 +557,20 @@  discard block
 block discarded – undo
557 557
 
558 558
 		$components = [];
559 559
 		if ($row['components']) {
560
-			$components = explode(',',$row['components']);
560
+			$components = explode(',', $row['components']);
561 561
 		}
562 562
 
563 563
 		$calendar = [
564 564
 			'id' => $row['id'],
565 565
 			'uri' => $row['uri'],
566 566
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
567
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
568
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
569
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
571 571
 		];
572 572
 
573
-		foreach($this->propertyMap as $xmlName=>$dbName) {
573
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
574 574
 			$calendar[$xmlName] = $row[$dbName];
575 575
 		}
576 576
 
@@ -603,20 +603,20 @@  discard block
 block discarded – undo
603 603
 
604 604
 		$components = [];
605 605
 		if ($row['components']) {
606
-			$components = explode(',',$row['components']);
606
+			$components = explode(',', $row['components']);
607 607
 		}
608 608
 
609 609
 		$calendar = [
610 610
 			'id' => $row['id'],
611 611
 			'uri' => $row['uri'],
612 612
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
613
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
614
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
615
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
617 617
 		];
618 618
 
619
-		foreach($this->propertyMap as $xmlName=>$dbName) {
619
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
620 620
 			$calendar[$xmlName] = $row[$dbName];
621 621
 		}
622 622
 
@@ -650,16 +650,16 @@  discard block
 block discarded – undo
650 650
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
651 651
 		if (isset($properties[$sccs])) {
652 652
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
653
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
653
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
654 654
 			}
655
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
655
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
656 656
 		}
657
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
657
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
658 658
 		if (isset($properties[$transp])) {
659 659
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
660 660
 		}
661 661
 
662
-		foreach($this->propertyMap as $xmlName=>$dbName) {
662
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
663 663
 			if (isset($properties[$xmlName])) {
664 664
 				$values[$dbName] = $properties[$xmlName];
665 665
 			}
@@ -667,7 +667,7 @@  discard block
 block discarded – undo
667 667
 
668 668
 		$query = $this->db->getQueryBuilder();
669 669
 		$query->insert('calendars');
670
-		foreach($values as $column => $value) {
670
+		foreach ($values as $column => $value) {
671 671
 			$query->setValue($column, $query->createNamedParameter($value));
672 672
 		}
673 673
 		$query->execute();
@@ -700,14 +700,14 @@  discard block
 block discarded – undo
700 700
 	 */
701 701
 	function updateCalendar($calendarId, PropPatch $propPatch) {
702 702
 		$supportedProperties = array_keys($this->propertyMap);
703
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
703
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
704 704
 
705 705
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
706 706
 			$newValues = [];
707 707
 			foreach ($mutations as $propertyName => $propertyValue) {
708 708
 
709 709
 				switch ($propertyName) {
710
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
710
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
711 711
 						$fieldName = 'transparent';
712 712
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
713 713
 						break;
@@ -822,16 +822,16 @@  discard block
 block discarded – undo
822 822
 		$stmt = $query->execute();
823 823
 
824 824
 		$result = [];
825
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
825
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
826 826
 			$result[] = [
827 827
 					'id'           => $row['id'],
828 828
 					'uri'          => $row['uri'],
829 829
 					'lastmodified' => $row['lastmodified'],
830
-					'etag'         => '"' . $row['etag'] . '"',
830
+					'etag'         => '"'.$row['etag'].'"',
831 831
 					'calendarid'   => $row['calendarid'],
832
-					'size'         => (int)$row['size'],
832
+					'size'         => (int) $row['size'],
833 833
 					'component'    => strtolower($row['componenttype']),
834
-					'classification'=> (int)$row['classification']
834
+					'classification'=> (int) $row['classification']
835 835
 			];
836 836
 		}
837 837
 
@@ -864,18 +864,18 @@  discard block
 block discarded – undo
864 864
 		$stmt = $query->execute();
865 865
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
866 866
 
867
-		if(!$row) return null;
867
+		if (!$row) return null;
868 868
 
869 869
 		return [
870 870
 				'id'            => $row['id'],
871 871
 				'uri'           => $row['uri'],
872 872
 				'lastmodified'  => $row['lastmodified'],
873
-				'etag'          => '"' . $row['etag'] . '"',
873
+				'etag'          => '"'.$row['etag'].'"',
874 874
 				'calendarid'    => $row['calendarid'],
875
-				'size'          => (int)$row['size'],
875
+				'size'          => (int) $row['size'],
876 876
 				'calendardata'  => $this->readBlob($row['calendardata']),
877 877
 				'component'     => strtolower($row['componenttype']),
878
-				'classification'=> (int)$row['classification']
878
+				'classification'=> (int) $row['classification']
879 879
 		];
880 880
 	}
881 881
 
@@ -914,12 +914,12 @@  discard block
 block discarded – undo
914 914
 					'id'           => $row['id'],
915 915
 					'uri'          => $row['uri'],
916 916
 					'lastmodified' => $row['lastmodified'],
917
-					'etag'         => '"' . $row['etag'] . '"',
917
+					'etag'         => '"'.$row['etag'].'"',
918 918
 					'calendarid'   => $row['calendarid'],
919
-					'size'         => (int)$row['size'],
919
+					'size'         => (int) $row['size'],
920 920
 					'calendardata' => $this->readBlob($row['calendardata']),
921 921
 					'component'    => strtolower($row['componenttype']),
922
-					'classification' => (int)$row['classification']
922
+					'classification' => (int) $row['classification']
923 923
 				];
924 924
 			}
925 925
 			$result->closeCursor();
@@ -992,7 +992,7 @@  discard block
 block discarded – undo
992 992
 		));
993 993
 		$this->addChange($calendarId, $objectUri, 1);
994 994
 
995
-		return '"' . $extraData['etag'] . '"';
995
+		return '"'.$extraData['etag'].'"';
996 996
 	}
997 997
 
998 998
 	/**
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
 		}
1048 1048
 		$this->addChange($calendarId, $objectUri, 2);
1049 1049
 
1050
-		return '"' . $extraData['etag'] . '"';
1050
+		return '"'.$extraData['etag'].'"';
1051 1051
 	}
1052 1052
 
1053 1053
 	/**
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
 		$stmt = $query->execute();
1201 1201
 
1202 1202
 		$result = [];
1203
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1203
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1204 1204
 			if ($requirePostFilter) {
1205 1205
 				if (!$this->validateFilterForObject($row, $filters)) {
1206 1206
 					continue;
@@ -1221,14 +1221,14 @@  discard block
 block discarded – undo
1221 1221
 	 * @param integer|null $offset
1222 1222
 	 * @return array
1223 1223
 	 */
1224
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1224
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1225 1225
 		$calendars = $this->getCalendarsForUser($principalUri);
1226 1226
 		$ownCalendars = [];
1227 1227
 		$sharedCalendars = [];
1228 1228
 
1229 1229
 		$uriMapper = [];
1230 1230
 
1231
-		foreach($calendars as $calendar) {
1231
+		foreach ($calendars as $calendar) {
1232 1232
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1233 1233
 				$ownCalendars[] = $calendar['id'];
1234 1234
 			} else {
@@ -1243,11 +1243,11 @@  discard block
 block discarded – undo
1243 1243
 		$query = $this->db->getQueryBuilder();
1244 1244
 		// Calendar id expressions
1245 1245
 		$calendarExpressions = [];
1246
-		foreach($ownCalendars as $id) {
1246
+		foreach ($ownCalendars as $id) {
1247 1247
 			$calendarExpressions[] = $query->expr()
1248 1248
 				->eq('c.calendarid', $query->createNamedParameter($id));
1249 1249
 		}
1250
-		foreach($sharedCalendars as $id) {
1250
+		foreach ($sharedCalendars as $id) {
1251 1251
 			$calendarExpressions[] = $query->expr()->andX(
1252 1252
 				$query->expr()->eq('c.calendarid',
1253 1253
 					$query->createNamedParameter($id)),
@@ -1264,7 +1264,7 @@  discard block
 block discarded – undo
1264 1264
 
1265 1265
 		// Component expressions
1266 1266
 		$compExpressions = [];
1267
-		foreach($filters['comps'] as $comp) {
1267
+		foreach ($filters['comps'] as $comp) {
1268 1268
 			$compExpressions[] = $query->expr()
1269 1269
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1270 1270
 		}
@@ -1283,13 +1283,13 @@  discard block
 block discarded – undo
1283 1283
 		}
1284 1284
 
1285 1285
 		$propParamExpressions = [];
1286
-		foreach($filters['props'] as $prop) {
1286
+		foreach ($filters['props'] as $prop) {
1287 1287
 			$propParamExpressions[] = $query->expr()->andX(
1288 1288
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1289 1289
 				$query->expr()->isNull('i.parameter')
1290 1290
 			);
1291 1291
 		}
1292
-		foreach($filters['params'] as $param) {
1292
+		foreach ($filters['params'] as $param) {
1293 1293
 			$propParamExpressions[] = $query->expr()->andX(
1294 1294
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1295 1295
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1321,8 +1321,8 @@  discard block
 block discarded – undo
1321 1321
 		$stmt = $query->execute();
1322 1322
 
1323 1323
 		$result = [];
1324
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1325
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1324
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1325
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1326 1326
 			if (!in_array($path, $result)) {
1327 1327
 				$result[] = $path;
1328 1328
 			}
@@ -1362,7 +1362,7 @@  discard block
 block discarded – undo
1362 1362
 		$stmt = $query->execute();
1363 1363
 
1364 1364
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1365
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1365
+			return $row['calendaruri'].'/'.$row['objecturi'];
1366 1366
 		}
1367 1367
 
1368 1368
 		return null;
@@ -1427,7 +1427,7 @@  discard block
 block discarded – undo
1427 1427
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1428 1428
 		// Current synctoken
1429 1429
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1430
-		$stmt->execute([ $calendarId ]);
1430
+		$stmt->execute([$calendarId]);
1431 1431
 		$currentToken = $stmt->fetchColumn(0);
1432 1432
 
1433 1433
 		if (is_null($currentToken)) {
@@ -1444,8 +1444,8 @@  discard block
 block discarded – undo
1444 1444
 		if ($syncToken) {
1445 1445
 
1446 1446
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1447
-			if ($limit>0) {
1448
-				$query.= " LIMIT " . (int)$limit;
1447
+			if ($limit > 0) {
1448
+				$query .= " LIMIT ".(int) $limit;
1449 1449
 			}
1450 1450
 
1451 1451
 			// Fetching all changes
@@ -1456,15 +1456,15 @@  discard block
 block discarded – undo
1456 1456
 
1457 1457
 			// This loop ensures that any duplicates are overwritten, only the
1458 1458
 			// last change on a node is relevant.
1459
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1459
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1460 1460
 
1461 1461
 				$changes[$row['uri']] = $row['operation'];
1462 1462
 
1463 1463
 			}
1464 1464
 
1465
-			foreach($changes as $uri => $operation) {
1465
+			foreach ($changes as $uri => $operation) {
1466 1466
 
1467
-				switch($operation) {
1467
+				switch ($operation) {
1468 1468
 					case 1 :
1469 1469
 						$result['added'][] = $uri;
1470 1470
 						break;
@@ -1534,10 +1534,10 @@  discard block
 block discarded – undo
1534 1534
 			->from('calendarsubscriptions')
1535 1535
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1536 1536
 			->orderBy('calendarorder', 'asc');
1537
-		$stmt =$query->execute();
1537
+		$stmt = $query->execute();
1538 1538
 
1539 1539
 		$subscriptions = [];
1540
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1540
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1541 1541
 
1542 1542
 			$subscription = [
1543 1543
 				'id'           => $row['id'],
@@ -1546,10 +1546,10 @@  discard block
 block discarded – undo
1546 1546
 				'source'       => $row['source'],
1547 1547
 				'lastmodified' => $row['lastmodified'],
1548 1548
 
1549
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1549
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1550 1550
 			];
1551 1551
 
1552
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1552
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1553 1553
 				if (!is_null($row[$dbName])) {
1554 1554
 					$subscription[$xmlName] = $row[$dbName];
1555 1555
 				}
@@ -1588,7 +1588,7 @@  discard block
 block discarded – undo
1588 1588
 
1589 1589
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1590 1590
 
1591
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1591
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1592 1592
 			if (array_key_exists($xmlName, $properties)) {
1593 1593
 					$values[$dbName] = $properties[$xmlName];
1594 1594
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1636,7 +1636,7 @@  discard block
 block discarded – undo
1636 1636
 
1637 1637
 			$newValues = [];
1638 1638
 
1639
-			foreach($mutations as $propertyName=>$propertyValue) {
1639
+			foreach ($mutations as $propertyName=>$propertyValue) {
1640 1640
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1641 1641
 					$newValues['source'] = $propertyValue->getHref();
1642 1642
 				} else {
@@ -1648,7 +1648,7 @@  discard block
 block discarded – undo
1648 1648
 			$query = $this->db->getQueryBuilder();
1649 1649
 			$query->update('calendarsubscriptions')
1650 1650
 				->set('lastmodified', $query->createNamedParameter(time()));
1651
-			foreach($newValues as $fieldName=>$value) {
1651
+			foreach ($newValues as $fieldName=>$value) {
1652 1652
 				$query->set($fieldName, $query->createNamedParameter($value));
1653 1653
 			}
1654 1654
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1698,7 +1698,7 @@  discard block
 block discarded – undo
1698 1698
 
1699 1699
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1700 1700
 
1701
-		if(!$row) {
1701
+		if (!$row) {
1702 1702
 			return null;
1703 1703
 		}
1704 1704
 
@@ -1706,8 +1706,8 @@  discard block
 block discarded – undo
1706 1706
 				'uri'          => $row['uri'],
1707 1707
 				'calendardata' => $row['calendardata'],
1708 1708
 				'lastmodified' => $row['lastmodified'],
1709
-				'etag'         => '"' . $row['etag'] . '"',
1710
-				'size'         => (int)$row['size'],
1709
+				'etag'         => '"'.$row['etag'].'"',
1710
+				'size'         => (int) $row['size'],
1711 1711
 		];
1712 1712
 	}
1713 1713
 
@@ -1730,13 +1730,13 @@  discard block
 block discarded – undo
1730 1730
 				->execute();
1731 1731
 
1732 1732
 		$result = [];
1733
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1733
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1734 1734
 			$result[] = [
1735 1735
 					'calendardata' => $row['calendardata'],
1736 1736
 					'uri'          => $row['uri'],
1737 1737
 					'lastmodified' => $row['lastmodified'],
1738
-					'etag'         => '"' . $row['etag'] . '"',
1739
-					'size'         => (int)$row['size'],
1738
+					'etag'         => '"'.$row['etag'].'"',
1739
+					'size'         => (int) $row['size'],
1740 1740
 			];
1741 1741
 		}
1742 1742
 
@@ -1828,10 +1828,10 @@  discard block
 block discarded – undo
1828 1828
 		$lastOccurrence = null;
1829 1829
 		$uid = null;
1830 1830
 		$classification = self::CLASSIFICATION_PUBLIC;
1831
-		foreach($vObject->getComponents() as $component) {
1832
-			if ($component->name!=='VTIMEZONE') {
1831
+		foreach ($vObject->getComponents() as $component) {
1832
+			if ($component->name !== 'VTIMEZONE') {
1833 1833
 				$componentType = $component->name;
1834
-				$uid = (string)$component->UID;
1834
+				$uid = (string) $component->UID;
1835 1835
 				break;
1836 1836
 			}
1837 1837
 		}
@@ -1856,13 +1856,13 @@  discard block
 block discarded – undo
1856 1856
 					$lastOccurrence = $firstOccurrence;
1857 1857
 				}
1858 1858
 			} else {
1859
-				$it = new EventIterator($vObject, (string)$component->UID);
1859
+				$it = new EventIterator($vObject, (string) $component->UID);
1860 1860
 				$maxDate = new \DateTime(self::MAX_DATE);
1861 1861
 				if ($it->isInfinite()) {
1862 1862
 					$lastOccurrence = $maxDate->getTimestamp();
1863 1863
 				} else {
1864 1864
 					$end = $it->getDtEnd();
1865
-					while($it->valid() && $end < $maxDate) {
1865
+					while ($it->valid() && $end < $maxDate) {
1866 1866
 						$end = $it->getDtEnd();
1867 1867
 						$it->next();
1868 1868
 
@@ -2102,10 +2102,10 @@  discard block
 block discarded – undo
2102 2102
 		$result->closeCursor();
2103 2103
 
2104 2104
 		if (!isset($objectIds['id'])) {
2105
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2105
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2106 2106
 		}
2107 2107
 
2108
-		return (int)$objectIds['id'];
2108
+		return (int) $objectIds['id'];
2109 2109
 	}
2110 2110
 
2111 2111
 	private function convertPrincipal($principalUri, $toV2) {
@@ -2120,8 +2120,8 @@  discard block
 block discarded – undo
2120 2120
 	}
2121 2121
 
2122 2122
 	private function addOwnerPrincipal(&$calendarInfo) {
2123
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2124
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2123
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2124
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2125 2125
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2126 2126
 			$uri = $calendarInfo[$ownerPrincipalKey];
2127 2127
 		} else {
Please login to merge, or discard this patch.
Indentation   +2070 added lines, -2070 removed lines patch added patch discarded remove patch
@@ -62,2075 +62,2075 @@
 block discarded – undo
62 62
  */
63 63
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
64 64
 
65
-	const PERSONAL_CALENDAR_URI = 'personal';
66
-	const PERSONAL_CALENDAR_NAME = 'Personal';
67
-
68
-	/**
69
-	 * We need to specify a max date, because we need to stop *somewhere*
70
-	 *
71
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
72
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
73
-	 * in 2038-01-19 to avoid problems when the date is converted
74
-	 * to a unix timestamp.
75
-	 */
76
-	const MAX_DATE = '2038-01-01';
77
-
78
-	const ACCESS_PUBLIC = 4;
79
-	const CLASSIFICATION_PUBLIC = 0;
80
-	const CLASSIFICATION_PRIVATE = 1;
81
-	const CLASSIFICATION_CONFIDENTIAL = 2;
82
-
83
-	/**
84
-	 * List of CalDAV properties, and how they map to database field names
85
-	 * Add your own properties by simply adding on to this array.
86
-	 *
87
-	 * Note that only string-based properties are supported here.
88
-	 *
89
-	 * @var array
90
-	 */
91
-	public $propertyMap = [
92
-		'{DAV:}displayname'                          => 'displayname',
93
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
94
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
95
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
96
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
97
-	];
98
-
99
-	/**
100
-	 * List of subscription properties, and how they map to database field names.
101
-	 *
102
-	 * @var array
103
-	 */
104
-	public $subscriptionPropertyMap = [
105
-		'{DAV:}displayname'                                           => 'displayname',
106
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
107
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
108
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
109
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
110
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
111
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
112
-	];
113
-
114
-	/** @var array properties to index */
115
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
116
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
117
-		'ORGANIZER'];
118
-
119
-	/** @var array parameters to index */
120
-	public static $indexParameters = [
121
-		'ATTENDEE' => ['CN'],
122
-		'ORGANIZER' => ['CN'],
123
-	];
124
-
125
-	/**
126
-	 * @var string[] Map of uid => display name
127
-	 */
128
-	protected $userDisplayNames;
129
-
130
-	/** @var IDBConnection */
131
-	private $db;
132
-
133
-	/** @var Backend */
134
-	private $sharingBackend;
135
-
136
-	/** @var Principal */
137
-	private $principalBackend;
138
-
139
-	/** @var IUserManager */
140
-	private $userManager;
141
-
142
-	/** @var ISecureRandom */
143
-	private $random;
144
-
145
-	/** @var EventDispatcherInterface */
146
-	private $dispatcher;
147
-
148
-	/** @var bool */
149
-	private $legacyEndpoint;
150
-
151
-	/** @var string */
152
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
153
-
154
-	/**
155
-	 * CalDavBackend constructor.
156
-	 *
157
-	 * @param IDBConnection $db
158
-	 * @param Principal $principalBackend
159
-	 * @param IUserManager $userManager
160
-	 * @param ISecureRandom $random
161
-	 * @param EventDispatcherInterface $dispatcher
162
-	 * @param bool $legacyEndpoint
163
-	 */
164
-	public function __construct(IDBConnection $db,
165
-								Principal $principalBackend,
166
-								IUserManager $userManager,
167
-								ISecureRandom $random,
168
-								EventDispatcherInterface $dispatcher,
169
-								$legacyEndpoint = false) {
170
-		$this->db = $db;
171
-		$this->principalBackend = $principalBackend;
172
-		$this->userManager = $userManager;
173
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
174
-		$this->random = $random;
175
-		$this->dispatcher = $dispatcher;
176
-		$this->legacyEndpoint = $legacyEndpoint;
177
-	}
178
-
179
-	/**
180
-	 * Return the number of calendars for a principal
181
-	 *
182
-	 * By default this excludes the automatically generated birthday calendar
183
-	 *
184
-	 * @param $principalUri
185
-	 * @param bool $excludeBirthday
186
-	 * @return int
187
-	 */
188
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
189
-		$principalUri = $this->convertPrincipal($principalUri, true);
190
-		$query = $this->db->getQueryBuilder();
191
-		$query->select($query->createFunction('COUNT(*)'))
192
-			->from('calendars')
193
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
194
-
195
-		if ($excludeBirthday) {
196
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197
-		}
198
-
199
-		return (int)$query->execute()->fetchColumn();
200
-	}
201
-
202
-	/**
203
-	 * Returns a list of calendars for a principal.
204
-	 *
205
-	 * Every project is an array with the following keys:
206
-	 *  * id, a unique id that will be used by other functions to modify the
207
-	 *    calendar. This can be the same as the uri or a database key.
208
-	 *  * uri, which the basename of the uri with which the calendar is
209
-	 *    accessed.
210
-	 *  * principaluri. The owner of the calendar. Almost always the same as
211
-	 *    principalUri passed to this method.
212
-	 *
213
-	 * Furthermore it can contain webdav properties in clark notation. A very
214
-	 * common one is '{DAV:}displayname'.
215
-	 *
216
-	 * Many clients also require:
217
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
218
-	 * For this property, you can just return an instance of
219
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
220
-	 *
221
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
222
-	 * ACL will automatically be put in read-only mode.
223
-	 *
224
-	 * @param string $principalUri
225
-	 * @return array
226
-	 */
227
-	function getCalendarsForUser($principalUri) {
228
-		$principalUriOriginal = $principalUri;
229
-		$principalUri = $this->convertPrincipal($principalUri, true);
230
-		$fields = array_values($this->propertyMap);
231
-		$fields[] = 'id';
232
-		$fields[] = 'uri';
233
-		$fields[] = 'synctoken';
234
-		$fields[] = 'components';
235
-		$fields[] = 'principaluri';
236
-		$fields[] = 'transparent';
237
-
238
-		// Making fields a comma-delimited list
239
-		$query = $this->db->getQueryBuilder();
240
-		$query->select($fields)->from('calendars')
241
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
242
-				->orderBy('calendarorder', 'ASC');
243
-		$stmt = $query->execute();
244
-
245
-		$calendars = [];
246
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247
-
248
-			$components = [];
249
-			if ($row['components']) {
250
-				$components = explode(',',$row['components']);
251
-			}
252
-
253
-			$calendar = [
254
-				'id' => $row['id'],
255
-				'uri' => $row['uri'],
256
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262
-			];
263
-
264
-			foreach($this->propertyMap as $xmlName=>$dbName) {
265
-				$calendar[$xmlName] = $row[$dbName];
266
-			}
267
-
268
-			$this->addOwnerPrincipal($calendar);
269
-
270
-			if (!isset($calendars[$calendar['id']])) {
271
-				$calendars[$calendar['id']] = $calendar;
272
-			}
273
-		}
274
-
275
-		$stmt->closeCursor();
276
-
277
-		// query for shared calendars
278
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
279
-		$principals = array_map(function($principal) {
280
-			return urldecode($principal);
281
-		}, $principals);
282
-		$principals[]= $principalUri;
283
-
284
-		$fields = array_values($this->propertyMap);
285
-		$fields[] = 'a.id';
286
-		$fields[] = 'a.uri';
287
-		$fields[] = 'a.synctoken';
288
-		$fields[] = 'a.components';
289
-		$fields[] = 'a.principaluri';
290
-		$fields[] = 'a.transparent';
291
-		$fields[] = 's.access';
292
-		$query = $this->db->getQueryBuilder();
293
-		$result = $query->select($fields)
294
-			->from('dav_shares', 's')
295
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
296
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
297
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
298
-			->setParameter('type', 'calendar')
299
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300
-			->execute();
301
-
302
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
-		while($row = $result->fetch()) {
304
-			if ($row['principaluri'] === $principalUri) {
305
-				continue;
306
-			}
307
-
308
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
309
-			if (isset($calendars[$row['id']])) {
310
-				if ($readOnly) {
311
-					// New share can not have more permissions then the old one.
312
-					continue;
313
-				}
314
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
315
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
316
-					// Old share is already read-write, no more permissions can be gained
317
-					continue;
318
-				}
319
-			}
320
-
321
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
322
-			$uri = $row['uri'] . '_shared_by_' . $name;
323
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
324
-			$components = [];
325
-			if ($row['components']) {
326
-				$components = explode(',',$row['components']);
327
-			}
328
-			$calendar = [
329
-				'id' => $row['id'],
330
-				'uri' => $uri,
331
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
-				$readOnlyPropertyName => $readOnly,
338
-			];
339
-
340
-			foreach($this->propertyMap as $xmlName=>$dbName) {
341
-				$calendar[$xmlName] = $row[$dbName];
342
-			}
343
-
344
-			$this->addOwnerPrincipal($calendar);
345
-
346
-			$calendars[$calendar['id']] = $calendar;
347
-		}
348
-		$result->closeCursor();
349
-
350
-		return array_values($calendars);
351
-	}
352
-
353
-	public function getUsersOwnCalendars($principalUri) {
354
-		$principalUri = $this->convertPrincipal($principalUri, true);
355
-		$fields = array_values($this->propertyMap);
356
-		$fields[] = 'id';
357
-		$fields[] = 'uri';
358
-		$fields[] = 'synctoken';
359
-		$fields[] = 'components';
360
-		$fields[] = 'principaluri';
361
-		$fields[] = 'transparent';
362
-		// Making fields a comma-delimited list
363
-		$query = $this->db->getQueryBuilder();
364
-		$query->select($fields)->from('calendars')
365
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
366
-			->orderBy('calendarorder', 'ASC');
367
-		$stmt = $query->execute();
368
-		$calendars = [];
369
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370
-			$components = [];
371
-			if ($row['components']) {
372
-				$components = explode(',',$row['components']);
373
-			}
374
-			$calendar = [
375
-				'id' => $row['id'],
376
-				'uri' => $row['uri'],
377
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
382
-			];
383
-			foreach($this->propertyMap as $xmlName=>$dbName) {
384
-				$calendar[$xmlName] = $row[$dbName];
385
-			}
386
-
387
-			$this->addOwnerPrincipal($calendar);
388
-
389
-			if (!isset($calendars[$calendar['id']])) {
390
-				$calendars[$calendar['id']] = $calendar;
391
-			}
392
-		}
393
-		$stmt->closeCursor();
394
-		return array_values($calendars);
395
-	}
396
-
397
-
398
-	private function getUserDisplayName($uid) {
399
-		if (!isset($this->userDisplayNames[$uid])) {
400
-			$user = $this->userManager->get($uid);
401
-
402
-			if ($user instanceof IUser) {
403
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
404
-			} else {
405
-				$this->userDisplayNames[$uid] = $uid;
406
-			}
407
-		}
408
-
409
-		return $this->userDisplayNames[$uid];
410
-	}
65
+    const PERSONAL_CALENDAR_URI = 'personal';
66
+    const PERSONAL_CALENDAR_NAME = 'Personal';
67
+
68
+    /**
69
+     * We need to specify a max date, because we need to stop *somewhere*
70
+     *
71
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
72
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
73
+     * in 2038-01-19 to avoid problems when the date is converted
74
+     * to a unix timestamp.
75
+     */
76
+    const MAX_DATE = '2038-01-01';
77
+
78
+    const ACCESS_PUBLIC = 4;
79
+    const CLASSIFICATION_PUBLIC = 0;
80
+    const CLASSIFICATION_PRIVATE = 1;
81
+    const CLASSIFICATION_CONFIDENTIAL = 2;
82
+
83
+    /**
84
+     * List of CalDAV properties, and how they map to database field names
85
+     * Add your own properties by simply adding on to this array.
86
+     *
87
+     * Note that only string-based properties are supported here.
88
+     *
89
+     * @var array
90
+     */
91
+    public $propertyMap = [
92
+        '{DAV:}displayname'                          => 'displayname',
93
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
94
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
95
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
96
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
97
+    ];
98
+
99
+    /**
100
+     * List of subscription properties, and how they map to database field names.
101
+     *
102
+     * @var array
103
+     */
104
+    public $subscriptionPropertyMap = [
105
+        '{DAV:}displayname'                                           => 'displayname',
106
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
107
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
108
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
109
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
110
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
111
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
112
+    ];
113
+
114
+    /** @var array properties to index */
115
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
116
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
117
+        'ORGANIZER'];
118
+
119
+    /** @var array parameters to index */
120
+    public static $indexParameters = [
121
+        'ATTENDEE' => ['CN'],
122
+        'ORGANIZER' => ['CN'],
123
+    ];
124
+
125
+    /**
126
+     * @var string[] Map of uid => display name
127
+     */
128
+    protected $userDisplayNames;
129
+
130
+    /** @var IDBConnection */
131
+    private $db;
132
+
133
+    /** @var Backend */
134
+    private $sharingBackend;
135
+
136
+    /** @var Principal */
137
+    private $principalBackend;
138
+
139
+    /** @var IUserManager */
140
+    private $userManager;
141
+
142
+    /** @var ISecureRandom */
143
+    private $random;
144
+
145
+    /** @var EventDispatcherInterface */
146
+    private $dispatcher;
147
+
148
+    /** @var bool */
149
+    private $legacyEndpoint;
150
+
151
+    /** @var string */
152
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
153
+
154
+    /**
155
+     * CalDavBackend constructor.
156
+     *
157
+     * @param IDBConnection $db
158
+     * @param Principal $principalBackend
159
+     * @param IUserManager $userManager
160
+     * @param ISecureRandom $random
161
+     * @param EventDispatcherInterface $dispatcher
162
+     * @param bool $legacyEndpoint
163
+     */
164
+    public function __construct(IDBConnection $db,
165
+                                Principal $principalBackend,
166
+                                IUserManager $userManager,
167
+                                ISecureRandom $random,
168
+                                EventDispatcherInterface $dispatcher,
169
+                                $legacyEndpoint = false) {
170
+        $this->db = $db;
171
+        $this->principalBackend = $principalBackend;
172
+        $this->userManager = $userManager;
173
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
174
+        $this->random = $random;
175
+        $this->dispatcher = $dispatcher;
176
+        $this->legacyEndpoint = $legacyEndpoint;
177
+    }
178
+
179
+    /**
180
+     * Return the number of calendars for a principal
181
+     *
182
+     * By default this excludes the automatically generated birthday calendar
183
+     *
184
+     * @param $principalUri
185
+     * @param bool $excludeBirthday
186
+     * @return int
187
+     */
188
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
189
+        $principalUri = $this->convertPrincipal($principalUri, true);
190
+        $query = $this->db->getQueryBuilder();
191
+        $query->select($query->createFunction('COUNT(*)'))
192
+            ->from('calendars')
193
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
194
+
195
+        if ($excludeBirthday) {
196
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
197
+        }
198
+
199
+        return (int)$query->execute()->fetchColumn();
200
+    }
201
+
202
+    /**
203
+     * Returns a list of calendars for a principal.
204
+     *
205
+     * Every project is an array with the following keys:
206
+     *  * id, a unique id that will be used by other functions to modify the
207
+     *    calendar. This can be the same as the uri or a database key.
208
+     *  * uri, which the basename of the uri with which the calendar is
209
+     *    accessed.
210
+     *  * principaluri. The owner of the calendar. Almost always the same as
211
+     *    principalUri passed to this method.
212
+     *
213
+     * Furthermore it can contain webdav properties in clark notation. A very
214
+     * common one is '{DAV:}displayname'.
215
+     *
216
+     * Many clients also require:
217
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
218
+     * For this property, you can just return an instance of
219
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
220
+     *
221
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
222
+     * ACL will automatically be put in read-only mode.
223
+     *
224
+     * @param string $principalUri
225
+     * @return array
226
+     */
227
+    function getCalendarsForUser($principalUri) {
228
+        $principalUriOriginal = $principalUri;
229
+        $principalUri = $this->convertPrincipal($principalUri, true);
230
+        $fields = array_values($this->propertyMap);
231
+        $fields[] = 'id';
232
+        $fields[] = 'uri';
233
+        $fields[] = 'synctoken';
234
+        $fields[] = 'components';
235
+        $fields[] = 'principaluri';
236
+        $fields[] = 'transparent';
237
+
238
+        // Making fields a comma-delimited list
239
+        $query = $this->db->getQueryBuilder();
240
+        $query->select($fields)->from('calendars')
241
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
242
+                ->orderBy('calendarorder', 'ASC');
243
+        $stmt = $query->execute();
244
+
245
+        $calendars = [];
246
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
247
+
248
+            $components = [];
249
+            if ($row['components']) {
250
+                $components = explode(',',$row['components']);
251
+            }
252
+
253
+            $calendar = [
254
+                'id' => $row['id'],
255
+                'uri' => $row['uri'],
256
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
257
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
258
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
259
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
260
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
261
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
262
+            ];
263
+
264
+            foreach($this->propertyMap as $xmlName=>$dbName) {
265
+                $calendar[$xmlName] = $row[$dbName];
266
+            }
267
+
268
+            $this->addOwnerPrincipal($calendar);
269
+
270
+            if (!isset($calendars[$calendar['id']])) {
271
+                $calendars[$calendar['id']] = $calendar;
272
+            }
273
+        }
274
+
275
+        $stmt->closeCursor();
276
+
277
+        // query for shared calendars
278
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
279
+        $principals = array_map(function($principal) {
280
+            return urldecode($principal);
281
+        }, $principals);
282
+        $principals[]= $principalUri;
283
+
284
+        $fields = array_values($this->propertyMap);
285
+        $fields[] = 'a.id';
286
+        $fields[] = 'a.uri';
287
+        $fields[] = 'a.synctoken';
288
+        $fields[] = 'a.components';
289
+        $fields[] = 'a.principaluri';
290
+        $fields[] = 'a.transparent';
291
+        $fields[] = 's.access';
292
+        $query = $this->db->getQueryBuilder();
293
+        $result = $query->select($fields)
294
+            ->from('dav_shares', 's')
295
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
296
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
297
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
298
+            ->setParameter('type', 'calendar')
299
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
300
+            ->execute();
301
+
302
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
303
+        while($row = $result->fetch()) {
304
+            if ($row['principaluri'] === $principalUri) {
305
+                continue;
306
+            }
307
+
308
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
309
+            if (isset($calendars[$row['id']])) {
310
+                if ($readOnly) {
311
+                    // New share can not have more permissions then the old one.
312
+                    continue;
313
+                }
314
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
315
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
316
+                    // Old share is already read-write, no more permissions can be gained
317
+                    continue;
318
+                }
319
+            }
320
+
321
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
322
+            $uri = $row['uri'] . '_shared_by_' . $name;
323
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
324
+            $components = [];
325
+            if ($row['components']) {
326
+                $components = explode(',',$row['components']);
327
+            }
328
+            $calendar = [
329
+                'id' => $row['id'],
330
+                'uri' => $uri,
331
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
332
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
333
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
334
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
335
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
336
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
337
+                $readOnlyPropertyName => $readOnly,
338
+            ];
339
+
340
+            foreach($this->propertyMap as $xmlName=>$dbName) {
341
+                $calendar[$xmlName] = $row[$dbName];
342
+            }
343
+
344
+            $this->addOwnerPrincipal($calendar);
345
+
346
+            $calendars[$calendar['id']] = $calendar;
347
+        }
348
+        $result->closeCursor();
349
+
350
+        return array_values($calendars);
351
+    }
352
+
353
+    public function getUsersOwnCalendars($principalUri) {
354
+        $principalUri = $this->convertPrincipal($principalUri, true);
355
+        $fields = array_values($this->propertyMap);
356
+        $fields[] = 'id';
357
+        $fields[] = 'uri';
358
+        $fields[] = 'synctoken';
359
+        $fields[] = 'components';
360
+        $fields[] = 'principaluri';
361
+        $fields[] = 'transparent';
362
+        // Making fields a comma-delimited list
363
+        $query = $this->db->getQueryBuilder();
364
+        $query->select($fields)->from('calendars')
365
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
366
+            ->orderBy('calendarorder', 'ASC');
367
+        $stmt = $query->execute();
368
+        $calendars = [];
369
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
370
+            $components = [];
371
+            if ($row['components']) {
372
+                $components = explode(',',$row['components']);
373
+            }
374
+            $calendar = [
375
+                'id' => $row['id'],
376
+                'uri' => $row['uri'],
377
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
378
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
379
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
380
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
381
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
382
+            ];
383
+            foreach($this->propertyMap as $xmlName=>$dbName) {
384
+                $calendar[$xmlName] = $row[$dbName];
385
+            }
386
+
387
+            $this->addOwnerPrincipal($calendar);
388
+
389
+            if (!isset($calendars[$calendar['id']])) {
390
+                $calendars[$calendar['id']] = $calendar;
391
+            }
392
+        }
393
+        $stmt->closeCursor();
394
+        return array_values($calendars);
395
+    }
396
+
397
+
398
+    private function getUserDisplayName($uid) {
399
+        if (!isset($this->userDisplayNames[$uid])) {
400
+            $user = $this->userManager->get($uid);
401
+
402
+            if ($user instanceof IUser) {
403
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
404
+            } else {
405
+                $this->userDisplayNames[$uid] = $uid;
406
+            }
407
+        }
408
+
409
+        return $this->userDisplayNames[$uid];
410
+    }
411 411
 	
412
-	/**
413
-	 * @return array
414
-	 */
415
-	public function getPublicCalendars() {
416
-		$fields = array_values($this->propertyMap);
417
-		$fields[] = 'a.id';
418
-		$fields[] = 'a.uri';
419
-		$fields[] = 'a.synctoken';
420
-		$fields[] = 'a.components';
421
-		$fields[] = 'a.principaluri';
422
-		$fields[] = 'a.transparent';
423
-		$fields[] = 's.access';
424
-		$fields[] = 's.publicuri';
425
-		$calendars = [];
426
-		$query = $this->db->getQueryBuilder();
427
-		$result = $query->select($fields)
428
-			->from('dav_shares', 's')
429
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
430
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
431
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432
-			->execute();
433
-
434
-		while($row = $result->fetch()) {
435
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
436
-			$row['displayname'] = $row['displayname'] . "($name)";
437
-			$components = [];
438
-			if ($row['components']) {
439
-				$components = explode(',',$row['components']);
440
-			}
441
-			$calendar = [
442
-				'id' => $row['id'],
443
-				'uri' => $row['publicuri'],
444
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
452
-			];
453
-
454
-			foreach($this->propertyMap as $xmlName=>$dbName) {
455
-				$calendar[$xmlName] = $row[$dbName];
456
-			}
457
-
458
-			$this->addOwnerPrincipal($calendar);
459
-
460
-			if (!isset($calendars[$calendar['id']])) {
461
-				$calendars[$calendar['id']] = $calendar;
462
-			}
463
-		}
464
-		$result->closeCursor();
465
-
466
-		return array_values($calendars);
467
-	}
468
-
469
-	/**
470
-	 * @param string $uri
471
-	 * @return array
472
-	 * @throws NotFound
473
-	 */
474
-	public function getPublicCalendar($uri) {
475
-		$fields = array_values($this->propertyMap);
476
-		$fields[] = 'a.id';
477
-		$fields[] = 'a.uri';
478
-		$fields[] = 'a.synctoken';
479
-		$fields[] = 'a.components';
480
-		$fields[] = 'a.principaluri';
481
-		$fields[] = 'a.transparent';
482
-		$fields[] = 's.access';
483
-		$fields[] = 's.publicuri';
484
-		$query = $this->db->getQueryBuilder();
485
-		$result = $query->select($fields)
486
-			->from('dav_shares', 's')
487
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
488
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
489
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
490
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
491
-			->execute();
492
-
493
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
494
-
495
-		$result->closeCursor();
496
-
497
-		if ($row === false) {
498
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
499
-		}
500
-
501
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
502
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
503
-		$components = [];
504
-		if ($row['components']) {
505
-			$components = explode(',',$row['components']);
506
-		}
507
-		$calendar = [
508
-			'id' => $row['id'],
509
-			'uri' => $row['publicuri'],
510
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
518
-		];
519
-
520
-		foreach($this->propertyMap as $xmlName=>$dbName) {
521
-			$calendar[$xmlName] = $row[$dbName];
522
-		}
523
-
524
-		$this->addOwnerPrincipal($calendar);
525
-
526
-		return $calendar;
527
-
528
-	}
529
-
530
-	/**
531
-	 * @param string $principal
532
-	 * @param string $uri
533
-	 * @return array|null
534
-	 */
535
-	public function getCalendarByUri($principal, $uri) {
536
-		$fields = array_values($this->propertyMap);
537
-		$fields[] = 'id';
538
-		$fields[] = 'uri';
539
-		$fields[] = 'synctoken';
540
-		$fields[] = 'components';
541
-		$fields[] = 'principaluri';
542
-		$fields[] = 'transparent';
543
-
544
-		// Making fields a comma-delimited list
545
-		$query = $this->db->getQueryBuilder();
546
-		$query->select($fields)->from('calendars')
547
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
548
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
549
-			->setMaxResults(1);
550
-		$stmt = $query->execute();
551
-
552
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
553
-		$stmt->closeCursor();
554
-		if ($row === false) {
555
-			return null;
556
-		}
557
-
558
-		$components = [];
559
-		if ($row['components']) {
560
-			$components = explode(',',$row['components']);
561
-		}
562
-
563
-		$calendar = [
564
-			'id' => $row['id'],
565
-			'uri' => $row['uri'],
566
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
571
-		];
572
-
573
-		foreach($this->propertyMap as $xmlName=>$dbName) {
574
-			$calendar[$xmlName] = $row[$dbName];
575
-		}
576
-
577
-		$this->addOwnerPrincipal($calendar);
578
-
579
-		return $calendar;
580
-	}
581
-
582
-	public function getCalendarById($calendarId) {
583
-		$fields = array_values($this->propertyMap);
584
-		$fields[] = 'id';
585
-		$fields[] = 'uri';
586
-		$fields[] = 'synctoken';
587
-		$fields[] = 'components';
588
-		$fields[] = 'principaluri';
589
-		$fields[] = 'transparent';
590
-
591
-		// Making fields a comma-delimited list
592
-		$query = $this->db->getQueryBuilder();
593
-		$query->select($fields)->from('calendars')
594
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
595
-			->setMaxResults(1);
596
-		$stmt = $query->execute();
597
-
598
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
599
-		$stmt->closeCursor();
600
-		if ($row === false) {
601
-			return null;
602
-		}
603
-
604
-		$components = [];
605
-		if ($row['components']) {
606
-			$components = explode(',',$row['components']);
607
-		}
608
-
609
-		$calendar = [
610
-			'id' => $row['id'],
611
-			'uri' => $row['uri'],
612
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
617
-		];
618
-
619
-		foreach($this->propertyMap as $xmlName=>$dbName) {
620
-			$calendar[$xmlName] = $row[$dbName];
621
-		}
622
-
623
-		$this->addOwnerPrincipal($calendar);
624
-
625
-		return $calendar;
626
-	}
627
-
628
-	/**
629
-	 * Creates a new calendar for a principal.
630
-	 *
631
-	 * If the creation was a success, an id must be returned that can be used to reference
632
-	 * this calendar in other methods, such as updateCalendar.
633
-	 *
634
-	 * @param string $principalUri
635
-	 * @param string $calendarUri
636
-	 * @param array $properties
637
-	 * @return int
638
-	 */
639
-	function createCalendar($principalUri, $calendarUri, array $properties) {
640
-		$values = [
641
-			'principaluri' => $this->convertPrincipal($principalUri, true),
642
-			'uri'          => $calendarUri,
643
-			'synctoken'    => 1,
644
-			'transparent'  => 0,
645
-			'components'   => 'VEVENT,VTODO',
646
-			'displayname'  => $calendarUri
647
-		];
648
-
649
-		// Default value
650
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
651
-		if (isset($properties[$sccs])) {
652
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
653
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
654
-			}
655
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
656
-		}
657
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
658
-		if (isset($properties[$transp])) {
659
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
660
-		}
661
-
662
-		foreach($this->propertyMap as $xmlName=>$dbName) {
663
-			if (isset($properties[$xmlName])) {
664
-				$values[$dbName] = $properties[$xmlName];
665
-			}
666
-		}
667
-
668
-		$query = $this->db->getQueryBuilder();
669
-		$query->insert('calendars');
670
-		foreach($values as $column => $value) {
671
-			$query->setValue($column, $query->createNamedParameter($value));
672
-		}
673
-		$query->execute();
674
-		$calendarId = $query->getLastInsertId();
675
-
676
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
677
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
678
-			[
679
-				'calendarId' => $calendarId,
680
-				'calendarData' => $this->getCalendarById($calendarId),
681
-		]));
682
-
683
-		return $calendarId;
684
-	}
685
-
686
-	/**
687
-	 * Updates properties for a calendar.
688
-	 *
689
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
690
-	 * To do the actual updates, you must tell this object which properties
691
-	 * you're going to process with the handle() method.
692
-	 *
693
-	 * Calling the handle method is like telling the PropPatch object "I
694
-	 * promise I can handle updating this property".
695
-	 *
696
-	 * Read the PropPatch documentation for more info and examples.
697
-	 *
698
-	 * @param PropPatch $propPatch
699
-	 * @return void
700
-	 */
701
-	function updateCalendar($calendarId, PropPatch $propPatch) {
702
-		$supportedProperties = array_keys($this->propertyMap);
703
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
704
-
705
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
706
-			$newValues = [];
707
-			foreach ($mutations as $propertyName => $propertyValue) {
708
-
709
-				switch ($propertyName) {
710
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
711
-						$fieldName = 'transparent';
712
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
713
-						break;
714
-					default :
715
-						$fieldName = $this->propertyMap[$propertyName];
716
-						$newValues[$fieldName] = $propertyValue;
717
-						break;
718
-				}
719
-
720
-			}
721
-			$query = $this->db->getQueryBuilder();
722
-			$query->update('calendars');
723
-			foreach ($newValues as $fieldName => $value) {
724
-				$query->set($fieldName, $query->createNamedParameter($value));
725
-			}
726
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
727
-			$query->execute();
728
-
729
-			$this->addChange($calendarId, "", 2);
730
-
731
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
732
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
733
-				[
734
-					'calendarId' => $calendarId,
735
-					'calendarData' => $this->getCalendarById($calendarId),
736
-					'shares' => $this->getShares($calendarId),
737
-					'propertyMutations' => $mutations,
738
-			]));
739
-
740
-			return true;
741
-		});
742
-	}
743
-
744
-	/**
745
-	 * Delete a calendar and all it's objects
746
-	 *
747
-	 * @param mixed $calendarId
748
-	 * @return void
749
-	 */
750
-	function deleteCalendar($calendarId) {
751
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
752
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
753
-			[
754
-				'calendarId' => $calendarId,
755
-				'calendarData' => $this->getCalendarById($calendarId),
756
-				'shares' => $this->getShares($calendarId),
757
-		]));
758
-
759
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
760
-		$stmt->execute([$calendarId]);
761
-
762
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
763
-		$stmt->execute([$calendarId]);
764
-
765
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
766
-		$stmt->execute([$calendarId]);
767
-
768
-		$this->sharingBackend->deleteAllShares($calendarId);
769
-
770
-		$query = $this->db->getQueryBuilder();
771
-		$query->delete($this->dbObjectPropertiesTable)
772
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
773
-			->execute();
774
-	}
775
-
776
-	/**
777
-	 * Delete all of an user's shares
778
-	 *
779
-	 * @param string $principaluri
780
-	 * @return void
781
-	 */
782
-	function deleteAllSharesByUser($principaluri) {
783
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
784
-	}
785
-
786
-	/**
787
-	 * Returns all calendar objects within a calendar.
788
-	 *
789
-	 * Every item contains an array with the following keys:
790
-	 *   * calendardata - The iCalendar-compatible calendar data
791
-	 *   * uri - a unique key which will be used to construct the uri. This can
792
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
793
-	 *     good idea. This is only the basename, or filename, not the full
794
-	 *     path.
795
-	 *   * lastmodified - a timestamp of the last modification time
796
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
797
-	 *   '"abcdef"')
798
-	 *   * size - The size of the calendar objects, in bytes.
799
-	 *   * component - optional, a string containing the type of object, such
800
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
801
-	 *     the Content-Type header.
802
-	 *
803
-	 * Note that the etag is optional, but it's highly encouraged to return for
804
-	 * speed reasons.
805
-	 *
806
-	 * The calendardata is also optional. If it's not returned
807
-	 * 'getCalendarObject' will be called later, which *is* expected to return
808
-	 * calendardata.
809
-	 *
810
-	 * If neither etag or size are specified, the calendardata will be
811
-	 * used/fetched to determine these numbers. If both are specified the
812
-	 * amount of times this is needed is reduced by a great degree.
813
-	 *
814
-	 * @param mixed $calendarId
815
-	 * @return array
816
-	 */
817
-	function getCalendarObjects($calendarId) {
818
-		$query = $this->db->getQueryBuilder();
819
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
820
-			->from('calendarobjects')
821
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
822
-		$stmt = $query->execute();
823
-
824
-		$result = [];
825
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
826
-			$result[] = [
827
-					'id'           => $row['id'],
828
-					'uri'          => $row['uri'],
829
-					'lastmodified' => $row['lastmodified'],
830
-					'etag'         => '"' . $row['etag'] . '"',
831
-					'calendarid'   => $row['calendarid'],
832
-					'size'         => (int)$row['size'],
833
-					'component'    => strtolower($row['componenttype']),
834
-					'classification'=> (int)$row['classification']
835
-			];
836
-		}
837
-
838
-		return $result;
839
-	}
840
-
841
-	/**
842
-	 * Returns information from a single calendar object, based on it's object
843
-	 * uri.
844
-	 *
845
-	 * The object uri is only the basename, or filename and not a full path.
846
-	 *
847
-	 * The returned array must have the same keys as getCalendarObjects. The
848
-	 * 'calendardata' object is required here though, while it's not required
849
-	 * for getCalendarObjects.
850
-	 *
851
-	 * This method must return null if the object did not exist.
852
-	 *
853
-	 * @param mixed $calendarId
854
-	 * @param string $objectUri
855
-	 * @return array|null
856
-	 */
857
-	function getCalendarObject($calendarId, $objectUri) {
858
-
859
-		$query = $this->db->getQueryBuilder();
860
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
861
-				->from('calendarobjects')
862
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
863
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
864
-		$stmt = $query->execute();
865
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
866
-
867
-		if(!$row) return null;
868
-
869
-		return [
870
-				'id'            => $row['id'],
871
-				'uri'           => $row['uri'],
872
-				'lastmodified'  => $row['lastmodified'],
873
-				'etag'          => '"' . $row['etag'] . '"',
874
-				'calendarid'    => $row['calendarid'],
875
-				'size'          => (int)$row['size'],
876
-				'calendardata'  => $this->readBlob($row['calendardata']),
877
-				'component'     => strtolower($row['componenttype']),
878
-				'classification'=> (int)$row['classification']
879
-		];
880
-	}
881
-
882
-	/**
883
-	 * Returns a list of calendar objects.
884
-	 *
885
-	 * This method should work identical to getCalendarObject, but instead
886
-	 * return all the calendar objects in the list as an array.
887
-	 *
888
-	 * If the backend supports this, it may allow for some speed-ups.
889
-	 *
890
-	 * @param mixed $calendarId
891
-	 * @param string[] $uris
892
-	 * @return array
893
-	 */
894
-	function getMultipleCalendarObjects($calendarId, array $uris) {
895
-		if (empty($uris)) {
896
-			return [];
897
-		}
898
-
899
-		$chunks = array_chunk($uris, 100);
900
-		$objects = [];
901
-
902
-		$query = $this->db->getQueryBuilder();
903
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
904
-			->from('calendarobjects')
905
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
906
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
907
-
908
-		foreach ($chunks as $uris) {
909
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
910
-			$result = $query->execute();
911
-
912
-			while ($row = $result->fetch()) {
913
-				$objects[] = [
914
-					'id'           => $row['id'],
915
-					'uri'          => $row['uri'],
916
-					'lastmodified' => $row['lastmodified'],
917
-					'etag'         => '"' . $row['etag'] . '"',
918
-					'calendarid'   => $row['calendarid'],
919
-					'size'         => (int)$row['size'],
920
-					'calendardata' => $this->readBlob($row['calendardata']),
921
-					'component'    => strtolower($row['componenttype']),
922
-					'classification' => (int)$row['classification']
923
-				];
924
-			}
925
-			$result->closeCursor();
926
-		}
927
-		return $objects;
928
-	}
929
-
930
-	/**
931
-	 * Creates a new calendar object.
932
-	 *
933
-	 * The object uri is only the basename, or filename and not a full path.
934
-	 *
935
-	 * It is possible return an etag from this function, which will be used in
936
-	 * the response to this PUT request. Note that the ETag must be surrounded
937
-	 * by double-quotes.
938
-	 *
939
-	 * However, you should only really return this ETag if you don't mangle the
940
-	 * calendar-data. If the result of a subsequent GET to this object is not
941
-	 * the exact same as this request body, you should omit the ETag.
942
-	 *
943
-	 * @param mixed $calendarId
944
-	 * @param string $objectUri
945
-	 * @param string $calendarData
946
-	 * @return string
947
-	 */
948
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
949
-		$extraData = $this->getDenormalizedData($calendarData);
950
-
951
-		$q = $this->db->getQueryBuilder();
952
-		$q->select($q->createFunction('COUNT(*)'))
953
-			->from('calendarobjects')
954
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
955
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
956
-
957
-		$result = $q->execute();
958
-		$count = (int) $result->fetchColumn();
959
-		$result->closeCursor();
960
-
961
-		if ($count !== 0) {
962
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
963
-		}
964
-
965
-		$query = $this->db->getQueryBuilder();
966
-		$query->insert('calendarobjects')
967
-			->values([
968
-				'calendarid' => $query->createNamedParameter($calendarId),
969
-				'uri' => $query->createNamedParameter($objectUri),
970
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
971
-				'lastmodified' => $query->createNamedParameter(time()),
972
-				'etag' => $query->createNamedParameter($extraData['etag']),
973
-				'size' => $query->createNamedParameter($extraData['size']),
974
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
975
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
976
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
977
-				'classification' => $query->createNamedParameter($extraData['classification']),
978
-				'uid' => $query->createNamedParameter($extraData['uid']),
979
-			])
980
-			->execute();
981
-
982
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
983
-
984
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
985
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
986
-			[
987
-				'calendarId' => $calendarId,
988
-				'calendarData' => $this->getCalendarById($calendarId),
989
-				'shares' => $this->getShares($calendarId),
990
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
991
-			]
992
-		));
993
-		$this->addChange($calendarId, $objectUri, 1);
994
-
995
-		return '"' . $extraData['etag'] . '"';
996
-	}
997
-
998
-	/**
999
-	 * Updates an existing calendarobject, based on it's uri.
1000
-	 *
1001
-	 * The object uri is only the basename, or filename and not a full path.
1002
-	 *
1003
-	 * It is possible return an etag from this function, which will be used in
1004
-	 * the response to this PUT request. Note that the ETag must be surrounded
1005
-	 * by double-quotes.
1006
-	 *
1007
-	 * However, you should only really return this ETag if you don't mangle the
1008
-	 * calendar-data. If the result of a subsequent GET to this object is not
1009
-	 * the exact same as this request body, you should omit the ETag.
1010
-	 *
1011
-	 * @param mixed $calendarId
1012
-	 * @param string $objectUri
1013
-	 * @param string $calendarData
1014
-	 * @return string
1015
-	 */
1016
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1017
-		$extraData = $this->getDenormalizedData($calendarData);
1018
-
1019
-		$query = $this->db->getQueryBuilder();
1020
-		$query->update('calendarobjects')
1021
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1022
-				->set('lastmodified', $query->createNamedParameter(time()))
1023
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1024
-				->set('size', $query->createNamedParameter($extraData['size']))
1025
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1026
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1027
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1028
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1029
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1030
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1031
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1032
-			->execute();
1033
-
1034
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1035
-
1036
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1037
-		if (is_array($data)) {
1038
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1039
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1040
-				[
1041
-					'calendarId' => $calendarId,
1042
-					'calendarData' => $this->getCalendarById($calendarId),
1043
-					'shares' => $this->getShares($calendarId),
1044
-					'objectData' => $data,
1045
-				]
1046
-			));
1047
-		}
1048
-		$this->addChange($calendarId, $objectUri, 2);
1049
-
1050
-		return '"' . $extraData['etag'] . '"';
1051
-	}
1052
-
1053
-	/**
1054
-	 * @param int $calendarObjectId
1055
-	 * @param int $classification
1056
-	 */
1057
-	public function setClassification($calendarObjectId, $classification) {
1058
-		if (!in_array($classification, [
1059
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1060
-		])) {
1061
-			throw new \InvalidArgumentException();
1062
-		}
1063
-		$query = $this->db->getQueryBuilder();
1064
-		$query->update('calendarobjects')
1065
-			->set('classification', $query->createNamedParameter($classification))
1066
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1067
-			->execute();
1068
-	}
1069
-
1070
-	/**
1071
-	 * Deletes an existing calendar object.
1072
-	 *
1073
-	 * The object uri is only the basename, or filename and not a full path.
1074
-	 *
1075
-	 * @param mixed $calendarId
1076
-	 * @param string $objectUri
1077
-	 * @return void
1078
-	 */
1079
-	function deleteCalendarObject($calendarId, $objectUri) {
1080
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1081
-		if (is_array($data)) {
1082
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1083
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1084
-				[
1085
-					'calendarId' => $calendarId,
1086
-					'calendarData' => $this->getCalendarById($calendarId),
1087
-					'shares' => $this->getShares($calendarId),
1088
-					'objectData' => $data,
1089
-				]
1090
-			));
1091
-		}
1092
-
1093
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1094
-		$stmt->execute([$calendarId, $objectUri]);
1095
-
1096
-		$this->purgeProperties($calendarId, $data['id']);
1097
-
1098
-		$this->addChange($calendarId, $objectUri, 3);
1099
-	}
1100
-
1101
-	/**
1102
-	 * Performs a calendar-query on the contents of this calendar.
1103
-	 *
1104
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1105
-	 * calendar-query it is possible for a client to request a specific set of
1106
-	 * object, based on contents of iCalendar properties, date-ranges and
1107
-	 * iCalendar component types (VTODO, VEVENT).
1108
-	 *
1109
-	 * This method should just return a list of (relative) urls that match this
1110
-	 * query.
1111
-	 *
1112
-	 * The list of filters are specified as an array. The exact array is
1113
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1114
-	 *
1115
-	 * Note that it is extremely likely that getCalendarObject for every path
1116
-	 * returned from this method will be called almost immediately after. You
1117
-	 * may want to anticipate this to speed up these requests.
1118
-	 *
1119
-	 * This method provides a default implementation, which parses *all* the
1120
-	 * iCalendar objects in the specified calendar.
1121
-	 *
1122
-	 * This default may well be good enough for personal use, and calendars
1123
-	 * that aren't very large. But if you anticipate high usage, big calendars
1124
-	 * or high loads, you are strongly advised to optimize certain paths.
1125
-	 *
1126
-	 * The best way to do so is override this method and to optimize
1127
-	 * specifically for 'common filters'.
1128
-	 *
1129
-	 * Requests that are extremely common are:
1130
-	 *   * requests for just VEVENTS
1131
-	 *   * requests for just VTODO
1132
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1133
-	 *
1134
-	 * ..and combinations of these requests. It may not be worth it to try to
1135
-	 * handle every possible situation and just rely on the (relatively
1136
-	 * easy to use) CalendarQueryValidator to handle the rest.
1137
-	 *
1138
-	 * Note that especially time-range-filters may be difficult to parse. A
1139
-	 * time-range filter specified on a VEVENT must for instance also handle
1140
-	 * recurrence rules correctly.
1141
-	 * A good example of how to interprete all these filters can also simply
1142
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1143
-	 * as possible, so it gives you a good idea on what type of stuff you need
1144
-	 * to think of.
1145
-	 *
1146
-	 * @param mixed $calendarId
1147
-	 * @param array $filters
1148
-	 * @return array
1149
-	 */
1150
-	function calendarQuery($calendarId, array $filters) {
1151
-		$componentType = null;
1152
-		$requirePostFilter = true;
1153
-		$timeRange = null;
1154
-
1155
-		// if no filters were specified, we don't need to filter after a query
1156
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1157
-			$requirePostFilter = false;
1158
-		}
1159
-
1160
-		// Figuring out if there's a component filter
1161
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1162
-			$componentType = $filters['comp-filters'][0]['name'];
1163
-
1164
-			// Checking if we need post-filters
1165
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1166
-				$requirePostFilter = false;
1167
-			}
1168
-			// There was a time-range filter
1169
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1170
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1171
-
1172
-				// If start time OR the end time is not specified, we can do a
1173
-				// 100% accurate mysql query.
1174
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1175
-					$requirePostFilter = false;
1176
-				}
1177
-			}
1178
-
1179
-		}
1180
-		$columns = ['uri'];
1181
-		if ($requirePostFilter) {
1182
-			$columns = ['uri', 'calendardata'];
1183
-		}
1184
-		$query = $this->db->getQueryBuilder();
1185
-		$query->select($columns)
1186
-			->from('calendarobjects')
1187
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1188
-
1189
-		if ($componentType) {
1190
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1191
-		}
1192
-
1193
-		if ($timeRange && $timeRange['start']) {
1194
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1195
-		}
1196
-		if ($timeRange && $timeRange['end']) {
1197
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1198
-		}
1199
-
1200
-		$stmt = $query->execute();
1201
-
1202
-		$result = [];
1203
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1204
-			if ($requirePostFilter) {
1205
-				if (!$this->validateFilterForObject($row, $filters)) {
1206
-					continue;
1207
-				}
1208
-			}
1209
-			$result[] = $row['uri'];
1210
-		}
1211
-
1212
-		return $result;
1213
-	}
1214
-
1215
-	/**
1216
-	 * custom Nextcloud search extension for CalDAV
1217
-	 *
1218
-	 * @param string $principalUri
1219
-	 * @param array $filters
1220
-	 * @param integer|null $limit
1221
-	 * @param integer|null $offset
1222
-	 * @return array
1223
-	 */
1224
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1225
-		$calendars = $this->getCalendarsForUser($principalUri);
1226
-		$ownCalendars = [];
1227
-		$sharedCalendars = [];
1228
-
1229
-		$uriMapper = [];
1230
-
1231
-		foreach($calendars as $calendar) {
1232
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1233
-				$ownCalendars[] = $calendar['id'];
1234
-			} else {
1235
-				$sharedCalendars[] = $calendar['id'];
1236
-			}
1237
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1238
-		}
1239
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1240
-			return [];
1241
-		}
1242
-
1243
-		$query = $this->db->getQueryBuilder();
1244
-		// Calendar id expressions
1245
-		$calendarExpressions = [];
1246
-		foreach($ownCalendars as $id) {
1247
-			$calendarExpressions[] = $query->expr()
1248
-				->eq('c.calendarid', $query->createNamedParameter($id));
1249
-		}
1250
-		foreach($sharedCalendars as $id) {
1251
-			$calendarExpressions[] = $query->expr()->andX(
1252
-				$query->expr()->eq('c.calendarid',
1253
-					$query->createNamedParameter($id)),
1254
-				$query->expr()->eq('c.classification',
1255
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1256
-			);
1257
-		}
1258
-
1259
-		if (count($calendarExpressions) === 1) {
1260
-			$calExpr = $calendarExpressions[0];
1261
-		} else {
1262
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1263
-		}
1264
-
1265
-		// Component expressions
1266
-		$compExpressions = [];
1267
-		foreach($filters['comps'] as $comp) {
1268
-			$compExpressions[] = $query->expr()
1269
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1270
-		}
1271
-
1272
-		if (count($compExpressions) === 1) {
1273
-			$compExpr = $compExpressions[0];
1274
-		} else {
1275
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1276
-		}
1277
-
1278
-		if (!isset($filters['props'])) {
1279
-			$filters['props'] = [];
1280
-		}
1281
-		if (!isset($filters['params'])) {
1282
-			$filters['params'] = [];
1283
-		}
1284
-
1285
-		$propParamExpressions = [];
1286
-		foreach($filters['props'] as $prop) {
1287
-			$propParamExpressions[] = $query->expr()->andX(
1288
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1289
-				$query->expr()->isNull('i.parameter')
1290
-			);
1291
-		}
1292
-		foreach($filters['params'] as $param) {
1293
-			$propParamExpressions[] = $query->expr()->andX(
1294
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1295
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1296
-			);
1297
-		}
1298
-
1299
-		if (count($propParamExpressions) === 1) {
1300
-			$propParamExpr = $propParamExpressions[0];
1301
-		} else {
1302
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1303
-		}
1304
-
1305
-		$query->select(['c.calendarid', 'c.uri'])
1306
-			->from($this->dbObjectPropertiesTable, 'i')
1307
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1308
-			->where($calExpr)
1309
-			->andWhere($compExpr)
1310
-			->andWhere($propParamExpr)
1311
-			->andWhere($query->expr()->iLike('i.value',
1312
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1313
-
1314
-		if ($offset) {
1315
-			$query->setFirstResult($offset);
1316
-		}
1317
-		if ($limit) {
1318
-			$query->setMaxResults($limit);
1319
-		}
1320
-
1321
-		$stmt = $query->execute();
1322
-
1323
-		$result = [];
1324
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1325
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1326
-			if (!in_array($path, $result)) {
1327
-				$result[] = $path;
1328
-			}
1329
-		}
1330
-
1331
-		return $result;
1332
-	}
1333
-
1334
-	/**
1335
-	 * Searches through all of a users calendars and calendar objects to find
1336
-	 * an object with a specific UID.
1337
-	 *
1338
-	 * This method should return the path to this object, relative to the
1339
-	 * calendar home, so this path usually only contains two parts:
1340
-	 *
1341
-	 * calendarpath/objectpath.ics
1342
-	 *
1343
-	 * If the uid is not found, return null.
1344
-	 *
1345
-	 * This method should only consider * objects that the principal owns, so
1346
-	 * any calendars owned by other principals that also appear in this
1347
-	 * collection should be ignored.
1348
-	 *
1349
-	 * @param string $principalUri
1350
-	 * @param string $uid
1351
-	 * @return string|null
1352
-	 */
1353
-	function getCalendarObjectByUID($principalUri, $uid) {
1354
-
1355
-		$query = $this->db->getQueryBuilder();
1356
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1357
-			->from('calendarobjects', 'co')
1358
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1359
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1360
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1361
-
1362
-		$stmt = $query->execute();
1363
-
1364
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1365
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1366
-		}
1367
-
1368
-		return null;
1369
-	}
1370
-
1371
-	/**
1372
-	 * The getChanges method returns all the changes that have happened, since
1373
-	 * the specified syncToken in the specified calendar.
1374
-	 *
1375
-	 * This function should return an array, such as the following:
1376
-	 *
1377
-	 * [
1378
-	 *   'syncToken' => 'The current synctoken',
1379
-	 *   'added'   => [
1380
-	 *      'new.txt',
1381
-	 *   ],
1382
-	 *   'modified'   => [
1383
-	 *      'modified.txt',
1384
-	 *   ],
1385
-	 *   'deleted' => [
1386
-	 *      'foo.php.bak',
1387
-	 *      'old.txt'
1388
-	 *   ]
1389
-	 * );
1390
-	 *
1391
-	 * The returned syncToken property should reflect the *current* syncToken
1392
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1393
-	 * property This is * needed here too, to ensure the operation is atomic.
1394
-	 *
1395
-	 * If the $syncToken argument is specified as null, this is an initial
1396
-	 * sync, and all members should be reported.
1397
-	 *
1398
-	 * The modified property is an array of nodenames that have changed since
1399
-	 * the last token.
1400
-	 *
1401
-	 * The deleted property is an array with nodenames, that have been deleted
1402
-	 * from collection.
1403
-	 *
1404
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1405
-	 * 1, you only have to report changes that happened only directly in
1406
-	 * immediate descendants. If it's 2, it should also include changes from
1407
-	 * the nodes below the child collections. (grandchildren)
1408
-	 *
1409
-	 * The $limit argument allows a client to specify how many results should
1410
-	 * be returned at most. If the limit is not specified, it should be treated
1411
-	 * as infinite.
1412
-	 *
1413
-	 * If the limit (infinite or not) is higher than you're willing to return,
1414
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1415
-	 *
1416
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1417
-	 * return null.
1418
-	 *
1419
-	 * The limit is 'suggestive'. You are free to ignore it.
1420
-	 *
1421
-	 * @param string $calendarId
1422
-	 * @param string $syncToken
1423
-	 * @param int $syncLevel
1424
-	 * @param int $limit
1425
-	 * @return array
1426
-	 */
1427
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1428
-		// Current synctoken
1429
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1430
-		$stmt->execute([ $calendarId ]);
1431
-		$currentToken = $stmt->fetchColumn(0);
1432
-
1433
-		if (is_null($currentToken)) {
1434
-			return null;
1435
-		}
1436
-
1437
-		$result = [
1438
-			'syncToken' => $currentToken,
1439
-			'added'     => [],
1440
-			'modified'  => [],
1441
-			'deleted'   => [],
1442
-		];
1443
-
1444
-		if ($syncToken) {
1445
-
1446
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1447
-			if ($limit>0) {
1448
-				$query.= " LIMIT " . (int)$limit;
1449
-			}
1450
-
1451
-			// Fetching all changes
1452
-			$stmt = $this->db->prepare($query);
1453
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1454
-
1455
-			$changes = [];
1456
-
1457
-			// This loop ensures that any duplicates are overwritten, only the
1458
-			// last change on a node is relevant.
1459
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1460
-
1461
-				$changes[$row['uri']] = $row['operation'];
1462
-
1463
-			}
1464
-
1465
-			foreach($changes as $uri => $operation) {
1466
-
1467
-				switch($operation) {
1468
-					case 1 :
1469
-						$result['added'][] = $uri;
1470
-						break;
1471
-					case 2 :
1472
-						$result['modified'][] = $uri;
1473
-						break;
1474
-					case 3 :
1475
-						$result['deleted'][] = $uri;
1476
-						break;
1477
-				}
1478
-
1479
-			}
1480
-		} else {
1481
-			// No synctoken supplied, this is the initial sync.
1482
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1483
-			$stmt = $this->db->prepare($query);
1484
-			$stmt->execute([$calendarId]);
1485
-
1486
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1487
-		}
1488
-		return $result;
1489
-
1490
-	}
1491
-
1492
-	/**
1493
-	 * Returns a list of subscriptions for a principal.
1494
-	 *
1495
-	 * Every subscription is an array with the following keys:
1496
-	 *  * id, a unique id that will be used by other functions to modify the
1497
-	 *    subscription. This can be the same as the uri or a database key.
1498
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1499
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1500
-	 *    principalUri passed to this method.
1501
-	 *
1502
-	 * Furthermore, all the subscription info must be returned too:
1503
-	 *
1504
-	 * 1. {DAV:}displayname
1505
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1506
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1507
-	 *    should not be stripped).
1508
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1509
-	 *    should not be stripped).
1510
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1511
-	 *    attachments should not be stripped).
1512
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1513
-	 *     Sabre\DAV\Property\Href).
1514
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1515
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1516
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1517
-	 *    (should just be an instance of
1518
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1519
-	 *    default components).
1520
-	 *
1521
-	 * @param string $principalUri
1522
-	 * @return array
1523
-	 */
1524
-	function getSubscriptionsForUser($principalUri) {
1525
-		$fields = array_values($this->subscriptionPropertyMap);
1526
-		$fields[] = 'id';
1527
-		$fields[] = 'uri';
1528
-		$fields[] = 'source';
1529
-		$fields[] = 'principaluri';
1530
-		$fields[] = 'lastmodified';
1531
-
1532
-		$query = $this->db->getQueryBuilder();
1533
-		$query->select($fields)
1534
-			->from('calendarsubscriptions')
1535
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1536
-			->orderBy('calendarorder', 'asc');
1537
-		$stmt =$query->execute();
1538
-
1539
-		$subscriptions = [];
1540
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1541
-
1542
-			$subscription = [
1543
-				'id'           => $row['id'],
1544
-				'uri'          => $row['uri'],
1545
-				'principaluri' => $row['principaluri'],
1546
-				'source'       => $row['source'],
1547
-				'lastmodified' => $row['lastmodified'],
1548
-
1549
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1550
-			];
1551
-
1552
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1553
-				if (!is_null($row[$dbName])) {
1554
-					$subscription[$xmlName] = $row[$dbName];
1555
-				}
1556
-			}
1557
-
1558
-			$subscriptions[] = $subscription;
1559
-
1560
-		}
1561
-
1562
-		return $subscriptions;
1563
-	}
1564
-
1565
-	/**
1566
-	 * Creates a new subscription for a principal.
1567
-	 *
1568
-	 * If the creation was a success, an id must be returned that can be used to reference
1569
-	 * this subscription in other methods, such as updateSubscription.
1570
-	 *
1571
-	 * @param string $principalUri
1572
-	 * @param string $uri
1573
-	 * @param array $properties
1574
-	 * @return mixed
1575
-	 */
1576
-	function createSubscription($principalUri, $uri, array $properties) {
1577
-
1578
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1579
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1580
-		}
1581
-
1582
-		$values = [
1583
-			'principaluri' => $principalUri,
1584
-			'uri'          => $uri,
1585
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1586
-			'lastmodified' => time(),
1587
-		];
1588
-
1589
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1590
-
1591
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1592
-			if (array_key_exists($xmlName, $properties)) {
1593
-					$values[$dbName] = $properties[$xmlName];
1594
-					if (in_array($dbName, $propertiesBoolean)) {
1595
-						$values[$dbName] = true;
1596
-				}
1597
-			}
1598
-		}
1599
-
1600
-		$valuesToInsert = array();
1601
-
1602
-		$query = $this->db->getQueryBuilder();
1603
-
1604
-		foreach (array_keys($values) as $name) {
1605
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1606
-		}
1607
-
1608
-		$query->insert('calendarsubscriptions')
1609
-			->values($valuesToInsert)
1610
-			->execute();
1611
-
1612
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1613
-	}
1614
-
1615
-	/**
1616
-	 * Updates a subscription
1617
-	 *
1618
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1619
-	 * To do the actual updates, you must tell this object which properties
1620
-	 * you're going to process with the handle() method.
1621
-	 *
1622
-	 * Calling the handle method is like telling the PropPatch object "I
1623
-	 * promise I can handle updating this property".
1624
-	 *
1625
-	 * Read the PropPatch documentation for more info and examples.
1626
-	 *
1627
-	 * @param mixed $subscriptionId
1628
-	 * @param PropPatch $propPatch
1629
-	 * @return void
1630
-	 */
1631
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1632
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1633
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1634
-
1635
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1636
-
1637
-			$newValues = [];
1638
-
1639
-			foreach($mutations as $propertyName=>$propertyValue) {
1640
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1641
-					$newValues['source'] = $propertyValue->getHref();
1642
-				} else {
1643
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1644
-					$newValues[$fieldName] = $propertyValue;
1645
-				}
1646
-			}
1647
-
1648
-			$query = $this->db->getQueryBuilder();
1649
-			$query->update('calendarsubscriptions')
1650
-				->set('lastmodified', $query->createNamedParameter(time()));
1651
-			foreach($newValues as $fieldName=>$value) {
1652
-				$query->set($fieldName, $query->createNamedParameter($value));
1653
-			}
1654
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1655
-				->execute();
1656
-
1657
-			return true;
1658
-
1659
-		});
1660
-	}
1661
-
1662
-	/**
1663
-	 * Deletes a subscription.
1664
-	 *
1665
-	 * @param mixed $subscriptionId
1666
-	 * @return void
1667
-	 */
1668
-	function deleteSubscription($subscriptionId) {
1669
-		$query = $this->db->getQueryBuilder();
1670
-		$query->delete('calendarsubscriptions')
1671
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1672
-			->execute();
1673
-	}
1674
-
1675
-	/**
1676
-	 * Returns a single scheduling object for the inbox collection.
1677
-	 *
1678
-	 * The returned array should contain the following elements:
1679
-	 *   * uri - A unique basename for the object. This will be used to
1680
-	 *           construct a full uri.
1681
-	 *   * calendardata - The iCalendar object
1682
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1683
-	 *                    timestamp, or a PHP DateTime object.
1684
-	 *   * etag - A unique token that must change if the object changed.
1685
-	 *   * size - The size of the object, in bytes.
1686
-	 *
1687
-	 * @param string $principalUri
1688
-	 * @param string $objectUri
1689
-	 * @return array
1690
-	 */
1691
-	function getSchedulingObject($principalUri, $objectUri) {
1692
-		$query = $this->db->getQueryBuilder();
1693
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1694
-			->from('schedulingobjects')
1695
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1696
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1697
-			->execute();
1698
-
1699
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1700
-
1701
-		if(!$row) {
1702
-			return null;
1703
-		}
1704
-
1705
-		return [
1706
-				'uri'          => $row['uri'],
1707
-				'calendardata' => $row['calendardata'],
1708
-				'lastmodified' => $row['lastmodified'],
1709
-				'etag'         => '"' . $row['etag'] . '"',
1710
-				'size'         => (int)$row['size'],
1711
-		];
1712
-	}
1713
-
1714
-	/**
1715
-	 * Returns all scheduling objects for the inbox collection.
1716
-	 *
1717
-	 * These objects should be returned as an array. Every item in the array
1718
-	 * should follow the same structure as returned from getSchedulingObject.
1719
-	 *
1720
-	 * The main difference is that 'calendardata' is optional.
1721
-	 *
1722
-	 * @param string $principalUri
1723
-	 * @return array
1724
-	 */
1725
-	function getSchedulingObjects($principalUri) {
1726
-		$query = $this->db->getQueryBuilder();
1727
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1728
-				->from('schedulingobjects')
1729
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1730
-				->execute();
1731
-
1732
-		$result = [];
1733
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1734
-			$result[] = [
1735
-					'calendardata' => $row['calendardata'],
1736
-					'uri'          => $row['uri'],
1737
-					'lastmodified' => $row['lastmodified'],
1738
-					'etag'         => '"' . $row['etag'] . '"',
1739
-					'size'         => (int)$row['size'],
1740
-			];
1741
-		}
1742
-
1743
-		return $result;
1744
-	}
1745
-
1746
-	/**
1747
-	 * Deletes a scheduling object from the inbox collection.
1748
-	 *
1749
-	 * @param string $principalUri
1750
-	 * @param string $objectUri
1751
-	 * @return void
1752
-	 */
1753
-	function deleteSchedulingObject($principalUri, $objectUri) {
1754
-		$query = $this->db->getQueryBuilder();
1755
-		$query->delete('schedulingobjects')
1756
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1757
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1758
-				->execute();
1759
-	}
1760
-
1761
-	/**
1762
-	 * Creates a new scheduling object. This should land in a users' inbox.
1763
-	 *
1764
-	 * @param string $principalUri
1765
-	 * @param string $objectUri
1766
-	 * @param string $objectData
1767
-	 * @return void
1768
-	 */
1769
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1770
-		$query = $this->db->getQueryBuilder();
1771
-		$query->insert('schedulingobjects')
1772
-			->values([
1773
-				'principaluri' => $query->createNamedParameter($principalUri),
1774
-				'calendardata' => $query->createNamedParameter($objectData),
1775
-				'uri' => $query->createNamedParameter($objectUri),
1776
-				'lastmodified' => $query->createNamedParameter(time()),
1777
-				'etag' => $query->createNamedParameter(md5($objectData)),
1778
-				'size' => $query->createNamedParameter(strlen($objectData))
1779
-			])
1780
-			->execute();
1781
-	}
1782
-
1783
-	/**
1784
-	 * Adds a change record to the calendarchanges table.
1785
-	 *
1786
-	 * @param mixed $calendarId
1787
-	 * @param string $objectUri
1788
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1789
-	 * @return void
1790
-	 */
1791
-	protected function addChange($calendarId, $objectUri, $operation) {
1792
-
1793
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1794
-		$stmt->execute([
1795
-			$objectUri,
1796
-			$calendarId,
1797
-			$operation,
1798
-			$calendarId
1799
-		]);
1800
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1801
-		$stmt->execute([
1802
-			$calendarId
1803
-		]);
1804
-
1805
-	}
1806
-
1807
-	/**
1808
-	 * Parses some information from calendar objects, used for optimized
1809
-	 * calendar-queries.
1810
-	 *
1811
-	 * Returns an array with the following keys:
1812
-	 *   * etag - An md5 checksum of the object without the quotes.
1813
-	 *   * size - Size of the object in bytes
1814
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1815
-	 *   * firstOccurence
1816
-	 *   * lastOccurence
1817
-	 *   * uid - value of the UID property
1818
-	 *
1819
-	 * @param string $calendarData
1820
-	 * @return array
1821
-	 */
1822
-	public function getDenormalizedData($calendarData) {
1823
-
1824
-		$vObject = Reader::read($calendarData);
1825
-		$componentType = null;
1826
-		$component = null;
1827
-		$firstOccurrence = null;
1828
-		$lastOccurrence = null;
1829
-		$uid = null;
1830
-		$classification = self::CLASSIFICATION_PUBLIC;
1831
-		foreach($vObject->getComponents() as $component) {
1832
-			if ($component->name!=='VTIMEZONE') {
1833
-				$componentType = $component->name;
1834
-				$uid = (string)$component->UID;
1835
-				break;
1836
-			}
1837
-		}
1838
-		if (!$componentType) {
1839
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1840
-		}
1841
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1842
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1843
-			// Finding the last occurrence is a bit harder
1844
-			if (!isset($component->RRULE)) {
1845
-				if (isset($component->DTEND)) {
1846
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1847
-				} elseif (isset($component->DURATION)) {
1848
-					$endDate = clone $component->DTSTART->getDateTime();
1849
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1850
-					$lastOccurrence = $endDate->getTimeStamp();
1851
-				} elseif (!$component->DTSTART->hasTime()) {
1852
-					$endDate = clone $component->DTSTART->getDateTime();
1853
-					$endDate->modify('+1 day');
1854
-					$lastOccurrence = $endDate->getTimeStamp();
1855
-				} else {
1856
-					$lastOccurrence = $firstOccurrence;
1857
-				}
1858
-			} else {
1859
-				$it = new EventIterator($vObject, (string)$component->UID);
1860
-				$maxDate = new \DateTime(self::MAX_DATE);
1861
-				if ($it->isInfinite()) {
1862
-					$lastOccurrence = $maxDate->getTimestamp();
1863
-				} else {
1864
-					$end = $it->getDtEnd();
1865
-					while($it->valid() && $end < $maxDate) {
1866
-						$end = $it->getDtEnd();
1867
-						$it->next();
1868
-
1869
-					}
1870
-					$lastOccurrence = $end->getTimestamp();
1871
-				}
1872
-
1873
-			}
1874
-		}
1875
-
1876
-		if ($component->CLASS) {
1877
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1878
-			switch ($component->CLASS->getValue()) {
1879
-				case 'PUBLIC':
1880
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1881
-					break;
1882
-				case 'CONFIDENTIAL':
1883
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1884
-					break;
1885
-			}
1886
-		}
1887
-		return [
1888
-			'etag' => md5($calendarData),
1889
-			'size' => strlen($calendarData),
1890
-			'componentType' => $componentType,
1891
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1892
-			'lastOccurence'  => $lastOccurrence,
1893
-			'uid' => $uid,
1894
-			'classification' => $classification
1895
-		];
1896
-
1897
-	}
1898
-
1899
-	private function readBlob($cardData) {
1900
-		if (is_resource($cardData)) {
1901
-			return stream_get_contents($cardData);
1902
-		}
1903
-
1904
-		return $cardData;
1905
-	}
1906
-
1907
-	/**
1908
-	 * @param IShareable $shareable
1909
-	 * @param array $add
1910
-	 * @param array $remove
1911
-	 */
1912
-	public function updateShares($shareable, $add, $remove) {
1913
-		$calendarId = $shareable->getResourceId();
1914
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1915
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1916
-			[
1917
-				'calendarId' => $calendarId,
1918
-				'calendarData' => $this->getCalendarById($calendarId),
1919
-				'shares' => $this->getShares($calendarId),
1920
-				'add' => $add,
1921
-				'remove' => $remove,
1922
-			]));
1923
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1924
-	}
1925
-
1926
-	/**
1927
-	 * @param int $resourceId
1928
-	 * @return array
1929
-	 */
1930
-	public function getShares($resourceId) {
1931
-		return $this->sharingBackend->getShares($resourceId);
1932
-	}
1933
-
1934
-	/**
1935
-	 * @param boolean $value
1936
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1937
-	 * @return string|null
1938
-	 */
1939
-	public function setPublishStatus($value, $calendar) {
1940
-		$query = $this->db->getQueryBuilder();
1941
-		if ($value) {
1942
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1943
-			$query->insert('dav_shares')
1944
-				->values([
1945
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1946
-					'type' => $query->createNamedParameter('calendar'),
1947
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1948
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1949
-					'publicuri' => $query->createNamedParameter($publicUri)
1950
-				]);
1951
-			$query->execute();
1952
-			return $publicUri;
1953
-		}
1954
-		$query->delete('dav_shares')
1955
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1956
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1957
-		$query->execute();
1958
-		return null;
1959
-	}
1960
-
1961
-	/**
1962
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1963
-	 * @return mixed
1964
-	 */
1965
-	public function getPublishStatus($calendar) {
1966
-		$query = $this->db->getQueryBuilder();
1967
-		$result = $query->select('publicuri')
1968
-			->from('dav_shares')
1969
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1970
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1971
-			->execute();
1972
-
1973
-		$row = $result->fetch();
1974
-		$result->closeCursor();
1975
-		return $row ? reset($row) : false;
1976
-	}
1977
-
1978
-	/**
1979
-	 * @param int $resourceId
1980
-	 * @param array $acl
1981
-	 * @return array
1982
-	 */
1983
-	public function applyShareAcl($resourceId, $acl) {
1984
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1985
-	}
1986
-
1987
-
1988
-
1989
-	/**
1990
-	 * update properties table
1991
-	 *
1992
-	 * @param int $calendarId
1993
-	 * @param string $objectUri
1994
-	 * @param string $calendarData
1995
-	 */
1996
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
1997
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
1998
-
1999
-		try {
2000
-			$vCalendar = $this->readCalendarData($calendarData);
2001
-		} catch (\Exception $ex) {
2002
-			return;
2003
-		}
2004
-
2005
-		$this->purgeProperties($calendarId, $objectId);
2006
-
2007
-		$query = $this->db->getQueryBuilder();
2008
-		$query->insert($this->dbObjectPropertiesTable)
2009
-			->values(
2010
-				[
2011
-					'calendarid' => $query->createNamedParameter($calendarId),
2012
-					'objectid' => $query->createNamedParameter($objectId),
2013
-					'name' => $query->createParameter('name'),
2014
-					'parameter' => $query->createParameter('parameter'),
2015
-					'value' => $query->createParameter('value'),
2016
-				]
2017
-			);
2018
-
2019
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2020
-		foreach ($vCalendar->getComponents() as $component) {
2021
-			if (!in_array($component->name, $indexComponents)) {
2022
-				continue;
2023
-			}
2024
-
2025
-			foreach ($component->children() as $property) {
2026
-				if (in_array($property->name, self::$indexProperties)) {
2027
-					$value = $property->getValue();
2028
-					// is this a shitty db?
2029
-					if (!$this->db->supports4ByteText()) {
2030
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2031
-					}
2032
-					$value = mb_substr($value, 0, 254);
2033
-
2034
-					$query->setParameter('name', $property->name);
2035
-					$query->setParameter('parameter', null);
2036
-					$query->setParameter('value', $value);
2037
-					$query->execute();
2038
-				}
2039
-
2040
-				if (in_array($property->name, array_keys(self::$indexParameters))) {
2041
-					$parameters = $property->parameters();
2042
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2043
-
2044
-					foreach ($parameters as $key => $value) {
2045
-						if (in_array($key, $indexedParametersForProperty)) {
2046
-							// is this a shitty db?
2047
-							if ($this->db->supports4ByteText()) {
2048
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2049
-							}
2050
-							$value = mb_substr($value, 0, 254);
2051
-
2052
-							$query->setParameter('name', $property->name);
2053
-							$query->setParameter('parameter', substr($key, 0, 254));
2054
-							$query->setParameter('value', substr($value, 0, 254));
2055
-							$query->execute();
2056
-						}
2057
-					}
2058
-				}
2059
-			}
2060
-		}
2061
-	}
2062
-
2063
-	/**
2064
-	 * read VCalendar data into a VCalendar object
2065
-	 *
2066
-	 * @param string $objectData
2067
-	 * @return VCalendar
2068
-	 */
2069
-	protected function readCalendarData($objectData) {
2070
-		return Reader::read($objectData);
2071
-	}
2072
-
2073
-	/**
2074
-	 * delete all properties from a given calendar object
2075
-	 *
2076
-	 * @param int $calendarId
2077
-	 * @param int $objectId
2078
-	 */
2079
-	protected function purgeProperties($calendarId, $objectId) {
2080
-		$query = $this->db->getQueryBuilder();
2081
-		$query->delete($this->dbObjectPropertiesTable)
2082
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2083
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2084
-		$query->execute();
2085
-	}
2086
-
2087
-	/**
2088
-	 * get ID from a given calendar object
2089
-	 *
2090
-	 * @param int $calendarId
2091
-	 * @param string $uri
2092
-	 * @return int
2093
-	 */
2094
-	protected function getCalendarObjectId($calendarId, $uri) {
2095
-		$query = $this->db->getQueryBuilder();
2096
-		$query->select('id')->from('calendarobjects')
2097
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2098
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2099
-
2100
-		$result = $query->execute();
2101
-		$objectIds = $result->fetch();
2102
-		$result->closeCursor();
2103
-
2104
-		if (!isset($objectIds['id'])) {
2105
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2106
-		}
2107
-
2108
-		return (int)$objectIds['id'];
2109
-	}
2110
-
2111
-	private function convertPrincipal($principalUri, $toV2) {
2112
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2113
-			list(, $name) = URLUtil::splitPath($principalUri);
2114
-			if ($toV2 === true) {
2115
-				return "principals/users/$name";
2116
-			}
2117
-			return "principals/$name";
2118
-		}
2119
-		return $principalUri;
2120
-	}
2121
-
2122
-	private function addOwnerPrincipal(&$calendarInfo) {
2123
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2124
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2125
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2126
-			$uri = $calendarInfo[$ownerPrincipalKey];
2127
-		} else {
2128
-			$uri = $calendarInfo['principaluri'];
2129
-		}
2130
-
2131
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2132
-		if (isset($principalInformation['{DAV:}displayname'])) {
2133
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2134
-		}
2135
-	}
412
+    /**
413
+     * @return array
414
+     */
415
+    public function getPublicCalendars() {
416
+        $fields = array_values($this->propertyMap);
417
+        $fields[] = 'a.id';
418
+        $fields[] = 'a.uri';
419
+        $fields[] = 'a.synctoken';
420
+        $fields[] = 'a.components';
421
+        $fields[] = 'a.principaluri';
422
+        $fields[] = 'a.transparent';
423
+        $fields[] = 's.access';
424
+        $fields[] = 's.publicuri';
425
+        $calendars = [];
426
+        $query = $this->db->getQueryBuilder();
427
+        $result = $query->select($fields)
428
+            ->from('dav_shares', 's')
429
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
430
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
431
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
432
+            ->execute();
433
+
434
+        while($row = $result->fetch()) {
435
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
436
+            $row['displayname'] = $row['displayname'] . "($name)";
437
+            $components = [];
438
+            if ($row['components']) {
439
+                $components = explode(',',$row['components']);
440
+            }
441
+            $calendar = [
442
+                'id' => $row['id'],
443
+                'uri' => $row['publicuri'],
444
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
445
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
446
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
447
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
448
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
449
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
450
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
451
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
452
+            ];
453
+
454
+            foreach($this->propertyMap as $xmlName=>$dbName) {
455
+                $calendar[$xmlName] = $row[$dbName];
456
+            }
457
+
458
+            $this->addOwnerPrincipal($calendar);
459
+
460
+            if (!isset($calendars[$calendar['id']])) {
461
+                $calendars[$calendar['id']] = $calendar;
462
+            }
463
+        }
464
+        $result->closeCursor();
465
+
466
+        return array_values($calendars);
467
+    }
468
+
469
+    /**
470
+     * @param string $uri
471
+     * @return array
472
+     * @throws NotFound
473
+     */
474
+    public function getPublicCalendar($uri) {
475
+        $fields = array_values($this->propertyMap);
476
+        $fields[] = 'a.id';
477
+        $fields[] = 'a.uri';
478
+        $fields[] = 'a.synctoken';
479
+        $fields[] = 'a.components';
480
+        $fields[] = 'a.principaluri';
481
+        $fields[] = 'a.transparent';
482
+        $fields[] = 's.access';
483
+        $fields[] = 's.publicuri';
484
+        $query = $this->db->getQueryBuilder();
485
+        $result = $query->select($fields)
486
+            ->from('dav_shares', 's')
487
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
488
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
489
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
490
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
491
+            ->execute();
492
+
493
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
494
+
495
+        $result->closeCursor();
496
+
497
+        if ($row === false) {
498
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
499
+        }
500
+
501
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
502
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
503
+        $components = [];
504
+        if ($row['components']) {
505
+            $components = explode(',',$row['components']);
506
+        }
507
+        $calendar = [
508
+            'id' => $row['id'],
509
+            'uri' => $row['publicuri'],
510
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
511
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
512
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
513
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
514
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
515
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
516
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
517
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
518
+        ];
519
+
520
+        foreach($this->propertyMap as $xmlName=>$dbName) {
521
+            $calendar[$xmlName] = $row[$dbName];
522
+        }
523
+
524
+        $this->addOwnerPrincipal($calendar);
525
+
526
+        return $calendar;
527
+
528
+    }
529
+
530
+    /**
531
+     * @param string $principal
532
+     * @param string $uri
533
+     * @return array|null
534
+     */
535
+    public function getCalendarByUri($principal, $uri) {
536
+        $fields = array_values($this->propertyMap);
537
+        $fields[] = 'id';
538
+        $fields[] = 'uri';
539
+        $fields[] = 'synctoken';
540
+        $fields[] = 'components';
541
+        $fields[] = 'principaluri';
542
+        $fields[] = 'transparent';
543
+
544
+        // Making fields a comma-delimited list
545
+        $query = $this->db->getQueryBuilder();
546
+        $query->select($fields)->from('calendars')
547
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
548
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
549
+            ->setMaxResults(1);
550
+        $stmt = $query->execute();
551
+
552
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
553
+        $stmt->closeCursor();
554
+        if ($row === false) {
555
+            return null;
556
+        }
557
+
558
+        $components = [];
559
+        if ($row['components']) {
560
+            $components = explode(',',$row['components']);
561
+        }
562
+
563
+        $calendar = [
564
+            'id' => $row['id'],
565
+            'uri' => $row['uri'],
566
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
567
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
568
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
569
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
570
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
571
+        ];
572
+
573
+        foreach($this->propertyMap as $xmlName=>$dbName) {
574
+            $calendar[$xmlName] = $row[$dbName];
575
+        }
576
+
577
+        $this->addOwnerPrincipal($calendar);
578
+
579
+        return $calendar;
580
+    }
581
+
582
+    public function getCalendarById($calendarId) {
583
+        $fields = array_values($this->propertyMap);
584
+        $fields[] = 'id';
585
+        $fields[] = 'uri';
586
+        $fields[] = 'synctoken';
587
+        $fields[] = 'components';
588
+        $fields[] = 'principaluri';
589
+        $fields[] = 'transparent';
590
+
591
+        // Making fields a comma-delimited list
592
+        $query = $this->db->getQueryBuilder();
593
+        $query->select($fields)->from('calendars')
594
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
595
+            ->setMaxResults(1);
596
+        $stmt = $query->execute();
597
+
598
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
599
+        $stmt->closeCursor();
600
+        if ($row === false) {
601
+            return null;
602
+        }
603
+
604
+        $components = [];
605
+        if ($row['components']) {
606
+            $components = explode(',',$row['components']);
607
+        }
608
+
609
+        $calendar = [
610
+            'id' => $row['id'],
611
+            'uri' => $row['uri'],
612
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
614
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
615
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
616
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
617
+        ];
618
+
619
+        foreach($this->propertyMap as $xmlName=>$dbName) {
620
+            $calendar[$xmlName] = $row[$dbName];
621
+        }
622
+
623
+        $this->addOwnerPrincipal($calendar);
624
+
625
+        return $calendar;
626
+    }
627
+
628
+    /**
629
+     * Creates a new calendar for a principal.
630
+     *
631
+     * If the creation was a success, an id must be returned that can be used to reference
632
+     * this calendar in other methods, such as updateCalendar.
633
+     *
634
+     * @param string $principalUri
635
+     * @param string $calendarUri
636
+     * @param array $properties
637
+     * @return int
638
+     */
639
+    function createCalendar($principalUri, $calendarUri, array $properties) {
640
+        $values = [
641
+            'principaluri' => $this->convertPrincipal($principalUri, true),
642
+            'uri'          => $calendarUri,
643
+            'synctoken'    => 1,
644
+            'transparent'  => 0,
645
+            'components'   => 'VEVENT,VTODO',
646
+            'displayname'  => $calendarUri
647
+        ];
648
+
649
+        // Default value
650
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
651
+        if (isset($properties[$sccs])) {
652
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
653
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
654
+            }
655
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
656
+        }
657
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
658
+        if (isset($properties[$transp])) {
659
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
660
+        }
661
+
662
+        foreach($this->propertyMap as $xmlName=>$dbName) {
663
+            if (isset($properties[$xmlName])) {
664
+                $values[$dbName] = $properties[$xmlName];
665
+            }
666
+        }
667
+
668
+        $query = $this->db->getQueryBuilder();
669
+        $query->insert('calendars');
670
+        foreach($values as $column => $value) {
671
+            $query->setValue($column, $query->createNamedParameter($value));
672
+        }
673
+        $query->execute();
674
+        $calendarId = $query->getLastInsertId();
675
+
676
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
677
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
678
+            [
679
+                'calendarId' => $calendarId,
680
+                'calendarData' => $this->getCalendarById($calendarId),
681
+        ]));
682
+
683
+        return $calendarId;
684
+    }
685
+
686
+    /**
687
+     * Updates properties for a calendar.
688
+     *
689
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
690
+     * To do the actual updates, you must tell this object which properties
691
+     * you're going to process with the handle() method.
692
+     *
693
+     * Calling the handle method is like telling the PropPatch object "I
694
+     * promise I can handle updating this property".
695
+     *
696
+     * Read the PropPatch documentation for more info and examples.
697
+     *
698
+     * @param PropPatch $propPatch
699
+     * @return void
700
+     */
701
+    function updateCalendar($calendarId, PropPatch $propPatch) {
702
+        $supportedProperties = array_keys($this->propertyMap);
703
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
704
+
705
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
706
+            $newValues = [];
707
+            foreach ($mutations as $propertyName => $propertyValue) {
708
+
709
+                switch ($propertyName) {
710
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
711
+                        $fieldName = 'transparent';
712
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
713
+                        break;
714
+                    default :
715
+                        $fieldName = $this->propertyMap[$propertyName];
716
+                        $newValues[$fieldName] = $propertyValue;
717
+                        break;
718
+                }
719
+
720
+            }
721
+            $query = $this->db->getQueryBuilder();
722
+            $query->update('calendars');
723
+            foreach ($newValues as $fieldName => $value) {
724
+                $query->set($fieldName, $query->createNamedParameter($value));
725
+            }
726
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
727
+            $query->execute();
728
+
729
+            $this->addChange($calendarId, "", 2);
730
+
731
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
732
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
733
+                [
734
+                    'calendarId' => $calendarId,
735
+                    'calendarData' => $this->getCalendarById($calendarId),
736
+                    'shares' => $this->getShares($calendarId),
737
+                    'propertyMutations' => $mutations,
738
+            ]));
739
+
740
+            return true;
741
+        });
742
+    }
743
+
744
+    /**
745
+     * Delete a calendar and all it's objects
746
+     *
747
+     * @param mixed $calendarId
748
+     * @return void
749
+     */
750
+    function deleteCalendar($calendarId) {
751
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
752
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
753
+            [
754
+                'calendarId' => $calendarId,
755
+                'calendarData' => $this->getCalendarById($calendarId),
756
+                'shares' => $this->getShares($calendarId),
757
+        ]));
758
+
759
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
760
+        $stmt->execute([$calendarId]);
761
+
762
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
763
+        $stmt->execute([$calendarId]);
764
+
765
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
766
+        $stmt->execute([$calendarId]);
767
+
768
+        $this->sharingBackend->deleteAllShares($calendarId);
769
+
770
+        $query = $this->db->getQueryBuilder();
771
+        $query->delete($this->dbObjectPropertiesTable)
772
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
773
+            ->execute();
774
+    }
775
+
776
+    /**
777
+     * Delete all of an user's shares
778
+     *
779
+     * @param string $principaluri
780
+     * @return void
781
+     */
782
+    function deleteAllSharesByUser($principaluri) {
783
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
784
+    }
785
+
786
+    /**
787
+     * Returns all calendar objects within a calendar.
788
+     *
789
+     * Every item contains an array with the following keys:
790
+     *   * calendardata - The iCalendar-compatible calendar data
791
+     *   * uri - a unique key which will be used to construct the uri. This can
792
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
793
+     *     good idea. This is only the basename, or filename, not the full
794
+     *     path.
795
+     *   * lastmodified - a timestamp of the last modification time
796
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
797
+     *   '"abcdef"')
798
+     *   * size - The size of the calendar objects, in bytes.
799
+     *   * component - optional, a string containing the type of object, such
800
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
801
+     *     the Content-Type header.
802
+     *
803
+     * Note that the etag is optional, but it's highly encouraged to return for
804
+     * speed reasons.
805
+     *
806
+     * The calendardata is also optional. If it's not returned
807
+     * 'getCalendarObject' will be called later, which *is* expected to return
808
+     * calendardata.
809
+     *
810
+     * If neither etag or size are specified, the calendardata will be
811
+     * used/fetched to determine these numbers. If both are specified the
812
+     * amount of times this is needed is reduced by a great degree.
813
+     *
814
+     * @param mixed $calendarId
815
+     * @return array
816
+     */
817
+    function getCalendarObjects($calendarId) {
818
+        $query = $this->db->getQueryBuilder();
819
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
820
+            ->from('calendarobjects')
821
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
822
+        $stmt = $query->execute();
823
+
824
+        $result = [];
825
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
826
+            $result[] = [
827
+                    'id'           => $row['id'],
828
+                    'uri'          => $row['uri'],
829
+                    'lastmodified' => $row['lastmodified'],
830
+                    'etag'         => '"' . $row['etag'] . '"',
831
+                    'calendarid'   => $row['calendarid'],
832
+                    'size'         => (int)$row['size'],
833
+                    'component'    => strtolower($row['componenttype']),
834
+                    'classification'=> (int)$row['classification']
835
+            ];
836
+        }
837
+
838
+        return $result;
839
+    }
840
+
841
+    /**
842
+     * Returns information from a single calendar object, based on it's object
843
+     * uri.
844
+     *
845
+     * The object uri is only the basename, or filename and not a full path.
846
+     *
847
+     * The returned array must have the same keys as getCalendarObjects. The
848
+     * 'calendardata' object is required here though, while it's not required
849
+     * for getCalendarObjects.
850
+     *
851
+     * This method must return null if the object did not exist.
852
+     *
853
+     * @param mixed $calendarId
854
+     * @param string $objectUri
855
+     * @return array|null
856
+     */
857
+    function getCalendarObject($calendarId, $objectUri) {
858
+
859
+        $query = $this->db->getQueryBuilder();
860
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
861
+                ->from('calendarobjects')
862
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
863
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
864
+        $stmt = $query->execute();
865
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
866
+
867
+        if(!$row) return null;
868
+
869
+        return [
870
+                'id'            => $row['id'],
871
+                'uri'           => $row['uri'],
872
+                'lastmodified'  => $row['lastmodified'],
873
+                'etag'          => '"' . $row['etag'] . '"',
874
+                'calendarid'    => $row['calendarid'],
875
+                'size'          => (int)$row['size'],
876
+                'calendardata'  => $this->readBlob($row['calendardata']),
877
+                'component'     => strtolower($row['componenttype']),
878
+                'classification'=> (int)$row['classification']
879
+        ];
880
+    }
881
+
882
+    /**
883
+     * Returns a list of calendar objects.
884
+     *
885
+     * This method should work identical to getCalendarObject, but instead
886
+     * return all the calendar objects in the list as an array.
887
+     *
888
+     * If the backend supports this, it may allow for some speed-ups.
889
+     *
890
+     * @param mixed $calendarId
891
+     * @param string[] $uris
892
+     * @return array
893
+     */
894
+    function getMultipleCalendarObjects($calendarId, array $uris) {
895
+        if (empty($uris)) {
896
+            return [];
897
+        }
898
+
899
+        $chunks = array_chunk($uris, 100);
900
+        $objects = [];
901
+
902
+        $query = $this->db->getQueryBuilder();
903
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
904
+            ->from('calendarobjects')
905
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
906
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
907
+
908
+        foreach ($chunks as $uris) {
909
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
910
+            $result = $query->execute();
911
+
912
+            while ($row = $result->fetch()) {
913
+                $objects[] = [
914
+                    'id'           => $row['id'],
915
+                    'uri'          => $row['uri'],
916
+                    'lastmodified' => $row['lastmodified'],
917
+                    'etag'         => '"' . $row['etag'] . '"',
918
+                    'calendarid'   => $row['calendarid'],
919
+                    'size'         => (int)$row['size'],
920
+                    'calendardata' => $this->readBlob($row['calendardata']),
921
+                    'component'    => strtolower($row['componenttype']),
922
+                    'classification' => (int)$row['classification']
923
+                ];
924
+            }
925
+            $result->closeCursor();
926
+        }
927
+        return $objects;
928
+    }
929
+
930
+    /**
931
+     * Creates a new calendar object.
932
+     *
933
+     * The object uri is only the basename, or filename and not a full path.
934
+     *
935
+     * It is possible return an etag from this function, which will be used in
936
+     * the response to this PUT request. Note that the ETag must be surrounded
937
+     * by double-quotes.
938
+     *
939
+     * However, you should only really return this ETag if you don't mangle the
940
+     * calendar-data. If the result of a subsequent GET to this object is not
941
+     * the exact same as this request body, you should omit the ETag.
942
+     *
943
+     * @param mixed $calendarId
944
+     * @param string $objectUri
945
+     * @param string $calendarData
946
+     * @return string
947
+     */
948
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
949
+        $extraData = $this->getDenormalizedData($calendarData);
950
+
951
+        $q = $this->db->getQueryBuilder();
952
+        $q->select($q->createFunction('COUNT(*)'))
953
+            ->from('calendarobjects')
954
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
955
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
956
+
957
+        $result = $q->execute();
958
+        $count = (int) $result->fetchColumn();
959
+        $result->closeCursor();
960
+
961
+        if ($count !== 0) {
962
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
963
+        }
964
+
965
+        $query = $this->db->getQueryBuilder();
966
+        $query->insert('calendarobjects')
967
+            ->values([
968
+                'calendarid' => $query->createNamedParameter($calendarId),
969
+                'uri' => $query->createNamedParameter($objectUri),
970
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
971
+                'lastmodified' => $query->createNamedParameter(time()),
972
+                'etag' => $query->createNamedParameter($extraData['etag']),
973
+                'size' => $query->createNamedParameter($extraData['size']),
974
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
975
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
976
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
977
+                'classification' => $query->createNamedParameter($extraData['classification']),
978
+                'uid' => $query->createNamedParameter($extraData['uid']),
979
+            ])
980
+            ->execute();
981
+
982
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
983
+
984
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
985
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
986
+            [
987
+                'calendarId' => $calendarId,
988
+                'calendarData' => $this->getCalendarById($calendarId),
989
+                'shares' => $this->getShares($calendarId),
990
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
991
+            ]
992
+        ));
993
+        $this->addChange($calendarId, $objectUri, 1);
994
+
995
+        return '"' . $extraData['etag'] . '"';
996
+    }
997
+
998
+    /**
999
+     * Updates an existing calendarobject, based on it's uri.
1000
+     *
1001
+     * The object uri is only the basename, or filename and not a full path.
1002
+     *
1003
+     * It is possible return an etag from this function, which will be used in
1004
+     * the response to this PUT request. Note that the ETag must be surrounded
1005
+     * by double-quotes.
1006
+     *
1007
+     * However, you should only really return this ETag if you don't mangle the
1008
+     * calendar-data. If the result of a subsequent GET to this object is not
1009
+     * the exact same as this request body, you should omit the ETag.
1010
+     *
1011
+     * @param mixed $calendarId
1012
+     * @param string $objectUri
1013
+     * @param string $calendarData
1014
+     * @return string
1015
+     */
1016
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1017
+        $extraData = $this->getDenormalizedData($calendarData);
1018
+
1019
+        $query = $this->db->getQueryBuilder();
1020
+        $query->update('calendarobjects')
1021
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1022
+                ->set('lastmodified', $query->createNamedParameter(time()))
1023
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1024
+                ->set('size', $query->createNamedParameter($extraData['size']))
1025
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1026
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1027
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1028
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1029
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1030
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1031
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1032
+            ->execute();
1033
+
1034
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1035
+
1036
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1037
+        if (is_array($data)) {
1038
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1039
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1040
+                [
1041
+                    'calendarId' => $calendarId,
1042
+                    'calendarData' => $this->getCalendarById($calendarId),
1043
+                    'shares' => $this->getShares($calendarId),
1044
+                    'objectData' => $data,
1045
+                ]
1046
+            ));
1047
+        }
1048
+        $this->addChange($calendarId, $objectUri, 2);
1049
+
1050
+        return '"' . $extraData['etag'] . '"';
1051
+    }
1052
+
1053
+    /**
1054
+     * @param int $calendarObjectId
1055
+     * @param int $classification
1056
+     */
1057
+    public function setClassification($calendarObjectId, $classification) {
1058
+        if (!in_array($classification, [
1059
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1060
+        ])) {
1061
+            throw new \InvalidArgumentException();
1062
+        }
1063
+        $query = $this->db->getQueryBuilder();
1064
+        $query->update('calendarobjects')
1065
+            ->set('classification', $query->createNamedParameter($classification))
1066
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1067
+            ->execute();
1068
+    }
1069
+
1070
+    /**
1071
+     * Deletes an existing calendar object.
1072
+     *
1073
+     * The object uri is only the basename, or filename and not a full path.
1074
+     *
1075
+     * @param mixed $calendarId
1076
+     * @param string $objectUri
1077
+     * @return void
1078
+     */
1079
+    function deleteCalendarObject($calendarId, $objectUri) {
1080
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1081
+        if (is_array($data)) {
1082
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1083
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1084
+                [
1085
+                    'calendarId' => $calendarId,
1086
+                    'calendarData' => $this->getCalendarById($calendarId),
1087
+                    'shares' => $this->getShares($calendarId),
1088
+                    'objectData' => $data,
1089
+                ]
1090
+            ));
1091
+        }
1092
+
1093
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1094
+        $stmt->execute([$calendarId, $objectUri]);
1095
+
1096
+        $this->purgeProperties($calendarId, $data['id']);
1097
+
1098
+        $this->addChange($calendarId, $objectUri, 3);
1099
+    }
1100
+
1101
+    /**
1102
+     * Performs a calendar-query on the contents of this calendar.
1103
+     *
1104
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1105
+     * calendar-query it is possible for a client to request a specific set of
1106
+     * object, based on contents of iCalendar properties, date-ranges and
1107
+     * iCalendar component types (VTODO, VEVENT).
1108
+     *
1109
+     * This method should just return a list of (relative) urls that match this
1110
+     * query.
1111
+     *
1112
+     * The list of filters are specified as an array. The exact array is
1113
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1114
+     *
1115
+     * Note that it is extremely likely that getCalendarObject for every path
1116
+     * returned from this method will be called almost immediately after. You
1117
+     * may want to anticipate this to speed up these requests.
1118
+     *
1119
+     * This method provides a default implementation, which parses *all* the
1120
+     * iCalendar objects in the specified calendar.
1121
+     *
1122
+     * This default may well be good enough for personal use, and calendars
1123
+     * that aren't very large. But if you anticipate high usage, big calendars
1124
+     * or high loads, you are strongly advised to optimize certain paths.
1125
+     *
1126
+     * The best way to do so is override this method and to optimize
1127
+     * specifically for 'common filters'.
1128
+     *
1129
+     * Requests that are extremely common are:
1130
+     *   * requests for just VEVENTS
1131
+     *   * requests for just VTODO
1132
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1133
+     *
1134
+     * ..and combinations of these requests. It may not be worth it to try to
1135
+     * handle every possible situation and just rely on the (relatively
1136
+     * easy to use) CalendarQueryValidator to handle the rest.
1137
+     *
1138
+     * Note that especially time-range-filters may be difficult to parse. A
1139
+     * time-range filter specified on a VEVENT must for instance also handle
1140
+     * recurrence rules correctly.
1141
+     * A good example of how to interprete all these filters can also simply
1142
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1143
+     * as possible, so it gives you a good idea on what type of stuff you need
1144
+     * to think of.
1145
+     *
1146
+     * @param mixed $calendarId
1147
+     * @param array $filters
1148
+     * @return array
1149
+     */
1150
+    function calendarQuery($calendarId, array $filters) {
1151
+        $componentType = null;
1152
+        $requirePostFilter = true;
1153
+        $timeRange = null;
1154
+
1155
+        // if no filters were specified, we don't need to filter after a query
1156
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1157
+            $requirePostFilter = false;
1158
+        }
1159
+
1160
+        // Figuring out if there's a component filter
1161
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1162
+            $componentType = $filters['comp-filters'][0]['name'];
1163
+
1164
+            // Checking if we need post-filters
1165
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1166
+                $requirePostFilter = false;
1167
+            }
1168
+            // There was a time-range filter
1169
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1170
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1171
+
1172
+                // If start time OR the end time is not specified, we can do a
1173
+                // 100% accurate mysql query.
1174
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1175
+                    $requirePostFilter = false;
1176
+                }
1177
+            }
1178
+
1179
+        }
1180
+        $columns = ['uri'];
1181
+        if ($requirePostFilter) {
1182
+            $columns = ['uri', 'calendardata'];
1183
+        }
1184
+        $query = $this->db->getQueryBuilder();
1185
+        $query->select($columns)
1186
+            ->from('calendarobjects')
1187
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1188
+
1189
+        if ($componentType) {
1190
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1191
+        }
1192
+
1193
+        if ($timeRange && $timeRange['start']) {
1194
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1195
+        }
1196
+        if ($timeRange && $timeRange['end']) {
1197
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1198
+        }
1199
+
1200
+        $stmt = $query->execute();
1201
+
1202
+        $result = [];
1203
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1204
+            if ($requirePostFilter) {
1205
+                if (!$this->validateFilterForObject($row, $filters)) {
1206
+                    continue;
1207
+                }
1208
+            }
1209
+            $result[] = $row['uri'];
1210
+        }
1211
+
1212
+        return $result;
1213
+    }
1214
+
1215
+    /**
1216
+     * custom Nextcloud search extension for CalDAV
1217
+     *
1218
+     * @param string $principalUri
1219
+     * @param array $filters
1220
+     * @param integer|null $limit
1221
+     * @param integer|null $offset
1222
+     * @return array
1223
+     */
1224
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1225
+        $calendars = $this->getCalendarsForUser($principalUri);
1226
+        $ownCalendars = [];
1227
+        $sharedCalendars = [];
1228
+
1229
+        $uriMapper = [];
1230
+
1231
+        foreach($calendars as $calendar) {
1232
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1233
+                $ownCalendars[] = $calendar['id'];
1234
+            } else {
1235
+                $sharedCalendars[] = $calendar['id'];
1236
+            }
1237
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1238
+        }
1239
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1240
+            return [];
1241
+        }
1242
+
1243
+        $query = $this->db->getQueryBuilder();
1244
+        // Calendar id expressions
1245
+        $calendarExpressions = [];
1246
+        foreach($ownCalendars as $id) {
1247
+            $calendarExpressions[] = $query->expr()
1248
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1249
+        }
1250
+        foreach($sharedCalendars as $id) {
1251
+            $calendarExpressions[] = $query->expr()->andX(
1252
+                $query->expr()->eq('c.calendarid',
1253
+                    $query->createNamedParameter($id)),
1254
+                $query->expr()->eq('c.classification',
1255
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1256
+            );
1257
+        }
1258
+
1259
+        if (count($calendarExpressions) === 1) {
1260
+            $calExpr = $calendarExpressions[0];
1261
+        } else {
1262
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1263
+        }
1264
+
1265
+        // Component expressions
1266
+        $compExpressions = [];
1267
+        foreach($filters['comps'] as $comp) {
1268
+            $compExpressions[] = $query->expr()
1269
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1270
+        }
1271
+
1272
+        if (count($compExpressions) === 1) {
1273
+            $compExpr = $compExpressions[0];
1274
+        } else {
1275
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1276
+        }
1277
+
1278
+        if (!isset($filters['props'])) {
1279
+            $filters['props'] = [];
1280
+        }
1281
+        if (!isset($filters['params'])) {
1282
+            $filters['params'] = [];
1283
+        }
1284
+
1285
+        $propParamExpressions = [];
1286
+        foreach($filters['props'] as $prop) {
1287
+            $propParamExpressions[] = $query->expr()->andX(
1288
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1289
+                $query->expr()->isNull('i.parameter')
1290
+            );
1291
+        }
1292
+        foreach($filters['params'] as $param) {
1293
+            $propParamExpressions[] = $query->expr()->andX(
1294
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1295
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1296
+            );
1297
+        }
1298
+
1299
+        if (count($propParamExpressions) === 1) {
1300
+            $propParamExpr = $propParamExpressions[0];
1301
+        } else {
1302
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1303
+        }
1304
+
1305
+        $query->select(['c.calendarid', 'c.uri'])
1306
+            ->from($this->dbObjectPropertiesTable, 'i')
1307
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1308
+            ->where($calExpr)
1309
+            ->andWhere($compExpr)
1310
+            ->andWhere($propParamExpr)
1311
+            ->andWhere($query->expr()->iLike('i.value',
1312
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1313
+
1314
+        if ($offset) {
1315
+            $query->setFirstResult($offset);
1316
+        }
1317
+        if ($limit) {
1318
+            $query->setMaxResults($limit);
1319
+        }
1320
+
1321
+        $stmt = $query->execute();
1322
+
1323
+        $result = [];
1324
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1325
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1326
+            if (!in_array($path, $result)) {
1327
+                $result[] = $path;
1328
+            }
1329
+        }
1330
+
1331
+        return $result;
1332
+    }
1333
+
1334
+    /**
1335
+     * Searches through all of a users calendars and calendar objects to find
1336
+     * an object with a specific UID.
1337
+     *
1338
+     * This method should return the path to this object, relative to the
1339
+     * calendar home, so this path usually only contains two parts:
1340
+     *
1341
+     * calendarpath/objectpath.ics
1342
+     *
1343
+     * If the uid is not found, return null.
1344
+     *
1345
+     * This method should only consider * objects that the principal owns, so
1346
+     * any calendars owned by other principals that also appear in this
1347
+     * collection should be ignored.
1348
+     *
1349
+     * @param string $principalUri
1350
+     * @param string $uid
1351
+     * @return string|null
1352
+     */
1353
+    function getCalendarObjectByUID($principalUri, $uid) {
1354
+
1355
+        $query = $this->db->getQueryBuilder();
1356
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1357
+            ->from('calendarobjects', 'co')
1358
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1359
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1360
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1361
+
1362
+        $stmt = $query->execute();
1363
+
1364
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1365
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1366
+        }
1367
+
1368
+        return null;
1369
+    }
1370
+
1371
+    /**
1372
+     * The getChanges method returns all the changes that have happened, since
1373
+     * the specified syncToken in the specified calendar.
1374
+     *
1375
+     * This function should return an array, such as the following:
1376
+     *
1377
+     * [
1378
+     *   'syncToken' => 'The current synctoken',
1379
+     *   'added'   => [
1380
+     *      'new.txt',
1381
+     *   ],
1382
+     *   'modified'   => [
1383
+     *      'modified.txt',
1384
+     *   ],
1385
+     *   'deleted' => [
1386
+     *      'foo.php.bak',
1387
+     *      'old.txt'
1388
+     *   ]
1389
+     * );
1390
+     *
1391
+     * The returned syncToken property should reflect the *current* syncToken
1392
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1393
+     * property This is * needed here too, to ensure the operation is atomic.
1394
+     *
1395
+     * If the $syncToken argument is specified as null, this is an initial
1396
+     * sync, and all members should be reported.
1397
+     *
1398
+     * The modified property is an array of nodenames that have changed since
1399
+     * the last token.
1400
+     *
1401
+     * The deleted property is an array with nodenames, that have been deleted
1402
+     * from collection.
1403
+     *
1404
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1405
+     * 1, you only have to report changes that happened only directly in
1406
+     * immediate descendants. If it's 2, it should also include changes from
1407
+     * the nodes below the child collections. (grandchildren)
1408
+     *
1409
+     * The $limit argument allows a client to specify how many results should
1410
+     * be returned at most. If the limit is not specified, it should be treated
1411
+     * as infinite.
1412
+     *
1413
+     * If the limit (infinite or not) is higher than you're willing to return,
1414
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1415
+     *
1416
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1417
+     * return null.
1418
+     *
1419
+     * The limit is 'suggestive'. You are free to ignore it.
1420
+     *
1421
+     * @param string $calendarId
1422
+     * @param string $syncToken
1423
+     * @param int $syncLevel
1424
+     * @param int $limit
1425
+     * @return array
1426
+     */
1427
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1428
+        // Current synctoken
1429
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1430
+        $stmt->execute([ $calendarId ]);
1431
+        $currentToken = $stmt->fetchColumn(0);
1432
+
1433
+        if (is_null($currentToken)) {
1434
+            return null;
1435
+        }
1436
+
1437
+        $result = [
1438
+            'syncToken' => $currentToken,
1439
+            'added'     => [],
1440
+            'modified'  => [],
1441
+            'deleted'   => [],
1442
+        ];
1443
+
1444
+        if ($syncToken) {
1445
+
1446
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1447
+            if ($limit>0) {
1448
+                $query.= " LIMIT " . (int)$limit;
1449
+            }
1450
+
1451
+            // Fetching all changes
1452
+            $stmt = $this->db->prepare($query);
1453
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1454
+
1455
+            $changes = [];
1456
+
1457
+            // This loop ensures that any duplicates are overwritten, only the
1458
+            // last change on a node is relevant.
1459
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1460
+
1461
+                $changes[$row['uri']] = $row['operation'];
1462
+
1463
+            }
1464
+
1465
+            foreach($changes as $uri => $operation) {
1466
+
1467
+                switch($operation) {
1468
+                    case 1 :
1469
+                        $result['added'][] = $uri;
1470
+                        break;
1471
+                    case 2 :
1472
+                        $result['modified'][] = $uri;
1473
+                        break;
1474
+                    case 3 :
1475
+                        $result['deleted'][] = $uri;
1476
+                        break;
1477
+                }
1478
+
1479
+            }
1480
+        } else {
1481
+            // No synctoken supplied, this is the initial sync.
1482
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1483
+            $stmt = $this->db->prepare($query);
1484
+            $stmt->execute([$calendarId]);
1485
+
1486
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1487
+        }
1488
+        return $result;
1489
+
1490
+    }
1491
+
1492
+    /**
1493
+     * Returns a list of subscriptions for a principal.
1494
+     *
1495
+     * Every subscription is an array with the following keys:
1496
+     *  * id, a unique id that will be used by other functions to modify the
1497
+     *    subscription. This can be the same as the uri or a database key.
1498
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1499
+     *  * principaluri. The owner of the subscription. Almost always the same as
1500
+     *    principalUri passed to this method.
1501
+     *
1502
+     * Furthermore, all the subscription info must be returned too:
1503
+     *
1504
+     * 1. {DAV:}displayname
1505
+     * 2. {http://apple.com/ns/ical/}refreshrate
1506
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1507
+     *    should not be stripped).
1508
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1509
+     *    should not be stripped).
1510
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1511
+     *    attachments should not be stripped).
1512
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1513
+     *     Sabre\DAV\Property\Href).
1514
+     * 7. {http://apple.com/ns/ical/}calendar-color
1515
+     * 8. {http://apple.com/ns/ical/}calendar-order
1516
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1517
+     *    (should just be an instance of
1518
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1519
+     *    default components).
1520
+     *
1521
+     * @param string $principalUri
1522
+     * @return array
1523
+     */
1524
+    function getSubscriptionsForUser($principalUri) {
1525
+        $fields = array_values($this->subscriptionPropertyMap);
1526
+        $fields[] = 'id';
1527
+        $fields[] = 'uri';
1528
+        $fields[] = 'source';
1529
+        $fields[] = 'principaluri';
1530
+        $fields[] = 'lastmodified';
1531
+
1532
+        $query = $this->db->getQueryBuilder();
1533
+        $query->select($fields)
1534
+            ->from('calendarsubscriptions')
1535
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1536
+            ->orderBy('calendarorder', 'asc');
1537
+        $stmt =$query->execute();
1538
+
1539
+        $subscriptions = [];
1540
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1541
+
1542
+            $subscription = [
1543
+                'id'           => $row['id'],
1544
+                'uri'          => $row['uri'],
1545
+                'principaluri' => $row['principaluri'],
1546
+                'source'       => $row['source'],
1547
+                'lastmodified' => $row['lastmodified'],
1548
+
1549
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1550
+            ];
1551
+
1552
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1553
+                if (!is_null($row[$dbName])) {
1554
+                    $subscription[$xmlName] = $row[$dbName];
1555
+                }
1556
+            }
1557
+
1558
+            $subscriptions[] = $subscription;
1559
+
1560
+        }
1561
+
1562
+        return $subscriptions;
1563
+    }
1564
+
1565
+    /**
1566
+     * Creates a new subscription for a principal.
1567
+     *
1568
+     * If the creation was a success, an id must be returned that can be used to reference
1569
+     * this subscription in other methods, such as updateSubscription.
1570
+     *
1571
+     * @param string $principalUri
1572
+     * @param string $uri
1573
+     * @param array $properties
1574
+     * @return mixed
1575
+     */
1576
+    function createSubscription($principalUri, $uri, array $properties) {
1577
+
1578
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1579
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1580
+        }
1581
+
1582
+        $values = [
1583
+            'principaluri' => $principalUri,
1584
+            'uri'          => $uri,
1585
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1586
+            'lastmodified' => time(),
1587
+        ];
1588
+
1589
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1590
+
1591
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1592
+            if (array_key_exists($xmlName, $properties)) {
1593
+                    $values[$dbName] = $properties[$xmlName];
1594
+                    if (in_array($dbName, $propertiesBoolean)) {
1595
+                        $values[$dbName] = true;
1596
+                }
1597
+            }
1598
+        }
1599
+
1600
+        $valuesToInsert = array();
1601
+
1602
+        $query = $this->db->getQueryBuilder();
1603
+
1604
+        foreach (array_keys($values) as $name) {
1605
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1606
+        }
1607
+
1608
+        $query->insert('calendarsubscriptions')
1609
+            ->values($valuesToInsert)
1610
+            ->execute();
1611
+
1612
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1613
+    }
1614
+
1615
+    /**
1616
+     * Updates a subscription
1617
+     *
1618
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1619
+     * To do the actual updates, you must tell this object which properties
1620
+     * you're going to process with the handle() method.
1621
+     *
1622
+     * Calling the handle method is like telling the PropPatch object "I
1623
+     * promise I can handle updating this property".
1624
+     *
1625
+     * Read the PropPatch documentation for more info and examples.
1626
+     *
1627
+     * @param mixed $subscriptionId
1628
+     * @param PropPatch $propPatch
1629
+     * @return void
1630
+     */
1631
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1632
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1633
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1634
+
1635
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1636
+
1637
+            $newValues = [];
1638
+
1639
+            foreach($mutations as $propertyName=>$propertyValue) {
1640
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1641
+                    $newValues['source'] = $propertyValue->getHref();
1642
+                } else {
1643
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1644
+                    $newValues[$fieldName] = $propertyValue;
1645
+                }
1646
+            }
1647
+
1648
+            $query = $this->db->getQueryBuilder();
1649
+            $query->update('calendarsubscriptions')
1650
+                ->set('lastmodified', $query->createNamedParameter(time()));
1651
+            foreach($newValues as $fieldName=>$value) {
1652
+                $query->set($fieldName, $query->createNamedParameter($value));
1653
+            }
1654
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1655
+                ->execute();
1656
+
1657
+            return true;
1658
+
1659
+        });
1660
+    }
1661
+
1662
+    /**
1663
+     * Deletes a subscription.
1664
+     *
1665
+     * @param mixed $subscriptionId
1666
+     * @return void
1667
+     */
1668
+    function deleteSubscription($subscriptionId) {
1669
+        $query = $this->db->getQueryBuilder();
1670
+        $query->delete('calendarsubscriptions')
1671
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1672
+            ->execute();
1673
+    }
1674
+
1675
+    /**
1676
+     * Returns a single scheduling object for the inbox collection.
1677
+     *
1678
+     * The returned array should contain the following elements:
1679
+     *   * uri - A unique basename for the object. This will be used to
1680
+     *           construct a full uri.
1681
+     *   * calendardata - The iCalendar object
1682
+     *   * lastmodified - The last modification date. Can be an int for a unix
1683
+     *                    timestamp, or a PHP DateTime object.
1684
+     *   * etag - A unique token that must change if the object changed.
1685
+     *   * size - The size of the object, in bytes.
1686
+     *
1687
+     * @param string $principalUri
1688
+     * @param string $objectUri
1689
+     * @return array
1690
+     */
1691
+    function getSchedulingObject($principalUri, $objectUri) {
1692
+        $query = $this->db->getQueryBuilder();
1693
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1694
+            ->from('schedulingobjects')
1695
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1696
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1697
+            ->execute();
1698
+
1699
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1700
+
1701
+        if(!$row) {
1702
+            return null;
1703
+        }
1704
+
1705
+        return [
1706
+                'uri'          => $row['uri'],
1707
+                'calendardata' => $row['calendardata'],
1708
+                'lastmodified' => $row['lastmodified'],
1709
+                'etag'         => '"' . $row['etag'] . '"',
1710
+                'size'         => (int)$row['size'],
1711
+        ];
1712
+    }
1713
+
1714
+    /**
1715
+     * Returns all scheduling objects for the inbox collection.
1716
+     *
1717
+     * These objects should be returned as an array. Every item in the array
1718
+     * should follow the same structure as returned from getSchedulingObject.
1719
+     *
1720
+     * The main difference is that 'calendardata' is optional.
1721
+     *
1722
+     * @param string $principalUri
1723
+     * @return array
1724
+     */
1725
+    function getSchedulingObjects($principalUri) {
1726
+        $query = $this->db->getQueryBuilder();
1727
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1728
+                ->from('schedulingobjects')
1729
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1730
+                ->execute();
1731
+
1732
+        $result = [];
1733
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1734
+            $result[] = [
1735
+                    'calendardata' => $row['calendardata'],
1736
+                    'uri'          => $row['uri'],
1737
+                    'lastmodified' => $row['lastmodified'],
1738
+                    'etag'         => '"' . $row['etag'] . '"',
1739
+                    'size'         => (int)$row['size'],
1740
+            ];
1741
+        }
1742
+
1743
+        return $result;
1744
+    }
1745
+
1746
+    /**
1747
+     * Deletes a scheduling object from the inbox collection.
1748
+     *
1749
+     * @param string $principalUri
1750
+     * @param string $objectUri
1751
+     * @return void
1752
+     */
1753
+    function deleteSchedulingObject($principalUri, $objectUri) {
1754
+        $query = $this->db->getQueryBuilder();
1755
+        $query->delete('schedulingobjects')
1756
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1757
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1758
+                ->execute();
1759
+    }
1760
+
1761
+    /**
1762
+     * Creates a new scheduling object. This should land in a users' inbox.
1763
+     *
1764
+     * @param string $principalUri
1765
+     * @param string $objectUri
1766
+     * @param string $objectData
1767
+     * @return void
1768
+     */
1769
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1770
+        $query = $this->db->getQueryBuilder();
1771
+        $query->insert('schedulingobjects')
1772
+            ->values([
1773
+                'principaluri' => $query->createNamedParameter($principalUri),
1774
+                'calendardata' => $query->createNamedParameter($objectData),
1775
+                'uri' => $query->createNamedParameter($objectUri),
1776
+                'lastmodified' => $query->createNamedParameter(time()),
1777
+                'etag' => $query->createNamedParameter(md5($objectData)),
1778
+                'size' => $query->createNamedParameter(strlen($objectData))
1779
+            ])
1780
+            ->execute();
1781
+    }
1782
+
1783
+    /**
1784
+     * Adds a change record to the calendarchanges table.
1785
+     *
1786
+     * @param mixed $calendarId
1787
+     * @param string $objectUri
1788
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1789
+     * @return void
1790
+     */
1791
+    protected function addChange($calendarId, $objectUri, $operation) {
1792
+
1793
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1794
+        $stmt->execute([
1795
+            $objectUri,
1796
+            $calendarId,
1797
+            $operation,
1798
+            $calendarId
1799
+        ]);
1800
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1801
+        $stmt->execute([
1802
+            $calendarId
1803
+        ]);
1804
+
1805
+    }
1806
+
1807
+    /**
1808
+     * Parses some information from calendar objects, used for optimized
1809
+     * calendar-queries.
1810
+     *
1811
+     * Returns an array with the following keys:
1812
+     *   * etag - An md5 checksum of the object without the quotes.
1813
+     *   * size - Size of the object in bytes
1814
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1815
+     *   * firstOccurence
1816
+     *   * lastOccurence
1817
+     *   * uid - value of the UID property
1818
+     *
1819
+     * @param string $calendarData
1820
+     * @return array
1821
+     */
1822
+    public function getDenormalizedData($calendarData) {
1823
+
1824
+        $vObject = Reader::read($calendarData);
1825
+        $componentType = null;
1826
+        $component = null;
1827
+        $firstOccurrence = null;
1828
+        $lastOccurrence = null;
1829
+        $uid = null;
1830
+        $classification = self::CLASSIFICATION_PUBLIC;
1831
+        foreach($vObject->getComponents() as $component) {
1832
+            if ($component->name!=='VTIMEZONE') {
1833
+                $componentType = $component->name;
1834
+                $uid = (string)$component->UID;
1835
+                break;
1836
+            }
1837
+        }
1838
+        if (!$componentType) {
1839
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1840
+        }
1841
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1842
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1843
+            // Finding the last occurrence is a bit harder
1844
+            if (!isset($component->RRULE)) {
1845
+                if (isset($component->DTEND)) {
1846
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1847
+                } elseif (isset($component->DURATION)) {
1848
+                    $endDate = clone $component->DTSTART->getDateTime();
1849
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1850
+                    $lastOccurrence = $endDate->getTimeStamp();
1851
+                } elseif (!$component->DTSTART->hasTime()) {
1852
+                    $endDate = clone $component->DTSTART->getDateTime();
1853
+                    $endDate->modify('+1 day');
1854
+                    $lastOccurrence = $endDate->getTimeStamp();
1855
+                } else {
1856
+                    $lastOccurrence = $firstOccurrence;
1857
+                }
1858
+            } else {
1859
+                $it = new EventIterator($vObject, (string)$component->UID);
1860
+                $maxDate = new \DateTime(self::MAX_DATE);
1861
+                if ($it->isInfinite()) {
1862
+                    $lastOccurrence = $maxDate->getTimestamp();
1863
+                } else {
1864
+                    $end = $it->getDtEnd();
1865
+                    while($it->valid() && $end < $maxDate) {
1866
+                        $end = $it->getDtEnd();
1867
+                        $it->next();
1868
+
1869
+                    }
1870
+                    $lastOccurrence = $end->getTimestamp();
1871
+                }
1872
+
1873
+            }
1874
+        }
1875
+
1876
+        if ($component->CLASS) {
1877
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1878
+            switch ($component->CLASS->getValue()) {
1879
+                case 'PUBLIC':
1880
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1881
+                    break;
1882
+                case 'CONFIDENTIAL':
1883
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1884
+                    break;
1885
+            }
1886
+        }
1887
+        return [
1888
+            'etag' => md5($calendarData),
1889
+            'size' => strlen($calendarData),
1890
+            'componentType' => $componentType,
1891
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1892
+            'lastOccurence'  => $lastOccurrence,
1893
+            'uid' => $uid,
1894
+            'classification' => $classification
1895
+        ];
1896
+
1897
+    }
1898
+
1899
+    private function readBlob($cardData) {
1900
+        if (is_resource($cardData)) {
1901
+            return stream_get_contents($cardData);
1902
+        }
1903
+
1904
+        return $cardData;
1905
+    }
1906
+
1907
+    /**
1908
+     * @param IShareable $shareable
1909
+     * @param array $add
1910
+     * @param array $remove
1911
+     */
1912
+    public function updateShares($shareable, $add, $remove) {
1913
+        $calendarId = $shareable->getResourceId();
1914
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1915
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1916
+            [
1917
+                'calendarId' => $calendarId,
1918
+                'calendarData' => $this->getCalendarById($calendarId),
1919
+                'shares' => $this->getShares($calendarId),
1920
+                'add' => $add,
1921
+                'remove' => $remove,
1922
+            ]));
1923
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1924
+    }
1925
+
1926
+    /**
1927
+     * @param int $resourceId
1928
+     * @return array
1929
+     */
1930
+    public function getShares($resourceId) {
1931
+        return $this->sharingBackend->getShares($resourceId);
1932
+    }
1933
+
1934
+    /**
1935
+     * @param boolean $value
1936
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1937
+     * @return string|null
1938
+     */
1939
+    public function setPublishStatus($value, $calendar) {
1940
+        $query = $this->db->getQueryBuilder();
1941
+        if ($value) {
1942
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1943
+            $query->insert('dav_shares')
1944
+                ->values([
1945
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1946
+                    'type' => $query->createNamedParameter('calendar'),
1947
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1948
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1949
+                    'publicuri' => $query->createNamedParameter($publicUri)
1950
+                ]);
1951
+            $query->execute();
1952
+            return $publicUri;
1953
+        }
1954
+        $query->delete('dav_shares')
1955
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1956
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1957
+        $query->execute();
1958
+        return null;
1959
+    }
1960
+
1961
+    /**
1962
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1963
+     * @return mixed
1964
+     */
1965
+    public function getPublishStatus($calendar) {
1966
+        $query = $this->db->getQueryBuilder();
1967
+        $result = $query->select('publicuri')
1968
+            ->from('dav_shares')
1969
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1970
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1971
+            ->execute();
1972
+
1973
+        $row = $result->fetch();
1974
+        $result->closeCursor();
1975
+        return $row ? reset($row) : false;
1976
+    }
1977
+
1978
+    /**
1979
+     * @param int $resourceId
1980
+     * @param array $acl
1981
+     * @return array
1982
+     */
1983
+    public function applyShareAcl($resourceId, $acl) {
1984
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1985
+    }
1986
+
1987
+
1988
+
1989
+    /**
1990
+     * update properties table
1991
+     *
1992
+     * @param int $calendarId
1993
+     * @param string $objectUri
1994
+     * @param string $calendarData
1995
+     */
1996
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
1997
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
1998
+
1999
+        try {
2000
+            $vCalendar = $this->readCalendarData($calendarData);
2001
+        } catch (\Exception $ex) {
2002
+            return;
2003
+        }
2004
+
2005
+        $this->purgeProperties($calendarId, $objectId);
2006
+
2007
+        $query = $this->db->getQueryBuilder();
2008
+        $query->insert($this->dbObjectPropertiesTable)
2009
+            ->values(
2010
+                [
2011
+                    'calendarid' => $query->createNamedParameter($calendarId),
2012
+                    'objectid' => $query->createNamedParameter($objectId),
2013
+                    'name' => $query->createParameter('name'),
2014
+                    'parameter' => $query->createParameter('parameter'),
2015
+                    'value' => $query->createParameter('value'),
2016
+                ]
2017
+            );
2018
+
2019
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2020
+        foreach ($vCalendar->getComponents() as $component) {
2021
+            if (!in_array($component->name, $indexComponents)) {
2022
+                continue;
2023
+            }
2024
+
2025
+            foreach ($component->children() as $property) {
2026
+                if (in_array($property->name, self::$indexProperties)) {
2027
+                    $value = $property->getValue();
2028
+                    // is this a shitty db?
2029
+                    if (!$this->db->supports4ByteText()) {
2030
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2031
+                    }
2032
+                    $value = mb_substr($value, 0, 254);
2033
+
2034
+                    $query->setParameter('name', $property->name);
2035
+                    $query->setParameter('parameter', null);
2036
+                    $query->setParameter('value', $value);
2037
+                    $query->execute();
2038
+                }
2039
+
2040
+                if (in_array($property->name, array_keys(self::$indexParameters))) {
2041
+                    $parameters = $property->parameters();
2042
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2043
+
2044
+                    foreach ($parameters as $key => $value) {
2045
+                        if (in_array($key, $indexedParametersForProperty)) {
2046
+                            // is this a shitty db?
2047
+                            if ($this->db->supports4ByteText()) {
2048
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2049
+                            }
2050
+                            $value = mb_substr($value, 0, 254);
2051
+
2052
+                            $query->setParameter('name', $property->name);
2053
+                            $query->setParameter('parameter', substr($key, 0, 254));
2054
+                            $query->setParameter('value', substr($value, 0, 254));
2055
+                            $query->execute();
2056
+                        }
2057
+                    }
2058
+                }
2059
+            }
2060
+        }
2061
+    }
2062
+
2063
+    /**
2064
+     * read VCalendar data into a VCalendar object
2065
+     *
2066
+     * @param string $objectData
2067
+     * @return VCalendar
2068
+     */
2069
+    protected function readCalendarData($objectData) {
2070
+        return Reader::read($objectData);
2071
+    }
2072
+
2073
+    /**
2074
+     * delete all properties from a given calendar object
2075
+     *
2076
+     * @param int $calendarId
2077
+     * @param int $objectId
2078
+     */
2079
+    protected function purgeProperties($calendarId, $objectId) {
2080
+        $query = $this->db->getQueryBuilder();
2081
+        $query->delete($this->dbObjectPropertiesTable)
2082
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2083
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2084
+        $query->execute();
2085
+    }
2086
+
2087
+    /**
2088
+     * get ID from a given calendar object
2089
+     *
2090
+     * @param int $calendarId
2091
+     * @param string $uri
2092
+     * @return int
2093
+     */
2094
+    protected function getCalendarObjectId($calendarId, $uri) {
2095
+        $query = $this->db->getQueryBuilder();
2096
+        $query->select('id')->from('calendarobjects')
2097
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2098
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2099
+
2100
+        $result = $query->execute();
2101
+        $objectIds = $result->fetch();
2102
+        $result->closeCursor();
2103
+
2104
+        if (!isset($objectIds['id'])) {
2105
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2106
+        }
2107
+
2108
+        return (int)$objectIds['id'];
2109
+    }
2110
+
2111
+    private function convertPrincipal($principalUri, $toV2) {
2112
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2113
+            list(, $name) = URLUtil::splitPath($principalUri);
2114
+            if ($toV2 === true) {
2115
+                return "principals/users/$name";
2116
+            }
2117
+            return "principals/$name";
2118
+        }
2119
+        return $principalUri;
2120
+    }
2121
+
2122
+    private function addOwnerPrincipal(&$calendarInfo) {
2123
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2124
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2125
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2126
+            $uri = $calendarInfo[$ownerPrincipalKey];
2127
+        } else {
2128
+            $uri = $calendarInfo['principaluri'];
2129
+        }
2130
+
2131
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2132
+        if (isset($principalInformation['{DAV:}displayname'])) {
2133
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2134
+        }
2135
+    }
2136 2136
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Plugin.php 2 patches
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -25,17 +25,17 @@
 block discarded – undo
25 25
 
26 26
 class Plugin extends \Sabre\CalDAV\Plugin {
27 27
 
28
-	/**
29
-	 * @inheritdoc
30
-	 */
31
-	function getCalendarHomeForPrincipal($principalUrl) {
28
+    /**
29
+     * @inheritdoc
30
+     */
31
+    function getCalendarHomeForPrincipal($principalUrl) {
32 32
 
33
-		if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
34
-			list(, $principalId) = URLUtil::splitPath($principalUrl);
35
-			return self::CALENDAR_ROOT .'/' . $principalId;
36
-		}
33
+        if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
34
+            list(, $principalId) = URLUtil::splitPath($principalUrl);
35
+            return self::CALENDAR_ROOT .'/' . $principalId;
36
+        }
37 37
 
38
-		return;
39
-	}
38
+        return;
39
+    }
40 40
 
41 41
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@
 block discarded – undo
32 32
 
33 33
 		if (strrpos($principalUrl, 'principals/users', -strlen($principalUrl)) !== false) {
34 34
 			list(, $principalId) = URLUtil::splitPath($principalUrl);
35
-			return self::CALENDAR_ROOT .'/' . $principalId;
35
+			return self::CALENDAR_ROOT.'/'.$principalId;
36 36
 		}
37 37
 
38 38
 		return;
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarObject.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -61,19 +61,19 @@
 block discarded – undo
61 61
 
62 62
 		/** @var Component $vElement */
63 63
 		$vElement = null;
64
-		if(isset($vObject->VEVENT)) {
64
+		if (isset($vObject->VEVENT)) {
65 65
 			$vElement = $vObject->VEVENT;
66 66
 		}
67
-		if(isset($vObject->VJOURNAL)) {
67
+		if (isset($vObject->VJOURNAL)) {
68 68
 			$vElement = $vObject->VJOURNAL;
69 69
 		}
70
-		if(isset($vObject->VTODO)) {
70
+		if (isset($vObject->VTODO)) {
71 71
 			$vElement = $vObject->VTODO;
72 72
 		}
73
-		if(!is_null($vElement)) {
73
+		if (!is_null($vElement)) {
74 74
 			foreach ($vElement->children() as &$property) {
75 75
 				/** @var Property $property */
76
-				switch($property->name) {
76
+				switch ($property->name) {
77 77
 					case 'CREATED':
78 78
 					case 'DTSTART':
79 79
 					case 'RRULE':
Please login to merge, or discard this patch.
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -32,68 +32,68 @@
 block discarded – undo
32 32
 
33 33
 class CalendarObject extends \Sabre\CalDAV\CalendarObject {
34 34
 
35
-	/**
36
-	 * @inheritdoc
37
-	 */
38
-	function get() {
39
-		$data = parent::get();
40
-		if ($this->isShared() && $this->objectData['classification'] === CalDavBackend::CLASSIFICATION_CONFIDENTIAL) {
41
-			return $this->createConfidentialObject($data);
42
-		}
43
-		return $data;
44
-	}
35
+    /**
36
+     * @inheritdoc
37
+     */
38
+    function get() {
39
+        $data = parent::get();
40
+        if ($this->isShared() && $this->objectData['classification'] === CalDavBackend::CLASSIFICATION_CONFIDENTIAL) {
41
+            return $this->createConfidentialObject($data);
42
+        }
43
+        return $data;
44
+    }
45 45
 
46
-	protected function isShared() {
47
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
48
-			return false;
49
-		}
46
+    protected function isShared() {
47
+        if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
48
+            return false;
49
+        }
50 50
 
51
-		return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
52
-	}
51
+        return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
52
+    }
53 53
 
54
-	/**
55
-	 * @param string $calData
56
-	 * @return string
57
-	 */
58
-	private static function createConfidentialObject($calData) {
54
+    /**
55
+     * @param string $calData
56
+     * @return string
57
+     */
58
+    private static function createConfidentialObject($calData) {
59 59
 
60
-		$vObject = Reader::read($calData);
60
+        $vObject = Reader::read($calData);
61 61
 
62
-		/** @var Component $vElement */
63
-		$vElement = null;
64
-		if(isset($vObject->VEVENT)) {
65
-			$vElement = $vObject->VEVENT;
66
-		}
67
-		if(isset($vObject->VJOURNAL)) {
68
-			$vElement = $vObject->VJOURNAL;
69
-		}
70
-		if(isset($vObject->VTODO)) {
71
-			$vElement = $vObject->VTODO;
72
-		}
73
-		if(!is_null($vElement)) {
74
-			foreach ($vElement->children() as &$property) {
75
-				/** @var Property $property */
76
-				switch($property->name) {
77
-					case 'CREATED':
78
-					case 'DTSTART':
79
-					case 'RRULE':
80
-					case 'DURATION':
81
-					case 'DTEND':
82
-					case 'CLASS':
83
-					case 'UID':
84
-						break;
85
-					case 'SUMMARY':
86
-						$property->setValue('Busy');
87
-						break;
88
-					default:
89
-						$vElement->__unset($property->name);
90
-						unset($property);
91
-						break;
92
-				}
93
-			}
94
-		}
62
+        /** @var Component $vElement */
63
+        $vElement = null;
64
+        if(isset($vObject->VEVENT)) {
65
+            $vElement = $vObject->VEVENT;
66
+        }
67
+        if(isset($vObject->VJOURNAL)) {
68
+            $vElement = $vObject->VJOURNAL;
69
+        }
70
+        if(isset($vObject->VTODO)) {
71
+            $vElement = $vObject->VTODO;
72
+        }
73
+        if(!is_null($vElement)) {
74
+            foreach ($vElement->children() as &$property) {
75
+                /** @var Property $property */
76
+                switch($property->name) {
77
+                    case 'CREATED':
78
+                    case 'DTSTART':
79
+                    case 'RRULE':
80
+                    case 'DURATION':
81
+                    case 'DTEND':
82
+                    case 'CLASS':
83
+                    case 'UID':
84
+                        break;
85
+                    case 'SUMMARY':
86
+                        $property->setValue('Busy');
87
+                        break;
88
+                    default:
89
+                        $vElement->__unset($property->name);
90
+                        unset($property);
91
+                        break;
92
+                }
93
+            }
94
+        }
95 95
 		
96
-		return $vObject->serialize();
97
-	}
96
+        return $vObject->serialize();
97
+    }
98 98
 
99 99
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Schedule/Plugin.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	 */
71 71
 	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
72 72
 		if ($node instanceof IPrincipal) {
73
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
73
+			$propFind->handle('{'.self::NS_CALDAV.'}schedule-default-calendar-URL', function() use ($node) {
74 74
 				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
75 75
 				$caldavPlugin = $this->server->getPlugin('caldav');
76 76
 				$principalUrl = $node->getPrincipalUrl();
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 					]);
90 90
 				}
91 91
 
92
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
92
+				$result = $this->server->getPropertiesForPath($calendarHomePath.'/'.CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
93 93
 				if (empty($result)) {
94 94
 					return null;
95 95
 				}
Please login to merge, or discard this patch.
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -38,131 +38,131 @@
 block discarded – undo
38 38
 
39 39
 class Plugin extends \Sabre\CalDAV\Schedule\Plugin {
40 40
 
41
-	/**
42
-	 * Initializes the plugin
43
-	 *
44
-	 * @param Server $server
45
-	 * @return void
46
-	 */
47
-	function initialize(Server $server) {
48
-		parent::initialize($server);
49
-		$server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
-	}
51
-
52
-	/**
53
-	 * Returns a list of addresses that are associated with a principal.
54
-	 *
55
-	 * @param string $principal
56
-	 * @return array
57
-	 */
58
-	protected function getAddressesForPrincipal($principal) {
59
-		$result = parent::getAddressesForPrincipal($principal);
60
-
61
-		if ($result === null) {
62
-			$result = [];
63
-		}
64
-
65
-		return $result;
66
-	}
67
-
68
-	/**
69
-	 * Always use the personal calendar as target for scheduled events
70
-	 *
71
-	 * @param PropFind $propFind
72
-	 * @param INode $node
73
-	 * @return void
74
-	 */
75
-	function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
-		if ($node instanceof IPrincipal) {
77
-			$propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
-				/** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
-				$caldavPlugin = $this->server->getPlugin('caldav');
80
-				$principalUrl = $node->getPrincipalUrl();
81
-
82
-				$calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
-
84
-				if (!$calendarHomePath) {
85
-					return null;
86
-				}
87
-
88
-				/** @var CalendarHome $calendarHome */
89
-				$calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
90
-				if (!$calendarHome->childExists(CalDavBackend::PERSONAL_CALENDAR_URI)) {
91
-					$calendarHome->getCalDAVBackend()->createCalendar($principalUrl, CalDavBackend::PERSONAL_CALENDAR_URI, [
92
-						'{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
93
-					]);
94
-				}
95
-
96
-				$result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
97
-				if (empty($result)) {
98
-					return null;
99
-				}
100
-
101
-				return new LocalHref($result[0]['href']);
102
-			});
103
-		}
104
-	}
105
-
106
-	/**
107
-	 * This method is triggered whenever there was a calendar object gets
108
-	 * created or updated.
109
-	 *
110
-	 * Basically just a copy of parent::calendarObjectChange, with the change
111
-	 * from:
112
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
113
-	 * to:
114
-	 * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
115
-	 *
116
-	 * @param RequestInterface $request HTTP request
117
-	 * @param ResponseInterface $response HTTP Response
118
-	 * @param VCalendar $vCal Parsed iCalendar object
119
-	 * @param mixed $calendarPath Path to calendar collection
120
-	 * @param mixed $modified The iCalendar object has been touched.
121
-	 * @param mixed $isNew Whether this was a new item or we're updating one
122
-	 * @return void
123
-	 */
124
-	function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
125
-
126
-		if (!$this->scheduleReply($this->server->httpRequest)) {
127
-			return;
128
-		}
129
-
130
-		$calendarNode = $this->server->tree->getNodeForPath($calendarPath);
131
-
132
-		$addresses = $this->getAddressesForPrincipal(
133
-			$calendarNode->getPrincipalURI()
134
-		);
135
-
136
-		if (!$isNew) {
137
-			$node = $this->server->tree->getNodeForPath($request->getPath());
138
-			$oldObj = Reader::read($node->get());
139
-		} else {
140
-			$oldObj = null;
141
-		}
142
-
143
-		$this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
144
-
145
-		if ($oldObj) {
146
-			// Destroy circular references so PHP will GC the object.
147
-			$oldObj->destroy();
148
-		}
149
-
150
-	}
151
-
152
-	/**
153
-	 * This method checks the 'Schedule-Reply' header
154
-	 * and returns false if it's 'F', otherwise true.
155
-	 *
156
-	 * Copied from Sabre/DAV's Schedule plugin, because it's
157
-	 * private for whatever reason
158
-	 *
159
-	 * @param RequestInterface $request
160
-	 * @return bool
161
-	 */
162
-	private function scheduleReply(RequestInterface $request) {
163
-
164
-		$scheduleReply = $request->getHeader('Schedule-Reply');
165
-		return $scheduleReply !== 'F';
166
-
167
-	}
41
+    /**
42
+     * Initializes the plugin
43
+     *
44
+     * @param Server $server
45
+     * @return void
46
+     */
47
+    function initialize(Server $server) {
48
+        parent::initialize($server);
49
+        $server->on('propFind', [$this, 'propFindDefaultCalendarUrl'], 90);
50
+    }
51
+
52
+    /**
53
+     * Returns a list of addresses that are associated with a principal.
54
+     *
55
+     * @param string $principal
56
+     * @return array
57
+     */
58
+    protected function getAddressesForPrincipal($principal) {
59
+        $result = parent::getAddressesForPrincipal($principal);
60
+
61
+        if ($result === null) {
62
+            $result = [];
63
+        }
64
+
65
+        return $result;
66
+    }
67
+
68
+    /**
69
+     * Always use the personal calendar as target for scheduled events
70
+     *
71
+     * @param PropFind $propFind
72
+     * @param INode $node
73
+     * @return void
74
+     */
75
+    function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) {
76
+        if ($node instanceof IPrincipal) {
77
+            $propFind->handle('{' . self::NS_CALDAV . '}schedule-default-calendar-URL', function() use ($node) {
78
+                /** @var \OCA\DAV\CalDAV\Plugin $caldavPlugin */
79
+                $caldavPlugin = $this->server->getPlugin('caldav');
80
+                $principalUrl = $node->getPrincipalUrl();
81
+
82
+                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
83
+
84
+                if (!$calendarHomePath) {
85
+                    return null;
86
+                }
87
+
88
+                /** @var CalendarHome $calendarHome */
89
+                $calendarHome = $this->server->tree->getNodeForPath($calendarHomePath);
90
+                if (!$calendarHome->childExists(CalDavBackend::PERSONAL_CALENDAR_URI)) {
91
+                    $calendarHome->getCalDAVBackend()->createCalendar($principalUrl, CalDavBackend::PERSONAL_CALENDAR_URI, [
92
+                        '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME,
93
+                    ]);
94
+                }
95
+
96
+                $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . CalDavBackend::PERSONAL_CALENDAR_URI, [], 1);
97
+                if (empty($result)) {
98
+                    return null;
99
+                }
100
+
101
+                return new LocalHref($result[0]['href']);
102
+            });
103
+        }
104
+    }
105
+
106
+    /**
107
+     * This method is triggered whenever there was a calendar object gets
108
+     * created or updated.
109
+     *
110
+     * Basically just a copy of parent::calendarObjectChange, with the change
111
+     * from:
112
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getOwner());
113
+     * to:
114
+     * $addresses = $this->getAddressesForPrincipal($calendarNode->getPrincipalURI());
115
+     *
116
+     * @param RequestInterface $request HTTP request
117
+     * @param ResponseInterface $response HTTP Response
118
+     * @param VCalendar $vCal Parsed iCalendar object
119
+     * @param mixed $calendarPath Path to calendar collection
120
+     * @param mixed $modified The iCalendar object has been touched.
121
+     * @param mixed $isNew Whether this was a new item or we're updating one
122
+     * @return void
123
+     */
124
+    function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) {
125
+
126
+        if (!$this->scheduleReply($this->server->httpRequest)) {
127
+            return;
128
+        }
129
+
130
+        $calendarNode = $this->server->tree->getNodeForPath($calendarPath);
131
+
132
+        $addresses = $this->getAddressesForPrincipal(
133
+            $calendarNode->getPrincipalURI()
134
+        );
135
+
136
+        if (!$isNew) {
137
+            $node = $this->server->tree->getNodeForPath($request->getPath());
138
+            $oldObj = Reader::read($node->get());
139
+        } else {
140
+            $oldObj = null;
141
+        }
142
+
143
+        $this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified);
144
+
145
+        if ($oldObj) {
146
+            // Destroy circular references so PHP will GC the object.
147
+            $oldObj->destroy();
148
+        }
149
+
150
+    }
151
+
152
+    /**
153
+     * This method checks the 'Schedule-Reply' header
154
+     * and returns false if it's 'F', otherwise true.
155
+     *
156
+     * Copied from Sabre/DAV's Schedule plugin, because it's
157
+     * private for whatever reason
158
+     *
159
+     * @param RequestInterface $request
160
+     * @return bool
161
+     */
162
+    private function scheduleReply(RequestInterface $request) {
163
+
164
+        $scheduleReply = $request->getHeader('Schedule-Reply');
165
+        return $scheduleReply !== 'F';
166
+
167
+    }
168 168
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -26,58 +26,58 @@
 block discarded – undo
26 26
 
27 27
 class Publisher implements XmlSerializable {
28 28
 
29
-	/**
30
-	 * @var string $publishUrl
31
-	 */
32
-	protected $publishUrl;
29
+    /**
30
+     * @var string $publishUrl
31
+     */
32
+    protected $publishUrl;
33 33
 
34
-	/**
35
-	 * @var boolean $isPublished
36
-	 */
37
-	protected $isPublished;
34
+    /**
35
+     * @var boolean $isPublished
36
+     */
37
+    protected $isPublished;
38 38
 
39
-	/**
40
-	 * @param string $publishUrl
41
-	 * @param boolean $isPublished
42
-	 */
43
-	function __construct($publishUrl, $isPublished) {
44
-		$this->publishUrl = $publishUrl;
45
-		$this->isPublished = $isPublished;
46
-	}
39
+    /**
40
+     * @param string $publishUrl
41
+     * @param boolean $isPublished
42
+     */
43
+    function __construct($publishUrl, $isPublished) {
44
+        $this->publishUrl = $publishUrl;
45
+        $this->isPublished = $isPublished;
46
+    }
47 47
 
48
-	/**
49
-	 * @return string
50
-	 */
51
-	function getValue() {
52
-		return $this->publishUrl;
53
-	}
48
+    /**
49
+     * @return string
50
+     */
51
+    function getValue() {
52
+        return $this->publishUrl;
53
+    }
54 54
 
55
-	/**
56
-	 * The xmlSerialize metod is called during xml writing.
57
-	 *
58
-	 * Use the $writer argument to write its own xml serialization.
59
-	 *
60
-	 * An important note: do _not_ create a parent element. Any element
61
-	 * implementing XmlSerializble should only ever write what's considered
62
-	 * its 'inner xml'.
63
-	 *
64
-	 * The parent of the current element is responsible for writing a
65
-	 * containing element.
66
-	 *
67
-	 * This allows serializers to be re-used for different element names.
68
-	 *
69
-	 * If you are opening new elements, you must also close them again.
70
-	 *
71
-	 * @param Writer $writer
72
-	 * @return void
73
-	 */
74
-	function xmlSerialize(Writer $writer) {
75
-		if (!$this->isPublished) {
76
-			// for pre-publish-url
77
-			$writer->write($this->publishUrl);
78
-		} else {
79
-			// for publish-url
80
-			$writer->writeElement('{DAV:}href', $this->publishUrl);
81
-		}
82
-	}
55
+    /**
56
+     * The xmlSerialize metod is called during xml writing.
57
+     *
58
+     * Use the $writer argument to write its own xml serialization.
59
+     *
60
+     * An important note: do _not_ create a parent element. Any element
61
+     * implementing XmlSerializble should only ever write what's considered
62
+     * its 'inner xml'.
63
+     *
64
+     * The parent of the current element is responsible for writing a
65
+     * containing element.
66
+     *
67
+     * This allows serializers to be re-used for different element names.
68
+     *
69
+     * If you are opening new elements, you must also close them again.
70
+     *
71
+     * @param Writer $writer
72
+     * @return void
73
+     */
74
+    function xmlSerialize(Writer $writer) {
75
+        if (!$this->isPublished) {
76
+            // for pre-publish-url
77
+            $writer->write($this->publishUrl);
78
+        } else {
79
+            // for publish-url
80
+            $writer->writeElement('{DAV:}href', $this->publishUrl);
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarRoot.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 
25 25
 class CalendarRoot extends \Sabre\CalDAV\CalendarRoot {
26 26
 
27
-	function getChildForPrincipal(array $principal) {
28
-		return new CalendarHome($this->caldavBackend, $principal);
29
-	}
27
+    function getChildForPrincipal(array $principal) {
28
+        return new CalendarHome($this->caldavBackend, $principal);
29
+    }
30 30
 }
31 31
\ No newline at end of file
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookImpl.php 2 patches
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -34,255 +34,255 @@
 block discarded – undo
34 34
 
35 35
 class AddressBookImpl implements IAddressBook {
36 36
 
37
-	/** @var CardDavBackend */
38
-	private $backend;
39
-
40
-	/** @var array */
41
-	private $addressBookInfo;
42
-
43
-	/** @var AddressBook */
44
-	private $addressBook;
45
-
46
-	/** @var IURLGenerator */
47
-	private $urlGenerator;
48
-
49
-	/**
50
-	 * AddressBookImpl constructor.
51
-	 *
52
-	 * @param AddressBook $addressBook
53
-	 * @param array $addressBookInfo
54
-	 * @param CardDavBackend $backend
55
-	 * @param IUrlGenerator $urlGenerator
56
-	 */
57
-	public function __construct(
58
-			AddressBook $addressBook,
59
-			array $addressBookInfo,
60
-			CardDavBackend $backend,
61
-			IURLGenerator $urlGenerator) {
62
-
63
-		$this->addressBook = $addressBook;
64
-		$this->addressBookInfo = $addressBookInfo;
65
-		$this->backend = $backend;
66
-		$this->urlGenerator = $urlGenerator;
67
-	}
68
-
69
-	/**
70
-	 * @return string defining the technical unique key
71
-	 * @since 5.0.0
72
-	 */
73
-	public function getKey() {
74
-		return $this->addressBookInfo['id'];
75
-	}
76
-
77
-	/**
78
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
79
-	 *
80
-	 * @return mixed
81
-	 * @since 5.0.0
82
-	 */
83
-	public function getDisplayName() {
84
-		return $this->addressBookInfo['{DAV:}displayname'];
85
-	}
86
-
87
-	/**
88
-	 * @param string $pattern which should match within the $searchProperties
89
-	 * @param array $searchProperties defines the properties within the query pattern should match
90
-	 * @param array $options - for future use. One should always have options!
91
-	 * @return array an array of contacts which are arrays of key-value-pairs
92
-	 * @since 5.0.0
93
-	 */
94
-	public function search($pattern, $searchProperties, $options) {
95
-		$results = $this->backend->search($this->getKey(), $pattern, $searchProperties);
96
-
97
-		$vCards = [];
98
-		foreach ($results as $result) {
99
-			$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']));
100
-		}
101
-
102
-		return $vCards;
103
-	}
104
-
105
-	/**
106
-	 * @param array $properties this array if key-value-pairs defines a contact
107
-	 * @return array an array representing the contact just created or updated
108
-	 * @since 5.0.0
109
-	 */
110
-	public function createOrUpdate($properties) {
111
-		$update = false;
112
-		if (!isset($properties['URI'])) { // create a new contact
113
-			$uid = $this->createUid();
114
-			$uri = $uid . '.vcf';
115
-			$vCard = $this->createEmptyVCard($uid);
116
-		} else { // update existing contact
117
-			$uri = $properties['URI'];
118
-			$vCardData = $this->backend->getCard($this->getKey(), $uri);
119
-			$vCard = $this->readCard($vCardData['carddata']);
120
-			$update = true;
121
-		}
122
-
123
-		foreach ($properties as $key => $value) {
124
-			$vCard->$key = $vCard->createProperty($key, $value);
125
-		}
126
-
127
-		if ($update) {
128
-			$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
129
-		} else {
130
-			$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
131
-		}
132
-
133
-		return $this->vCard2Array($uri, $vCard);
134
-
135
-	}
136
-
137
-	/**
138
-	 * @return mixed
139
-	 * @since 5.0.0
140
-	 */
141
-	public function getPermissions() {
142
-		$permissions = $this->addressBook->getACL();
143
-		$result = 0;
144
-		foreach ($permissions as $permission) {
145
-			switch($permission['privilege']) {
146
-				case '{DAV:}read':
147
-					$result |= Constants::PERMISSION_READ;
148
-					break;
149
-				case '{DAV:}write':
150
-					$result |= Constants::PERMISSION_CREATE;
151
-					$result |= Constants::PERMISSION_UPDATE;
152
-					break;
153
-				case '{DAV:}all':
154
-					$result |= Constants::PERMISSION_ALL;
155
-					break;
156
-			}
157
-		}
158
-
159
-		return $result;
160
-	}
161
-
162
-	/**
163
-	 * @param object $id the unique identifier to a contact
164
-	 * @return bool successful or not
165
-	 * @since 5.0.0
166
-	 */
167
-	public function delete($id) {
168
-		$uri = $this->backend->getCardUri($id);
169
-		return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
170
-	}
171
-
172
-	/**
173
-	 * read vCard data into a vCard object
174
-	 *
175
-	 * @param string $cardData
176
-	 * @return VCard
177
-	 */
178
-	protected function readCard($cardData) {
179
-		return  Reader::read($cardData);
180
-	}
181
-
182
-	/**
183
-	 * create UID for contact
184
-	 *
185
-	 * @return string
186
-	 */
187
-	protected function createUid() {
188
-		do {
189
-			$uid = $this->getUid();
190
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
191
-		} while (!empty($contact));
192
-
193
-		return $uid;
194
-	}
195
-
196
-	/**
197
-	 * getUid is only there for testing, use createUid instead
198
-	 */
199
-	protected function getUid() {
200
-		return UUIDUtil::getUUID();
201
-	}
202
-
203
-	/**
204
-	 * create empty vcard
205
-	 *
206
-	 * @param string $uid
207
-	 * @return VCard
208
-	 */
209
-	protected function createEmptyVCard($uid) {
210
-		$vCard = new VCard();
211
-		$vCard->UID = $uid;
212
-		return $vCard;
213
-	}
214
-
215
-	/**
216
-	 * create array with all vCard properties
217
-	 *
218
-	 * @param string $uri
219
-	 * @param VCard $vCard
220
-	 * @return array
221
-	 */
222
-	protected function vCard2Array($uri, VCard $vCard) {
223
-		$result = [
224
-			'URI' => $uri,
225
-		];
226
-
227
-		foreach ($vCard->children() as $property) {
228
-			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
229
-				$url = $this->urlGenerator->getAbsoluteURL(
230
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
231
-				$url .= implode('/', [
232
-					'addressbooks',
233
-					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
234
-					$this->addressBookInfo['uri'],
235
-					$uri
236
-				]) . '?photo';
237
-
238
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
239
-
240
-			} else if ($property->name === 'X-SOCIALPROFILE') {
241
-				$type = $this->getTypeFromProperty($property);
242
-
243
-				// Type is the social network, when it's empty we don't need this.
244
-				if ($type !== null) {
245
-					if (!isset($result[$property->name])) {
246
-						$result[$property->name] = [];
247
-					}
248
-					$result[$property->name][$type] = $property->getValue();
249
-				}
250
-
251
-			// The following properties can be set multiple times
252
-			} else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL'])) {
253
-				if (!isset($result[$property->name])) {
254
-					$result[$property->name] = [];
255
-				}
256
-
257
-				$result[$property->name][] = $property->getValue();
258
-
259
-			} else {
260
-				$result[$property->name] = $property->getValue();
261
-			}
262
-		}
263
-
264
-		if ($this->addressBookInfo['principaluri'] === 'principals/system/system' &&
265
-			$this->addressBookInfo['uri'] === 'system') {
266
-			$result['isLocalSystemBook'] = true;
267
-		}
268
-		return $result;
269
-	}
270
-
271
-	/**
272
-	 * Get the type of the current property
273
-	 *
274
-	 * @param Property $property
275
-	 * @return null|string
276
-	 */
277
-	protected function getTypeFromProperty(Property $property) {
278
-		$parameters = $property->parameters();
279
-		// Type is the social network, when it's empty we don't need this.
280
-		if (isset($parameters['TYPE'])) {
281
-			/** @var \Sabre\VObject\Parameter $type */
282
-			$type = $parameters['TYPE'];
283
-			return $type->getValue();
284
-		}
285
-
286
-		return null;
287
-	}
37
+    /** @var CardDavBackend */
38
+    private $backend;
39
+
40
+    /** @var array */
41
+    private $addressBookInfo;
42
+
43
+    /** @var AddressBook */
44
+    private $addressBook;
45
+
46
+    /** @var IURLGenerator */
47
+    private $urlGenerator;
48
+
49
+    /**
50
+     * AddressBookImpl constructor.
51
+     *
52
+     * @param AddressBook $addressBook
53
+     * @param array $addressBookInfo
54
+     * @param CardDavBackend $backend
55
+     * @param IUrlGenerator $urlGenerator
56
+     */
57
+    public function __construct(
58
+            AddressBook $addressBook,
59
+            array $addressBookInfo,
60
+            CardDavBackend $backend,
61
+            IURLGenerator $urlGenerator) {
62
+
63
+        $this->addressBook = $addressBook;
64
+        $this->addressBookInfo = $addressBookInfo;
65
+        $this->backend = $backend;
66
+        $this->urlGenerator = $urlGenerator;
67
+    }
68
+
69
+    /**
70
+     * @return string defining the technical unique key
71
+     * @since 5.0.0
72
+     */
73
+    public function getKey() {
74
+        return $this->addressBookInfo['id'];
75
+    }
76
+
77
+    /**
78
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
79
+     *
80
+     * @return mixed
81
+     * @since 5.0.0
82
+     */
83
+    public function getDisplayName() {
84
+        return $this->addressBookInfo['{DAV:}displayname'];
85
+    }
86
+
87
+    /**
88
+     * @param string $pattern which should match within the $searchProperties
89
+     * @param array $searchProperties defines the properties within the query pattern should match
90
+     * @param array $options - for future use. One should always have options!
91
+     * @return array an array of contacts which are arrays of key-value-pairs
92
+     * @since 5.0.0
93
+     */
94
+    public function search($pattern, $searchProperties, $options) {
95
+        $results = $this->backend->search($this->getKey(), $pattern, $searchProperties);
96
+
97
+        $vCards = [];
98
+        foreach ($results as $result) {
99
+            $vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']));
100
+        }
101
+
102
+        return $vCards;
103
+    }
104
+
105
+    /**
106
+     * @param array $properties this array if key-value-pairs defines a contact
107
+     * @return array an array representing the contact just created or updated
108
+     * @since 5.0.0
109
+     */
110
+    public function createOrUpdate($properties) {
111
+        $update = false;
112
+        if (!isset($properties['URI'])) { // create a new contact
113
+            $uid = $this->createUid();
114
+            $uri = $uid . '.vcf';
115
+            $vCard = $this->createEmptyVCard($uid);
116
+        } else { // update existing contact
117
+            $uri = $properties['URI'];
118
+            $vCardData = $this->backend->getCard($this->getKey(), $uri);
119
+            $vCard = $this->readCard($vCardData['carddata']);
120
+            $update = true;
121
+        }
122
+
123
+        foreach ($properties as $key => $value) {
124
+            $vCard->$key = $vCard->createProperty($key, $value);
125
+        }
126
+
127
+        if ($update) {
128
+            $this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
129
+        } else {
130
+            $this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
131
+        }
132
+
133
+        return $this->vCard2Array($uri, $vCard);
134
+
135
+    }
136
+
137
+    /**
138
+     * @return mixed
139
+     * @since 5.0.0
140
+     */
141
+    public function getPermissions() {
142
+        $permissions = $this->addressBook->getACL();
143
+        $result = 0;
144
+        foreach ($permissions as $permission) {
145
+            switch($permission['privilege']) {
146
+                case '{DAV:}read':
147
+                    $result |= Constants::PERMISSION_READ;
148
+                    break;
149
+                case '{DAV:}write':
150
+                    $result |= Constants::PERMISSION_CREATE;
151
+                    $result |= Constants::PERMISSION_UPDATE;
152
+                    break;
153
+                case '{DAV:}all':
154
+                    $result |= Constants::PERMISSION_ALL;
155
+                    break;
156
+            }
157
+        }
158
+
159
+        return $result;
160
+    }
161
+
162
+    /**
163
+     * @param object $id the unique identifier to a contact
164
+     * @return bool successful or not
165
+     * @since 5.0.0
166
+     */
167
+    public function delete($id) {
168
+        $uri = $this->backend->getCardUri($id);
169
+        return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
170
+    }
171
+
172
+    /**
173
+     * read vCard data into a vCard object
174
+     *
175
+     * @param string $cardData
176
+     * @return VCard
177
+     */
178
+    protected function readCard($cardData) {
179
+        return  Reader::read($cardData);
180
+    }
181
+
182
+    /**
183
+     * create UID for contact
184
+     *
185
+     * @return string
186
+     */
187
+    protected function createUid() {
188
+        do {
189
+            $uid = $this->getUid();
190
+            $contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
191
+        } while (!empty($contact));
192
+
193
+        return $uid;
194
+    }
195
+
196
+    /**
197
+     * getUid is only there for testing, use createUid instead
198
+     */
199
+    protected function getUid() {
200
+        return UUIDUtil::getUUID();
201
+    }
202
+
203
+    /**
204
+     * create empty vcard
205
+     *
206
+     * @param string $uid
207
+     * @return VCard
208
+     */
209
+    protected function createEmptyVCard($uid) {
210
+        $vCard = new VCard();
211
+        $vCard->UID = $uid;
212
+        return $vCard;
213
+    }
214
+
215
+    /**
216
+     * create array with all vCard properties
217
+     *
218
+     * @param string $uri
219
+     * @param VCard $vCard
220
+     * @return array
221
+     */
222
+    protected function vCard2Array($uri, VCard $vCard) {
223
+        $result = [
224
+            'URI' => $uri,
225
+        ];
226
+
227
+        foreach ($vCard->children() as $property) {
228
+            if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
229
+                $url = $this->urlGenerator->getAbsoluteURL(
230
+                    $this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
231
+                $url .= implode('/', [
232
+                    'addressbooks',
233
+                    substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
234
+                    $this->addressBookInfo['uri'],
235
+                    $uri
236
+                ]) . '?photo';
237
+
238
+                $result['PHOTO'] = 'VALUE=uri:' . $url;
239
+
240
+            } else if ($property->name === 'X-SOCIALPROFILE') {
241
+                $type = $this->getTypeFromProperty($property);
242
+
243
+                // Type is the social network, when it's empty we don't need this.
244
+                if ($type !== null) {
245
+                    if (!isset($result[$property->name])) {
246
+                        $result[$property->name] = [];
247
+                    }
248
+                    $result[$property->name][$type] = $property->getValue();
249
+                }
250
+
251
+            // The following properties can be set multiple times
252
+            } else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL'])) {
253
+                if (!isset($result[$property->name])) {
254
+                    $result[$property->name] = [];
255
+                }
256
+
257
+                $result[$property->name][] = $property->getValue();
258
+
259
+            } else {
260
+                $result[$property->name] = $property->getValue();
261
+            }
262
+        }
263
+
264
+        if ($this->addressBookInfo['principaluri'] === 'principals/system/system' &&
265
+            $this->addressBookInfo['uri'] === 'system') {
266
+            $result['isLocalSystemBook'] = true;
267
+        }
268
+        return $result;
269
+    }
270
+
271
+    /**
272
+     * Get the type of the current property
273
+     *
274
+     * @param Property $property
275
+     * @return null|string
276
+     */
277
+    protected function getTypeFromProperty(Property $property) {
278
+        $parameters = $property->parameters();
279
+        // Type is the social network, when it's empty we don't need this.
280
+        if (isset($parameters['TYPE'])) {
281
+            /** @var \Sabre\VObject\Parameter $type */
282
+            $type = $parameters['TYPE'];
283
+            return $type->getValue();
284
+        }
285
+
286
+        return null;
287
+    }
288 288
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		$update = false;
112 112
 		if (!isset($properties['URI'])) { // create a new contact
113 113
 			$uid = $this->createUid();
114
-			$uri = $uid . '.vcf';
114
+			$uri = $uid.'.vcf';
115 115
 			$vCard = $this->createEmptyVCard($uid);
116 116
 		} else { // update existing contact
117 117
 			$uri = $properties['URI'];
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		$permissions = $this->addressBook->getACL();
143 143
 		$result = 0;
144 144
 		foreach ($permissions as $permission) {
145
-			switch($permission['privilege']) {
145
+			switch ($permission['privilege']) {
146 146
 				case '{DAV:}read':
147 147
 					$result |= Constants::PERMISSION_READ;
148 148
 					break;
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	protected function createUid() {
188 188
 		do {
189 189
 			$uid = $this->getUid();
190
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
190
+			$contact = $this->backend->getContact($this->getKey(), $uid.'.vcf');
191 191
 		} while (!empty($contact));
192 192
 
193 193
 		return $uid;
@@ -227,15 +227,15 @@  discard block
 block discarded – undo
227 227
 		foreach ($vCard->children() as $property) {
228 228
 			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
229 229
 				$url = $this->urlGenerator->getAbsoluteURL(
230
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
230
+					$this->urlGenerator->linkTo('', 'remote.php').'/dav/');
231 231
 				$url .= implode('/', [
232 232
 					'addressbooks',
233 233
 					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
234 234
 					$this->addressBookInfo['uri'],
235 235
 					$uri
236
-				]) . '?photo';
236
+				]).'?photo';
237 237
 
238
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
238
+				$result['PHOTO'] = 'VALUE=uri:'.$url;
239 239
 
240 240
 			} else if ($property->name === 'X-SOCIALPROFILE') {
241 241
 				$type = $this->getTypeFromProperty($property);
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/Xml/Groups.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -26,21 +26,21 @@
 block discarded – undo
26 26
 use Sabre\Xml\Writer;
27 27
 
28 28
 class Groups implements XmlSerializable {
29
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
29
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
30 30
 
31
-	/** @var string[] of TYPE:CHECKSUM */
32
-	private $groups;
31
+    /** @var string[] of TYPE:CHECKSUM */
32
+    private $groups;
33 33
 
34
-	/**
35
-	 * @param string $groups
36
-	 */
37
-	public function __construct($groups) {
38
-		$this->groups = $groups;
39
-	}
34
+    /**
35
+     * @param string $groups
36
+     */
37
+    public function __construct($groups) {
38
+        $this->groups = $groups;
39
+    }
40 40
 
41
-	function xmlSerialize(Writer $writer) {
42
-		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
-		}
45
-	}
41
+    function xmlSerialize(Writer $writer) {
42
+        foreach ($this->groups as $group) {
43
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
+        }
45
+    }
46 46
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@
 block discarded – undo
40 40
 
41 41
 	function xmlSerialize(Writer $writer) {
42 42
 		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
43
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}group', $group);
44 44
 		}
45 45
 	}
46 46
 }
Please login to merge, or discard this patch.