Completed
Pull Request — master (#3233)
by Christoph
14:57
created
apps/dav/lib/CalDAV/Activity/Setting/Todo.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -27,72 +27,72 @@
 block discarded – undo
27 27
 
28 28
 class Todo implements ISetting {
29 29
 
30
-	/** @var IL10N */
31
-	protected $l;
30
+    /** @var IL10N */
31
+    protected $l;
32 32
 
33
-	/**
34
-	 * @param IL10N $l
35
-	 */
36
-	public function __construct(IL10N $l) {
37
-		$this->l = $l;
38
-	}
33
+    /**
34
+     * @param IL10N $l
35
+     */
36
+    public function __construct(IL10N $l) {
37
+        $this->l = $l;
38
+    }
39 39
 
40
-	/**
41
-	 * @return string Lowercase a-z and underscore only identifier
42
-	 * @since 11.0.0
43
-	 */
44
-	public function getIdentifier() {
45
-		return 'calendar_todo';
46
-	}
40
+    /**
41
+     * @return string Lowercase a-z and underscore only identifier
42
+     * @since 11.0.0
43
+     */
44
+    public function getIdentifier() {
45
+        return 'calendar_todo';
46
+    }
47 47
 
48
-	/**
49
-	 * @return string A translated string
50
-	 * @since 11.0.0
51
-	 */
52
-	public function getName() {
53
-		return $this->l->t('A calendar <strong>todo</strong> was modified');
54
-	}
48
+    /**
49
+     * @return string A translated string
50
+     * @since 11.0.0
51
+     */
52
+    public function getName() {
53
+        return $this->l->t('A calendar <strong>todo</strong> was modified');
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the filter should be rather on the top or bottom of
58
-	 * the admin section. The filters are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 * @since 11.0.0
61
-	 */
62
-	public function getPriority() {
63
-		return 50;
64
-	}
56
+    /**
57
+     * @return int whether the filter should be rather on the top or bottom of
58
+     * the admin section. The filters are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     * @since 11.0.0
61
+     */
62
+    public function getPriority() {
63
+        return 50;
64
+    }
65 65
 
66
-	/**
67
-	 * @return bool True when the option can be changed for the stream
68
-	 * @since 11.0.0
69
-	 */
70
-	public function canChangeStream() {
71
-		return true;
72
-	}
66
+    /**
67
+     * @return bool True when the option can be changed for the stream
68
+     * @since 11.0.0
69
+     */
70
+    public function canChangeStream() {
71
+        return true;
72
+    }
73 73
 
74
-	/**
75
-	 * @return bool True when the option can be changed for the stream
76
-	 * @since 11.0.0
77
-	 */
78
-	public function isDefaultEnabledStream() {
79
-		return true;
80
-	}
74
+    /**
75
+     * @return bool True when the option can be changed for the stream
76
+     * @since 11.0.0
77
+     */
78
+    public function isDefaultEnabledStream() {
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * @return bool True when the option can be changed for the mail
84
-	 * @since 11.0.0
85
-	 */
86
-	public function canChangeMail() {
87
-		return true;
88
-	}
82
+    /**
83
+     * @return bool True when the option can be changed for the mail
84
+     * @since 11.0.0
85
+     */
86
+    public function canChangeMail() {
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * @return bool True when the option can be changed for the stream
92
-	 * @since 11.0.0
93
-	 */
94
-	public function isDefaultEnabledMail() {
95
-		return false;
96
-	}
90
+    /**
91
+     * @return bool True when the option can be changed for the stream
92
+     * @since 11.0.0
93
+     */
94
+    public function isDefaultEnabledMail() {
95
+        return false;
96
+    }
97 97
 }
98 98
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Activity/Backend.php 1 patch
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.
apps/dav/lib/CalDAV/Calendar.php 1 patch
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -32,267 +32,267 @@
 block discarded – undo
32 32
 
33 33
 class Calendar extends \Sabre\CalDAV\Calendar implements IShareable {
34 34
 
35
-	public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n) {
36
-		parent::__construct($caldavBackend, $calendarInfo);
37
-
38
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
39
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
40
-		}
41
-		if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
42
-			$this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
43
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
44
-		}
45
-	}
46
-
47
-	/**
48
-	 * Updates the list of shares.
49
-	 *
50
-	 * The first array is a list of people that are to be added to the
51
-	 * resource.
52
-	 *
53
-	 * Every element in the add array has the following properties:
54
-	 *   * href - A url. Usually a mailto: address
55
-	 *   * commonName - Usually a first and last name, or false
56
-	 *   * summary - A description of the share, can also be false
57
-	 *   * readOnly - A boolean value
58
-	 *
59
-	 * Every element in the remove array is just the address string.
60
-	 *
61
-	 * @param array $add
62
-	 * @param array $remove
63
-	 * @return void
64
-	 */
65
-	function updateShares(array $add, array $remove) {
66
-		/** @var CalDavBackend $calDavBackend */
67
-		$calDavBackend = $this->caldavBackend;
68
-		$calDavBackend->updateShares($this, $add, $remove);
69
-	}
70
-
71
-	/**
72
-	 * Returns the list of people whom this resource is shared with.
73
-	 *
74
-	 * Every element in this array should have the following properties:
75
-	 *   * href - Often a mailto: address
76
-	 *   * commonName - Optional, for example a first + last name
77
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
78
-	 *   * readOnly - boolean
79
-	 *   * summary - Optional, a description for the share
80
-	 *
81
-	 * @return array
82
-	 */
83
-	function getShares() {
84
-		/** @var CalDavBackend $calDavBackend */
85
-		$calDavBackend = $this->caldavBackend;
86
-		return $calDavBackend->getShares($this->getResourceId());
87
-	}
88
-
89
-	/**
90
-	 * @return int
91
-	 */
92
-	public function getResourceId() {
93
-		return $this->calendarInfo['id'];
94
-	}
95
-
96
-	/**
97
-	 * @return string
98
-	 */
99
-	public function getPrincipalURI() {
100
-		return $this->calendarInfo['principaluri'];
101
-	}
102
-
103
-	function getACL() {
104
-		$acl =  [
105
-			[
106
-				'privilege' => '{DAV:}read',
107
-				'principal' => $this->getOwner(),
108
-				'protected' => true,
109
-			]];
110
-		if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
111
-			$acl[] = [
112
-				'privilege' => '{DAV:}write',
113
-				'principal' => $this->getOwner(),
114
-				'protected' => true,
115
-			];
116
-		}
117
-		if ($this->getOwner() !== parent::getOwner()) {
118
-			$acl[] =  [
119
-					'privilege' => '{DAV:}read',
120
-					'principal' => parent::getOwner(),
121
-					'protected' => true,
122
-				];
123
-			if ($this->canWrite()) {
124
-				$acl[] = [
125
-					'privilege' => '{DAV:}write',
126
-					'principal' => parent::getOwner(),
127
-					'protected' => true,
128
-				];
129
-			}
130
-		}
131
-		if ($this->isPublic()) {
132
-			$acl[] = [
133
-				'privilege' => '{DAV:}read',
134
-				'principal' => 'principals/system/public',
135
-				'protected' => true,
136
-			];
137
-		}
138
-
139
-		/** @var CalDavBackend $calDavBackend */
140
-		$calDavBackend = $this->caldavBackend;
141
-		return $calDavBackend->applyShareAcl($this->getResourceId(), $acl);
142
-	}
143
-
144
-	function getChildACL() {
145
-		return $this->getACL();
146
-	}
147
-
148
-	function getOwner() {
149
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
150
-			return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
151
-		}
152
-		return parent::getOwner();
153
-	}
154
-
155
-	function delete() {
156
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
157
-			$this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
158
-			$principal = 'principal:' . parent::getOwner();
159
-			$shares = $this->getShares();
160
-			$shares = array_filter($shares, function($share) use ($principal){
161
-				return $share['href'] === $principal;
162
-			});
163
-			if (empty($shares)) {
164
-				throw new Forbidden();
165
-			}
166
-
167
-			/** @var CalDavBackend $calDavBackend */
168
-			$calDavBackend = $this->caldavBackend;
169
-			$calDavBackend->updateShares($this, [], [
170
-				'href' => $principal
171
-			]);
172
-			return;
173
-		}
174
-		parent::delete();
175
-	}
176
-
177
-	function propPatch(PropPatch $propPatch) {
178
-		$mutations = $propPatch->getMutations();
179
-		// If this is a shared calendar, the user can only change the enabled property, to hide it.
180
-		if ($this->isShared() && (sizeof($mutations) !== 1 || !isset($mutations['{http://owncloud.org/ns}calendar-enabled']))) {
181
-			throw new Forbidden();
182
-		}
183
-		parent::propPatch($propPatch);
184
-	}
185
-
186
-	function getChild($name) {
187
-
188
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
189
-
190
-		if (!$obj) {
191
-			throw new NotFound('Calendar object not found');
192
-		}
193
-
194
-		if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
195
-			throw new NotFound('Calendar object not found');
196
-		}
197
-
198
-		$obj['acl'] = $this->getChildACL();
199
-
200
-		return new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
201
-
202
-	}
203
-
204
-	function getChildren() {
205
-
206
-		$objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
207
-		$children = [];
208
-		foreach ($objs as $obj) {
209
-			if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
210
-				continue;
211
-			}
212
-			$obj['acl'] = $this->getChildACL();
213
-			$children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
214
-		}
215
-		return $children;
216
-
217
-	}
218
-
219
-	function getMultipleChildren(array $paths) {
220
-
221
-		$objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
222
-		$children = [];
223
-		foreach ($objs as $obj) {
224
-			if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
225
-				continue;
226
-			}
227
-			$obj['acl'] = $this->getChildACL();
228
-			$children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
229
-		}
230
-		return $children;
231
-
232
-	}
233
-
234
-	function childExists($name) {
235
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
236
-		if (!$obj) {
237
-			return false;
238
-		}
239
-		if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
240
-			return false;
241
-		}
242
-
243
-		return true;
244
-	}
245
-
246
-	function calendarQuery(array $filters) {
247
-
248
-		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
249
-		if ($this->isShared()) {
250
-			return array_filter($uris, function ($uri) {
251
-				return $this->childExists($uri);
252
-			});
253
-		}
254
-
255
-		return $uris;
256
-	}
257
-
258
-	/**
259
-	 * @param boolean $value
260
-	 * @return string|null
261
-	 */
262
-	function setPublishStatus($value) {
263
-		$publicUri = $this->caldavBackend->setPublishStatus($value, $this);
264
-		$this->calendarInfo['publicuri'] = $publicUri;
265
-		return $publicUri;
266
-	}
267
-
268
-	/**
269
-	 * @return mixed $value
270
-	 */
271
-	function getPublishStatus() {
272
-		return $this->caldavBackend->getPublishStatus($this);
273
-	}
274
-
275
-	private function canWrite() {
276
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
277
-			return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
278
-		}
279
-		return true;
280
-	}
281
-
282
-	private function isPublic() {
283
-		return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
284
-	}
285
-
286
-	private function isShared() {
287
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
288
-			return false;
289
-		}
290
-
291
-		return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
292
-	}
293
-
294
-	public function isSubscription() {
295
-		return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
296
-	}
35
+    public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n) {
36
+        parent::__construct($caldavBackend, $calendarInfo);
37
+
38
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
39
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
40
+        }
41
+        if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI &&
42
+            $this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
43
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
44
+        }
45
+    }
46
+
47
+    /**
48
+     * Updates the list of shares.
49
+     *
50
+     * The first array is a list of people that are to be added to the
51
+     * resource.
52
+     *
53
+     * Every element in the add array has the following properties:
54
+     *   * href - A url. Usually a mailto: address
55
+     *   * commonName - Usually a first and last name, or false
56
+     *   * summary - A description of the share, can also be false
57
+     *   * readOnly - A boolean value
58
+     *
59
+     * Every element in the remove array is just the address string.
60
+     *
61
+     * @param array $add
62
+     * @param array $remove
63
+     * @return void
64
+     */
65
+    function updateShares(array $add, array $remove) {
66
+        /** @var CalDavBackend $calDavBackend */
67
+        $calDavBackend = $this->caldavBackend;
68
+        $calDavBackend->updateShares($this, $add, $remove);
69
+    }
70
+
71
+    /**
72
+     * Returns the list of people whom this resource is shared with.
73
+     *
74
+     * Every element in this array should have the following properties:
75
+     *   * href - Often a mailto: address
76
+     *   * commonName - Optional, for example a first + last name
77
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
78
+     *   * readOnly - boolean
79
+     *   * summary - Optional, a description for the share
80
+     *
81
+     * @return array
82
+     */
83
+    function getShares() {
84
+        /** @var CalDavBackend $calDavBackend */
85
+        $calDavBackend = $this->caldavBackend;
86
+        return $calDavBackend->getShares($this->getResourceId());
87
+    }
88
+
89
+    /**
90
+     * @return int
91
+     */
92
+    public function getResourceId() {
93
+        return $this->calendarInfo['id'];
94
+    }
95
+
96
+    /**
97
+     * @return string
98
+     */
99
+    public function getPrincipalURI() {
100
+        return $this->calendarInfo['principaluri'];
101
+    }
102
+
103
+    function getACL() {
104
+        $acl =  [
105
+            [
106
+                'privilege' => '{DAV:}read',
107
+                'principal' => $this->getOwner(),
108
+                'protected' => true,
109
+            ]];
110
+        if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
111
+            $acl[] = [
112
+                'privilege' => '{DAV:}write',
113
+                'principal' => $this->getOwner(),
114
+                'protected' => true,
115
+            ];
116
+        }
117
+        if ($this->getOwner() !== parent::getOwner()) {
118
+            $acl[] =  [
119
+                    'privilege' => '{DAV:}read',
120
+                    'principal' => parent::getOwner(),
121
+                    'protected' => true,
122
+                ];
123
+            if ($this->canWrite()) {
124
+                $acl[] = [
125
+                    'privilege' => '{DAV:}write',
126
+                    'principal' => parent::getOwner(),
127
+                    'protected' => true,
128
+                ];
129
+            }
130
+        }
131
+        if ($this->isPublic()) {
132
+            $acl[] = [
133
+                'privilege' => '{DAV:}read',
134
+                'principal' => 'principals/system/public',
135
+                'protected' => true,
136
+            ];
137
+        }
138
+
139
+        /** @var CalDavBackend $calDavBackend */
140
+        $calDavBackend = $this->caldavBackend;
141
+        return $calDavBackend->applyShareAcl($this->getResourceId(), $acl);
142
+    }
143
+
144
+    function getChildACL() {
145
+        return $this->getACL();
146
+    }
147
+
148
+    function getOwner() {
149
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
150
+            return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
151
+        }
152
+        return parent::getOwner();
153
+    }
154
+
155
+    function delete() {
156
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal']) &&
157
+            $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']) {
158
+            $principal = 'principal:' . parent::getOwner();
159
+            $shares = $this->getShares();
160
+            $shares = array_filter($shares, function($share) use ($principal){
161
+                return $share['href'] === $principal;
162
+            });
163
+            if (empty($shares)) {
164
+                throw new Forbidden();
165
+            }
166
+
167
+            /** @var CalDavBackend $calDavBackend */
168
+            $calDavBackend = $this->caldavBackend;
169
+            $calDavBackend->updateShares($this, [], [
170
+                'href' => $principal
171
+            ]);
172
+            return;
173
+        }
174
+        parent::delete();
175
+    }
176
+
177
+    function propPatch(PropPatch $propPatch) {
178
+        $mutations = $propPatch->getMutations();
179
+        // If this is a shared calendar, the user can only change the enabled property, to hide it.
180
+        if ($this->isShared() && (sizeof($mutations) !== 1 || !isset($mutations['{http://owncloud.org/ns}calendar-enabled']))) {
181
+            throw new Forbidden();
182
+        }
183
+        parent::propPatch($propPatch);
184
+    }
185
+
186
+    function getChild($name) {
187
+
188
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
189
+
190
+        if (!$obj) {
191
+            throw new NotFound('Calendar object not found');
192
+        }
193
+
194
+        if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
195
+            throw new NotFound('Calendar object not found');
196
+        }
197
+
198
+        $obj['acl'] = $this->getChildACL();
199
+
200
+        return new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
201
+
202
+    }
203
+
204
+    function getChildren() {
205
+
206
+        $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']);
207
+        $children = [];
208
+        foreach ($objs as $obj) {
209
+            if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
210
+                continue;
211
+            }
212
+            $obj['acl'] = $this->getChildACL();
213
+            $children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
214
+        }
215
+        return $children;
216
+
217
+    }
218
+
219
+    function getMultipleChildren(array $paths) {
220
+
221
+        $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths);
222
+        $children = [];
223
+        foreach ($objs as $obj) {
224
+            if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
225
+                continue;
226
+            }
227
+            $obj['acl'] = $this->getChildACL();
228
+            $children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj);
229
+        }
230
+        return $children;
231
+
232
+    }
233
+
234
+    function childExists($name) {
235
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name);
236
+        if (!$obj) {
237
+            return false;
238
+        }
239
+        if ($this->isShared() && $obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE) {
240
+            return false;
241
+        }
242
+
243
+        return true;
244
+    }
245
+
246
+    function calendarQuery(array $filters) {
247
+
248
+        $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters);
249
+        if ($this->isShared()) {
250
+            return array_filter($uris, function ($uri) {
251
+                return $this->childExists($uri);
252
+            });
253
+        }
254
+
255
+        return $uris;
256
+    }
257
+
258
+    /**
259
+     * @param boolean $value
260
+     * @return string|null
261
+     */
262
+    function setPublishStatus($value) {
263
+        $publicUri = $this->caldavBackend->setPublishStatus($value, $this);
264
+        $this->calendarInfo['publicuri'] = $publicUri;
265
+        return $publicUri;
266
+    }
267
+
268
+    /**
269
+     * @return mixed $value
270
+     */
271
+    function getPublishStatus() {
272
+        return $this->caldavBackend->getPublishStatus($this);
273
+    }
274
+
275
+    private function canWrite() {
276
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
277
+            return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
278
+        }
279
+        return true;
280
+    }
281
+
282
+    private function isPublic() {
283
+        return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
284
+    }
285
+
286
+    private function isShared() {
287
+        if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
288
+            return false;
289
+        }
290
+
291
+        return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
292
+    }
293
+
294
+    public function isSubscription() {
295
+        return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
296
+    }
297 297
 
298 298
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarHome.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -33,82 +33,82 @@
 block discarded – undo
33 33
 
34 34
 class CalendarHome extends \Sabre\CalDAV\CalendarHome {
35 35
 
36
-	/** @var \OCP\IL10N */
37
-	private $l10n;
36
+    /** @var \OCP\IL10N */
37
+    private $l10n;
38 38
 
39
-	public function __construct(BackendInterface $caldavBackend, $principalInfo) {
40
-		parent::__construct($caldavBackend, $principalInfo);
41
-		$this->l10n = \OC::$server->getL10N('dav');
42
-	}
39
+    public function __construct(BackendInterface $caldavBackend, $principalInfo) {
40
+        parent::__construct($caldavBackend, $principalInfo);
41
+        $this->l10n = \OC::$server->getL10N('dav');
42
+    }
43 43
 
44
-	/**
45
-	 * @return BackendInterface
46
-	 */
47
-	public function getCalDAVBackend() {
48
-		return $this->caldavBackend;
49
-	}
44
+    /**
45
+     * @return BackendInterface
46
+     */
47
+    public function getCalDAVBackend() {
48
+        return $this->caldavBackend;
49
+    }
50 50
 
51
-	/**
52
-	 * @inheritdoc
53
-	 */
54
-	function getChildren() {
55
-		$calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
56
-		$objects = [];
57
-		foreach ($calendars as $calendar) {
58
-			$objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
59
-		}
51
+    /**
52
+     * @inheritdoc
53
+     */
54
+    function getChildren() {
55
+        $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
56
+        $objects = [];
57
+        foreach ($calendars as $calendar) {
58
+            $objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
59
+        }
60 60
 
61
-		if ($this->caldavBackend instanceof SchedulingSupport) {
62
-			$objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
63
-			$objects[] = new Outbox($this->principalInfo['uri']);
64
-		}
61
+        if ($this->caldavBackend instanceof SchedulingSupport) {
62
+            $objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
63
+            $objects[] = new Outbox($this->principalInfo['uri']);
64
+        }
65 65
 
66
-		// We're adding a notifications node, if it's supported by the backend.
67
-		if ($this->caldavBackend instanceof NotificationSupport) {
68
-			$objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
69
-		}
66
+        // We're adding a notifications node, if it's supported by the backend.
67
+        if ($this->caldavBackend instanceof NotificationSupport) {
68
+            $objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
69
+        }
70 70
 
71
-		// If the backend supports subscriptions, we'll add those as well,
72
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
73
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
74
-				$objects[] = new Subscription($this->caldavBackend, $subscription);
75
-			}
76
-		}
71
+        // If the backend supports subscriptions, we'll add those as well,
72
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
73
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
74
+                $objects[] = new Subscription($this->caldavBackend, $subscription);
75
+            }
76
+        }
77 77
 
78
-		return $objects;
79
-	}
78
+        return $objects;
79
+    }
80 80
 
81
-	/**
82
-	 * @inheritdoc
83
-	 */
84
-	function getChild($name) {
85
-		// Special nodes
86
-		if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
87
-			return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
88
-		}
89
-		if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
90
-			return new Outbox($this->principalInfo['uri']);
91
-		}
92
-		if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
93
-			return new \Sabre\CalDAv\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
94
-		}
81
+    /**
82
+     * @inheritdoc
83
+     */
84
+    function getChild($name) {
85
+        // Special nodes
86
+        if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
87
+            return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
88
+        }
89
+        if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
90
+            return new Outbox($this->principalInfo['uri']);
91
+        }
92
+        if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
93
+            return new \Sabre\CalDAv\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
94
+        }
95 95
 
96
-		// Calendars
97
-		foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
98
-			if ($calendar['uri'] === $name) {
99
-				return new Calendar($this->caldavBackend, $calendar, $this->l10n);
100
-			}
101
-		}
96
+        // Calendars
97
+        foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
98
+            if ($calendar['uri'] === $name) {
99
+                return new Calendar($this->caldavBackend, $calendar, $this->l10n);
100
+            }
101
+        }
102 102
 
103
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
104
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
105
-				if ($subscription['uri'] === $name) {
106
-					return new Subscription($this->caldavBackend, $subscription);
107
-				}
108
-			}
103
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
104
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
105
+                if ($subscription['uri'] === $name) {
106
+                    return new Subscription($this->caldavBackend, $subscription);
107
+                }
108
+            }
109 109
 
110
-		}
110
+        }
111 111
 
112
-		throw new NotFound('Node with name \'' . $name . '\' could not be found');
113
-	}
112
+        throw new NotFound('Node with name \'' . $name . '\' could not be found');
113
+    }
114 114
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/PublicCalendarRoot.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,43 +25,43 @@
 block discarded – undo
25 25
 
26 26
 class PublicCalendarRoot extends Collection {
27 27
 
28
-	/** @var CalDavBackend */
29
-	protected $caldavBackend;
28
+    /** @var CalDavBackend */
29
+    protected $caldavBackend;
30 30
 
31
-	/** @var \OCP\IL10N */
32
-	protected $l10n;
31
+    /** @var \OCP\IL10N */
32
+    protected $l10n;
33 33
 
34
-	function __construct(CalDavBackend $caldavBackend) {
35
-		$this->caldavBackend = $caldavBackend;
36
-		$this->l10n = \OC::$server->getL10N('dav');
37
-	}
34
+    function __construct(CalDavBackend $caldavBackend) {
35
+        $this->caldavBackend = $caldavBackend;
36
+        $this->l10n = \OC::$server->getL10N('dav');
37
+    }
38 38
 
39
-	/**
40
-	 * @inheritdoc
41
-	 */
42
-	function getName() {
43
-		return 'public-calendars';
44
-	}
39
+    /**
40
+     * @inheritdoc
41
+     */
42
+    function getName() {
43
+        return 'public-calendars';
44
+    }
45 45
 
46
-	/**
47
-	 * @inheritdoc
48
-	 */
49
-	function getChild($name) {
50
-		$calendar = $this->caldavBackend->getPublicCalendar($name);
51
-		return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
-	}
46
+    /**
47
+     * @inheritdoc
48
+     */
49
+    function getChild($name) {
50
+        $calendar = $this->caldavBackend->getPublicCalendar($name);
51
+        return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
+    }
53 53
 
54
-	/**
55
-	 * @inheritdoc
56
-	 */
57
-	function getChildren() {
58
-		$calendars = $this->caldavBackend->getPublicCalendars();
59
-		$children = [];
60
-		foreach ($calendars as $calendar) {
61
-			// TODO: maybe implement a new class PublicCalendar ???
62
-			$children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
-		}
54
+    /**
55
+     * @inheritdoc
56
+     */
57
+    function getChildren() {
58
+        $calendars = $this->caldavBackend->getPublicCalendars();
59
+        $children = [];
60
+        foreach ($calendars as $calendar) {
61
+            // TODO: maybe implement a new class PublicCalendar ???
62
+            $children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
+        }
64 64
 
65
-		return $children;
66
-	}
65
+        return $children;
66
+    }
67 67
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +1739 added lines, -1739 removed lines patch added patch discarded remove patch
@@ -59,1744 +59,1744 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			if (!isset($calendars[$calendar['id']])) {
252
-				$calendars[$calendar['id']] = $calendar;
253
-			}
254
-		}
255
-
256
-		$stmt->closeCursor();
257
-
258
-		// query for shared calendars
259
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
261
-
262
-		$fields = array_values($this->propertyMap);
263
-		$fields[] = 'a.id';
264
-		$fields[] = 'a.uri';
265
-		$fields[] = 'a.synctoken';
266
-		$fields[] = 'a.components';
267
-		$fields[] = 'a.principaluri';
268
-		$fields[] = 'a.transparent';
269
-		$fields[] = 's.access';
270
-		$query = $this->db->getQueryBuilder();
271
-		$result = $query->select($fields)
272
-			->from('dav_shares', 's')
273
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
-			->setParameter('type', 'calendar')
277
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
-			->execute();
279
-
280
-		while($row = $result->fetch()) {
281
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
282
-			$uri = $row['uri'] . '_shared_by_' . $name;
283
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
284
-			$components = [];
285
-			if ($row['components']) {
286
-				$components = explode(',',$row['components']);
287
-			}
288
-			$calendar = [
289
-				'id' => $row['id'],
290
-				'uri' => $uri,
291
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
293
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
294
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
296
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
298
-			];
299
-
300
-			foreach($this->propertyMap as $xmlName=>$dbName) {
301
-				$calendar[$xmlName] = $row[$dbName];
302
-			}
303
-
304
-			if (!isset($calendars[$calendar['id']])) {
305
-				$calendars[$calendar['id']] = $calendar;
306
-			}
307
-		}
308
-		$result->closeCursor();
309
-
310
-		return array_values($calendars);
311
-	}
312
-
313
-	public function getUsersOwnCalendars($principalUri) {
314
-		$principalUri = $this->convertPrincipal($principalUri, true);
315
-		$fields = array_values($this->propertyMap);
316
-		$fields[] = 'id';
317
-		$fields[] = 'uri';
318
-		$fields[] = 'synctoken';
319
-		$fields[] = 'components';
320
-		$fields[] = 'principaluri';
321
-		$fields[] = 'transparent';
322
-		// Making fields a comma-delimited list
323
-		$query = $this->db->getQueryBuilder();
324
-		$query->select($fields)->from('calendars')
325
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
326
-			->orderBy('calendarorder', 'ASC');
327
-		$stmt = $query->execute();
328
-		$calendars = [];
329
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
330
-			$components = [];
331
-			if ($row['components']) {
332
-				$components = explode(',',$row['components']);
333
-			}
334
-			$calendar = [
335
-				'id' => $row['id'],
336
-				'uri' => $row['uri'],
337
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
338
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
339
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
340
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
342
-			];
343
-			foreach($this->propertyMap as $xmlName=>$dbName) {
344
-				$calendar[$xmlName] = $row[$dbName];
345
-			}
346
-			if (!isset($calendars[$calendar['id']])) {
347
-				$calendars[$calendar['id']] = $calendar;
348
-			}
349
-		}
350
-		$stmt->closeCursor();
351
-		return array_values($calendars);
352
-	}
353
-
354
-
355
-	private function getUserDisplayName($uid) {
356
-		if (!isset($this->userDisplayNames[$uid])) {
357
-			$user = $this->userManager->get($uid);
358
-
359
-			if ($user instanceof IUser) {
360
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
361
-			} else {
362
-				$this->userDisplayNames[$uid] = $uid;
363
-			}
364
-		}
365
-
366
-		return $this->userDisplayNames[$uid];
367
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            if (!isset($calendars[$calendar['id']])) {
252
+                $calendars[$calendar['id']] = $calendar;
253
+            }
254
+        }
255
+
256
+        $stmt->closeCursor();
257
+
258
+        // query for shared calendars
259
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
+        $principals[]= $principalUri;
261
+
262
+        $fields = array_values($this->propertyMap);
263
+        $fields[] = 'a.id';
264
+        $fields[] = 'a.uri';
265
+        $fields[] = 'a.synctoken';
266
+        $fields[] = 'a.components';
267
+        $fields[] = 'a.principaluri';
268
+        $fields[] = 'a.transparent';
269
+        $fields[] = 's.access';
270
+        $query = $this->db->getQueryBuilder();
271
+        $result = $query->select($fields)
272
+            ->from('dav_shares', 's')
273
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
+            ->setParameter('type', 'calendar')
277
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
+            ->execute();
279
+
280
+        while($row = $result->fetch()) {
281
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
282
+            $uri = $row['uri'] . '_shared_by_' . $name;
283
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
284
+            $components = [];
285
+            if ($row['components']) {
286
+                $components = explode(',',$row['components']);
287
+            }
288
+            $calendar = [
289
+                'id' => $row['id'],
290
+                'uri' => $uri,
291
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
292
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
293
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
294
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
295
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
296
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
297
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
298
+            ];
299
+
300
+            foreach($this->propertyMap as $xmlName=>$dbName) {
301
+                $calendar[$xmlName] = $row[$dbName];
302
+            }
303
+
304
+            if (!isset($calendars[$calendar['id']])) {
305
+                $calendars[$calendar['id']] = $calendar;
306
+            }
307
+        }
308
+        $result->closeCursor();
309
+
310
+        return array_values($calendars);
311
+    }
312
+
313
+    public function getUsersOwnCalendars($principalUri) {
314
+        $principalUri = $this->convertPrincipal($principalUri, true);
315
+        $fields = array_values($this->propertyMap);
316
+        $fields[] = 'id';
317
+        $fields[] = 'uri';
318
+        $fields[] = 'synctoken';
319
+        $fields[] = 'components';
320
+        $fields[] = 'principaluri';
321
+        $fields[] = 'transparent';
322
+        // Making fields a comma-delimited list
323
+        $query = $this->db->getQueryBuilder();
324
+        $query->select($fields)->from('calendars')
325
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
326
+            ->orderBy('calendarorder', 'ASC');
327
+        $stmt = $query->execute();
328
+        $calendars = [];
329
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
330
+            $components = [];
331
+            if ($row['components']) {
332
+                $components = explode(',',$row['components']);
333
+            }
334
+            $calendar = [
335
+                'id' => $row['id'],
336
+                'uri' => $row['uri'],
337
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
338
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
339
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
340
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
341
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
342
+            ];
343
+            foreach($this->propertyMap as $xmlName=>$dbName) {
344
+                $calendar[$xmlName] = $row[$dbName];
345
+            }
346
+            if (!isset($calendars[$calendar['id']])) {
347
+                $calendars[$calendar['id']] = $calendar;
348
+            }
349
+        }
350
+        $stmt->closeCursor();
351
+        return array_values($calendars);
352
+    }
353
+
354
+
355
+    private function getUserDisplayName($uid) {
356
+        if (!isset($this->userDisplayNames[$uid])) {
357
+            $user = $this->userManager->get($uid);
358
+
359
+            if ($user instanceof IUser) {
360
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
361
+            } else {
362
+                $this->userDisplayNames[$uid] = $uid;
363
+            }
364
+        }
365
+
366
+        return $this->userDisplayNames[$uid];
367
+    }
368 368
 	
369
-	/**
370
-	 * @return array
371
-	 */
372
-	public function getPublicCalendars() {
373
-		$fields = array_values($this->propertyMap);
374
-		$fields[] = 'a.id';
375
-		$fields[] = 'a.uri';
376
-		$fields[] = 'a.synctoken';
377
-		$fields[] = 'a.components';
378
-		$fields[] = 'a.principaluri';
379
-		$fields[] = 'a.transparent';
380
-		$fields[] = 's.access';
381
-		$fields[] = 's.publicuri';
382
-		$calendars = [];
383
-		$query = $this->db->getQueryBuilder();
384
-		$result = $query->select($fields)
385
-			->from('dav_shares', 's')
386
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
387
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
388
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
389
-			->execute();
390
-
391
-		while($row = $result->fetch()) {
392
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
393
-			$row['displayname'] = $row['displayname'] . "($name)";
394
-			$components = [];
395
-			if ($row['components']) {
396
-				$components = explode(',',$row['components']);
397
-			}
398
-			$calendar = [
399
-				'id' => $row['id'],
400
-				'uri' => $row['publicuri'],
401
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
402
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
403
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
404
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
406
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
408
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
409
-			];
410
-
411
-			foreach($this->propertyMap as $xmlName=>$dbName) {
412
-				$calendar[$xmlName] = $row[$dbName];
413
-			}
414
-
415
-			if (!isset($calendars[$calendar['id']])) {
416
-				$calendars[$calendar['id']] = $calendar;
417
-			}
418
-		}
419
-		$result->closeCursor();
420
-
421
-		return array_values($calendars);
422
-	}
423
-
424
-	/**
425
-	 * @param string $uri
426
-	 * @return array
427
-	 * @throws NotFound
428
-	 */
429
-	public function getPublicCalendar($uri) {
430
-		$fields = array_values($this->propertyMap);
431
-		$fields[] = 'a.id';
432
-		$fields[] = 'a.uri';
433
-		$fields[] = 'a.synctoken';
434
-		$fields[] = 'a.components';
435
-		$fields[] = 'a.principaluri';
436
-		$fields[] = 'a.transparent';
437
-		$fields[] = 's.access';
438
-		$fields[] = 's.publicuri';
439
-		$query = $this->db->getQueryBuilder();
440
-		$result = $query->select($fields)
441
-			->from('dav_shares', 's')
442
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
443
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
444
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
445
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
446
-			->execute();
447
-
448
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
449
-
450
-		$result->closeCursor();
451
-
452
-		if ($row === false) {
453
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
454
-		}
455
-
456
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
457
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
458
-		$components = [];
459
-		if ($row['components']) {
460
-			$components = explode(',',$row['components']);
461
-		}
462
-		$calendar = [
463
-			'id' => $row['id'],
464
-			'uri' => $row['publicuri'],
465
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
473
-		];
474
-
475
-		foreach($this->propertyMap as $xmlName=>$dbName) {
476
-			$calendar[$xmlName] = $row[$dbName];
477
-		}
478
-
479
-		return $calendar;
480
-
481
-	}
482
-
483
-	/**
484
-	 * @param string $principal
485
-	 * @param string $uri
486
-	 * @return array|null
487
-	 */
488
-	public function getCalendarByUri($principal, $uri) {
489
-		$fields = array_values($this->propertyMap);
490
-		$fields[] = 'id';
491
-		$fields[] = 'uri';
492
-		$fields[] = 'synctoken';
493
-		$fields[] = 'components';
494
-		$fields[] = 'principaluri';
495
-		$fields[] = 'transparent';
496
-
497
-		// Making fields a comma-delimited list
498
-		$query = $this->db->getQueryBuilder();
499
-		$query->select($fields)->from('calendars')
500
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
501
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
502
-			->setMaxResults(1);
503
-		$stmt = $query->execute();
504
-
505
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
506
-		$stmt->closeCursor();
507
-		if ($row === false) {
508
-			return null;
509
-		}
510
-
511
-		$components = [];
512
-		if ($row['components']) {
513
-			$components = explode(',',$row['components']);
514
-		}
515
-
516
-		$calendar = [
517
-			'id' => $row['id'],
518
-			'uri' => $row['uri'],
519
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
520
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
521
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
522
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
524
-		];
525
-
526
-		foreach($this->propertyMap as $xmlName=>$dbName) {
527
-			$calendar[$xmlName] = $row[$dbName];
528
-		}
529
-
530
-		return $calendar;
531
-	}
532
-
533
-	public function getCalendarById($calendarId) {
534
-		$fields = array_values($this->propertyMap);
535
-		$fields[] = 'id';
536
-		$fields[] = 'uri';
537
-		$fields[] = 'synctoken';
538
-		$fields[] = 'components';
539
-		$fields[] = 'principaluri';
540
-		$fields[] = 'transparent';
541
-
542
-		// Making fields a comma-delimited list
543
-		$query = $this->db->getQueryBuilder();
544
-		$query->select($fields)->from('calendars')
545
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
546
-			->setMaxResults(1);
547
-		$stmt = $query->execute();
548
-
549
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
550
-		$stmt->closeCursor();
551
-		if ($row === false) {
552
-			return null;
553
-		}
554
-
555
-		$components = [];
556
-		if ($row['components']) {
557
-			$components = explode(',',$row['components']);
558
-		}
559
-
560
-		$calendar = [
561
-			'id' => $row['id'],
562
-			'uri' => $row['uri'],
563
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
564
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
565
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
566
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
568
-		];
569
-
570
-		foreach($this->propertyMap as $xmlName=>$dbName) {
571
-			$calendar[$xmlName] = $row[$dbName];
572
-		}
573
-
574
-		return $calendar;
575
-	}
576
-
577
-	/**
578
-	 * Creates a new calendar for a principal.
579
-	 *
580
-	 * If the creation was a success, an id must be returned that can be used to reference
581
-	 * this calendar in other methods, such as updateCalendar.
582
-	 *
583
-	 * @param string $principalUri
584
-	 * @param string $calendarUri
585
-	 * @param array $properties
586
-	 * @return int
587
-	 */
588
-	function createCalendar($principalUri, $calendarUri, array $properties) {
589
-		$values = [
590
-			'principaluri' => $this->convertPrincipal($principalUri, true),
591
-			'uri'          => $calendarUri,
592
-			'synctoken'    => 1,
593
-			'transparent'  => 0,
594
-			'components'   => 'VEVENT,VTODO',
595
-			'displayname'  => $calendarUri
596
-		];
597
-
598
-		// Default value
599
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
600
-		if (isset($properties[$sccs])) {
601
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
602
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
603
-			}
604
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
605
-		}
606
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
607
-		if (isset($properties[$transp])) {
608
-			$values['transparent'] = $properties[$transp]->getValue()==='transparent';
609
-		}
610
-
611
-		foreach($this->propertyMap as $xmlName=>$dbName) {
612
-			if (isset($properties[$xmlName])) {
613
-				$values[$dbName] = $properties[$xmlName];
614
-			}
615
-		}
616
-
617
-		$query = $this->db->getQueryBuilder();
618
-		$query->insert('calendars');
619
-		foreach($values as $column => $value) {
620
-			$query->setValue($column, $query->createNamedParameter($value));
621
-		}
622
-		$query->execute();
623
-		$calendarId = $query->getLastInsertId();
624
-
625
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
626
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
627
-			[
628
-				'calendarId' => $calendarId,
629
-				'calendarData' => $this->getCalendarById($calendarId),
630
-		]));
631
-
632
-		return $calendarId;
633
-	}
634
-
635
-	/**
636
-	 * Updates properties for a calendar.
637
-	 *
638
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
639
-	 * To do the actual updates, you must tell this object which properties
640
-	 * you're going to process with the handle() method.
641
-	 *
642
-	 * Calling the handle method is like telling the PropPatch object "I
643
-	 * promise I can handle updating this property".
644
-	 *
645
-	 * Read the PropPatch documentation for more info and examples.
646
-	 *
647
-	 * @param PropPatch $propPatch
648
-	 * @return void
649
-	 */
650
-	function updateCalendar($calendarId, PropPatch $propPatch) {
651
-		$supportedProperties = array_keys($this->propertyMap);
652
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
653
-
654
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
655
-			$newValues = [];
656
-			foreach ($mutations as $propertyName => $propertyValue) {
657
-
658
-				switch ($propertyName) {
659
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
660
-						$fieldName = 'transparent';
661
-						$newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
662
-						break;
663
-					default :
664
-						$fieldName = $this->propertyMap[$propertyName];
665
-						$newValues[$fieldName] = $propertyValue;
666
-						break;
667
-				}
668
-
669
-			}
670
-			$query = $this->db->getQueryBuilder();
671
-			$query->update('calendars');
672
-			foreach ($newValues as $fieldName => $value) {
673
-				$query->set($fieldName, $query->createNamedParameter($value));
674
-			}
675
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
676
-			$query->execute();
677
-
678
-			$this->addChange($calendarId, "", 2);
679
-
680
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
681
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
682
-				[
683
-					'calendarId' => $calendarId,
684
-					'calendarData' => $this->getCalendarById($calendarId),
685
-					'shares' => $this->getShares($calendarId),
686
-					'propertyMutations' => $mutations,
687
-			]));
688
-
689
-			return true;
690
-		});
691
-	}
692
-
693
-	/**
694
-	 * Delete a calendar and all it's objects
695
-	 *
696
-	 * @param mixed $calendarId
697
-	 * @return void
698
-	 */
699
-	function deleteCalendar($calendarId) {
700
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
701
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
702
-			[
703
-				'calendarId' => $calendarId,
704
-				'calendarData' => $this->getCalendarById($calendarId),
705
-				'shares' => $this->getShares($calendarId),
706
-		]));
707
-
708
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
709
-		$stmt->execute([$calendarId]);
710
-
711
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
712
-		$stmt->execute([$calendarId]);
713
-
714
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
715
-		$stmt->execute([$calendarId]);
716
-
717
-		$this->sharingBackend->deleteAllShares($calendarId);
718
-	}
719
-
720
-	/**
721
-	 * Delete all of an user's shares
722
-	 *
723
-	 * @param string $principaluri
724
-	 * @return void
725
-	 */
726
-	function deleteAllSharesByUser($principaluri) {
727
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
728
-	}
729
-
730
-	/**
731
-	 * Returns all calendar objects within a calendar.
732
-	 *
733
-	 * Every item contains an array with the following keys:
734
-	 *   * calendardata - The iCalendar-compatible calendar data
735
-	 *   * uri - a unique key which will be used to construct the uri. This can
736
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
737
-	 *     good idea. This is only the basename, or filename, not the full
738
-	 *     path.
739
-	 *   * lastmodified - a timestamp of the last modification time
740
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
741
-	 *   '"abcdef"')
742
-	 *   * size - The size of the calendar objects, in bytes.
743
-	 *   * component - optional, a string containing the type of object, such
744
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
745
-	 *     the Content-Type header.
746
-	 *
747
-	 * Note that the etag is optional, but it's highly encouraged to return for
748
-	 * speed reasons.
749
-	 *
750
-	 * The calendardata is also optional. If it's not returned
751
-	 * 'getCalendarObject' will be called later, which *is* expected to return
752
-	 * calendardata.
753
-	 *
754
-	 * If neither etag or size are specified, the calendardata will be
755
-	 * used/fetched to determine these numbers. If both are specified the
756
-	 * amount of times this is needed is reduced by a great degree.
757
-	 *
758
-	 * @param mixed $calendarId
759
-	 * @return array
760
-	 */
761
-	function getCalendarObjects($calendarId) {
762
-		$query = $this->db->getQueryBuilder();
763
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
764
-			->from('calendarobjects')
765
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
766
-		$stmt = $query->execute();
767
-
768
-		$result = [];
769
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
770
-			$result[] = [
771
-					'id'           => $row['id'],
772
-					'uri'          => $row['uri'],
773
-					'lastmodified' => $row['lastmodified'],
774
-					'etag'         => '"' . $row['etag'] . '"',
775
-					'calendarid'   => $row['calendarid'],
776
-					'size'         => (int)$row['size'],
777
-					'component'    => strtolower($row['componenttype']),
778
-					'classification'=> (int)$row['classification']
779
-			];
780
-		}
781
-
782
-		return $result;
783
-	}
784
-
785
-	/**
786
-	 * Returns information from a single calendar object, based on it's object
787
-	 * uri.
788
-	 *
789
-	 * The object uri is only the basename, or filename and not a full path.
790
-	 *
791
-	 * The returned array must have the same keys as getCalendarObjects. The
792
-	 * 'calendardata' object is required here though, while it's not required
793
-	 * for getCalendarObjects.
794
-	 *
795
-	 * This method must return null if the object did not exist.
796
-	 *
797
-	 * @param mixed $calendarId
798
-	 * @param string $objectUri
799
-	 * @return array|null
800
-	 */
801
-	function getCalendarObject($calendarId, $objectUri) {
802
-
803
-		$query = $this->db->getQueryBuilder();
804
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
805
-				->from('calendarobjects')
806
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
807
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
808
-		$stmt = $query->execute();
809
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810
-
811
-		if(!$row) return null;
812
-
813
-		return [
814
-				'id'            => $row['id'],
815
-				'uri'           => $row['uri'],
816
-				'lastmodified'  => $row['lastmodified'],
817
-				'etag'          => '"' . $row['etag'] . '"',
818
-				'calendarid'    => $row['calendarid'],
819
-				'size'          => (int)$row['size'],
820
-				'calendardata'  => $this->readBlob($row['calendardata']),
821
-				'component'     => strtolower($row['componenttype']),
822
-				'classification'=> (int)$row['classification']
823
-		];
824
-	}
825
-
826
-	/**
827
-	 * Returns a list of calendar objects.
828
-	 *
829
-	 * This method should work identical to getCalendarObject, but instead
830
-	 * return all the calendar objects in the list as an array.
831
-	 *
832
-	 * If the backend supports this, it may allow for some speed-ups.
833
-	 *
834
-	 * @param mixed $calendarId
835
-	 * @param string[] $uris
836
-	 * @return array
837
-	 */
838
-	function getMultipleCalendarObjects($calendarId, array $uris) {
839
-		if (empty($uris)) {
840
-			return [];
841
-		}
842
-
843
-		$chunks = array_chunk($uris, 100);
844
-		$objects = [];
845
-
846
-		$query = $this->db->getQueryBuilder();
847
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
848
-			->from('calendarobjects')
849
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
850
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
851
-
852
-		foreach ($chunks as $uris) {
853
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
854
-			$result = $query->execute();
855
-
856
-			while ($row = $result->fetch()) {
857
-				$objects[] = [
858
-					'id'           => $row['id'],
859
-					'uri'          => $row['uri'],
860
-					'lastmodified' => $row['lastmodified'],
861
-					'etag'         => '"' . $row['etag'] . '"',
862
-					'calendarid'   => $row['calendarid'],
863
-					'size'         => (int)$row['size'],
864
-					'calendardata' => $this->readBlob($row['calendardata']),
865
-					'component'    => strtolower($row['componenttype']),
866
-					'classification' => (int)$row['classification']
867
-				];
868
-			}
869
-			$result->closeCursor();
870
-		}
871
-		return $objects;
872
-	}
873
-
874
-	/**
875
-	 * Creates a new calendar object.
876
-	 *
877
-	 * The object uri is only the basename, or filename and not a full path.
878
-	 *
879
-	 * It is possible return an etag from this function, which will be used in
880
-	 * the response to this PUT request. Note that the ETag must be surrounded
881
-	 * by double-quotes.
882
-	 *
883
-	 * However, you should only really return this ETag if you don't mangle the
884
-	 * calendar-data. If the result of a subsequent GET to this object is not
885
-	 * the exact same as this request body, you should omit the ETag.
886
-	 *
887
-	 * @param mixed $calendarId
888
-	 * @param string $objectUri
889
-	 * @param string $calendarData
890
-	 * @return string
891
-	 */
892
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
893
-		$extraData = $this->getDenormalizedData($calendarData);
894
-
895
-		$query = $this->db->getQueryBuilder();
896
-		$query->insert('calendarobjects')
897
-			->values([
898
-				'calendarid' => $query->createNamedParameter($calendarId),
899
-				'uri' => $query->createNamedParameter($objectUri),
900
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
901
-				'lastmodified' => $query->createNamedParameter(time()),
902
-				'etag' => $query->createNamedParameter($extraData['etag']),
903
-				'size' => $query->createNamedParameter($extraData['size']),
904
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
905
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
906
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
907
-				'classification' => $query->createNamedParameter($extraData['classification']),
908
-				'uid' => $query->createNamedParameter($extraData['uid']),
909
-			])
910
-			->execute();
911
-
912
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
913
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
914
-			[
915
-				'calendarId' => $calendarId,
916
-				'calendarData' => $this->getCalendarById($calendarId),
917
-				'shares' => $this->getShares($calendarId),
918
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
919
-			]
920
-		));
921
-		$this->addChange($calendarId, $objectUri, 1);
922
-
923
-		return '"' . $extraData['etag'] . '"';
924
-	}
925
-
926
-	/**
927
-	 * Updates an existing calendarobject, based on it's uri.
928
-	 *
929
-	 * The object uri is only the basename, or filename and not a full path.
930
-	 *
931
-	 * It is possible return an etag from this function, which will be used in
932
-	 * the response to this PUT request. Note that the ETag must be surrounded
933
-	 * by double-quotes.
934
-	 *
935
-	 * However, you should only really return this ETag if you don't mangle the
936
-	 * calendar-data. If the result of a subsequent GET to this object is not
937
-	 * the exact same as this request body, you should omit the ETag.
938
-	 *
939
-	 * @param mixed $calendarId
940
-	 * @param string $objectUri
941
-	 * @param string $calendarData
942
-	 * @return string
943
-	 */
944
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
945
-		$extraData = $this->getDenormalizedData($calendarData);
946
-
947
-		$query = $this->db->getQueryBuilder();
948
-		$query->update('calendarobjects')
949
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
950
-				->set('lastmodified', $query->createNamedParameter(time()))
951
-				->set('etag', $query->createNamedParameter($extraData['etag']))
952
-				->set('size', $query->createNamedParameter($extraData['size']))
953
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
954
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
955
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
956
-				->set('classification', $query->createNamedParameter($extraData['classification']))
957
-				->set('uid', $query->createNamedParameter($extraData['uid']))
958
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
-			->execute();
961
-
962
-		$data = $this->getCalendarObject($calendarId, $objectUri);
963
-		if (is_array($data)) {
964
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
965
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
966
-				[
967
-					'calendarId' => $calendarId,
968
-					'calendarData' => $this->getCalendarById($calendarId),
969
-					'shares' => $this->getShares($calendarId),
970
-					'objectData' => $data,
971
-				]
972
-			));
973
-		}
974
-		$this->addChange($calendarId, $objectUri, 2);
975
-
976
-		return '"' . $extraData['etag'] . '"';
977
-	}
978
-
979
-	/**
980
-	 * @param int $calendarObjectId
981
-	 * @param int $classification
982
-	 */
983
-	public function setClassification($calendarObjectId, $classification) {
984
-		if (!in_array($classification, [
985
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
986
-		])) {
987
-			throw new \InvalidArgumentException();
988
-		}
989
-		$query = $this->db->getQueryBuilder();
990
-		$query->update('calendarobjects')
991
-			->set('classification', $query->createNamedParameter($classification))
992
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
993
-			->execute();
994
-	}
995
-
996
-	/**
997
-	 * Deletes an existing calendar object.
998
-	 *
999
-	 * The object uri is only the basename, or filename and not a full path.
1000
-	 *
1001
-	 * @param mixed $calendarId
1002
-	 * @param string $objectUri
1003
-	 * @return void
1004
-	 */
1005
-	function deleteCalendarObject($calendarId, $objectUri) {
1006
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1007
-		if (is_array($data)) {
1008
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1009
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1010
-				[
1011
-					'calendarId' => $calendarId,
1012
-					'calendarData' => $this->getCalendarById($calendarId),
1013
-					'shares' => $this->getShares($calendarId),
1014
-					'objectData' => $data,
1015
-				]
1016
-			));
1017
-		}
1018
-
1019
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1020
-		$stmt->execute([$calendarId, $objectUri]);
1021
-
1022
-		$this->addChange($calendarId, $objectUri, 3);
1023
-	}
1024
-
1025
-	/**
1026
-	 * Performs a calendar-query on the contents of this calendar.
1027
-	 *
1028
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1029
-	 * calendar-query it is possible for a client to request a specific set of
1030
-	 * object, based on contents of iCalendar properties, date-ranges and
1031
-	 * iCalendar component types (VTODO, VEVENT).
1032
-	 *
1033
-	 * This method should just return a list of (relative) urls that match this
1034
-	 * query.
1035
-	 *
1036
-	 * The list of filters are specified as an array. The exact array is
1037
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1038
-	 *
1039
-	 * Note that it is extremely likely that getCalendarObject for every path
1040
-	 * returned from this method will be called almost immediately after. You
1041
-	 * may want to anticipate this to speed up these requests.
1042
-	 *
1043
-	 * This method provides a default implementation, which parses *all* the
1044
-	 * iCalendar objects in the specified calendar.
1045
-	 *
1046
-	 * This default may well be good enough for personal use, and calendars
1047
-	 * that aren't very large. But if you anticipate high usage, big calendars
1048
-	 * or high loads, you are strongly advised to optimize certain paths.
1049
-	 *
1050
-	 * The best way to do so is override this method and to optimize
1051
-	 * specifically for 'common filters'.
1052
-	 *
1053
-	 * Requests that are extremely common are:
1054
-	 *   * requests for just VEVENTS
1055
-	 *   * requests for just VTODO
1056
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1057
-	 *
1058
-	 * ..and combinations of these requests. It may not be worth it to try to
1059
-	 * handle every possible situation and just rely on the (relatively
1060
-	 * easy to use) CalendarQueryValidator to handle the rest.
1061
-	 *
1062
-	 * Note that especially time-range-filters may be difficult to parse. A
1063
-	 * time-range filter specified on a VEVENT must for instance also handle
1064
-	 * recurrence rules correctly.
1065
-	 * A good example of how to interprete all these filters can also simply
1066
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1067
-	 * as possible, so it gives you a good idea on what type of stuff you need
1068
-	 * to think of.
1069
-	 *
1070
-	 * @param mixed $calendarId
1071
-	 * @param array $filters
1072
-	 * @return array
1073
-	 */
1074
-	function calendarQuery($calendarId, array $filters) {
1075
-		$componentType = null;
1076
-		$requirePostFilter = true;
1077
-		$timeRange = null;
1078
-
1079
-		// if no filters were specified, we don't need to filter after a query
1080
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1081
-			$requirePostFilter = false;
1082
-		}
1083
-
1084
-		// Figuring out if there's a component filter
1085
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1086
-			$componentType = $filters['comp-filters'][0]['name'];
1087
-
1088
-			// Checking if we need post-filters
1089
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1090
-				$requirePostFilter = false;
1091
-			}
1092
-			// There was a time-range filter
1093
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1094
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1095
-
1096
-				// If start time OR the end time is not specified, we can do a
1097
-				// 100% accurate mysql query.
1098
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1099
-					$requirePostFilter = false;
1100
-				}
1101
-			}
1102
-
1103
-		}
1104
-		$columns = ['uri'];
1105
-		if ($requirePostFilter) {
1106
-			$columns = ['uri', 'calendardata'];
1107
-		}
1108
-		$query = $this->db->getQueryBuilder();
1109
-		$query->select($columns)
1110
-			->from('calendarobjects')
1111
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1112
-
1113
-		if ($componentType) {
1114
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1115
-		}
1116
-
1117
-		if ($timeRange && $timeRange['start']) {
1118
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1119
-		}
1120
-		if ($timeRange && $timeRange['end']) {
1121
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1122
-		}
1123
-
1124
-		$stmt = $query->execute();
1125
-
1126
-		$result = [];
1127
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1128
-			if ($requirePostFilter) {
1129
-				if (!$this->validateFilterForObject($row, $filters)) {
1130
-					continue;
1131
-				}
1132
-			}
1133
-			$result[] = $row['uri'];
1134
-		}
1135
-
1136
-		return $result;
1137
-	}
1138
-
1139
-	/**
1140
-	 * Searches through all of a users calendars and calendar objects to find
1141
-	 * an object with a specific UID.
1142
-	 *
1143
-	 * This method should return the path to this object, relative to the
1144
-	 * calendar home, so this path usually only contains two parts:
1145
-	 *
1146
-	 * calendarpath/objectpath.ics
1147
-	 *
1148
-	 * If the uid is not found, return null.
1149
-	 *
1150
-	 * This method should only consider * objects that the principal owns, so
1151
-	 * any calendars owned by other principals that also appear in this
1152
-	 * collection should be ignored.
1153
-	 *
1154
-	 * @param string $principalUri
1155
-	 * @param string $uid
1156
-	 * @return string|null
1157
-	 */
1158
-	function getCalendarObjectByUID($principalUri, $uid) {
1159
-
1160
-		$query = $this->db->getQueryBuilder();
1161
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1162
-			->from('calendarobjects', 'co')
1163
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1164
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1165
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1166
-
1167
-		$stmt = $query->execute();
1168
-
1169
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1170
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1171
-		}
1172
-
1173
-		return null;
1174
-	}
1175
-
1176
-	/**
1177
-	 * The getChanges method returns all the changes that have happened, since
1178
-	 * the specified syncToken in the specified calendar.
1179
-	 *
1180
-	 * This function should return an array, such as the following:
1181
-	 *
1182
-	 * [
1183
-	 *   'syncToken' => 'The current synctoken',
1184
-	 *   'added'   => [
1185
-	 *      'new.txt',
1186
-	 *   ],
1187
-	 *   'modified'   => [
1188
-	 *      'modified.txt',
1189
-	 *   ],
1190
-	 *   'deleted' => [
1191
-	 *      'foo.php.bak',
1192
-	 *      'old.txt'
1193
-	 *   ]
1194
-	 * );
1195
-	 *
1196
-	 * The returned syncToken property should reflect the *current* syncToken
1197
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1198
-	 * property This is * needed here too, to ensure the operation is atomic.
1199
-	 *
1200
-	 * If the $syncToken argument is specified as null, this is an initial
1201
-	 * sync, and all members should be reported.
1202
-	 *
1203
-	 * The modified property is an array of nodenames that have changed since
1204
-	 * the last token.
1205
-	 *
1206
-	 * The deleted property is an array with nodenames, that have been deleted
1207
-	 * from collection.
1208
-	 *
1209
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1210
-	 * 1, you only have to report changes that happened only directly in
1211
-	 * immediate descendants. If it's 2, it should also include changes from
1212
-	 * the nodes below the child collections. (grandchildren)
1213
-	 *
1214
-	 * The $limit argument allows a client to specify how many results should
1215
-	 * be returned at most. If the limit is not specified, it should be treated
1216
-	 * as infinite.
1217
-	 *
1218
-	 * If the limit (infinite or not) is higher than you're willing to return,
1219
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1220
-	 *
1221
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1222
-	 * return null.
1223
-	 *
1224
-	 * The limit is 'suggestive'. You are free to ignore it.
1225
-	 *
1226
-	 * @param string $calendarId
1227
-	 * @param string $syncToken
1228
-	 * @param int $syncLevel
1229
-	 * @param int $limit
1230
-	 * @return array
1231
-	 */
1232
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1233
-		// Current synctoken
1234
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1235
-		$stmt->execute([ $calendarId ]);
1236
-		$currentToken = $stmt->fetchColumn(0);
1237
-
1238
-		if (is_null($currentToken)) {
1239
-			return null;
1240
-		}
1241
-
1242
-		$result = [
1243
-			'syncToken' => $currentToken,
1244
-			'added'     => [],
1245
-			'modified'  => [],
1246
-			'deleted'   => [],
1247
-		];
1248
-
1249
-		if ($syncToken) {
1250
-
1251
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1252
-			if ($limit>0) {
1253
-				$query.= " `LIMIT` " . (int)$limit;
1254
-			}
1255
-
1256
-			// Fetching all changes
1257
-			$stmt = $this->db->prepare($query);
1258
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1259
-
1260
-			$changes = [];
1261
-
1262
-			// This loop ensures that any duplicates are overwritten, only the
1263
-			// last change on a node is relevant.
1264
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1265
-
1266
-				$changes[$row['uri']] = $row['operation'];
1267
-
1268
-			}
1269
-
1270
-			foreach($changes as $uri => $operation) {
1271
-
1272
-				switch($operation) {
1273
-					case 1 :
1274
-						$result['added'][] = $uri;
1275
-						break;
1276
-					case 2 :
1277
-						$result['modified'][] = $uri;
1278
-						break;
1279
-					case 3 :
1280
-						$result['deleted'][] = $uri;
1281
-						break;
1282
-				}
1283
-
1284
-			}
1285
-		} else {
1286
-			// No synctoken supplied, this is the initial sync.
1287
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1288
-			$stmt = $this->db->prepare($query);
1289
-			$stmt->execute([$calendarId]);
1290
-
1291
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1292
-		}
1293
-		return $result;
1294
-
1295
-	}
1296
-
1297
-	/**
1298
-	 * Returns a list of subscriptions for a principal.
1299
-	 *
1300
-	 * Every subscription is an array with the following keys:
1301
-	 *  * id, a unique id that will be used by other functions to modify the
1302
-	 *    subscription. This can be the same as the uri or a database key.
1303
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1304
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1305
-	 *    principalUri passed to this method.
1306
-	 *
1307
-	 * Furthermore, all the subscription info must be returned too:
1308
-	 *
1309
-	 * 1. {DAV:}displayname
1310
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1311
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1312
-	 *    should not be stripped).
1313
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1314
-	 *    should not be stripped).
1315
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1316
-	 *    attachments should not be stripped).
1317
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1318
-	 *     Sabre\DAV\Property\Href).
1319
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1320
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1321
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1322
-	 *    (should just be an instance of
1323
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1324
-	 *    default components).
1325
-	 *
1326
-	 * @param string $principalUri
1327
-	 * @return array
1328
-	 */
1329
-	function getSubscriptionsForUser($principalUri) {
1330
-		$fields = array_values($this->subscriptionPropertyMap);
1331
-		$fields[] = 'id';
1332
-		$fields[] = 'uri';
1333
-		$fields[] = 'source';
1334
-		$fields[] = 'principaluri';
1335
-		$fields[] = 'lastmodified';
1336
-
1337
-		$query = $this->db->getQueryBuilder();
1338
-		$query->select($fields)
1339
-			->from('calendarsubscriptions')
1340
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1341
-			->orderBy('calendarorder', 'asc');
1342
-		$stmt =$query->execute();
1343
-
1344
-		$subscriptions = [];
1345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1346
-
1347
-			$subscription = [
1348
-				'id'           => $row['id'],
1349
-				'uri'          => $row['uri'],
1350
-				'principaluri' => $row['principaluri'],
1351
-				'source'       => $row['source'],
1352
-				'lastmodified' => $row['lastmodified'],
1353
-
1354
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1355
-			];
1356
-
1357
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1358
-				if (!is_null($row[$dbName])) {
1359
-					$subscription[$xmlName] = $row[$dbName];
1360
-				}
1361
-			}
1362
-
1363
-			$subscriptions[] = $subscription;
1364
-
1365
-		}
1366
-
1367
-		return $subscriptions;
1368
-	}
1369
-
1370
-	/**
1371
-	 * Creates a new subscription for a principal.
1372
-	 *
1373
-	 * If the creation was a success, an id must be returned that can be used to reference
1374
-	 * this subscription in other methods, such as updateSubscription.
1375
-	 *
1376
-	 * @param string $principalUri
1377
-	 * @param string $uri
1378
-	 * @param array $properties
1379
-	 * @return mixed
1380
-	 */
1381
-	function createSubscription($principalUri, $uri, array $properties) {
1382
-
1383
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1384
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1385
-		}
1386
-
1387
-		$values = [
1388
-			'principaluri' => $principalUri,
1389
-			'uri'          => $uri,
1390
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1391
-			'lastmodified' => time(),
1392
-		];
1393
-
1394
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1395
-
1396
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1397
-			if (array_key_exists($xmlName, $properties)) {
1398
-					$values[$dbName] = $properties[$xmlName];
1399
-					if (in_array($dbName, $propertiesBoolean)) {
1400
-						$values[$dbName] = true;
1401
-				}
1402
-			}
1403
-		}
1404
-
1405
-		$valuesToInsert = array();
1406
-
1407
-		$query = $this->db->getQueryBuilder();
1408
-
1409
-		foreach (array_keys($values) as $name) {
1410
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1411
-		}
1412
-
1413
-		$query->insert('calendarsubscriptions')
1414
-			->values($valuesToInsert)
1415
-			->execute();
1416
-
1417
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Updates a subscription
1422
-	 *
1423
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1424
-	 * To do the actual updates, you must tell this object which properties
1425
-	 * you're going to process with the handle() method.
1426
-	 *
1427
-	 * Calling the handle method is like telling the PropPatch object "I
1428
-	 * promise I can handle updating this property".
1429
-	 *
1430
-	 * Read the PropPatch documentation for more info and examples.
1431
-	 *
1432
-	 * @param mixed $subscriptionId
1433
-	 * @param PropPatch $propPatch
1434
-	 * @return void
1435
-	 */
1436
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1437
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1438
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1439
-
1440
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1441
-
1442
-			$newValues = [];
1443
-
1444
-			foreach($mutations as $propertyName=>$propertyValue) {
1445
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1446
-					$newValues['source'] = $propertyValue->getHref();
1447
-				} else {
1448
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1449
-					$newValues[$fieldName] = $propertyValue;
1450
-				}
1451
-			}
1452
-
1453
-			$query = $this->db->getQueryBuilder();
1454
-			$query->update('calendarsubscriptions')
1455
-				->set('lastmodified', $query->createNamedParameter(time()));
1456
-			foreach($newValues as $fieldName=>$value) {
1457
-				$query->set($fieldName, $query->createNamedParameter($value));
1458
-			}
1459
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1460
-				->execute();
1461
-
1462
-			return true;
1463
-
1464
-		});
1465
-	}
1466
-
1467
-	/**
1468
-	 * Deletes a subscription.
1469
-	 *
1470
-	 * @param mixed $subscriptionId
1471
-	 * @return void
1472
-	 */
1473
-	function deleteSubscription($subscriptionId) {
1474
-		$query = $this->db->getQueryBuilder();
1475
-		$query->delete('calendarsubscriptions')
1476
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1477
-			->execute();
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns a single scheduling object for the inbox collection.
1482
-	 *
1483
-	 * The returned array should contain the following elements:
1484
-	 *   * uri - A unique basename for the object. This will be used to
1485
-	 *           construct a full uri.
1486
-	 *   * calendardata - The iCalendar object
1487
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1488
-	 *                    timestamp, or a PHP DateTime object.
1489
-	 *   * etag - A unique token that must change if the object changed.
1490
-	 *   * size - The size of the object, in bytes.
1491
-	 *
1492
-	 * @param string $principalUri
1493
-	 * @param string $objectUri
1494
-	 * @return array
1495
-	 */
1496
-	function getSchedulingObject($principalUri, $objectUri) {
1497
-		$query = $this->db->getQueryBuilder();
1498
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1499
-			->from('schedulingobjects')
1500
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1501
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1502
-			->execute();
1503
-
1504
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1505
-
1506
-		if(!$row) {
1507
-			return null;
1508
-		}
1509
-
1510
-		return [
1511
-				'uri'          => $row['uri'],
1512
-				'calendardata' => $row['calendardata'],
1513
-				'lastmodified' => $row['lastmodified'],
1514
-				'etag'         => '"' . $row['etag'] . '"',
1515
-				'size'         => (int)$row['size'],
1516
-		];
1517
-	}
1518
-
1519
-	/**
1520
-	 * Returns all scheduling objects for the inbox collection.
1521
-	 *
1522
-	 * These objects should be returned as an array. Every item in the array
1523
-	 * should follow the same structure as returned from getSchedulingObject.
1524
-	 *
1525
-	 * The main difference is that 'calendardata' is optional.
1526
-	 *
1527
-	 * @param string $principalUri
1528
-	 * @return array
1529
-	 */
1530
-	function getSchedulingObjects($principalUri) {
1531
-		$query = $this->db->getQueryBuilder();
1532
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1533
-				->from('schedulingobjects')
1534
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1535
-				->execute();
1536
-
1537
-		$result = [];
1538
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1539
-			$result[] = [
1540
-					'calendardata' => $row['calendardata'],
1541
-					'uri'          => $row['uri'],
1542
-					'lastmodified' => $row['lastmodified'],
1543
-					'etag'         => '"' . $row['etag'] . '"',
1544
-					'size'         => (int)$row['size'],
1545
-			];
1546
-		}
1547
-
1548
-		return $result;
1549
-	}
1550
-
1551
-	/**
1552
-	 * Deletes a scheduling object from the inbox collection.
1553
-	 *
1554
-	 * @param string $principalUri
1555
-	 * @param string $objectUri
1556
-	 * @return void
1557
-	 */
1558
-	function deleteSchedulingObject($principalUri, $objectUri) {
1559
-		$query = $this->db->getQueryBuilder();
1560
-		$query->delete('schedulingobjects')
1561
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1562
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1563
-				->execute();
1564
-	}
1565
-
1566
-	/**
1567
-	 * Creates a new scheduling object. This should land in a users' inbox.
1568
-	 *
1569
-	 * @param string $principalUri
1570
-	 * @param string $objectUri
1571
-	 * @param string $objectData
1572
-	 * @return void
1573
-	 */
1574
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1575
-		$query = $this->db->getQueryBuilder();
1576
-		$query->insert('schedulingobjects')
1577
-			->values([
1578
-				'principaluri' => $query->createNamedParameter($principalUri),
1579
-				'calendardata' => $query->createNamedParameter($objectData),
1580
-				'uri' => $query->createNamedParameter($objectUri),
1581
-				'lastmodified' => $query->createNamedParameter(time()),
1582
-				'etag' => $query->createNamedParameter(md5($objectData)),
1583
-				'size' => $query->createNamedParameter(strlen($objectData))
1584
-			])
1585
-			->execute();
1586
-	}
1587
-
1588
-	/**
1589
-	 * Adds a change record to the calendarchanges table.
1590
-	 *
1591
-	 * @param mixed $calendarId
1592
-	 * @param string $objectUri
1593
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1594
-	 * @return void
1595
-	 */
1596
-	protected function addChange($calendarId, $objectUri, $operation) {
1597
-
1598
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1599
-		$stmt->execute([
1600
-			$objectUri,
1601
-			$calendarId,
1602
-			$operation,
1603
-			$calendarId
1604
-		]);
1605
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1606
-		$stmt->execute([
1607
-			$calendarId
1608
-		]);
1609
-
1610
-	}
1611
-
1612
-	/**
1613
-	 * Parses some information from calendar objects, used for optimized
1614
-	 * calendar-queries.
1615
-	 *
1616
-	 * Returns an array with the following keys:
1617
-	 *   * etag - An md5 checksum of the object without the quotes.
1618
-	 *   * size - Size of the object in bytes
1619
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1620
-	 *   * firstOccurence
1621
-	 *   * lastOccurence
1622
-	 *   * uid - value of the UID property
1623
-	 *
1624
-	 * @param string $calendarData
1625
-	 * @return array
1626
-	 */
1627
-	public function getDenormalizedData($calendarData) {
1628
-
1629
-		$vObject = Reader::read($calendarData);
1630
-		$componentType = null;
1631
-		$component = null;
1632
-		$firstOccurrence = null;
1633
-		$lastOccurrence = null;
1634
-		$uid = null;
1635
-		$classification = self::CLASSIFICATION_PUBLIC;
1636
-		foreach($vObject->getComponents() as $component) {
1637
-			if ($component->name!=='VTIMEZONE') {
1638
-				$componentType = $component->name;
1639
-				$uid = (string)$component->UID;
1640
-				break;
1641
-			}
1642
-		}
1643
-		if (!$componentType) {
1644
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1645
-		}
1646
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1647
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1648
-			// Finding the last occurrence is a bit harder
1649
-			if (!isset($component->RRULE)) {
1650
-				if (isset($component->DTEND)) {
1651
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1652
-				} elseif (isset($component->DURATION)) {
1653
-					$endDate = clone $component->DTSTART->getDateTime();
1654
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1655
-					$lastOccurrence = $endDate->getTimeStamp();
1656
-				} elseif (!$component->DTSTART->hasTime()) {
1657
-					$endDate = clone $component->DTSTART->getDateTime();
1658
-					$endDate->modify('+1 day');
1659
-					$lastOccurrence = $endDate->getTimeStamp();
1660
-				} else {
1661
-					$lastOccurrence = $firstOccurrence;
1662
-				}
1663
-			} else {
1664
-				$it = new EventIterator($vObject, (string)$component->UID);
1665
-				$maxDate = new \DateTime(self::MAX_DATE);
1666
-				if ($it->isInfinite()) {
1667
-					$lastOccurrence = $maxDate->getTimestamp();
1668
-				} else {
1669
-					$end = $it->getDtEnd();
1670
-					while($it->valid() && $end < $maxDate) {
1671
-						$end = $it->getDtEnd();
1672
-						$it->next();
1673
-
1674
-					}
1675
-					$lastOccurrence = $end->getTimestamp();
1676
-				}
1677
-
1678
-			}
1679
-		}
1680
-
1681
-		if ($component->CLASS) {
1682
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1683
-			switch ($component->CLASS->getValue()) {
1684
-				case 'PUBLIC':
1685
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1686
-					break;
1687
-				case 'CONFIDENTIAL':
1688
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1689
-					break;
1690
-			}
1691
-		}
1692
-		return [
1693
-			'etag' => md5($calendarData),
1694
-			'size' => strlen($calendarData),
1695
-			'componentType' => $componentType,
1696
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1697
-			'lastOccurence'  => $lastOccurrence,
1698
-			'uid' => $uid,
1699
-			'classification' => $classification
1700
-		];
1701
-
1702
-	}
1703
-
1704
-	private function readBlob($cardData) {
1705
-		if (is_resource($cardData)) {
1706
-			return stream_get_contents($cardData);
1707
-		}
1708
-
1709
-		return $cardData;
1710
-	}
1711
-
1712
-	/**
1713
-	 * @param IShareable $shareable
1714
-	 * @param array $add
1715
-	 * @param array $remove
1716
-	 */
1717
-	public function updateShares($shareable, $add, $remove) {
1718
-		$calendarId = $shareable->getResourceId();
1719
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1720
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1721
-			[
1722
-				'calendarId' => $calendarId,
1723
-				'calendarData' => $this->getCalendarById($calendarId),
1724
-				'shares' => $this->getShares($calendarId),
1725
-				'add' => $add,
1726
-				'remove' => $remove,
1727
-			]));
1728
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1729
-	}
1730
-
1731
-	/**
1732
-	 * @param int $resourceId
1733
-	 * @return array
1734
-	 */
1735
-	public function getShares($resourceId) {
1736
-		return $this->sharingBackend->getShares($resourceId);
1737
-	}
1738
-
1739
-	/**
1740
-	 * @param boolean $value
1741
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1742
-	 * @return string|null
1743
-	 */
1744
-	public function setPublishStatus($value, $calendar) {
1745
-		$query = $this->db->getQueryBuilder();
1746
-		if ($value) {
1747
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1748
-			$query->insert('dav_shares')
1749
-				->values([
1750
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1751
-					'type' => $query->createNamedParameter('calendar'),
1752
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1753
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1754
-					'publicuri' => $query->createNamedParameter($publicUri)
1755
-				]);
1756
-			$query->execute();
1757
-			return $publicUri;
1758
-		}
1759
-		$query->delete('dav_shares')
1760
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1761
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1762
-		$query->execute();
1763
-		return null;
1764
-	}
1765
-
1766
-	/**
1767
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1768
-	 * @return mixed
1769
-	 */
1770
-	public function getPublishStatus($calendar) {
1771
-		$query = $this->db->getQueryBuilder();
1772
-		$result = $query->select('publicuri')
1773
-			->from('dav_shares')
1774
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1775
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1776
-			->execute();
1777
-
1778
-		$row = $result->fetch();
1779
-		$result->closeCursor();
1780
-		return $row ? reset($row) : false;
1781
-	}
1782
-
1783
-	/**
1784
-	 * @param int $resourceId
1785
-	 * @param array $acl
1786
-	 * @return array
1787
-	 */
1788
-	public function applyShareAcl($resourceId, $acl) {
1789
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1790
-	}
1791
-
1792
-	private function convertPrincipal($principalUri, $toV2) {
1793
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1794
-			list(, $name) = URLUtil::splitPath($principalUri);
1795
-			if ($toV2 === true) {
1796
-				return "principals/users/$name";
1797
-			}
1798
-			return "principals/$name";
1799
-		}
1800
-		return $principalUri;
1801
-	}
369
+    /**
370
+     * @return array
371
+     */
372
+    public function getPublicCalendars() {
373
+        $fields = array_values($this->propertyMap);
374
+        $fields[] = 'a.id';
375
+        $fields[] = 'a.uri';
376
+        $fields[] = 'a.synctoken';
377
+        $fields[] = 'a.components';
378
+        $fields[] = 'a.principaluri';
379
+        $fields[] = 'a.transparent';
380
+        $fields[] = 's.access';
381
+        $fields[] = 's.publicuri';
382
+        $calendars = [];
383
+        $query = $this->db->getQueryBuilder();
384
+        $result = $query->select($fields)
385
+            ->from('dav_shares', 's')
386
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
387
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
388
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
389
+            ->execute();
390
+
391
+        while($row = $result->fetch()) {
392
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
393
+            $row['displayname'] = $row['displayname'] . "($name)";
394
+            $components = [];
395
+            if ($row['components']) {
396
+                $components = explode(',',$row['components']);
397
+            }
398
+            $calendar = [
399
+                'id' => $row['id'],
400
+                'uri' => $row['publicuri'],
401
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
402
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
403
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
404
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
405
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
406
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
407
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
408
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
409
+            ];
410
+
411
+            foreach($this->propertyMap as $xmlName=>$dbName) {
412
+                $calendar[$xmlName] = $row[$dbName];
413
+            }
414
+
415
+            if (!isset($calendars[$calendar['id']])) {
416
+                $calendars[$calendar['id']] = $calendar;
417
+            }
418
+        }
419
+        $result->closeCursor();
420
+
421
+        return array_values($calendars);
422
+    }
423
+
424
+    /**
425
+     * @param string $uri
426
+     * @return array
427
+     * @throws NotFound
428
+     */
429
+    public function getPublicCalendar($uri) {
430
+        $fields = array_values($this->propertyMap);
431
+        $fields[] = 'a.id';
432
+        $fields[] = 'a.uri';
433
+        $fields[] = 'a.synctoken';
434
+        $fields[] = 'a.components';
435
+        $fields[] = 'a.principaluri';
436
+        $fields[] = 'a.transparent';
437
+        $fields[] = 's.access';
438
+        $fields[] = 's.publicuri';
439
+        $query = $this->db->getQueryBuilder();
440
+        $result = $query->select($fields)
441
+            ->from('dav_shares', 's')
442
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
443
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
444
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
445
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
446
+            ->execute();
447
+
448
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
449
+
450
+        $result->closeCursor();
451
+
452
+        if ($row === false) {
453
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
454
+        }
455
+
456
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
457
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
458
+        $components = [];
459
+        if ($row['components']) {
460
+            $components = explode(',',$row['components']);
461
+        }
462
+        $calendar = [
463
+            'id' => $row['id'],
464
+            'uri' => $row['publicuri'],
465
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
471
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
473
+        ];
474
+
475
+        foreach($this->propertyMap as $xmlName=>$dbName) {
476
+            $calendar[$xmlName] = $row[$dbName];
477
+        }
478
+
479
+        return $calendar;
480
+
481
+    }
482
+
483
+    /**
484
+     * @param string $principal
485
+     * @param string $uri
486
+     * @return array|null
487
+     */
488
+    public function getCalendarByUri($principal, $uri) {
489
+        $fields = array_values($this->propertyMap);
490
+        $fields[] = 'id';
491
+        $fields[] = 'uri';
492
+        $fields[] = 'synctoken';
493
+        $fields[] = 'components';
494
+        $fields[] = 'principaluri';
495
+        $fields[] = 'transparent';
496
+
497
+        // Making fields a comma-delimited list
498
+        $query = $this->db->getQueryBuilder();
499
+        $query->select($fields)->from('calendars')
500
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
501
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
502
+            ->setMaxResults(1);
503
+        $stmt = $query->execute();
504
+
505
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
506
+        $stmt->closeCursor();
507
+        if ($row === false) {
508
+            return null;
509
+        }
510
+
511
+        $components = [];
512
+        if ($row['components']) {
513
+            $components = explode(',',$row['components']);
514
+        }
515
+
516
+        $calendar = [
517
+            'id' => $row['id'],
518
+            'uri' => $row['uri'],
519
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
520
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
521
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
522
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
523
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
524
+        ];
525
+
526
+        foreach($this->propertyMap as $xmlName=>$dbName) {
527
+            $calendar[$xmlName] = $row[$dbName];
528
+        }
529
+
530
+        return $calendar;
531
+    }
532
+
533
+    public function getCalendarById($calendarId) {
534
+        $fields = array_values($this->propertyMap);
535
+        $fields[] = 'id';
536
+        $fields[] = 'uri';
537
+        $fields[] = 'synctoken';
538
+        $fields[] = 'components';
539
+        $fields[] = 'principaluri';
540
+        $fields[] = 'transparent';
541
+
542
+        // Making fields a comma-delimited list
543
+        $query = $this->db->getQueryBuilder();
544
+        $query->select($fields)->from('calendars')
545
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
546
+            ->setMaxResults(1);
547
+        $stmt = $query->execute();
548
+
549
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
550
+        $stmt->closeCursor();
551
+        if ($row === false) {
552
+            return null;
553
+        }
554
+
555
+        $components = [];
556
+        if ($row['components']) {
557
+            $components = explode(',',$row['components']);
558
+        }
559
+
560
+        $calendar = [
561
+            'id' => $row['id'],
562
+            'uri' => $row['uri'],
563
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
564
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
565
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
566
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
567
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
568
+        ];
569
+
570
+        foreach($this->propertyMap as $xmlName=>$dbName) {
571
+            $calendar[$xmlName] = $row[$dbName];
572
+        }
573
+
574
+        return $calendar;
575
+    }
576
+
577
+    /**
578
+     * Creates a new calendar for a principal.
579
+     *
580
+     * If the creation was a success, an id must be returned that can be used to reference
581
+     * this calendar in other methods, such as updateCalendar.
582
+     *
583
+     * @param string $principalUri
584
+     * @param string $calendarUri
585
+     * @param array $properties
586
+     * @return int
587
+     */
588
+    function createCalendar($principalUri, $calendarUri, array $properties) {
589
+        $values = [
590
+            'principaluri' => $this->convertPrincipal($principalUri, true),
591
+            'uri'          => $calendarUri,
592
+            'synctoken'    => 1,
593
+            'transparent'  => 0,
594
+            'components'   => 'VEVENT,VTODO',
595
+            'displayname'  => $calendarUri
596
+        ];
597
+
598
+        // Default value
599
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
600
+        if (isset($properties[$sccs])) {
601
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
602
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
603
+            }
604
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
605
+        }
606
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
607
+        if (isset($properties[$transp])) {
608
+            $values['transparent'] = $properties[$transp]->getValue()==='transparent';
609
+        }
610
+
611
+        foreach($this->propertyMap as $xmlName=>$dbName) {
612
+            if (isset($properties[$xmlName])) {
613
+                $values[$dbName] = $properties[$xmlName];
614
+            }
615
+        }
616
+
617
+        $query = $this->db->getQueryBuilder();
618
+        $query->insert('calendars');
619
+        foreach($values as $column => $value) {
620
+            $query->setValue($column, $query->createNamedParameter($value));
621
+        }
622
+        $query->execute();
623
+        $calendarId = $query->getLastInsertId();
624
+
625
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
626
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
627
+            [
628
+                'calendarId' => $calendarId,
629
+                'calendarData' => $this->getCalendarById($calendarId),
630
+        ]));
631
+
632
+        return $calendarId;
633
+    }
634
+
635
+    /**
636
+     * Updates properties for a calendar.
637
+     *
638
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
639
+     * To do the actual updates, you must tell this object which properties
640
+     * you're going to process with the handle() method.
641
+     *
642
+     * Calling the handle method is like telling the PropPatch object "I
643
+     * promise I can handle updating this property".
644
+     *
645
+     * Read the PropPatch documentation for more info and examples.
646
+     *
647
+     * @param PropPatch $propPatch
648
+     * @return void
649
+     */
650
+    function updateCalendar($calendarId, PropPatch $propPatch) {
651
+        $supportedProperties = array_keys($this->propertyMap);
652
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
653
+
654
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
655
+            $newValues = [];
656
+            foreach ($mutations as $propertyName => $propertyValue) {
657
+
658
+                switch ($propertyName) {
659
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
660
+                        $fieldName = 'transparent';
661
+                        $newValues[$fieldName] = $propertyValue->getValue() === 'transparent';
662
+                        break;
663
+                    default :
664
+                        $fieldName = $this->propertyMap[$propertyName];
665
+                        $newValues[$fieldName] = $propertyValue;
666
+                        break;
667
+                }
668
+
669
+            }
670
+            $query = $this->db->getQueryBuilder();
671
+            $query->update('calendars');
672
+            foreach ($newValues as $fieldName => $value) {
673
+                $query->set($fieldName, $query->createNamedParameter($value));
674
+            }
675
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
676
+            $query->execute();
677
+
678
+            $this->addChange($calendarId, "", 2);
679
+
680
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
681
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
682
+                [
683
+                    'calendarId' => $calendarId,
684
+                    'calendarData' => $this->getCalendarById($calendarId),
685
+                    'shares' => $this->getShares($calendarId),
686
+                    'propertyMutations' => $mutations,
687
+            ]));
688
+
689
+            return true;
690
+        });
691
+    }
692
+
693
+    /**
694
+     * Delete a calendar and all it's objects
695
+     *
696
+     * @param mixed $calendarId
697
+     * @return void
698
+     */
699
+    function deleteCalendar($calendarId) {
700
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
701
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
702
+            [
703
+                'calendarId' => $calendarId,
704
+                'calendarData' => $this->getCalendarById($calendarId),
705
+                'shares' => $this->getShares($calendarId),
706
+        ]));
707
+
708
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
709
+        $stmt->execute([$calendarId]);
710
+
711
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
712
+        $stmt->execute([$calendarId]);
713
+
714
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
715
+        $stmt->execute([$calendarId]);
716
+
717
+        $this->sharingBackend->deleteAllShares($calendarId);
718
+    }
719
+
720
+    /**
721
+     * Delete all of an user's shares
722
+     *
723
+     * @param string $principaluri
724
+     * @return void
725
+     */
726
+    function deleteAllSharesByUser($principaluri) {
727
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
728
+    }
729
+
730
+    /**
731
+     * Returns all calendar objects within a calendar.
732
+     *
733
+     * Every item contains an array with the following keys:
734
+     *   * calendardata - The iCalendar-compatible calendar data
735
+     *   * uri - a unique key which will be used to construct the uri. This can
736
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
737
+     *     good idea. This is only the basename, or filename, not the full
738
+     *     path.
739
+     *   * lastmodified - a timestamp of the last modification time
740
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
741
+     *   '"abcdef"')
742
+     *   * size - The size of the calendar objects, in bytes.
743
+     *   * component - optional, a string containing the type of object, such
744
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
745
+     *     the Content-Type header.
746
+     *
747
+     * Note that the etag is optional, but it's highly encouraged to return for
748
+     * speed reasons.
749
+     *
750
+     * The calendardata is also optional. If it's not returned
751
+     * 'getCalendarObject' will be called later, which *is* expected to return
752
+     * calendardata.
753
+     *
754
+     * If neither etag or size are specified, the calendardata will be
755
+     * used/fetched to determine these numbers. If both are specified the
756
+     * amount of times this is needed is reduced by a great degree.
757
+     *
758
+     * @param mixed $calendarId
759
+     * @return array
760
+     */
761
+    function getCalendarObjects($calendarId) {
762
+        $query = $this->db->getQueryBuilder();
763
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
764
+            ->from('calendarobjects')
765
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
766
+        $stmt = $query->execute();
767
+
768
+        $result = [];
769
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
770
+            $result[] = [
771
+                    'id'           => $row['id'],
772
+                    'uri'          => $row['uri'],
773
+                    'lastmodified' => $row['lastmodified'],
774
+                    'etag'         => '"' . $row['etag'] . '"',
775
+                    'calendarid'   => $row['calendarid'],
776
+                    'size'         => (int)$row['size'],
777
+                    'component'    => strtolower($row['componenttype']),
778
+                    'classification'=> (int)$row['classification']
779
+            ];
780
+        }
781
+
782
+        return $result;
783
+    }
784
+
785
+    /**
786
+     * Returns information from a single calendar object, based on it's object
787
+     * uri.
788
+     *
789
+     * The object uri is only the basename, or filename and not a full path.
790
+     *
791
+     * The returned array must have the same keys as getCalendarObjects. The
792
+     * 'calendardata' object is required here though, while it's not required
793
+     * for getCalendarObjects.
794
+     *
795
+     * This method must return null if the object did not exist.
796
+     *
797
+     * @param mixed $calendarId
798
+     * @param string $objectUri
799
+     * @return array|null
800
+     */
801
+    function getCalendarObject($calendarId, $objectUri) {
802
+
803
+        $query = $this->db->getQueryBuilder();
804
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
805
+                ->from('calendarobjects')
806
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
807
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
808
+        $stmt = $query->execute();
809
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
810
+
811
+        if(!$row) return null;
812
+
813
+        return [
814
+                'id'            => $row['id'],
815
+                'uri'           => $row['uri'],
816
+                'lastmodified'  => $row['lastmodified'],
817
+                'etag'          => '"' . $row['etag'] . '"',
818
+                'calendarid'    => $row['calendarid'],
819
+                'size'          => (int)$row['size'],
820
+                'calendardata'  => $this->readBlob($row['calendardata']),
821
+                'component'     => strtolower($row['componenttype']),
822
+                'classification'=> (int)$row['classification']
823
+        ];
824
+    }
825
+
826
+    /**
827
+     * Returns a list of calendar objects.
828
+     *
829
+     * This method should work identical to getCalendarObject, but instead
830
+     * return all the calendar objects in the list as an array.
831
+     *
832
+     * If the backend supports this, it may allow for some speed-ups.
833
+     *
834
+     * @param mixed $calendarId
835
+     * @param string[] $uris
836
+     * @return array
837
+     */
838
+    function getMultipleCalendarObjects($calendarId, array $uris) {
839
+        if (empty($uris)) {
840
+            return [];
841
+        }
842
+
843
+        $chunks = array_chunk($uris, 100);
844
+        $objects = [];
845
+
846
+        $query = $this->db->getQueryBuilder();
847
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
848
+            ->from('calendarobjects')
849
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
850
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
851
+
852
+        foreach ($chunks as $uris) {
853
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
854
+            $result = $query->execute();
855
+
856
+            while ($row = $result->fetch()) {
857
+                $objects[] = [
858
+                    'id'           => $row['id'],
859
+                    'uri'          => $row['uri'],
860
+                    'lastmodified' => $row['lastmodified'],
861
+                    'etag'         => '"' . $row['etag'] . '"',
862
+                    'calendarid'   => $row['calendarid'],
863
+                    'size'         => (int)$row['size'],
864
+                    'calendardata' => $this->readBlob($row['calendardata']),
865
+                    'component'    => strtolower($row['componenttype']),
866
+                    'classification' => (int)$row['classification']
867
+                ];
868
+            }
869
+            $result->closeCursor();
870
+        }
871
+        return $objects;
872
+    }
873
+
874
+    /**
875
+     * Creates a new calendar object.
876
+     *
877
+     * The object uri is only the basename, or filename and not a full path.
878
+     *
879
+     * It is possible return an etag from this function, which will be used in
880
+     * the response to this PUT request. Note that the ETag must be surrounded
881
+     * by double-quotes.
882
+     *
883
+     * However, you should only really return this ETag if you don't mangle the
884
+     * calendar-data. If the result of a subsequent GET to this object is not
885
+     * the exact same as this request body, you should omit the ETag.
886
+     *
887
+     * @param mixed $calendarId
888
+     * @param string $objectUri
889
+     * @param string $calendarData
890
+     * @return string
891
+     */
892
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
893
+        $extraData = $this->getDenormalizedData($calendarData);
894
+
895
+        $query = $this->db->getQueryBuilder();
896
+        $query->insert('calendarobjects')
897
+            ->values([
898
+                'calendarid' => $query->createNamedParameter($calendarId),
899
+                'uri' => $query->createNamedParameter($objectUri),
900
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
901
+                'lastmodified' => $query->createNamedParameter(time()),
902
+                'etag' => $query->createNamedParameter($extraData['etag']),
903
+                'size' => $query->createNamedParameter($extraData['size']),
904
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
905
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
906
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
907
+                'classification' => $query->createNamedParameter($extraData['classification']),
908
+                'uid' => $query->createNamedParameter($extraData['uid']),
909
+            ])
910
+            ->execute();
911
+
912
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
913
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
914
+            [
915
+                'calendarId' => $calendarId,
916
+                'calendarData' => $this->getCalendarById($calendarId),
917
+                'shares' => $this->getShares($calendarId),
918
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
919
+            ]
920
+        ));
921
+        $this->addChange($calendarId, $objectUri, 1);
922
+
923
+        return '"' . $extraData['etag'] . '"';
924
+    }
925
+
926
+    /**
927
+     * Updates an existing calendarobject, based on it's uri.
928
+     *
929
+     * The object uri is only the basename, or filename and not a full path.
930
+     *
931
+     * It is possible return an etag from this function, which will be used in
932
+     * the response to this PUT request. Note that the ETag must be surrounded
933
+     * by double-quotes.
934
+     *
935
+     * However, you should only really return this ETag if you don't mangle the
936
+     * calendar-data. If the result of a subsequent GET to this object is not
937
+     * the exact same as this request body, you should omit the ETag.
938
+     *
939
+     * @param mixed $calendarId
940
+     * @param string $objectUri
941
+     * @param string $calendarData
942
+     * @return string
943
+     */
944
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
945
+        $extraData = $this->getDenormalizedData($calendarData);
946
+
947
+        $query = $this->db->getQueryBuilder();
948
+        $query->update('calendarobjects')
949
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
950
+                ->set('lastmodified', $query->createNamedParameter(time()))
951
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
952
+                ->set('size', $query->createNamedParameter($extraData['size']))
953
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
954
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
955
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
956
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
957
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
958
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
959
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
960
+            ->execute();
961
+
962
+        $data = $this->getCalendarObject($calendarId, $objectUri);
963
+        if (is_array($data)) {
964
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
965
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
966
+                [
967
+                    'calendarId' => $calendarId,
968
+                    'calendarData' => $this->getCalendarById($calendarId),
969
+                    'shares' => $this->getShares($calendarId),
970
+                    'objectData' => $data,
971
+                ]
972
+            ));
973
+        }
974
+        $this->addChange($calendarId, $objectUri, 2);
975
+
976
+        return '"' . $extraData['etag'] . '"';
977
+    }
978
+
979
+    /**
980
+     * @param int $calendarObjectId
981
+     * @param int $classification
982
+     */
983
+    public function setClassification($calendarObjectId, $classification) {
984
+        if (!in_array($classification, [
985
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
986
+        ])) {
987
+            throw new \InvalidArgumentException();
988
+        }
989
+        $query = $this->db->getQueryBuilder();
990
+        $query->update('calendarobjects')
991
+            ->set('classification', $query->createNamedParameter($classification))
992
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
993
+            ->execute();
994
+    }
995
+
996
+    /**
997
+     * Deletes an existing calendar object.
998
+     *
999
+     * The object uri is only the basename, or filename and not a full path.
1000
+     *
1001
+     * @param mixed $calendarId
1002
+     * @param string $objectUri
1003
+     * @return void
1004
+     */
1005
+    function deleteCalendarObject($calendarId, $objectUri) {
1006
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1007
+        if (is_array($data)) {
1008
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1009
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1010
+                [
1011
+                    'calendarId' => $calendarId,
1012
+                    'calendarData' => $this->getCalendarById($calendarId),
1013
+                    'shares' => $this->getShares($calendarId),
1014
+                    'objectData' => $data,
1015
+                ]
1016
+            ));
1017
+        }
1018
+
1019
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1020
+        $stmt->execute([$calendarId, $objectUri]);
1021
+
1022
+        $this->addChange($calendarId, $objectUri, 3);
1023
+    }
1024
+
1025
+    /**
1026
+     * Performs a calendar-query on the contents of this calendar.
1027
+     *
1028
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1029
+     * calendar-query it is possible for a client to request a specific set of
1030
+     * object, based on contents of iCalendar properties, date-ranges and
1031
+     * iCalendar component types (VTODO, VEVENT).
1032
+     *
1033
+     * This method should just return a list of (relative) urls that match this
1034
+     * query.
1035
+     *
1036
+     * The list of filters are specified as an array. The exact array is
1037
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1038
+     *
1039
+     * Note that it is extremely likely that getCalendarObject for every path
1040
+     * returned from this method will be called almost immediately after. You
1041
+     * may want to anticipate this to speed up these requests.
1042
+     *
1043
+     * This method provides a default implementation, which parses *all* the
1044
+     * iCalendar objects in the specified calendar.
1045
+     *
1046
+     * This default may well be good enough for personal use, and calendars
1047
+     * that aren't very large. But if you anticipate high usage, big calendars
1048
+     * or high loads, you are strongly advised to optimize certain paths.
1049
+     *
1050
+     * The best way to do so is override this method and to optimize
1051
+     * specifically for 'common filters'.
1052
+     *
1053
+     * Requests that are extremely common are:
1054
+     *   * requests for just VEVENTS
1055
+     *   * requests for just VTODO
1056
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1057
+     *
1058
+     * ..and combinations of these requests. It may not be worth it to try to
1059
+     * handle every possible situation and just rely on the (relatively
1060
+     * easy to use) CalendarQueryValidator to handle the rest.
1061
+     *
1062
+     * Note that especially time-range-filters may be difficult to parse. A
1063
+     * time-range filter specified on a VEVENT must for instance also handle
1064
+     * recurrence rules correctly.
1065
+     * A good example of how to interprete all these filters can also simply
1066
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1067
+     * as possible, so it gives you a good idea on what type of stuff you need
1068
+     * to think of.
1069
+     *
1070
+     * @param mixed $calendarId
1071
+     * @param array $filters
1072
+     * @return array
1073
+     */
1074
+    function calendarQuery($calendarId, array $filters) {
1075
+        $componentType = null;
1076
+        $requirePostFilter = true;
1077
+        $timeRange = null;
1078
+
1079
+        // if no filters were specified, we don't need to filter after a query
1080
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1081
+            $requirePostFilter = false;
1082
+        }
1083
+
1084
+        // Figuring out if there's a component filter
1085
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1086
+            $componentType = $filters['comp-filters'][0]['name'];
1087
+
1088
+            // Checking if we need post-filters
1089
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1090
+                $requirePostFilter = false;
1091
+            }
1092
+            // There was a time-range filter
1093
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1094
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1095
+
1096
+                // If start time OR the end time is not specified, we can do a
1097
+                // 100% accurate mysql query.
1098
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1099
+                    $requirePostFilter = false;
1100
+                }
1101
+            }
1102
+
1103
+        }
1104
+        $columns = ['uri'];
1105
+        if ($requirePostFilter) {
1106
+            $columns = ['uri', 'calendardata'];
1107
+        }
1108
+        $query = $this->db->getQueryBuilder();
1109
+        $query->select($columns)
1110
+            ->from('calendarobjects')
1111
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1112
+
1113
+        if ($componentType) {
1114
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1115
+        }
1116
+
1117
+        if ($timeRange && $timeRange['start']) {
1118
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1119
+        }
1120
+        if ($timeRange && $timeRange['end']) {
1121
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1122
+        }
1123
+
1124
+        $stmt = $query->execute();
1125
+
1126
+        $result = [];
1127
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1128
+            if ($requirePostFilter) {
1129
+                if (!$this->validateFilterForObject($row, $filters)) {
1130
+                    continue;
1131
+                }
1132
+            }
1133
+            $result[] = $row['uri'];
1134
+        }
1135
+
1136
+        return $result;
1137
+    }
1138
+
1139
+    /**
1140
+     * Searches through all of a users calendars and calendar objects to find
1141
+     * an object with a specific UID.
1142
+     *
1143
+     * This method should return the path to this object, relative to the
1144
+     * calendar home, so this path usually only contains two parts:
1145
+     *
1146
+     * calendarpath/objectpath.ics
1147
+     *
1148
+     * If the uid is not found, return null.
1149
+     *
1150
+     * This method should only consider * objects that the principal owns, so
1151
+     * any calendars owned by other principals that also appear in this
1152
+     * collection should be ignored.
1153
+     *
1154
+     * @param string $principalUri
1155
+     * @param string $uid
1156
+     * @return string|null
1157
+     */
1158
+    function getCalendarObjectByUID($principalUri, $uid) {
1159
+
1160
+        $query = $this->db->getQueryBuilder();
1161
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1162
+            ->from('calendarobjects', 'co')
1163
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1164
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1165
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1166
+
1167
+        $stmt = $query->execute();
1168
+
1169
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1170
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1171
+        }
1172
+
1173
+        return null;
1174
+    }
1175
+
1176
+    /**
1177
+     * The getChanges method returns all the changes that have happened, since
1178
+     * the specified syncToken in the specified calendar.
1179
+     *
1180
+     * This function should return an array, such as the following:
1181
+     *
1182
+     * [
1183
+     *   'syncToken' => 'The current synctoken',
1184
+     *   'added'   => [
1185
+     *      'new.txt',
1186
+     *   ],
1187
+     *   'modified'   => [
1188
+     *      'modified.txt',
1189
+     *   ],
1190
+     *   'deleted' => [
1191
+     *      'foo.php.bak',
1192
+     *      'old.txt'
1193
+     *   ]
1194
+     * );
1195
+     *
1196
+     * The returned syncToken property should reflect the *current* syncToken
1197
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1198
+     * property This is * needed here too, to ensure the operation is atomic.
1199
+     *
1200
+     * If the $syncToken argument is specified as null, this is an initial
1201
+     * sync, and all members should be reported.
1202
+     *
1203
+     * The modified property is an array of nodenames that have changed since
1204
+     * the last token.
1205
+     *
1206
+     * The deleted property is an array with nodenames, that have been deleted
1207
+     * from collection.
1208
+     *
1209
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1210
+     * 1, you only have to report changes that happened only directly in
1211
+     * immediate descendants. If it's 2, it should also include changes from
1212
+     * the nodes below the child collections. (grandchildren)
1213
+     *
1214
+     * The $limit argument allows a client to specify how many results should
1215
+     * be returned at most. If the limit is not specified, it should be treated
1216
+     * as infinite.
1217
+     *
1218
+     * If the limit (infinite or not) is higher than you're willing to return,
1219
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1220
+     *
1221
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1222
+     * return null.
1223
+     *
1224
+     * The limit is 'suggestive'. You are free to ignore it.
1225
+     *
1226
+     * @param string $calendarId
1227
+     * @param string $syncToken
1228
+     * @param int $syncLevel
1229
+     * @param int $limit
1230
+     * @return array
1231
+     */
1232
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1233
+        // Current synctoken
1234
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1235
+        $stmt->execute([ $calendarId ]);
1236
+        $currentToken = $stmt->fetchColumn(0);
1237
+
1238
+        if (is_null($currentToken)) {
1239
+            return null;
1240
+        }
1241
+
1242
+        $result = [
1243
+            'syncToken' => $currentToken,
1244
+            'added'     => [],
1245
+            'modified'  => [],
1246
+            'deleted'   => [],
1247
+        ];
1248
+
1249
+        if ($syncToken) {
1250
+
1251
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1252
+            if ($limit>0) {
1253
+                $query.= " `LIMIT` " . (int)$limit;
1254
+            }
1255
+
1256
+            // Fetching all changes
1257
+            $stmt = $this->db->prepare($query);
1258
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1259
+
1260
+            $changes = [];
1261
+
1262
+            // This loop ensures that any duplicates are overwritten, only the
1263
+            // last change on a node is relevant.
1264
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1265
+
1266
+                $changes[$row['uri']] = $row['operation'];
1267
+
1268
+            }
1269
+
1270
+            foreach($changes as $uri => $operation) {
1271
+
1272
+                switch($operation) {
1273
+                    case 1 :
1274
+                        $result['added'][] = $uri;
1275
+                        break;
1276
+                    case 2 :
1277
+                        $result['modified'][] = $uri;
1278
+                        break;
1279
+                    case 3 :
1280
+                        $result['deleted'][] = $uri;
1281
+                        break;
1282
+                }
1283
+
1284
+            }
1285
+        } else {
1286
+            // No synctoken supplied, this is the initial sync.
1287
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1288
+            $stmt = $this->db->prepare($query);
1289
+            $stmt->execute([$calendarId]);
1290
+
1291
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1292
+        }
1293
+        return $result;
1294
+
1295
+    }
1296
+
1297
+    /**
1298
+     * Returns a list of subscriptions for a principal.
1299
+     *
1300
+     * Every subscription is an array with the following keys:
1301
+     *  * id, a unique id that will be used by other functions to modify the
1302
+     *    subscription. This can be the same as the uri or a database key.
1303
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1304
+     *  * principaluri. The owner of the subscription. Almost always the same as
1305
+     *    principalUri passed to this method.
1306
+     *
1307
+     * Furthermore, all the subscription info must be returned too:
1308
+     *
1309
+     * 1. {DAV:}displayname
1310
+     * 2. {http://apple.com/ns/ical/}refreshrate
1311
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1312
+     *    should not be stripped).
1313
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1314
+     *    should not be stripped).
1315
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1316
+     *    attachments should not be stripped).
1317
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1318
+     *     Sabre\DAV\Property\Href).
1319
+     * 7. {http://apple.com/ns/ical/}calendar-color
1320
+     * 8. {http://apple.com/ns/ical/}calendar-order
1321
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1322
+     *    (should just be an instance of
1323
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1324
+     *    default components).
1325
+     *
1326
+     * @param string $principalUri
1327
+     * @return array
1328
+     */
1329
+    function getSubscriptionsForUser($principalUri) {
1330
+        $fields = array_values($this->subscriptionPropertyMap);
1331
+        $fields[] = 'id';
1332
+        $fields[] = 'uri';
1333
+        $fields[] = 'source';
1334
+        $fields[] = 'principaluri';
1335
+        $fields[] = 'lastmodified';
1336
+
1337
+        $query = $this->db->getQueryBuilder();
1338
+        $query->select($fields)
1339
+            ->from('calendarsubscriptions')
1340
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1341
+            ->orderBy('calendarorder', 'asc');
1342
+        $stmt =$query->execute();
1343
+
1344
+        $subscriptions = [];
1345
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1346
+
1347
+            $subscription = [
1348
+                'id'           => $row['id'],
1349
+                'uri'          => $row['uri'],
1350
+                'principaluri' => $row['principaluri'],
1351
+                'source'       => $row['source'],
1352
+                'lastmodified' => $row['lastmodified'],
1353
+
1354
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1355
+            ];
1356
+
1357
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1358
+                if (!is_null($row[$dbName])) {
1359
+                    $subscription[$xmlName] = $row[$dbName];
1360
+                }
1361
+            }
1362
+
1363
+            $subscriptions[] = $subscription;
1364
+
1365
+        }
1366
+
1367
+        return $subscriptions;
1368
+    }
1369
+
1370
+    /**
1371
+     * Creates a new subscription for a principal.
1372
+     *
1373
+     * If the creation was a success, an id must be returned that can be used to reference
1374
+     * this subscription in other methods, such as updateSubscription.
1375
+     *
1376
+     * @param string $principalUri
1377
+     * @param string $uri
1378
+     * @param array $properties
1379
+     * @return mixed
1380
+     */
1381
+    function createSubscription($principalUri, $uri, array $properties) {
1382
+
1383
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1384
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1385
+        }
1386
+
1387
+        $values = [
1388
+            'principaluri' => $principalUri,
1389
+            'uri'          => $uri,
1390
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1391
+            'lastmodified' => time(),
1392
+        ];
1393
+
1394
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1395
+
1396
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1397
+            if (array_key_exists($xmlName, $properties)) {
1398
+                    $values[$dbName] = $properties[$xmlName];
1399
+                    if (in_array($dbName, $propertiesBoolean)) {
1400
+                        $values[$dbName] = true;
1401
+                }
1402
+            }
1403
+        }
1404
+
1405
+        $valuesToInsert = array();
1406
+
1407
+        $query = $this->db->getQueryBuilder();
1408
+
1409
+        foreach (array_keys($values) as $name) {
1410
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1411
+        }
1412
+
1413
+        $query->insert('calendarsubscriptions')
1414
+            ->values($valuesToInsert)
1415
+            ->execute();
1416
+
1417
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1418
+    }
1419
+
1420
+    /**
1421
+     * Updates a subscription
1422
+     *
1423
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1424
+     * To do the actual updates, you must tell this object which properties
1425
+     * you're going to process with the handle() method.
1426
+     *
1427
+     * Calling the handle method is like telling the PropPatch object "I
1428
+     * promise I can handle updating this property".
1429
+     *
1430
+     * Read the PropPatch documentation for more info and examples.
1431
+     *
1432
+     * @param mixed $subscriptionId
1433
+     * @param PropPatch $propPatch
1434
+     * @return void
1435
+     */
1436
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1437
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1438
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1439
+
1440
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1441
+
1442
+            $newValues = [];
1443
+
1444
+            foreach($mutations as $propertyName=>$propertyValue) {
1445
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1446
+                    $newValues['source'] = $propertyValue->getHref();
1447
+                } else {
1448
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1449
+                    $newValues[$fieldName] = $propertyValue;
1450
+                }
1451
+            }
1452
+
1453
+            $query = $this->db->getQueryBuilder();
1454
+            $query->update('calendarsubscriptions')
1455
+                ->set('lastmodified', $query->createNamedParameter(time()));
1456
+            foreach($newValues as $fieldName=>$value) {
1457
+                $query->set($fieldName, $query->createNamedParameter($value));
1458
+            }
1459
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1460
+                ->execute();
1461
+
1462
+            return true;
1463
+
1464
+        });
1465
+    }
1466
+
1467
+    /**
1468
+     * Deletes a subscription.
1469
+     *
1470
+     * @param mixed $subscriptionId
1471
+     * @return void
1472
+     */
1473
+    function deleteSubscription($subscriptionId) {
1474
+        $query = $this->db->getQueryBuilder();
1475
+        $query->delete('calendarsubscriptions')
1476
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1477
+            ->execute();
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns a single scheduling object for the inbox collection.
1482
+     *
1483
+     * The returned array should contain the following elements:
1484
+     *   * uri - A unique basename for the object. This will be used to
1485
+     *           construct a full uri.
1486
+     *   * calendardata - The iCalendar object
1487
+     *   * lastmodified - The last modification date. Can be an int for a unix
1488
+     *                    timestamp, or a PHP DateTime object.
1489
+     *   * etag - A unique token that must change if the object changed.
1490
+     *   * size - The size of the object, in bytes.
1491
+     *
1492
+     * @param string $principalUri
1493
+     * @param string $objectUri
1494
+     * @return array
1495
+     */
1496
+    function getSchedulingObject($principalUri, $objectUri) {
1497
+        $query = $this->db->getQueryBuilder();
1498
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1499
+            ->from('schedulingobjects')
1500
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1501
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1502
+            ->execute();
1503
+
1504
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1505
+
1506
+        if(!$row) {
1507
+            return null;
1508
+        }
1509
+
1510
+        return [
1511
+                'uri'          => $row['uri'],
1512
+                'calendardata' => $row['calendardata'],
1513
+                'lastmodified' => $row['lastmodified'],
1514
+                'etag'         => '"' . $row['etag'] . '"',
1515
+                'size'         => (int)$row['size'],
1516
+        ];
1517
+    }
1518
+
1519
+    /**
1520
+     * Returns all scheduling objects for the inbox collection.
1521
+     *
1522
+     * These objects should be returned as an array. Every item in the array
1523
+     * should follow the same structure as returned from getSchedulingObject.
1524
+     *
1525
+     * The main difference is that 'calendardata' is optional.
1526
+     *
1527
+     * @param string $principalUri
1528
+     * @return array
1529
+     */
1530
+    function getSchedulingObjects($principalUri) {
1531
+        $query = $this->db->getQueryBuilder();
1532
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1533
+                ->from('schedulingobjects')
1534
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1535
+                ->execute();
1536
+
1537
+        $result = [];
1538
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1539
+            $result[] = [
1540
+                    'calendardata' => $row['calendardata'],
1541
+                    'uri'          => $row['uri'],
1542
+                    'lastmodified' => $row['lastmodified'],
1543
+                    'etag'         => '"' . $row['etag'] . '"',
1544
+                    'size'         => (int)$row['size'],
1545
+            ];
1546
+        }
1547
+
1548
+        return $result;
1549
+    }
1550
+
1551
+    /**
1552
+     * Deletes a scheduling object from the inbox collection.
1553
+     *
1554
+     * @param string $principalUri
1555
+     * @param string $objectUri
1556
+     * @return void
1557
+     */
1558
+    function deleteSchedulingObject($principalUri, $objectUri) {
1559
+        $query = $this->db->getQueryBuilder();
1560
+        $query->delete('schedulingobjects')
1561
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1562
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1563
+                ->execute();
1564
+    }
1565
+
1566
+    /**
1567
+     * Creates a new scheduling object. This should land in a users' inbox.
1568
+     *
1569
+     * @param string $principalUri
1570
+     * @param string $objectUri
1571
+     * @param string $objectData
1572
+     * @return void
1573
+     */
1574
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1575
+        $query = $this->db->getQueryBuilder();
1576
+        $query->insert('schedulingobjects')
1577
+            ->values([
1578
+                'principaluri' => $query->createNamedParameter($principalUri),
1579
+                'calendardata' => $query->createNamedParameter($objectData),
1580
+                'uri' => $query->createNamedParameter($objectUri),
1581
+                'lastmodified' => $query->createNamedParameter(time()),
1582
+                'etag' => $query->createNamedParameter(md5($objectData)),
1583
+                'size' => $query->createNamedParameter(strlen($objectData))
1584
+            ])
1585
+            ->execute();
1586
+    }
1587
+
1588
+    /**
1589
+     * Adds a change record to the calendarchanges table.
1590
+     *
1591
+     * @param mixed $calendarId
1592
+     * @param string $objectUri
1593
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1594
+     * @return void
1595
+     */
1596
+    protected function addChange($calendarId, $objectUri, $operation) {
1597
+
1598
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1599
+        $stmt->execute([
1600
+            $objectUri,
1601
+            $calendarId,
1602
+            $operation,
1603
+            $calendarId
1604
+        ]);
1605
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1606
+        $stmt->execute([
1607
+            $calendarId
1608
+        ]);
1609
+
1610
+    }
1611
+
1612
+    /**
1613
+     * Parses some information from calendar objects, used for optimized
1614
+     * calendar-queries.
1615
+     *
1616
+     * Returns an array with the following keys:
1617
+     *   * etag - An md5 checksum of the object without the quotes.
1618
+     *   * size - Size of the object in bytes
1619
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1620
+     *   * firstOccurence
1621
+     *   * lastOccurence
1622
+     *   * uid - value of the UID property
1623
+     *
1624
+     * @param string $calendarData
1625
+     * @return array
1626
+     */
1627
+    public function getDenormalizedData($calendarData) {
1628
+
1629
+        $vObject = Reader::read($calendarData);
1630
+        $componentType = null;
1631
+        $component = null;
1632
+        $firstOccurrence = null;
1633
+        $lastOccurrence = null;
1634
+        $uid = null;
1635
+        $classification = self::CLASSIFICATION_PUBLIC;
1636
+        foreach($vObject->getComponents() as $component) {
1637
+            if ($component->name!=='VTIMEZONE') {
1638
+                $componentType = $component->name;
1639
+                $uid = (string)$component->UID;
1640
+                break;
1641
+            }
1642
+        }
1643
+        if (!$componentType) {
1644
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1645
+        }
1646
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1647
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1648
+            // Finding the last occurrence is a bit harder
1649
+            if (!isset($component->RRULE)) {
1650
+                if (isset($component->DTEND)) {
1651
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1652
+                } elseif (isset($component->DURATION)) {
1653
+                    $endDate = clone $component->DTSTART->getDateTime();
1654
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1655
+                    $lastOccurrence = $endDate->getTimeStamp();
1656
+                } elseif (!$component->DTSTART->hasTime()) {
1657
+                    $endDate = clone $component->DTSTART->getDateTime();
1658
+                    $endDate->modify('+1 day');
1659
+                    $lastOccurrence = $endDate->getTimeStamp();
1660
+                } else {
1661
+                    $lastOccurrence = $firstOccurrence;
1662
+                }
1663
+            } else {
1664
+                $it = new EventIterator($vObject, (string)$component->UID);
1665
+                $maxDate = new \DateTime(self::MAX_DATE);
1666
+                if ($it->isInfinite()) {
1667
+                    $lastOccurrence = $maxDate->getTimestamp();
1668
+                } else {
1669
+                    $end = $it->getDtEnd();
1670
+                    while($it->valid() && $end < $maxDate) {
1671
+                        $end = $it->getDtEnd();
1672
+                        $it->next();
1673
+
1674
+                    }
1675
+                    $lastOccurrence = $end->getTimestamp();
1676
+                }
1677
+
1678
+            }
1679
+        }
1680
+
1681
+        if ($component->CLASS) {
1682
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1683
+            switch ($component->CLASS->getValue()) {
1684
+                case 'PUBLIC':
1685
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1686
+                    break;
1687
+                case 'CONFIDENTIAL':
1688
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1689
+                    break;
1690
+            }
1691
+        }
1692
+        return [
1693
+            'etag' => md5($calendarData),
1694
+            'size' => strlen($calendarData),
1695
+            'componentType' => $componentType,
1696
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1697
+            'lastOccurence'  => $lastOccurrence,
1698
+            'uid' => $uid,
1699
+            'classification' => $classification
1700
+        ];
1701
+
1702
+    }
1703
+
1704
+    private function readBlob($cardData) {
1705
+        if (is_resource($cardData)) {
1706
+            return stream_get_contents($cardData);
1707
+        }
1708
+
1709
+        return $cardData;
1710
+    }
1711
+
1712
+    /**
1713
+     * @param IShareable $shareable
1714
+     * @param array $add
1715
+     * @param array $remove
1716
+     */
1717
+    public function updateShares($shareable, $add, $remove) {
1718
+        $calendarId = $shareable->getResourceId();
1719
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1720
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1721
+            [
1722
+                'calendarId' => $calendarId,
1723
+                'calendarData' => $this->getCalendarById($calendarId),
1724
+                'shares' => $this->getShares($calendarId),
1725
+                'add' => $add,
1726
+                'remove' => $remove,
1727
+            ]));
1728
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1729
+    }
1730
+
1731
+    /**
1732
+     * @param int $resourceId
1733
+     * @return array
1734
+     */
1735
+    public function getShares($resourceId) {
1736
+        return $this->sharingBackend->getShares($resourceId);
1737
+    }
1738
+
1739
+    /**
1740
+     * @param boolean $value
1741
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1742
+     * @return string|null
1743
+     */
1744
+    public function setPublishStatus($value, $calendar) {
1745
+        $query = $this->db->getQueryBuilder();
1746
+        if ($value) {
1747
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1748
+            $query->insert('dav_shares')
1749
+                ->values([
1750
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1751
+                    'type' => $query->createNamedParameter('calendar'),
1752
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1753
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1754
+                    'publicuri' => $query->createNamedParameter($publicUri)
1755
+                ]);
1756
+            $query->execute();
1757
+            return $publicUri;
1758
+        }
1759
+        $query->delete('dav_shares')
1760
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1761
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1762
+        $query->execute();
1763
+        return null;
1764
+    }
1765
+
1766
+    /**
1767
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1768
+     * @return mixed
1769
+     */
1770
+    public function getPublishStatus($calendar) {
1771
+        $query = $this->db->getQueryBuilder();
1772
+        $result = $query->select('publicuri')
1773
+            ->from('dav_shares')
1774
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1775
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1776
+            ->execute();
1777
+
1778
+        $row = $result->fetch();
1779
+        $result->closeCursor();
1780
+        return $row ? reset($row) : false;
1781
+    }
1782
+
1783
+    /**
1784
+     * @param int $resourceId
1785
+     * @param array $acl
1786
+     * @return array
1787
+     */
1788
+    public function applyShareAcl($resourceId, $acl) {
1789
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1790
+    }
1791
+
1792
+    private function convertPrincipal($principalUri, $toV2) {
1793
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1794
+            list(, $name) = URLUtil::splitPath($principalUri);
1795
+            if ($toV2 === true) {
1796
+                return "principals/users/$name";
1797
+            }
1798
+            return "principals/$name";
1799
+        }
1800
+        return $principalUri;
1801
+    }
1802 1802
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Plugin.php 1 patch
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.
apps/dav/lib/CalDAV/CalendarObject.php 1 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
-	private function isShared() {
47
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
48
-			return false;
49
-		}
46
+    private 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/BirthdayService.php 1 patch
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -39,256 +39,256 @@
 block discarded – undo
39 39
 
40 40
 class BirthdayService {
41 41
 
42
-	const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';
42
+    const BIRTHDAY_CALENDAR_URI = 'contact_birthdays';
43 43
 
44
-	/** @var GroupPrincipalBackend */
45
-	private $principalBackend;
44
+    /** @var GroupPrincipalBackend */
45
+    private $principalBackend;
46 46
 
47
-	/** @var CalDavBackend  */
48
-	private $calDavBackEnd;
47
+    /** @var CalDavBackend  */
48
+    private $calDavBackEnd;
49 49
 
50
-	/** @var CardDavBackend  */
51
-	private $cardDavBackEnd;
50
+    /** @var CardDavBackend  */
51
+    private $cardDavBackEnd;
52 52
 
53
-	/**
54
-	 * BirthdayService constructor.
55
-	 *
56
-	 * @param CalDavBackend $calDavBackEnd
57
-	 * @param CardDavBackend $cardDavBackEnd
58
-	 * @param GroupPrincipalBackend $principalBackend
59
-	 */
60
-	public function __construct(CalDavBackend $calDavBackEnd, CardDavBackend $cardDavBackEnd, GroupPrincipalBackend $principalBackend) {
61
-		$this->calDavBackEnd = $calDavBackEnd;
62
-		$this->cardDavBackEnd = $cardDavBackEnd;
63
-		$this->principalBackend = $principalBackend;
64
-	}
53
+    /**
54
+     * BirthdayService constructor.
55
+     *
56
+     * @param CalDavBackend $calDavBackEnd
57
+     * @param CardDavBackend $cardDavBackEnd
58
+     * @param GroupPrincipalBackend $principalBackend
59
+     */
60
+    public function __construct(CalDavBackend $calDavBackEnd, CardDavBackend $cardDavBackEnd, GroupPrincipalBackend $principalBackend) {
61
+        $this->calDavBackEnd = $calDavBackEnd;
62
+        $this->cardDavBackEnd = $cardDavBackEnd;
63
+        $this->principalBackend = $principalBackend;
64
+    }
65 65
 
66
-	/**
67
-	 * @param int $addressBookId
68
-	 * @param string $cardUri
69
-	 * @param string $cardData
70
-	 */
71
-	public function onCardChanged($addressBookId, $cardUri, $cardData) {
72
-		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
66
+    /**
67
+     * @param int $addressBookId
68
+     * @param string $cardUri
69
+     * @param string $cardData
70
+     */
71
+    public function onCardChanged($addressBookId, $cardUri, $cardData) {
72
+        $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
73 73
 		
74
-		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
75
-		$targetPrincipals[] = $book['principaluri'];
76
-		$datesToSync = [
77
-			['postfix' => '', 'field' => 'BDAY', 'symbol' => '*'],
78
-			['postfix' => '-death', 'field' => 'DEATHDATE', 'symbol' => "†"],
79
-			['postfix' => '-anniversary', 'field' => 'ANNIVERSARY', 'symbol' => "⚭"],
80
-		];
81
-		foreach ($targetPrincipals as $principalUri) {
82
-			$calendar = $this->ensureCalendarExists($principalUri);
83
-			foreach ($datesToSync as $type) {
84
-				$this->updateCalendar($cardUri, $cardData, $book, $calendar['id'], $type);
85
-			}
86
-		}
87
-	}
74
+        $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
75
+        $targetPrincipals[] = $book['principaluri'];
76
+        $datesToSync = [
77
+            ['postfix' => '', 'field' => 'BDAY', 'symbol' => '*'],
78
+            ['postfix' => '-death', 'field' => 'DEATHDATE', 'symbol' => "†"],
79
+            ['postfix' => '-anniversary', 'field' => 'ANNIVERSARY', 'symbol' => "⚭"],
80
+        ];
81
+        foreach ($targetPrincipals as $principalUri) {
82
+            $calendar = $this->ensureCalendarExists($principalUri);
83
+            foreach ($datesToSync as $type) {
84
+                $this->updateCalendar($cardUri, $cardData, $book, $calendar['id'], $type);
85
+            }
86
+        }
87
+    }
88 88
 
89
-	/**
90
-	 * @param int $addressBookId
91
-	 * @param string $cardUri
92
-	 */
93
-	public function onCardDeleted($addressBookId, $cardUri) {
94
-		$targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
95
-		$book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
96
-		$targetPrincipals[] = $book['principaluri'];
97
-		foreach ($targetPrincipals as $principalUri) {
98
-			$calendar = $this->ensureCalendarExists($principalUri);
99
-			foreach (['', '-death', '-anniversary'] as $tag) {
100
-				$objectUri = $book['uri'] . '-' . $cardUri . $tag .'.ics';
101
-				$this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri);
102
-			}
103
-		}
104
-	}
89
+    /**
90
+     * @param int $addressBookId
91
+     * @param string $cardUri
92
+     */
93
+    public function onCardDeleted($addressBookId, $cardUri) {
94
+        $targetPrincipals = $this->getAllAffectedPrincipals($addressBookId);
95
+        $book = $this->cardDavBackEnd->getAddressBookById($addressBookId);
96
+        $targetPrincipals[] = $book['principaluri'];
97
+        foreach ($targetPrincipals as $principalUri) {
98
+            $calendar = $this->ensureCalendarExists($principalUri);
99
+            foreach (['', '-death', '-anniversary'] as $tag) {
100
+                $objectUri = $book['uri'] . '-' . $cardUri . $tag .'.ics';
101
+                $this->calDavBackEnd->deleteCalendarObject($calendar['id'], $objectUri);
102
+            }
103
+        }
104
+    }
105 105
 
106
-	/**
107
-	 * @param string $principal
108
-	 * @return array|null
109
-	 * @throws \Sabre\DAV\Exception\BadRequest
110
-	 */
111
-	public function ensureCalendarExists($principal) {
112
-		$book = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
113
-		if (!is_null($book)) {
114
-			return $book;
115
-		}
116
-		$this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
117
-			'{DAV:}displayname' => 'Contact birthdays',
118
-			'{http://apple.com/ns/ical/}calendar-color' => '#FFFFCA',
119
-			'components'   => 'VEVENT',
120
-		]);
106
+    /**
107
+     * @param string $principal
108
+     * @return array|null
109
+     * @throws \Sabre\DAV\Exception\BadRequest
110
+     */
111
+    public function ensureCalendarExists($principal) {
112
+        $book = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
113
+        if (!is_null($book)) {
114
+            return $book;
115
+        }
116
+        $this->calDavBackEnd->createCalendar($principal, self::BIRTHDAY_CALENDAR_URI, [
117
+            '{DAV:}displayname' => 'Contact birthdays',
118
+            '{http://apple.com/ns/ical/}calendar-color' => '#FFFFCA',
119
+            'components'   => 'VEVENT',
120
+        ]);
121 121
 
122
-		return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
123
-	}
122
+        return $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI);
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $cardData
127
-	 * @param string $dateField
128
-	 * @param string $summarySymbol
129
-	 * @return null|VCalendar
130
-	 */
131
-	public function buildDateFromContact($cardData, $dateField, $summarySymbol) {
132
-		if (empty($cardData)) {
133
-			return null;
134
-		}
135
-		try {
136
-			$doc = Reader::read($cardData);
137
-			// We're always converting to vCard 4.0 so we can rely on the
138
-			// VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
139
-			if (!$doc instanceof VCard) {
140
-				return null;
141
-			}
142
-			$doc = $doc->convert(Document::VCARD40);
143
-		} catch (Exception $e) {
144
-			return null;
145
-		}
125
+    /**
126
+     * @param string $cardData
127
+     * @param string $dateField
128
+     * @param string $summarySymbol
129
+     * @return null|VCalendar
130
+     */
131
+    public function buildDateFromContact($cardData, $dateField, $summarySymbol) {
132
+        if (empty($cardData)) {
133
+            return null;
134
+        }
135
+        try {
136
+            $doc = Reader::read($cardData);
137
+            // We're always converting to vCard 4.0 so we can rely on the
138
+            // VCardConverter handling the X-APPLE-OMIT-YEAR property for us.
139
+            if (!$doc instanceof VCard) {
140
+                return null;
141
+            }
142
+            $doc = $doc->convert(Document::VCARD40);
143
+        } catch (Exception $e) {
144
+            return null;
145
+        }
146 146
 
147
-		if (!isset($doc->{$dateField})) {
148
-			return null;
149
-		}
150
-		if (!isset($doc->FN)) {
151
-			return null;
152
-		}
153
-		$birthday = $doc->{$dateField};
154
-		if (!(string)$birthday) {
155
-			return null;
156
-		}
157
-		// Skip if the BDAY property is not of the right type.
158
-		if (!$birthday instanceof DateAndOrTime) {
159
-			return null;
160
-		}
147
+        if (!isset($doc->{$dateField})) {
148
+            return null;
149
+        }
150
+        if (!isset($doc->FN)) {
151
+            return null;
152
+        }
153
+        $birthday = $doc->{$dateField};
154
+        if (!(string)$birthday) {
155
+            return null;
156
+        }
157
+        // Skip if the BDAY property is not of the right type.
158
+        if (!$birthday instanceof DateAndOrTime) {
159
+            return null;
160
+        }
161 161
 
162
-		// Skip if we can't parse the BDAY value.
163
-		try {
164
-			$dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
165
-		} catch (InvalidDataException $e) {
166
-			return null;
167
-		}
162
+        // Skip if we can't parse the BDAY value.
163
+        try {
164
+            $dateParts = DateTimeParser::parseVCardDateTime($birthday->getValue());
165
+        } catch (InvalidDataException $e) {
166
+            return null;
167
+        }
168 168
 
169
-		$unknownYear = false;
170
-		if (!$dateParts['year']) {
171
-			$birthday = '1900-' . $dateParts['month'] . '-' . $dateParts['date'];
169
+        $unknownYear = false;
170
+        if (!$dateParts['year']) {
171
+            $birthday = '1900-' . $dateParts['month'] . '-' . $dateParts['date'];
172 172
 
173
-			$unknownYear = true;
174
-		}
173
+            $unknownYear = true;
174
+        }
175 175
 
176
-		try {
177
-			$date = new \DateTime($birthday);
178
-		} catch (Exception $e) {
179
-			return null;
180
-		}
181
-		if ($unknownYear) {
182
-			$summary = $doc->FN->getValue() . ' ' . $summarySymbol;
183
-		} else {
184
-			$year = (int)$date->format('Y');
185
-			$summary = $doc->FN->getValue() . " ($summarySymbol$year)";
186
-		}
187
-		$vCal = new VCalendar();
188
-		$vCal->VERSION = '2.0';
189
-		$vEvent = $vCal->createComponent('VEVENT');
190
-		$vEvent->add('DTSTART');
191
-		$vEvent->DTSTART->setDateTime(
192
-			$date
193
-		);
194
-		$vEvent->DTSTART['VALUE'] = 'DATE';
195
-		$vEvent->add('DTEND');
196
-		$date->add(new \DateInterval('P1D'));
197
-		$vEvent->DTEND->setDateTime(
198
-			$date
199
-		);
200
-		$vEvent->DTEND['VALUE'] = 'DATE';
201
-		$vEvent->{'UID'} = $doc->UID;
202
-		$vEvent->{'RRULE'} = 'FREQ=YEARLY';
203
-		$vEvent->{'SUMMARY'} = $summary;
204
-		$vEvent->{'TRANSP'} = 'TRANSPARENT';
205
-		$alarm = $vCal->createComponent('VALARM');
206
-		$alarm->add($vCal->createProperty('TRIGGER', '-PT0M', ['VALUE' => 'DURATION']));
207
-		$alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
208
-		$alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
209
-		$vEvent->add($alarm);
210
-		$vCal->add($vEvent);
211
-		return $vCal;
212
-	}
176
+        try {
177
+            $date = new \DateTime($birthday);
178
+        } catch (Exception $e) {
179
+            return null;
180
+        }
181
+        if ($unknownYear) {
182
+            $summary = $doc->FN->getValue() . ' ' . $summarySymbol;
183
+        } else {
184
+            $year = (int)$date->format('Y');
185
+            $summary = $doc->FN->getValue() . " ($summarySymbol$year)";
186
+        }
187
+        $vCal = new VCalendar();
188
+        $vCal->VERSION = '2.0';
189
+        $vEvent = $vCal->createComponent('VEVENT');
190
+        $vEvent->add('DTSTART');
191
+        $vEvent->DTSTART->setDateTime(
192
+            $date
193
+        );
194
+        $vEvent->DTSTART['VALUE'] = 'DATE';
195
+        $vEvent->add('DTEND');
196
+        $date->add(new \DateInterval('P1D'));
197
+        $vEvent->DTEND->setDateTime(
198
+            $date
199
+        );
200
+        $vEvent->DTEND['VALUE'] = 'DATE';
201
+        $vEvent->{'UID'} = $doc->UID;
202
+        $vEvent->{'RRULE'} = 'FREQ=YEARLY';
203
+        $vEvent->{'SUMMARY'} = $summary;
204
+        $vEvent->{'TRANSP'} = 'TRANSPARENT';
205
+        $alarm = $vCal->createComponent('VALARM');
206
+        $alarm->add($vCal->createProperty('TRIGGER', '-PT0M', ['VALUE' => 'DURATION']));
207
+        $alarm->add($vCal->createProperty('ACTION', 'DISPLAY'));
208
+        $alarm->add($vCal->createProperty('DESCRIPTION', $vEvent->{'SUMMARY'}));
209
+        $vEvent->add($alarm);
210
+        $vCal->add($vEvent);
211
+        return $vCal;
212
+    }
213 213
 
214
-	/**
215
-	 * @param string $user
216
-	 */
217
-	public function syncUser($user) {
218
-		$principal = 'principals/users/'.$user;
219
-		$this->ensureCalendarExists($principal);
220
-		$books = $this->cardDavBackEnd->getAddressBooksForUser($principal);
221
-		foreach($books as $book) {
222
-			$cards = $this->cardDavBackEnd->getCards($book['id']);
223
-			foreach($cards as $card) {
224
-				$this->onCardChanged($book['id'], $card['uri'], $card['carddata']);
225
-			}
226
-		}
227
-	}
214
+    /**
215
+     * @param string $user
216
+     */
217
+    public function syncUser($user) {
218
+        $principal = 'principals/users/'.$user;
219
+        $this->ensureCalendarExists($principal);
220
+        $books = $this->cardDavBackEnd->getAddressBooksForUser($principal);
221
+        foreach($books as $book) {
222
+            $cards = $this->cardDavBackEnd->getCards($book['id']);
223
+            foreach($cards as $card) {
224
+                $this->onCardChanged($book['id'], $card['uri'], $card['carddata']);
225
+            }
226
+        }
227
+    }
228 228
 
229
-	/**
230
-	 * @param string $existingCalendarData
231
-	 * @param VCalendar $newCalendarData
232
-	 * @return bool
233
-	 */
234
-	public function birthdayEvenChanged($existingCalendarData, $newCalendarData) {
235
-		try {
236
-			$existingBirthday = Reader::read($existingCalendarData);
237
-		} catch (Exception $ex) {
238
-			return true;
239
-		}
240
-		if ($newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue() ||
241
-			$newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
242
-		) {
243
-			return true;
244
-		}
245
-		return false;
246
-	}
229
+    /**
230
+     * @param string $existingCalendarData
231
+     * @param VCalendar $newCalendarData
232
+     * @return bool
233
+     */
234
+    public function birthdayEvenChanged($existingCalendarData, $newCalendarData) {
235
+        try {
236
+            $existingBirthday = Reader::read($existingCalendarData);
237
+        } catch (Exception $ex) {
238
+            return true;
239
+        }
240
+        if ($newCalendarData->VEVENT->DTSTART->getValue() !== $existingBirthday->VEVENT->DTSTART->getValue() ||
241
+            $newCalendarData->VEVENT->SUMMARY->getValue() !== $existingBirthday->VEVENT->SUMMARY->getValue()
242
+        ) {
243
+            return true;
244
+        }
245
+        return false;
246
+    }
247 247
 
248
-	/**
249
-	 * @param integer $addressBookId
250
-	 * @return mixed
251
-	 */
252
-	protected function getAllAffectedPrincipals($addressBookId) {
253
-		$targetPrincipals = [];
254
-		$shares = $this->cardDavBackEnd->getShares($addressBookId);
255
-		foreach ($shares as $share) {
256
-			if ($share['{http://owncloud.org/ns}group-share']) {
257
-				$users = $this->principalBackend->getGroupMemberSet($share['{http://owncloud.org/ns}principal']);
258
-				foreach ($users as $user) {
259
-					$targetPrincipals[] = $user['uri'];
260
-				}
261
-			} else {
262
-				$targetPrincipals[] = $share['{http://owncloud.org/ns}principal'];
263
-			}
264
-		}
265
-		return array_values(array_unique($targetPrincipals, SORT_STRING));
266
-	}
248
+    /**
249
+     * @param integer $addressBookId
250
+     * @return mixed
251
+     */
252
+    protected function getAllAffectedPrincipals($addressBookId) {
253
+        $targetPrincipals = [];
254
+        $shares = $this->cardDavBackEnd->getShares($addressBookId);
255
+        foreach ($shares as $share) {
256
+            if ($share['{http://owncloud.org/ns}group-share']) {
257
+                $users = $this->principalBackend->getGroupMemberSet($share['{http://owncloud.org/ns}principal']);
258
+                foreach ($users as $user) {
259
+                    $targetPrincipals[] = $user['uri'];
260
+                }
261
+            } else {
262
+                $targetPrincipals[] = $share['{http://owncloud.org/ns}principal'];
263
+            }
264
+        }
265
+        return array_values(array_unique($targetPrincipals, SORT_STRING));
266
+    }
267 267
 
268
-	/**
269
-	 * @param string $cardUri
270
-	 * @param string  $cardData
271
-	 * @param array $book
272
-	 * @param int $calendarId
273
-	 * @param string $type
274
-	 */
275
-	private function updateCalendar($cardUri, $cardData, $book, $calendarId, $type) {
276
-		$objectUri = $book['uri'] . '-' . $cardUri . $type['postfix'] . '.ics';
277
-		$calendarData = $this->buildDateFromContact($cardData, $type['field'], $type['symbol']);
278
-		$existing = $this->calDavBackEnd->getCalendarObject($calendarId, $objectUri);
279
-		if (is_null($calendarData)) {
280
-			if (!is_null($existing)) {
281
-				$this->calDavBackEnd->deleteCalendarObject($calendarId, $objectUri);
282
-			}
283
-		} else {
284
-			if (is_null($existing)) {
285
-				$this->calDavBackEnd->createCalendarObject($calendarId, $objectUri, $calendarData->serialize());
286
-			} else {
287
-				if ($this->birthdayEvenChanged($existing['calendardata'], $calendarData)) {
288
-					$this->calDavBackEnd->updateCalendarObject($calendarId, $objectUri, $calendarData->serialize());
289
-				}
290
-			}
291
-		}
292
-	}
268
+    /**
269
+     * @param string $cardUri
270
+     * @param string  $cardData
271
+     * @param array $book
272
+     * @param int $calendarId
273
+     * @param string $type
274
+     */
275
+    private function updateCalendar($cardUri, $cardData, $book, $calendarId, $type) {
276
+        $objectUri = $book['uri'] . '-' . $cardUri . $type['postfix'] . '.ics';
277
+        $calendarData = $this->buildDateFromContact($cardData, $type['field'], $type['symbol']);
278
+        $existing = $this->calDavBackEnd->getCalendarObject($calendarId, $objectUri);
279
+        if (is_null($calendarData)) {
280
+            if (!is_null($existing)) {
281
+                $this->calDavBackEnd->deleteCalendarObject($calendarId, $objectUri);
282
+            }
283
+        } else {
284
+            if (is_null($existing)) {
285
+                $this->calDavBackEnd->createCalendarObject($calendarId, $objectUri, $calendarData->serialize());
286
+            } else {
287
+                if ($this->birthdayEvenChanged($existing['calendardata'], $calendarData)) {
288
+                    $this->calDavBackEnd->updateCalendarObject($calendarId, $objectUri, $calendarData->serialize());
289
+                }
290
+            }
291
+        }
292
+    }
293 293
 
294 294
 }
Please login to merge, or discard this patch.