Completed
Push — stable10 ( e55881...b0ab3b )
by Joas
36:13 queued 35:48
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +1388 added lines, -1388 removed lines patch added patch discarded remove patch
@@ -54,1392 +54,1392 @@
 block discarded – undo
54 54
  */
55 55
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
56 56
 
57
-	/**
58
-	 * We need to specify a max date, because we need to stop *somewhere*
59
-	 *
60
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
61
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
62
-	 * in 2038-01-19 to avoid problems when the date is converted
63
-	 * to a unix timestamp.
64
-	 */
65
-	const MAX_DATE = '2038-01-01';
66
-
67
-	const CLASSIFICATION_PUBLIC = 0;
68
-	const CLASSIFICATION_PRIVATE = 1;
69
-	const CLASSIFICATION_CONFIDENTIAL = 2;
70
-
71
-	/**
72
-	 * List of CalDAV properties, and how they map to database field names
73
-	 * Add your own properties by simply adding on to this array.
74
-	 *
75
-	 * Note that only string-based properties are supported here.
76
-	 *
77
-	 * @var array
78
-	 */
79
-	public $propertyMap = [
80
-		'{DAV:}displayname'                          => 'displayname',
81
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
82
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
83
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
84
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
85
-	];
86
-
87
-	/**
88
-	 * List of subscription properties, and how they map to database field names.
89
-	 *
90
-	 * @var array
91
-	 */
92
-	public $subscriptionPropertyMap = [
93
-		'{DAV:}displayname'                                           => 'displayname',
94
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
95
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
96
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
97
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
98
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
99
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
100
-	];
101
-
102
-	/** @var IDBConnection */
103
-	private $db;
104
-
105
-	/** @var Backend */
106
-	private $sharingBackend;
107
-
108
-	/** @var Principal */
109
-	private $principalBackend;
110
-
111
-	/**
112
-	 * CalDavBackend constructor.
113
-	 *
114
-	 * @param IDBConnection $db
115
-	 * @param Principal $principalBackend
116
-	 */
117
-	public function __construct(IDBConnection $db, Principal $principalBackend) {
118
-		$this->db = $db;
119
-		$this->principalBackend = $principalBackend;
120
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
121
-	}
122
-
123
-	/**
124
-	 * Returns a list of calendars for a principal.
125
-	 *
126
-	 * Every project is an array with the following keys:
127
-	 *  * id, a unique id that will be used by other functions to modify the
128
-	 *    calendar. This can be the same as the uri or a database key.
129
-	 *  * uri, which the basename of the uri with which the calendar is
130
-	 *    accessed.
131
-	 *  * principaluri. The owner of the calendar. Almost always the same as
132
-	 *    principalUri passed to this method.
133
-	 *
134
-	 * Furthermore it can contain webdav properties in clark notation. A very
135
-	 * common one is '{DAV:}displayname'.
136
-	 *
137
-	 * Many clients also require:
138
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
139
-	 * For this property, you can just return an instance of
140
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
141
-	 *
142
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
143
-	 * ACL will automatically be put in read-only mode.
144
-	 *
145
-	 * @param string $principalUri
146
-	 * @return array
147
-	 */
148
-	function getCalendarsForUser($principalUri) {
149
-		$principalUriOriginal = $principalUri;
150
-		$principalUri = $this->convertPrincipal($principalUri, true);
151
-		$fields = array_values($this->propertyMap);
152
-		$fields[] = 'id';
153
-		$fields[] = 'uri';
154
-		$fields[] = 'synctoken';
155
-		$fields[] = 'components';
156
-		$fields[] = 'principaluri';
157
-		$fields[] = 'transparent';
158
-
159
-		// Making fields a comma-delimited list
160
-		$query = $this->db->getQueryBuilder();
161
-		$query->select($fields)->from('calendars')
162
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
163
-				->orderBy('calendarorder', 'ASC');
164
-		$stmt = $query->execute();
165
-
166
-		$calendars = [];
167
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
168
-
169
-			$components = [];
170
-			if ($row['components']) {
171
-				$components = explode(',',$row['components']);
172
-			}
173
-
174
-			$calendar = [
175
-				'id' => $row['id'],
176
-				'uri' => $row['uri'],
177
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
178
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
179
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
180
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
181
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
182
-			];
183
-
184
-			foreach($this->propertyMap as $xmlName=>$dbName) {
185
-				$calendar[$xmlName] = $row[$dbName];
186
-			}
187
-
188
-			if (!isset($calendars[$calendar['id']])) {
189
-				$calendars[$calendar['id']] = $calendar;
190
-			}
191
-		}
192
-
193
-		$stmt->closeCursor();
194
-
195
-		// query for shared calendars
196
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
197
-		$principals[]= $principalUri;
198
-
199
-		$fields = array_values($this->propertyMap);
200
-		$fields[] = 'a.id';
201
-		$fields[] = 'a.uri';
202
-		$fields[] = 'a.synctoken';
203
-		$fields[] = 'a.components';
204
-		$fields[] = 'a.principaluri';
205
-		$fields[] = 'a.transparent';
206
-		$fields[] = 's.access';
207
-		$query = $this->db->getQueryBuilder();
208
-		$result = $query->select($fields)
209
-			->from('dav_shares', 's')
210
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
211
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
212
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
213
-			->setParameter('type', 'calendar')
214
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
215
-			->execute();
216
-
217
-		while($row = $result->fetch()) {
218
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
219
-			$uri = $row['uri'] . '_shared_by_' . $name;
220
-			$row['displayname'] = $row['displayname'] . "($name)";
221
-			$components = [];
222
-			if ($row['components']) {
223
-				$components = explode(',',$row['components']);
224
-			}
225
-			$calendar = [
226
-				'id' => $row['id'],
227
-				'uri' => $uri,
228
-				'principaluri' => $principalUri,
229
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
232
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
233
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
234
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
235
-			];
236
-
237
-			foreach($this->propertyMap as $xmlName=>$dbName) {
238
-				$calendar[$xmlName] = $row[$dbName];
239
-			}
240
-
241
-			if (!isset($calendars[$calendar['id']])) {
242
-				$calendars[$calendar['id']] = $calendar;
243
-			}
244
-		}
245
-		$result->closeCursor();
246
-
247
-		return array_values($calendars);
248
-	}
249
-
250
-	/**
251
-	 * @param string $principal
252
-	 * @param string $uri
253
-	 * @return array|null
254
-	 */
255
-	public function getCalendarByUri($principal, $uri) {
256
-		$fields = array_values($this->propertyMap);
257
-		$fields[] = 'id';
258
-		$fields[] = 'uri';
259
-		$fields[] = 'synctoken';
260
-		$fields[] = 'components';
261
-		$fields[] = 'principaluri';
262
-		$fields[] = 'transparent';
263
-
264
-		// Making fields a comma-delimited list
265
-		$query = $this->db->getQueryBuilder();
266
-		$query->select($fields)->from('calendars')
267
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
268
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
269
-			->setMaxResults(1);
270
-		$stmt = $query->execute();
271
-
272
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
273
-		$stmt->closeCursor();
274
-		if ($row === false) {
275
-			return null;
276
-		}
277
-
278
-		$components = [];
279
-		if ($row['components']) {
280
-			$components = explode(',',$row['components']);
281
-		}
282
-
283
-		$calendar = [
284
-			'id' => $row['id'],
285
-			'uri' => $row['uri'],
286
-			'principaluri' => $row['principaluri'],
287
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
-		];
292
-
293
-		foreach($this->propertyMap as $xmlName=>$dbName) {
294
-			$calendar[$xmlName] = $row[$dbName];
295
-		}
296
-
297
-		return $calendar;
298
-	}
299
-
300
-	public function getCalendarById($calendarId) {
301
-		$fields = array_values($this->propertyMap);
302
-		$fields[] = 'id';
303
-		$fields[] = 'uri';
304
-		$fields[] = 'synctoken';
305
-		$fields[] = 'components';
306
-		$fields[] = 'principaluri';
307
-		$fields[] = 'transparent';
308
-
309
-		// Making fields a comma-delimited list
310
-		$query = $this->db->getQueryBuilder();
311
-		$query->select($fields)->from('calendars')
312
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
313
-			->setMaxResults(1);
314
-		$stmt = $query->execute();
315
-
316
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
317
-		$stmt->closeCursor();
318
-		if ($row === false) {
319
-			return null;
320
-		}
321
-
322
-		$components = [];
323
-		if ($row['components']) {
324
-			$components = explode(',',$row['components']);
325
-		}
326
-
327
-		$calendar = [
328
-			'id' => $row['id'],
329
-			'uri' => $row['uri'],
330
-			'principaluri' => $row['principaluri'],
331
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
332
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
334
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
335
-		];
336
-
337
-		foreach($this->propertyMap as $xmlName=>$dbName) {
338
-			$calendar[$xmlName] = $row[$dbName];
339
-		}
340
-
341
-		return $calendar;
342
-	}
343
-
344
-	/**
345
-	 * Creates a new calendar for a principal.
346
-	 *
347
-	 * If the creation was a success, an id must be returned that can be used to reference
348
-	 * this calendar in other methods, such as updateCalendar.
349
-	 *
350
-	 * @param string $principalUri
351
-	 * @param string $calendarUri
352
-	 * @param array $properties
353
-	 * @return int
354
-	 */
355
-	function createCalendar($principalUri, $calendarUri, array $properties) {
356
-		$values = [
357
-			'principaluri' => $this->convertPrincipal($principalUri, true),
358
-			'uri'          => $calendarUri,
359
-			'synctoken'    => 1,
360
-			'transparent'  => 0,
361
-			'components'   => 'VEVENT,VTODO',
362
-			'displayname'  => $calendarUri
363
-		];
364
-
365
-		// Default value
366
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
367
-		if (isset($properties[$sccs])) {
368
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
369
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
370
-			}
371
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
372
-		}
373
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
374
-		if (isset($properties[$transp])) {
375
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
376
-		}
377
-
378
-		foreach($this->propertyMap as $xmlName=>$dbName) {
379
-			if (isset($properties[$xmlName])) {
380
-				$values[$dbName] = $properties[$xmlName];
381
-			}
382
-		}
383
-
384
-		$query = $this->db->getQueryBuilder();
385
-		$query->insert('calendars');
386
-		foreach($values as $column => $value) {
387
-			$query->setValue($column, $query->createNamedParameter($value));
388
-		}
389
-		$query->execute();
390
-		return $query->getLastInsertId();
391
-	}
392
-
393
-	/**
394
-	 * Updates properties for a calendar.
395
-	 *
396
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
397
-	 * To do the actual updates, you must tell this object which properties
398
-	 * you're going to process with the handle() method.
399
-	 *
400
-	 * Calling the handle method is like telling the PropPatch object "I
401
-	 * promise I can handle updating this property".
402
-	 *
403
-	 * Read the PropPatch documentation for more info and examples.
404
-	 *
405
-	 * @param PropPatch $propPatch
406
-	 * @return void
407
-	 */
408
-	function updateCalendar($calendarId, PropPatch $propPatch) {
409
-		$supportedProperties = array_keys($this->propertyMap);
410
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
411
-
412
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
413
-			$newValues = [];
414
-			foreach ($mutations as $propertyName => $propertyValue) {
415
-
416
-				switch ($propertyName) {
417
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
418
-						$fieldName = 'transparent';
419
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
420
-						break;
421
-					default :
422
-						$fieldName = $this->propertyMap[$propertyName];
423
-						$newValues[$fieldName] = $propertyValue;
424
-						break;
425
-				}
426
-
427
-			}
428
-			$query = $this->db->getQueryBuilder();
429
-			$query->update('calendars');
430
-			foreach ($newValues as $fieldName => $value) {
431
-				$query->set($fieldName, $query->createNamedParameter($value));
432
-			}
433
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
434
-			$query->execute();
435
-
436
-			$this->addChange($calendarId, "", 2);
437
-
438
-			return true;
439
-		});
440
-	}
441
-
442
-	/**
443
-	 * Delete a calendar and all it's objects
444
-	 *
445
-	 * @param mixed $calendarId
446
-	 * @return void
447
-	 */
448
-	function deleteCalendar($calendarId) {
449
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
450
-		$stmt->execute([$calendarId]);
451
-
452
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
453
-		$stmt->execute([$calendarId]);
454
-
455
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
456
-		$stmt->execute([$calendarId]);
457
-
458
-		$this->sharingBackend->deleteAllShares($calendarId);
459
-	}
460
-
461
-	/**
462
-	 * Returns all calendar objects within a calendar.
463
-	 *
464
-	 * Every item contains an array with the following keys:
465
-	 *   * calendardata - The iCalendar-compatible calendar data
466
-	 *   * uri - a unique key which will be used to construct the uri. This can
467
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
468
-	 *     good idea. This is only the basename, or filename, not the full
469
-	 *     path.
470
-	 *   * lastmodified - a timestamp of the last modification time
471
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
472
-	 *   '"abcdef"')
473
-	 *   * size - The size of the calendar objects, in bytes.
474
-	 *   * component - optional, a string containing the type of object, such
475
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
476
-	 *     the Content-Type header.
477
-	 *
478
-	 * Note that the etag is optional, but it's highly encouraged to return for
479
-	 * speed reasons.
480
-	 *
481
-	 * The calendardata is also optional. If it's not returned
482
-	 * 'getCalendarObject' will be called later, which *is* expected to return
483
-	 * calendardata.
484
-	 *
485
-	 * If neither etag or size are specified, the calendardata will be
486
-	 * used/fetched to determine these numbers. If both are specified the
487
-	 * amount of times this is needed is reduced by a great degree.
488
-	 *
489
-	 * @param mixed $calendarId
490
-	 * @return array
491
-	 */
492
-	function getCalendarObjects($calendarId) {
493
-		$query = $this->db->getQueryBuilder();
494
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
495
-			->from('calendarobjects')
496
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
497
-		$stmt = $query->execute();
498
-
499
-		$result = [];
500
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
501
-			$result[] = [
502
-					'id'           => $row['id'],
503
-					'uri'          => $row['uri'],
504
-					'lastmodified' => $row['lastmodified'],
505
-					'etag'         => '"' . $row['etag'] . '"',
506
-					'calendarid'   => $row['calendarid'],
507
-					'size'         => (int)$row['size'],
508
-					'component'    => strtolower($row['componenttype']),
509
-					'classification'=> (int)$row['classification']
510
-			];
511
-		}
512
-
513
-		return $result;
514
-	}
515
-
516
-	/**
517
-	 * Returns information from a single calendar object, based on it's object
518
-	 * uri.
519
-	 *
520
-	 * The object uri is only the basename, or filename and not a full path.
521
-	 *
522
-	 * The returned array must have the same keys as getCalendarObjects. The
523
-	 * 'calendardata' object is required here though, while it's not required
524
-	 * for getCalendarObjects.
525
-	 *
526
-	 * This method must return null if the object did not exist.
527
-	 *
528
-	 * @param mixed $calendarId
529
-	 * @param string $objectUri
530
-	 * @return array|null
531
-	 */
532
-	function getCalendarObject($calendarId, $objectUri) {
533
-
534
-		$query = $this->db->getQueryBuilder();
535
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
536
-				->from('calendarobjects')
537
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
538
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
539
-		$stmt = $query->execute();
540
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
541
-
542
-		if(!$row) return null;
543
-
544
-		return [
545
-				'id'            => $row['id'],
546
-				'uri'           => $row['uri'],
547
-				'lastmodified'  => $row['lastmodified'],
548
-				'etag'          => '"' . $row['etag'] . '"',
549
-				'calendarid'    => $row['calendarid'],
550
-				'size'          => (int)$row['size'],
551
-				'calendardata'  => $this->readBlob($row['calendardata']),
552
-				'component'     => strtolower($row['componenttype']),
553
-				'classification'=> (int)$row['classification']
554
-		];
555
-	}
556
-
557
-	/**
558
-	 * Returns a list of calendar objects.
559
-	 *
560
-	 * This method should work identical to getCalendarObject, but instead
561
-	 * return all the calendar objects in the list as an array.
562
-	 *
563
-	 * If the backend supports this, it may allow for some speed-ups.
564
-	 *
565
-	 * @param mixed $calendarId
566
-	 * @param string[] $uris
567
-	 * @return array
568
-	 */
569
-	function getMultipleCalendarObjects($calendarId, array $uris) {
570
-		if (empty($uris)) {
571
-			return [];
572
-		}
573
-
574
-		$chunks = array_chunk($uris, 100);
575
-		$objects = [];
576
-
577
-		$query = $this->db->getQueryBuilder();
578
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
579
-			->from('calendarobjects')
580
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
581
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
582
-
583
-		foreach ($chunks as $uris) {
584
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
585
-			$result = $query->execute();
586
-
587
-			while ($row = $result->fetch()) {
588
-				$objects[] = [
589
-					'id'           => $row['id'],
590
-					'uri'          => $row['uri'],
591
-					'lastmodified' => $row['lastmodified'],
592
-					'etag'         => '"' . $row['etag'] . '"',
593
-					'calendarid'   => $row['calendarid'],
594
-					'size'         => (int)$row['size'],
595
-					'calendardata' => $this->readBlob($row['calendardata']),
596
-					'component'    => strtolower($row['componenttype']),
597
-					'classification' => (int)$row['classification']
598
-				];
599
-			}
600
-			$result->closeCursor();
601
-		}
602
-		return $objects;
603
-	}
604
-
605
-	/**
606
-	 * Creates a new calendar object.
607
-	 *
608
-	 * The object uri is only the basename, or filename and not a full path.
609
-	 *
610
-	 * It is possible return an etag from this function, which will be used in
611
-	 * the response to this PUT request. Note that the ETag must be surrounded
612
-	 * by double-quotes.
613
-	 *
614
-	 * However, you should only really return this ETag if you don't mangle the
615
-	 * calendar-data. If the result of a subsequent GET to this object is not
616
-	 * the exact same as this request body, you should omit the ETag.
617
-	 *
618
-	 * @param mixed $calendarId
619
-	 * @param string $objectUri
620
-	 * @param string $calendarData
621
-	 * @return string
622
-	 */
623
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
624
-		$extraData = $this->getDenormalizedData($calendarData);
625
-
626
-		$query = $this->db->getQueryBuilder();
627
-		$query->insert('calendarobjects')
628
-			->values([
629
-				'calendarid' => $query->createNamedParameter($calendarId),
630
-				'uri' => $query->createNamedParameter($objectUri),
631
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
632
-				'lastmodified' => $query->createNamedParameter(time()),
633
-				'etag' => $query->createNamedParameter($extraData['etag']),
634
-				'size' => $query->createNamedParameter($extraData['size']),
635
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
636
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
637
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
638
-				'classification' => $query->createNamedParameter($extraData['classification']),
639
-				'uid' => $query->createNamedParameter($extraData['uid']),
640
-			])
641
-			->execute();
642
-
643
-		$this->addChange($calendarId, $objectUri, 1);
644
-
645
-		return '"' . $extraData['etag'] . '"';
646
-	}
647
-
648
-	/**
649
-	 * Updates an existing calendarobject, based on it's uri.
650
-	 *
651
-	 * The object uri is only the basename, or filename and not a full path.
652
-	 *
653
-	 * It is possible return an etag from this function, which will be used in
654
-	 * the response to this PUT request. Note that the ETag must be surrounded
655
-	 * by double-quotes.
656
-	 *
657
-	 * However, you should only really return this ETag if you don't mangle the
658
-	 * calendar-data. If the result of a subsequent GET to this object is not
659
-	 * the exact same as this request body, you should omit the ETag.
660
-	 *
661
-	 * @param mixed $calendarId
662
-	 * @param string $objectUri
663
-	 * @param string $calendarData
664
-	 * @return string
665
-	 */
666
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
667
-		$extraData = $this->getDenormalizedData($calendarData);
668
-
669
-		$query = $this->db->getQueryBuilder();
670
-		$query->update('calendarobjects')
671
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
672
-				->set('lastmodified', $query->createNamedParameter(time()))
673
-				->set('etag', $query->createNamedParameter($extraData['etag']))
674
-				->set('size', $query->createNamedParameter($extraData['size']))
675
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
676
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
677
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
678
-				->set('classification', $query->createNamedParameter($extraData['classification']))
679
-				->set('uid', $query->createNamedParameter($extraData['uid']))
680
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
681
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
682
-			->execute();
683
-
684
-		$this->addChange($calendarId, $objectUri, 2);
685
-
686
-		return '"' . $extraData['etag'] . '"';
687
-	}
688
-
689
-	/**
690
-	 * @param int $calendarObjectId
691
-	 * @param int $classification
692
-	 */
693
-	public function setClassification($calendarObjectId, $classification) {
694
-		if (!in_array($classification, [
695
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
696
-		])) {
697
-			throw new \InvalidArgumentException();
698
-		}
699
-		$query = $this->db->getQueryBuilder();
700
-		$query->update('calendarobjects')
701
-			->set('classification', $query->createNamedParameter($classification))
702
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
703
-			->execute();
704
-	}
705
-
706
-	/**
707
-	 * Deletes an existing calendar object.
708
-	 *
709
-	 * The object uri is only the basename, or filename and not a full path.
710
-	 *
711
-	 * @param mixed $calendarId
712
-	 * @param string $objectUri
713
-	 * @return void
714
-	 */
715
-	function deleteCalendarObject($calendarId, $objectUri) {
716
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
717
-		$stmt->execute([$calendarId, $objectUri]);
718
-
719
-		$this->addChange($calendarId, $objectUri, 3);
720
-	}
721
-
722
-	/**
723
-	 * Performs a calendar-query on the contents of this calendar.
724
-	 *
725
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
726
-	 * calendar-query it is possible for a client to request a specific set of
727
-	 * object, based on contents of iCalendar properties, date-ranges and
728
-	 * iCalendar component types (VTODO, VEVENT).
729
-	 *
730
-	 * This method should just return a list of (relative) urls that match this
731
-	 * query.
732
-	 *
733
-	 * The list of filters are specified as an array. The exact array is
734
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
735
-	 *
736
-	 * Note that it is extremely likely that getCalendarObject for every path
737
-	 * returned from this method will be called almost immediately after. You
738
-	 * may want to anticipate this to speed up these requests.
739
-	 *
740
-	 * This method provides a default implementation, which parses *all* the
741
-	 * iCalendar objects in the specified calendar.
742
-	 *
743
-	 * This default may well be good enough for personal use, and calendars
744
-	 * that aren't very large. But if you anticipate high usage, big calendars
745
-	 * or high loads, you are strongly advised to optimize certain paths.
746
-	 *
747
-	 * The best way to do so is override this method and to optimize
748
-	 * specifically for 'common filters'.
749
-	 *
750
-	 * Requests that are extremely common are:
751
-	 *   * requests for just VEVENTS
752
-	 *   * requests for just VTODO
753
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
754
-	 *
755
-	 * ..and combinations of these requests. It may not be worth it to try to
756
-	 * handle every possible situation and just rely on the (relatively
757
-	 * easy to use) CalendarQueryValidator to handle the rest.
758
-	 *
759
-	 * Note that especially time-range-filters may be difficult to parse. A
760
-	 * time-range filter specified on a VEVENT must for instance also handle
761
-	 * recurrence rules correctly.
762
-	 * A good example of how to interprete all these filters can also simply
763
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
764
-	 * as possible, so it gives you a good idea on what type of stuff you need
765
-	 * to think of.
766
-	 *
767
-	 * @param mixed $calendarId
768
-	 * @param array $filters
769
-	 * @return array
770
-	 */
771
-	function calendarQuery($calendarId, array $filters) {
772
-		$componentType = null;
773
-		$requirePostFilter = true;
774
-		$timeRange = null;
775
-
776
-		// if no filters were specified, we don't need to filter after a query
777
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
778
-			$requirePostFilter = false;
779
-		}
780
-
781
-		// Figuring out if there's a component filter
782
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
783
-			$componentType = $filters['comp-filters'][0]['name'];
784
-
785
-			// Checking if we need post-filters
786
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
787
-				$requirePostFilter = false;
788
-			}
789
-			// There was a time-range filter
790
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
791
-				$timeRange = $filters['comp-filters'][0]['time-range'];
792
-
793
-				// If start time OR the end time is not specified, we can do a
794
-				// 100% accurate mysql query.
795
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
796
-					$requirePostFilter = false;
797
-				}
798
-			}
799
-
800
-		}
801
-		$columns = ['uri'];
802
-		if ($requirePostFilter) {
803
-			$columns = ['uri', 'calendardata'];
804
-		}
805
-		$query = $this->db->getQueryBuilder();
806
-		$query->select($columns)
807
-			->from('calendarobjects')
808
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
809
-
810
-		if ($componentType) {
811
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
812
-		}
813
-
814
-		if ($timeRange && $timeRange['start']) {
815
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
816
-		}
817
-		if ($timeRange && $timeRange['end']) {
818
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
819
-		}
820
-
821
-		$stmt = $query->execute();
822
-
823
-		$result = [];
824
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
825
-			if ($requirePostFilter) {
826
-				if (!$this->validateFilterForObject($row, $filters)) {
827
-					continue;
828
-				}
829
-			}
830
-			$result[] = $row['uri'];
831
-		}
832
-
833
-		return $result;
834
-	}
835
-
836
-	/**
837
-	 * Searches through all of a users calendars and calendar objects to find
838
-	 * an object with a specific UID.
839
-	 *
840
-	 * This method should return the path to this object, relative to the
841
-	 * calendar home, so this path usually only contains two parts:
842
-	 *
843
-	 * calendarpath/objectpath.ics
844
-	 *
845
-	 * If the uid is not found, return null.
846
-	 *
847
-	 * This method should only consider * objects that the principal owns, so
848
-	 * any calendars owned by other principals that also appear in this
849
-	 * collection should be ignored.
850
-	 *
851
-	 * @param string $principalUri
852
-	 * @param string $uid
853
-	 * @return string|null
854
-	 */
855
-	function getCalendarObjectByUID($principalUri, $uid) {
856
-
857
-		$query = $this->db->getQueryBuilder();
858
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
859
-			->from('calendarobjects', 'co')
860
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
861
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
862
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
863
-
864
-		$stmt = $query->execute();
865
-
866
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
867
-			return $row['calendaruri'] . '/' . $row['objecturi'];
868
-		}
869
-
870
-		return null;
871
-	}
872
-
873
-	/**
874
-	 * The getChanges method returns all the changes that have happened, since
875
-	 * the specified syncToken in the specified calendar.
876
-	 *
877
-	 * This function should return an array, such as the following:
878
-	 *
879
-	 * [
880
-	 *   'syncToken' => 'The current synctoken',
881
-	 *   'added'   => [
882
-	 *      'new.txt',
883
-	 *   ],
884
-	 *   'modified'   => [
885
-	 *      'modified.txt',
886
-	 *   ],
887
-	 *   'deleted' => [
888
-	 *      'foo.php.bak',
889
-	 *      'old.txt'
890
-	 *   ]
891
-	 * );
892
-	 *
893
-	 * The returned syncToken property should reflect the *current* syncToken
894
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
895
-	 * property This is * needed here too, to ensure the operation is atomic.
896
-	 *
897
-	 * If the $syncToken argument is specified as null, this is an initial
898
-	 * sync, and all members should be reported.
899
-	 *
900
-	 * The modified property is an array of nodenames that have changed since
901
-	 * the last token.
902
-	 *
903
-	 * The deleted property is an array with nodenames, that have been deleted
904
-	 * from collection.
905
-	 *
906
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
907
-	 * 1, you only have to report changes that happened only directly in
908
-	 * immediate descendants. If it's 2, it should also include changes from
909
-	 * the nodes below the child collections. (grandchildren)
910
-	 *
911
-	 * The $limit argument allows a client to specify how many results should
912
-	 * be returned at most. If the limit is not specified, it should be treated
913
-	 * as infinite.
914
-	 *
915
-	 * If the limit (infinite or not) is higher than you're willing to return,
916
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
917
-	 *
918
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
919
-	 * return null.
920
-	 *
921
-	 * The limit is 'suggestive'. You are free to ignore it.
922
-	 *
923
-	 * @param string $calendarId
924
-	 * @param string $syncToken
925
-	 * @param int $syncLevel
926
-	 * @param int $limit
927
-	 * @return array
928
-	 */
929
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
930
-		// Current synctoken
931
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
932
-		$stmt->execute([ $calendarId ]);
933
-		$currentToken = $stmt->fetchColumn(0);
934
-
935
-		if (is_null($currentToken)) {
936
-			return null;
937
-		}
938
-
939
-		$result = [
940
-			'syncToken' => $currentToken,
941
-			'added'     => [],
942
-			'modified'  => [],
943
-			'deleted'   => [],
944
-		];
945
-
946
-		if ($syncToken) {
947
-
948
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
949
-			if ($limit>0) {
950
-				$query.= " `LIMIT` " . (int)$limit;
951
-			}
952
-
953
-			// Fetching all changes
954
-			$stmt = $this->db->prepare($query);
955
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
956
-
957
-			$changes = [];
958
-
959
-			// This loop ensures that any duplicates are overwritten, only the
960
-			// last change on a node is relevant.
961
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
962
-
963
-				$changes[$row['uri']] = $row['operation'];
964
-
965
-			}
966
-
967
-			foreach($changes as $uri => $operation) {
968
-
969
-				switch($operation) {
970
-					case 1 :
971
-						$result['added'][] = $uri;
972
-						break;
973
-					case 2 :
974
-						$result['modified'][] = $uri;
975
-						break;
976
-					case 3 :
977
-						$result['deleted'][] = $uri;
978
-						break;
979
-				}
980
-
981
-			}
982
-		} else {
983
-			// No synctoken supplied, this is the initial sync.
984
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
985
-			$stmt = $this->db->prepare($query);
986
-			$stmt->execute([$calendarId]);
987
-
988
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
989
-		}
990
-		return $result;
991
-
992
-	}
993
-
994
-	/**
995
-	 * Returns a list of subscriptions for a principal.
996
-	 *
997
-	 * Every subscription is an array with the following keys:
998
-	 *  * id, a unique id that will be used by other functions to modify the
999
-	 *    subscription. This can be the same as the uri or a database key.
1000
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1001
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1002
-	 *    principalUri passed to this method.
1003
-	 *
1004
-	 * Furthermore, all the subscription info must be returned too:
1005
-	 *
1006
-	 * 1. {DAV:}displayname
1007
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1008
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1009
-	 *    should not be stripped).
1010
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1011
-	 *    should not be stripped).
1012
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1013
-	 *    attachments should not be stripped).
1014
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1015
-	 *     Sabre\DAV\Property\Href).
1016
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1017
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1018
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1019
-	 *    (should just be an instance of
1020
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1021
-	 *    default components).
1022
-	 *
1023
-	 * @param string $principalUri
1024
-	 * @return array
1025
-	 */
1026
-	function getSubscriptionsForUser($principalUri) {
1027
-		$fields = array_values($this->subscriptionPropertyMap);
1028
-		$fields[] = 'id';
1029
-		$fields[] = 'uri';
1030
-		$fields[] = 'source';
1031
-		$fields[] = 'principaluri';
1032
-		$fields[] = 'lastmodified';
1033
-
1034
-		$query = $this->db->getQueryBuilder();
1035
-		$query->select($fields)
1036
-			->from('calendarsubscriptions')
1037
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1038
-			->orderBy('calendarorder', 'asc');
1039
-		$stmt =$query->execute();
1040
-
1041
-		$subscriptions = [];
1042
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1043
-
1044
-			$subscription = [
1045
-				'id'           => $row['id'],
1046
-				'uri'          => $row['uri'],
1047
-				'principaluri' => $row['principaluri'],
1048
-				'source'       => $row['source'],
1049
-				'lastmodified' => $row['lastmodified'],
1050
-
1051
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1052
-			];
1053
-
1054
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1055
-				if (!is_null($row[$dbName])) {
1056
-					$subscription[$xmlName] = $row[$dbName];
1057
-				}
1058
-			}
1059
-
1060
-			$subscriptions[] = $subscription;
1061
-
1062
-		}
1063
-
1064
-		return $subscriptions;
1065
-	}
1066
-
1067
-	/**
1068
-	 * Creates a new subscription for a principal.
1069
-	 *
1070
-	 * If the creation was a success, an id must be returned that can be used to reference
1071
-	 * this subscription in other methods, such as updateSubscription.
1072
-	 *
1073
-	 * @param string $principalUri
1074
-	 * @param string $uri
1075
-	 * @param array $properties
1076
-	 * @return mixed
1077
-	 */
1078
-	function createSubscription($principalUri, $uri, array $properties) {
1079
-
1080
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1081
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1082
-		}
1083
-
1084
-		$values = [
1085
-			'principaluri' => $principalUri,
1086
-			'uri'          => $uri,
1087
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1088
-			'lastmodified' => time(),
1089
-		];
1090
-
1091
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1092
-
1093
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1094
-			if (array_key_exists($xmlName, $properties)) {
1095
-					$values[$dbName] = $properties[$xmlName];
1096
-					if (in_array($dbName, $propertiesBoolean)) {
1097
-						$values[$dbName] = true;
1098
-				}
1099
-			}
1100
-		}
1101
-
1102
-		$valuesToInsert = array();
1103
-
1104
-		$query = $this->db->getQueryBuilder();
1105
-
1106
-		foreach (array_keys($values) as $name) {
1107
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1108
-		}
1109
-
1110
-		$query->insert('calendarsubscriptions')
1111
-			->values($valuesToInsert)
1112
-			->execute();
1113
-
1114
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1115
-	}
1116
-
1117
-	/**
1118
-	 * Updates a subscription
1119
-	 *
1120
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1121
-	 * To do the actual updates, you must tell this object which properties
1122
-	 * you're going to process with the handle() method.
1123
-	 *
1124
-	 * Calling the handle method is like telling the PropPatch object "I
1125
-	 * promise I can handle updating this property".
1126
-	 *
1127
-	 * Read the PropPatch documentation for more info and examples.
1128
-	 *
1129
-	 * @param mixed $subscriptionId
1130
-	 * @param PropPatch $propPatch
1131
-	 * @return void
1132
-	 */
1133
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1134
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1135
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1136
-
1137
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1138
-
1139
-			$newValues = [];
1140
-
1141
-			foreach($mutations as $propertyName=>$propertyValue) {
1142
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1143
-					$newValues['source'] = $propertyValue->getHref();
1144
-				} else {
1145
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1146
-					$newValues[$fieldName] = $propertyValue;
1147
-				}
1148
-			}
1149
-
1150
-			$query = $this->db->getQueryBuilder();
1151
-			$query->update('calendarsubscriptions')
1152
-				->set('lastmodified', $query->createNamedParameter(time()));
1153
-			foreach($newValues as $fieldName=>$value) {
1154
-				$query->set($fieldName, $query->createNamedParameter($value));
1155
-			}
1156
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1157
-				->execute();
1158
-
1159
-			return true;
1160
-
1161
-		});
1162
-	}
1163
-
1164
-	/**
1165
-	 * Deletes a subscription.
1166
-	 *
1167
-	 * @param mixed $subscriptionId
1168
-	 * @return void
1169
-	 */
1170
-	function deleteSubscription($subscriptionId) {
1171
-		$query = $this->db->getQueryBuilder();
1172
-		$query->delete('calendarsubscriptions')
1173
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1174
-			->execute();
1175
-	}
1176
-
1177
-	/**
1178
-	 * Returns a single scheduling object for the inbox collection.
1179
-	 *
1180
-	 * The returned array should contain the following elements:
1181
-	 *   * uri - A unique basename for the object. This will be used to
1182
-	 *           construct a full uri.
1183
-	 *   * calendardata - The iCalendar object
1184
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1185
-	 *                    timestamp, or a PHP DateTime object.
1186
-	 *   * etag - A unique token that must change if the object changed.
1187
-	 *   * size - The size of the object, in bytes.
1188
-	 *
1189
-	 * @param string $principalUri
1190
-	 * @param string $objectUri
1191
-	 * @return array
1192
-	 */
1193
-	function getSchedulingObject($principalUri, $objectUri) {
1194
-		$query = $this->db->getQueryBuilder();
1195
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1196
-			->from('schedulingobjects')
1197
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1198
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1199
-			->execute();
1200
-
1201
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1202
-
1203
-		if(!$row) {
1204
-			return null;
1205
-		}
1206
-
1207
-		return [
1208
-				'uri'          => $row['uri'],
1209
-				'calendardata' => $row['calendardata'],
1210
-				'lastmodified' => $row['lastmodified'],
1211
-				'etag'         => '"' . $row['etag'] . '"',
1212
-				'size'         => (int)$row['size'],
1213
-		];
1214
-	}
1215
-
1216
-	/**
1217
-	 * Returns all scheduling objects for the inbox collection.
1218
-	 *
1219
-	 * These objects should be returned as an array. Every item in the array
1220
-	 * should follow the same structure as returned from getSchedulingObject.
1221
-	 *
1222
-	 * The main difference is that 'calendardata' is optional.
1223
-	 *
1224
-	 * @param string $principalUri
1225
-	 * @return array
1226
-	 */
1227
-	function getSchedulingObjects($principalUri) {
1228
-		$query = $this->db->getQueryBuilder();
1229
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1230
-				->from('schedulingobjects')
1231
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1232
-				->execute();
1233
-
1234
-		$result = [];
1235
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1236
-			$result[] = [
1237
-					'calendardata' => $row['calendardata'],
1238
-					'uri'          => $row['uri'],
1239
-					'lastmodified' => $row['lastmodified'],
1240
-					'etag'         => '"' . $row['etag'] . '"',
1241
-					'size'         => (int)$row['size'],
1242
-			];
1243
-		}
1244
-
1245
-		return $result;
1246
-	}
1247
-
1248
-	/**
1249
-	 * Deletes a scheduling object from the inbox collection.
1250
-	 *
1251
-	 * @param string $principalUri
1252
-	 * @param string $objectUri
1253
-	 * @return void
1254
-	 */
1255
-	function deleteSchedulingObject($principalUri, $objectUri) {
1256
-		$query = $this->db->getQueryBuilder();
1257
-		$query->delete('schedulingobjects')
1258
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1259
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1260
-				->execute();
1261
-	}
1262
-
1263
-	/**
1264
-	 * Creates a new scheduling object. This should land in a users' inbox.
1265
-	 *
1266
-	 * @param string $principalUri
1267
-	 * @param string $objectUri
1268
-	 * @param string $objectData
1269
-	 * @return void
1270
-	 */
1271
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1272
-		$query = $this->db->getQueryBuilder();
1273
-		$query->insert('schedulingobjects')
1274
-			->values([
1275
-				'principaluri' => $query->createNamedParameter($principalUri),
1276
-				'calendardata' => $query->createNamedParameter($objectData),
1277
-				'uri' => $query->createNamedParameter($objectUri),
1278
-				'lastmodified' => $query->createNamedParameter(time()),
1279
-				'etag' => $query->createNamedParameter(md5($objectData)),
1280
-				'size' => $query->createNamedParameter(strlen($objectData))
1281
-			])
1282
-			->execute();
1283
-	}
1284
-
1285
-	/**
1286
-	 * Adds a change record to the calendarchanges table.
1287
-	 *
1288
-	 * @param mixed $calendarId
1289
-	 * @param string $objectUri
1290
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1291
-	 * @return void
1292
-	 */
1293
-	protected function addChange($calendarId, $objectUri, $operation) {
1294
-
1295
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1296
-		$stmt->execute([
1297
-			$objectUri,
1298
-			$calendarId,
1299
-			$operation,
1300
-			$calendarId
1301
-		]);
1302
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1303
-		$stmt->execute([
1304
-			$calendarId
1305
-		]);
1306
-
1307
-	}
1308
-
1309
-	/**
1310
-	 * Parses some information from calendar objects, used for optimized
1311
-	 * calendar-queries.
1312
-	 *
1313
-	 * Returns an array with the following keys:
1314
-	 *   * etag - An md5 checksum of the object without the quotes.
1315
-	 *   * size - Size of the object in bytes
1316
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1317
-	 *   * firstOccurence
1318
-	 *   * lastOccurence
1319
-	 *   * uid - value of the UID property
1320
-	 *
1321
-	 * @param string $calendarData
1322
-	 * @return array
1323
-	 */
1324
-	public function getDenormalizedData($calendarData) {
1325
-
1326
-		$vObject = Reader::read($calendarData);
1327
-		$componentType = null;
1328
-		$component = null;
1329
-		$firstOccurrence = null;
1330
-		$lastOccurrence = null;
1331
-		$uid = null;
1332
-		$classification = self::CLASSIFICATION_PUBLIC;
1333
-		foreach($vObject->getComponents() as $component) {
1334
-			if ($component->name!=='VTIMEZONE') {
1335
-				$componentType = $component->name;
1336
-				$uid = (string)$component->UID;
1337
-				break;
1338
-			}
1339
-		}
1340
-		if (!$componentType) {
1341
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1342
-		}
1343
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1344
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1345
-			// Finding the last occurrence is a bit harder
1346
-			if (!isset($component->RRULE)) {
1347
-				if (isset($component->DTEND)) {
1348
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1349
-				} elseif (isset($component->DURATION)) {
1350
-					$endDate = clone $component->DTSTART->getDateTime();
1351
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1352
-					$lastOccurrence = $endDate->getTimeStamp();
1353
-				} elseif (!$component->DTSTART->hasTime()) {
1354
-					$endDate = clone $component->DTSTART->getDateTime();
1355
-					$endDate->modify('+1 day');
1356
-					$lastOccurrence = $endDate->getTimeStamp();
1357
-				} else {
1358
-					$lastOccurrence = $firstOccurrence;
1359
-				}
1360
-			} else {
1361
-				$it = new EventIterator($vObject, (string)$component->UID);
1362
-				$maxDate = new \DateTime(self::MAX_DATE);
1363
-				if ($it->isInfinite()) {
1364
-					$lastOccurrence = $maxDate->getTimeStamp();
1365
-				} else {
1366
-					$end = $it->getDtEnd();
1367
-					while($it->valid() && $end < $maxDate) {
1368
-						$end = $it->getDtEnd();
1369
-						$it->next();
1370
-
1371
-					}
1372
-					$lastOccurrence = $end->getTimeStamp();
1373
-				}
1374
-
1375
-			}
1376
-		}
1377
-
1378
-		if ($component->CLASS) {
1379
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1380
-			switch ($component->CLASS->getValue()) {
1381
-				case 'PUBLIC':
1382
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1383
-					break;
1384
-				case 'CONFIDENTIAL':
1385
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1386
-					break;
1387
-			}
1388
-		}
1389
-		return [
1390
-			'etag' => md5($calendarData),
1391
-			'size' => strlen($calendarData),
1392
-			'componentType' => $componentType,
1393
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1394
-			'lastOccurence'  => $lastOccurrence,
1395
-			'uid' => $uid,
1396
-			'classification' => $classification
1397
-		];
1398
-
1399
-	}
1400
-
1401
-	private function readBlob($cardData) {
1402
-		if (is_resource($cardData)) {
1403
-			return stream_get_contents($cardData);
1404
-		}
1405
-
1406
-		return $cardData;
1407
-	}
1408
-
1409
-	/**
1410
-	 * @param IShareable $shareable
1411
-	 * @param array $add
1412
-	 * @param array $remove
1413
-	 */
1414
-	public function updateShares($shareable, $add, $remove) {
1415
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1416
-	}
1417
-
1418
-	/**
1419
-	 * @param int $resourceId
1420
-	 * @return array
1421
-	 */
1422
-	public function getShares($resourceId) {
1423
-		return $this->sharingBackend->getShares($resourceId);
1424
-	}
1425
-
1426
-	/**
1427
-	 * @param int $resourceId
1428
-	 * @param array $acl
1429
-	 * @return array
1430
-	 */
1431
-	public function applyShareAcl($resourceId, $acl) {
1432
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1433
-	}
1434
-
1435
-	private function convertPrincipal($principalUri, $toV2) {
1436
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1437
-			list(, $name) = URLUtil::splitPath($principalUri);
1438
-			if ($toV2 === true) {
1439
-				return "principals/users/$name";
1440
-			}
1441
-			return "principals/$name";
1442
-		}
1443
-		return $principalUri;
1444
-	}
57
+    /**
58
+     * We need to specify a max date, because we need to stop *somewhere*
59
+     *
60
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
61
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
62
+     * in 2038-01-19 to avoid problems when the date is converted
63
+     * to a unix timestamp.
64
+     */
65
+    const MAX_DATE = '2038-01-01';
66
+
67
+    const CLASSIFICATION_PUBLIC = 0;
68
+    const CLASSIFICATION_PRIVATE = 1;
69
+    const CLASSIFICATION_CONFIDENTIAL = 2;
70
+
71
+    /**
72
+     * List of CalDAV properties, and how they map to database field names
73
+     * Add your own properties by simply adding on to this array.
74
+     *
75
+     * Note that only string-based properties are supported here.
76
+     *
77
+     * @var array
78
+     */
79
+    public $propertyMap = [
80
+        '{DAV:}displayname'                          => 'displayname',
81
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
82
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
83
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
84
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
85
+    ];
86
+
87
+    /**
88
+     * List of subscription properties, and how they map to database field names.
89
+     *
90
+     * @var array
91
+     */
92
+    public $subscriptionPropertyMap = [
93
+        '{DAV:}displayname'                                           => 'displayname',
94
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
95
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
96
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
97
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
98
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
99
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
100
+    ];
101
+
102
+    /** @var IDBConnection */
103
+    private $db;
104
+
105
+    /** @var Backend */
106
+    private $sharingBackend;
107
+
108
+    /** @var Principal */
109
+    private $principalBackend;
110
+
111
+    /**
112
+     * CalDavBackend constructor.
113
+     *
114
+     * @param IDBConnection $db
115
+     * @param Principal $principalBackend
116
+     */
117
+    public function __construct(IDBConnection $db, Principal $principalBackend) {
118
+        $this->db = $db;
119
+        $this->principalBackend = $principalBackend;
120
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
121
+    }
122
+
123
+    /**
124
+     * Returns a list of calendars for a principal.
125
+     *
126
+     * Every project is an array with the following keys:
127
+     *  * id, a unique id that will be used by other functions to modify the
128
+     *    calendar. This can be the same as the uri or a database key.
129
+     *  * uri, which the basename of the uri with which the calendar is
130
+     *    accessed.
131
+     *  * principaluri. The owner of the calendar. Almost always the same as
132
+     *    principalUri passed to this method.
133
+     *
134
+     * Furthermore it can contain webdav properties in clark notation. A very
135
+     * common one is '{DAV:}displayname'.
136
+     *
137
+     * Many clients also require:
138
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
139
+     * For this property, you can just return an instance of
140
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
141
+     *
142
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
143
+     * ACL will automatically be put in read-only mode.
144
+     *
145
+     * @param string $principalUri
146
+     * @return array
147
+     */
148
+    function getCalendarsForUser($principalUri) {
149
+        $principalUriOriginal = $principalUri;
150
+        $principalUri = $this->convertPrincipal($principalUri, true);
151
+        $fields = array_values($this->propertyMap);
152
+        $fields[] = 'id';
153
+        $fields[] = 'uri';
154
+        $fields[] = 'synctoken';
155
+        $fields[] = 'components';
156
+        $fields[] = 'principaluri';
157
+        $fields[] = 'transparent';
158
+
159
+        // Making fields a comma-delimited list
160
+        $query = $this->db->getQueryBuilder();
161
+        $query->select($fields)->from('calendars')
162
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
163
+                ->orderBy('calendarorder', 'ASC');
164
+        $stmt = $query->execute();
165
+
166
+        $calendars = [];
167
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
168
+
169
+            $components = [];
170
+            if ($row['components']) {
171
+                $components = explode(',',$row['components']);
172
+            }
173
+
174
+            $calendar = [
175
+                'id' => $row['id'],
176
+                'uri' => $row['uri'],
177
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
178
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
179
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
180
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
181
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
182
+            ];
183
+
184
+            foreach($this->propertyMap as $xmlName=>$dbName) {
185
+                $calendar[$xmlName] = $row[$dbName];
186
+            }
187
+
188
+            if (!isset($calendars[$calendar['id']])) {
189
+                $calendars[$calendar['id']] = $calendar;
190
+            }
191
+        }
192
+
193
+        $stmt->closeCursor();
194
+
195
+        // query for shared calendars
196
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
197
+        $principals[]= $principalUri;
198
+
199
+        $fields = array_values($this->propertyMap);
200
+        $fields[] = 'a.id';
201
+        $fields[] = 'a.uri';
202
+        $fields[] = 'a.synctoken';
203
+        $fields[] = 'a.components';
204
+        $fields[] = 'a.principaluri';
205
+        $fields[] = 'a.transparent';
206
+        $fields[] = 's.access';
207
+        $query = $this->db->getQueryBuilder();
208
+        $result = $query->select($fields)
209
+            ->from('dav_shares', 's')
210
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
211
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
212
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
213
+            ->setParameter('type', 'calendar')
214
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
215
+            ->execute();
216
+
217
+        while($row = $result->fetch()) {
218
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
219
+            $uri = $row['uri'] . '_shared_by_' . $name;
220
+            $row['displayname'] = $row['displayname'] . "($name)";
221
+            $components = [];
222
+            if ($row['components']) {
223
+                $components = explode(',',$row['components']);
224
+            }
225
+            $calendar = [
226
+                'id' => $row['id'],
227
+                'uri' => $uri,
228
+                'principaluri' => $principalUri,
229
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
230
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
232
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
233
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
234
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
235
+            ];
236
+
237
+            foreach($this->propertyMap as $xmlName=>$dbName) {
238
+                $calendar[$xmlName] = $row[$dbName];
239
+            }
240
+
241
+            if (!isset($calendars[$calendar['id']])) {
242
+                $calendars[$calendar['id']] = $calendar;
243
+            }
244
+        }
245
+        $result->closeCursor();
246
+
247
+        return array_values($calendars);
248
+    }
249
+
250
+    /**
251
+     * @param string $principal
252
+     * @param string $uri
253
+     * @return array|null
254
+     */
255
+    public function getCalendarByUri($principal, $uri) {
256
+        $fields = array_values($this->propertyMap);
257
+        $fields[] = 'id';
258
+        $fields[] = 'uri';
259
+        $fields[] = 'synctoken';
260
+        $fields[] = 'components';
261
+        $fields[] = 'principaluri';
262
+        $fields[] = 'transparent';
263
+
264
+        // Making fields a comma-delimited list
265
+        $query = $this->db->getQueryBuilder();
266
+        $query->select($fields)->from('calendars')
267
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
268
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
269
+            ->setMaxResults(1);
270
+        $stmt = $query->execute();
271
+
272
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
273
+        $stmt->closeCursor();
274
+        if ($row === false) {
275
+            return null;
276
+        }
277
+
278
+        $components = [];
279
+        if ($row['components']) {
280
+            $components = explode(',',$row['components']);
281
+        }
282
+
283
+        $calendar = [
284
+            'id' => $row['id'],
285
+            'uri' => $row['uri'],
286
+            'principaluri' => $row['principaluri'],
287
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
291
+        ];
292
+
293
+        foreach($this->propertyMap as $xmlName=>$dbName) {
294
+            $calendar[$xmlName] = $row[$dbName];
295
+        }
296
+
297
+        return $calendar;
298
+    }
299
+
300
+    public function getCalendarById($calendarId) {
301
+        $fields = array_values($this->propertyMap);
302
+        $fields[] = 'id';
303
+        $fields[] = 'uri';
304
+        $fields[] = 'synctoken';
305
+        $fields[] = 'components';
306
+        $fields[] = 'principaluri';
307
+        $fields[] = 'transparent';
308
+
309
+        // Making fields a comma-delimited list
310
+        $query = $this->db->getQueryBuilder();
311
+        $query->select($fields)->from('calendars')
312
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
313
+            ->setMaxResults(1);
314
+        $stmt = $query->execute();
315
+
316
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
317
+        $stmt->closeCursor();
318
+        if ($row === false) {
319
+            return null;
320
+        }
321
+
322
+        $components = [];
323
+        if ($row['components']) {
324
+            $components = explode(',',$row['components']);
325
+        }
326
+
327
+        $calendar = [
328
+            'id' => $row['id'],
329
+            'uri' => $row['uri'],
330
+            'principaluri' => $row['principaluri'],
331
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
332
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
334
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
335
+        ];
336
+
337
+        foreach($this->propertyMap as $xmlName=>$dbName) {
338
+            $calendar[$xmlName] = $row[$dbName];
339
+        }
340
+
341
+        return $calendar;
342
+    }
343
+
344
+    /**
345
+     * Creates a new calendar for a principal.
346
+     *
347
+     * If the creation was a success, an id must be returned that can be used to reference
348
+     * this calendar in other methods, such as updateCalendar.
349
+     *
350
+     * @param string $principalUri
351
+     * @param string $calendarUri
352
+     * @param array $properties
353
+     * @return int
354
+     */
355
+    function createCalendar($principalUri, $calendarUri, array $properties) {
356
+        $values = [
357
+            'principaluri' => $this->convertPrincipal($principalUri, true),
358
+            'uri'          => $calendarUri,
359
+            'synctoken'    => 1,
360
+            'transparent'  => 0,
361
+            'components'   => 'VEVENT,VTODO',
362
+            'displayname'  => $calendarUri
363
+        ];
364
+
365
+        // Default value
366
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
367
+        if (isset($properties[$sccs])) {
368
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
369
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
370
+            }
371
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
372
+        }
373
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
374
+        if (isset($properties[$transp])) {
375
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
376
+        }
377
+
378
+        foreach($this->propertyMap as $xmlName=>$dbName) {
379
+            if (isset($properties[$xmlName])) {
380
+                $values[$dbName] = $properties[$xmlName];
381
+            }
382
+        }
383
+
384
+        $query = $this->db->getQueryBuilder();
385
+        $query->insert('calendars');
386
+        foreach($values as $column => $value) {
387
+            $query->setValue($column, $query->createNamedParameter($value));
388
+        }
389
+        $query->execute();
390
+        return $query->getLastInsertId();
391
+    }
392
+
393
+    /**
394
+     * Updates properties for a calendar.
395
+     *
396
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
397
+     * To do the actual updates, you must tell this object which properties
398
+     * you're going to process with the handle() method.
399
+     *
400
+     * Calling the handle method is like telling the PropPatch object "I
401
+     * promise I can handle updating this property".
402
+     *
403
+     * Read the PropPatch documentation for more info and examples.
404
+     *
405
+     * @param PropPatch $propPatch
406
+     * @return void
407
+     */
408
+    function updateCalendar($calendarId, PropPatch $propPatch) {
409
+        $supportedProperties = array_keys($this->propertyMap);
410
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
411
+
412
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
413
+            $newValues = [];
414
+            foreach ($mutations as $propertyName => $propertyValue) {
415
+
416
+                switch ($propertyName) {
417
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
418
+                        $fieldName = 'transparent';
419
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
420
+                        break;
421
+                    default :
422
+                        $fieldName = $this->propertyMap[$propertyName];
423
+                        $newValues[$fieldName] = $propertyValue;
424
+                        break;
425
+                }
426
+
427
+            }
428
+            $query = $this->db->getQueryBuilder();
429
+            $query->update('calendars');
430
+            foreach ($newValues as $fieldName => $value) {
431
+                $query->set($fieldName, $query->createNamedParameter($value));
432
+            }
433
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
434
+            $query->execute();
435
+
436
+            $this->addChange($calendarId, "", 2);
437
+
438
+            return true;
439
+        });
440
+    }
441
+
442
+    /**
443
+     * Delete a calendar and all it's objects
444
+     *
445
+     * @param mixed $calendarId
446
+     * @return void
447
+     */
448
+    function deleteCalendar($calendarId) {
449
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
450
+        $stmt->execute([$calendarId]);
451
+
452
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
453
+        $stmt->execute([$calendarId]);
454
+
455
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
456
+        $stmt->execute([$calendarId]);
457
+
458
+        $this->sharingBackend->deleteAllShares($calendarId);
459
+    }
460
+
461
+    /**
462
+     * Returns all calendar objects within a calendar.
463
+     *
464
+     * Every item contains an array with the following keys:
465
+     *   * calendardata - The iCalendar-compatible calendar data
466
+     *   * uri - a unique key which will be used to construct the uri. This can
467
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
468
+     *     good idea. This is only the basename, or filename, not the full
469
+     *     path.
470
+     *   * lastmodified - a timestamp of the last modification time
471
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
472
+     *   '"abcdef"')
473
+     *   * size - The size of the calendar objects, in bytes.
474
+     *   * component - optional, a string containing the type of object, such
475
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
476
+     *     the Content-Type header.
477
+     *
478
+     * Note that the etag is optional, but it's highly encouraged to return for
479
+     * speed reasons.
480
+     *
481
+     * The calendardata is also optional. If it's not returned
482
+     * 'getCalendarObject' will be called later, which *is* expected to return
483
+     * calendardata.
484
+     *
485
+     * If neither etag or size are specified, the calendardata will be
486
+     * used/fetched to determine these numbers. If both are specified the
487
+     * amount of times this is needed is reduced by a great degree.
488
+     *
489
+     * @param mixed $calendarId
490
+     * @return array
491
+     */
492
+    function getCalendarObjects($calendarId) {
493
+        $query = $this->db->getQueryBuilder();
494
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
495
+            ->from('calendarobjects')
496
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
497
+        $stmt = $query->execute();
498
+
499
+        $result = [];
500
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
501
+            $result[] = [
502
+                    'id'           => $row['id'],
503
+                    'uri'          => $row['uri'],
504
+                    'lastmodified' => $row['lastmodified'],
505
+                    'etag'         => '"' . $row['etag'] . '"',
506
+                    'calendarid'   => $row['calendarid'],
507
+                    'size'         => (int)$row['size'],
508
+                    'component'    => strtolower($row['componenttype']),
509
+                    'classification'=> (int)$row['classification']
510
+            ];
511
+        }
512
+
513
+        return $result;
514
+    }
515
+
516
+    /**
517
+     * Returns information from a single calendar object, based on it's object
518
+     * uri.
519
+     *
520
+     * The object uri is only the basename, or filename and not a full path.
521
+     *
522
+     * The returned array must have the same keys as getCalendarObjects. The
523
+     * 'calendardata' object is required here though, while it's not required
524
+     * for getCalendarObjects.
525
+     *
526
+     * This method must return null if the object did not exist.
527
+     *
528
+     * @param mixed $calendarId
529
+     * @param string $objectUri
530
+     * @return array|null
531
+     */
532
+    function getCalendarObject($calendarId, $objectUri) {
533
+
534
+        $query = $this->db->getQueryBuilder();
535
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
536
+                ->from('calendarobjects')
537
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
538
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
539
+        $stmt = $query->execute();
540
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
541
+
542
+        if(!$row) return null;
543
+
544
+        return [
545
+                'id'            => $row['id'],
546
+                'uri'           => $row['uri'],
547
+                'lastmodified'  => $row['lastmodified'],
548
+                'etag'          => '"' . $row['etag'] . '"',
549
+                'calendarid'    => $row['calendarid'],
550
+                'size'          => (int)$row['size'],
551
+                'calendardata'  => $this->readBlob($row['calendardata']),
552
+                'component'     => strtolower($row['componenttype']),
553
+                'classification'=> (int)$row['classification']
554
+        ];
555
+    }
556
+
557
+    /**
558
+     * Returns a list of calendar objects.
559
+     *
560
+     * This method should work identical to getCalendarObject, but instead
561
+     * return all the calendar objects in the list as an array.
562
+     *
563
+     * If the backend supports this, it may allow for some speed-ups.
564
+     *
565
+     * @param mixed $calendarId
566
+     * @param string[] $uris
567
+     * @return array
568
+     */
569
+    function getMultipleCalendarObjects($calendarId, array $uris) {
570
+        if (empty($uris)) {
571
+            return [];
572
+        }
573
+
574
+        $chunks = array_chunk($uris, 100);
575
+        $objects = [];
576
+
577
+        $query = $this->db->getQueryBuilder();
578
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
579
+            ->from('calendarobjects')
580
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
581
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
582
+
583
+        foreach ($chunks as $uris) {
584
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
585
+            $result = $query->execute();
586
+
587
+            while ($row = $result->fetch()) {
588
+                $objects[] = [
589
+                    'id'           => $row['id'],
590
+                    'uri'          => $row['uri'],
591
+                    'lastmodified' => $row['lastmodified'],
592
+                    'etag'         => '"' . $row['etag'] . '"',
593
+                    'calendarid'   => $row['calendarid'],
594
+                    'size'         => (int)$row['size'],
595
+                    'calendardata' => $this->readBlob($row['calendardata']),
596
+                    'component'    => strtolower($row['componenttype']),
597
+                    'classification' => (int)$row['classification']
598
+                ];
599
+            }
600
+            $result->closeCursor();
601
+        }
602
+        return $objects;
603
+    }
604
+
605
+    /**
606
+     * Creates a new calendar object.
607
+     *
608
+     * The object uri is only the basename, or filename and not a full path.
609
+     *
610
+     * It is possible return an etag from this function, which will be used in
611
+     * the response to this PUT request. Note that the ETag must be surrounded
612
+     * by double-quotes.
613
+     *
614
+     * However, you should only really return this ETag if you don't mangle the
615
+     * calendar-data. If the result of a subsequent GET to this object is not
616
+     * the exact same as this request body, you should omit the ETag.
617
+     *
618
+     * @param mixed $calendarId
619
+     * @param string $objectUri
620
+     * @param string $calendarData
621
+     * @return string
622
+     */
623
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
624
+        $extraData = $this->getDenormalizedData($calendarData);
625
+
626
+        $query = $this->db->getQueryBuilder();
627
+        $query->insert('calendarobjects')
628
+            ->values([
629
+                'calendarid' => $query->createNamedParameter($calendarId),
630
+                'uri' => $query->createNamedParameter($objectUri),
631
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
632
+                'lastmodified' => $query->createNamedParameter(time()),
633
+                'etag' => $query->createNamedParameter($extraData['etag']),
634
+                'size' => $query->createNamedParameter($extraData['size']),
635
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
636
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
637
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
638
+                'classification' => $query->createNamedParameter($extraData['classification']),
639
+                'uid' => $query->createNamedParameter($extraData['uid']),
640
+            ])
641
+            ->execute();
642
+
643
+        $this->addChange($calendarId, $objectUri, 1);
644
+
645
+        return '"' . $extraData['etag'] . '"';
646
+    }
647
+
648
+    /**
649
+     * Updates an existing calendarobject, based on it's uri.
650
+     *
651
+     * The object uri is only the basename, or filename and not a full path.
652
+     *
653
+     * It is possible return an etag from this function, which will be used in
654
+     * the response to this PUT request. Note that the ETag must be surrounded
655
+     * by double-quotes.
656
+     *
657
+     * However, you should only really return this ETag if you don't mangle the
658
+     * calendar-data. If the result of a subsequent GET to this object is not
659
+     * the exact same as this request body, you should omit the ETag.
660
+     *
661
+     * @param mixed $calendarId
662
+     * @param string $objectUri
663
+     * @param string $calendarData
664
+     * @return string
665
+     */
666
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
667
+        $extraData = $this->getDenormalizedData($calendarData);
668
+
669
+        $query = $this->db->getQueryBuilder();
670
+        $query->update('calendarobjects')
671
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
672
+                ->set('lastmodified', $query->createNamedParameter(time()))
673
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
674
+                ->set('size', $query->createNamedParameter($extraData['size']))
675
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
676
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
677
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
678
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
679
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
680
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
681
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
682
+            ->execute();
683
+
684
+        $this->addChange($calendarId, $objectUri, 2);
685
+
686
+        return '"' . $extraData['etag'] . '"';
687
+    }
688
+
689
+    /**
690
+     * @param int $calendarObjectId
691
+     * @param int $classification
692
+     */
693
+    public function setClassification($calendarObjectId, $classification) {
694
+        if (!in_array($classification, [
695
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
696
+        ])) {
697
+            throw new \InvalidArgumentException();
698
+        }
699
+        $query = $this->db->getQueryBuilder();
700
+        $query->update('calendarobjects')
701
+            ->set('classification', $query->createNamedParameter($classification))
702
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
703
+            ->execute();
704
+    }
705
+
706
+    /**
707
+     * Deletes an existing calendar object.
708
+     *
709
+     * The object uri is only the basename, or filename and not a full path.
710
+     *
711
+     * @param mixed $calendarId
712
+     * @param string $objectUri
713
+     * @return void
714
+     */
715
+    function deleteCalendarObject($calendarId, $objectUri) {
716
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
717
+        $stmt->execute([$calendarId, $objectUri]);
718
+
719
+        $this->addChange($calendarId, $objectUri, 3);
720
+    }
721
+
722
+    /**
723
+     * Performs a calendar-query on the contents of this calendar.
724
+     *
725
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
726
+     * calendar-query it is possible for a client to request a specific set of
727
+     * object, based on contents of iCalendar properties, date-ranges and
728
+     * iCalendar component types (VTODO, VEVENT).
729
+     *
730
+     * This method should just return a list of (relative) urls that match this
731
+     * query.
732
+     *
733
+     * The list of filters are specified as an array. The exact array is
734
+     * documented by Sabre\CalDAV\CalendarQueryParser.
735
+     *
736
+     * Note that it is extremely likely that getCalendarObject for every path
737
+     * returned from this method will be called almost immediately after. You
738
+     * may want to anticipate this to speed up these requests.
739
+     *
740
+     * This method provides a default implementation, which parses *all* the
741
+     * iCalendar objects in the specified calendar.
742
+     *
743
+     * This default may well be good enough for personal use, and calendars
744
+     * that aren't very large. But if you anticipate high usage, big calendars
745
+     * or high loads, you are strongly advised to optimize certain paths.
746
+     *
747
+     * The best way to do so is override this method and to optimize
748
+     * specifically for 'common filters'.
749
+     *
750
+     * Requests that are extremely common are:
751
+     *   * requests for just VEVENTS
752
+     *   * requests for just VTODO
753
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
754
+     *
755
+     * ..and combinations of these requests. It may not be worth it to try to
756
+     * handle every possible situation and just rely on the (relatively
757
+     * easy to use) CalendarQueryValidator to handle the rest.
758
+     *
759
+     * Note that especially time-range-filters may be difficult to parse. A
760
+     * time-range filter specified on a VEVENT must for instance also handle
761
+     * recurrence rules correctly.
762
+     * A good example of how to interprete all these filters can also simply
763
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
764
+     * as possible, so it gives you a good idea on what type of stuff you need
765
+     * to think of.
766
+     *
767
+     * @param mixed $calendarId
768
+     * @param array $filters
769
+     * @return array
770
+     */
771
+    function calendarQuery($calendarId, array $filters) {
772
+        $componentType = null;
773
+        $requirePostFilter = true;
774
+        $timeRange = null;
775
+
776
+        // if no filters were specified, we don't need to filter after a query
777
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
778
+            $requirePostFilter = false;
779
+        }
780
+
781
+        // Figuring out if there's a component filter
782
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
783
+            $componentType = $filters['comp-filters'][0]['name'];
784
+
785
+            // Checking if we need post-filters
786
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
787
+                $requirePostFilter = false;
788
+            }
789
+            // There was a time-range filter
790
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
791
+                $timeRange = $filters['comp-filters'][0]['time-range'];
792
+
793
+                // If start time OR the end time is not specified, we can do a
794
+                // 100% accurate mysql query.
795
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
796
+                    $requirePostFilter = false;
797
+                }
798
+            }
799
+
800
+        }
801
+        $columns = ['uri'];
802
+        if ($requirePostFilter) {
803
+            $columns = ['uri', 'calendardata'];
804
+        }
805
+        $query = $this->db->getQueryBuilder();
806
+        $query->select($columns)
807
+            ->from('calendarobjects')
808
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
809
+
810
+        if ($componentType) {
811
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
812
+        }
813
+
814
+        if ($timeRange && $timeRange['start']) {
815
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
816
+        }
817
+        if ($timeRange && $timeRange['end']) {
818
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
819
+        }
820
+
821
+        $stmt = $query->execute();
822
+
823
+        $result = [];
824
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
825
+            if ($requirePostFilter) {
826
+                if (!$this->validateFilterForObject($row, $filters)) {
827
+                    continue;
828
+                }
829
+            }
830
+            $result[] = $row['uri'];
831
+        }
832
+
833
+        return $result;
834
+    }
835
+
836
+    /**
837
+     * Searches through all of a users calendars and calendar objects to find
838
+     * an object with a specific UID.
839
+     *
840
+     * This method should return the path to this object, relative to the
841
+     * calendar home, so this path usually only contains two parts:
842
+     *
843
+     * calendarpath/objectpath.ics
844
+     *
845
+     * If the uid is not found, return null.
846
+     *
847
+     * This method should only consider * objects that the principal owns, so
848
+     * any calendars owned by other principals that also appear in this
849
+     * collection should be ignored.
850
+     *
851
+     * @param string $principalUri
852
+     * @param string $uid
853
+     * @return string|null
854
+     */
855
+    function getCalendarObjectByUID($principalUri, $uid) {
856
+
857
+        $query = $this->db->getQueryBuilder();
858
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
859
+            ->from('calendarobjects', 'co')
860
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
861
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
862
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
863
+
864
+        $stmt = $query->execute();
865
+
866
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
867
+            return $row['calendaruri'] . '/' . $row['objecturi'];
868
+        }
869
+
870
+        return null;
871
+    }
872
+
873
+    /**
874
+     * The getChanges method returns all the changes that have happened, since
875
+     * the specified syncToken in the specified calendar.
876
+     *
877
+     * This function should return an array, such as the following:
878
+     *
879
+     * [
880
+     *   'syncToken' => 'The current synctoken',
881
+     *   'added'   => [
882
+     *      'new.txt',
883
+     *   ],
884
+     *   'modified'   => [
885
+     *      'modified.txt',
886
+     *   ],
887
+     *   'deleted' => [
888
+     *      'foo.php.bak',
889
+     *      'old.txt'
890
+     *   ]
891
+     * );
892
+     *
893
+     * The returned syncToken property should reflect the *current* syncToken
894
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
895
+     * property This is * needed here too, to ensure the operation is atomic.
896
+     *
897
+     * If the $syncToken argument is specified as null, this is an initial
898
+     * sync, and all members should be reported.
899
+     *
900
+     * The modified property is an array of nodenames that have changed since
901
+     * the last token.
902
+     *
903
+     * The deleted property is an array with nodenames, that have been deleted
904
+     * from collection.
905
+     *
906
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
907
+     * 1, you only have to report changes that happened only directly in
908
+     * immediate descendants. If it's 2, it should also include changes from
909
+     * the nodes below the child collections. (grandchildren)
910
+     *
911
+     * The $limit argument allows a client to specify how many results should
912
+     * be returned at most. If the limit is not specified, it should be treated
913
+     * as infinite.
914
+     *
915
+     * If the limit (infinite or not) is higher than you're willing to return,
916
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
917
+     *
918
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
919
+     * return null.
920
+     *
921
+     * The limit is 'suggestive'. You are free to ignore it.
922
+     *
923
+     * @param string $calendarId
924
+     * @param string $syncToken
925
+     * @param int $syncLevel
926
+     * @param int $limit
927
+     * @return array
928
+     */
929
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
930
+        // Current synctoken
931
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
932
+        $stmt->execute([ $calendarId ]);
933
+        $currentToken = $stmt->fetchColumn(0);
934
+
935
+        if (is_null($currentToken)) {
936
+            return null;
937
+        }
938
+
939
+        $result = [
940
+            'syncToken' => $currentToken,
941
+            'added'     => [],
942
+            'modified'  => [],
943
+            'deleted'   => [],
944
+        ];
945
+
946
+        if ($syncToken) {
947
+
948
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
949
+            if ($limit>0) {
950
+                $query.= " `LIMIT` " . (int)$limit;
951
+            }
952
+
953
+            // Fetching all changes
954
+            $stmt = $this->db->prepare($query);
955
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
956
+
957
+            $changes = [];
958
+
959
+            // This loop ensures that any duplicates are overwritten, only the
960
+            // last change on a node is relevant.
961
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
962
+
963
+                $changes[$row['uri']] = $row['operation'];
964
+
965
+            }
966
+
967
+            foreach($changes as $uri => $operation) {
968
+
969
+                switch($operation) {
970
+                    case 1 :
971
+                        $result['added'][] = $uri;
972
+                        break;
973
+                    case 2 :
974
+                        $result['modified'][] = $uri;
975
+                        break;
976
+                    case 3 :
977
+                        $result['deleted'][] = $uri;
978
+                        break;
979
+                }
980
+
981
+            }
982
+        } else {
983
+            // No synctoken supplied, this is the initial sync.
984
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
985
+            $stmt = $this->db->prepare($query);
986
+            $stmt->execute([$calendarId]);
987
+
988
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
989
+        }
990
+        return $result;
991
+
992
+    }
993
+
994
+    /**
995
+     * Returns a list of subscriptions for a principal.
996
+     *
997
+     * Every subscription is an array with the following keys:
998
+     *  * id, a unique id that will be used by other functions to modify the
999
+     *    subscription. This can be the same as the uri or a database key.
1000
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1001
+     *  * principaluri. The owner of the subscription. Almost always the same as
1002
+     *    principalUri passed to this method.
1003
+     *
1004
+     * Furthermore, all the subscription info must be returned too:
1005
+     *
1006
+     * 1. {DAV:}displayname
1007
+     * 2. {http://apple.com/ns/ical/}refreshrate
1008
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1009
+     *    should not be stripped).
1010
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1011
+     *    should not be stripped).
1012
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1013
+     *    attachments should not be stripped).
1014
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1015
+     *     Sabre\DAV\Property\Href).
1016
+     * 7. {http://apple.com/ns/ical/}calendar-color
1017
+     * 8. {http://apple.com/ns/ical/}calendar-order
1018
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1019
+     *    (should just be an instance of
1020
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1021
+     *    default components).
1022
+     *
1023
+     * @param string $principalUri
1024
+     * @return array
1025
+     */
1026
+    function getSubscriptionsForUser($principalUri) {
1027
+        $fields = array_values($this->subscriptionPropertyMap);
1028
+        $fields[] = 'id';
1029
+        $fields[] = 'uri';
1030
+        $fields[] = 'source';
1031
+        $fields[] = 'principaluri';
1032
+        $fields[] = 'lastmodified';
1033
+
1034
+        $query = $this->db->getQueryBuilder();
1035
+        $query->select($fields)
1036
+            ->from('calendarsubscriptions')
1037
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1038
+            ->orderBy('calendarorder', 'asc');
1039
+        $stmt =$query->execute();
1040
+
1041
+        $subscriptions = [];
1042
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1043
+
1044
+            $subscription = [
1045
+                'id'           => $row['id'],
1046
+                'uri'          => $row['uri'],
1047
+                'principaluri' => $row['principaluri'],
1048
+                'source'       => $row['source'],
1049
+                'lastmodified' => $row['lastmodified'],
1050
+
1051
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1052
+            ];
1053
+
1054
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1055
+                if (!is_null($row[$dbName])) {
1056
+                    $subscription[$xmlName] = $row[$dbName];
1057
+                }
1058
+            }
1059
+
1060
+            $subscriptions[] = $subscription;
1061
+
1062
+        }
1063
+
1064
+        return $subscriptions;
1065
+    }
1066
+
1067
+    /**
1068
+     * Creates a new subscription for a principal.
1069
+     *
1070
+     * If the creation was a success, an id must be returned that can be used to reference
1071
+     * this subscription in other methods, such as updateSubscription.
1072
+     *
1073
+     * @param string $principalUri
1074
+     * @param string $uri
1075
+     * @param array $properties
1076
+     * @return mixed
1077
+     */
1078
+    function createSubscription($principalUri, $uri, array $properties) {
1079
+
1080
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1081
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1082
+        }
1083
+
1084
+        $values = [
1085
+            'principaluri' => $principalUri,
1086
+            'uri'          => $uri,
1087
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1088
+            'lastmodified' => time(),
1089
+        ];
1090
+
1091
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1092
+
1093
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1094
+            if (array_key_exists($xmlName, $properties)) {
1095
+                    $values[$dbName] = $properties[$xmlName];
1096
+                    if (in_array($dbName, $propertiesBoolean)) {
1097
+                        $values[$dbName] = true;
1098
+                }
1099
+            }
1100
+        }
1101
+
1102
+        $valuesToInsert = array();
1103
+
1104
+        $query = $this->db->getQueryBuilder();
1105
+
1106
+        foreach (array_keys($values) as $name) {
1107
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1108
+        }
1109
+
1110
+        $query->insert('calendarsubscriptions')
1111
+            ->values($valuesToInsert)
1112
+            ->execute();
1113
+
1114
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1115
+    }
1116
+
1117
+    /**
1118
+     * Updates a subscription
1119
+     *
1120
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1121
+     * To do the actual updates, you must tell this object which properties
1122
+     * you're going to process with the handle() method.
1123
+     *
1124
+     * Calling the handle method is like telling the PropPatch object "I
1125
+     * promise I can handle updating this property".
1126
+     *
1127
+     * Read the PropPatch documentation for more info and examples.
1128
+     *
1129
+     * @param mixed $subscriptionId
1130
+     * @param PropPatch $propPatch
1131
+     * @return void
1132
+     */
1133
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1134
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1135
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1136
+
1137
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1138
+
1139
+            $newValues = [];
1140
+
1141
+            foreach($mutations as $propertyName=>$propertyValue) {
1142
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1143
+                    $newValues['source'] = $propertyValue->getHref();
1144
+                } else {
1145
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1146
+                    $newValues[$fieldName] = $propertyValue;
1147
+                }
1148
+            }
1149
+
1150
+            $query = $this->db->getQueryBuilder();
1151
+            $query->update('calendarsubscriptions')
1152
+                ->set('lastmodified', $query->createNamedParameter(time()));
1153
+            foreach($newValues as $fieldName=>$value) {
1154
+                $query->set($fieldName, $query->createNamedParameter($value));
1155
+            }
1156
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1157
+                ->execute();
1158
+
1159
+            return true;
1160
+
1161
+        });
1162
+    }
1163
+
1164
+    /**
1165
+     * Deletes a subscription.
1166
+     *
1167
+     * @param mixed $subscriptionId
1168
+     * @return void
1169
+     */
1170
+    function deleteSubscription($subscriptionId) {
1171
+        $query = $this->db->getQueryBuilder();
1172
+        $query->delete('calendarsubscriptions')
1173
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1174
+            ->execute();
1175
+    }
1176
+
1177
+    /**
1178
+     * Returns a single scheduling object for the inbox collection.
1179
+     *
1180
+     * The returned array should contain the following elements:
1181
+     *   * uri - A unique basename for the object. This will be used to
1182
+     *           construct a full uri.
1183
+     *   * calendardata - The iCalendar object
1184
+     *   * lastmodified - The last modification date. Can be an int for a unix
1185
+     *                    timestamp, or a PHP DateTime object.
1186
+     *   * etag - A unique token that must change if the object changed.
1187
+     *   * size - The size of the object, in bytes.
1188
+     *
1189
+     * @param string $principalUri
1190
+     * @param string $objectUri
1191
+     * @return array
1192
+     */
1193
+    function getSchedulingObject($principalUri, $objectUri) {
1194
+        $query = $this->db->getQueryBuilder();
1195
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1196
+            ->from('schedulingobjects')
1197
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1198
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1199
+            ->execute();
1200
+
1201
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1202
+
1203
+        if(!$row) {
1204
+            return null;
1205
+        }
1206
+
1207
+        return [
1208
+                'uri'          => $row['uri'],
1209
+                'calendardata' => $row['calendardata'],
1210
+                'lastmodified' => $row['lastmodified'],
1211
+                'etag'         => '"' . $row['etag'] . '"',
1212
+                'size'         => (int)$row['size'],
1213
+        ];
1214
+    }
1215
+
1216
+    /**
1217
+     * Returns all scheduling objects for the inbox collection.
1218
+     *
1219
+     * These objects should be returned as an array. Every item in the array
1220
+     * should follow the same structure as returned from getSchedulingObject.
1221
+     *
1222
+     * The main difference is that 'calendardata' is optional.
1223
+     *
1224
+     * @param string $principalUri
1225
+     * @return array
1226
+     */
1227
+    function getSchedulingObjects($principalUri) {
1228
+        $query = $this->db->getQueryBuilder();
1229
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1230
+                ->from('schedulingobjects')
1231
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1232
+                ->execute();
1233
+
1234
+        $result = [];
1235
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1236
+            $result[] = [
1237
+                    'calendardata' => $row['calendardata'],
1238
+                    'uri'          => $row['uri'],
1239
+                    'lastmodified' => $row['lastmodified'],
1240
+                    'etag'         => '"' . $row['etag'] . '"',
1241
+                    'size'         => (int)$row['size'],
1242
+            ];
1243
+        }
1244
+
1245
+        return $result;
1246
+    }
1247
+
1248
+    /**
1249
+     * Deletes a scheduling object from the inbox collection.
1250
+     *
1251
+     * @param string $principalUri
1252
+     * @param string $objectUri
1253
+     * @return void
1254
+     */
1255
+    function deleteSchedulingObject($principalUri, $objectUri) {
1256
+        $query = $this->db->getQueryBuilder();
1257
+        $query->delete('schedulingobjects')
1258
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1259
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1260
+                ->execute();
1261
+    }
1262
+
1263
+    /**
1264
+     * Creates a new scheduling object. This should land in a users' inbox.
1265
+     *
1266
+     * @param string $principalUri
1267
+     * @param string $objectUri
1268
+     * @param string $objectData
1269
+     * @return void
1270
+     */
1271
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1272
+        $query = $this->db->getQueryBuilder();
1273
+        $query->insert('schedulingobjects')
1274
+            ->values([
1275
+                'principaluri' => $query->createNamedParameter($principalUri),
1276
+                'calendardata' => $query->createNamedParameter($objectData),
1277
+                'uri' => $query->createNamedParameter($objectUri),
1278
+                'lastmodified' => $query->createNamedParameter(time()),
1279
+                'etag' => $query->createNamedParameter(md5($objectData)),
1280
+                'size' => $query->createNamedParameter(strlen($objectData))
1281
+            ])
1282
+            ->execute();
1283
+    }
1284
+
1285
+    /**
1286
+     * Adds a change record to the calendarchanges table.
1287
+     *
1288
+     * @param mixed $calendarId
1289
+     * @param string $objectUri
1290
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1291
+     * @return void
1292
+     */
1293
+    protected function addChange($calendarId, $objectUri, $operation) {
1294
+
1295
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1296
+        $stmt->execute([
1297
+            $objectUri,
1298
+            $calendarId,
1299
+            $operation,
1300
+            $calendarId
1301
+        ]);
1302
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1303
+        $stmt->execute([
1304
+            $calendarId
1305
+        ]);
1306
+
1307
+    }
1308
+
1309
+    /**
1310
+     * Parses some information from calendar objects, used for optimized
1311
+     * calendar-queries.
1312
+     *
1313
+     * Returns an array with the following keys:
1314
+     *   * etag - An md5 checksum of the object without the quotes.
1315
+     *   * size - Size of the object in bytes
1316
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1317
+     *   * firstOccurence
1318
+     *   * lastOccurence
1319
+     *   * uid - value of the UID property
1320
+     *
1321
+     * @param string $calendarData
1322
+     * @return array
1323
+     */
1324
+    public function getDenormalizedData($calendarData) {
1325
+
1326
+        $vObject = Reader::read($calendarData);
1327
+        $componentType = null;
1328
+        $component = null;
1329
+        $firstOccurrence = null;
1330
+        $lastOccurrence = null;
1331
+        $uid = null;
1332
+        $classification = self::CLASSIFICATION_PUBLIC;
1333
+        foreach($vObject->getComponents() as $component) {
1334
+            if ($component->name!=='VTIMEZONE') {
1335
+                $componentType = $component->name;
1336
+                $uid = (string)$component->UID;
1337
+                break;
1338
+            }
1339
+        }
1340
+        if (!$componentType) {
1341
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1342
+        }
1343
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1344
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1345
+            // Finding the last occurrence is a bit harder
1346
+            if (!isset($component->RRULE)) {
1347
+                if (isset($component->DTEND)) {
1348
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1349
+                } elseif (isset($component->DURATION)) {
1350
+                    $endDate = clone $component->DTSTART->getDateTime();
1351
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1352
+                    $lastOccurrence = $endDate->getTimeStamp();
1353
+                } elseif (!$component->DTSTART->hasTime()) {
1354
+                    $endDate = clone $component->DTSTART->getDateTime();
1355
+                    $endDate->modify('+1 day');
1356
+                    $lastOccurrence = $endDate->getTimeStamp();
1357
+                } else {
1358
+                    $lastOccurrence = $firstOccurrence;
1359
+                }
1360
+            } else {
1361
+                $it = new EventIterator($vObject, (string)$component->UID);
1362
+                $maxDate = new \DateTime(self::MAX_DATE);
1363
+                if ($it->isInfinite()) {
1364
+                    $lastOccurrence = $maxDate->getTimeStamp();
1365
+                } else {
1366
+                    $end = $it->getDtEnd();
1367
+                    while($it->valid() && $end < $maxDate) {
1368
+                        $end = $it->getDtEnd();
1369
+                        $it->next();
1370
+
1371
+                    }
1372
+                    $lastOccurrence = $end->getTimeStamp();
1373
+                }
1374
+
1375
+            }
1376
+        }
1377
+
1378
+        if ($component->CLASS) {
1379
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1380
+            switch ($component->CLASS->getValue()) {
1381
+                case 'PUBLIC':
1382
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1383
+                    break;
1384
+                case 'CONFIDENTIAL':
1385
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1386
+                    break;
1387
+            }
1388
+        }
1389
+        return [
1390
+            'etag' => md5($calendarData),
1391
+            'size' => strlen($calendarData),
1392
+            'componentType' => $componentType,
1393
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1394
+            'lastOccurence'  => $lastOccurrence,
1395
+            'uid' => $uid,
1396
+            'classification' => $classification
1397
+        ];
1398
+
1399
+    }
1400
+
1401
+    private function readBlob($cardData) {
1402
+        if (is_resource($cardData)) {
1403
+            return stream_get_contents($cardData);
1404
+        }
1405
+
1406
+        return $cardData;
1407
+    }
1408
+
1409
+    /**
1410
+     * @param IShareable $shareable
1411
+     * @param array $add
1412
+     * @param array $remove
1413
+     */
1414
+    public function updateShares($shareable, $add, $remove) {
1415
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1416
+    }
1417
+
1418
+    /**
1419
+     * @param int $resourceId
1420
+     * @return array
1421
+     */
1422
+    public function getShares($resourceId) {
1423
+        return $this->sharingBackend->getShares($resourceId);
1424
+    }
1425
+
1426
+    /**
1427
+     * @param int $resourceId
1428
+     * @param array $acl
1429
+     * @return array
1430
+     */
1431
+    public function applyShareAcl($resourceId, $acl) {
1432
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1433
+    }
1434
+
1435
+    private function convertPrincipal($principalUri, $toV2) {
1436
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1437
+            list(, $name) = URLUtil::splitPath($principalUri);
1438
+            if ($toV2 === true) {
1439
+                return "principals/users/$name";
1440
+            }
1441
+            return "principals/$name";
1442
+        }
1443
+        return $principalUri;
1444
+    }
1445 1445
 }
Please login to merge, or discard this patch.
Spacing   +77 added lines, -77 removed lines patch added patch discarded remove patch
@@ -164,24 +164,24 @@  discard block
 block discarded – undo
164 164
 		$stmt = $query->execute();
165 165
 
166 166
 		$calendars = [];
167
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
167
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
168 168
 
169 169
 			$components = [];
170 170
 			if ($row['components']) {
171
-				$components = explode(',',$row['components']);
171
+				$components = explode(',', $row['components']);
172 172
 			}
173 173
 
174 174
 			$calendar = [
175 175
 				'id' => $row['id'],
176 176
 				'uri' => $row['uri'],
177 177
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
178
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
179
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
180
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
181
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
178
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
179
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
180
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
181
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
182 182
 			];
183 183
 
184
-			foreach($this->propertyMap as $xmlName=>$dbName) {
184
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
185 185
 				$calendar[$xmlName] = $row[$dbName];
186 186
 			}
187 187
 
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 
195 195
 		// query for shared calendars
196 196
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
197
-		$principals[]= $principalUri;
197
+		$principals[] = $principalUri;
198 198
 
199 199
 		$fields = array_values($this->propertyMap);
200 200
 		$fields[] = 'a.id';
@@ -214,27 +214,27 @@  discard block
 block discarded – undo
214 214
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
215 215
 			->execute();
216 216
 
217
-		while($row = $result->fetch()) {
217
+		while ($row = $result->fetch()) {
218 218
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
219
-			$uri = $row['uri'] . '_shared_by_' . $name;
220
-			$row['displayname'] = $row['displayname'] . "($name)";
219
+			$uri = $row['uri'].'_shared_by_'.$name;
220
+			$row['displayname'] = $row['displayname']."($name)";
221 221
 			$components = [];
222 222
 			if ($row['components']) {
223
-				$components = explode(',',$row['components']);
223
+				$components = explode(',', $row['components']);
224 224
 			}
225 225
 			$calendar = [
226 226
 				'id' => $row['id'],
227 227
 				'uri' => $uri,
228 228
 				'principaluri' => $principalUri,
229
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
230
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
231
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
232
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
233
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
234
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
229
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
230
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
231
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
232
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
233
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
234
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
235 235
 			];
236 236
 
237
-			foreach($this->propertyMap as $xmlName=>$dbName) {
237
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
238 238
 				$calendar[$xmlName] = $row[$dbName];
239 239
 			}
240 240
 
@@ -277,20 +277,20 @@  discard block
 block discarded – undo
277 277
 
278 278
 		$components = [];
279 279
 		if ($row['components']) {
280
-			$components = explode(',',$row['components']);
280
+			$components = explode(',', $row['components']);
281 281
 		}
282 282
 
283 283
 		$calendar = [
284 284
 			'id' => $row['id'],
285 285
 			'uri' => $row['uri'],
286 286
 			'principaluri' => $row['principaluri'],
287
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
288
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
289
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
287
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
288
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
289
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
290
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
291 291
 		];
292 292
 
293
-		foreach($this->propertyMap as $xmlName=>$dbName) {
293
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
294 294
 			$calendar[$xmlName] = $row[$dbName];
295 295
 		}
296 296
 
@@ -321,20 +321,20 @@  discard block
 block discarded – undo
321 321
 
322 322
 		$components = [];
323 323
 		if ($row['components']) {
324
-			$components = explode(',',$row['components']);
324
+			$components = explode(',', $row['components']);
325 325
 		}
326 326
 
327 327
 		$calendar = [
328 328
 			'id' => $row['id'],
329 329
 			'uri' => $row['uri'],
330 330
 			'principaluri' => $row['principaluri'],
331
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
332
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
334
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
331
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
332
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
333
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
334
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
335 335
 		];
336 336
 
337
-		foreach($this->propertyMap as $xmlName=>$dbName) {
337
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
338 338
 			$calendar[$xmlName] = $row[$dbName];
339 339
 		}
340 340
 
@@ -366,16 +366,16 @@  discard block
 block discarded – undo
366 366
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
367 367
 		if (isset($properties[$sccs])) {
368 368
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
369
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
369
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
370 370
 			}
371
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
371
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
372 372
 		}
373
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
373
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
374 374
 		if (isset($properties[$transp])) {
375 375
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
376 376
 		}
377 377
 
378
-		foreach($this->propertyMap as $xmlName=>$dbName) {
378
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
379 379
 			if (isset($properties[$xmlName])) {
380 380
 				$values[$dbName] = $properties[$xmlName];
381 381
 			}
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 
384 384
 		$query = $this->db->getQueryBuilder();
385 385
 		$query->insert('calendars');
386
-		foreach($values as $column => $value) {
386
+		foreach ($values as $column => $value) {
387 387
 			$query->setValue($column, $query->createNamedParameter($value));
388 388
 		}
389 389
 		$query->execute();
@@ -407,14 +407,14 @@  discard block
 block discarded – undo
407 407
 	 */
408 408
 	function updateCalendar($calendarId, PropPatch $propPatch) {
409 409
 		$supportedProperties = array_keys($this->propertyMap);
410
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
410
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
411 411
 
412 412
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
413 413
 			$newValues = [];
414 414
 			foreach ($mutations as $propertyName => $propertyValue) {
415 415
 
416 416
 				switch ($propertyName) {
417
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
417
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
418 418
 						$fieldName = 'transparent';
419 419
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
420 420
 						break;
@@ -497,16 +497,16 @@  discard block
 block discarded – undo
497 497
 		$stmt = $query->execute();
498 498
 
499 499
 		$result = [];
500
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
500
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
501 501
 			$result[] = [
502 502
 					'id'           => $row['id'],
503 503
 					'uri'          => $row['uri'],
504 504
 					'lastmodified' => $row['lastmodified'],
505
-					'etag'         => '"' . $row['etag'] . '"',
505
+					'etag'         => '"'.$row['etag'].'"',
506 506
 					'calendarid'   => $row['calendarid'],
507
-					'size'         => (int)$row['size'],
507
+					'size'         => (int) $row['size'],
508 508
 					'component'    => strtolower($row['componenttype']),
509
-					'classification'=> (int)$row['classification']
509
+					'classification'=> (int) $row['classification']
510 510
 			];
511 511
 		}
512 512
 
@@ -539,18 +539,18 @@  discard block
 block discarded – undo
539 539
 		$stmt = $query->execute();
540 540
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
541 541
 
542
-		if(!$row) return null;
542
+		if (!$row) return null;
543 543
 
544 544
 		return [
545 545
 				'id'            => $row['id'],
546 546
 				'uri'           => $row['uri'],
547 547
 				'lastmodified'  => $row['lastmodified'],
548
-				'etag'          => '"' . $row['etag'] . '"',
548
+				'etag'          => '"'.$row['etag'].'"',
549 549
 				'calendarid'    => $row['calendarid'],
550
-				'size'          => (int)$row['size'],
550
+				'size'          => (int) $row['size'],
551 551
 				'calendardata'  => $this->readBlob($row['calendardata']),
552 552
 				'component'     => strtolower($row['componenttype']),
553
-				'classification'=> (int)$row['classification']
553
+				'classification'=> (int) $row['classification']
554 554
 		];
555 555
 	}
556 556
 
@@ -589,12 +589,12 @@  discard block
 block discarded – undo
589 589
 					'id'           => $row['id'],
590 590
 					'uri'          => $row['uri'],
591 591
 					'lastmodified' => $row['lastmodified'],
592
-					'etag'         => '"' . $row['etag'] . '"',
592
+					'etag'         => '"'.$row['etag'].'"',
593 593
 					'calendarid'   => $row['calendarid'],
594
-					'size'         => (int)$row['size'],
594
+					'size'         => (int) $row['size'],
595 595
 					'calendardata' => $this->readBlob($row['calendardata']),
596 596
 					'component'    => strtolower($row['componenttype']),
597
-					'classification' => (int)$row['classification']
597
+					'classification' => (int) $row['classification']
598 598
 				];
599 599
 			}
600 600
 			$result->closeCursor();
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
 
643 643
 		$this->addChange($calendarId, $objectUri, 1);
644 644
 
645
-		return '"' . $extraData['etag'] . '"';
645
+		return '"'.$extraData['etag'].'"';
646 646
 	}
647 647
 
648 648
 	/**
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 
684 684
 		$this->addChange($calendarId, $objectUri, 2);
685 685
 
686
-		return '"' . $extraData['etag'] . '"';
686
+		return '"'.$extraData['etag'].'"';
687 687
 	}
688 688
 
689 689
 	/**
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		$stmt = $query->execute();
822 822
 
823 823
 		$result = [];
824
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
824
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
825 825
 			if ($requirePostFilter) {
826 826
 				if (!$this->validateFilterForObject($row, $filters)) {
827 827
 					continue;
@@ -864,7 +864,7 @@  discard block
 block discarded – undo
864 864
 		$stmt = $query->execute();
865 865
 
866 866
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
867
-			return $row['calendaruri'] . '/' . $row['objecturi'];
867
+			return $row['calendaruri'].'/'.$row['objecturi'];
868 868
 		}
869 869
 
870 870
 		return null;
@@ -929,7 +929,7 @@  discard block
 block discarded – undo
929 929
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
930 930
 		// Current synctoken
931 931
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
932
-		$stmt->execute([ $calendarId ]);
932
+		$stmt->execute([$calendarId]);
933 933
 		$currentToken = $stmt->fetchColumn(0);
934 934
 
935 935
 		if (is_null($currentToken)) {
@@ -946,8 +946,8 @@  discard block
 block discarded – undo
946 946
 		if ($syncToken) {
947 947
 
948 948
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
949
-			if ($limit>0) {
950
-				$query.= " `LIMIT` " . (int)$limit;
949
+			if ($limit > 0) {
950
+				$query .= " `LIMIT` ".(int) $limit;
951 951
 			}
952 952
 
953 953
 			// Fetching all changes
@@ -958,15 +958,15 @@  discard block
 block discarded – undo
958 958
 
959 959
 			// This loop ensures that any duplicates are overwritten, only the
960 960
 			// last change on a node is relevant.
961
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
961
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
962 962
 
963 963
 				$changes[$row['uri']] = $row['operation'];
964 964
 
965 965
 			}
966 966
 
967
-			foreach($changes as $uri => $operation) {
967
+			foreach ($changes as $uri => $operation) {
968 968
 
969
-				switch($operation) {
969
+				switch ($operation) {
970 970
 					case 1 :
971 971
 						$result['added'][] = $uri;
972 972
 						break;
@@ -1036,10 +1036,10 @@  discard block
 block discarded – undo
1036 1036
 			->from('calendarsubscriptions')
1037 1037
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1038 1038
 			->orderBy('calendarorder', 'asc');
1039
-		$stmt =$query->execute();
1039
+		$stmt = $query->execute();
1040 1040
 
1041 1041
 		$subscriptions = [];
1042
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1042
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1043 1043
 
1044 1044
 			$subscription = [
1045 1045
 				'id'           => $row['id'],
@@ -1048,10 +1048,10 @@  discard block
 block discarded – undo
1048 1048
 				'source'       => $row['source'],
1049 1049
 				'lastmodified' => $row['lastmodified'],
1050 1050
 
1051
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1051
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1052 1052
 			];
1053 1053
 
1054
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1054
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1055 1055
 				if (!is_null($row[$dbName])) {
1056 1056
 					$subscription[$xmlName] = $row[$dbName];
1057 1057
 				}
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
 
1091 1091
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1092 1092
 
1093
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1093
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1094 1094
 			if (array_key_exists($xmlName, $properties)) {
1095 1095
 					$values[$dbName] = $properties[$xmlName];
1096 1096
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1138,7 +1138,7 @@  discard block
 block discarded – undo
1138 1138
 
1139 1139
 			$newValues = [];
1140 1140
 
1141
-			foreach($mutations as $propertyName=>$propertyValue) {
1141
+			foreach ($mutations as $propertyName=>$propertyValue) {
1142 1142
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1143 1143
 					$newValues['source'] = $propertyValue->getHref();
1144 1144
 				} else {
@@ -1150,7 +1150,7 @@  discard block
 block discarded – undo
1150 1150
 			$query = $this->db->getQueryBuilder();
1151 1151
 			$query->update('calendarsubscriptions')
1152 1152
 				->set('lastmodified', $query->createNamedParameter(time()));
1153
-			foreach($newValues as $fieldName=>$value) {
1153
+			foreach ($newValues as $fieldName=>$value) {
1154 1154
 				$query->set($fieldName, $query->createNamedParameter($value));
1155 1155
 			}
1156 1156
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1200,7 +1200,7 @@  discard block
 block discarded – undo
1200 1200
 
1201 1201
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1202 1202
 
1203
-		if(!$row) {
1203
+		if (!$row) {
1204 1204
 			return null;
1205 1205
 		}
1206 1206
 
@@ -1208,8 +1208,8 @@  discard block
 block discarded – undo
1208 1208
 				'uri'          => $row['uri'],
1209 1209
 				'calendardata' => $row['calendardata'],
1210 1210
 				'lastmodified' => $row['lastmodified'],
1211
-				'etag'         => '"' . $row['etag'] . '"',
1212
-				'size'         => (int)$row['size'],
1211
+				'etag'         => '"'.$row['etag'].'"',
1212
+				'size'         => (int) $row['size'],
1213 1213
 		];
1214 1214
 	}
1215 1215
 
@@ -1232,13 +1232,13 @@  discard block
 block discarded – undo
1232 1232
 				->execute();
1233 1233
 
1234 1234
 		$result = [];
1235
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1235
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1236 1236
 			$result[] = [
1237 1237
 					'calendardata' => $row['calendardata'],
1238 1238
 					'uri'          => $row['uri'],
1239 1239
 					'lastmodified' => $row['lastmodified'],
1240
-					'etag'         => '"' . $row['etag'] . '"',
1241
-					'size'         => (int)$row['size'],
1240
+					'etag'         => '"'.$row['etag'].'"',
1241
+					'size'         => (int) $row['size'],
1242 1242
 			];
1243 1243
 		}
1244 1244
 
@@ -1330,10 +1330,10 @@  discard block
 block discarded – undo
1330 1330
 		$lastOccurrence = null;
1331 1331
 		$uid = null;
1332 1332
 		$classification = self::CLASSIFICATION_PUBLIC;
1333
-		foreach($vObject->getComponents() as $component) {
1334
-			if ($component->name!=='VTIMEZONE') {
1333
+		foreach ($vObject->getComponents() as $component) {
1334
+			if ($component->name !== 'VTIMEZONE') {
1335 1335
 				$componentType = $component->name;
1336
-				$uid = (string)$component->UID;
1336
+				$uid = (string) $component->UID;
1337 1337
 				break;
1338 1338
 			}
1339 1339
 		}
@@ -1358,13 +1358,13 @@  discard block
 block discarded – undo
1358 1358
 					$lastOccurrence = $firstOccurrence;
1359 1359
 				}
1360 1360
 			} else {
1361
-				$it = new EventIterator($vObject, (string)$component->UID);
1361
+				$it = new EventIterator($vObject, (string) $component->UID);
1362 1362
 				$maxDate = new \DateTime(self::MAX_DATE);
1363 1363
 				if ($it->isInfinite()) {
1364 1364
 					$lastOccurrence = $maxDate->getTimeStamp();
1365 1365
 				} else {
1366 1366
 					$end = $it->getDtEnd();
1367
-					while($it->valid() && $end < $maxDate) {
1367
+					while ($it->valid() && $end < $maxDate) {
1368 1368
 						$end = $it->getDtEnd();
1369 1369
 						$it->next();
1370 1370
 
Please login to merge, or discard this patch.