Passed
Push — master ( 569cf3...c504ed )
by Roeland
13:57
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +2559 added lines, -2559 removed lines patch added patch discarded remove patch
@@ -75,2564 +75,2564 @@
 block discarded – undo
75 75
  */
76 76
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
77 77
 
78
-	const CALENDAR_TYPE_CALENDAR = 0;
79
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
-
81
-	const PERSONAL_CALENDAR_URI = 'personal';
82
-	const PERSONAL_CALENDAR_NAME = 'Personal';
83
-
84
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
-
87
-	/**
88
-	 * We need to specify a max date, because we need to stop *somewhere*
89
-	 *
90
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
91
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
-	 * in 2038-01-19 to avoid problems when the date is converted
93
-	 * to a unix timestamp.
94
-	 */
95
-	const MAX_DATE = '2038-01-01';
96
-
97
-	const ACCESS_PUBLIC = 4;
98
-	const CLASSIFICATION_PUBLIC = 0;
99
-	const CLASSIFICATION_PRIVATE = 1;
100
-	const CLASSIFICATION_CONFIDENTIAL = 2;
101
-
102
-	/**
103
-	 * List of CalDAV properties, and how they map to database field names
104
-	 * Add your own properties by simply adding on to this array.
105
-	 *
106
-	 * Note that only string-based properties are supported here.
107
-	 *
108
-	 * @var array
109
-	 */
110
-	public $propertyMap = [
111
-		'{DAV:}displayname'                          => 'displayname',
112
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
-	];
117
-
118
-	/**
119
-	 * List of subscription properties, and how they map to database field names.
120
-	 *
121
-	 * @var array
122
-	 */
123
-	public $subscriptionPropertyMap = [
124
-		'{DAV:}displayname'                                           => 'displayname',
125
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
-	];
132
-
133
-	/** @var array properties to index */
134
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
-		'ORGANIZER'];
137
-
138
-	/** @var array parameters to index */
139
-	public static $indexParameters = [
140
-		'ATTENDEE' => ['CN'],
141
-		'ORGANIZER' => ['CN'],
142
-	];
143
-
144
-	/**
145
-	 * @var string[] Map of uid => display name
146
-	 */
147
-	protected $userDisplayNames;
148
-
149
-	/** @var IDBConnection */
150
-	private $db;
151
-
152
-	/** @var Backend */
153
-	private $calendarSharingBackend;
154
-
155
-	/** @var Principal */
156
-	private $principalBackend;
157
-
158
-	/** @var IUserManager */
159
-	private $userManager;
160
-
161
-	/** @var ISecureRandom */
162
-	private $random;
163
-
164
-	/** @var ILogger */
165
-	private $logger;
166
-
167
-	/** @var EventDispatcherInterface */
168
-	private $dispatcher;
169
-
170
-	/** @var bool */
171
-	private $legacyEndpoint;
172
-
173
-	/** @var string */
174
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
175
-
176
-	/**
177
-	 * CalDavBackend constructor.
178
-	 *
179
-	 * @param IDBConnection $db
180
-	 * @param Principal $principalBackend
181
-	 * @param IUserManager $userManager
182
-	 * @param IGroupManager $groupManager
183
-	 * @param ISecureRandom $random
184
-	 * @param ILogger $logger
185
-	 * @param EventDispatcherInterface $dispatcher
186
-	 * @param bool $legacyEndpoint
187
-	 */
188
-	public function __construct(IDBConnection $db,
189
-								Principal $principalBackend,
190
-								IUserManager $userManager,
191
-								IGroupManager $groupManager,
192
-								ISecureRandom $random,
193
-								ILogger $logger,
194
-								EventDispatcherInterface $dispatcher,
195
-								bool $legacyEndpoint = false) {
196
-		$this->db = $db;
197
-		$this->principalBackend = $principalBackend;
198
-		$this->userManager = $userManager;
199
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
-		$this->random = $random;
201
-		$this->logger = $logger;
202
-		$this->dispatcher = $dispatcher;
203
-		$this->legacyEndpoint = $legacyEndpoint;
204
-	}
205
-
206
-	/**
207
-	 * Return the number of calendars for a principal
208
-	 *
209
-	 * By default this excludes the automatically generated birthday calendar
210
-	 *
211
-	 * @param $principalUri
212
-	 * @param bool $excludeBirthday
213
-	 * @return int
214
-	 */
215
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
-		$principalUri = $this->convertPrincipal($principalUri, true);
217
-		$query = $this->db->getQueryBuilder();
218
-		$query->select($query->func()->count('*'))
219
-			->from('calendars')
220
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
-
222
-		if ($excludeBirthday) {
223
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
-		}
225
-
226
-		return (int)$query->execute()->fetchColumn();
227
-	}
228
-
229
-	/**
230
-	 * Returns a list of calendars for a principal.
231
-	 *
232
-	 * Every project is an array with the following keys:
233
-	 *  * id, a unique id that will be used by other functions to modify the
234
-	 *    calendar. This can be the same as the uri or a database key.
235
-	 *  * uri, which the basename of the uri with which the calendar is
236
-	 *    accessed.
237
-	 *  * principaluri. The owner of the calendar. Almost always the same as
238
-	 *    principalUri passed to this method.
239
-	 *
240
-	 * Furthermore it can contain webdav properties in clark notation. A very
241
-	 * common one is '{DAV:}displayname'.
242
-	 *
243
-	 * Many clients also require:
244
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
-	 * For this property, you can just return an instance of
246
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
-	 *
248
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
-	 * ACL will automatically be put in read-only mode.
250
-	 *
251
-	 * @param string $principalUri
252
-	 * @return array
253
-	 */
254
-	function getCalendarsForUser($principalUri) {
255
-		$principalUriOriginal = $principalUri;
256
-		$principalUri = $this->convertPrincipal($principalUri, true);
257
-		$fields = array_values($this->propertyMap);
258
-		$fields[] = 'id';
259
-		$fields[] = 'uri';
260
-		$fields[] = 'synctoken';
261
-		$fields[] = 'components';
262
-		$fields[] = 'principaluri';
263
-		$fields[] = 'transparent';
264
-
265
-		// Making fields a comma-delimited list
266
-		$query = $this->db->getQueryBuilder();
267
-		$query->select($fields)->from('calendars')
268
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
-				->orderBy('calendarorder', 'ASC');
270
-		$stmt = $query->execute();
271
-
272
-		$calendars = [];
273
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
-
275
-			$components = [];
276
-			if ($row['components']) {
277
-				$components = explode(',',$row['components']);
278
-			}
279
-
280
-			$calendar = [
281
-				'id' => $row['id'],
282
-				'uri' => $row['uri'],
283
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
-			];
290
-
291
-			foreach($this->propertyMap as $xmlName=>$dbName) {
292
-				$calendar[$xmlName] = $row[$dbName];
293
-			}
294
-
295
-			$this->addOwnerPrincipal($calendar);
296
-
297
-			if (!isset($calendars[$calendar['id']])) {
298
-				$calendars[$calendar['id']] = $calendar;
299
-			}
300
-		}
301
-
302
-		$stmt->closeCursor();
303
-
304
-		// query for shared calendars
305
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
-
308
-		$principals = array_map(function($principal) {
309
-			return urldecode($principal);
310
-		}, $principals);
311
-		$principals[]= $principalUri;
312
-
313
-		$fields = array_values($this->propertyMap);
314
-		$fields[] = 'a.id';
315
-		$fields[] = 'a.uri';
316
-		$fields[] = 'a.synctoken';
317
-		$fields[] = 'a.components';
318
-		$fields[] = 'a.principaluri';
319
-		$fields[] = 'a.transparent';
320
-		$fields[] = 's.access';
321
-		$query = $this->db->getQueryBuilder();
322
-		$result = $query->select($fields)
323
-			->from('dav_shares', 's')
324
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
-			->setParameter('type', 'calendar')
328
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
-			->execute();
330
-
331
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
-		while($row = $result->fetch()) {
333
-			if ($row['principaluri'] === $principalUri) {
334
-				continue;
335
-			}
336
-
337
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
-			if (isset($calendars[$row['id']])) {
339
-				if ($readOnly) {
340
-					// New share can not have more permissions then the old one.
341
-					continue;
342
-				}
343
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
-					// Old share is already read-write, no more permissions can be gained
346
-					continue;
347
-				}
348
-			}
349
-
350
-			list(, $name) = Uri\split($row['principaluri']);
351
-			$uri = $row['uri'] . '_shared_by_' . $name;
352
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
-			$components = [];
354
-			if ($row['components']) {
355
-				$components = explode(',',$row['components']);
356
-			}
357
-			$calendar = [
358
-				'id' => $row['id'],
359
-				'uri' => $uri,
360
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
-				$readOnlyPropertyName => $readOnly,
367
-			];
368
-
369
-			foreach($this->propertyMap as $xmlName=>$dbName) {
370
-				$calendar[$xmlName] = $row[$dbName];
371
-			}
372
-
373
-			$this->addOwnerPrincipal($calendar);
374
-
375
-			$calendars[$calendar['id']] = $calendar;
376
-		}
377
-		$result->closeCursor();
378
-
379
-		return array_values($calendars);
380
-	}
381
-
382
-	/**
383
-	 * @param $principalUri
384
-	 * @return array
385
-	 */
386
-	public function getUsersOwnCalendars($principalUri) {
387
-		$principalUri = $this->convertPrincipal($principalUri, true);
388
-		$fields = array_values($this->propertyMap);
389
-		$fields[] = 'id';
390
-		$fields[] = 'uri';
391
-		$fields[] = 'synctoken';
392
-		$fields[] = 'components';
393
-		$fields[] = 'principaluri';
394
-		$fields[] = 'transparent';
395
-		// Making fields a comma-delimited list
396
-		$query = $this->db->getQueryBuilder();
397
-		$query->select($fields)->from('calendars')
398
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
-			->orderBy('calendarorder', 'ASC');
400
-		$stmt = $query->execute();
401
-		$calendars = [];
402
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
-			$components = [];
404
-			if ($row['components']) {
405
-				$components = explode(',',$row['components']);
406
-			}
407
-			$calendar = [
408
-				'id' => $row['id'],
409
-				'uri' => $row['uri'],
410
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
-			];
416
-			foreach($this->propertyMap as $xmlName=>$dbName) {
417
-				$calendar[$xmlName] = $row[$dbName];
418
-			}
419
-
420
-			$this->addOwnerPrincipal($calendar);
421
-
422
-			if (!isset($calendars[$calendar['id']])) {
423
-				$calendars[$calendar['id']] = $calendar;
424
-			}
425
-		}
426
-		$stmt->closeCursor();
427
-		return array_values($calendars);
428
-	}
429
-
430
-
431
-	/**
432
-	 * @param $uid
433
-	 * @return string
434
-	 */
435
-	private function getUserDisplayName($uid) {
436
-		if (!isset($this->userDisplayNames[$uid])) {
437
-			$user = $this->userManager->get($uid);
438
-
439
-			if ($user instanceof IUser) {
440
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
441
-			} else {
442
-				$this->userDisplayNames[$uid] = $uid;
443
-			}
444
-		}
445
-
446
-		return $this->userDisplayNames[$uid];
447
-	}
78
+    const CALENDAR_TYPE_CALENDAR = 0;
79
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
80
+
81
+    const PERSONAL_CALENDAR_URI = 'personal';
82
+    const PERSONAL_CALENDAR_NAME = 'Personal';
83
+
84
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
85
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
86
+
87
+    /**
88
+     * We need to specify a max date, because we need to stop *somewhere*
89
+     *
90
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
91
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
92
+     * in 2038-01-19 to avoid problems when the date is converted
93
+     * to a unix timestamp.
94
+     */
95
+    const MAX_DATE = '2038-01-01';
96
+
97
+    const ACCESS_PUBLIC = 4;
98
+    const CLASSIFICATION_PUBLIC = 0;
99
+    const CLASSIFICATION_PRIVATE = 1;
100
+    const CLASSIFICATION_CONFIDENTIAL = 2;
101
+
102
+    /**
103
+     * List of CalDAV properties, and how they map to database field names
104
+     * Add your own properties by simply adding on to this array.
105
+     *
106
+     * Note that only string-based properties are supported here.
107
+     *
108
+     * @var array
109
+     */
110
+    public $propertyMap = [
111
+        '{DAV:}displayname'                          => 'displayname',
112
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
113
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
114
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
115
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
116
+    ];
117
+
118
+    /**
119
+     * List of subscription properties, and how they map to database field names.
120
+     *
121
+     * @var array
122
+     */
123
+    public $subscriptionPropertyMap = [
124
+        '{DAV:}displayname'                                           => 'displayname',
125
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
126
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
127
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
128
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
129
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
130
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
131
+    ];
132
+
133
+    /** @var array properties to index */
134
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
135
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
136
+        'ORGANIZER'];
137
+
138
+    /** @var array parameters to index */
139
+    public static $indexParameters = [
140
+        'ATTENDEE' => ['CN'],
141
+        'ORGANIZER' => ['CN'],
142
+    ];
143
+
144
+    /**
145
+     * @var string[] Map of uid => display name
146
+     */
147
+    protected $userDisplayNames;
148
+
149
+    /** @var IDBConnection */
150
+    private $db;
151
+
152
+    /** @var Backend */
153
+    private $calendarSharingBackend;
154
+
155
+    /** @var Principal */
156
+    private $principalBackend;
157
+
158
+    /** @var IUserManager */
159
+    private $userManager;
160
+
161
+    /** @var ISecureRandom */
162
+    private $random;
163
+
164
+    /** @var ILogger */
165
+    private $logger;
166
+
167
+    /** @var EventDispatcherInterface */
168
+    private $dispatcher;
169
+
170
+    /** @var bool */
171
+    private $legacyEndpoint;
172
+
173
+    /** @var string */
174
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
175
+
176
+    /**
177
+     * CalDavBackend constructor.
178
+     *
179
+     * @param IDBConnection $db
180
+     * @param Principal $principalBackend
181
+     * @param IUserManager $userManager
182
+     * @param IGroupManager $groupManager
183
+     * @param ISecureRandom $random
184
+     * @param ILogger $logger
185
+     * @param EventDispatcherInterface $dispatcher
186
+     * @param bool $legacyEndpoint
187
+     */
188
+    public function __construct(IDBConnection $db,
189
+                                Principal $principalBackend,
190
+                                IUserManager $userManager,
191
+                                IGroupManager $groupManager,
192
+                                ISecureRandom $random,
193
+                                ILogger $logger,
194
+                                EventDispatcherInterface $dispatcher,
195
+                                bool $legacyEndpoint = false) {
196
+        $this->db = $db;
197
+        $this->principalBackend = $principalBackend;
198
+        $this->userManager = $userManager;
199
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
200
+        $this->random = $random;
201
+        $this->logger = $logger;
202
+        $this->dispatcher = $dispatcher;
203
+        $this->legacyEndpoint = $legacyEndpoint;
204
+    }
205
+
206
+    /**
207
+     * Return the number of calendars for a principal
208
+     *
209
+     * By default this excludes the automatically generated birthday calendar
210
+     *
211
+     * @param $principalUri
212
+     * @param bool $excludeBirthday
213
+     * @return int
214
+     */
215
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
216
+        $principalUri = $this->convertPrincipal($principalUri, true);
217
+        $query = $this->db->getQueryBuilder();
218
+        $query->select($query->func()->count('*'))
219
+            ->from('calendars')
220
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
221
+
222
+        if ($excludeBirthday) {
223
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224
+        }
225
+
226
+        return (int)$query->execute()->fetchColumn();
227
+    }
228
+
229
+    /**
230
+     * Returns a list of calendars for a principal.
231
+     *
232
+     * Every project is an array with the following keys:
233
+     *  * id, a unique id that will be used by other functions to modify the
234
+     *    calendar. This can be the same as the uri or a database key.
235
+     *  * uri, which the basename of the uri with which the calendar is
236
+     *    accessed.
237
+     *  * principaluri. The owner of the calendar. Almost always the same as
238
+     *    principalUri passed to this method.
239
+     *
240
+     * Furthermore it can contain webdav properties in clark notation. A very
241
+     * common one is '{DAV:}displayname'.
242
+     *
243
+     * Many clients also require:
244
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
245
+     * For this property, you can just return an instance of
246
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
247
+     *
248
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
249
+     * ACL will automatically be put in read-only mode.
250
+     *
251
+     * @param string $principalUri
252
+     * @return array
253
+     */
254
+    function getCalendarsForUser($principalUri) {
255
+        $principalUriOriginal = $principalUri;
256
+        $principalUri = $this->convertPrincipal($principalUri, true);
257
+        $fields = array_values($this->propertyMap);
258
+        $fields[] = 'id';
259
+        $fields[] = 'uri';
260
+        $fields[] = 'synctoken';
261
+        $fields[] = 'components';
262
+        $fields[] = 'principaluri';
263
+        $fields[] = 'transparent';
264
+
265
+        // Making fields a comma-delimited list
266
+        $query = $this->db->getQueryBuilder();
267
+        $query->select($fields)->from('calendars')
268
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
269
+                ->orderBy('calendarorder', 'ASC');
270
+        $stmt = $query->execute();
271
+
272
+        $calendars = [];
273
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274
+
275
+            $components = [];
276
+            if ($row['components']) {
277
+                $components = explode(',',$row['components']);
278
+            }
279
+
280
+            $calendar = [
281
+                'id' => $row['id'],
282
+                'uri' => $row['uri'],
283
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289
+            ];
290
+
291
+            foreach($this->propertyMap as $xmlName=>$dbName) {
292
+                $calendar[$xmlName] = $row[$dbName];
293
+            }
294
+
295
+            $this->addOwnerPrincipal($calendar);
296
+
297
+            if (!isset($calendars[$calendar['id']])) {
298
+                $calendars[$calendar['id']] = $calendar;
299
+            }
300
+        }
301
+
302
+        $stmt->closeCursor();
303
+
304
+        // query for shared calendars
305
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
306
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
307
+
308
+        $principals = array_map(function($principal) {
309
+            return urldecode($principal);
310
+        }, $principals);
311
+        $principals[]= $principalUri;
312
+
313
+        $fields = array_values($this->propertyMap);
314
+        $fields[] = 'a.id';
315
+        $fields[] = 'a.uri';
316
+        $fields[] = 'a.synctoken';
317
+        $fields[] = 'a.components';
318
+        $fields[] = 'a.principaluri';
319
+        $fields[] = 'a.transparent';
320
+        $fields[] = 's.access';
321
+        $query = $this->db->getQueryBuilder();
322
+        $result = $query->select($fields)
323
+            ->from('dav_shares', 's')
324
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
325
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
326
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
327
+            ->setParameter('type', 'calendar')
328
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329
+            ->execute();
330
+
331
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
+        while($row = $result->fetch()) {
333
+            if ($row['principaluri'] === $principalUri) {
334
+                continue;
335
+            }
336
+
337
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
338
+            if (isset($calendars[$row['id']])) {
339
+                if ($readOnly) {
340
+                    // New share can not have more permissions then the old one.
341
+                    continue;
342
+                }
343
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
344
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
345
+                    // Old share is already read-write, no more permissions can be gained
346
+                    continue;
347
+                }
348
+            }
349
+
350
+            list(, $name) = Uri\split($row['principaluri']);
351
+            $uri = $row['uri'] . '_shared_by_' . $name;
352
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
353
+            $components = [];
354
+            if ($row['components']) {
355
+                $components = explode(',',$row['components']);
356
+            }
357
+            $calendar = [
358
+                'id' => $row['id'],
359
+                'uri' => $uri,
360
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366
+                $readOnlyPropertyName => $readOnly,
367
+            ];
368
+
369
+            foreach($this->propertyMap as $xmlName=>$dbName) {
370
+                $calendar[$xmlName] = $row[$dbName];
371
+            }
372
+
373
+            $this->addOwnerPrincipal($calendar);
374
+
375
+            $calendars[$calendar['id']] = $calendar;
376
+        }
377
+        $result->closeCursor();
378
+
379
+        return array_values($calendars);
380
+    }
381
+
382
+    /**
383
+     * @param $principalUri
384
+     * @return array
385
+     */
386
+    public function getUsersOwnCalendars($principalUri) {
387
+        $principalUri = $this->convertPrincipal($principalUri, true);
388
+        $fields = array_values($this->propertyMap);
389
+        $fields[] = 'id';
390
+        $fields[] = 'uri';
391
+        $fields[] = 'synctoken';
392
+        $fields[] = 'components';
393
+        $fields[] = 'principaluri';
394
+        $fields[] = 'transparent';
395
+        // Making fields a comma-delimited list
396
+        $query = $this->db->getQueryBuilder();
397
+        $query->select($fields)->from('calendars')
398
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
399
+            ->orderBy('calendarorder', 'ASC');
400
+        $stmt = $query->execute();
401
+        $calendars = [];
402
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403
+            $components = [];
404
+            if ($row['components']) {
405
+                $components = explode(',',$row['components']);
406
+            }
407
+            $calendar = [
408
+                'id' => $row['id'],
409
+                'uri' => $row['uri'],
410
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
415
+            ];
416
+            foreach($this->propertyMap as $xmlName=>$dbName) {
417
+                $calendar[$xmlName] = $row[$dbName];
418
+            }
419
+
420
+            $this->addOwnerPrincipal($calendar);
421
+
422
+            if (!isset($calendars[$calendar['id']])) {
423
+                $calendars[$calendar['id']] = $calendar;
424
+            }
425
+        }
426
+        $stmt->closeCursor();
427
+        return array_values($calendars);
428
+    }
429
+
430
+
431
+    /**
432
+     * @param $uid
433
+     * @return string
434
+     */
435
+    private function getUserDisplayName($uid) {
436
+        if (!isset($this->userDisplayNames[$uid])) {
437
+            $user = $this->userManager->get($uid);
438
+
439
+            if ($user instanceof IUser) {
440
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
441
+            } else {
442
+                $this->userDisplayNames[$uid] = $uid;
443
+            }
444
+        }
445
+
446
+        return $this->userDisplayNames[$uid];
447
+    }
448 448
 	
449
-	/**
450
-	 * @return array
451
-	 */
452
-	public function getPublicCalendars() {
453
-		$fields = array_values($this->propertyMap);
454
-		$fields[] = 'a.id';
455
-		$fields[] = 'a.uri';
456
-		$fields[] = 'a.synctoken';
457
-		$fields[] = 'a.components';
458
-		$fields[] = 'a.principaluri';
459
-		$fields[] = 'a.transparent';
460
-		$fields[] = 's.access';
461
-		$fields[] = 's.publicuri';
462
-		$calendars = [];
463
-		$query = $this->db->getQueryBuilder();
464
-		$result = $query->select($fields)
465
-			->from('dav_shares', 's')
466
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
-			->execute();
470
-
471
-		while($row = $result->fetch()) {
472
-			list(, $name) = Uri\split($row['principaluri']);
473
-			$row['displayname'] = $row['displayname'] . "($name)";
474
-			$components = [];
475
-			if ($row['components']) {
476
-				$components = explode(',',$row['components']);
477
-			}
478
-			$calendar = [
479
-				'id' => $row['id'],
480
-				'uri' => $row['publicuri'],
481
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
-			];
490
-
491
-			foreach($this->propertyMap as $xmlName=>$dbName) {
492
-				$calendar[$xmlName] = $row[$dbName];
493
-			}
494
-
495
-			$this->addOwnerPrincipal($calendar);
496
-
497
-			if (!isset($calendars[$calendar['id']])) {
498
-				$calendars[$calendar['id']] = $calendar;
499
-			}
500
-		}
501
-		$result->closeCursor();
502
-
503
-		return array_values($calendars);
504
-	}
505
-
506
-	/**
507
-	 * @param string $uri
508
-	 * @return array
509
-	 * @throws NotFound
510
-	 */
511
-	public function getPublicCalendar($uri) {
512
-		$fields = array_values($this->propertyMap);
513
-		$fields[] = 'a.id';
514
-		$fields[] = 'a.uri';
515
-		$fields[] = 'a.synctoken';
516
-		$fields[] = 'a.components';
517
-		$fields[] = 'a.principaluri';
518
-		$fields[] = 'a.transparent';
519
-		$fields[] = 's.access';
520
-		$fields[] = 's.publicuri';
521
-		$query = $this->db->getQueryBuilder();
522
-		$result = $query->select($fields)
523
-			->from('dav_shares', 's')
524
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
-			->execute();
529
-
530
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
531
-
532
-		$result->closeCursor();
533
-
534
-		if ($row === false) {
535
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
-		}
537
-
538
-		list(, $name) = Uri\split($row['principaluri']);
539
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
-		$components = [];
541
-		if ($row['components']) {
542
-			$components = explode(',',$row['components']);
543
-		}
544
-		$calendar = [
545
-			'id' => $row['id'],
546
-			'uri' => $row['publicuri'],
547
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
-		];
556
-
557
-		foreach($this->propertyMap as $xmlName=>$dbName) {
558
-			$calendar[$xmlName] = $row[$dbName];
559
-		}
560
-
561
-		$this->addOwnerPrincipal($calendar);
562
-
563
-		return $calendar;
564
-
565
-	}
566
-
567
-	/**
568
-	 * @param string $principal
569
-	 * @param string $uri
570
-	 * @return array|null
571
-	 */
572
-	public function getCalendarByUri($principal, $uri) {
573
-		$fields = array_values($this->propertyMap);
574
-		$fields[] = 'id';
575
-		$fields[] = 'uri';
576
-		$fields[] = 'synctoken';
577
-		$fields[] = 'components';
578
-		$fields[] = 'principaluri';
579
-		$fields[] = 'transparent';
580
-
581
-		// Making fields a comma-delimited list
582
-		$query = $this->db->getQueryBuilder();
583
-		$query->select($fields)->from('calendars')
584
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
-			->setMaxResults(1);
587
-		$stmt = $query->execute();
588
-
589
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
-		$stmt->closeCursor();
591
-		if ($row === false) {
592
-			return null;
593
-		}
594
-
595
-		$components = [];
596
-		if ($row['components']) {
597
-			$components = explode(',',$row['components']);
598
-		}
599
-
600
-		$calendar = [
601
-			'id' => $row['id'],
602
-			'uri' => $row['uri'],
603
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
-		];
609
-
610
-		foreach($this->propertyMap as $xmlName=>$dbName) {
611
-			$calendar[$xmlName] = $row[$dbName];
612
-		}
613
-
614
-		$this->addOwnerPrincipal($calendar);
615
-
616
-		return $calendar;
617
-	}
618
-
619
-	/**
620
-	 * @param $calendarId
621
-	 * @return array|null
622
-	 */
623
-	public function getCalendarById($calendarId) {
624
-		$fields = array_values($this->propertyMap);
625
-		$fields[] = 'id';
626
-		$fields[] = 'uri';
627
-		$fields[] = 'synctoken';
628
-		$fields[] = 'components';
629
-		$fields[] = 'principaluri';
630
-		$fields[] = 'transparent';
631
-
632
-		// Making fields a comma-delimited list
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->select($fields)->from('calendars')
635
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
-			->setMaxResults(1);
637
-		$stmt = $query->execute();
638
-
639
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
-		$stmt->closeCursor();
641
-		if ($row === false) {
642
-			return null;
643
-		}
644
-
645
-		$components = [];
646
-		if ($row['components']) {
647
-			$components = explode(',',$row['components']);
648
-		}
649
-
650
-		$calendar = [
651
-			'id' => $row['id'],
652
-			'uri' => $row['uri'],
653
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
-		];
659
-
660
-		foreach($this->propertyMap as $xmlName=>$dbName) {
661
-			$calendar[$xmlName] = $row[$dbName];
662
-		}
663
-
664
-		$this->addOwnerPrincipal($calendar);
665
-
666
-		return $calendar;
667
-	}
668
-
669
-	/**
670
-	 * @param $subscriptionId
671
-	 */
672
-	public function getSubscriptionById($subscriptionId) {
673
-		$fields = array_values($this->subscriptionPropertyMap);
674
-		$fields[] = 'id';
675
-		$fields[] = 'uri';
676
-		$fields[] = 'source';
677
-		$fields[] = 'synctoken';
678
-		$fields[] = 'principaluri';
679
-		$fields[] = 'lastmodified';
680
-
681
-		$query = $this->db->getQueryBuilder();
682
-		$query->select($fields)
683
-			->from('calendarsubscriptions')
684
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
-			->orderBy('calendarorder', 'asc');
686
-		$stmt =$query->execute();
687
-
688
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
-		$stmt->closeCursor();
690
-		if ($row === false) {
691
-			return null;
692
-		}
693
-
694
-		$subscription = [
695
-			'id'           => $row['id'],
696
-			'uri'          => $row['uri'],
697
-			'principaluri' => $row['principaluri'],
698
-			'source'       => $row['source'],
699
-			'lastmodified' => $row['lastmodified'],
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
-		];
703
-
704
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
-			if (!is_null($row[$dbName])) {
706
-				$subscription[$xmlName] = $row[$dbName];
707
-			}
708
-		}
709
-
710
-		return $subscription;
711
-	}
712
-
713
-	/**
714
-	 * Creates a new calendar for a principal.
715
-	 *
716
-	 * If the creation was a success, an id must be returned that can be used to reference
717
-	 * this calendar in other methods, such as updateCalendar.
718
-	 *
719
-	 * @param string $principalUri
720
-	 * @param string $calendarUri
721
-	 * @param array $properties
722
-	 * @return int
723
-	 * @suppress SqlInjectionChecker
724
-	 */
725
-	function createCalendar($principalUri, $calendarUri, array $properties) {
726
-		$values = [
727
-			'principaluri' => $this->convertPrincipal($principalUri, true),
728
-			'uri'          => $calendarUri,
729
-			'synctoken'    => 1,
730
-			'transparent'  => 0,
731
-			'components'   => 'VEVENT,VTODO',
732
-			'displayname'  => $calendarUri
733
-		];
734
-
735
-		// Default value
736
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
-		if (isset($properties[$sccs])) {
738
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
-			}
741
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
742
-		} else if (isset($properties['components'])) {
743
-			// Allow to provide components internally without having
744
-			// to create a SupportedCalendarComponentSet object
745
-			$values['components'] = $properties['components'];
746
-		}
747
-
748
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
-		if (isset($properties[$transp])) {
750
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
-		}
752
-
753
-		foreach($this->propertyMap as $xmlName=>$dbName) {
754
-			if (isset($properties[$xmlName])) {
755
-				$values[$dbName] = $properties[$xmlName];
756
-			}
757
-		}
758
-
759
-		$query = $this->db->getQueryBuilder();
760
-		$query->insert('calendars');
761
-		foreach($values as $column => $value) {
762
-			$query->setValue($column, $query->createNamedParameter($value));
763
-		}
764
-		$query->execute();
765
-		$calendarId = $query->getLastInsertId();
766
-
767
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
-			[
770
-				'calendarId' => $calendarId,
771
-				'calendarData' => $this->getCalendarById($calendarId),
772
-		]));
773
-
774
-		return $calendarId;
775
-	}
776
-
777
-	/**
778
-	 * Updates properties for a calendar.
779
-	 *
780
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
-	 * To do the actual updates, you must tell this object which properties
782
-	 * you're going to process with the handle() method.
783
-	 *
784
-	 * Calling the handle method is like telling the PropPatch object "I
785
-	 * promise I can handle updating this property".
786
-	 *
787
-	 * Read the PropPatch documentation for more info and examples.
788
-	 *
789
-	 * @param mixed $calendarId
790
-	 * @param PropPatch $propPatch
791
-	 * @return void
792
-	 */
793
-	function updateCalendar($calendarId, PropPatch $propPatch) {
794
-		$supportedProperties = array_keys($this->propertyMap);
795
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
-
797
-		/**
798
-		 * @suppress SqlInjectionChecker
799
-		 */
800
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
801
-			$newValues = [];
802
-			foreach ($mutations as $propertyName => $propertyValue) {
803
-
804
-				switch ($propertyName) {
805
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
806
-						$fieldName = 'transparent';
807
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808
-						break;
809
-					default :
810
-						$fieldName = $this->propertyMap[$propertyName];
811
-						$newValues[$fieldName] = $propertyValue;
812
-						break;
813
-				}
814
-
815
-			}
816
-			$query = $this->db->getQueryBuilder();
817
-			$query->update('calendars');
818
-			foreach ($newValues as $fieldName => $value) {
819
-				$query->set($fieldName, $query->createNamedParameter($value));
820
-			}
821
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
822
-			$query->execute();
823
-
824
-			$this->addChange($calendarId, "", 2);
825
-
826
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
827
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
828
-				[
829
-					'calendarId' => $calendarId,
830
-					'calendarData' => $this->getCalendarById($calendarId),
831
-					'shares' => $this->getShares($calendarId),
832
-					'propertyMutations' => $mutations,
833
-			]));
834
-
835
-			return true;
836
-		});
837
-	}
838
-
839
-	/**
840
-	 * Delete a calendar and all it's objects
841
-	 *
842
-	 * @param mixed $calendarId
843
-	 * @return void
844
-	 */
845
-	function deleteCalendar($calendarId) {
846
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
847
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
848
-			[
849
-				'calendarId' => $calendarId,
850
-				'calendarData' => $this->getCalendarById($calendarId),
851
-				'shares' => $this->getShares($calendarId),
852
-		]));
853
-
854
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
855
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
856
-
857
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
858
-		$stmt->execute([$calendarId]);
859
-
860
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
861
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
862
-
863
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
864
-
865
-		$query = $this->db->getQueryBuilder();
866
-		$query->delete($this->dbObjectPropertiesTable)
867
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
869
-			->execute();
870
-	}
871
-
872
-	/**
873
-	 * Delete all of an user's shares
874
-	 *
875
-	 * @param string $principaluri
876
-	 * @return void
877
-	 */
878
-	function deleteAllSharesByUser($principaluri) {
879
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
880
-	}
881
-
882
-	/**
883
-	 * Returns all calendar objects within a calendar.
884
-	 *
885
-	 * Every item contains an array with the following keys:
886
-	 *   * calendardata - The iCalendar-compatible calendar data
887
-	 *   * uri - a unique key which will be used to construct the uri. This can
888
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
889
-	 *     good idea. This is only the basename, or filename, not the full
890
-	 *     path.
891
-	 *   * lastmodified - a timestamp of the last modification time
892
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
893
-	 *   '"abcdef"')
894
-	 *   * size - The size of the calendar objects, in bytes.
895
-	 *   * component - optional, a string containing the type of object, such
896
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
897
-	 *     the Content-Type header.
898
-	 *
899
-	 * Note that the etag is optional, but it's highly encouraged to return for
900
-	 * speed reasons.
901
-	 *
902
-	 * The calendardata is also optional. If it's not returned
903
-	 * 'getCalendarObject' will be called later, which *is* expected to return
904
-	 * calendardata.
905
-	 *
906
-	 * If neither etag or size are specified, the calendardata will be
907
-	 * used/fetched to determine these numbers. If both are specified the
908
-	 * amount of times this is needed is reduced by a great degree.
909
-	 *
910
-	 * @param mixed $id
911
-	 * @param int $calendarType
912
-	 * @return array
913
-	 */
914
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
915
-		$query = $this->db->getQueryBuilder();
916
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917
-			->from('calendarobjects')
918
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
919
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
920
-		$stmt = $query->execute();
921
-
922
-		$result = [];
923
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924
-			$result[] = [
925
-				'id'           => $row['id'],
926
-				'uri'          => $row['uri'],
927
-				'lastmodified' => $row['lastmodified'],
928
-				'etag'         => '"' . $row['etag'] . '"',
929
-				'calendarid'   => $row['calendarid'],
930
-				'size'         => (int)$row['size'],
931
-				'component'    => strtolower($row['componenttype']),
932
-				'classification'=> (int)$row['classification']
933
-			];
934
-		}
935
-
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * Returns information from a single calendar object, based on it's object
941
-	 * uri.
942
-	 *
943
-	 * The object uri is only the basename, or filename and not a full path.
944
-	 *
945
-	 * The returned array must have the same keys as getCalendarObjects. The
946
-	 * 'calendardata' object is required here though, while it's not required
947
-	 * for getCalendarObjects.
948
-	 *
949
-	 * This method must return null if the object did not exist.
950
-	 *
951
-	 * @param mixed $id
952
-	 * @param string $objectUri
953
-	 * @param int $calendarType
954
-	 * @return array|null
955
-	 */
956
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
957
-		$query = $this->db->getQueryBuilder();
958
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959
-			->from('calendarobjects')
960
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
961
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
962
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
963
-		$stmt = $query->execute();
964
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
965
-
966
-		if(!$row) {
967
-			return null;
968
-		}
969
-
970
-		return [
971
-			'id'            => $row['id'],
972
-			'uri'           => $row['uri'],
973
-			'lastmodified'  => $row['lastmodified'],
974
-			'etag'          => '"' . $row['etag'] . '"',
975
-			'calendarid'    => $row['calendarid'],
976
-			'size'          => (int)$row['size'],
977
-			'calendardata'  => $this->readBlob($row['calendardata']),
978
-			'component'     => strtolower($row['componenttype']),
979
-			'classification'=> (int)$row['classification']
980
-		];
981
-	}
982
-
983
-	/**
984
-	 * Returns a list of calendar objects.
985
-	 *
986
-	 * This method should work identical to getCalendarObject, but instead
987
-	 * return all the calendar objects in the list as an array.
988
-	 *
989
-	 * If the backend supports this, it may allow for some speed-ups.
990
-	 *
991
-	 * @param mixed $calendarId
992
-	 * @param string[] $uris
993
-	 * @param int $calendarType
994
-	 * @return array
995
-	 */
996
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
997
-		if (empty($uris)) {
998
-			return [];
999
-		}
1000
-
1001
-		$chunks = array_chunk($uris, 100);
1002
-		$objects = [];
1003
-
1004
-		$query = $this->db->getQueryBuilder();
1005
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1006
-			->from('calendarobjects')
1007
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1008
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1009
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1010
-
1011
-		foreach ($chunks as $uris) {
1012
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1013
-			$result = $query->execute();
1014
-
1015
-			while ($row = $result->fetch()) {
1016
-				$objects[] = [
1017
-					'id'           => $row['id'],
1018
-					'uri'          => $row['uri'],
1019
-					'lastmodified' => $row['lastmodified'],
1020
-					'etag'         => '"' . $row['etag'] . '"',
1021
-					'calendarid'   => $row['calendarid'],
1022
-					'size'         => (int)$row['size'],
1023
-					'calendardata' => $this->readBlob($row['calendardata']),
1024
-					'component'    => strtolower($row['componenttype']),
1025
-					'classification' => (int)$row['classification']
1026
-				];
1027
-			}
1028
-			$result->closeCursor();
1029
-		}
1030
-
1031
-		return $objects;
1032
-	}
1033
-
1034
-	/**
1035
-	 * Creates a new calendar object.
1036
-	 *
1037
-	 * The object uri is only the basename, or filename and not a full path.
1038
-	 *
1039
-	 * It is possible return an etag from this function, which will be used in
1040
-	 * the response to this PUT request. Note that the ETag must be surrounded
1041
-	 * by double-quotes.
1042
-	 *
1043
-	 * However, you should only really return this ETag if you don't mangle the
1044
-	 * calendar-data. If the result of a subsequent GET to this object is not
1045
-	 * the exact same as this request body, you should omit the ETag.
1046
-	 *
1047
-	 * @param mixed $calendarId
1048
-	 * @param string $objectUri
1049
-	 * @param string $calendarData
1050
-	 * @param int $calendarType
1051
-	 * @return string
1052
-	 */
1053
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1054
-		$extraData = $this->getDenormalizedData($calendarData);
1055
-
1056
-		$q = $this->db->getQueryBuilder();
1057
-		$q->select($q->func()->count('*'))
1058
-			->from('calendarobjects')
1059
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1060
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1061
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1062
-
1063
-		$result = $q->execute();
1064
-		$count = (int) $result->fetchColumn();
1065
-		$result->closeCursor();
1066
-
1067
-		if ($count !== 0) {
1068
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1069
-		}
1070
-
1071
-		$query = $this->db->getQueryBuilder();
1072
-		$query->insert('calendarobjects')
1073
-			->values([
1074
-				'calendarid' => $query->createNamedParameter($calendarId),
1075
-				'uri' => $query->createNamedParameter($objectUri),
1076
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1077
-				'lastmodified' => $query->createNamedParameter(time()),
1078
-				'etag' => $query->createNamedParameter($extraData['etag']),
1079
-				'size' => $query->createNamedParameter($extraData['size']),
1080
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1081
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1082
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1083
-				'classification' => $query->createNamedParameter($extraData['classification']),
1084
-				'uid' => $query->createNamedParameter($extraData['uid']),
1085
-				'calendartype' => $query->createNamedParameter($calendarType),
1086
-			])
1087
-			->execute();
1088
-
1089
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1090
-
1091
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1092
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1093
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1094
-				[
1095
-					'calendarId' => $calendarId,
1096
-					'calendarData' => $this->getCalendarById($calendarId),
1097
-					'shares' => $this->getShares($calendarId),
1098
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1099
-				]
1100
-			));
1101
-		} else {
1102
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1103
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1104
-				[
1105
-					'subscriptionId' => $calendarId,
1106
-					'calendarData' => $this->getCalendarById($calendarId),
1107
-					'shares' => $this->getShares($calendarId),
1108
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1109
-				]
1110
-			));
1111
-		}
1112
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1113
-
1114
-		return '"' . $extraData['etag'] . '"';
1115
-	}
1116
-
1117
-	/**
1118
-	 * Updates an existing calendarobject, based on it's uri.
1119
-	 *
1120
-	 * The object uri is only the basename, or filename and not a full path.
1121
-	 *
1122
-	 * It is possible return an etag from this function, which will be used in
1123
-	 * the response to this PUT request. Note that the ETag must be surrounded
1124
-	 * by double-quotes.
1125
-	 *
1126
-	 * However, you should only really return this ETag if you don't mangle the
1127
-	 * calendar-data. If the result of a subsequent GET to this object is not
1128
-	 * the exact same as this request body, you should omit the ETag.
1129
-	 *
1130
-	 * @param mixed $calendarId
1131
-	 * @param string $objectUri
1132
-	 * @param string $calendarData
1133
-	 * @param int $calendarType
1134
-	 * @return string
1135
-	 */
1136
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1137
-		$extraData = $this->getDenormalizedData($calendarData);
1138
-
1139
-		$query = $this->db->getQueryBuilder();
1140
-		$query->update('calendarobjects')
1141
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1142
-				->set('lastmodified', $query->createNamedParameter(time()))
1143
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1144
-				->set('size', $query->createNamedParameter($extraData['size']))
1145
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1146
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1147
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1148
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1149
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1150
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1151
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1152
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1153
-			->execute();
1154
-
1155
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1156
-
1157
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1158
-		if (is_array($data)) {
1159
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1160
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1161
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1162
-					[
1163
-						'calendarId' => $calendarId,
1164
-						'calendarData' => $this->getCalendarById($calendarId),
1165
-						'shares' => $this->getShares($calendarId),
1166
-						'objectData' => $data,
1167
-					]
1168
-				));
1169
-			} else {
1170
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1171
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1172
-					[
1173
-						'subscriptionId' => $calendarId,
1174
-						'calendarData' => $this->getCalendarById($calendarId),
1175
-						'shares' => $this->getShares($calendarId),
1176
-						'objectData' => $data,
1177
-					]
1178
-				));
1179
-			}
1180
-		}
1181
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1182
-
1183
-		return '"' . $extraData['etag'] . '"';
1184
-	}
1185
-
1186
-	/**
1187
-	 * @param int $calendarObjectId
1188
-	 * @param int $classification
1189
-	 */
1190
-	public function setClassification($calendarObjectId, $classification) {
1191
-		if (!in_array($classification, [
1192
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1193
-		])) {
1194
-			throw new \InvalidArgumentException();
1195
-		}
1196
-		$query = $this->db->getQueryBuilder();
1197
-		$query->update('calendarobjects')
1198
-			->set('classification', $query->createNamedParameter($classification))
1199
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1200
-			->execute();
1201
-	}
1202
-
1203
-	/**
1204
-	 * Deletes an existing calendar object.
1205
-	 *
1206
-	 * The object uri is only the basename, or filename and not a full path.
1207
-	 *
1208
-	 * @param mixed $calendarId
1209
-	 * @param string $objectUri
1210
-	 * @param int $calendarType
1211
-	 * @return void
1212
-	 */
1213
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1214
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1215
-		if (is_array($data)) {
1216
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1217
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1218
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1219
-					[
1220
-						'calendarId' => $calendarId,
1221
-						'calendarData' => $this->getCalendarById($calendarId),
1222
-						'shares' => $this->getShares($calendarId),
1223
-						'objectData' => $data,
1224
-					]
1225
-				));
1226
-			} else {
1227
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1228
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1229
-					[
1230
-						'subscriptionId' => $calendarId,
1231
-						'calendarData' => $this->getCalendarById($calendarId),
1232
-						'shares' => $this->getShares($calendarId),
1233
-						'objectData' => $data,
1234
-					]
1235
-				));
1236
-			}
1237
-		}
1238
-
1239
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1240
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1241
-
1242
-		$this->purgeProperties($calendarId, $data['id'], $calendarType);
1243
-
1244
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1245
-	}
1246
-
1247
-	/**
1248
-	 * Performs a calendar-query on the contents of this calendar.
1249
-	 *
1250
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1251
-	 * calendar-query it is possible for a client to request a specific set of
1252
-	 * object, based on contents of iCalendar properties, date-ranges and
1253
-	 * iCalendar component types (VTODO, VEVENT).
1254
-	 *
1255
-	 * This method should just return a list of (relative) urls that match this
1256
-	 * query.
1257
-	 *
1258
-	 * The list of filters are specified as an array. The exact array is
1259
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1260
-	 *
1261
-	 * Note that it is extremely likely that getCalendarObject for every path
1262
-	 * returned from this method will be called almost immediately after. You
1263
-	 * may want to anticipate this to speed up these requests.
1264
-	 *
1265
-	 * This method provides a default implementation, which parses *all* the
1266
-	 * iCalendar objects in the specified calendar.
1267
-	 *
1268
-	 * This default may well be good enough for personal use, and calendars
1269
-	 * that aren't very large. But if you anticipate high usage, big calendars
1270
-	 * or high loads, you are strongly advised to optimize certain paths.
1271
-	 *
1272
-	 * The best way to do so is override this method and to optimize
1273
-	 * specifically for 'common filters'.
1274
-	 *
1275
-	 * Requests that are extremely common are:
1276
-	 *   * requests for just VEVENTS
1277
-	 *   * requests for just VTODO
1278
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1279
-	 *
1280
-	 * ..and combinations of these requests. It may not be worth it to try to
1281
-	 * handle every possible situation and just rely on the (relatively
1282
-	 * easy to use) CalendarQueryValidator to handle the rest.
1283
-	 *
1284
-	 * Note that especially time-range-filters may be difficult to parse. A
1285
-	 * time-range filter specified on a VEVENT must for instance also handle
1286
-	 * recurrence rules correctly.
1287
-	 * A good example of how to interprete all these filters can also simply
1288
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1289
-	 * as possible, so it gives you a good idea on what type of stuff you need
1290
-	 * to think of.
1291
-	 *
1292
-	 * @param mixed $id
1293
-	 * @param array $filters
1294
-	 * @param int $calendarType
1295
-	 * @return array
1296
-	 */
1297
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1298
-		$componentType = null;
1299
-		$requirePostFilter = true;
1300
-		$timeRange = null;
1301
-
1302
-		// if no filters were specified, we don't need to filter after a query
1303
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1304
-			$requirePostFilter = false;
1305
-		}
1306
-
1307
-		// Figuring out if there's a component filter
1308
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1309
-			$componentType = $filters['comp-filters'][0]['name'];
1310
-
1311
-			// Checking if we need post-filters
1312
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1313
-				$requirePostFilter = false;
1314
-			}
1315
-			// There was a time-range filter
1316
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1317
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1318
-
1319
-				// If start time OR the end time is not specified, we can do a
1320
-				// 100% accurate mysql query.
1321
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1322
-					$requirePostFilter = false;
1323
-				}
1324
-			}
1325
-
1326
-		}
1327
-		$columns = ['uri'];
1328
-		if ($requirePostFilter) {
1329
-			$columns = ['uri', 'calendardata'];
1330
-		}
1331
-		$query = $this->db->getQueryBuilder();
1332
-		$query->select($columns)
1333
-			->from('calendarobjects')
1334
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1335
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1336
-
1337
-		if ($componentType) {
1338
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1339
-		}
1340
-
1341
-		if ($timeRange && $timeRange['start']) {
1342
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1343
-		}
1344
-		if ($timeRange && $timeRange['end']) {
1345
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1346
-		}
1347
-
1348
-		$stmt = $query->execute();
1349
-
1350
-		$result = [];
1351
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1352
-			if ($requirePostFilter) {
1353
-				// validateFilterForObject will parse the calendar data
1354
-				// catch parsing errors
1355
-				try {
1356
-					$matches = $this->validateFilterForObject($row, $filters);
1357
-				} catch(ParseException $ex) {
1358
-					$this->logger->logException($ex, [
1359
-						'app' => 'dav',
1360
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1361
-					]);
1362
-					continue;
1363
-				} catch (InvalidDataException $ex) {
1364
-					$this->logger->logException($ex, [
1365
-						'app' => 'dav',
1366
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1367
-					]);
1368
-					continue;
1369
-				}
1370
-
1371
-				if (!$matches) {
1372
-					continue;
1373
-				}
1374
-			}
1375
-			$result[] = $row['uri'];
1376
-		}
1377
-
1378
-		return $result;
1379
-	}
1380
-
1381
-	/**
1382
-	 * custom Nextcloud search extension for CalDAV
1383
-	 *
1384
-	 * TODO - this should optionally cover cached calendar objects as well
1385
-	 *
1386
-	 * @param string $principalUri
1387
-	 * @param array $filters
1388
-	 * @param integer|null $limit
1389
-	 * @param integer|null $offset
1390
-	 * @return array
1391
-	 */
1392
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1393
-		$calendars = $this->getCalendarsForUser($principalUri);
1394
-		$ownCalendars = [];
1395
-		$sharedCalendars = [];
1396
-
1397
-		$uriMapper = [];
1398
-
1399
-		foreach($calendars as $calendar) {
1400
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1401
-				$ownCalendars[] = $calendar['id'];
1402
-			} else {
1403
-				$sharedCalendars[] = $calendar['id'];
1404
-			}
1405
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1406
-		}
1407
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1408
-			return [];
1409
-		}
1410
-
1411
-		$query = $this->db->getQueryBuilder();
1412
-		// Calendar id expressions
1413
-		$calendarExpressions = [];
1414
-		foreach($ownCalendars as $id) {
1415
-			$calendarExpressions[] = $query->expr()->andX(
1416
-				$query->expr()->eq('c.calendarid',
1417
-					$query->createNamedParameter($id)),
1418
-				$query->expr()->eq('c.calendartype',
1419
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
-		}
1421
-		foreach($sharedCalendars as $id) {
1422
-			$calendarExpressions[] = $query->expr()->andX(
1423
-				$query->expr()->eq('c.calendarid',
1424
-					$query->createNamedParameter($id)),
1425
-				$query->expr()->eq('c.classification',
1426
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1427
-				$query->expr()->eq('c.calendartype',
1428
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1429
-		}
1430
-
1431
-		if (count($calendarExpressions) === 1) {
1432
-			$calExpr = $calendarExpressions[0];
1433
-		} else {
1434
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1435
-		}
1436
-
1437
-		// Component expressions
1438
-		$compExpressions = [];
1439
-		foreach($filters['comps'] as $comp) {
1440
-			$compExpressions[] = $query->expr()
1441
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1442
-		}
1443
-
1444
-		if (count($compExpressions) === 1) {
1445
-			$compExpr = $compExpressions[0];
1446
-		} else {
1447
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1448
-		}
1449
-
1450
-		if (!isset($filters['props'])) {
1451
-			$filters['props'] = [];
1452
-		}
1453
-		if (!isset($filters['params'])) {
1454
-			$filters['params'] = [];
1455
-		}
1456
-
1457
-		$propParamExpressions = [];
1458
-		foreach($filters['props'] as $prop) {
1459
-			$propParamExpressions[] = $query->expr()->andX(
1460
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1461
-				$query->expr()->isNull('i.parameter')
1462
-			);
1463
-		}
1464
-		foreach($filters['params'] as $param) {
1465
-			$propParamExpressions[] = $query->expr()->andX(
1466
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1467
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1468
-			);
1469
-		}
1470
-
1471
-		if (count($propParamExpressions) === 1) {
1472
-			$propParamExpr = $propParamExpressions[0];
1473
-		} else {
1474
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1475
-		}
1476
-
1477
-		$query->select(['c.calendarid', 'c.uri'])
1478
-			->from($this->dbObjectPropertiesTable, 'i')
1479
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1480
-			->where($calExpr)
1481
-			->andWhere($compExpr)
1482
-			->andWhere($propParamExpr)
1483
-			->andWhere($query->expr()->iLike('i.value',
1484
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1485
-
1486
-		if ($offset) {
1487
-			$query->setFirstResult($offset);
1488
-		}
1489
-		if ($limit) {
1490
-			$query->setMaxResults($limit);
1491
-		}
1492
-
1493
-		$stmt = $query->execute();
1494
-
1495
-		$result = [];
1496
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1497
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1498
-			if (!in_array($path, $result)) {
1499
-				$result[] = $path;
1500
-			}
1501
-		}
1502
-
1503
-		return $result;
1504
-	}
1505
-
1506
-	/**
1507
-	 * used for Nextcloud's calendar API
1508
-	 *
1509
-	 * @param array $calendarInfo
1510
-	 * @param string $pattern
1511
-	 * @param array $searchProperties
1512
-	 * @param array $options
1513
-	 * @param integer|null $limit
1514
-	 * @param integer|null $offset
1515
-	 *
1516
-	 * @return array
1517
-	 */
1518
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1519
-						   array $options, $limit, $offset) {
1520
-		$outerQuery = $this->db->getQueryBuilder();
1521
-		$innerQuery = $this->db->getQueryBuilder();
1522
-
1523
-		$innerQuery->selectDistinct('op.objectid')
1524
-			->from($this->dbObjectPropertiesTable, 'op')
1525
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1526
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1527
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1528
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1529
-
1530
-		// only return public items for shared calendars for now
1531
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1532
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1533
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1534
-		}
1535
-
1536
-		$or = $innerQuery->expr()->orX();
1537
-		foreach($searchProperties as $searchProperty) {
1538
-			$or->add($innerQuery->expr()->eq('op.name',
1539
-				$outerQuery->createNamedParameter($searchProperty)));
1540
-		}
1541
-		$innerQuery->andWhere($or);
1542
-
1543
-		if ($pattern !== '') {
1544
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1545
-				$outerQuery->createNamedParameter('%' .
1546
-					$this->db->escapeLikeParameter($pattern) . '%')));
1547
-		}
1548
-
1549
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1550
-			->from('calendarobjects', 'c');
1551
-
1552
-		if (isset($options['timerange'])) {
1553
-			if (isset($options['timerange']['start'])) {
1554
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1555
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1556
-
1557
-			}
1558
-			if (isset($options['timerange']['end'])) {
1559
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1560
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1561
-			}
1562
-		}
1563
-
1564
-		if (isset($options['types'])) {
1565
-			$or = $outerQuery->expr()->orX();
1566
-			foreach($options['types'] as $type) {
1567
-				$or->add($outerQuery->expr()->eq('componenttype',
1568
-					$outerQuery->createNamedParameter($type)));
1569
-			}
1570
-			$outerQuery->andWhere($or);
1571
-		}
1572
-
1573
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1574
-			$outerQuery->createFunction($innerQuery->getSQL())));
1575
-
1576
-		if ($offset) {
1577
-			$outerQuery->setFirstResult($offset);
1578
-		}
1579
-		if ($limit) {
1580
-			$outerQuery->setMaxResults($limit);
1581
-		}
1582
-
1583
-		$result = $outerQuery->execute();
1584
-		$calendarObjects = $result->fetchAll();
1585
-
1586
-		return array_map(function($o) {
1587
-			$calendarData = Reader::read($o['calendardata']);
1588
-			$comps = $calendarData->getComponents();
1589
-			$objects = [];
1590
-			$timezones = [];
1591
-			foreach($comps as $comp) {
1592
-				if ($comp instanceof VTimeZone) {
1593
-					$timezones[] = $comp;
1594
-				} else {
1595
-					$objects[] = $comp;
1596
-				}
1597
-			}
1598
-
1599
-			return [
1600
-				'id' => $o['id'],
1601
-				'type' => $o['componenttype'],
1602
-				'uid' => $o['uid'],
1603
-				'uri' => $o['uri'],
1604
-				'objects' => array_map(function($c) {
1605
-					return $this->transformSearchData($c);
1606
-				}, $objects),
1607
-				'timezones' => array_map(function($c) {
1608
-					return $this->transformSearchData($c);
1609
-				}, $timezones),
1610
-			];
1611
-		}, $calendarObjects);
1612
-	}
1613
-
1614
-	/**
1615
-	 * @param Component $comp
1616
-	 * @return array
1617
-	 */
1618
-	private function transformSearchData(Component $comp) {
1619
-		$data = [];
1620
-		/** @var Component[] $subComponents */
1621
-		$subComponents = $comp->getComponents();
1622
-		/** @var Property[] $properties */
1623
-		$properties = array_filter($comp->children(), function($c) {
1624
-			return $c instanceof Property;
1625
-		});
1626
-		$validationRules = $comp->getValidationRules();
1627
-
1628
-		foreach($subComponents as $subComponent) {
1629
-			$name = $subComponent->name;
1630
-			if (!isset($data[$name])) {
1631
-				$data[$name] = [];
1632
-			}
1633
-			$data[$name][] = $this->transformSearchData($subComponent);
1634
-		}
1635
-
1636
-		foreach($properties as $property) {
1637
-			$name = $property->name;
1638
-			if (!isset($validationRules[$name])) {
1639
-				$validationRules[$name] = '*';
1640
-			}
1641
-
1642
-			$rule = $validationRules[$property->name];
1643
-			if ($rule === '+' || $rule === '*') { // multiple
1644
-				if (!isset($data[$name])) {
1645
-					$data[$name] = [];
1646
-				}
1647
-
1648
-				$data[$name][] = $this->transformSearchProperty($property);
1649
-			} else { // once
1650
-				$data[$name] = $this->transformSearchProperty($property);
1651
-			}
1652
-		}
1653
-
1654
-		return $data;
1655
-	}
1656
-
1657
-	/**
1658
-	 * @param Property $prop
1659
-	 * @return array
1660
-	 */
1661
-	private function transformSearchProperty(Property $prop) {
1662
-		// No need to check Date, as it extends DateTime
1663
-		if ($prop instanceof Property\ICalendar\DateTime) {
1664
-			$value = $prop->getDateTime();
1665
-		} else {
1666
-			$value = $prop->getValue();
1667
-		}
1668
-
1669
-		return [
1670
-			$value,
1671
-			$prop->parameters()
1672
-		];
1673
-	}
1674
-
1675
-	/**
1676
-	 * Searches through all of a users calendars and calendar objects to find
1677
-	 * an object with a specific UID.
1678
-	 *
1679
-	 * This method should return the path to this object, relative to the
1680
-	 * calendar home, so this path usually only contains two parts:
1681
-	 *
1682
-	 * calendarpath/objectpath.ics
1683
-	 *
1684
-	 * If the uid is not found, return null.
1685
-	 *
1686
-	 * This method should only consider * objects that the principal owns, so
1687
-	 * any calendars owned by other principals that also appear in this
1688
-	 * collection should be ignored.
1689
-	 *
1690
-	 * @param string $principalUri
1691
-	 * @param string $uid
1692
-	 * @return string|null
1693
-	 */
1694
-	function getCalendarObjectByUID($principalUri, $uid) {
1695
-
1696
-		$query = $this->db->getQueryBuilder();
1697
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1698
-			->from('calendarobjects', 'co')
1699
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1700
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1701
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1702
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1703
-
1704
-		$stmt = $query->execute();
1705
-
1706
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1707
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1708
-		}
1709
-
1710
-		return null;
1711
-	}
1712
-
1713
-	/**
1714
-	 * The getChanges method returns all the changes that have happened, since
1715
-	 * the specified syncToken in the specified calendar.
1716
-	 *
1717
-	 * This function should return an array, such as the following:
1718
-	 *
1719
-	 * [
1720
-	 *   'syncToken' => 'The current synctoken',
1721
-	 *   'added'   => [
1722
-	 *      'new.txt',
1723
-	 *   ],
1724
-	 *   'modified'   => [
1725
-	 *      'modified.txt',
1726
-	 *   ],
1727
-	 *   'deleted' => [
1728
-	 *      'foo.php.bak',
1729
-	 *      'old.txt'
1730
-	 *   ]
1731
-	 * );
1732
-	 *
1733
-	 * The returned syncToken property should reflect the *current* syncToken
1734
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1735
-	 * property This is * needed here too, to ensure the operation is atomic.
1736
-	 *
1737
-	 * If the $syncToken argument is specified as null, this is an initial
1738
-	 * sync, and all members should be reported.
1739
-	 *
1740
-	 * The modified property is an array of nodenames that have changed since
1741
-	 * the last token.
1742
-	 *
1743
-	 * The deleted property is an array with nodenames, that have been deleted
1744
-	 * from collection.
1745
-	 *
1746
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1747
-	 * 1, you only have to report changes that happened only directly in
1748
-	 * immediate descendants. If it's 2, it should also include changes from
1749
-	 * the nodes below the child collections. (grandchildren)
1750
-	 *
1751
-	 * The $limit argument allows a client to specify how many results should
1752
-	 * be returned at most. If the limit is not specified, it should be treated
1753
-	 * as infinite.
1754
-	 *
1755
-	 * If the limit (infinite or not) is higher than you're willing to return,
1756
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1757
-	 *
1758
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1759
-	 * return null.
1760
-	 *
1761
-	 * The limit is 'suggestive'. You are free to ignore it.
1762
-	 *
1763
-	 * @param string $calendarId
1764
-	 * @param string $syncToken
1765
-	 * @param int $syncLevel
1766
-	 * @param int $limit
1767
-	 * @param int $calendarType
1768
-	 * @return array
1769
-	 */
1770
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1771
-		// Current synctoken
1772
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1773
-		$stmt->execute([ $calendarId ]);
1774
-		$currentToken = $stmt->fetchColumn(0);
1775
-
1776
-		if (is_null($currentToken)) {
1777
-			return null;
1778
-		}
1779
-
1780
-		$result = [
1781
-			'syncToken' => $currentToken,
1782
-			'added'     => [],
1783
-			'modified'  => [],
1784
-			'deleted'   => [],
1785
-		];
1786
-
1787
-		if ($syncToken) {
1788
-
1789
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1790
-			if ($limit>0) {
1791
-				$query.= " LIMIT " . (int)$limit;
1792
-			}
1793
-
1794
-			// Fetching all changes
1795
-			$stmt = $this->db->prepare($query);
1796
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1797
-
1798
-			$changes = [];
1799
-
1800
-			// This loop ensures that any duplicates are overwritten, only the
1801
-			// last change on a node is relevant.
1802
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1803
-
1804
-				$changes[$row['uri']] = $row['operation'];
1805
-
1806
-			}
1807
-
1808
-			foreach($changes as $uri => $operation) {
1809
-
1810
-				switch($operation) {
1811
-					case 1 :
1812
-						$result['added'][] = $uri;
1813
-						break;
1814
-					case 2 :
1815
-						$result['modified'][] = $uri;
1816
-						break;
1817
-					case 3 :
1818
-						$result['deleted'][] = $uri;
1819
-						break;
1820
-				}
1821
-
1822
-			}
1823
-		} else {
1824
-			// No synctoken supplied, this is the initial sync.
1825
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1826
-			$stmt = $this->db->prepare($query);
1827
-			$stmt->execute([$calendarId, $calendarType]);
1828
-
1829
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1830
-		}
1831
-		return $result;
1832
-
1833
-	}
1834
-
1835
-	/**
1836
-	 * Returns a list of subscriptions for a principal.
1837
-	 *
1838
-	 * Every subscription is an array with the following keys:
1839
-	 *  * id, a unique id that will be used by other functions to modify the
1840
-	 *    subscription. This can be the same as the uri or a database key.
1841
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1842
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1843
-	 *    principalUri passed to this method.
1844
-	 *
1845
-	 * Furthermore, all the subscription info must be returned too:
1846
-	 *
1847
-	 * 1. {DAV:}displayname
1848
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1849
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1850
-	 *    should not be stripped).
1851
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1852
-	 *    should not be stripped).
1853
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1854
-	 *    attachments should not be stripped).
1855
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1856
-	 *     Sabre\DAV\Property\Href).
1857
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1858
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1859
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1860
-	 *    (should just be an instance of
1861
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1862
-	 *    default components).
1863
-	 *
1864
-	 * @param string $principalUri
1865
-	 * @return array
1866
-	 */
1867
-	function getSubscriptionsForUser($principalUri) {
1868
-		$fields = array_values($this->subscriptionPropertyMap);
1869
-		$fields[] = 'id';
1870
-		$fields[] = 'uri';
1871
-		$fields[] = 'source';
1872
-		$fields[] = 'principaluri';
1873
-		$fields[] = 'lastmodified';
1874
-		$fields[] = 'synctoken';
1875
-
1876
-		$query = $this->db->getQueryBuilder();
1877
-		$query->select($fields)
1878
-			->from('calendarsubscriptions')
1879
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1880
-			->orderBy('calendarorder', 'asc');
1881
-		$stmt =$query->execute();
1882
-
1883
-		$subscriptions = [];
1884
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1885
-
1886
-			$subscription = [
1887
-				'id'           => $row['id'],
1888
-				'uri'          => $row['uri'],
1889
-				'principaluri' => $row['principaluri'],
1890
-				'source'       => $row['source'],
1891
-				'lastmodified' => $row['lastmodified'],
1892
-
1893
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1894
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1895
-			];
1896
-
1897
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1898
-				if (!is_null($row[$dbName])) {
1899
-					$subscription[$xmlName] = $row[$dbName];
1900
-				}
1901
-			}
1902
-
1903
-			$subscriptions[] = $subscription;
1904
-
1905
-		}
1906
-
1907
-		return $subscriptions;
1908
-	}
1909
-
1910
-	/**
1911
-	 * Creates a new subscription for a principal.
1912
-	 *
1913
-	 * If the creation was a success, an id must be returned that can be used to reference
1914
-	 * this subscription in other methods, such as updateSubscription.
1915
-	 *
1916
-	 * @param string $principalUri
1917
-	 * @param string $uri
1918
-	 * @param array $properties
1919
-	 * @return mixed
1920
-	 */
1921
-	function createSubscription($principalUri, $uri, array $properties) {
1922
-
1923
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1924
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1925
-		}
1926
-
1927
-		$values = [
1928
-			'principaluri' => $principalUri,
1929
-			'uri'          => $uri,
1930
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1931
-			'lastmodified' => time(),
1932
-		];
1933
-
1934
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1935
-
1936
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1937
-			if (array_key_exists($xmlName, $properties)) {
1938
-					$values[$dbName] = $properties[$xmlName];
1939
-					if (in_array($dbName, $propertiesBoolean)) {
1940
-						$values[$dbName] = true;
1941
-				}
1942
-			}
1943
-		}
1944
-
1945
-		$valuesToInsert = array();
1946
-
1947
-		$query = $this->db->getQueryBuilder();
1948
-
1949
-		foreach (array_keys($values) as $name) {
1950
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1951
-		}
1952
-
1953
-		$query->insert('calendarsubscriptions')
1954
-			->values($valuesToInsert)
1955
-			->execute();
1956
-
1957
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1958
-
1959
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1960
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1961
-			[
1962
-				'subscriptionId' => $subscriptionId,
1963
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1964
-			]));
1965
-
1966
-		return $subscriptionId;
1967
-	}
1968
-
1969
-	/**
1970
-	 * Updates a subscription
1971
-	 *
1972
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1973
-	 * To do the actual updates, you must tell this object which properties
1974
-	 * you're going to process with the handle() method.
1975
-	 *
1976
-	 * Calling the handle method is like telling the PropPatch object "I
1977
-	 * promise I can handle updating this property".
1978
-	 *
1979
-	 * Read the PropPatch documentation for more info and examples.
1980
-	 *
1981
-	 * @param mixed $subscriptionId
1982
-	 * @param PropPatch $propPatch
1983
-	 * @return void
1984
-	 */
1985
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1986
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1987
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1988
-
1989
-		/**
1990
-		 * @suppress SqlInjectionChecker
1991
-		 */
1992
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1993
-
1994
-			$newValues = [];
1995
-
1996
-			foreach($mutations as $propertyName=>$propertyValue) {
1997
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1998
-					$newValues['source'] = $propertyValue->getHref();
1999
-				} else {
2000
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2001
-					$newValues[$fieldName] = $propertyValue;
2002
-				}
2003
-			}
2004
-
2005
-			$query = $this->db->getQueryBuilder();
2006
-			$query->update('calendarsubscriptions')
2007
-				->set('lastmodified', $query->createNamedParameter(time()));
2008
-			foreach($newValues as $fieldName=>$value) {
2009
-				$query->set($fieldName, $query->createNamedParameter($value));
2010
-			}
2011
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2012
-				->execute();
2013
-
2014
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2015
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2016
-				[
2017
-					'subscriptionId' => $subscriptionId,
2018
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2019
-					'propertyMutations' => $mutations,
2020
-				]));
2021
-
2022
-			return true;
2023
-
2024
-		});
2025
-	}
2026
-
2027
-	/**
2028
-	 * Deletes a subscription.
2029
-	 *
2030
-	 * @param mixed $subscriptionId
2031
-	 * @return void
2032
-	 */
2033
-	function deleteSubscription($subscriptionId) {
2034
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2035
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2036
-			[
2037
-				'subscriptionId' => $subscriptionId,
2038
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2039
-			]));
2040
-
2041
-		$query = $this->db->getQueryBuilder();
2042
-		$query->delete('calendarsubscriptions')
2043
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2044
-			->execute();
2045
-
2046
-		$query = $this->db->getQueryBuilder();
2047
-		$query->delete('calendarobjects')
2048
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2049
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2050
-			->execute();
2051
-
2052
-		$query->delete('calendarchanges')
2053
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2054
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2055
-			->execute();
2056
-
2057
-		$query->delete($this->dbObjectPropertiesTable)
2058
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2059
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2060
-			->execute();
2061
-	}
2062
-
2063
-	/**
2064
-	 * Returns a single scheduling object for the inbox collection.
2065
-	 *
2066
-	 * The returned array should contain the following elements:
2067
-	 *   * uri - A unique basename for the object. This will be used to
2068
-	 *           construct a full uri.
2069
-	 *   * calendardata - The iCalendar object
2070
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2071
-	 *                    timestamp, or a PHP DateTime object.
2072
-	 *   * etag - A unique token that must change if the object changed.
2073
-	 *   * size - The size of the object, in bytes.
2074
-	 *
2075
-	 * @param string $principalUri
2076
-	 * @param string $objectUri
2077
-	 * @return array
2078
-	 */
2079
-	function getSchedulingObject($principalUri, $objectUri) {
2080
-		$query = $this->db->getQueryBuilder();
2081
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2082
-			->from('schedulingobjects')
2083
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2084
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2085
-			->execute();
2086
-
2087
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2088
-
2089
-		if(!$row) {
2090
-			return null;
2091
-		}
2092
-
2093
-		return [
2094
-				'uri'          => $row['uri'],
2095
-				'calendardata' => $row['calendardata'],
2096
-				'lastmodified' => $row['lastmodified'],
2097
-				'etag'         => '"' . $row['etag'] . '"',
2098
-				'size'         => (int)$row['size'],
2099
-		];
2100
-	}
2101
-
2102
-	/**
2103
-	 * Returns all scheduling objects for the inbox collection.
2104
-	 *
2105
-	 * These objects should be returned as an array. Every item in the array
2106
-	 * should follow the same structure as returned from getSchedulingObject.
2107
-	 *
2108
-	 * The main difference is that 'calendardata' is optional.
2109
-	 *
2110
-	 * @param string $principalUri
2111
-	 * @return array
2112
-	 */
2113
-	function getSchedulingObjects($principalUri) {
2114
-		$query = $this->db->getQueryBuilder();
2115
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2116
-				->from('schedulingobjects')
2117
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2118
-				->execute();
2119
-
2120
-		$result = [];
2121
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2122
-			$result[] = [
2123
-					'calendardata' => $row['calendardata'],
2124
-					'uri'          => $row['uri'],
2125
-					'lastmodified' => $row['lastmodified'],
2126
-					'etag'         => '"' . $row['etag'] . '"',
2127
-					'size'         => (int)$row['size'],
2128
-			];
2129
-		}
2130
-
2131
-		return $result;
2132
-	}
2133
-
2134
-	/**
2135
-	 * Deletes a scheduling object from the inbox collection.
2136
-	 *
2137
-	 * @param string $principalUri
2138
-	 * @param string $objectUri
2139
-	 * @return void
2140
-	 */
2141
-	function deleteSchedulingObject($principalUri, $objectUri) {
2142
-		$query = $this->db->getQueryBuilder();
2143
-		$query->delete('schedulingobjects')
2144
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2145
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2146
-				->execute();
2147
-	}
2148
-
2149
-	/**
2150
-	 * Creates a new scheduling object. This should land in a users' inbox.
2151
-	 *
2152
-	 * @param string $principalUri
2153
-	 * @param string $objectUri
2154
-	 * @param string $objectData
2155
-	 * @return void
2156
-	 */
2157
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2158
-		$query = $this->db->getQueryBuilder();
2159
-		$query->insert('schedulingobjects')
2160
-			->values([
2161
-				'principaluri' => $query->createNamedParameter($principalUri),
2162
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2163
-				'uri' => $query->createNamedParameter($objectUri),
2164
-				'lastmodified' => $query->createNamedParameter(time()),
2165
-				'etag' => $query->createNamedParameter(md5($objectData)),
2166
-				'size' => $query->createNamedParameter(strlen($objectData))
2167
-			])
2168
-			->execute();
2169
-	}
2170
-
2171
-	/**
2172
-	 * Adds a change record to the calendarchanges table.
2173
-	 *
2174
-	 * @param mixed $calendarId
2175
-	 * @param string $objectUri
2176
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2177
-	 * @param int $calendarType
2178
-	 * @return void
2179
-	 */
2180
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2181
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2182
-
2183
-		$query = $this->db->getQueryBuilder();
2184
-		$query->select('synctoken')
2185
-			->from($table)
2186
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2187
-		$syncToken = (int)$query->execute()->fetchColumn();
2188
-
2189
-		$query = $this->db->getQueryBuilder();
2190
-		$query->insert('calendarchanges')
2191
-			->values([
2192
-				'uri' => $query->createNamedParameter($objectUri),
2193
-				'synctoken' => $query->createNamedParameter($syncToken),
2194
-				'calendarid' => $query->createNamedParameter($calendarId),
2195
-				'operation' => $query->createNamedParameter($operation),
2196
-				'calendartype' => $query->createNamedParameter($calendarType),
2197
-			])
2198
-			->execute();
2199
-
2200
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2201
-		$stmt->execute([
2202
-			$calendarId
2203
-		]);
2204
-
2205
-	}
2206
-
2207
-	/**
2208
-	 * Parses some information from calendar objects, used for optimized
2209
-	 * calendar-queries.
2210
-	 *
2211
-	 * Returns an array with the following keys:
2212
-	 *   * etag - An md5 checksum of the object without the quotes.
2213
-	 *   * size - Size of the object in bytes
2214
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2215
-	 *   * firstOccurence
2216
-	 *   * lastOccurence
2217
-	 *   * uid - value of the UID property
2218
-	 *
2219
-	 * @param string $calendarData
2220
-	 * @return array
2221
-	 */
2222
-	public function getDenormalizedData($calendarData) {
2223
-
2224
-		$vObject = Reader::read($calendarData);
2225
-		$componentType = null;
2226
-		$component = null;
2227
-		$firstOccurrence = null;
2228
-		$lastOccurrence = null;
2229
-		$uid = null;
2230
-		$classification = self::CLASSIFICATION_PUBLIC;
2231
-		foreach($vObject->getComponents() as $component) {
2232
-			if ($component->name!=='VTIMEZONE') {
2233
-				$componentType = $component->name;
2234
-				$uid = (string)$component->UID;
2235
-				break;
2236
-			}
2237
-		}
2238
-		if (!$componentType) {
2239
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2240
-		}
2241
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2242
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2243
-			// Finding the last occurrence is a bit harder
2244
-			if (!isset($component->RRULE)) {
2245
-				if (isset($component->DTEND)) {
2246
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2247
-				} elseif (isset($component->DURATION)) {
2248
-					$endDate = clone $component->DTSTART->getDateTime();
2249
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2250
-					$lastOccurrence = $endDate->getTimeStamp();
2251
-				} elseif (!$component->DTSTART->hasTime()) {
2252
-					$endDate = clone $component->DTSTART->getDateTime();
2253
-					$endDate->modify('+1 day');
2254
-					$lastOccurrence = $endDate->getTimeStamp();
2255
-				} else {
2256
-					$lastOccurrence = $firstOccurrence;
2257
-				}
2258
-			} else {
2259
-				$it = new EventIterator($vObject, (string)$component->UID);
2260
-				$maxDate = new \DateTime(self::MAX_DATE);
2261
-				if ($it->isInfinite()) {
2262
-					$lastOccurrence = $maxDate->getTimestamp();
2263
-				} else {
2264
-					$end = $it->getDtEnd();
2265
-					while($it->valid() && $end < $maxDate) {
2266
-						$end = $it->getDtEnd();
2267
-						$it->next();
2268
-
2269
-					}
2270
-					$lastOccurrence = $end->getTimestamp();
2271
-				}
2272
-
2273
-			}
2274
-		}
2275
-
2276
-		if ($component->CLASS) {
2277
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2278
-			switch ($component->CLASS->getValue()) {
2279
-				case 'PUBLIC':
2280
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2281
-					break;
2282
-				case 'CONFIDENTIAL':
2283
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2284
-					break;
2285
-			}
2286
-		}
2287
-		return [
2288
-			'etag' => md5($calendarData),
2289
-			'size' => strlen($calendarData),
2290
-			'componentType' => $componentType,
2291
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2292
-			'lastOccurence'  => $lastOccurrence,
2293
-			'uid' => $uid,
2294
-			'classification' => $classification
2295
-		];
2296
-
2297
-	}
2298
-
2299
-	/**
2300
-	 * @param $cardData
2301
-	 * @return bool|string
2302
-	 */
2303
-	private function readBlob($cardData) {
2304
-		if (is_resource($cardData)) {
2305
-			return stream_get_contents($cardData);
2306
-		}
2307
-
2308
-		return $cardData;
2309
-	}
2310
-
2311
-	/**
2312
-	 * @param IShareable $shareable
2313
-	 * @param array $add
2314
-	 * @param array $remove
2315
-	 */
2316
-	public function updateShares($shareable, $add, $remove) {
2317
-		$calendarId = $shareable->getResourceId();
2318
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2319
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2320
-			[
2321
-				'calendarId' => $calendarId,
2322
-				'calendarData' => $this->getCalendarById($calendarId),
2323
-				'shares' => $this->getShares($calendarId),
2324
-				'add' => $add,
2325
-				'remove' => $remove,
2326
-			]));
2327
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2328
-	}
2329
-
2330
-	/**
2331
-	 * @param int $resourceId
2332
-	 * @param int $calendarType
2333
-	 * @return array
2334
-	 */
2335
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2336
-		return $this->calendarSharingBackend->getShares($resourceId);
2337
-	}
2338
-
2339
-	/**
2340
-	 * @param boolean $value
2341
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2342
-	 * @return string|null
2343
-	 */
2344
-	public function setPublishStatus($value, $calendar) {
2345
-
2346
-		$calendarId = $calendar->getResourceId();
2347
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2348
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2349
-			[
2350
-				'calendarId' => $calendarId,
2351
-				'calendarData' => $this->getCalendarById($calendarId),
2352
-				'public' => $value,
2353
-			]));
2354
-
2355
-		$query = $this->db->getQueryBuilder();
2356
-		if ($value) {
2357
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2358
-			$query->insert('dav_shares')
2359
-				->values([
2360
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2361
-					'type' => $query->createNamedParameter('calendar'),
2362
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2363
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2364
-					'publicuri' => $query->createNamedParameter($publicUri)
2365
-				]);
2366
-			$query->execute();
2367
-			return $publicUri;
2368
-		}
2369
-		$query->delete('dav_shares')
2370
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2371
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2372
-		$query->execute();
2373
-		return null;
2374
-	}
2375
-
2376
-	/**
2377
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2378
-	 * @return mixed
2379
-	 */
2380
-	public function getPublishStatus($calendar) {
2381
-		$query = $this->db->getQueryBuilder();
2382
-		$result = $query->select('publicuri')
2383
-			->from('dav_shares')
2384
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2385
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2386
-			->execute();
2387
-
2388
-		$row = $result->fetch();
2389
-		$result->closeCursor();
2390
-		return $row ? reset($row) : false;
2391
-	}
2392
-
2393
-	/**
2394
-	 * @param int $resourceId
2395
-	 * @param array $acl
2396
-	 * @return array
2397
-	 */
2398
-	public function applyShareAcl($resourceId, $acl) {
2399
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2400
-	}
2401
-
2402
-
2403
-
2404
-	/**
2405
-	 * update properties table
2406
-	 *
2407
-	 * @param int $calendarId
2408
-	 * @param string $objectUri
2409
-	 * @param string $calendarData
2410
-	 * @param int $calendarType
2411
-	 */
2412
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2413
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2414
-
2415
-		try {
2416
-			$vCalendar = $this->readCalendarData($calendarData);
2417
-		} catch (\Exception $ex) {
2418
-			return;
2419
-		}
2420
-
2421
-		$this->purgeProperties($calendarId, $objectId);
2422
-
2423
-		$query = $this->db->getQueryBuilder();
2424
-		$query->insert($this->dbObjectPropertiesTable)
2425
-			->values(
2426
-				[
2427
-					'calendarid' => $query->createNamedParameter($calendarId),
2428
-					'calendartype' => $query->createNamedParameter($calendarType),
2429
-					'objectid' => $query->createNamedParameter($objectId),
2430
-					'name' => $query->createParameter('name'),
2431
-					'parameter' => $query->createParameter('parameter'),
2432
-					'value' => $query->createParameter('value'),
2433
-				]
2434
-			);
2435
-
2436
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2437
-		foreach ($vCalendar->getComponents() as $component) {
2438
-			if (!in_array($component->name, $indexComponents)) {
2439
-				continue;
2440
-			}
2441
-
2442
-			foreach ($component->children() as $property) {
2443
-				if (in_array($property->name, self::$indexProperties)) {
2444
-					$value = $property->getValue();
2445
-					// is this a shitty db?
2446
-					if (!$this->db->supports4ByteText()) {
2447
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2448
-					}
2449
-					$value = mb_substr($value, 0, 254);
2450
-
2451
-					$query->setParameter('name', $property->name);
2452
-					$query->setParameter('parameter', null);
2453
-					$query->setParameter('value', $value);
2454
-					$query->execute();
2455
-				}
2456
-
2457
-				if (array_key_exists($property->name, self::$indexParameters)) {
2458
-					$parameters = $property->parameters();
2459
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2460
-
2461
-					foreach ($parameters as $key => $value) {
2462
-						if (in_array($key, $indexedParametersForProperty)) {
2463
-							// is this a shitty db?
2464
-							if ($this->db->supports4ByteText()) {
2465
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2466
-							}
2467
-							$value = mb_substr($value, 0, 254);
2468
-
2469
-							$query->setParameter('name', $property->name);
2470
-							$query->setParameter('parameter', substr($key, 0, 254));
2471
-							$query->setParameter('value', substr($value, 0, 254));
2472
-							$query->execute();
2473
-						}
2474
-					}
2475
-				}
2476
-			}
2477
-		}
2478
-	}
2479
-
2480
-	/**
2481
-	 * deletes all birthday calendars
2482
-	 */
2483
-	public function deleteAllBirthdayCalendars() {
2484
-		$query = $this->db->getQueryBuilder();
2485
-		$result = $query->select(['id'])->from('calendars')
2486
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2487
-			->execute();
2488
-
2489
-		$ids = $result->fetchAll();
2490
-		foreach($ids as $id) {
2491
-			$this->deleteCalendar($id['id']);
2492
-		}
2493
-	}
2494
-
2495
-	/**
2496
-	 * @param $subscriptionId
2497
-	 */
2498
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2499
-		$query = $this->db->getQueryBuilder();
2500
-		$query->select('uri')
2501
-			->from('calendarobjects')
2502
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2503
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2504
-		$stmt = $query->execute();
2505
-
2506
-		$uris = [];
2507
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2508
-			$uris[] = $row['uri'];
2509
-		}
2510
-		$stmt->closeCursor();
2511
-
2512
-		$query = $this->db->getQueryBuilder();
2513
-		$query->delete('calendarobjects')
2514
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2515
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2516
-			->execute();
2517
-
2518
-		$query->delete('calendarchanges')
2519
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2520
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2521
-			->execute();
2522
-
2523
-		$query->delete($this->dbObjectPropertiesTable)
2524
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2525
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2526
-			->execute();
2527
-
2528
-		foreach($uris as $uri) {
2529
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2530
-		}
2531
-	}
2532
-
2533
-	/**
2534
-	 * Move a calendar from one user to another
2535
-	 *
2536
-	 * @param string $uriName
2537
-	 * @param string $uriOrigin
2538
-	 * @param string $uriDestination
2539
-	 */
2540
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2541
-	{
2542
-		$query = $this->db->getQueryBuilder();
2543
-		$query->update('calendars')
2544
-			->set('principaluri', $query->createNamedParameter($uriDestination))
2545
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2546
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2547
-			->execute();
2548
-	}
2549
-
2550
-	/**
2551
-	 * read VCalendar data into a VCalendar object
2552
-	 *
2553
-	 * @param string $objectData
2554
-	 * @return VCalendar
2555
-	 */
2556
-	protected function readCalendarData($objectData) {
2557
-		return Reader::read($objectData);
2558
-	}
2559
-
2560
-	/**
2561
-	 * delete all properties from a given calendar object
2562
-	 *
2563
-	 * @param int $calendarId
2564
-	 * @param int $objectId
2565
-	 */
2566
-	protected function purgeProperties($calendarId, $objectId) {
2567
-		$query = $this->db->getQueryBuilder();
2568
-		$query->delete($this->dbObjectPropertiesTable)
2569
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2570
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2571
-		$query->execute();
2572
-	}
2573
-
2574
-	/**
2575
-	 * get ID from a given calendar object
2576
-	 *
2577
-	 * @param int $calendarId
2578
-	 * @param string $uri
2579
-	 * @param int $calendarType
2580
-	 * @return int
2581
-	 */
2582
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2583
-		$query = $this->db->getQueryBuilder();
2584
-		$query->select('id')
2585
-			->from('calendarobjects')
2586
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2587
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2588
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2589
-
2590
-		$result = $query->execute();
2591
-		$objectIds = $result->fetch();
2592
-		$result->closeCursor();
2593
-
2594
-		if (!isset($objectIds['id'])) {
2595
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2596
-		}
2597
-
2598
-		return (int)$objectIds['id'];
2599
-	}
2600
-
2601
-	/**
2602
-	 * return legacy endpoint principal name to new principal name
2603
-	 *
2604
-	 * @param $principalUri
2605
-	 * @param $toV2
2606
-	 * @return string
2607
-	 */
2608
-	private function convertPrincipal($principalUri, $toV2) {
2609
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2610
-			list(, $name) = Uri\split($principalUri);
2611
-			if ($toV2 === true) {
2612
-				return "principals/users/$name";
2613
-			}
2614
-			return "principals/$name";
2615
-		}
2616
-		return $principalUri;
2617
-	}
2618
-
2619
-	/**
2620
-	 * adds information about an owner to the calendar data
2621
-	 *
2622
-	 * @param $calendarInfo
2623
-	 */
2624
-	private function addOwnerPrincipal(&$calendarInfo) {
2625
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2626
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2627
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2628
-			$uri = $calendarInfo[$ownerPrincipalKey];
2629
-		} else {
2630
-			$uri = $calendarInfo['principaluri'];
2631
-		}
2632
-
2633
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2634
-		if (isset($principalInformation['{DAV:}displayname'])) {
2635
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2636
-		}
2637
-	}
449
+    /**
450
+     * @return array
451
+     */
452
+    public function getPublicCalendars() {
453
+        $fields = array_values($this->propertyMap);
454
+        $fields[] = 'a.id';
455
+        $fields[] = 'a.uri';
456
+        $fields[] = 'a.synctoken';
457
+        $fields[] = 'a.components';
458
+        $fields[] = 'a.principaluri';
459
+        $fields[] = 'a.transparent';
460
+        $fields[] = 's.access';
461
+        $fields[] = 's.publicuri';
462
+        $calendars = [];
463
+        $query = $this->db->getQueryBuilder();
464
+        $result = $query->select($fields)
465
+            ->from('dav_shares', 's')
466
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
467
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
468
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469
+            ->execute();
470
+
471
+        while($row = $result->fetch()) {
472
+            list(, $name) = Uri\split($row['principaluri']);
473
+            $row['displayname'] = $row['displayname'] . "($name)";
474
+            $components = [];
475
+            if ($row['components']) {
476
+                $components = explode(',',$row['components']);
477
+            }
478
+            $calendar = [
479
+                'id' => $row['id'],
480
+                'uri' => $row['publicuri'],
481
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
+            ];
490
+
491
+            foreach($this->propertyMap as $xmlName=>$dbName) {
492
+                $calendar[$xmlName] = $row[$dbName];
493
+            }
494
+
495
+            $this->addOwnerPrincipal($calendar);
496
+
497
+            if (!isset($calendars[$calendar['id']])) {
498
+                $calendars[$calendar['id']] = $calendar;
499
+            }
500
+        }
501
+        $result->closeCursor();
502
+
503
+        return array_values($calendars);
504
+    }
505
+
506
+    /**
507
+     * @param string $uri
508
+     * @return array
509
+     * @throws NotFound
510
+     */
511
+    public function getPublicCalendar($uri) {
512
+        $fields = array_values($this->propertyMap);
513
+        $fields[] = 'a.id';
514
+        $fields[] = 'a.uri';
515
+        $fields[] = 'a.synctoken';
516
+        $fields[] = 'a.components';
517
+        $fields[] = 'a.principaluri';
518
+        $fields[] = 'a.transparent';
519
+        $fields[] = 's.access';
520
+        $fields[] = 's.publicuri';
521
+        $query = $this->db->getQueryBuilder();
522
+        $result = $query->select($fields)
523
+            ->from('dav_shares', 's')
524
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
525
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
526
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
527
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
528
+            ->execute();
529
+
530
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
531
+
532
+        $result->closeCursor();
533
+
534
+        if ($row === false) {
535
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
536
+        }
537
+
538
+        list(, $name) = Uri\split($row['principaluri']);
539
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
540
+        $components = [];
541
+        if ($row['components']) {
542
+            $components = explode(',',$row['components']);
543
+        }
544
+        $calendar = [
545
+            'id' => $row['id'],
546
+            'uri' => $row['publicuri'],
547
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
555
+        ];
556
+
557
+        foreach($this->propertyMap as $xmlName=>$dbName) {
558
+            $calendar[$xmlName] = $row[$dbName];
559
+        }
560
+
561
+        $this->addOwnerPrincipal($calendar);
562
+
563
+        return $calendar;
564
+
565
+    }
566
+
567
+    /**
568
+     * @param string $principal
569
+     * @param string $uri
570
+     * @return array|null
571
+     */
572
+    public function getCalendarByUri($principal, $uri) {
573
+        $fields = array_values($this->propertyMap);
574
+        $fields[] = 'id';
575
+        $fields[] = 'uri';
576
+        $fields[] = 'synctoken';
577
+        $fields[] = 'components';
578
+        $fields[] = 'principaluri';
579
+        $fields[] = 'transparent';
580
+
581
+        // Making fields a comma-delimited list
582
+        $query = $this->db->getQueryBuilder();
583
+        $query->select($fields)->from('calendars')
584
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
585
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
586
+            ->setMaxResults(1);
587
+        $stmt = $query->execute();
588
+
589
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
590
+        $stmt->closeCursor();
591
+        if ($row === false) {
592
+            return null;
593
+        }
594
+
595
+        $components = [];
596
+        if ($row['components']) {
597
+            $components = explode(',',$row['components']);
598
+        }
599
+
600
+        $calendar = [
601
+            'id' => $row['id'],
602
+            'uri' => $row['uri'],
603
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
608
+        ];
609
+
610
+        foreach($this->propertyMap as $xmlName=>$dbName) {
611
+            $calendar[$xmlName] = $row[$dbName];
612
+        }
613
+
614
+        $this->addOwnerPrincipal($calendar);
615
+
616
+        return $calendar;
617
+    }
618
+
619
+    /**
620
+     * @param $calendarId
621
+     * @return array|null
622
+     */
623
+    public function getCalendarById($calendarId) {
624
+        $fields = array_values($this->propertyMap);
625
+        $fields[] = 'id';
626
+        $fields[] = 'uri';
627
+        $fields[] = 'synctoken';
628
+        $fields[] = 'components';
629
+        $fields[] = 'principaluri';
630
+        $fields[] = 'transparent';
631
+
632
+        // Making fields a comma-delimited list
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->select($fields)->from('calendars')
635
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
636
+            ->setMaxResults(1);
637
+        $stmt = $query->execute();
638
+
639
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
640
+        $stmt->closeCursor();
641
+        if ($row === false) {
642
+            return null;
643
+        }
644
+
645
+        $components = [];
646
+        if ($row['components']) {
647
+            $components = explode(',',$row['components']);
648
+        }
649
+
650
+        $calendar = [
651
+            'id' => $row['id'],
652
+            'uri' => $row['uri'],
653
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
+        ];
659
+
660
+        foreach($this->propertyMap as $xmlName=>$dbName) {
661
+            $calendar[$xmlName] = $row[$dbName];
662
+        }
663
+
664
+        $this->addOwnerPrincipal($calendar);
665
+
666
+        return $calendar;
667
+    }
668
+
669
+    /**
670
+     * @param $subscriptionId
671
+     */
672
+    public function getSubscriptionById($subscriptionId) {
673
+        $fields = array_values($this->subscriptionPropertyMap);
674
+        $fields[] = 'id';
675
+        $fields[] = 'uri';
676
+        $fields[] = 'source';
677
+        $fields[] = 'synctoken';
678
+        $fields[] = 'principaluri';
679
+        $fields[] = 'lastmodified';
680
+
681
+        $query = $this->db->getQueryBuilder();
682
+        $query->select($fields)
683
+            ->from('calendarsubscriptions')
684
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685
+            ->orderBy('calendarorder', 'asc');
686
+        $stmt =$query->execute();
687
+
688
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
689
+        $stmt->closeCursor();
690
+        if ($row === false) {
691
+            return null;
692
+        }
693
+
694
+        $subscription = [
695
+            'id'           => $row['id'],
696
+            'uri'          => $row['uri'],
697
+            'principaluri' => $row['principaluri'],
698
+            'source'       => $row['source'],
699
+            'lastmodified' => $row['lastmodified'],
700
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
702
+        ];
703
+
704
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705
+            if (!is_null($row[$dbName])) {
706
+                $subscription[$xmlName] = $row[$dbName];
707
+            }
708
+        }
709
+
710
+        return $subscription;
711
+    }
712
+
713
+    /**
714
+     * Creates a new calendar for a principal.
715
+     *
716
+     * If the creation was a success, an id must be returned that can be used to reference
717
+     * this calendar in other methods, such as updateCalendar.
718
+     *
719
+     * @param string $principalUri
720
+     * @param string $calendarUri
721
+     * @param array $properties
722
+     * @return int
723
+     * @suppress SqlInjectionChecker
724
+     */
725
+    function createCalendar($principalUri, $calendarUri, array $properties) {
726
+        $values = [
727
+            'principaluri' => $this->convertPrincipal($principalUri, true),
728
+            'uri'          => $calendarUri,
729
+            'synctoken'    => 1,
730
+            'transparent'  => 0,
731
+            'components'   => 'VEVENT,VTODO',
732
+            'displayname'  => $calendarUri
733
+        ];
734
+
735
+        // Default value
736
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737
+        if (isset($properties[$sccs])) {
738
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740
+            }
741
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
742
+        } else if (isset($properties['components'])) {
743
+            // Allow to provide components internally without having
744
+            // to create a SupportedCalendarComponentSet object
745
+            $values['components'] = $properties['components'];
746
+        }
747
+
748
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
749
+        if (isset($properties[$transp])) {
750
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751
+        }
752
+
753
+        foreach($this->propertyMap as $xmlName=>$dbName) {
754
+            if (isset($properties[$xmlName])) {
755
+                $values[$dbName] = $properties[$xmlName];
756
+            }
757
+        }
758
+
759
+        $query = $this->db->getQueryBuilder();
760
+        $query->insert('calendars');
761
+        foreach($values as $column => $value) {
762
+            $query->setValue($column, $query->createNamedParameter($value));
763
+        }
764
+        $query->execute();
765
+        $calendarId = $query->getLastInsertId();
766
+
767
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
768
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
769
+            [
770
+                'calendarId' => $calendarId,
771
+                'calendarData' => $this->getCalendarById($calendarId),
772
+        ]));
773
+
774
+        return $calendarId;
775
+    }
776
+
777
+    /**
778
+     * Updates properties for a calendar.
779
+     *
780
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
781
+     * To do the actual updates, you must tell this object which properties
782
+     * you're going to process with the handle() method.
783
+     *
784
+     * Calling the handle method is like telling the PropPatch object "I
785
+     * promise I can handle updating this property".
786
+     *
787
+     * Read the PropPatch documentation for more info and examples.
788
+     *
789
+     * @param mixed $calendarId
790
+     * @param PropPatch $propPatch
791
+     * @return void
792
+     */
793
+    function updateCalendar($calendarId, PropPatch $propPatch) {
794
+        $supportedProperties = array_keys($this->propertyMap);
795
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
796
+
797
+        /**
798
+         * @suppress SqlInjectionChecker
799
+         */
800
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
801
+            $newValues = [];
802
+            foreach ($mutations as $propertyName => $propertyValue) {
803
+
804
+                switch ($propertyName) {
805
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
806
+                        $fieldName = 'transparent';
807
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808
+                        break;
809
+                    default :
810
+                        $fieldName = $this->propertyMap[$propertyName];
811
+                        $newValues[$fieldName] = $propertyValue;
812
+                        break;
813
+                }
814
+
815
+            }
816
+            $query = $this->db->getQueryBuilder();
817
+            $query->update('calendars');
818
+            foreach ($newValues as $fieldName => $value) {
819
+                $query->set($fieldName, $query->createNamedParameter($value));
820
+            }
821
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
822
+            $query->execute();
823
+
824
+            $this->addChange($calendarId, "", 2);
825
+
826
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
827
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
828
+                [
829
+                    'calendarId' => $calendarId,
830
+                    'calendarData' => $this->getCalendarById($calendarId),
831
+                    'shares' => $this->getShares($calendarId),
832
+                    'propertyMutations' => $mutations,
833
+            ]));
834
+
835
+            return true;
836
+        });
837
+    }
838
+
839
+    /**
840
+     * Delete a calendar and all it's objects
841
+     *
842
+     * @param mixed $calendarId
843
+     * @return void
844
+     */
845
+    function deleteCalendar($calendarId) {
846
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
847
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
848
+            [
849
+                'calendarId' => $calendarId,
850
+                'calendarData' => $this->getCalendarById($calendarId),
851
+                'shares' => $this->getShares($calendarId),
852
+        ]));
853
+
854
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
855
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
856
+
857
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
858
+        $stmt->execute([$calendarId]);
859
+
860
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
861
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
862
+
863
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
864
+
865
+        $query = $this->db->getQueryBuilder();
866
+        $query->delete($this->dbObjectPropertiesTable)
867
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
868
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
869
+            ->execute();
870
+    }
871
+
872
+    /**
873
+     * Delete all of an user's shares
874
+     *
875
+     * @param string $principaluri
876
+     * @return void
877
+     */
878
+    function deleteAllSharesByUser($principaluri) {
879
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
880
+    }
881
+
882
+    /**
883
+     * Returns all calendar objects within a calendar.
884
+     *
885
+     * Every item contains an array with the following keys:
886
+     *   * calendardata - The iCalendar-compatible calendar data
887
+     *   * uri - a unique key which will be used to construct the uri. This can
888
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
889
+     *     good idea. This is only the basename, or filename, not the full
890
+     *     path.
891
+     *   * lastmodified - a timestamp of the last modification time
892
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
893
+     *   '"abcdef"')
894
+     *   * size - The size of the calendar objects, in bytes.
895
+     *   * component - optional, a string containing the type of object, such
896
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
897
+     *     the Content-Type header.
898
+     *
899
+     * Note that the etag is optional, but it's highly encouraged to return for
900
+     * speed reasons.
901
+     *
902
+     * The calendardata is also optional. If it's not returned
903
+     * 'getCalendarObject' will be called later, which *is* expected to return
904
+     * calendardata.
905
+     *
906
+     * If neither etag or size are specified, the calendardata will be
907
+     * used/fetched to determine these numbers. If both are specified the
908
+     * amount of times this is needed is reduced by a great degree.
909
+     *
910
+     * @param mixed $id
911
+     * @param int $calendarType
912
+     * @return array
913
+     */
914
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
915
+        $query = $this->db->getQueryBuilder();
916
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917
+            ->from('calendarobjects')
918
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
919
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
920
+        $stmt = $query->execute();
921
+
922
+        $result = [];
923
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924
+            $result[] = [
925
+                'id'           => $row['id'],
926
+                'uri'          => $row['uri'],
927
+                'lastmodified' => $row['lastmodified'],
928
+                'etag'         => '"' . $row['etag'] . '"',
929
+                'calendarid'   => $row['calendarid'],
930
+                'size'         => (int)$row['size'],
931
+                'component'    => strtolower($row['componenttype']),
932
+                'classification'=> (int)$row['classification']
933
+            ];
934
+        }
935
+
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * Returns information from a single calendar object, based on it's object
941
+     * uri.
942
+     *
943
+     * The object uri is only the basename, or filename and not a full path.
944
+     *
945
+     * The returned array must have the same keys as getCalendarObjects. The
946
+     * 'calendardata' object is required here though, while it's not required
947
+     * for getCalendarObjects.
948
+     *
949
+     * This method must return null if the object did not exist.
950
+     *
951
+     * @param mixed $id
952
+     * @param string $objectUri
953
+     * @param int $calendarType
954
+     * @return array|null
955
+     */
956
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
957
+        $query = $this->db->getQueryBuilder();
958
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959
+            ->from('calendarobjects')
960
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
961
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
962
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
963
+        $stmt = $query->execute();
964
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
965
+
966
+        if(!$row) {
967
+            return null;
968
+        }
969
+
970
+        return [
971
+            'id'            => $row['id'],
972
+            'uri'           => $row['uri'],
973
+            'lastmodified'  => $row['lastmodified'],
974
+            'etag'          => '"' . $row['etag'] . '"',
975
+            'calendarid'    => $row['calendarid'],
976
+            'size'          => (int)$row['size'],
977
+            'calendardata'  => $this->readBlob($row['calendardata']),
978
+            'component'     => strtolower($row['componenttype']),
979
+            'classification'=> (int)$row['classification']
980
+        ];
981
+    }
982
+
983
+    /**
984
+     * Returns a list of calendar objects.
985
+     *
986
+     * This method should work identical to getCalendarObject, but instead
987
+     * return all the calendar objects in the list as an array.
988
+     *
989
+     * If the backend supports this, it may allow for some speed-ups.
990
+     *
991
+     * @param mixed $calendarId
992
+     * @param string[] $uris
993
+     * @param int $calendarType
994
+     * @return array
995
+     */
996
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
997
+        if (empty($uris)) {
998
+            return [];
999
+        }
1000
+
1001
+        $chunks = array_chunk($uris, 100);
1002
+        $objects = [];
1003
+
1004
+        $query = $this->db->getQueryBuilder();
1005
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1006
+            ->from('calendarobjects')
1007
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1008
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1009
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1010
+
1011
+        foreach ($chunks as $uris) {
1012
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1013
+            $result = $query->execute();
1014
+
1015
+            while ($row = $result->fetch()) {
1016
+                $objects[] = [
1017
+                    'id'           => $row['id'],
1018
+                    'uri'          => $row['uri'],
1019
+                    'lastmodified' => $row['lastmodified'],
1020
+                    'etag'         => '"' . $row['etag'] . '"',
1021
+                    'calendarid'   => $row['calendarid'],
1022
+                    'size'         => (int)$row['size'],
1023
+                    'calendardata' => $this->readBlob($row['calendardata']),
1024
+                    'component'    => strtolower($row['componenttype']),
1025
+                    'classification' => (int)$row['classification']
1026
+                ];
1027
+            }
1028
+            $result->closeCursor();
1029
+        }
1030
+
1031
+        return $objects;
1032
+    }
1033
+
1034
+    /**
1035
+     * Creates a new calendar object.
1036
+     *
1037
+     * The object uri is only the basename, or filename and not a full path.
1038
+     *
1039
+     * It is possible return an etag from this function, which will be used in
1040
+     * the response to this PUT request. Note that the ETag must be surrounded
1041
+     * by double-quotes.
1042
+     *
1043
+     * However, you should only really return this ETag if you don't mangle the
1044
+     * calendar-data. If the result of a subsequent GET to this object is not
1045
+     * the exact same as this request body, you should omit the ETag.
1046
+     *
1047
+     * @param mixed $calendarId
1048
+     * @param string $objectUri
1049
+     * @param string $calendarData
1050
+     * @param int $calendarType
1051
+     * @return string
1052
+     */
1053
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1054
+        $extraData = $this->getDenormalizedData($calendarData);
1055
+
1056
+        $q = $this->db->getQueryBuilder();
1057
+        $q->select($q->func()->count('*'))
1058
+            ->from('calendarobjects')
1059
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1060
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1061
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1062
+
1063
+        $result = $q->execute();
1064
+        $count = (int) $result->fetchColumn();
1065
+        $result->closeCursor();
1066
+
1067
+        if ($count !== 0) {
1068
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1069
+        }
1070
+
1071
+        $query = $this->db->getQueryBuilder();
1072
+        $query->insert('calendarobjects')
1073
+            ->values([
1074
+                'calendarid' => $query->createNamedParameter($calendarId),
1075
+                'uri' => $query->createNamedParameter($objectUri),
1076
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1077
+                'lastmodified' => $query->createNamedParameter(time()),
1078
+                'etag' => $query->createNamedParameter($extraData['etag']),
1079
+                'size' => $query->createNamedParameter($extraData['size']),
1080
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1081
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1082
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1083
+                'classification' => $query->createNamedParameter($extraData['classification']),
1084
+                'uid' => $query->createNamedParameter($extraData['uid']),
1085
+                'calendartype' => $query->createNamedParameter($calendarType),
1086
+            ])
1087
+            ->execute();
1088
+
1089
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1090
+
1091
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1092
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1093
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1094
+                [
1095
+                    'calendarId' => $calendarId,
1096
+                    'calendarData' => $this->getCalendarById($calendarId),
1097
+                    'shares' => $this->getShares($calendarId),
1098
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1099
+                ]
1100
+            ));
1101
+        } else {
1102
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1103
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1104
+                [
1105
+                    'subscriptionId' => $calendarId,
1106
+                    'calendarData' => $this->getCalendarById($calendarId),
1107
+                    'shares' => $this->getShares($calendarId),
1108
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1109
+                ]
1110
+            ));
1111
+        }
1112
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1113
+
1114
+        return '"' . $extraData['etag'] . '"';
1115
+    }
1116
+
1117
+    /**
1118
+     * Updates an existing calendarobject, based on it's uri.
1119
+     *
1120
+     * The object uri is only the basename, or filename and not a full path.
1121
+     *
1122
+     * It is possible return an etag from this function, which will be used in
1123
+     * the response to this PUT request. Note that the ETag must be surrounded
1124
+     * by double-quotes.
1125
+     *
1126
+     * However, you should only really return this ETag if you don't mangle the
1127
+     * calendar-data. If the result of a subsequent GET to this object is not
1128
+     * the exact same as this request body, you should omit the ETag.
1129
+     *
1130
+     * @param mixed $calendarId
1131
+     * @param string $objectUri
1132
+     * @param string $calendarData
1133
+     * @param int $calendarType
1134
+     * @return string
1135
+     */
1136
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1137
+        $extraData = $this->getDenormalizedData($calendarData);
1138
+
1139
+        $query = $this->db->getQueryBuilder();
1140
+        $query->update('calendarobjects')
1141
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1142
+                ->set('lastmodified', $query->createNamedParameter(time()))
1143
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1144
+                ->set('size', $query->createNamedParameter($extraData['size']))
1145
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1146
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1147
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1148
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1149
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1150
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1151
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1152
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1153
+            ->execute();
1154
+
1155
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1156
+
1157
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1158
+        if (is_array($data)) {
1159
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1160
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1161
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1162
+                    [
1163
+                        'calendarId' => $calendarId,
1164
+                        'calendarData' => $this->getCalendarById($calendarId),
1165
+                        'shares' => $this->getShares($calendarId),
1166
+                        'objectData' => $data,
1167
+                    ]
1168
+                ));
1169
+            } else {
1170
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1171
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1172
+                    [
1173
+                        'subscriptionId' => $calendarId,
1174
+                        'calendarData' => $this->getCalendarById($calendarId),
1175
+                        'shares' => $this->getShares($calendarId),
1176
+                        'objectData' => $data,
1177
+                    ]
1178
+                ));
1179
+            }
1180
+        }
1181
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1182
+
1183
+        return '"' . $extraData['etag'] . '"';
1184
+    }
1185
+
1186
+    /**
1187
+     * @param int $calendarObjectId
1188
+     * @param int $classification
1189
+     */
1190
+    public function setClassification($calendarObjectId, $classification) {
1191
+        if (!in_array($classification, [
1192
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1193
+        ])) {
1194
+            throw new \InvalidArgumentException();
1195
+        }
1196
+        $query = $this->db->getQueryBuilder();
1197
+        $query->update('calendarobjects')
1198
+            ->set('classification', $query->createNamedParameter($classification))
1199
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1200
+            ->execute();
1201
+    }
1202
+
1203
+    /**
1204
+     * Deletes an existing calendar object.
1205
+     *
1206
+     * The object uri is only the basename, or filename and not a full path.
1207
+     *
1208
+     * @param mixed $calendarId
1209
+     * @param string $objectUri
1210
+     * @param int $calendarType
1211
+     * @return void
1212
+     */
1213
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1214
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1215
+        if (is_array($data)) {
1216
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1217
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1218
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1219
+                    [
1220
+                        'calendarId' => $calendarId,
1221
+                        'calendarData' => $this->getCalendarById($calendarId),
1222
+                        'shares' => $this->getShares($calendarId),
1223
+                        'objectData' => $data,
1224
+                    ]
1225
+                ));
1226
+            } else {
1227
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1228
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1229
+                    [
1230
+                        'subscriptionId' => $calendarId,
1231
+                        'calendarData' => $this->getCalendarById($calendarId),
1232
+                        'shares' => $this->getShares($calendarId),
1233
+                        'objectData' => $data,
1234
+                    ]
1235
+                ));
1236
+            }
1237
+        }
1238
+
1239
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1240
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1241
+
1242
+        $this->purgeProperties($calendarId, $data['id'], $calendarType);
1243
+
1244
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1245
+    }
1246
+
1247
+    /**
1248
+     * Performs a calendar-query on the contents of this calendar.
1249
+     *
1250
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1251
+     * calendar-query it is possible for a client to request a specific set of
1252
+     * object, based on contents of iCalendar properties, date-ranges and
1253
+     * iCalendar component types (VTODO, VEVENT).
1254
+     *
1255
+     * This method should just return a list of (relative) urls that match this
1256
+     * query.
1257
+     *
1258
+     * The list of filters are specified as an array. The exact array is
1259
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1260
+     *
1261
+     * Note that it is extremely likely that getCalendarObject for every path
1262
+     * returned from this method will be called almost immediately after. You
1263
+     * may want to anticipate this to speed up these requests.
1264
+     *
1265
+     * This method provides a default implementation, which parses *all* the
1266
+     * iCalendar objects in the specified calendar.
1267
+     *
1268
+     * This default may well be good enough for personal use, and calendars
1269
+     * that aren't very large. But if you anticipate high usage, big calendars
1270
+     * or high loads, you are strongly advised to optimize certain paths.
1271
+     *
1272
+     * The best way to do so is override this method and to optimize
1273
+     * specifically for 'common filters'.
1274
+     *
1275
+     * Requests that are extremely common are:
1276
+     *   * requests for just VEVENTS
1277
+     *   * requests for just VTODO
1278
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1279
+     *
1280
+     * ..and combinations of these requests. It may not be worth it to try to
1281
+     * handle every possible situation and just rely on the (relatively
1282
+     * easy to use) CalendarQueryValidator to handle the rest.
1283
+     *
1284
+     * Note that especially time-range-filters may be difficult to parse. A
1285
+     * time-range filter specified on a VEVENT must for instance also handle
1286
+     * recurrence rules correctly.
1287
+     * A good example of how to interprete all these filters can also simply
1288
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1289
+     * as possible, so it gives you a good idea on what type of stuff you need
1290
+     * to think of.
1291
+     *
1292
+     * @param mixed $id
1293
+     * @param array $filters
1294
+     * @param int $calendarType
1295
+     * @return array
1296
+     */
1297
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1298
+        $componentType = null;
1299
+        $requirePostFilter = true;
1300
+        $timeRange = null;
1301
+
1302
+        // if no filters were specified, we don't need to filter after a query
1303
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1304
+            $requirePostFilter = false;
1305
+        }
1306
+
1307
+        // Figuring out if there's a component filter
1308
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1309
+            $componentType = $filters['comp-filters'][0]['name'];
1310
+
1311
+            // Checking if we need post-filters
1312
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1313
+                $requirePostFilter = false;
1314
+            }
1315
+            // There was a time-range filter
1316
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1317
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1318
+
1319
+                // If start time OR the end time is not specified, we can do a
1320
+                // 100% accurate mysql query.
1321
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1322
+                    $requirePostFilter = false;
1323
+                }
1324
+            }
1325
+
1326
+        }
1327
+        $columns = ['uri'];
1328
+        if ($requirePostFilter) {
1329
+            $columns = ['uri', 'calendardata'];
1330
+        }
1331
+        $query = $this->db->getQueryBuilder();
1332
+        $query->select($columns)
1333
+            ->from('calendarobjects')
1334
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1335
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1336
+
1337
+        if ($componentType) {
1338
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1339
+        }
1340
+
1341
+        if ($timeRange && $timeRange['start']) {
1342
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1343
+        }
1344
+        if ($timeRange && $timeRange['end']) {
1345
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1346
+        }
1347
+
1348
+        $stmt = $query->execute();
1349
+
1350
+        $result = [];
1351
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1352
+            if ($requirePostFilter) {
1353
+                // validateFilterForObject will parse the calendar data
1354
+                // catch parsing errors
1355
+                try {
1356
+                    $matches = $this->validateFilterForObject($row, $filters);
1357
+                } catch(ParseException $ex) {
1358
+                    $this->logger->logException($ex, [
1359
+                        'app' => 'dav',
1360
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1361
+                    ]);
1362
+                    continue;
1363
+                } catch (InvalidDataException $ex) {
1364
+                    $this->logger->logException($ex, [
1365
+                        'app' => 'dav',
1366
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1367
+                    ]);
1368
+                    continue;
1369
+                }
1370
+
1371
+                if (!$matches) {
1372
+                    continue;
1373
+                }
1374
+            }
1375
+            $result[] = $row['uri'];
1376
+        }
1377
+
1378
+        return $result;
1379
+    }
1380
+
1381
+    /**
1382
+     * custom Nextcloud search extension for CalDAV
1383
+     *
1384
+     * TODO - this should optionally cover cached calendar objects as well
1385
+     *
1386
+     * @param string $principalUri
1387
+     * @param array $filters
1388
+     * @param integer|null $limit
1389
+     * @param integer|null $offset
1390
+     * @return array
1391
+     */
1392
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1393
+        $calendars = $this->getCalendarsForUser($principalUri);
1394
+        $ownCalendars = [];
1395
+        $sharedCalendars = [];
1396
+
1397
+        $uriMapper = [];
1398
+
1399
+        foreach($calendars as $calendar) {
1400
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1401
+                $ownCalendars[] = $calendar['id'];
1402
+            } else {
1403
+                $sharedCalendars[] = $calendar['id'];
1404
+            }
1405
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1406
+        }
1407
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1408
+            return [];
1409
+        }
1410
+
1411
+        $query = $this->db->getQueryBuilder();
1412
+        // Calendar id expressions
1413
+        $calendarExpressions = [];
1414
+        foreach($ownCalendars as $id) {
1415
+            $calendarExpressions[] = $query->expr()->andX(
1416
+                $query->expr()->eq('c.calendarid',
1417
+                    $query->createNamedParameter($id)),
1418
+                $query->expr()->eq('c.calendartype',
1419
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
+        }
1421
+        foreach($sharedCalendars as $id) {
1422
+            $calendarExpressions[] = $query->expr()->andX(
1423
+                $query->expr()->eq('c.calendarid',
1424
+                    $query->createNamedParameter($id)),
1425
+                $query->expr()->eq('c.classification',
1426
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1427
+                $query->expr()->eq('c.calendartype',
1428
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1429
+        }
1430
+
1431
+        if (count($calendarExpressions) === 1) {
1432
+            $calExpr = $calendarExpressions[0];
1433
+        } else {
1434
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1435
+        }
1436
+
1437
+        // Component expressions
1438
+        $compExpressions = [];
1439
+        foreach($filters['comps'] as $comp) {
1440
+            $compExpressions[] = $query->expr()
1441
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1442
+        }
1443
+
1444
+        if (count($compExpressions) === 1) {
1445
+            $compExpr = $compExpressions[0];
1446
+        } else {
1447
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1448
+        }
1449
+
1450
+        if (!isset($filters['props'])) {
1451
+            $filters['props'] = [];
1452
+        }
1453
+        if (!isset($filters['params'])) {
1454
+            $filters['params'] = [];
1455
+        }
1456
+
1457
+        $propParamExpressions = [];
1458
+        foreach($filters['props'] as $prop) {
1459
+            $propParamExpressions[] = $query->expr()->andX(
1460
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1461
+                $query->expr()->isNull('i.parameter')
1462
+            );
1463
+        }
1464
+        foreach($filters['params'] as $param) {
1465
+            $propParamExpressions[] = $query->expr()->andX(
1466
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1467
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1468
+            );
1469
+        }
1470
+
1471
+        if (count($propParamExpressions) === 1) {
1472
+            $propParamExpr = $propParamExpressions[0];
1473
+        } else {
1474
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1475
+        }
1476
+
1477
+        $query->select(['c.calendarid', 'c.uri'])
1478
+            ->from($this->dbObjectPropertiesTable, 'i')
1479
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1480
+            ->where($calExpr)
1481
+            ->andWhere($compExpr)
1482
+            ->andWhere($propParamExpr)
1483
+            ->andWhere($query->expr()->iLike('i.value',
1484
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1485
+
1486
+        if ($offset) {
1487
+            $query->setFirstResult($offset);
1488
+        }
1489
+        if ($limit) {
1490
+            $query->setMaxResults($limit);
1491
+        }
1492
+
1493
+        $stmt = $query->execute();
1494
+
1495
+        $result = [];
1496
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1497
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1498
+            if (!in_array($path, $result)) {
1499
+                $result[] = $path;
1500
+            }
1501
+        }
1502
+
1503
+        return $result;
1504
+    }
1505
+
1506
+    /**
1507
+     * used for Nextcloud's calendar API
1508
+     *
1509
+     * @param array $calendarInfo
1510
+     * @param string $pattern
1511
+     * @param array $searchProperties
1512
+     * @param array $options
1513
+     * @param integer|null $limit
1514
+     * @param integer|null $offset
1515
+     *
1516
+     * @return array
1517
+     */
1518
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1519
+                            array $options, $limit, $offset) {
1520
+        $outerQuery = $this->db->getQueryBuilder();
1521
+        $innerQuery = $this->db->getQueryBuilder();
1522
+
1523
+        $innerQuery->selectDistinct('op.objectid')
1524
+            ->from($this->dbObjectPropertiesTable, 'op')
1525
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1526
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1527
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1528
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1529
+
1530
+        // only return public items for shared calendars for now
1531
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1532
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1533
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1534
+        }
1535
+
1536
+        $or = $innerQuery->expr()->orX();
1537
+        foreach($searchProperties as $searchProperty) {
1538
+            $or->add($innerQuery->expr()->eq('op.name',
1539
+                $outerQuery->createNamedParameter($searchProperty)));
1540
+        }
1541
+        $innerQuery->andWhere($or);
1542
+
1543
+        if ($pattern !== '') {
1544
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1545
+                $outerQuery->createNamedParameter('%' .
1546
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1547
+        }
1548
+
1549
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1550
+            ->from('calendarobjects', 'c');
1551
+
1552
+        if (isset($options['timerange'])) {
1553
+            if (isset($options['timerange']['start'])) {
1554
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1555
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1556
+
1557
+            }
1558
+            if (isset($options['timerange']['end'])) {
1559
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1560
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1561
+            }
1562
+        }
1563
+
1564
+        if (isset($options['types'])) {
1565
+            $or = $outerQuery->expr()->orX();
1566
+            foreach($options['types'] as $type) {
1567
+                $or->add($outerQuery->expr()->eq('componenttype',
1568
+                    $outerQuery->createNamedParameter($type)));
1569
+            }
1570
+            $outerQuery->andWhere($or);
1571
+        }
1572
+
1573
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1574
+            $outerQuery->createFunction($innerQuery->getSQL())));
1575
+
1576
+        if ($offset) {
1577
+            $outerQuery->setFirstResult($offset);
1578
+        }
1579
+        if ($limit) {
1580
+            $outerQuery->setMaxResults($limit);
1581
+        }
1582
+
1583
+        $result = $outerQuery->execute();
1584
+        $calendarObjects = $result->fetchAll();
1585
+
1586
+        return array_map(function($o) {
1587
+            $calendarData = Reader::read($o['calendardata']);
1588
+            $comps = $calendarData->getComponents();
1589
+            $objects = [];
1590
+            $timezones = [];
1591
+            foreach($comps as $comp) {
1592
+                if ($comp instanceof VTimeZone) {
1593
+                    $timezones[] = $comp;
1594
+                } else {
1595
+                    $objects[] = $comp;
1596
+                }
1597
+            }
1598
+
1599
+            return [
1600
+                'id' => $o['id'],
1601
+                'type' => $o['componenttype'],
1602
+                'uid' => $o['uid'],
1603
+                'uri' => $o['uri'],
1604
+                'objects' => array_map(function($c) {
1605
+                    return $this->transformSearchData($c);
1606
+                }, $objects),
1607
+                'timezones' => array_map(function($c) {
1608
+                    return $this->transformSearchData($c);
1609
+                }, $timezones),
1610
+            ];
1611
+        }, $calendarObjects);
1612
+    }
1613
+
1614
+    /**
1615
+     * @param Component $comp
1616
+     * @return array
1617
+     */
1618
+    private function transformSearchData(Component $comp) {
1619
+        $data = [];
1620
+        /** @var Component[] $subComponents */
1621
+        $subComponents = $comp->getComponents();
1622
+        /** @var Property[] $properties */
1623
+        $properties = array_filter($comp->children(), function($c) {
1624
+            return $c instanceof Property;
1625
+        });
1626
+        $validationRules = $comp->getValidationRules();
1627
+
1628
+        foreach($subComponents as $subComponent) {
1629
+            $name = $subComponent->name;
1630
+            if (!isset($data[$name])) {
1631
+                $data[$name] = [];
1632
+            }
1633
+            $data[$name][] = $this->transformSearchData($subComponent);
1634
+        }
1635
+
1636
+        foreach($properties as $property) {
1637
+            $name = $property->name;
1638
+            if (!isset($validationRules[$name])) {
1639
+                $validationRules[$name] = '*';
1640
+            }
1641
+
1642
+            $rule = $validationRules[$property->name];
1643
+            if ($rule === '+' || $rule === '*') { // multiple
1644
+                if (!isset($data[$name])) {
1645
+                    $data[$name] = [];
1646
+                }
1647
+
1648
+                $data[$name][] = $this->transformSearchProperty($property);
1649
+            } else { // once
1650
+                $data[$name] = $this->transformSearchProperty($property);
1651
+            }
1652
+        }
1653
+
1654
+        return $data;
1655
+    }
1656
+
1657
+    /**
1658
+     * @param Property $prop
1659
+     * @return array
1660
+     */
1661
+    private function transformSearchProperty(Property $prop) {
1662
+        // No need to check Date, as it extends DateTime
1663
+        if ($prop instanceof Property\ICalendar\DateTime) {
1664
+            $value = $prop->getDateTime();
1665
+        } else {
1666
+            $value = $prop->getValue();
1667
+        }
1668
+
1669
+        return [
1670
+            $value,
1671
+            $prop->parameters()
1672
+        ];
1673
+    }
1674
+
1675
+    /**
1676
+     * Searches through all of a users calendars and calendar objects to find
1677
+     * an object with a specific UID.
1678
+     *
1679
+     * This method should return the path to this object, relative to the
1680
+     * calendar home, so this path usually only contains two parts:
1681
+     *
1682
+     * calendarpath/objectpath.ics
1683
+     *
1684
+     * If the uid is not found, return null.
1685
+     *
1686
+     * This method should only consider * objects that the principal owns, so
1687
+     * any calendars owned by other principals that also appear in this
1688
+     * collection should be ignored.
1689
+     *
1690
+     * @param string $principalUri
1691
+     * @param string $uid
1692
+     * @return string|null
1693
+     */
1694
+    function getCalendarObjectByUID($principalUri, $uid) {
1695
+
1696
+        $query = $this->db->getQueryBuilder();
1697
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1698
+            ->from('calendarobjects', 'co')
1699
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1700
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1701
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1702
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1703
+
1704
+        $stmt = $query->execute();
1705
+
1706
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1707
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1708
+        }
1709
+
1710
+        return null;
1711
+    }
1712
+
1713
+    /**
1714
+     * The getChanges method returns all the changes that have happened, since
1715
+     * the specified syncToken in the specified calendar.
1716
+     *
1717
+     * This function should return an array, such as the following:
1718
+     *
1719
+     * [
1720
+     *   'syncToken' => 'The current synctoken',
1721
+     *   'added'   => [
1722
+     *      'new.txt',
1723
+     *   ],
1724
+     *   'modified'   => [
1725
+     *      'modified.txt',
1726
+     *   ],
1727
+     *   'deleted' => [
1728
+     *      'foo.php.bak',
1729
+     *      'old.txt'
1730
+     *   ]
1731
+     * );
1732
+     *
1733
+     * The returned syncToken property should reflect the *current* syncToken
1734
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1735
+     * property This is * needed here too, to ensure the operation is atomic.
1736
+     *
1737
+     * If the $syncToken argument is specified as null, this is an initial
1738
+     * sync, and all members should be reported.
1739
+     *
1740
+     * The modified property is an array of nodenames that have changed since
1741
+     * the last token.
1742
+     *
1743
+     * The deleted property is an array with nodenames, that have been deleted
1744
+     * from collection.
1745
+     *
1746
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1747
+     * 1, you only have to report changes that happened only directly in
1748
+     * immediate descendants. If it's 2, it should also include changes from
1749
+     * the nodes below the child collections. (grandchildren)
1750
+     *
1751
+     * The $limit argument allows a client to specify how many results should
1752
+     * be returned at most. If the limit is not specified, it should be treated
1753
+     * as infinite.
1754
+     *
1755
+     * If the limit (infinite or not) is higher than you're willing to return,
1756
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1757
+     *
1758
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1759
+     * return null.
1760
+     *
1761
+     * The limit is 'suggestive'. You are free to ignore it.
1762
+     *
1763
+     * @param string $calendarId
1764
+     * @param string $syncToken
1765
+     * @param int $syncLevel
1766
+     * @param int $limit
1767
+     * @param int $calendarType
1768
+     * @return array
1769
+     */
1770
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1771
+        // Current synctoken
1772
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1773
+        $stmt->execute([ $calendarId ]);
1774
+        $currentToken = $stmt->fetchColumn(0);
1775
+
1776
+        if (is_null($currentToken)) {
1777
+            return null;
1778
+        }
1779
+
1780
+        $result = [
1781
+            'syncToken' => $currentToken,
1782
+            'added'     => [],
1783
+            'modified'  => [],
1784
+            'deleted'   => [],
1785
+        ];
1786
+
1787
+        if ($syncToken) {
1788
+
1789
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1790
+            if ($limit>0) {
1791
+                $query.= " LIMIT " . (int)$limit;
1792
+            }
1793
+
1794
+            // Fetching all changes
1795
+            $stmt = $this->db->prepare($query);
1796
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1797
+
1798
+            $changes = [];
1799
+
1800
+            // This loop ensures that any duplicates are overwritten, only the
1801
+            // last change on a node is relevant.
1802
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1803
+
1804
+                $changes[$row['uri']] = $row['operation'];
1805
+
1806
+            }
1807
+
1808
+            foreach($changes as $uri => $operation) {
1809
+
1810
+                switch($operation) {
1811
+                    case 1 :
1812
+                        $result['added'][] = $uri;
1813
+                        break;
1814
+                    case 2 :
1815
+                        $result['modified'][] = $uri;
1816
+                        break;
1817
+                    case 3 :
1818
+                        $result['deleted'][] = $uri;
1819
+                        break;
1820
+                }
1821
+
1822
+            }
1823
+        } else {
1824
+            // No synctoken supplied, this is the initial sync.
1825
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1826
+            $stmt = $this->db->prepare($query);
1827
+            $stmt->execute([$calendarId, $calendarType]);
1828
+
1829
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1830
+        }
1831
+        return $result;
1832
+
1833
+    }
1834
+
1835
+    /**
1836
+     * Returns a list of subscriptions for a principal.
1837
+     *
1838
+     * Every subscription is an array with the following keys:
1839
+     *  * id, a unique id that will be used by other functions to modify the
1840
+     *    subscription. This can be the same as the uri or a database key.
1841
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1842
+     *  * principaluri. The owner of the subscription. Almost always the same as
1843
+     *    principalUri passed to this method.
1844
+     *
1845
+     * Furthermore, all the subscription info must be returned too:
1846
+     *
1847
+     * 1. {DAV:}displayname
1848
+     * 2. {http://apple.com/ns/ical/}refreshrate
1849
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1850
+     *    should not be stripped).
1851
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1852
+     *    should not be stripped).
1853
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1854
+     *    attachments should not be stripped).
1855
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1856
+     *     Sabre\DAV\Property\Href).
1857
+     * 7. {http://apple.com/ns/ical/}calendar-color
1858
+     * 8. {http://apple.com/ns/ical/}calendar-order
1859
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1860
+     *    (should just be an instance of
1861
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1862
+     *    default components).
1863
+     *
1864
+     * @param string $principalUri
1865
+     * @return array
1866
+     */
1867
+    function getSubscriptionsForUser($principalUri) {
1868
+        $fields = array_values($this->subscriptionPropertyMap);
1869
+        $fields[] = 'id';
1870
+        $fields[] = 'uri';
1871
+        $fields[] = 'source';
1872
+        $fields[] = 'principaluri';
1873
+        $fields[] = 'lastmodified';
1874
+        $fields[] = 'synctoken';
1875
+
1876
+        $query = $this->db->getQueryBuilder();
1877
+        $query->select($fields)
1878
+            ->from('calendarsubscriptions')
1879
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1880
+            ->orderBy('calendarorder', 'asc');
1881
+        $stmt =$query->execute();
1882
+
1883
+        $subscriptions = [];
1884
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1885
+
1886
+            $subscription = [
1887
+                'id'           => $row['id'],
1888
+                'uri'          => $row['uri'],
1889
+                'principaluri' => $row['principaluri'],
1890
+                'source'       => $row['source'],
1891
+                'lastmodified' => $row['lastmodified'],
1892
+
1893
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1894
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1895
+            ];
1896
+
1897
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1898
+                if (!is_null($row[$dbName])) {
1899
+                    $subscription[$xmlName] = $row[$dbName];
1900
+                }
1901
+            }
1902
+
1903
+            $subscriptions[] = $subscription;
1904
+
1905
+        }
1906
+
1907
+        return $subscriptions;
1908
+    }
1909
+
1910
+    /**
1911
+     * Creates a new subscription for a principal.
1912
+     *
1913
+     * If the creation was a success, an id must be returned that can be used to reference
1914
+     * this subscription in other methods, such as updateSubscription.
1915
+     *
1916
+     * @param string $principalUri
1917
+     * @param string $uri
1918
+     * @param array $properties
1919
+     * @return mixed
1920
+     */
1921
+    function createSubscription($principalUri, $uri, array $properties) {
1922
+
1923
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1924
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1925
+        }
1926
+
1927
+        $values = [
1928
+            'principaluri' => $principalUri,
1929
+            'uri'          => $uri,
1930
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1931
+            'lastmodified' => time(),
1932
+        ];
1933
+
1934
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1935
+
1936
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1937
+            if (array_key_exists($xmlName, $properties)) {
1938
+                    $values[$dbName] = $properties[$xmlName];
1939
+                    if (in_array($dbName, $propertiesBoolean)) {
1940
+                        $values[$dbName] = true;
1941
+                }
1942
+            }
1943
+        }
1944
+
1945
+        $valuesToInsert = array();
1946
+
1947
+        $query = $this->db->getQueryBuilder();
1948
+
1949
+        foreach (array_keys($values) as $name) {
1950
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1951
+        }
1952
+
1953
+        $query->insert('calendarsubscriptions')
1954
+            ->values($valuesToInsert)
1955
+            ->execute();
1956
+
1957
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1958
+
1959
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1960
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1961
+            [
1962
+                'subscriptionId' => $subscriptionId,
1963
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1964
+            ]));
1965
+
1966
+        return $subscriptionId;
1967
+    }
1968
+
1969
+    /**
1970
+     * Updates a subscription
1971
+     *
1972
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1973
+     * To do the actual updates, you must tell this object which properties
1974
+     * you're going to process with the handle() method.
1975
+     *
1976
+     * Calling the handle method is like telling the PropPatch object "I
1977
+     * promise I can handle updating this property".
1978
+     *
1979
+     * Read the PropPatch documentation for more info and examples.
1980
+     *
1981
+     * @param mixed $subscriptionId
1982
+     * @param PropPatch $propPatch
1983
+     * @return void
1984
+     */
1985
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1986
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1987
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1988
+
1989
+        /**
1990
+         * @suppress SqlInjectionChecker
1991
+         */
1992
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1993
+
1994
+            $newValues = [];
1995
+
1996
+            foreach($mutations as $propertyName=>$propertyValue) {
1997
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1998
+                    $newValues['source'] = $propertyValue->getHref();
1999
+                } else {
2000
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2001
+                    $newValues[$fieldName] = $propertyValue;
2002
+                }
2003
+            }
2004
+
2005
+            $query = $this->db->getQueryBuilder();
2006
+            $query->update('calendarsubscriptions')
2007
+                ->set('lastmodified', $query->createNamedParameter(time()));
2008
+            foreach($newValues as $fieldName=>$value) {
2009
+                $query->set($fieldName, $query->createNamedParameter($value));
2010
+            }
2011
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2012
+                ->execute();
2013
+
2014
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2015
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2016
+                [
2017
+                    'subscriptionId' => $subscriptionId,
2018
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2019
+                    'propertyMutations' => $mutations,
2020
+                ]));
2021
+
2022
+            return true;
2023
+
2024
+        });
2025
+    }
2026
+
2027
+    /**
2028
+     * Deletes a subscription.
2029
+     *
2030
+     * @param mixed $subscriptionId
2031
+     * @return void
2032
+     */
2033
+    function deleteSubscription($subscriptionId) {
2034
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2035
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2036
+            [
2037
+                'subscriptionId' => $subscriptionId,
2038
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2039
+            ]));
2040
+
2041
+        $query = $this->db->getQueryBuilder();
2042
+        $query->delete('calendarsubscriptions')
2043
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2044
+            ->execute();
2045
+
2046
+        $query = $this->db->getQueryBuilder();
2047
+        $query->delete('calendarobjects')
2048
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2049
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2050
+            ->execute();
2051
+
2052
+        $query->delete('calendarchanges')
2053
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2054
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2055
+            ->execute();
2056
+
2057
+        $query->delete($this->dbObjectPropertiesTable)
2058
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2059
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2060
+            ->execute();
2061
+    }
2062
+
2063
+    /**
2064
+     * Returns a single scheduling object for the inbox collection.
2065
+     *
2066
+     * The returned array should contain the following elements:
2067
+     *   * uri - A unique basename for the object. This will be used to
2068
+     *           construct a full uri.
2069
+     *   * calendardata - The iCalendar object
2070
+     *   * lastmodified - The last modification date. Can be an int for a unix
2071
+     *                    timestamp, or a PHP DateTime object.
2072
+     *   * etag - A unique token that must change if the object changed.
2073
+     *   * size - The size of the object, in bytes.
2074
+     *
2075
+     * @param string $principalUri
2076
+     * @param string $objectUri
2077
+     * @return array
2078
+     */
2079
+    function getSchedulingObject($principalUri, $objectUri) {
2080
+        $query = $this->db->getQueryBuilder();
2081
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2082
+            ->from('schedulingobjects')
2083
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2084
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2085
+            ->execute();
2086
+
2087
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2088
+
2089
+        if(!$row) {
2090
+            return null;
2091
+        }
2092
+
2093
+        return [
2094
+                'uri'          => $row['uri'],
2095
+                'calendardata' => $row['calendardata'],
2096
+                'lastmodified' => $row['lastmodified'],
2097
+                'etag'         => '"' . $row['etag'] . '"',
2098
+                'size'         => (int)$row['size'],
2099
+        ];
2100
+    }
2101
+
2102
+    /**
2103
+     * Returns all scheduling objects for the inbox collection.
2104
+     *
2105
+     * These objects should be returned as an array. Every item in the array
2106
+     * should follow the same structure as returned from getSchedulingObject.
2107
+     *
2108
+     * The main difference is that 'calendardata' is optional.
2109
+     *
2110
+     * @param string $principalUri
2111
+     * @return array
2112
+     */
2113
+    function getSchedulingObjects($principalUri) {
2114
+        $query = $this->db->getQueryBuilder();
2115
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2116
+                ->from('schedulingobjects')
2117
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2118
+                ->execute();
2119
+
2120
+        $result = [];
2121
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2122
+            $result[] = [
2123
+                    'calendardata' => $row['calendardata'],
2124
+                    'uri'          => $row['uri'],
2125
+                    'lastmodified' => $row['lastmodified'],
2126
+                    'etag'         => '"' . $row['etag'] . '"',
2127
+                    'size'         => (int)$row['size'],
2128
+            ];
2129
+        }
2130
+
2131
+        return $result;
2132
+    }
2133
+
2134
+    /**
2135
+     * Deletes a scheduling object from the inbox collection.
2136
+     *
2137
+     * @param string $principalUri
2138
+     * @param string $objectUri
2139
+     * @return void
2140
+     */
2141
+    function deleteSchedulingObject($principalUri, $objectUri) {
2142
+        $query = $this->db->getQueryBuilder();
2143
+        $query->delete('schedulingobjects')
2144
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2145
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2146
+                ->execute();
2147
+    }
2148
+
2149
+    /**
2150
+     * Creates a new scheduling object. This should land in a users' inbox.
2151
+     *
2152
+     * @param string $principalUri
2153
+     * @param string $objectUri
2154
+     * @param string $objectData
2155
+     * @return void
2156
+     */
2157
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2158
+        $query = $this->db->getQueryBuilder();
2159
+        $query->insert('schedulingobjects')
2160
+            ->values([
2161
+                'principaluri' => $query->createNamedParameter($principalUri),
2162
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2163
+                'uri' => $query->createNamedParameter($objectUri),
2164
+                'lastmodified' => $query->createNamedParameter(time()),
2165
+                'etag' => $query->createNamedParameter(md5($objectData)),
2166
+                'size' => $query->createNamedParameter(strlen($objectData))
2167
+            ])
2168
+            ->execute();
2169
+    }
2170
+
2171
+    /**
2172
+     * Adds a change record to the calendarchanges table.
2173
+     *
2174
+     * @param mixed $calendarId
2175
+     * @param string $objectUri
2176
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2177
+     * @param int $calendarType
2178
+     * @return void
2179
+     */
2180
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2181
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2182
+
2183
+        $query = $this->db->getQueryBuilder();
2184
+        $query->select('synctoken')
2185
+            ->from($table)
2186
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2187
+        $syncToken = (int)$query->execute()->fetchColumn();
2188
+
2189
+        $query = $this->db->getQueryBuilder();
2190
+        $query->insert('calendarchanges')
2191
+            ->values([
2192
+                'uri' => $query->createNamedParameter($objectUri),
2193
+                'synctoken' => $query->createNamedParameter($syncToken),
2194
+                'calendarid' => $query->createNamedParameter($calendarId),
2195
+                'operation' => $query->createNamedParameter($operation),
2196
+                'calendartype' => $query->createNamedParameter($calendarType),
2197
+            ])
2198
+            ->execute();
2199
+
2200
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2201
+        $stmt->execute([
2202
+            $calendarId
2203
+        ]);
2204
+
2205
+    }
2206
+
2207
+    /**
2208
+     * Parses some information from calendar objects, used for optimized
2209
+     * calendar-queries.
2210
+     *
2211
+     * Returns an array with the following keys:
2212
+     *   * etag - An md5 checksum of the object without the quotes.
2213
+     *   * size - Size of the object in bytes
2214
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2215
+     *   * firstOccurence
2216
+     *   * lastOccurence
2217
+     *   * uid - value of the UID property
2218
+     *
2219
+     * @param string $calendarData
2220
+     * @return array
2221
+     */
2222
+    public function getDenormalizedData($calendarData) {
2223
+
2224
+        $vObject = Reader::read($calendarData);
2225
+        $componentType = null;
2226
+        $component = null;
2227
+        $firstOccurrence = null;
2228
+        $lastOccurrence = null;
2229
+        $uid = null;
2230
+        $classification = self::CLASSIFICATION_PUBLIC;
2231
+        foreach($vObject->getComponents() as $component) {
2232
+            if ($component->name!=='VTIMEZONE') {
2233
+                $componentType = $component->name;
2234
+                $uid = (string)$component->UID;
2235
+                break;
2236
+            }
2237
+        }
2238
+        if (!$componentType) {
2239
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2240
+        }
2241
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2242
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2243
+            // Finding the last occurrence is a bit harder
2244
+            if (!isset($component->RRULE)) {
2245
+                if (isset($component->DTEND)) {
2246
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2247
+                } elseif (isset($component->DURATION)) {
2248
+                    $endDate = clone $component->DTSTART->getDateTime();
2249
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2250
+                    $lastOccurrence = $endDate->getTimeStamp();
2251
+                } elseif (!$component->DTSTART->hasTime()) {
2252
+                    $endDate = clone $component->DTSTART->getDateTime();
2253
+                    $endDate->modify('+1 day');
2254
+                    $lastOccurrence = $endDate->getTimeStamp();
2255
+                } else {
2256
+                    $lastOccurrence = $firstOccurrence;
2257
+                }
2258
+            } else {
2259
+                $it = new EventIterator($vObject, (string)$component->UID);
2260
+                $maxDate = new \DateTime(self::MAX_DATE);
2261
+                if ($it->isInfinite()) {
2262
+                    $lastOccurrence = $maxDate->getTimestamp();
2263
+                } else {
2264
+                    $end = $it->getDtEnd();
2265
+                    while($it->valid() && $end < $maxDate) {
2266
+                        $end = $it->getDtEnd();
2267
+                        $it->next();
2268
+
2269
+                    }
2270
+                    $lastOccurrence = $end->getTimestamp();
2271
+                }
2272
+
2273
+            }
2274
+        }
2275
+
2276
+        if ($component->CLASS) {
2277
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2278
+            switch ($component->CLASS->getValue()) {
2279
+                case 'PUBLIC':
2280
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2281
+                    break;
2282
+                case 'CONFIDENTIAL':
2283
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2284
+                    break;
2285
+            }
2286
+        }
2287
+        return [
2288
+            'etag' => md5($calendarData),
2289
+            'size' => strlen($calendarData),
2290
+            'componentType' => $componentType,
2291
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2292
+            'lastOccurence'  => $lastOccurrence,
2293
+            'uid' => $uid,
2294
+            'classification' => $classification
2295
+        ];
2296
+
2297
+    }
2298
+
2299
+    /**
2300
+     * @param $cardData
2301
+     * @return bool|string
2302
+     */
2303
+    private function readBlob($cardData) {
2304
+        if (is_resource($cardData)) {
2305
+            return stream_get_contents($cardData);
2306
+        }
2307
+
2308
+        return $cardData;
2309
+    }
2310
+
2311
+    /**
2312
+     * @param IShareable $shareable
2313
+     * @param array $add
2314
+     * @param array $remove
2315
+     */
2316
+    public function updateShares($shareable, $add, $remove) {
2317
+        $calendarId = $shareable->getResourceId();
2318
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2319
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2320
+            [
2321
+                'calendarId' => $calendarId,
2322
+                'calendarData' => $this->getCalendarById($calendarId),
2323
+                'shares' => $this->getShares($calendarId),
2324
+                'add' => $add,
2325
+                'remove' => $remove,
2326
+            ]));
2327
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2328
+    }
2329
+
2330
+    /**
2331
+     * @param int $resourceId
2332
+     * @param int $calendarType
2333
+     * @return array
2334
+     */
2335
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2336
+        return $this->calendarSharingBackend->getShares($resourceId);
2337
+    }
2338
+
2339
+    /**
2340
+     * @param boolean $value
2341
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2342
+     * @return string|null
2343
+     */
2344
+    public function setPublishStatus($value, $calendar) {
2345
+
2346
+        $calendarId = $calendar->getResourceId();
2347
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2348
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2349
+            [
2350
+                'calendarId' => $calendarId,
2351
+                'calendarData' => $this->getCalendarById($calendarId),
2352
+                'public' => $value,
2353
+            ]));
2354
+
2355
+        $query = $this->db->getQueryBuilder();
2356
+        if ($value) {
2357
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2358
+            $query->insert('dav_shares')
2359
+                ->values([
2360
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2361
+                    'type' => $query->createNamedParameter('calendar'),
2362
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2363
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2364
+                    'publicuri' => $query->createNamedParameter($publicUri)
2365
+                ]);
2366
+            $query->execute();
2367
+            return $publicUri;
2368
+        }
2369
+        $query->delete('dav_shares')
2370
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2371
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2372
+        $query->execute();
2373
+        return null;
2374
+    }
2375
+
2376
+    /**
2377
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2378
+     * @return mixed
2379
+     */
2380
+    public function getPublishStatus($calendar) {
2381
+        $query = $this->db->getQueryBuilder();
2382
+        $result = $query->select('publicuri')
2383
+            ->from('dav_shares')
2384
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2385
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2386
+            ->execute();
2387
+
2388
+        $row = $result->fetch();
2389
+        $result->closeCursor();
2390
+        return $row ? reset($row) : false;
2391
+    }
2392
+
2393
+    /**
2394
+     * @param int $resourceId
2395
+     * @param array $acl
2396
+     * @return array
2397
+     */
2398
+    public function applyShareAcl($resourceId, $acl) {
2399
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2400
+    }
2401
+
2402
+
2403
+
2404
+    /**
2405
+     * update properties table
2406
+     *
2407
+     * @param int $calendarId
2408
+     * @param string $objectUri
2409
+     * @param string $calendarData
2410
+     * @param int $calendarType
2411
+     */
2412
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2413
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2414
+
2415
+        try {
2416
+            $vCalendar = $this->readCalendarData($calendarData);
2417
+        } catch (\Exception $ex) {
2418
+            return;
2419
+        }
2420
+
2421
+        $this->purgeProperties($calendarId, $objectId);
2422
+
2423
+        $query = $this->db->getQueryBuilder();
2424
+        $query->insert($this->dbObjectPropertiesTable)
2425
+            ->values(
2426
+                [
2427
+                    'calendarid' => $query->createNamedParameter($calendarId),
2428
+                    'calendartype' => $query->createNamedParameter($calendarType),
2429
+                    'objectid' => $query->createNamedParameter($objectId),
2430
+                    'name' => $query->createParameter('name'),
2431
+                    'parameter' => $query->createParameter('parameter'),
2432
+                    'value' => $query->createParameter('value'),
2433
+                ]
2434
+            );
2435
+
2436
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2437
+        foreach ($vCalendar->getComponents() as $component) {
2438
+            if (!in_array($component->name, $indexComponents)) {
2439
+                continue;
2440
+            }
2441
+
2442
+            foreach ($component->children() as $property) {
2443
+                if (in_array($property->name, self::$indexProperties)) {
2444
+                    $value = $property->getValue();
2445
+                    // is this a shitty db?
2446
+                    if (!$this->db->supports4ByteText()) {
2447
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2448
+                    }
2449
+                    $value = mb_substr($value, 0, 254);
2450
+
2451
+                    $query->setParameter('name', $property->name);
2452
+                    $query->setParameter('parameter', null);
2453
+                    $query->setParameter('value', $value);
2454
+                    $query->execute();
2455
+                }
2456
+
2457
+                if (array_key_exists($property->name, self::$indexParameters)) {
2458
+                    $parameters = $property->parameters();
2459
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2460
+
2461
+                    foreach ($parameters as $key => $value) {
2462
+                        if (in_array($key, $indexedParametersForProperty)) {
2463
+                            // is this a shitty db?
2464
+                            if ($this->db->supports4ByteText()) {
2465
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2466
+                            }
2467
+                            $value = mb_substr($value, 0, 254);
2468
+
2469
+                            $query->setParameter('name', $property->name);
2470
+                            $query->setParameter('parameter', substr($key, 0, 254));
2471
+                            $query->setParameter('value', substr($value, 0, 254));
2472
+                            $query->execute();
2473
+                        }
2474
+                    }
2475
+                }
2476
+            }
2477
+        }
2478
+    }
2479
+
2480
+    /**
2481
+     * deletes all birthday calendars
2482
+     */
2483
+    public function deleteAllBirthdayCalendars() {
2484
+        $query = $this->db->getQueryBuilder();
2485
+        $result = $query->select(['id'])->from('calendars')
2486
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2487
+            ->execute();
2488
+
2489
+        $ids = $result->fetchAll();
2490
+        foreach($ids as $id) {
2491
+            $this->deleteCalendar($id['id']);
2492
+        }
2493
+    }
2494
+
2495
+    /**
2496
+     * @param $subscriptionId
2497
+     */
2498
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2499
+        $query = $this->db->getQueryBuilder();
2500
+        $query->select('uri')
2501
+            ->from('calendarobjects')
2502
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2503
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2504
+        $stmt = $query->execute();
2505
+
2506
+        $uris = [];
2507
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2508
+            $uris[] = $row['uri'];
2509
+        }
2510
+        $stmt->closeCursor();
2511
+
2512
+        $query = $this->db->getQueryBuilder();
2513
+        $query->delete('calendarobjects')
2514
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2515
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2516
+            ->execute();
2517
+
2518
+        $query->delete('calendarchanges')
2519
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2520
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2521
+            ->execute();
2522
+
2523
+        $query->delete($this->dbObjectPropertiesTable)
2524
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2525
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2526
+            ->execute();
2527
+
2528
+        foreach($uris as $uri) {
2529
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2530
+        }
2531
+    }
2532
+
2533
+    /**
2534
+     * Move a calendar from one user to another
2535
+     *
2536
+     * @param string $uriName
2537
+     * @param string $uriOrigin
2538
+     * @param string $uriDestination
2539
+     */
2540
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination)
2541
+    {
2542
+        $query = $this->db->getQueryBuilder();
2543
+        $query->update('calendars')
2544
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
2545
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
2546
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
2547
+            ->execute();
2548
+    }
2549
+
2550
+    /**
2551
+     * read VCalendar data into a VCalendar object
2552
+     *
2553
+     * @param string $objectData
2554
+     * @return VCalendar
2555
+     */
2556
+    protected function readCalendarData($objectData) {
2557
+        return Reader::read($objectData);
2558
+    }
2559
+
2560
+    /**
2561
+     * delete all properties from a given calendar object
2562
+     *
2563
+     * @param int $calendarId
2564
+     * @param int $objectId
2565
+     */
2566
+    protected function purgeProperties($calendarId, $objectId) {
2567
+        $query = $this->db->getQueryBuilder();
2568
+        $query->delete($this->dbObjectPropertiesTable)
2569
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2570
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2571
+        $query->execute();
2572
+    }
2573
+
2574
+    /**
2575
+     * get ID from a given calendar object
2576
+     *
2577
+     * @param int $calendarId
2578
+     * @param string $uri
2579
+     * @param int $calendarType
2580
+     * @return int
2581
+     */
2582
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2583
+        $query = $this->db->getQueryBuilder();
2584
+        $query->select('id')
2585
+            ->from('calendarobjects')
2586
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2587
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2588
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2589
+
2590
+        $result = $query->execute();
2591
+        $objectIds = $result->fetch();
2592
+        $result->closeCursor();
2593
+
2594
+        if (!isset($objectIds['id'])) {
2595
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2596
+        }
2597
+
2598
+        return (int)$objectIds['id'];
2599
+    }
2600
+
2601
+    /**
2602
+     * return legacy endpoint principal name to new principal name
2603
+     *
2604
+     * @param $principalUri
2605
+     * @param $toV2
2606
+     * @return string
2607
+     */
2608
+    private function convertPrincipal($principalUri, $toV2) {
2609
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2610
+            list(, $name) = Uri\split($principalUri);
2611
+            if ($toV2 === true) {
2612
+                return "principals/users/$name";
2613
+            }
2614
+            return "principals/$name";
2615
+        }
2616
+        return $principalUri;
2617
+    }
2618
+
2619
+    /**
2620
+     * adds information about an owner to the calendar data
2621
+     *
2622
+     * @param $calendarInfo
2623
+     */
2624
+    private function addOwnerPrincipal(&$calendarInfo) {
2625
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2626
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2627
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2628
+            $uri = $calendarInfo[$ownerPrincipalKey];
2629
+        } else {
2630
+            $uri = $calendarInfo['principaluri'];
2631
+        }
2632
+
2633
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2634
+        if (isset($principalInformation['{DAV:}displayname'])) {
2635
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2636
+        }
2637
+    }
2638 2638
 }
Please login to merge, or discard this patch.
Spacing   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
224 224
 		}
225 225
 
226
-		return (int)$query->execute()->fetchColumn();
226
+		return (int) $query->execute()->fetchColumn();
227 227
 	}
228 228
 
229 229
 	/**
@@ -270,25 +270,25 @@  discard block
 block discarded – undo
270 270
 		$stmt = $query->execute();
271 271
 
272 272
 		$calendars = [];
273
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
273
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
274 274
 
275 275
 			$components = [];
276 276
 			if ($row['components']) {
277
-				$components = explode(',',$row['components']);
277
+				$components = explode(',', $row['components']);
278 278
 			}
279 279
 
280 280
 			$calendar = [
281 281
 				'id' => $row['id'],
282 282
 				'uri' => $row['uri'],
283 283
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
284
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
285
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
286
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
288
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
284
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
285
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
286
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
287
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
288
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
289 289
 			];
290 290
 
291
-			foreach($this->propertyMap as $xmlName=>$dbName) {
291
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
292 292
 				$calendar[$xmlName] = $row[$dbName];
293 293
 			}
294 294
 
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 		$principals = array_map(function($principal) {
309 309
 			return urldecode($principal);
310 310
 		}, $principals);
311
-		$principals[]= $principalUri;
311
+		$principals[] = $principalUri;
312 312
 
313 313
 		$fields = array_values($this->propertyMap);
314 314
 		$fields[] = 'a.id';
@@ -328,8 +328,8 @@  discard block
 block discarded – undo
328 328
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
329 329
 			->execute();
330 330
 
331
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
332
-		while($row = $result->fetch()) {
331
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
332
+		while ($row = $result->fetch()) {
333 333
 			if ($row['principaluri'] === $principalUri) {
334 334
 				continue;
335 335
 			}
@@ -348,25 +348,25 @@  discard block
 block discarded – undo
348 348
 			}
349 349
 
350 350
 			list(, $name) = Uri\split($row['principaluri']);
351
-			$uri = $row['uri'] . '_shared_by_' . $name;
352
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
351
+			$uri = $row['uri'].'_shared_by_'.$name;
352
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
353 353
 			$components = [];
354 354
 			if ($row['components']) {
355
-				$components = explode(',',$row['components']);
355
+				$components = explode(',', $row['components']);
356 356
 			}
357 357
 			$calendar = [
358 358
 				'id' => $row['id'],
359 359
 				'uri' => $uri,
360 360
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
362
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
363
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
361
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
362
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
363
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
364
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
365
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
366 366
 				$readOnlyPropertyName => $readOnly,
367 367
 			];
368 368
 
369
-			foreach($this->propertyMap as $xmlName=>$dbName) {
369
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
370 370
 				$calendar[$xmlName] = $row[$dbName];
371 371
 			}
372 372
 
@@ -399,21 +399,21 @@  discard block
 block discarded – undo
399 399
 			->orderBy('calendarorder', 'ASC');
400 400
 		$stmt = $query->execute();
401 401
 		$calendars = [];
402
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
402
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
403 403
 			$components = [];
404 404
 			if ($row['components']) {
405
-				$components = explode(',',$row['components']);
405
+				$components = explode(',', $row['components']);
406 406
 			}
407 407
 			$calendar = [
408 408
 				'id' => $row['id'],
409 409
 				'uri' => $row['uri'],
410 410
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
411
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
412
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
413
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
412
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
413
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
414
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
415 415
 			];
416
-			foreach($this->propertyMap as $xmlName=>$dbName) {
416
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
417 417
 				$calendar[$xmlName] = $row[$dbName];
418 418
 			}
419 419
 
@@ -468,27 +468,27 @@  discard block
 block discarded – undo
468 468
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
469 469
 			->execute();
470 470
 
471
-		while($row = $result->fetch()) {
471
+		while ($row = $result->fetch()) {
472 472
 			list(, $name) = Uri\split($row['principaluri']);
473
-			$row['displayname'] = $row['displayname'] . "($name)";
473
+			$row['displayname'] = $row['displayname']."($name)";
474 474
 			$components = [];
475 475
 			if ($row['components']) {
476
-				$components = explode(',',$row['components']);
476
+				$components = explode(',', $row['components']);
477 477
 			}
478 478
 			$calendar = [
479 479
 				'id' => $row['id'],
480 480
 				'uri' => $row['publicuri'],
481 481
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
482
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
483
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
484
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
486
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
487
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
488
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
489 489
 			];
490 490
 
491
-			foreach($this->propertyMap as $xmlName=>$dbName) {
491
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
492 492
 				$calendar[$xmlName] = $row[$dbName];
493 493
 			}
494 494
 
@@ -532,29 +532,29 @@  discard block
 block discarded – undo
532 532
 		$result->closeCursor();
533 533
 
534 534
 		if ($row === false) {
535
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
535
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
536 536
 		}
537 537
 
538 538
 		list(, $name) = Uri\split($row['principaluri']);
539
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
539
+		$row['displayname'] = $row['displayname'].' '."($name)";
540 540
 		$components = [];
541 541
 		if ($row['components']) {
542
-			$components = explode(',',$row['components']);
542
+			$components = explode(',', $row['components']);
543 543
 		}
544 544
 		$calendar = [
545 545
 			'id' => $row['id'],
546 546
 			'uri' => $row['publicuri'],
547 547
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
548
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
549
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
550
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
552
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
554
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
548
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
549
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
550
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
551
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
552
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
553
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
554
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
555 555
 		];
556 556
 
557
-		foreach($this->propertyMap as $xmlName=>$dbName) {
557
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
558 558
 			$calendar[$xmlName] = $row[$dbName];
559 559
 		}
560 560
 
@@ -594,20 +594,20 @@  discard block
 block discarded – undo
594 594
 
595 595
 		$components = [];
596 596
 		if ($row['components']) {
597
-			$components = explode(',',$row['components']);
597
+			$components = explode(',', $row['components']);
598 598
 		}
599 599
 
600 600
 		$calendar = [
601 601
 			'id' => $row['id'],
602 602
 			'uri' => $row['uri'],
603 603
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
605
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
606
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
605
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
606
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
607
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
608 608
 		];
609 609
 
610
-		foreach($this->propertyMap as $xmlName=>$dbName) {
610
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
611 611
 			$calendar[$xmlName] = $row[$dbName];
612 612
 		}
613 613
 
@@ -644,20 +644,20 @@  discard block
 block discarded – undo
644 644
 
645 645
 		$components = [];
646 646
 		if ($row['components']) {
647
-			$components = explode(',',$row['components']);
647
+			$components = explode(',', $row['components']);
648 648
 		}
649 649
 
650 650
 		$calendar = [
651 651
 			'id' => $row['id'],
652 652
 			'uri' => $row['uri'],
653 653
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
654
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
655
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
656
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
655
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
656
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
657
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
658 658
 		];
659 659
 
660
-		foreach($this->propertyMap as $xmlName=>$dbName) {
660
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
661 661
 			$calendar[$xmlName] = $row[$dbName];
662 662
 		}
663 663
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 			->from('calendarsubscriptions')
684 684
 			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
685 685
 			->orderBy('calendarorder', 'asc');
686
-		$stmt =$query->execute();
686
+		$stmt = $query->execute();
687 687
 
688 688
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
689 689
 		$stmt->closeCursor();
@@ -697,11 +697,11 @@  discard block
 block discarded – undo
697 697
 			'principaluri' => $row['principaluri'],
698 698
 			'source'       => $row['source'],
699 699
 			'lastmodified' => $row['lastmodified'],
700
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
700
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
701
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
702 702
 		];
703 703
 
704
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
704
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
705 705
 			if (!is_null($row[$dbName])) {
706 706
 				$subscription[$xmlName] = $row[$dbName];
707 707
 			}
@@ -736,21 +736,21 @@  discard block
 block discarded – undo
736 736
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
737 737
 		if (isset($properties[$sccs])) {
738 738
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
739
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
739
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
740 740
 			}
741
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
741
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
742 742
 		} else if (isset($properties['components'])) {
743 743
 			// Allow to provide components internally without having
744 744
 			// to create a SupportedCalendarComponentSet object
745 745
 			$values['components'] = $properties['components'];
746 746
 		}
747 747
 
748
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
748
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
749 749
 		if (isset($properties[$transp])) {
750 750
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
751 751
 		}
752 752
 
753
-		foreach($this->propertyMap as $xmlName=>$dbName) {
753
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
754 754
 			if (isset($properties[$xmlName])) {
755 755
 				$values[$dbName] = $properties[$xmlName];
756 756
 			}
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 
759 759
 		$query = $this->db->getQueryBuilder();
760 760
 		$query->insert('calendars');
761
-		foreach($values as $column => $value) {
761
+		foreach ($values as $column => $value) {
762 762
 			$query->setValue($column, $query->createNamedParameter($value));
763 763
 		}
764 764
 		$query->execute();
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 	 */
793 793
 	function updateCalendar($calendarId, PropPatch $propPatch) {
794 794
 		$supportedProperties = array_keys($this->propertyMap);
795
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
795
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
796 796
 
797 797
 		/**
798 798
 		 * @suppress SqlInjectionChecker
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
 			foreach ($mutations as $propertyName => $propertyValue) {
803 803
 
804 804
 				switch ($propertyName) {
805
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
805
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
806 806
 						$fieldName = 'transparent';
807 807
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
808 808
 						break;
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 	 * @param int $calendarType
912 912
 	 * @return array
913 913
 	 */
914
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
914
+	public function getCalendarObjects($id, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
915 915
 		$query = $this->db->getQueryBuilder();
916 916
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
917 917
 			->from('calendarobjects')
@@ -920,16 +920,16 @@  discard block
 block discarded – undo
920 920
 		$stmt = $query->execute();
921 921
 
922 922
 		$result = [];
923
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
923
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
924 924
 			$result[] = [
925 925
 				'id'           => $row['id'],
926 926
 				'uri'          => $row['uri'],
927 927
 				'lastmodified' => $row['lastmodified'],
928
-				'etag'         => '"' . $row['etag'] . '"',
928
+				'etag'         => '"'.$row['etag'].'"',
929 929
 				'calendarid'   => $row['calendarid'],
930
-				'size'         => (int)$row['size'],
930
+				'size'         => (int) $row['size'],
931 931
 				'component'    => strtolower($row['componenttype']),
932
-				'classification'=> (int)$row['classification']
932
+				'classification'=> (int) $row['classification']
933 933
 			];
934 934
 		}
935 935
 
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
 	 * @param int $calendarType
954 954
 	 * @return array|null
955 955
 	 */
956
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
956
+	public function getCalendarObject($id, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
957 957
 		$query = $this->db->getQueryBuilder();
958 958
 		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
959 959
 			->from('calendarobjects')
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 		$stmt = $query->execute();
964 964
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
965 965
 
966
-		if(!$row) {
966
+		if (!$row) {
967 967
 			return null;
968 968
 		}
969 969
 
@@ -971,12 +971,12 @@  discard block
 block discarded – undo
971 971
 			'id'            => $row['id'],
972 972
 			'uri'           => $row['uri'],
973 973
 			'lastmodified'  => $row['lastmodified'],
974
-			'etag'          => '"' . $row['etag'] . '"',
974
+			'etag'          => '"'.$row['etag'].'"',
975 975
 			'calendarid'    => $row['calendarid'],
976
-			'size'          => (int)$row['size'],
976
+			'size'          => (int) $row['size'],
977 977
 			'calendardata'  => $this->readBlob($row['calendardata']),
978 978
 			'component'     => strtolower($row['componenttype']),
979
-			'classification'=> (int)$row['classification']
979
+			'classification'=> (int) $row['classification']
980 980
 		];
981 981
 	}
982 982
 
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
 	 * @param int $calendarType
994 994
 	 * @return array
995 995
 	 */
996
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
996
+	public function getMultipleCalendarObjects($id, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
997 997
 		if (empty($uris)) {
998 998
 			return [];
999 999
 		}
@@ -1017,12 +1017,12 @@  discard block
 block discarded – undo
1017 1017
 					'id'           => $row['id'],
1018 1018
 					'uri'          => $row['uri'],
1019 1019
 					'lastmodified' => $row['lastmodified'],
1020
-					'etag'         => '"' . $row['etag'] . '"',
1020
+					'etag'         => '"'.$row['etag'].'"',
1021 1021
 					'calendarid'   => $row['calendarid'],
1022
-					'size'         => (int)$row['size'],
1022
+					'size'         => (int) $row['size'],
1023 1023
 					'calendardata' => $this->readBlob($row['calendardata']),
1024 1024
 					'component'    => strtolower($row['componenttype']),
1025
-					'classification' => (int)$row['classification']
1025
+					'classification' => (int) $row['classification']
1026 1026
 				];
1027 1027
 			}
1028 1028
 			$result->closeCursor();
@@ -1050,7 +1050,7 @@  discard block
 block discarded – undo
1050 1050
 	 * @param int $calendarType
1051 1051
 	 * @return string
1052 1052
 	 */
1053
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1053
+	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1054 1054
 		$extraData = $this->getDenormalizedData($calendarData);
1055 1055
 
1056 1056
 		$q = $this->db->getQueryBuilder();
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
 		}
1112 1112
 		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1113 1113
 
1114
-		return '"' . $extraData['etag'] . '"';
1114
+		return '"'.$extraData['etag'].'"';
1115 1115
 	}
1116 1116
 
1117 1117
 	/**
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
 	 * @param int $calendarType
1134 1134
 	 * @return string
1135 1135
 	 */
1136
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1136
+	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1137 1137
 		$extraData = $this->getDenormalizedData($calendarData);
1138 1138
 
1139 1139
 		$query = $this->db->getQueryBuilder();
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
 		}
1181 1181
 		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1182 1182
 
1183
-		return '"' . $extraData['etag'] . '"';
1183
+		return '"'.$extraData['etag'].'"';
1184 1184
 	}
1185 1185
 
1186 1186
 	/**
@@ -1210,7 +1210,7 @@  discard block
 block discarded – undo
1210 1210
 	 * @param int $calendarType
1211 1211
 	 * @return void
1212 1212
 	 */
1213
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1213
+	function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1214 1214
 		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1215 1215
 		if (is_array($data)) {
1216 1216
 			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
@@ -1294,7 +1294,7 @@  discard block
 block discarded – undo
1294 1294
 	 * @param int $calendarType
1295 1295
 	 * @return array
1296 1296
 	 */
1297
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1297
+	public function calendarQuery($id, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1298 1298
 		$componentType = null;
1299 1299
 		$requirePostFilter = true;
1300 1300
 		$timeRange = null;
@@ -1348,13 +1348,13 @@  discard block
 block discarded – undo
1348 1348
 		$stmt = $query->execute();
1349 1349
 
1350 1350
 		$result = [];
1351
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1351
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1352 1352
 			if ($requirePostFilter) {
1353 1353
 				// validateFilterForObject will parse the calendar data
1354 1354
 				// catch parsing errors
1355 1355
 				try {
1356 1356
 					$matches = $this->validateFilterForObject($row, $filters);
1357
-				} catch(ParseException $ex) {
1357
+				} catch (ParseException $ex) {
1358 1358
 					$this->logger->logException($ex, [
1359 1359
 						'app' => 'dav',
1360 1360
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
@@ -1389,14 +1389,14 @@  discard block
 block discarded – undo
1389 1389
 	 * @param integer|null $offset
1390 1390
 	 * @return array
1391 1391
 	 */
1392
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1392
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1393 1393
 		$calendars = $this->getCalendarsForUser($principalUri);
1394 1394
 		$ownCalendars = [];
1395 1395
 		$sharedCalendars = [];
1396 1396
 
1397 1397
 		$uriMapper = [];
1398 1398
 
1399
-		foreach($calendars as $calendar) {
1399
+		foreach ($calendars as $calendar) {
1400 1400
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1401 1401
 				$ownCalendars[] = $calendar['id'];
1402 1402
 			} else {
@@ -1411,14 +1411,14 @@  discard block
 block discarded – undo
1411 1411
 		$query = $this->db->getQueryBuilder();
1412 1412
 		// Calendar id expressions
1413 1413
 		$calendarExpressions = [];
1414
-		foreach($ownCalendars as $id) {
1414
+		foreach ($ownCalendars as $id) {
1415 1415
 			$calendarExpressions[] = $query->expr()->andX(
1416 1416
 				$query->expr()->eq('c.calendarid',
1417 1417
 					$query->createNamedParameter($id)),
1418 1418
 				$query->expr()->eq('c.calendartype',
1419 1419
 						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420 1420
 		}
1421
-		foreach($sharedCalendars as $id) {
1421
+		foreach ($sharedCalendars as $id) {
1422 1422
 			$calendarExpressions[] = $query->expr()->andX(
1423 1423
 				$query->expr()->eq('c.calendarid',
1424 1424
 					$query->createNamedParameter($id)),
@@ -1436,7 +1436,7 @@  discard block
 block discarded – undo
1436 1436
 
1437 1437
 		// Component expressions
1438 1438
 		$compExpressions = [];
1439
-		foreach($filters['comps'] as $comp) {
1439
+		foreach ($filters['comps'] as $comp) {
1440 1440
 			$compExpressions[] = $query->expr()
1441 1441
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1442 1442
 		}
@@ -1455,13 +1455,13 @@  discard block
 block discarded – undo
1455 1455
 		}
1456 1456
 
1457 1457
 		$propParamExpressions = [];
1458
-		foreach($filters['props'] as $prop) {
1458
+		foreach ($filters['props'] as $prop) {
1459 1459
 			$propParamExpressions[] = $query->expr()->andX(
1460 1460
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1461 1461
 				$query->expr()->isNull('i.parameter')
1462 1462
 			);
1463 1463
 		}
1464
-		foreach($filters['params'] as $param) {
1464
+		foreach ($filters['params'] as $param) {
1465 1465
 			$propParamExpressions[] = $query->expr()->andX(
1466 1466
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1467 1467
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1493,8 +1493,8 @@  discard block
 block discarded – undo
1493 1493
 		$stmt = $query->execute();
1494 1494
 
1495 1495
 		$result = [];
1496
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1497
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1496
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1497
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1498 1498
 			if (!in_array($path, $result)) {
1499 1499
 				$result[] = $path;
1500 1500
 			}
@@ -1534,7 +1534,7 @@  discard block
 block discarded – undo
1534 1534
 		}
1535 1535
 
1536 1536
 		$or = $innerQuery->expr()->orX();
1537
-		foreach($searchProperties as $searchProperty) {
1537
+		foreach ($searchProperties as $searchProperty) {
1538 1538
 			$or->add($innerQuery->expr()->eq('op.name',
1539 1539
 				$outerQuery->createNamedParameter($searchProperty)));
1540 1540
 		}
@@ -1542,8 +1542,8 @@  discard block
 block discarded – undo
1542 1542
 
1543 1543
 		if ($pattern !== '') {
1544 1544
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1545
-				$outerQuery->createNamedParameter('%' .
1546
-					$this->db->escapeLikeParameter($pattern) . '%')));
1545
+				$outerQuery->createNamedParameter('%'.
1546
+					$this->db->escapeLikeParameter($pattern).'%')));
1547 1547
 		}
1548 1548
 
1549 1549
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1563,7 +1563,7 @@  discard block
 block discarded – undo
1563 1563
 
1564 1564
 		if (isset($options['types'])) {
1565 1565
 			$or = $outerQuery->expr()->orX();
1566
-			foreach($options['types'] as $type) {
1566
+			foreach ($options['types'] as $type) {
1567 1567
 				$or->add($outerQuery->expr()->eq('componenttype',
1568 1568
 					$outerQuery->createNamedParameter($type)));
1569 1569
 			}
@@ -1588,7 +1588,7 @@  discard block
 block discarded – undo
1588 1588
 			$comps = $calendarData->getComponents();
1589 1589
 			$objects = [];
1590 1590
 			$timezones = [];
1591
-			foreach($comps as $comp) {
1591
+			foreach ($comps as $comp) {
1592 1592
 				if ($comp instanceof VTimeZone) {
1593 1593
 					$timezones[] = $comp;
1594 1594
 				} else {
@@ -1625,7 +1625,7 @@  discard block
 block discarded – undo
1625 1625
 		});
1626 1626
 		$validationRules = $comp->getValidationRules();
1627 1627
 
1628
-		foreach($subComponents as $subComponent) {
1628
+		foreach ($subComponents as $subComponent) {
1629 1629
 			$name = $subComponent->name;
1630 1630
 			if (!isset($data[$name])) {
1631 1631
 				$data[$name] = [];
@@ -1633,7 +1633,7 @@  discard block
 block discarded – undo
1633 1633
 			$data[$name][] = $this->transformSearchData($subComponent);
1634 1634
 		}
1635 1635
 
1636
-		foreach($properties as $property) {
1636
+		foreach ($properties as $property) {
1637 1637
 			$name = $property->name;
1638 1638
 			if (!isset($validationRules[$name])) {
1639 1639
 				$validationRules[$name] = '*';
@@ -1704,7 +1704,7 @@  discard block
 block discarded – undo
1704 1704
 		$stmt = $query->execute();
1705 1705
 
1706 1706
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1707
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1707
+			return $row['calendaruri'].'/'.$row['objecturi'];
1708 1708
 		}
1709 1709
 
1710 1710
 		return null;
@@ -1767,10 +1767,10 @@  discard block
 block discarded – undo
1767 1767
 	 * @param int $calendarType
1768 1768
 	 * @return array
1769 1769
 	 */
1770
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1770
+	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1771 1771
 		// Current synctoken
1772 1772
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1773
-		$stmt->execute([ $calendarId ]);
1773
+		$stmt->execute([$calendarId]);
1774 1774
 		$currentToken = $stmt->fetchColumn(0);
1775 1775
 
1776 1776
 		if (is_null($currentToken)) {
@@ -1787,8 +1787,8 @@  discard block
 block discarded – undo
1787 1787
 		if ($syncToken) {
1788 1788
 
1789 1789
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1790
-			if ($limit>0) {
1791
-				$query.= " LIMIT " . (int)$limit;
1790
+			if ($limit > 0) {
1791
+				$query .= " LIMIT ".(int) $limit;
1792 1792
 			}
1793 1793
 
1794 1794
 			// Fetching all changes
@@ -1799,15 +1799,15 @@  discard block
 block discarded – undo
1799 1799
 
1800 1800
 			// This loop ensures that any duplicates are overwritten, only the
1801 1801
 			// last change on a node is relevant.
1802
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1802
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1803 1803
 
1804 1804
 				$changes[$row['uri']] = $row['operation'];
1805 1805
 
1806 1806
 			}
1807 1807
 
1808
-			foreach($changes as $uri => $operation) {
1808
+			foreach ($changes as $uri => $operation) {
1809 1809
 
1810
-				switch($operation) {
1810
+				switch ($operation) {
1811 1811
 					case 1 :
1812 1812
 						$result['added'][] = $uri;
1813 1813
 						break;
@@ -1878,10 +1878,10 @@  discard block
 block discarded – undo
1878 1878
 			->from('calendarsubscriptions')
1879 1879
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1880 1880
 			->orderBy('calendarorder', 'asc');
1881
-		$stmt =$query->execute();
1881
+		$stmt = $query->execute();
1882 1882
 
1883 1883
 		$subscriptions = [];
1884
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1884
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1885 1885
 
1886 1886
 			$subscription = [
1887 1887
 				'id'           => $row['id'],
@@ -1890,11 +1890,11 @@  discard block
 block discarded – undo
1890 1890
 				'source'       => $row['source'],
1891 1891
 				'lastmodified' => $row['lastmodified'],
1892 1892
 
1893
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1894
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1893
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1894
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
1895 1895
 			];
1896 1896
 
1897
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1897
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1898 1898
 				if (!is_null($row[$dbName])) {
1899 1899
 					$subscription[$xmlName] = $row[$dbName];
1900 1900
 				}
@@ -1933,7 +1933,7 @@  discard block
 block discarded – undo
1933 1933
 
1934 1934
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1935 1935
 
1936
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1936
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1937 1937
 			if (array_key_exists($xmlName, $properties)) {
1938 1938
 					$values[$dbName] = $properties[$xmlName];
1939 1939
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1993,7 +1993,7 @@  discard block
 block discarded – undo
1993 1993
 
1994 1994
 			$newValues = [];
1995 1995
 
1996
-			foreach($mutations as $propertyName=>$propertyValue) {
1996
+			foreach ($mutations as $propertyName=>$propertyValue) {
1997 1997
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1998 1998
 					$newValues['source'] = $propertyValue->getHref();
1999 1999
 				} else {
@@ -2005,7 +2005,7 @@  discard block
 block discarded – undo
2005 2005
 			$query = $this->db->getQueryBuilder();
2006 2006
 			$query->update('calendarsubscriptions')
2007 2007
 				->set('lastmodified', $query->createNamedParameter(time()));
2008
-			foreach($newValues as $fieldName=>$value) {
2008
+			foreach ($newValues as $fieldName=>$value) {
2009 2009
 				$query->set($fieldName, $query->createNamedParameter($value));
2010 2010
 			}
2011 2011
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -2086,7 +2086,7 @@  discard block
 block discarded – undo
2086 2086
 
2087 2087
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2088 2088
 
2089
-		if(!$row) {
2089
+		if (!$row) {
2090 2090
 			return null;
2091 2091
 		}
2092 2092
 
@@ -2094,8 +2094,8 @@  discard block
 block discarded – undo
2094 2094
 				'uri'          => $row['uri'],
2095 2095
 				'calendardata' => $row['calendardata'],
2096 2096
 				'lastmodified' => $row['lastmodified'],
2097
-				'etag'         => '"' . $row['etag'] . '"',
2098
-				'size'         => (int)$row['size'],
2097
+				'etag'         => '"'.$row['etag'].'"',
2098
+				'size'         => (int) $row['size'],
2099 2099
 		];
2100 2100
 	}
2101 2101
 
@@ -2118,13 +2118,13 @@  discard block
 block discarded – undo
2118 2118
 				->execute();
2119 2119
 
2120 2120
 		$result = [];
2121
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2121
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2122 2122
 			$result[] = [
2123 2123
 					'calendardata' => $row['calendardata'],
2124 2124
 					'uri'          => $row['uri'],
2125 2125
 					'lastmodified' => $row['lastmodified'],
2126
-					'etag'         => '"' . $row['etag'] . '"',
2127
-					'size'         => (int)$row['size'],
2126
+					'etag'         => '"'.$row['etag'].'"',
2127
+					'size'         => (int) $row['size'],
2128 2128
 			];
2129 2129
 		}
2130 2130
 
@@ -2177,14 +2177,14 @@  discard block
 block discarded – undo
2177 2177
 	 * @param int $calendarType
2178 2178
 	 * @return void
2179 2179
 	 */
2180
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2181
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2180
+	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2181
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2182 2182
 
2183 2183
 		$query = $this->db->getQueryBuilder();
2184 2184
 		$query->select('synctoken')
2185 2185
 			->from($table)
2186 2186
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2187
-		$syncToken = (int)$query->execute()->fetchColumn();
2187
+		$syncToken = (int) $query->execute()->fetchColumn();
2188 2188
 
2189 2189
 		$query = $this->db->getQueryBuilder();
2190 2190
 		$query->insert('calendarchanges')
@@ -2228,10 +2228,10 @@  discard block
 block discarded – undo
2228 2228
 		$lastOccurrence = null;
2229 2229
 		$uid = null;
2230 2230
 		$classification = self::CLASSIFICATION_PUBLIC;
2231
-		foreach($vObject->getComponents() as $component) {
2232
-			if ($component->name!=='VTIMEZONE') {
2231
+		foreach ($vObject->getComponents() as $component) {
2232
+			if ($component->name !== 'VTIMEZONE') {
2233 2233
 				$componentType = $component->name;
2234
-				$uid = (string)$component->UID;
2234
+				$uid = (string) $component->UID;
2235 2235
 				break;
2236 2236
 			}
2237 2237
 		}
@@ -2256,13 +2256,13 @@  discard block
 block discarded – undo
2256 2256
 					$lastOccurrence = $firstOccurrence;
2257 2257
 				}
2258 2258
 			} else {
2259
-				$it = new EventIterator($vObject, (string)$component->UID);
2259
+				$it = new EventIterator($vObject, (string) $component->UID);
2260 2260
 				$maxDate = new \DateTime(self::MAX_DATE);
2261 2261
 				if ($it->isInfinite()) {
2262 2262
 					$lastOccurrence = $maxDate->getTimestamp();
2263 2263
 				} else {
2264 2264
 					$end = $it->getDtEnd();
2265
-					while($it->valid() && $end < $maxDate) {
2265
+					while ($it->valid() && $end < $maxDate) {
2266 2266
 						$end = $it->getDtEnd();
2267 2267
 						$it->next();
2268 2268
 
@@ -2332,7 +2332,7 @@  discard block
 block discarded – undo
2332 2332
 	 * @param int $calendarType
2333 2333
 	 * @return array
2334 2334
 	 */
2335
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2335
+	public function getShares($resourceId, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2336 2336
 		return $this->calendarSharingBackend->getShares($resourceId);
2337 2337
 	}
2338 2338
 
@@ -2409,7 +2409,7 @@  discard block
 block discarded – undo
2409 2409
 	 * @param string $calendarData
2410 2410
 	 * @param int $calendarType
2411 2411
 	 */
2412
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2412
+	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2413 2413
 		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2414 2414
 
2415 2415
 		try {
@@ -2487,7 +2487,7 @@  discard block
 block discarded – undo
2487 2487
 			->execute();
2488 2488
 
2489 2489
 		$ids = $result->fetchAll();
2490
-		foreach($ids as $id) {
2490
+		foreach ($ids as $id) {
2491 2491
 			$this->deleteCalendar($id['id']);
2492 2492
 		}
2493 2493
 	}
@@ -2504,7 +2504,7 @@  discard block
 block discarded – undo
2504 2504
 		$stmt = $query->execute();
2505 2505
 
2506 2506
 		$uris = [];
2507
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2507
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2508 2508
 			$uris[] = $row['uri'];
2509 2509
 		}
2510 2510
 		$stmt->closeCursor();
@@ -2525,7 +2525,7 @@  discard block
 block discarded – undo
2525 2525
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2526 2526
 			->execute();
2527 2527
 
2528
-		foreach($uris as $uri) {
2528
+		foreach ($uris as $uri) {
2529 2529
 			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2530 2530
 		}
2531 2531
 	}
@@ -2592,10 +2592,10 @@  discard block
 block discarded – undo
2592 2592
 		$result->closeCursor();
2593 2593
 
2594 2594
 		if (!isset($objectIds['id'])) {
2595
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2595
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2596 2596
 		}
2597 2597
 
2598
-		return (int)$objectIds['id'];
2598
+		return (int) $objectIds['id'];
2599 2599
 	}
2600 2600
 
2601 2601
 	/**
@@ -2622,8 +2622,8 @@  discard block
 block discarded – undo
2622 2622
 	 * @param $calendarInfo
2623 2623
 	 */
2624 2624
 	private function addOwnerPrincipal(&$calendarInfo) {
2625
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2626
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2625
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2626
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2627 2627
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2628 2628
 			$uri = $calendarInfo[$ownerPrincipalKey];
2629 2629
 		} else {
Please login to merge, or discard this patch.