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