Passed
Push — master ( f28691...670257 )
by Jan-Christoph
12:38
created
apps/dav/lib/CalDAV/Activity/Setting/Todo.php 1 patch
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -27,72 +27,72 @@
 block discarded – undo
27 27
 
28 28
 class Todo implements ISetting {
29 29
 
30
-	/** @var IL10N */
31
-	protected $l;
30
+    /** @var IL10N */
31
+    protected $l;
32 32
 
33
-	/**
34
-	 * @param IL10N $l
35
-	 */
36
-	public function __construct(IL10N $l) {
37
-		$this->l = $l;
38
-	}
33
+    /**
34
+     * @param IL10N $l
35
+     */
36
+    public function __construct(IL10N $l) {
37
+        $this->l = $l;
38
+    }
39 39
 
40
-	/**
41
-	 * @return string Lowercase a-z and underscore only identifier
42
-	 * @since 11.0.0
43
-	 */
44
-	public function getIdentifier() {
45
-		return 'calendar_todo';
46
-	}
40
+    /**
41
+     * @return string Lowercase a-z and underscore only identifier
42
+     * @since 11.0.0
43
+     */
44
+    public function getIdentifier() {
45
+        return 'calendar_todo';
46
+    }
47 47
 
48
-	/**
49
-	 * @return string A translated string
50
-	 * @since 11.0.0
51
-	 */
52
-	public function getName() {
53
-		return $this->l->t('A calendar <strong>todo</strong> was modified');
54
-	}
48
+    /**
49
+     * @return string A translated string
50
+     * @since 11.0.0
51
+     */
52
+    public function getName() {
53
+        return $this->l->t('A calendar <strong>todo</strong> was modified');
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the filter should be rather on the top or bottom of
58
-	 * the admin section. The filters are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 * @since 11.0.0
61
-	 */
62
-	public function getPriority() {
63
-		return 50;
64
-	}
56
+    /**
57
+     * @return int whether the filter should be rather on the top or bottom of
58
+     * the admin section. The filters are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     * @since 11.0.0
61
+     */
62
+    public function getPriority() {
63
+        return 50;
64
+    }
65 65
 
66
-	/**
67
-	 * @return bool True when the option can be changed for the stream
68
-	 * @since 11.0.0
69
-	 */
70
-	public function canChangeStream() {
71
-		return true;
72
-	}
66
+    /**
67
+     * @return bool True when the option can be changed for the stream
68
+     * @since 11.0.0
69
+     */
70
+    public function canChangeStream() {
71
+        return true;
72
+    }
73 73
 
74
-	/**
75
-	 * @return bool True when the option can be changed for the stream
76
-	 * @since 11.0.0
77
-	 */
78
-	public function isDefaultEnabledStream() {
79
-		return true;
80
-	}
74
+    /**
75
+     * @return bool True when the option can be changed for the stream
76
+     * @since 11.0.0
77
+     */
78
+    public function isDefaultEnabledStream() {
79
+        return true;
80
+    }
81 81
 
82
-	/**
83
-	 * @return bool True when the option can be changed for the mail
84
-	 * @since 11.0.0
85
-	 */
86
-	public function canChangeMail() {
87
-		return true;
88
-	}
82
+    /**
83
+     * @return bool True when the option can be changed for the mail
84
+     * @since 11.0.0
85
+     */
86
+    public function canChangeMail() {
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * @return bool True when the option can be changed for the stream
92
-	 * @since 11.0.0
93
-	 */
94
-	public function isDefaultEnabledMail() {
95
-		return false;
96
-	}
90
+    /**
91
+     * @return bool True when the option can be changed for the stream
92
+     * @since 11.0.0
93
+     */
94
+    public function isDefaultEnabledMail() {
95
+        return false;
96
+    }
97 97
 }
98 98
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 3 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Spacing   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
218 218
 		}
219 219
 
220
-		return (int)$query->execute()->fetchColumn();
220
+		return (int) $query->execute()->fetchColumn();
221 221
 	}
222 222
 
223 223
 	/**
@@ -264,25 +264,25 @@  discard block
 block discarded – undo
264 264
 		$stmt = $query->execute();
265 265
 
266 266
 		$calendars = [];
267
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
267
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
268 268
 
269 269
 			$components = [];
270 270
 			if ($row['components']) {
271
-				$components = explode(',',$row['components']);
271
+				$components = explode(',', $row['components']);
272 272
 			}
273 273
 
274 274
 			$calendar = [
275 275
 				'id' => $row['id'],
276 276
 				'uri' => $row['uri'],
277 277
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
278
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
279
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
280
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
281
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
282
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
278
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
279
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
280
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
281
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
282
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
283 283
 			];
284 284
 
285
-			foreach($this->propertyMap as $xmlName=>$dbName) {
285
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
286 286
 				$calendar[$xmlName] = $row[$dbName];
287 287
 			}
288 288
 
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
 		$principals = array_map(function($principal) {
301 301
 			return urldecode($principal);
302 302
 		}, $principals);
303
-		$principals[]= $principalUri;
303
+		$principals[] = $principalUri;
304 304
 
305 305
 		$fields = array_values($this->propertyMap);
306 306
 		$fields[] = 'a.id';
@@ -320,8 +320,8 @@  discard block
 block discarded – undo
320 320
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
321 321
 			->execute();
322 322
 
323
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
324
-		while($row = $result->fetch()) {
323
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
324
+		while ($row = $result->fetch()) {
325 325
 			if ($row['principaluri'] === $principalUri) {
326 326
 				continue;
327 327
 			}
@@ -340,25 +340,25 @@  discard block
 block discarded – undo
340 340
 			}
341 341
 
342 342
 			list(, $name) = Uri\split($row['principaluri']);
343
-			$uri = $row['uri'] . '_shared_by_' . $name;
344
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
343
+			$uri = $row['uri'].'_shared_by_'.$name;
344
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
345 345
 			$components = [];
346 346
 			if ($row['components']) {
347
-				$components = explode(',',$row['components']);
347
+				$components = explode(',', $row['components']);
348 348
 			}
349 349
 			$calendar = [
350 350
 				'id' => $row['id'],
351 351
 				'uri' => $uri,
352 352
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
353
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
354
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
355
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
357
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
353
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
354
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
355
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
357
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
358 358
 				$readOnlyPropertyName => $readOnly,
359 359
 			];
360 360
 
361
-			foreach($this->propertyMap as $xmlName=>$dbName) {
361
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
362 362
 				$calendar[$xmlName] = $row[$dbName];
363 363
 			}
364 364
 
@@ -387,21 +387,21 @@  discard block
 block discarded – undo
387 387
 			->orderBy('calendarorder', 'ASC');
388 388
 		$stmt = $query->execute();
389 389
 		$calendars = [];
390
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
390
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
391 391
 			$components = [];
392 392
 			if ($row['components']) {
393
-				$components = explode(',',$row['components']);
393
+				$components = explode(',', $row['components']);
394 394
 			}
395 395
 			$calendar = [
396 396
 				'id' => $row['id'],
397 397
 				'uri' => $row['uri'],
398 398
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
399
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
400
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
401
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
402
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
399
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
400
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
401
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
402
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
403 403
 			];
404
-			foreach($this->propertyMap as $xmlName=>$dbName) {
404
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
405 405
 				$calendar[$xmlName] = $row[$dbName];
406 406
 			}
407 407
 
@@ -452,27 +452,27 @@  discard block
 block discarded – undo
452 452
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
453 453
 			->execute();
454 454
 
455
-		while($row = $result->fetch()) {
455
+		while ($row = $result->fetch()) {
456 456
 			list(, $name) = Uri\split($row['principaluri']);
457
-			$row['displayname'] = $row['displayname'] . "($name)";
457
+			$row['displayname'] = $row['displayname']."($name)";
458 458
 			$components = [];
459 459
 			if ($row['components']) {
460
-				$components = explode(',',$row['components']);
460
+				$components = explode(',', $row['components']);
461 461
 			}
462 462
 			$calendar = [
463 463
 				'id' => $row['id'],
464 464
 				'uri' => $row['publicuri'],
465 465
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
466
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
467
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
468
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
470
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
471
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
472
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
466
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
467
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
468
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
469
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
470
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
471
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
472
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
473 473
 			];
474 474
 
475
-			foreach($this->propertyMap as $xmlName=>$dbName) {
475
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
476 476
 				$calendar[$xmlName] = $row[$dbName];
477 477
 			}
478 478
 
@@ -516,29 +516,29 @@  discard block
 block discarded – undo
516 516
 		$result->closeCursor();
517 517
 
518 518
 		if ($row === false) {
519
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
519
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
520 520
 		}
521 521
 
522 522
 		list(, $name) = Uri\split($row['principaluri']);
523
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
523
+		$row['displayname'] = $row['displayname'].' '."($name)";
524 524
 		$components = [];
525 525
 		if ($row['components']) {
526
-			$components = explode(',',$row['components']);
526
+			$components = explode(',', $row['components']);
527 527
 		}
528 528
 		$calendar = [
529 529
 			'id' => $row['id'],
530 530
 			'uri' => $row['publicuri'],
531 531
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
532
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
533
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
534
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
538
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
532
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
533
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
534
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
535
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
536
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
538
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
539 539
 		];
540 540
 
541
-		foreach($this->propertyMap as $xmlName=>$dbName) {
541
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
542 542
 			$calendar[$xmlName] = $row[$dbName];
543 543
 		}
544 544
 
@@ -578,20 +578,20 @@  discard block
 block discarded – undo
578 578
 
579 579
 		$components = [];
580 580
 		if ($row['components']) {
581
-			$components = explode(',',$row['components']);
581
+			$components = explode(',', $row['components']);
582 582
 		}
583 583
 
584 584
 		$calendar = [
585 585
 			'id' => $row['id'],
586 586
 			'uri' => $row['uri'],
587 587
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
588
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
589
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
590
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
591
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
588
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
589
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
590
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
591
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
592 592
 		];
593 593
 
594
-		foreach($this->propertyMap as $xmlName=>$dbName) {
594
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
595 595
 			$calendar[$xmlName] = $row[$dbName];
596 596
 		}
597 597
 
@@ -624,20 +624,20 @@  discard block
 block discarded – undo
624 624
 
625 625
 		$components = [];
626 626
 		if ($row['components']) {
627
-			$components = explode(',',$row['components']);
627
+			$components = explode(',', $row['components']);
628 628
 		}
629 629
 
630 630
 		$calendar = [
631 631
 			'id' => $row['id'],
632 632
 			'uri' => $row['uri'],
633 633
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
634
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
635
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
636
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
637
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
634
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
635
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
636
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
637
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
638 638
 		];
639 639
 
640
-		foreach($this->propertyMap as $xmlName=>$dbName) {
640
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
641 641
 			$calendar[$xmlName] = $row[$dbName];
642 642
 		}
643 643
 
@@ -672,16 +672,16 @@  discard block
 block discarded – undo
672 672
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
673 673
 		if (isset($properties[$sccs])) {
674 674
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
675
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
675
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
676 676
 			}
677
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
677
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
678 678
 		}
679
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
679
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
680 680
 		if (isset($properties[$transp])) {
681 681
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
682 682
 		}
683 683
 
684
-		foreach($this->propertyMap as $xmlName=>$dbName) {
684
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
685 685
 			if (isset($properties[$xmlName])) {
686 686
 				$values[$dbName] = $properties[$xmlName];
687 687
 			}
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 
690 690
 		$query = $this->db->getQueryBuilder();
691 691
 		$query->insert('calendars');
692
-		foreach($values as $column => $value) {
692
+		foreach ($values as $column => $value) {
693 693
 			$query->setValue($column, $query->createNamedParameter($value));
694 694
 		}
695 695
 		$query->execute();
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 	 */
724 724
 	function updateCalendar($calendarId, PropPatch $propPatch) {
725 725
 		$supportedProperties = array_keys($this->propertyMap);
726
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
726
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
727 727
 
728 728
 		/**
729 729
 		 * @suppress SqlInjectionChecker
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
 			foreach ($mutations as $propertyName => $propertyValue) {
734 734
 
735 735
 				switch ($propertyName) {
736
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
736
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
737 737
 						$fieldName = 'transparent';
738 738
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
739 739
 						break;
@@ -848,16 +848,16 @@  discard block
 block discarded – undo
848 848
 		$stmt = $query->execute();
849 849
 
850 850
 		$result = [];
851
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
851
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
852 852
 			$result[] = [
853 853
 					'id'           => $row['id'],
854 854
 					'uri'          => $row['uri'],
855 855
 					'lastmodified' => $row['lastmodified'],
856
-					'etag'         => '"' . $row['etag'] . '"',
856
+					'etag'         => '"'.$row['etag'].'"',
857 857
 					'calendarid'   => $row['calendarid'],
858
-					'size'         => (int)$row['size'],
858
+					'size'         => (int) $row['size'],
859 859
 					'component'    => strtolower($row['componenttype']),
860
-					'classification'=> (int)$row['classification']
860
+					'classification'=> (int) $row['classification']
861 861
 			];
862 862
 		}
863 863
 
@@ -890,18 +890,18 @@  discard block
 block discarded – undo
890 890
 		$stmt = $query->execute();
891 891
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
892 892
 
893
-		if(!$row) return null;
893
+		if (!$row) return null;
894 894
 
895 895
 		return [
896 896
 				'id'            => $row['id'],
897 897
 				'uri'           => $row['uri'],
898 898
 				'lastmodified'  => $row['lastmodified'],
899
-				'etag'          => '"' . $row['etag'] . '"',
899
+				'etag'          => '"'.$row['etag'].'"',
900 900
 				'calendarid'    => $row['calendarid'],
901
-				'size'          => (int)$row['size'],
901
+				'size'          => (int) $row['size'],
902 902
 				'calendardata'  => $this->readBlob($row['calendardata']),
903 903
 				'component'     => strtolower($row['componenttype']),
904
-				'classification'=> (int)$row['classification']
904
+				'classification'=> (int) $row['classification']
905 905
 		];
906 906
 	}
907 907
 
@@ -940,12 +940,12 @@  discard block
 block discarded – undo
940 940
 					'id'           => $row['id'],
941 941
 					'uri'          => $row['uri'],
942 942
 					'lastmodified' => $row['lastmodified'],
943
-					'etag'         => '"' . $row['etag'] . '"',
943
+					'etag'         => '"'.$row['etag'].'"',
944 944
 					'calendarid'   => $row['calendarid'],
945
-					'size'         => (int)$row['size'],
945
+					'size'         => (int) $row['size'],
946 946
 					'calendardata' => $this->readBlob($row['calendardata']),
947 947
 					'component'    => strtolower($row['componenttype']),
948
-					'classification' => (int)$row['classification']
948
+					'classification' => (int) $row['classification']
949 949
 				];
950 950
 			}
951 951
 			$result->closeCursor();
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 		));
1019 1019
 		$this->addChange($calendarId, $objectUri, 1);
1020 1020
 
1021
-		return '"' . $extraData['etag'] . '"';
1021
+		return '"'.$extraData['etag'].'"';
1022 1022
 	}
1023 1023
 
1024 1024
 	/**
@@ -1073,7 +1073,7 @@  discard block
 block discarded – undo
1073 1073
 		}
1074 1074
 		$this->addChange($calendarId, $objectUri, 2);
1075 1075
 
1076
-		return '"' . $extraData['etag'] . '"';
1076
+		return '"'.$extraData['etag'].'"';
1077 1077
 	}
1078 1078
 
1079 1079
 	/**
@@ -1226,13 +1226,13 @@  discard block
 block discarded – undo
1226 1226
 		$stmt = $query->execute();
1227 1227
 
1228 1228
 		$result = [];
1229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1230 1230
 			if ($requirePostFilter) {
1231 1231
 				// validateFilterForObject will parse the calendar data
1232 1232
 				// catch parsing errors
1233 1233
 				try {
1234 1234
 					$matches = $this->validateFilterForObject($row, $filters);
1235
-				} catch(ParseException $ex) {
1235
+				} catch (ParseException $ex) {
1236 1236
 					$this->logger->logException($ex, [
1237 1237
 						'app' => 'dav',
1238 1238
 						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
@@ -1265,14 +1265,14 @@  discard block
 block discarded – undo
1265 1265
 	 * @param integer|null $offset
1266 1266
 	 * @return array
1267 1267
 	 */
1268
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1268
+	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1269 1269
 		$calendars = $this->getCalendarsForUser($principalUri);
1270 1270
 		$ownCalendars = [];
1271 1271
 		$sharedCalendars = [];
1272 1272
 
1273 1273
 		$uriMapper = [];
1274 1274
 
1275
-		foreach($calendars as $calendar) {
1275
+		foreach ($calendars as $calendar) {
1276 1276
 			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1277 1277
 				$ownCalendars[] = $calendar['id'];
1278 1278
 			} else {
@@ -1287,11 +1287,11 @@  discard block
 block discarded – undo
1287 1287
 		$query = $this->db->getQueryBuilder();
1288 1288
 		// Calendar id expressions
1289 1289
 		$calendarExpressions = [];
1290
-		foreach($ownCalendars as $id) {
1290
+		foreach ($ownCalendars as $id) {
1291 1291
 			$calendarExpressions[] = $query->expr()
1292 1292
 				->eq('c.calendarid', $query->createNamedParameter($id));
1293 1293
 		}
1294
-		foreach($sharedCalendars as $id) {
1294
+		foreach ($sharedCalendars as $id) {
1295 1295
 			$calendarExpressions[] = $query->expr()->andX(
1296 1296
 				$query->expr()->eq('c.calendarid',
1297 1297
 					$query->createNamedParameter($id)),
@@ -1308,7 +1308,7 @@  discard block
 block discarded – undo
1308 1308
 
1309 1309
 		// Component expressions
1310 1310
 		$compExpressions = [];
1311
-		foreach($filters['comps'] as $comp) {
1311
+		foreach ($filters['comps'] as $comp) {
1312 1312
 			$compExpressions[] = $query->expr()
1313 1313
 				->eq('c.componenttype', $query->createNamedParameter($comp));
1314 1314
 		}
@@ -1327,13 +1327,13 @@  discard block
 block discarded – undo
1327 1327
 		}
1328 1328
 
1329 1329
 		$propParamExpressions = [];
1330
-		foreach($filters['props'] as $prop) {
1330
+		foreach ($filters['props'] as $prop) {
1331 1331
 			$propParamExpressions[] = $query->expr()->andX(
1332 1332
 				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1333 1333
 				$query->expr()->isNull('i.parameter')
1334 1334
 			);
1335 1335
 		}
1336
-		foreach($filters['params'] as $param) {
1336
+		foreach ($filters['params'] as $param) {
1337 1337
 			$propParamExpressions[] = $query->expr()->andX(
1338 1338
 				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1339 1339
 				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
@@ -1365,8 +1365,8 @@  discard block
 block discarded – undo
1365 1365
 		$stmt = $query->execute();
1366 1366
 
1367 1367
 		$result = [];
1368
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1369
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1368
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1369
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1370 1370
 			if (!in_array($path, $result)) {
1371 1371
 				$result[] = $path;
1372 1372
 			}
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
 		}
1405 1405
 
1406 1406
 		$or = $innerQuery->expr()->orX();
1407
-		foreach($searchProperties as $searchProperty) {
1407
+		foreach ($searchProperties as $searchProperty) {
1408 1408
 			$or->add($innerQuery->expr()->eq('op.name',
1409 1409
 				$outerQuery->createNamedParameter($searchProperty)));
1410 1410
 		}
@@ -1412,8 +1412,8 @@  discard block
 block discarded – undo
1412 1412
 
1413 1413
 		if ($pattern !== '') {
1414 1414
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1415
-				$outerQuery->createNamedParameter('%' .
1416
-					$this->db->escapeLikeParameter($pattern) . '%')));
1415
+				$outerQuery->createNamedParameter('%'.
1416
+					$this->db->escapeLikeParameter($pattern).'%')));
1417 1417
 		}
1418 1418
 
1419 1419
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
 
1434 1434
 		if (isset($options['types'])) {
1435 1435
 			$or = $outerQuery->expr()->orX();
1436
-			foreach($options['types'] as $type) {
1436
+			foreach ($options['types'] as $type) {
1437 1437
 				$or->add($outerQuery->expr()->eq('componenttype',
1438 1438
 					$outerQuery->createNamedParameter($type)));
1439 1439
 			}
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 			$comps = $calendarData->getComponents();
1459 1459
 			$objects = [];
1460 1460
 			$timezones = [];
1461
-			foreach($comps as $comp) {
1461
+			foreach ($comps as $comp) {
1462 1462
 				if ($comp instanceof VTimeZone) {
1463 1463
 					$timezones[] = $comp;
1464 1464
 				} else {
@@ -1495,7 +1495,7 @@  discard block
 block discarded – undo
1495 1495
 		});
1496 1496
 		$validationRules = $comp->getValidationRules();
1497 1497
 
1498
-		foreach($subComponents as $subComponent) {
1498
+		foreach ($subComponents as $subComponent) {
1499 1499
 			$name = $subComponent->name;
1500 1500
 			if (!isset($data[$name])) {
1501 1501
 				$data[$name] = [];
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
 			$data[$name][] = $this->transformSearchData($subComponent);
1504 1504
 		}
1505 1505
 
1506
-		foreach($properties as $property) {
1506
+		foreach ($properties as $property) {
1507 1507
 			$name = $property->name;
1508 1508
 			if (!isset($validationRules[$name])) {
1509 1509
 				$validationRules[$name] = '*';
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
 		$stmt = $query->execute();
1574 1574
 
1575 1575
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1576
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1576
+			return $row['calendaruri'].'/'.$row['objecturi'];
1577 1577
 		}
1578 1578
 
1579 1579
 		return null;
@@ -1638,7 +1638,7 @@  discard block
 block discarded – undo
1638 1638
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1639 1639
 		// Current synctoken
1640 1640
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1641
-		$stmt->execute([ $calendarId ]);
1641
+		$stmt->execute([$calendarId]);
1642 1642
 		$currentToken = $stmt->fetchColumn(0);
1643 1643
 
1644 1644
 		if (is_null($currentToken)) {
@@ -1655,8 +1655,8 @@  discard block
 block discarded – undo
1655 1655
 		if ($syncToken) {
1656 1656
 
1657 1657
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1658
-			if ($limit>0) {
1659
-				$query.= " LIMIT " . (int)$limit;
1658
+			if ($limit > 0) {
1659
+				$query .= " LIMIT ".(int) $limit;
1660 1660
 			}
1661 1661
 
1662 1662
 			// Fetching all changes
@@ -1667,15 +1667,15 @@  discard block
 block discarded – undo
1667 1667
 
1668 1668
 			// This loop ensures that any duplicates are overwritten, only the
1669 1669
 			// last change on a node is relevant.
1670
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1670
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1671 1671
 
1672 1672
 				$changes[$row['uri']] = $row['operation'];
1673 1673
 
1674 1674
 			}
1675 1675
 
1676
-			foreach($changes as $uri => $operation) {
1676
+			foreach ($changes as $uri => $operation) {
1677 1677
 
1678
-				switch($operation) {
1678
+				switch ($operation) {
1679 1679
 					case 1 :
1680 1680
 						$result['added'][] = $uri;
1681 1681
 						break;
@@ -1745,10 +1745,10 @@  discard block
 block discarded – undo
1745 1745
 			->from('calendarsubscriptions')
1746 1746
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1747 1747
 			->orderBy('calendarorder', 'asc');
1748
-		$stmt =$query->execute();
1748
+		$stmt = $query->execute();
1749 1749
 
1750 1750
 		$subscriptions = [];
1751
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1751
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1752 1752
 
1753 1753
 			$subscription = [
1754 1754
 				'id'           => $row['id'],
@@ -1757,10 +1757,10 @@  discard block
 block discarded – undo
1757 1757
 				'source'       => $row['source'],
1758 1758
 				'lastmodified' => $row['lastmodified'],
1759 1759
 
1760
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1760
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1761 1761
 			];
1762 1762
 
1763
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1763
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1764 1764
 				if (!is_null($row[$dbName])) {
1765 1765
 					$subscription[$xmlName] = $row[$dbName];
1766 1766
 				}
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
 
1800 1800
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1801 1801
 
1802
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1802
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1803 1803
 			if (array_key_exists($xmlName, $properties)) {
1804 1804
 					$values[$dbName] = $properties[$xmlName];
1805 1805
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1850,7 +1850,7 @@  discard block
 block discarded – undo
1850 1850
 
1851 1851
 			$newValues = [];
1852 1852
 
1853
-			foreach($mutations as $propertyName=>$propertyValue) {
1853
+			foreach ($mutations as $propertyName=>$propertyValue) {
1854 1854
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1855 1855
 					$newValues['source'] = $propertyValue->getHref();
1856 1856
 				} else {
@@ -1862,7 +1862,7 @@  discard block
 block discarded – undo
1862 1862
 			$query = $this->db->getQueryBuilder();
1863 1863
 			$query->update('calendarsubscriptions')
1864 1864
 				->set('lastmodified', $query->createNamedParameter(time()));
1865
-			foreach($newValues as $fieldName=>$value) {
1865
+			foreach ($newValues as $fieldName=>$value) {
1866 1866
 				$query->set($fieldName, $query->createNamedParameter($value));
1867 1867
 			}
1868 1868
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
 
1913 1913
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1914 1914
 
1915
-		if(!$row) {
1915
+		if (!$row) {
1916 1916
 			return null;
1917 1917
 		}
1918 1918
 
@@ -1920,8 +1920,8 @@  discard block
 block discarded – undo
1920 1920
 				'uri'          => $row['uri'],
1921 1921
 				'calendardata' => $row['calendardata'],
1922 1922
 				'lastmodified' => $row['lastmodified'],
1923
-				'etag'         => '"' . $row['etag'] . '"',
1924
-				'size'         => (int)$row['size'],
1923
+				'etag'         => '"'.$row['etag'].'"',
1924
+				'size'         => (int) $row['size'],
1925 1925
 		];
1926 1926
 	}
1927 1927
 
@@ -1944,13 +1944,13 @@  discard block
 block discarded – undo
1944 1944
 				->execute();
1945 1945
 
1946 1946
 		$result = [];
1947
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1947
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1948 1948
 			$result[] = [
1949 1949
 					'calendardata' => $row['calendardata'],
1950 1950
 					'uri'          => $row['uri'],
1951 1951
 					'lastmodified' => $row['lastmodified'],
1952
-					'etag'         => '"' . $row['etag'] . '"',
1953
-					'size'         => (int)$row['size'],
1952
+					'etag'         => '"'.$row['etag'].'"',
1953
+					'size'         => (int) $row['size'],
1954 1954
 			];
1955 1955
 		}
1956 1956
 
@@ -2042,10 +2042,10 @@  discard block
 block discarded – undo
2042 2042
 		$lastOccurrence = null;
2043 2043
 		$uid = null;
2044 2044
 		$classification = self::CLASSIFICATION_PUBLIC;
2045
-		foreach($vObject->getComponents() as $component) {
2046
-			if ($component->name!=='VTIMEZONE') {
2045
+		foreach ($vObject->getComponents() as $component) {
2046
+			if ($component->name !== 'VTIMEZONE') {
2047 2047
 				$componentType = $component->name;
2048
-				$uid = (string)$component->UID;
2048
+				$uid = (string) $component->UID;
2049 2049
 				break;
2050 2050
 			}
2051 2051
 		}
@@ -2070,13 +2070,13 @@  discard block
 block discarded – undo
2070 2070
 					$lastOccurrence = $firstOccurrence;
2071 2071
 				}
2072 2072
 			} else {
2073
-				$it = new EventIterator($vObject, (string)$component->UID);
2073
+				$it = new EventIterator($vObject, (string) $component->UID);
2074 2074
 				$maxDate = new \DateTime(self::MAX_DATE);
2075 2075
 				if ($it->isInfinite()) {
2076 2076
 					$lastOccurrence = $maxDate->getTimestamp();
2077 2077
 				} else {
2078 2078
 					$end = $it->getDtEnd();
2079
-					while($it->valid() && $end < $maxDate) {
2079
+					while ($it->valid() && $end < $maxDate) {
2080 2080
 						$end = $it->getDtEnd();
2081 2081
 						$it->next();
2082 2082
 
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
 			->execute();
2296 2296
 
2297 2297
 		$ids = $result->fetchAll();
2298
-		foreach($ids as $id) {
2298
+		foreach ($ids as $id) {
2299 2299
 			$this->deleteCalendar($id['id']);
2300 2300
 		}
2301 2301
 	}
@@ -2342,10 +2342,10 @@  discard block
 block discarded – undo
2342 2342
 		$result->closeCursor();
2343 2343
 
2344 2344
 		if (!isset($objectIds['id'])) {
2345
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2345
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
2346 2346
 		}
2347 2347
 
2348
-		return (int)$objectIds['id'];
2348
+		return (int) $objectIds['id'];
2349 2349
 	}
2350 2350
 
2351 2351
 	private function convertPrincipal($principalUri, $toV2) {
@@ -2360,8 +2360,8 @@  discard block
 block discarded – undo
2360 2360
 	}
2361 2361
 
2362 2362
 	private function addOwnerPrincipal(&$calendarInfo) {
2363
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2364
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2363
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
2364
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
2365 2365
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
2366 2366
 			$uri = $calendarInfo[$ownerPrincipalKey];
2367 2367
 		} else {
Please login to merge, or discard this patch.
Indentation   +2300 added lines, -2300 removed lines patch added patch discarded remove patch
@@ -73,2305 +73,2305 @@
 block discarded – undo
73 73
  */
74 74
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
75 75
 
76
-	const PERSONAL_CALENDAR_URI = 'personal';
77
-	const PERSONAL_CALENDAR_NAME = 'Personal';
78
-
79
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
80
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
81
-
82
-	/**
83
-	 * We need to specify a max date, because we need to stop *somewhere*
84
-	 *
85
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
86
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
87
-	 * in 2038-01-19 to avoid problems when the date is converted
88
-	 * to a unix timestamp.
89
-	 */
90
-	const MAX_DATE = '2038-01-01';
91
-
92
-	const ACCESS_PUBLIC = 4;
93
-	const CLASSIFICATION_PUBLIC = 0;
94
-	const CLASSIFICATION_PRIVATE = 1;
95
-	const CLASSIFICATION_CONFIDENTIAL = 2;
96
-
97
-	/**
98
-	 * List of CalDAV properties, and how they map to database field names
99
-	 * Add your own properties by simply adding on to this array.
100
-	 *
101
-	 * Note that only string-based properties are supported here.
102
-	 *
103
-	 * @var array
104
-	 */
105
-	public $propertyMap = [
106
-		'{DAV:}displayname'                          => 'displayname',
107
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
108
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
109
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
110
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
111
-	];
112
-
113
-	/**
114
-	 * List of subscription properties, and how they map to database field names.
115
-	 *
116
-	 * @var array
117
-	 */
118
-	public $subscriptionPropertyMap = [
119
-		'{DAV:}displayname'                                           => 'displayname',
120
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
121
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
122
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
123
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
124
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
125
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
126
-	];
127
-
128
-	/** @var array properties to index */
129
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
130
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
131
-		'ORGANIZER'];
132
-
133
-	/** @var array parameters to index */
134
-	public static $indexParameters = [
135
-		'ATTENDEE' => ['CN'],
136
-		'ORGANIZER' => ['CN'],
137
-	];
138
-
139
-	/**
140
-	 * @var string[] Map of uid => display name
141
-	 */
142
-	protected $userDisplayNames;
143
-
144
-	/** @var IDBConnection */
145
-	private $db;
146
-
147
-	/** @var Backend */
148
-	private $sharingBackend;
149
-
150
-	/** @var Principal */
151
-	private $principalBackend;
152
-
153
-	/** @var IUserManager */
154
-	private $userManager;
155
-
156
-	/** @var ISecureRandom */
157
-	private $random;
158
-
159
-	/** @var ILogger */
160
-	private $logger;
161
-
162
-	/** @var EventDispatcherInterface */
163
-	private $dispatcher;
164
-
165
-	/** @var bool */
166
-	private $legacyEndpoint;
167
-
168
-	/** @var string */
169
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
170
-
171
-	/**
172
-	 * CalDavBackend constructor.
173
-	 *
174
-	 * @param IDBConnection $db
175
-	 * @param Principal $principalBackend
176
-	 * @param IUserManager $userManager
177
-	 * @param IGroupManager $groupManager
178
-	 * @param ISecureRandom $random
179
-	 * @param ILogger $logger
180
-	 * @param EventDispatcherInterface $dispatcher
181
-	 * @param bool $legacyEndpoint
182
-	 */
183
-	public function __construct(IDBConnection $db,
184
-								Principal $principalBackend,
185
-								IUserManager $userManager,
186
-								IGroupManager $groupManager,
187
-								ISecureRandom $random,
188
-								ILogger $logger,
189
-								EventDispatcherInterface $dispatcher,
190
-								$legacyEndpoint = false) {
191
-		$this->db = $db;
192
-		$this->principalBackend = $principalBackend;
193
-		$this->userManager = $userManager;
194
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
195
-		$this->random = $random;
196
-		$this->logger = $logger;
197
-		$this->dispatcher = $dispatcher;
198
-		$this->legacyEndpoint = $legacyEndpoint;
199
-	}
200
-
201
-	/**
202
-	 * Return the number of calendars for a principal
203
-	 *
204
-	 * By default this excludes the automatically generated birthday calendar
205
-	 *
206
-	 * @param $principalUri
207
-	 * @param bool $excludeBirthday
208
-	 * @return int
209
-	 */
210
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
211
-		$principalUri = $this->convertPrincipal($principalUri, true);
212
-		$query = $this->db->getQueryBuilder();
213
-		$query->select($query->createFunction('COUNT(*)'))
214
-			->from('calendars')
215
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
216
-
217
-		if ($excludeBirthday) {
218
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
219
-		}
220
-
221
-		return (int)$query->execute()->fetchColumn();
222
-	}
223
-
224
-	/**
225
-	 * Returns a list of calendars for a principal.
226
-	 *
227
-	 * Every project is an array with the following keys:
228
-	 *  * id, a unique id that will be used by other functions to modify the
229
-	 *    calendar. This can be the same as the uri or a database key.
230
-	 *  * uri, which the basename of the uri with which the calendar is
231
-	 *    accessed.
232
-	 *  * principaluri. The owner of the calendar. Almost always the same as
233
-	 *    principalUri passed to this method.
234
-	 *
235
-	 * Furthermore it can contain webdav properties in clark notation. A very
236
-	 * common one is '{DAV:}displayname'.
237
-	 *
238
-	 * Many clients also require:
239
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
240
-	 * For this property, you can just return an instance of
241
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
242
-	 *
243
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
244
-	 * ACL will automatically be put in read-only mode.
245
-	 *
246
-	 * @param string $principalUri
247
-	 * @return array
248
-	 */
249
-	function getCalendarsForUser($principalUri) {
250
-		$principalUriOriginal = $principalUri;
251
-		$principalUri = $this->convertPrincipal($principalUri, true);
252
-		$fields = array_values($this->propertyMap);
253
-		$fields[] = 'id';
254
-		$fields[] = 'uri';
255
-		$fields[] = 'synctoken';
256
-		$fields[] = 'components';
257
-		$fields[] = 'principaluri';
258
-		$fields[] = 'transparent';
259
-
260
-		// Making fields a comma-delimited list
261
-		$query = $this->db->getQueryBuilder();
262
-		$query->select($fields)->from('calendars')
263
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
264
-				->orderBy('calendarorder', 'ASC');
265
-		$stmt = $query->execute();
266
-
267
-		$calendars = [];
268
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
-
270
-			$components = [];
271
-			if ($row['components']) {
272
-				$components = explode(',',$row['components']);
273
-			}
274
-
275
-			$calendar = [
276
-				'id' => $row['id'],
277
-				'uri' => $row['uri'],
278
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
279
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
280
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
281
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
282
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
283
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
284
-			];
285
-
286
-			foreach($this->propertyMap as $xmlName=>$dbName) {
287
-				$calendar[$xmlName] = $row[$dbName];
288
-			}
289
-
290
-			$this->addOwnerPrincipal($calendar);
291
-
292
-			if (!isset($calendars[$calendar['id']])) {
293
-				$calendars[$calendar['id']] = $calendar;
294
-			}
295
-		}
296
-
297
-		$stmt->closeCursor();
298
-
299
-		// query for shared calendars
300
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
301
-		$principals = array_map(function($principal) {
302
-			return urldecode($principal);
303
-		}, $principals);
304
-		$principals[]= $principalUri;
305
-
306
-		$fields = array_values($this->propertyMap);
307
-		$fields[] = 'a.id';
308
-		$fields[] = 'a.uri';
309
-		$fields[] = 'a.synctoken';
310
-		$fields[] = 'a.components';
311
-		$fields[] = 'a.principaluri';
312
-		$fields[] = 'a.transparent';
313
-		$fields[] = 's.access';
314
-		$query = $this->db->getQueryBuilder();
315
-		$result = $query->select($fields)
316
-			->from('dav_shares', 's')
317
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
318
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
319
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
320
-			->setParameter('type', 'calendar')
321
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
322
-			->execute();
323
-
324
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
325
-		while($row = $result->fetch()) {
326
-			if ($row['principaluri'] === $principalUri) {
327
-				continue;
328
-			}
329
-
330
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
331
-			if (isset($calendars[$row['id']])) {
332
-				if ($readOnly) {
333
-					// New share can not have more permissions then the old one.
334
-					continue;
335
-				}
336
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
337
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
338
-					// Old share is already read-write, no more permissions can be gained
339
-					continue;
340
-				}
341
-			}
342
-
343
-			list(, $name) = Uri\split($row['principaluri']);
344
-			$uri = $row['uri'] . '_shared_by_' . $name;
345
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
346
-			$components = [];
347
-			if ($row['components']) {
348
-				$components = explode(',',$row['components']);
349
-			}
350
-			$calendar = [
351
-				'id' => $row['id'],
352
-				'uri' => $uri,
353
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
354
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
358
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
-				$readOnlyPropertyName => $readOnly,
360
-			];
361
-
362
-			foreach($this->propertyMap as $xmlName=>$dbName) {
363
-				$calendar[$xmlName] = $row[$dbName];
364
-			}
365
-
366
-			$this->addOwnerPrincipal($calendar);
367
-
368
-			$calendars[$calendar['id']] = $calendar;
369
-		}
370
-		$result->closeCursor();
371
-
372
-		return array_values($calendars);
373
-	}
374
-
375
-	public function getUsersOwnCalendars($principalUri) {
376
-		$principalUri = $this->convertPrincipal($principalUri, true);
377
-		$fields = array_values($this->propertyMap);
378
-		$fields[] = 'id';
379
-		$fields[] = 'uri';
380
-		$fields[] = 'synctoken';
381
-		$fields[] = 'components';
382
-		$fields[] = 'principaluri';
383
-		$fields[] = 'transparent';
384
-		// Making fields a comma-delimited list
385
-		$query = $this->db->getQueryBuilder();
386
-		$query->select($fields)->from('calendars')
387
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
388
-			->orderBy('calendarorder', 'ASC');
389
-		$stmt = $query->execute();
390
-		$calendars = [];
391
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
392
-			$components = [];
393
-			if ($row['components']) {
394
-				$components = explode(',',$row['components']);
395
-			}
396
-			$calendar = [
397
-				'id' => $row['id'],
398
-				'uri' => $row['uri'],
399
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
400
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
401
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
402
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
404
-			];
405
-			foreach($this->propertyMap as $xmlName=>$dbName) {
406
-				$calendar[$xmlName] = $row[$dbName];
407
-			}
408
-
409
-			$this->addOwnerPrincipal($calendar);
410
-
411
-			if (!isset($calendars[$calendar['id']])) {
412
-				$calendars[$calendar['id']] = $calendar;
413
-			}
414
-		}
415
-		$stmt->closeCursor();
416
-		return array_values($calendars);
417
-	}
418
-
419
-
420
-	private function getUserDisplayName($uid) {
421
-		if (!isset($this->userDisplayNames[$uid])) {
422
-			$user = $this->userManager->get($uid);
423
-
424
-			if ($user instanceof IUser) {
425
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
426
-			} else {
427
-				$this->userDisplayNames[$uid] = $uid;
428
-			}
429
-		}
430
-
431
-		return $this->userDisplayNames[$uid];
432
-	}
76
+    const PERSONAL_CALENDAR_URI = 'personal';
77
+    const PERSONAL_CALENDAR_NAME = 'Personal';
78
+
79
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
80
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
81
+
82
+    /**
83
+     * We need to specify a max date, because we need to stop *somewhere*
84
+     *
85
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
86
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
87
+     * in 2038-01-19 to avoid problems when the date is converted
88
+     * to a unix timestamp.
89
+     */
90
+    const MAX_DATE = '2038-01-01';
91
+
92
+    const ACCESS_PUBLIC = 4;
93
+    const CLASSIFICATION_PUBLIC = 0;
94
+    const CLASSIFICATION_PRIVATE = 1;
95
+    const CLASSIFICATION_CONFIDENTIAL = 2;
96
+
97
+    /**
98
+     * List of CalDAV properties, and how they map to database field names
99
+     * Add your own properties by simply adding on to this array.
100
+     *
101
+     * Note that only string-based properties are supported here.
102
+     *
103
+     * @var array
104
+     */
105
+    public $propertyMap = [
106
+        '{DAV:}displayname'                          => 'displayname',
107
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
108
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
109
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
110
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
111
+    ];
112
+
113
+    /**
114
+     * List of subscription properties, and how they map to database field names.
115
+     *
116
+     * @var array
117
+     */
118
+    public $subscriptionPropertyMap = [
119
+        '{DAV:}displayname'                                           => 'displayname',
120
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
121
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
122
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
123
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
124
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
125
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
126
+    ];
127
+
128
+    /** @var array properties to index */
129
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
130
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
131
+        'ORGANIZER'];
132
+
133
+    /** @var array parameters to index */
134
+    public static $indexParameters = [
135
+        'ATTENDEE' => ['CN'],
136
+        'ORGANIZER' => ['CN'],
137
+    ];
138
+
139
+    /**
140
+     * @var string[] Map of uid => display name
141
+     */
142
+    protected $userDisplayNames;
143
+
144
+    /** @var IDBConnection */
145
+    private $db;
146
+
147
+    /** @var Backend */
148
+    private $sharingBackend;
149
+
150
+    /** @var Principal */
151
+    private $principalBackend;
152
+
153
+    /** @var IUserManager */
154
+    private $userManager;
155
+
156
+    /** @var ISecureRandom */
157
+    private $random;
158
+
159
+    /** @var ILogger */
160
+    private $logger;
161
+
162
+    /** @var EventDispatcherInterface */
163
+    private $dispatcher;
164
+
165
+    /** @var bool */
166
+    private $legacyEndpoint;
167
+
168
+    /** @var string */
169
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
170
+
171
+    /**
172
+     * CalDavBackend constructor.
173
+     *
174
+     * @param IDBConnection $db
175
+     * @param Principal $principalBackend
176
+     * @param IUserManager $userManager
177
+     * @param IGroupManager $groupManager
178
+     * @param ISecureRandom $random
179
+     * @param ILogger $logger
180
+     * @param EventDispatcherInterface $dispatcher
181
+     * @param bool $legacyEndpoint
182
+     */
183
+    public function __construct(IDBConnection $db,
184
+                                Principal $principalBackend,
185
+                                IUserManager $userManager,
186
+                                IGroupManager $groupManager,
187
+                                ISecureRandom $random,
188
+                                ILogger $logger,
189
+                                EventDispatcherInterface $dispatcher,
190
+                                $legacyEndpoint = false) {
191
+        $this->db = $db;
192
+        $this->principalBackend = $principalBackend;
193
+        $this->userManager = $userManager;
194
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
195
+        $this->random = $random;
196
+        $this->logger = $logger;
197
+        $this->dispatcher = $dispatcher;
198
+        $this->legacyEndpoint = $legacyEndpoint;
199
+    }
200
+
201
+    /**
202
+     * Return the number of calendars for a principal
203
+     *
204
+     * By default this excludes the automatically generated birthday calendar
205
+     *
206
+     * @param $principalUri
207
+     * @param bool $excludeBirthday
208
+     * @return int
209
+     */
210
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
211
+        $principalUri = $this->convertPrincipal($principalUri, true);
212
+        $query = $this->db->getQueryBuilder();
213
+        $query->select($query->createFunction('COUNT(*)'))
214
+            ->from('calendars')
215
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
216
+
217
+        if ($excludeBirthday) {
218
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
219
+        }
220
+
221
+        return (int)$query->execute()->fetchColumn();
222
+    }
223
+
224
+    /**
225
+     * Returns a list of calendars for a principal.
226
+     *
227
+     * Every project is an array with the following keys:
228
+     *  * id, a unique id that will be used by other functions to modify the
229
+     *    calendar. This can be the same as the uri or a database key.
230
+     *  * uri, which the basename of the uri with which the calendar is
231
+     *    accessed.
232
+     *  * principaluri. The owner of the calendar. Almost always the same as
233
+     *    principalUri passed to this method.
234
+     *
235
+     * Furthermore it can contain webdav properties in clark notation. A very
236
+     * common one is '{DAV:}displayname'.
237
+     *
238
+     * Many clients also require:
239
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
240
+     * For this property, you can just return an instance of
241
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
242
+     *
243
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
244
+     * ACL will automatically be put in read-only mode.
245
+     *
246
+     * @param string $principalUri
247
+     * @return array
248
+     */
249
+    function getCalendarsForUser($principalUri) {
250
+        $principalUriOriginal = $principalUri;
251
+        $principalUri = $this->convertPrincipal($principalUri, true);
252
+        $fields = array_values($this->propertyMap);
253
+        $fields[] = 'id';
254
+        $fields[] = 'uri';
255
+        $fields[] = 'synctoken';
256
+        $fields[] = 'components';
257
+        $fields[] = 'principaluri';
258
+        $fields[] = 'transparent';
259
+
260
+        // Making fields a comma-delimited list
261
+        $query = $this->db->getQueryBuilder();
262
+        $query->select($fields)->from('calendars')
263
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
264
+                ->orderBy('calendarorder', 'ASC');
265
+        $stmt = $query->execute();
266
+
267
+        $calendars = [];
268
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
269
+
270
+            $components = [];
271
+            if ($row['components']) {
272
+                $components = explode(',',$row['components']);
273
+            }
274
+
275
+            $calendar = [
276
+                'id' => $row['id'],
277
+                'uri' => $row['uri'],
278
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
279
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
280
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
281
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
282
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
283
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
284
+            ];
285
+
286
+            foreach($this->propertyMap as $xmlName=>$dbName) {
287
+                $calendar[$xmlName] = $row[$dbName];
288
+            }
289
+
290
+            $this->addOwnerPrincipal($calendar);
291
+
292
+            if (!isset($calendars[$calendar['id']])) {
293
+                $calendars[$calendar['id']] = $calendar;
294
+            }
295
+        }
296
+
297
+        $stmt->closeCursor();
298
+
299
+        // query for shared calendars
300
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
301
+        $principals = array_map(function($principal) {
302
+            return urldecode($principal);
303
+        }, $principals);
304
+        $principals[]= $principalUri;
305
+
306
+        $fields = array_values($this->propertyMap);
307
+        $fields[] = 'a.id';
308
+        $fields[] = 'a.uri';
309
+        $fields[] = 'a.synctoken';
310
+        $fields[] = 'a.components';
311
+        $fields[] = 'a.principaluri';
312
+        $fields[] = 'a.transparent';
313
+        $fields[] = 's.access';
314
+        $query = $this->db->getQueryBuilder();
315
+        $result = $query->select($fields)
316
+            ->from('dav_shares', 's')
317
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
318
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
319
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
320
+            ->setParameter('type', 'calendar')
321
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
322
+            ->execute();
323
+
324
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
325
+        while($row = $result->fetch()) {
326
+            if ($row['principaluri'] === $principalUri) {
327
+                continue;
328
+            }
329
+
330
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
331
+            if (isset($calendars[$row['id']])) {
332
+                if ($readOnly) {
333
+                    // New share can not have more permissions then the old one.
334
+                    continue;
335
+                }
336
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
337
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
338
+                    // Old share is already read-write, no more permissions can be gained
339
+                    continue;
340
+                }
341
+            }
342
+
343
+            list(, $name) = Uri\split($row['principaluri']);
344
+            $uri = $row['uri'] . '_shared_by_' . $name;
345
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
346
+            $components = [];
347
+            if ($row['components']) {
348
+                $components = explode(',',$row['components']);
349
+            }
350
+            $calendar = [
351
+                'id' => $row['id'],
352
+                'uri' => $uri,
353
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
354
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
358
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
+                $readOnlyPropertyName => $readOnly,
360
+            ];
361
+
362
+            foreach($this->propertyMap as $xmlName=>$dbName) {
363
+                $calendar[$xmlName] = $row[$dbName];
364
+            }
365
+
366
+            $this->addOwnerPrincipal($calendar);
367
+
368
+            $calendars[$calendar['id']] = $calendar;
369
+        }
370
+        $result->closeCursor();
371
+
372
+        return array_values($calendars);
373
+    }
374
+
375
+    public function getUsersOwnCalendars($principalUri) {
376
+        $principalUri = $this->convertPrincipal($principalUri, true);
377
+        $fields = array_values($this->propertyMap);
378
+        $fields[] = 'id';
379
+        $fields[] = 'uri';
380
+        $fields[] = 'synctoken';
381
+        $fields[] = 'components';
382
+        $fields[] = 'principaluri';
383
+        $fields[] = 'transparent';
384
+        // Making fields a comma-delimited list
385
+        $query = $this->db->getQueryBuilder();
386
+        $query->select($fields)->from('calendars')
387
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
388
+            ->orderBy('calendarorder', 'ASC');
389
+        $stmt = $query->execute();
390
+        $calendars = [];
391
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
392
+            $components = [];
393
+            if ($row['components']) {
394
+                $components = explode(',',$row['components']);
395
+            }
396
+            $calendar = [
397
+                'id' => $row['id'],
398
+                'uri' => $row['uri'],
399
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
400
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
401
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
402
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
403
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
404
+            ];
405
+            foreach($this->propertyMap as $xmlName=>$dbName) {
406
+                $calendar[$xmlName] = $row[$dbName];
407
+            }
408
+
409
+            $this->addOwnerPrincipal($calendar);
410
+
411
+            if (!isset($calendars[$calendar['id']])) {
412
+                $calendars[$calendar['id']] = $calendar;
413
+            }
414
+        }
415
+        $stmt->closeCursor();
416
+        return array_values($calendars);
417
+    }
418
+
419
+
420
+    private function getUserDisplayName($uid) {
421
+        if (!isset($this->userDisplayNames[$uid])) {
422
+            $user = $this->userManager->get($uid);
423
+
424
+            if ($user instanceof IUser) {
425
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
426
+            } else {
427
+                $this->userDisplayNames[$uid] = $uid;
428
+            }
429
+        }
430
+
431
+        return $this->userDisplayNames[$uid];
432
+    }
433 433
 	
434
-	/**
435
-	 * @return array
436
-	 */
437
-	public function getPublicCalendars() {
438
-		$fields = array_values($this->propertyMap);
439
-		$fields[] = 'a.id';
440
-		$fields[] = 'a.uri';
441
-		$fields[] = 'a.synctoken';
442
-		$fields[] = 'a.components';
443
-		$fields[] = 'a.principaluri';
444
-		$fields[] = 'a.transparent';
445
-		$fields[] = 's.access';
446
-		$fields[] = 's.publicuri';
447
-		$calendars = [];
448
-		$query = $this->db->getQueryBuilder();
449
-		$result = $query->select($fields)
450
-			->from('dav_shares', 's')
451
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
452
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
453
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
454
-			->execute();
455
-
456
-		while($row = $result->fetch()) {
457
-			list(, $name) = Uri\split($row['principaluri']);
458
-			$row['displayname'] = $row['displayname'] . "($name)";
459
-			$components = [];
460
-			if ($row['components']) {
461
-				$components = explode(',',$row['components']);
462
-			}
463
-			$calendar = [
464
-				'id' => $row['id'],
465
-				'uri' => $row['publicuri'],
466
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
467
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
468
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
469
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
470
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
471
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
472
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
473
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
474
-			];
475
-
476
-			foreach($this->propertyMap as $xmlName=>$dbName) {
477
-				$calendar[$xmlName] = $row[$dbName];
478
-			}
479
-
480
-			$this->addOwnerPrincipal($calendar);
481
-
482
-			if (!isset($calendars[$calendar['id']])) {
483
-				$calendars[$calendar['id']] = $calendar;
484
-			}
485
-		}
486
-		$result->closeCursor();
487
-
488
-		return array_values($calendars);
489
-	}
490
-
491
-	/**
492
-	 * @param string $uri
493
-	 * @return array
494
-	 * @throws NotFound
495
-	 */
496
-	public function getPublicCalendar($uri) {
497
-		$fields = array_values($this->propertyMap);
498
-		$fields[] = 'a.id';
499
-		$fields[] = 'a.uri';
500
-		$fields[] = 'a.synctoken';
501
-		$fields[] = 'a.components';
502
-		$fields[] = 'a.principaluri';
503
-		$fields[] = 'a.transparent';
504
-		$fields[] = 's.access';
505
-		$fields[] = 's.publicuri';
506
-		$query = $this->db->getQueryBuilder();
507
-		$result = $query->select($fields)
508
-			->from('dav_shares', 's')
509
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
510
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
511
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
512
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
513
-			->execute();
514
-
515
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
516
-
517
-		$result->closeCursor();
518
-
519
-		if ($row === false) {
520
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
521
-		}
522
-
523
-		list(, $name) = Uri\split($row['principaluri']);
524
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
525
-		$components = [];
526
-		if ($row['components']) {
527
-			$components = explode(',',$row['components']);
528
-		}
529
-		$calendar = [
530
-			'id' => $row['id'],
531
-			'uri' => $row['publicuri'],
532
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
533
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
534
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
535
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
536
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
537
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
538
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
539
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
540
-		];
541
-
542
-		foreach($this->propertyMap as $xmlName=>$dbName) {
543
-			$calendar[$xmlName] = $row[$dbName];
544
-		}
545
-
546
-		$this->addOwnerPrincipal($calendar);
547
-
548
-		return $calendar;
549
-
550
-	}
551
-
552
-	/**
553
-	 * @param string $principal
554
-	 * @param string $uri
555
-	 * @return array|null
556
-	 */
557
-	public function getCalendarByUri($principal, $uri) {
558
-		$fields = array_values($this->propertyMap);
559
-		$fields[] = 'id';
560
-		$fields[] = 'uri';
561
-		$fields[] = 'synctoken';
562
-		$fields[] = 'components';
563
-		$fields[] = 'principaluri';
564
-		$fields[] = 'transparent';
565
-
566
-		// Making fields a comma-delimited list
567
-		$query = $this->db->getQueryBuilder();
568
-		$query->select($fields)->from('calendars')
569
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
570
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
571
-			->setMaxResults(1);
572
-		$stmt = $query->execute();
573
-
574
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
575
-		$stmt->closeCursor();
576
-		if ($row === false) {
577
-			return null;
578
-		}
579
-
580
-		$components = [];
581
-		if ($row['components']) {
582
-			$components = explode(',',$row['components']);
583
-		}
584
-
585
-		$calendar = [
586
-			'id' => $row['id'],
587
-			'uri' => $row['uri'],
588
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
589
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
590
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
591
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
592
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
593
-		];
594
-
595
-		foreach($this->propertyMap as $xmlName=>$dbName) {
596
-			$calendar[$xmlName] = $row[$dbName];
597
-		}
598
-
599
-		$this->addOwnerPrincipal($calendar);
600
-
601
-		return $calendar;
602
-	}
603
-
604
-	public function getCalendarById($calendarId) {
605
-		$fields = array_values($this->propertyMap);
606
-		$fields[] = 'id';
607
-		$fields[] = 'uri';
608
-		$fields[] = 'synctoken';
609
-		$fields[] = 'components';
610
-		$fields[] = 'principaluri';
611
-		$fields[] = 'transparent';
612
-
613
-		// Making fields a comma-delimited list
614
-		$query = $this->db->getQueryBuilder();
615
-		$query->select($fields)->from('calendars')
616
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
617
-			->setMaxResults(1);
618
-		$stmt = $query->execute();
619
-
620
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
621
-		$stmt->closeCursor();
622
-		if ($row === false) {
623
-			return null;
624
-		}
625
-
626
-		$components = [];
627
-		if ($row['components']) {
628
-			$components = explode(',',$row['components']);
629
-		}
630
-
631
-		$calendar = [
632
-			'id' => $row['id'],
633
-			'uri' => $row['uri'],
634
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
635
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
636
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
637
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
638
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
639
-		];
640
-
641
-		foreach($this->propertyMap as $xmlName=>$dbName) {
642
-			$calendar[$xmlName] = $row[$dbName];
643
-		}
644
-
645
-		$this->addOwnerPrincipal($calendar);
646
-
647
-		return $calendar;
648
-	}
649
-
650
-	/**
651
-	 * Creates a new calendar for a principal.
652
-	 *
653
-	 * If the creation was a success, an id must be returned that can be used to reference
654
-	 * this calendar in other methods, such as updateCalendar.
655
-	 *
656
-	 * @param string $principalUri
657
-	 * @param string $calendarUri
658
-	 * @param array $properties
659
-	 * @return int
660
-	 * @suppress SqlInjectionChecker
661
-	 */
662
-	function createCalendar($principalUri, $calendarUri, array $properties) {
663
-		$values = [
664
-			'principaluri' => $this->convertPrincipal($principalUri, true),
665
-			'uri'          => $calendarUri,
666
-			'synctoken'    => 1,
667
-			'transparent'  => 0,
668
-			'components'   => 'VEVENT,VTODO',
669
-			'displayname'  => $calendarUri
670
-		];
671
-
672
-		// Default value
673
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
674
-		if (isset($properties[$sccs])) {
675
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
676
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
677
-			}
678
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
679
-		}
680
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
681
-		if (isset($properties[$transp])) {
682
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
683
-		}
684
-
685
-		foreach($this->propertyMap as $xmlName=>$dbName) {
686
-			if (isset($properties[$xmlName])) {
687
-				$values[$dbName] = $properties[$xmlName];
688
-			}
689
-		}
690
-
691
-		$query = $this->db->getQueryBuilder();
692
-		$query->insert('calendars');
693
-		foreach($values as $column => $value) {
694
-			$query->setValue($column, $query->createNamedParameter($value));
695
-		}
696
-		$query->execute();
697
-		$calendarId = $query->getLastInsertId();
698
-
699
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
700
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
701
-			[
702
-				'calendarId' => $calendarId,
703
-				'calendarData' => $this->getCalendarById($calendarId),
704
-		]));
705
-
706
-		return $calendarId;
707
-	}
708
-
709
-	/**
710
-	 * Updates properties for a calendar.
711
-	 *
712
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
713
-	 * To do the actual updates, you must tell this object which properties
714
-	 * you're going to process with the handle() method.
715
-	 *
716
-	 * Calling the handle method is like telling the PropPatch object "I
717
-	 * promise I can handle updating this property".
718
-	 *
719
-	 * Read the PropPatch documentation for more info and examples.
720
-	 *
721
-	 * @param mixed $calendarId
722
-	 * @param PropPatch $propPatch
723
-	 * @return void
724
-	 */
725
-	function updateCalendar($calendarId, PropPatch $propPatch) {
726
-		$supportedProperties = array_keys($this->propertyMap);
727
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
728
-
729
-		/**
730
-		 * @suppress SqlInjectionChecker
731
-		 */
732
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
733
-			$newValues = [];
734
-			foreach ($mutations as $propertyName => $propertyValue) {
735
-
736
-				switch ($propertyName) {
737
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
738
-						$fieldName = 'transparent';
739
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
740
-						break;
741
-					default :
742
-						$fieldName = $this->propertyMap[$propertyName];
743
-						$newValues[$fieldName] = $propertyValue;
744
-						break;
745
-				}
746
-
747
-			}
748
-			$query = $this->db->getQueryBuilder();
749
-			$query->update('calendars');
750
-			foreach ($newValues as $fieldName => $value) {
751
-				$query->set($fieldName, $query->createNamedParameter($value));
752
-			}
753
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
754
-			$query->execute();
755
-
756
-			$this->addChange($calendarId, "", 2);
757
-
758
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
759
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
760
-				[
761
-					'calendarId' => $calendarId,
762
-					'calendarData' => $this->getCalendarById($calendarId),
763
-					'shares' => $this->getShares($calendarId),
764
-					'propertyMutations' => $mutations,
765
-			]));
766
-
767
-			return true;
768
-		});
769
-	}
770
-
771
-	/**
772
-	 * Delete a calendar and all it's objects
773
-	 *
774
-	 * @param mixed $calendarId
775
-	 * @return void
776
-	 */
777
-	function deleteCalendar($calendarId) {
778
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
779
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
780
-			[
781
-				'calendarId' => $calendarId,
782
-				'calendarData' => $this->getCalendarById($calendarId),
783
-				'shares' => $this->getShares($calendarId),
784
-		]));
785
-
786
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
787
-		$stmt->execute([$calendarId]);
788
-
789
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
790
-		$stmt->execute([$calendarId]);
791
-
792
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
793
-		$stmt->execute([$calendarId]);
794
-
795
-		$this->sharingBackend->deleteAllShares($calendarId);
796
-
797
-		$query = $this->db->getQueryBuilder();
798
-		$query->delete($this->dbObjectPropertiesTable)
799
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
800
-			->execute();
801
-	}
802
-
803
-	/**
804
-	 * Delete all of an user's shares
805
-	 *
806
-	 * @param string $principaluri
807
-	 * @return void
808
-	 */
809
-	function deleteAllSharesByUser($principaluri) {
810
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
811
-	}
812
-
813
-	/**
814
-	 * Returns all calendar objects within a calendar.
815
-	 *
816
-	 * Every item contains an array with the following keys:
817
-	 *   * calendardata - The iCalendar-compatible calendar data
818
-	 *   * uri - a unique key which will be used to construct the uri. This can
819
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
820
-	 *     good idea. This is only the basename, or filename, not the full
821
-	 *     path.
822
-	 *   * lastmodified - a timestamp of the last modification time
823
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
824
-	 *   '"abcdef"')
825
-	 *   * size - The size of the calendar objects, in bytes.
826
-	 *   * component - optional, a string containing the type of object, such
827
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
828
-	 *     the Content-Type header.
829
-	 *
830
-	 * Note that the etag is optional, but it's highly encouraged to return for
831
-	 * speed reasons.
832
-	 *
833
-	 * The calendardata is also optional. If it's not returned
834
-	 * 'getCalendarObject' will be called later, which *is* expected to return
835
-	 * calendardata.
836
-	 *
837
-	 * If neither etag or size are specified, the calendardata will be
838
-	 * used/fetched to determine these numbers. If both are specified the
839
-	 * amount of times this is needed is reduced by a great degree.
840
-	 *
841
-	 * @param mixed $calendarId
842
-	 * @return array
843
-	 */
844
-	function getCalendarObjects($calendarId) {
845
-		$query = $this->db->getQueryBuilder();
846
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
847
-			->from('calendarobjects')
848
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
849
-		$stmt = $query->execute();
850
-
851
-		$result = [];
852
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
853
-			$result[] = [
854
-					'id'           => $row['id'],
855
-					'uri'          => $row['uri'],
856
-					'lastmodified' => $row['lastmodified'],
857
-					'etag'         => '"' . $row['etag'] . '"',
858
-					'calendarid'   => $row['calendarid'],
859
-					'size'         => (int)$row['size'],
860
-					'component'    => strtolower($row['componenttype']),
861
-					'classification'=> (int)$row['classification']
862
-			];
863
-		}
864
-
865
-		return $result;
866
-	}
867
-
868
-	/**
869
-	 * Returns information from a single calendar object, based on it's object
870
-	 * uri.
871
-	 *
872
-	 * The object uri is only the basename, or filename and not a full path.
873
-	 *
874
-	 * The returned array must have the same keys as getCalendarObjects. The
875
-	 * 'calendardata' object is required here though, while it's not required
876
-	 * for getCalendarObjects.
877
-	 *
878
-	 * This method must return null if the object did not exist.
879
-	 *
880
-	 * @param mixed $calendarId
881
-	 * @param string $objectUri
882
-	 * @return array|null
883
-	 */
884
-	function getCalendarObject($calendarId, $objectUri) {
885
-
886
-		$query = $this->db->getQueryBuilder();
887
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
888
-				->from('calendarobjects')
889
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
890
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
891
-		$stmt = $query->execute();
892
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
893
-
894
-		if(!$row) return null;
895
-
896
-		return [
897
-				'id'            => $row['id'],
898
-				'uri'           => $row['uri'],
899
-				'lastmodified'  => $row['lastmodified'],
900
-				'etag'          => '"' . $row['etag'] . '"',
901
-				'calendarid'    => $row['calendarid'],
902
-				'size'          => (int)$row['size'],
903
-				'calendardata'  => $this->readBlob($row['calendardata']),
904
-				'component'     => strtolower($row['componenttype']),
905
-				'classification'=> (int)$row['classification']
906
-		];
907
-	}
908
-
909
-	/**
910
-	 * Returns a list of calendar objects.
911
-	 *
912
-	 * This method should work identical to getCalendarObject, but instead
913
-	 * return all the calendar objects in the list as an array.
914
-	 *
915
-	 * If the backend supports this, it may allow for some speed-ups.
916
-	 *
917
-	 * @param mixed $calendarId
918
-	 * @param string[] $uris
919
-	 * @return array
920
-	 */
921
-	function getMultipleCalendarObjects($calendarId, array $uris) {
922
-		if (empty($uris)) {
923
-			return [];
924
-		}
925
-
926
-		$chunks = array_chunk($uris, 100);
927
-		$objects = [];
928
-
929
-		$query = $this->db->getQueryBuilder();
930
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
931
-			->from('calendarobjects')
932
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
933
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
934
-
935
-		foreach ($chunks as $uris) {
936
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
937
-			$result = $query->execute();
938
-
939
-			while ($row = $result->fetch()) {
940
-				$objects[] = [
941
-					'id'           => $row['id'],
942
-					'uri'          => $row['uri'],
943
-					'lastmodified' => $row['lastmodified'],
944
-					'etag'         => '"' . $row['etag'] . '"',
945
-					'calendarid'   => $row['calendarid'],
946
-					'size'         => (int)$row['size'],
947
-					'calendardata' => $this->readBlob($row['calendardata']),
948
-					'component'    => strtolower($row['componenttype']),
949
-					'classification' => (int)$row['classification']
950
-				];
951
-			}
952
-			$result->closeCursor();
953
-		}
954
-		return $objects;
955
-	}
956
-
957
-	/**
958
-	 * Creates a new calendar object.
959
-	 *
960
-	 * The object uri is only the basename, or filename and not a full path.
961
-	 *
962
-	 * It is possible return an etag from this function, which will be used in
963
-	 * the response to this PUT request. Note that the ETag must be surrounded
964
-	 * by double-quotes.
965
-	 *
966
-	 * However, you should only really return this ETag if you don't mangle the
967
-	 * calendar-data. If the result of a subsequent GET to this object is not
968
-	 * the exact same as this request body, you should omit the ETag.
969
-	 *
970
-	 * @param mixed $calendarId
971
-	 * @param string $objectUri
972
-	 * @param string $calendarData
973
-	 * @return string
974
-	 */
975
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
976
-		$extraData = $this->getDenormalizedData($calendarData);
977
-
978
-		$q = $this->db->getQueryBuilder();
979
-		$q->select($q->createFunction('COUNT(*)'))
980
-			->from('calendarobjects')
981
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
982
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
983
-
984
-		$result = $q->execute();
985
-		$count = (int) $result->fetchColumn();
986
-		$result->closeCursor();
987
-
988
-		if ($count !== 0) {
989
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
990
-		}
991
-
992
-		$query = $this->db->getQueryBuilder();
993
-		$query->insert('calendarobjects')
994
-			->values([
995
-				'calendarid' => $query->createNamedParameter($calendarId),
996
-				'uri' => $query->createNamedParameter($objectUri),
997
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
998
-				'lastmodified' => $query->createNamedParameter(time()),
999
-				'etag' => $query->createNamedParameter($extraData['etag']),
1000
-				'size' => $query->createNamedParameter($extraData['size']),
1001
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1002
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1003
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1004
-				'classification' => $query->createNamedParameter($extraData['classification']),
1005
-				'uid' => $query->createNamedParameter($extraData['uid']),
1006
-			])
1007
-			->execute();
1008
-
1009
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1010
-
1011
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1012
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1013
-			[
1014
-				'calendarId' => $calendarId,
1015
-				'calendarData' => $this->getCalendarById($calendarId),
1016
-				'shares' => $this->getShares($calendarId),
1017
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1018
-			]
1019
-		));
1020
-		$this->addChange($calendarId, $objectUri, 1);
1021
-
1022
-		return '"' . $extraData['etag'] . '"';
1023
-	}
1024
-
1025
-	/**
1026
-	 * Updates an existing calendarobject, based on it's uri.
1027
-	 *
1028
-	 * The object uri is only the basename, or filename and not a full path.
1029
-	 *
1030
-	 * It is possible return an etag from this function, which will be used in
1031
-	 * the response to this PUT request. Note that the ETag must be surrounded
1032
-	 * by double-quotes.
1033
-	 *
1034
-	 * However, you should only really return this ETag if you don't mangle the
1035
-	 * calendar-data. If the result of a subsequent GET to this object is not
1036
-	 * the exact same as this request body, you should omit the ETag.
1037
-	 *
1038
-	 * @param mixed $calendarId
1039
-	 * @param string $objectUri
1040
-	 * @param string $calendarData
1041
-	 * @return string
1042
-	 */
1043
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1044
-		$extraData = $this->getDenormalizedData($calendarData);
1045
-
1046
-		$query = $this->db->getQueryBuilder();
1047
-		$query->update('calendarobjects')
1048
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1049
-				->set('lastmodified', $query->createNamedParameter(time()))
1050
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1051
-				->set('size', $query->createNamedParameter($extraData['size']))
1052
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1053
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1054
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1055
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1056
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1057
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1058
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1059
-			->execute();
1060
-
1061
-		$this->updateProperties($calendarId, $objectUri, $calendarData);
1062
-
1063
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1064
-		if (is_array($data)) {
1065
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1066
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1067
-				[
1068
-					'calendarId' => $calendarId,
1069
-					'calendarData' => $this->getCalendarById($calendarId),
1070
-					'shares' => $this->getShares($calendarId),
1071
-					'objectData' => $data,
1072
-				]
1073
-			));
1074
-		}
1075
-		$this->addChange($calendarId, $objectUri, 2);
1076
-
1077
-		return '"' . $extraData['etag'] . '"';
1078
-	}
1079
-
1080
-	/**
1081
-	 * @param int $calendarObjectId
1082
-	 * @param int $classification
1083
-	 */
1084
-	public function setClassification($calendarObjectId, $classification) {
1085
-		if (!in_array($classification, [
1086
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1087
-		])) {
1088
-			throw new \InvalidArgumentException();
1089
-		}
1090
-		$query = $this->db->getQueryBuilder();
1091
-		$query->update('calendarobjects')
1092
-			->set('classification', $query->createNamedParameter($classification))
1093
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1094
-			->execute();
1095
-	}
1096
-
1097
-	/**
1098
-	 * Deletes an existing calendar object.
1099
-	 *
1100
-	 * The object uri is only the basename, or filename and not a full path.
1101
-	 *
1102
-	 * @param mixed $calendarId
1103
-	 * @param string $objectUri
1104
-	 * @return void
1105
-	 */
1106
-	function deleteCalendarObject($calendarId, $objectUri) {
1107
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1108
-		if (is_array($data)) {
1109
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1110
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1111
-				[
1112
-					'calendarId' => $calendarId,
1113
-					'calendarData' => $this->getCalendarById($calendarId),
1114
-					'shares' => $this->getShares($calendarId),
1115
-					'objectData' => $data,
1116
-				]
1117
-			));
1118
-		}
1119
-
1120
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1121
-		$stmt->execute([$calendarId, $objectUri]);
1122
-
1123
-		$this->purgeProperties($calendarId, $data['id']);
1124
-
1125
-		$this->addChange($calendarId, $objectUri, 3);
1126
-	}
1127
-
1128
-	/**
1129
-	 * Performs a calendar-query on the contents of this calendar.
1130
-	 *
1131
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1132
-	 * calendar-query it is possible for a client to request a specific set of
1133
-	 * object, based on contents of iCalendar properties, date-ranges and
1134
-	 * iCalendar component types (VTODO, VEVENT).
1135
-	 *
1136
-	 * This method should just return a list of (relative) urls that match this
1137
-	 * query.
1138
-	 *
1139
-	 * The list of filters are specified as an array. The exact array is
1140
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1141
-	 *
1142
-	 * Note that it is extremely likely that getCalendarObject for every path
1143
-	 * returned from this method will be called almost immediately after. You
1144
-	 * may want to anticipate this to speed up these requests.
1145
-	 *
1146
-	 * This method provides a default implementation, which parses *all* the
1147
-	 * iCalendar objects in the specified calendar.
1148
-	 *
1149
-	 * This default may well be good enough for personal use, and calendars
1150
-	 * that aren't very large. But if you anticipate high usage, big calendars
1151
-	 * or high loads, you are strongly advised to optimize certain paths.
1152
-	 *
1153
-	 * The best way to do so is override this method and to optimize
1154
-	 * specifically for 'common filters'.
1155
-	 *
1156
-	 * Requests that are extremely common are:
1157
-	 *   * requests for just VEVENTS
1158
-	 *   * requests for just VTODO
1159
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1160
-	 *
1161
-	 * ..and combinations of these requests. It may not be worth it to try to
1162
-	 * handle every possible situation and just rely on the (relatively
1163
-	 * easy to use) CalendarQueryValidator to handle the rest.
1164
-	 *
1165
-	 * Note that especially time-range-filters may be difficult to parse. A
1166
-	 * time-range filter specified on a VEVENT must for instance also handle
1167
-	 * recurrence rules correctly.
1168
-	 * A good example of how to interprete all these filters can also simply
1169
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1170
-	 * as possible, so it gives you a good idea on what type of stuff you need
1171
-	 * to think of.
1172
-	 *
1173
-	 * @param mixed $calendarId
1174
-	 * @param array $filters
1175
-	 * @return array
1176
-	 */
1177
-	function calendarQuery($calendarId, array $filters) {
1178
-		$componentType = null;
1179
-		$requirePostFilter = true;
1180
-		$timeRange = null;
1181
-
1182
-		// if no filters were specified, we don't need to filter after a query
1183
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1184
-			$requirePostFilter = false;
1185
-		}
1186
-
1187
-		// Figuring out if there's a component filter
1188
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1189
-			$componentType = $filters['comp-filters'][0]['name'];
1190
-
1191
-			// Checking if we need post-filters
1192
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1193
-				$requirePostFilter = false;
1194
-			}
1195
-			// There was a time-range filter
1196
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1197
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1198
-
1199
-				// If start time OR the end time is not specified, we can do a
1200
-				// 100% accurate mysql query.
1201
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1202
-					$requirePostFilter = false;
1203
-				}
1204
-			}
1205
-
1206
-		}
1207
-		$columns = ['uri'];
1208
-		if ($requirePostFilter) {
1209
-			$columns = ['uri', 'calendardata'];
1210
-		}
1211
-		$query = $this->db->getQueryBuilder();
1212
-		$query->select($columns)
1213
-			->from('calendarobjects')
1214
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1215
-
1216
-		if ($componentType) {
1217
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1218
-		}
1219
-
1220
-		if ($timeRange && $timeRange['start']) {
1221
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1222
-		}
1223
-		if ($timeRange && $timeRange['end']) {
1224
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1225
-		}
1226
-
1227
-		$stmt = $query->execute();
1228
-
1229
-		$result = [];
1230
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1231
-			if ($requirePostFilter) {
1232
-				// validateFilterForObject will parse the calendar data
1233
-				// catch parsing errors
1234
-				try {
1235
-					$matches = $this->validateFilterForObject($row, $filters);
1236
-				} catch(ParseException $ex) {
1237
-					$this->logger->logException($ex, [
1238
-						'app' => 'dav',
1239
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1240
-					]);
1241
-					continue;
1242
-				} catch (InvalidDataException $ex) {
1243
-					$this->logger->logException($ex, [
1244
-						'app' => 'dav',
1245
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1246
-					]);
1247
-					continue;
1248
-				}
1249
-
1250
-				if (!$matches) {
1251
-					continue;
1252
-				}
1253
-			}
1254
-			$result[] = $row['uri'];
1255
-		}
1256
-
1257
-		return $result;
1258
-	}
1259
-
1260
-	/**
1261
-	 * custom Nextcloud search extension for CalDAV
1262
-	 *
1263
-	 * @param string $principalUri
1264
-	 * @param array $filters
1265
-	 * @param integer|null $limit
1266
-	 * @param integer|null $offset
1267
-	 * @return array
1268
-	 */
1269
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1270
-		$calendars = $this->getCalendarsForUser($principalUri);
1271
-		$ownCalendars = [];
1272
-		$sharedCalendars = [];
1273
-
1274
-		$uriMapper = [];
1275
-
1276
-		foreach($calendars as $calendar) {
1277
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1278
-				$ownCalendars[] = $calendar['id'];
1279
-			} else {
1280
-				$sharedCalendars[] = $calendar['id'];
1281
-			}
1282
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1283
-		}
1284
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1285
-			return [];
1286
-		}
1287
-
1288
-		$query = $this->db->getQueryBuilder();
1289
-		// Calendar id expressions
1290
-		$calendarExpressions = [];
1291
-		foreach($ownCalendars as $id) {
1292
-			$calendarExpressions[] = $query->expr()
1293
-				->eq('c.calendarid', $query->createNamedParameter($id));
1294
-		}
1295
-		foreach($sharedCalendars as $id) {
1296
-			$calendarExpressions[] = $query->expr()->andX(
1297
-				$query->expr()->eq('c.calendarid',
1298
-					$query->createNamedParameter($id)),
1299
-				$query->expr()->eq('c.classification',
1300
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1301
-			);
1302
-		}
1303
-
1304
-		if (count($calendarExpressions) === 1) {
1305
-			$calExpr = $calendarExpressions[0];
1306
-		} else {
1307
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1308
-		}
1309
-
1310
-		// Component expressions
1311
-		$compExpressions = [];
1312
-		foreach($filters['comps'] as $comp) {
1313
-			$compExpressions[] = $query->expr()
1314
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1315
-		}
1316
-
1317
-		if (count($compExpressions) === 1) {
1318
-			$compExpr = $compExpressions[0];
1319
-		} else {
1320
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1321
-		}
1322
-
1323
-		if (!isset($filters['props'])) {
1324
-			$filters['props'] = [];
1325
-		}
1326
-		if (!isset($filters['params'])) {
1327
-			$filters['params'] = [];
1328
-		}
1329
-
1330
-		$propParamExpressions = [];
1331
-		foreach($filters['props'] as $prop) {
1332
-			$propParamExpressions[] = $query->expr()->andX(
1333
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1334
-				$query->expr()->isNull('i.parameter')
1335
-			);
1336
-		}
1337
-		foreach($filters['params'] as $param) {
1338
-			$propParamExpressions[] = $query->expr()->andX(
1339
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1340
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1341
-			);
1342
-		}
1343
-
1344
-		if (count($propParamExpressions) === 1) {
1345
-			$propParamExpr = $propParamExpressions[0];
1346
-		} else {
1347
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1348
-		}
1349
-
1350
-		$query->select(['c.calendarid', 'c.uri'])
1351
-			->from($this->dbObjectPropertiesTable, 'i')
1352
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1353
-			->where($calExpr)
1354
-			->andWhere($compExpr)
1355
-			->andWhere($propParamExpr)
1356
-			->andWhere($query->expr()->iLike('i.value',
1357
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1358
-
1359
-		if ($offset) {
1360
-			$query->setFirstResult($offset);
1361
-		}
1362
-		if ($limit) {
1363
-			$query->setMaxResults($limit);
1364
-		}
1365
-
1366
-		$stmt = $query->execute();
1367
-
1368
-		$result = [];
1369
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1370
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1371
-			if (!in_array($path, $result)) {
1372
-				$result[] = $path;
1373
-			}
1374
-		}
1375
-
1376
-		return $result;
1377
-	}
1378
-
1379
-	/**
1380
-	 * used for Nextcloud's calendar API
1381
-	 *
1382
-	 * @param array $calendarInfo
1383
-	 * @param string $pattern
1384
-	 * @param array $searchProperties
1385
-	 * @param array $options
1386
-	 * @param integer|null $limit
1387
-	 * @param integer|null $offset
1388
-	 *
1389
-	 * @return array
1390
-	 */
1391
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1392
-						   array $options, $limit, $offset) {
1393
-		$outerQuery = $this->db->getQueryBuilder();
1394
-		$innerQuery = $this->db->getQueryBuilder();
1395
-
1396
-		$innerQuery->selectDistinct('op.objectid')
1397
-			->from($this->dbObjectPropertiesTable, 'op')
1398
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1399
-				$outerQuery->createNamedParameter($calendarInfo['id'])));
1400
-
1401
-		// only return public items for shared calendars for now
1402
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1403
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1404
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1405
-		}
1406
-
1407
-		$or = $innerQuery->expr()->orX();
1408
-		foreach($searchProperties as $searchProperty) {
1409
-			$or->add($innerQuery->expr()->eq('op.name',
1410
-				$outerQuery->createNamedParameter($searchProperty)));
1411
-		}
1412
-		$innerQuery->andWhere($or);
1413
-
1414
-		if ($pattern !== '') {
1415
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1416
-				$outerQuery->createNamedParameter('%' .
1417
-					$this->db->escapeLikeParameter($pattern) . '%')));
1418
-		}
1419
-
1420
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1421
-			->from('calendarobjects', 'c');
1422
-
1423
-		if (isset($options['timerange'])) {
1424
-			if (isset($options['timerange']['start'])) {
1425
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1426
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1427
-
1428
-			}
1429
-			if (isset($options['timerange']['end'])) {
1430
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1431
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1432
-			}
1433
-		}
1434
-
1435
-		if (isset($options['types'])) {
1436
-			$or = $outerQuery->expr()->orX();
1437
-			foreach($options['types'] as $type) {
1438
-				$or->add($outerQuery->expr()->eq('componenttype',
1439
-					$outerQuery->createNamedParameter($type)));
1440
-			}
1441
-			$outerQuery->andWhere($or);
1442
-		}
1443
-
1444
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1445
-			$outerQuery->createFunction($innerQuery->getSQL())));
1446
-
1447
-		if ($offset) {
1448
-			$outerQuery->setFirstResult($offset);
1449
-		}
1450
-		if ($limit) {
1451
-			$outerQuery->setMaxResults($limit);
1452
-		}
1453
-
1454
-		$result = $outerQuery->execute();
1455
-		$calendarObjects = $result->fetchAll();
1456
-
1457
-		return array_map(function($o) {
1458
-			$calendarData = Reader::read($o['calendardata']);
1459
-			$comps = $calendarData->getComponents();
1460
-			$objects = [];
1461
-			$timezones = [];
1462
-			foreach($comps as $comp) {
1463
-				if ($comp instanceof VTimeZone) {
1464
-					$timezones[] = $comp;
1465
-				} else {
1466
-					$objects[] = $comp;
1467
-				}
1468
-			}
1469
-
1470
-			return [
1471
-				'id' => $o['id'],
1472
-				'type' => $o['componenttype'],
1473
-				'uid' => $o['uid'],
1474
-				'uri' => $o['uri'],
1475
-				'objects' => array_map(function($c) {
1476
-					return $this->transformSearchData($c);
1477
-				}, $objects),
1478
-				'timezones' => array_map(function($c) {
1479
-					return $this->transformSearchData($c);
1480
-				}, $timezones),
1481
-			];
1482
-		}, $calendarObjects);
1483
-	}
1484
-
1485
-	/**
1486
-	 * @param Component $comp
1487
-	 * @return array
1488
-	 */
1489
-	private function transformSearchData(Component $comp) {
1490
-		$data = [];
1491
-		/** @var Component[] $subComponents */
1492
-		$subComponents = $comp->getComponents();
1493
-		/** @var Property[] $properties */
1494
-		$properties = array_filter($comp->children(), function($c) {
1495
-			return $c instanceof Property;
1496
-		});
1497
-		$validationRules = $comp->getValidationRules();
1498
-
1499
-		foreach($subComponents as $subComponent) {
1500
-			$name = $subComponent->name;
1501
-			if (!isset($data[$name])) {
1502
-				$data[$name] = [];
1503
-			}
1504
-			$data[$name][] = $this->transformSearchData($subComponent);
1505
-		}
1506
-
1507
-		foreach($properties as $property) {
1508
-			$name = $property->name;
1509
-			if (!isset($validationRules[$name])) {
1510
-				$validationRules[$name] = '*';
1511
-			}
1512
-
1513
-			$rule = $validationRules[$property->name];
1514
-			if ($rule === '+' || $rule === '*') { // multiple
1515
-				if (!isset($data[$name])) {
1516
-					$data[$name] = [];
1517
-				}
1518
-
1519
-				$data[$name][] = $this->transformSearchProperty($property);
1520
-			} else { // once
1521
-				$data[$name] = $this->transformSearchProperty($property);
1522
-			}
1523
-		}
1524
-
1525
-		return $data;
1526
-	}
1527
-
1528
-	/**
1529
-	 * @param Property $prop
1530
-	 * @return array
1531
-	 */
1532
-	private function transformSearchProperty(Property $prop) {
1533
-		// No need to check Date, as it extends DateTime
1534
-		if ($prop instanceof Property\ICalendar\DateTime) {
1535
-			$value = $prop->getDateTime();
1536
-		} else {
1537
-			$value = $prop->getValue();
1538
-		}
1539
-
1540
-		return [
1541
-			$value,
1542
-			$prop->parameters()
1543
-		];
1544
-	}
1545
-
1546
-	/**
1547
-	 * Searches through all of a users calendars and calendar objects to find
1548
-	 * an object with a specific UID.
1549
-	 *
1550
-	 * This method should return the path to this object, relative to the
1551
-	 * calendar home, so this path usually only contains two parts:
1552
-	 *
1553
-	 * calendarpath/objectpath.ics
1554
-	 *
1555
-	 * If the uid is not found, return null.
1556
-	 *
1557
-	 * This method should only consider * objects that the principal owns, so
1558
-	 * any calendars owned by other principals that also appear in this
1559
-	 * collection should be ignored.
1560
-	 *
1561
-	 * @param string $principalUri
1562
-	 * @param string $uid
1563
-	 * @return string|null
1564
-	 */
1565
-	function getCalendarObjectByUID($principalUri, $uid) {
1566
-
1567
-		$query = $this->db->getQueryBuilder();
1568
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1569
-			->from('calendarobjects', 'co')
1570
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1571
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1572
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1573
-
1574
-		$stmt = $query->execute();
1575
-
1576
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1577
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1578
-		}
1579
-
1580
-		return null;
1581
-	}
1582
-
1583
-	/**
1584
-	 * The getChanges method returns all the changes that have happened, since
1585
-	 * the specified syncToken in the specified calendar.
1586
-	 *
1587
-	 * This function should return an array, such as the following:
1588
-	 *
1589
-	 * [
1590
-	 *   'syncToken' => 'The current synctoken',
1591
-	 *   'added'   => [
1592
-	 *      'new.txt',
1593
-	 *   ],
1594
-	 *   'modified'   => [
1595
-	 *      'modified.txt',
1596
-	 *   ],
1597
-	 *   'deleted' => [
1598
-	 *      'foo.php.bak',
1599
-	 *      'old.txt'
1600
-	 *   ]
1601
-	 * );
1602
-	 *
1603
-	 * The returned syncToken property should reflect the *current* syncToken
1604
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1605
-	 * property This is * needed here too, to ensure the operation is atomic.
1606
-	 *
1607
-	 * If the $syncToken argument is specified as null, this is an initial
1608
-	 * sync, and all members should be reported.
1609
-	 *
1610
-	 * The modified property is an array of nodenames that have changed since
1611
-	 * the last token.
1612
-	 *
1613
-	 * The deleted property is an array with nodenames, that have been deleted
1614
-	 * from collection.
1615
-	 *
1616
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1617
-	 * 1, you only have to report changes that happened only directly in
1618
-	 * immediate descendants. If it's 2, it should also include changes from
1619
-	 * the nodes below the child collections. (grandchildren)
1620
-	 *
1621
-	 * The $limit argument allows a client to specify how many results should
1622
-	 * be returned at most. If the limit is not specified, it should be treated
1623
-	 * as infinite.
1624
-	 *
1625
-	 * If the limit (infinite or not) is higher than you're willing to return,
1626
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1627
-	 *
1628
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1629
-	 * return null.
1630
-	 *
1631
-	 * The limit is 'suggestive'. You are free to ignore it.
1632
-	 *
1633
-	 * @param string $calendarId
1634
-	 * @param string $syncToken
1635
-	 * @param int $syncLevel
1636
-	 * @param int $limit
1637
-	 * @return array
1638
-	 */
1639
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1640
-		// Current synctoken
1641
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1642
-		$stmt->execute([ $calendarId ]);
1643
-		$currentToken = $stmt->fetchColumn(0);
1644
-
1645
-		if (is_null($currentToken)) {
1646
-			return null;
1647
-		}
1648
-
1649
-		$result = [
1650
-			'syncToken' => $currentToken,
1651
-			'added'     => [],
1652
-			'modified'  => [],
1653
-			'deleted'   => [],
1654
-		];
1655
-
1656
-		if ($syncToken) {
1657
-
1658
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1659
-			if ($limit>0) {
1660
-				$query.= " LIMIT " . (int)$limit;
1661
-			}
1662
-
1663
-			// Fetching all changes
1664
-			$stmt = $this->db->prepare($query);
1665
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1666
-
1667
-			$changes = [];
1668
-
1669
-			// This loop ensures that any duplicates are overwritten, only the
1670
-			// last change on a node is relevant.
1671
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1672
-
1673
-				$changes[$row['uri']] = $row['operation'];
1674
-
1675
-			}
1676
-
1677
-			foreach($changes as $uri => $operation) {
1678
-
1679
-				switch($operation) {
1680
-					case 1 :
1681
-						$result['added'][] = $uri;
1682
-						break;
1683
-					case 2 :
1684
-						$result['modified'][] = $uri;
1685
-						break;
1686
-					case 3 :
1687
-						$result['deleted'][] = $uri;
1688
-						break;
1689
-				}
1690
-
1691
-			}
1692
-		} else {
1693
-			// No synctoken supplied, this is the initial sync.
1694
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1695
-			$stmt = $this->db->prepare($query);
1696
-			$stmt->execute([$calendarId]);
1697
-
1698
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1699
-		}
1700
-		return $result;
1701
-
1702
-	}
1703
-
1704
-	/**
1705
-	 * Returns a list of subscriptions for a principal.
1706
-	 *
1707
-	 * Every subscription is an array with the following keys:
1708
-	 *  * id, a unique id that will be used by other functions to modify the
1709
-	 *    subscription. This can be the same as the uri or a database key.
1710
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1711
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1712
-	 *    principalUri passed to this method.
1713
-	 *
1714
-	 * Furthermore, all the subscription info must be returned too:
1715
-	 *
1716
-	 * 1. {DAV:}displayname
1717
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1718
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1719
-	 *    should not be stripped).
1720
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1721
-	 *    should not be stripped).
1722
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1723
-	 *    attachments should not be stripped).
1724
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1725
-	 *     Sabre\DAV\Property\Href).
1726
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1727
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1728
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1729
-	 *    (should just be an instance of
1730
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1731
-	 *    default components).
1732
-	 *
1733
-	 * @param string $principalUri
1734
-	 * @return array
1735
-	 */
1736
-	function getSubscriptionsForUser($principalUri) {
1737
-		$fields = array_values($this->subscriptionPropertyMap);
1738
-		$fields[] = 'id';
1739
-		$fields[] = 'uri';
1740
-		$fields[] = 'source';
1741
-		$fields[] = 'principaluri';
1742
-		$fields[] = 'lastmodified';
1743
-
1744
-		$query = $this->db->getQueryBuilder();
1745
-		$query->select($fields)
1746
-			->from('calendarsubscriptions')
1747
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1748
-			->orderBy('calendarorder', 'asc');
1749
-		$stmt =$query->execute();
1750
-
1751
-		$subscriptions = [];
1752
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1753
-
1754
-			$subscription = [
1755
-				'id'           => $row['id'],
1756
-				'uri'          => $row['uri'],
1757
-				'principaluri' => $row['principaluri'],
1758
-				'source'       => $row['source'],
1759
-				'lastmodified' => $row['lastmodified'],
1760
-
1761
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1762
-			];
1763
-
1764
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1765
-				if (!is_null($row[$dbName])) {
1766
-					$subscription[$xmlName] = $row[$dbName];
1767
-				}
1768
-			}
1769
-
1770
-			$subscriptions[] = $subscription;
1771
-
1772
-		}
1773
-
1774
-		return $subscriptions;
1775
-	}
1776
-
1777
-	/**
1778
-	 * Creates a new subscription for a principal.
1779
-	 *
1780
-	 * If the creation was a success, an id must be returned that can be used to reference
1781
-	 * this subscription in other methods, such as updateSubscription.
1782
-	 *
1783
-	 * @param string $principalUri
1784
-	 * @param string $uri
1785
-	 * @param array $properties
1786
-	 * @return mixed
1787
-	 */
1788
-	function createSubscription($principalUri, $uri, array $properties) {
1789
-
1790
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1791
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1792
-		}
1793
-
1794
-		$values = [
1795
-			'principaluri' => $principalUri,
1796
-			'uri'          => $uri,
1797
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1798
-			'lastmodified' => time(),
1799
-		];
1800
-
1801
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1802
-
1803
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1804
-			if (array_key_exists($xmlName, $properties)) {
1805
-					$values[$dbName] = $properties[$xmlName];
1806
-					if (in_array($dbName, $propertiesBoolean)) {
1807
-						$values[$dbName] = true;
1808
-				}
1809
-			}
1810
-		}
1811
-
1812
-		$valuesToInsert = array();
1813
-
1814
-		$query = $this->db->getQueryBuilder();
1815
-
1816
-		foreach (array_keys($values) as $name) {
1817
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1818
-		}
1819
-
1820
-		$query->insert('calendarsubscriptions')
1821
-			->values($valuesToInsert)
1822
-			->execute();
1823
-
1824
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1825
-	}
1826
-
1827
-	/**
1828
-	 * Updates a subscription
1829
-	 *
1830
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1831
-	 * To do the actual updates, you must tell this object which properties
1832
-	 * you're going to process with the handle() method.
1833
-	 *
1834
-	 * Calling the handle method is like telling the PropPatch object "I
1835
-	 * promise I can handle updating this property".
1836
-	 *
1837
-	 * Read the PropPatch documentation for more info and examples.
1838
-	 *
1839
-	 * @param mixed $subscriptionId
1840
-	 * @param PropPatch $propPatch
1841
-	 * @return void
1842
-	 */
1843
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1844
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1845
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1846
-
1847
-		/**
1848
-		 * @suppress SqlInjectionChecker
1849
-		 */
1850
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1851
-
1852
-			$newValues = [];
1853
-
1854
-			foreach($mutations as $propertyName=>$propertyValue) {
1855
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1856
-					$newValues['source'] = $propertyValue->getHref();
1857
-				} else {
1858
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1859
-					$newValues[$fieldName] = $propertyValue;
1860
-				}
1861
-			}
1862
-
1863
-			$query = $this->db->getQueryBuilder();
1864
-			$query->update('calendarsubscriptions')
1865
-				->set('lastmodified', $query->createNamedParameter(time()));
1866
-			foreach($newValues as $fieldName=>$value) {
1867
-				$query->set($fieldName, $query->createNamedParameter($value));
1868
-			}
1869
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1870
-				->execute();
1871
-
1872
-			return true;
1873
-
1874
-		});
1875
-	}
1876
-
1877
-	/**
1878
-	 * Deletes a subscription.
1879
-	 *
1880
-	 * @param mixed $subscriptionId
1881
-	 * @return void
1882
-	 */
1883
-	function deleteSubscription($subscriptionId) {
1884
-		$query = $this->db->getQueryBuilder();
1885
-		$query->delete('calendarsubscriptions')
1886
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1887
-			->execute();
1888
-	}
1889
-
1890
-	/**
1891
-	 * Returns a single scheduling object for the inbox collection.
1892
-	 *
1893
-	 * The returned array should contain the following elements:
1894
-	 *   * uri - A unique basename for the object. This will be used to
1895
-	 *           construct a full uri.
1896
-	 *   * calendardata - The iCalendar object
1897
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1898
-	 *                    timestamp, or a PHP DateTime object.
1899
-	 *   * etag - A unique token that must change if the object changed.
1900
-	 *   * size - The size of the object, in bytes.
1901
-	 *
1902
-	 * @param string $principalUri
1903
-	 * @param string $objectUri
1904
-	 * @return array
1905
-	 */
1906
-	function getSchedulingObject($principalUri, $objectUri) {
1907
-		$query = $this->db->getQueryBuilder();
1908
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1909
-			->from('schedulingobjects')
1910
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1911
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1912
-			->execute();
1913
-
1914
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1915
-
1916
-		if(!$row) {
1917
-			return null;
1918
-		}
1919
-
1920
-		return [
1921
-				'uri'          => $row['uri'],
1922
-				'calendardata' => $row['calendardata'],
1923
-				'lastmodified' => $row['lastmodified'],
1924
-				'etag'         => '"' . $row['etag'] . '"',
1925
-				'size'         => (int)$row['size'],
1926
-		];
1927
-	}
1928
-
1929
-	/**
1930
-	 * Returns all scheduling objects for the inbox collection.
1931
-	 *
1932
-	 * These objects should be returned as an array. Every item in the array
1933
-	 * should follow the same structure as returned from getSchedulingObject.
1934
-	 *
1935
-	 * The main difference is that 'calendardata' is optional.
1936
-	 *
1937
-	 * @param string $principalUri
1938
-	 * @return array
1939
-	 */
1940
-	function getSchedulingObjects($principalUri) {
1941
-		$query = $this->db->getQueryBuilder();
1942
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1943
-				->from('schedulingobjects')
1944
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1945
-				->execute();
1946
-
1947
-		$result = [];
1948
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1949
-			$result[] = [
1950
-					'calendardata' => $row['calendardata'],
1951
-					'uri'          => $row['uri'],
1952
-					'lastmodified' => $row['lastmodified'],
1953
-					'etag'         => '"' . $row['etag'] . '"',
1954
-					'size'         => (int)$row['size'],
1955
-			];
1956
-		}
1957
-
1958
-		return $result;
1959
-	}
1960
-
1961
-	/**
1962
-	 * Deletes a scheduling object from the inbox collection.
1963
-	 *
1964
-	 * @param string $principalUri
1965
-	 * @param string $objectUri
1966
-	 * @return void
1967
-	 */
1968
-	function deleteSchedulingObject($principalUri, $objectUri) {
1969
-		$query = $this->db->getQueryBuilder();
1970
-		$query->delete('schedulingobjects')
1971
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1972
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1973
-				->execute();
1974
-	}
1975
-
1976
-	/**
1977
-	 * Creates a new scheduling object. This should land in a users' inbox.
1978
-	 *
1979
-	 * @param string $principalUri
1980
-	 * @param string $objectUri
1981
-	 * @param string $objectData
1982
-	 * @return void
1983
-	 */
1984
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1985
-		$query = $this->db->getQueryBuilder();
1986
-		$query->insert('schedulingobjects')
1987
-			->values([
1988
-				'principaluri' => $query->createNamedParameter($principalUri),
1989
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
1990
-				'uri' => $query->createNamedParameter($objectUri),
1991
-				'lastmodified' => $query->createNamedParameter(time()),
1992
-				'etag' => $query->createNamedParameter(md5($objectData)),
1993
-				'size' => $query->createNamedParameter(strlen($objectData))
1994
-			])
1995
-			->execute();
1996
-	}
1997
-
1998
-	/**
1999
-	 * Adds a change record to the calendarchanges table.
2000
-	 *
2001
-	 * @param mixed $calendarId
2002
-	 * @param string $objectUri
2003
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2004
-	 * @return void
2005
-	 */
2006
-	protected function addChange($calendarId, $objectUri, $operation) {
2007
-
2008
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2009
-		$stmt->execute([
2010
-			$objectUri,
2011
-			$calendarId,
2012
-			$operation,
2013
-			$calendarId
2014
-		]);
2015
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2016
-		$stmt->execute([
2017
-			$calendarId
2018
-		]);
2019
-
2020
-	}
2021
-
2022
-	/**
2023
-	 * Parses some information from calendar objects, used for optimized
2024
-	 * calendar-queries.
2025
-	 *
2026
-	 * Returns an array with the following keys:
2027
-	 *   * etag - An md5 checksum of the object without the quotes.
2028
-	 *   * size - Size of the object in bytes
2029
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2030
-	 *   * firstOccurence
2031
-	 *   * lastOccurence
2032
-	 *   * uid - value of the UID property
2033
-	 *
2034
-	 * @param string $calendarData
2035
-	 * @return array
2036
-	 */
2037
-	public function getDenormalizedData($calendarData) {
2038
-
2039
-		$vObject = Reader::read($calendarData);
2040
-		$componentType = null;
2041
-		$component = null;
2042
-		$firstOccurrence = null;
2043
-		$lastOccurrence = null;
2044
-		$uid = null;
2045
-		$classification = self::CLASSIFICATION_PUBLIC;
2046
-		foreach($vObject->getComponents() as $component) {
2047
-			if ($component->name!=='VTIMEZONE') {
2048
-				$componentType = $component->name;
2049
-				$uid = (string)$component->UID;
2050
-				break;
2051
-			}
2052
-		}
2053
-		if (!$componentType) {
2054
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2055
-		}
2056
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2057
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2058
-			// Finding the last occurrence is a bit harder
2059
-			if (!isset($component->RRULE)) {
2060
-				if (isset($component->DTEND)) {
2061
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2062
-				} elseif (isset($component->DURATION)) {
2063
-					$endDate = clone $component->DTSTART->getDateTime();
2064
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2065
-					$lastOccurrence = $endDate->getTimeStamp();
2066
-				} elseif (!$component->DTSTART->hasTime()) {
2067
-					$endDate = clone $component->DTSTART->getDateTime();
2068
-					$endDate->modify('+1 day');
2069
-					$lastOccurrence = $endDate->getTimeStamp();
2070
-				} else {
2071
-					$lastOccurrence = $firstOccurrence;
2072
-				}
2073
-			} else {
2074
-				$it = new EventIterator($vObject, (string)$component->UID);
2075
-				$maxDate = new \DateTime(self::MAX_DATE);
2076
-				if ($it->isInfinite()) {
2077
-					$lastOccurrence = $maxDate->getTimestamp();
2078
-				} else {
2079
-					$end = $it->getDtEnd();
2080
-					while($it->valid() && $end < $maxDate) {
2081
-						$end = $it->getDtEnd();
2082
-						$it->next();
2083
-
2084
-					}
2085
-					$lastOccurrence = $end->getTimestamp();
2086
-				}
2087
-
2088
-			}
2089
-		}
2090
-
2091
-		if ($component->CLASS) {
2092
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2093
-			switch ($component->CLASS->getValue()) {
2094
-				case 'PUBLIC':
2095
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2096
-					break;
2097
-				case 'CONFIDENTIAL':
2098
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2099
-					break;
2100
-			}
2101
-		}
2102
-		return [
2103
-			'etag' => md5($calendarData),
2104
-			'size' => strlen($calendarData),
2105
-			'componentType' => $componentType,
2106
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2107
-			'lastOccurence'  => $lastOccurrence,
2108
-			'uid' => $uid,
2109
-			'classification' => $classification
2110
-		];
2111
-
2112
-	}
2113
-
2114
-	private function readBlob($cardData) {
2115
-		if (is_resource($cardData)) {
2116
-			return stream_get_contents($cardData);
2117
-		}
2118
-
2119
-		return $cardData;
2120
-	}
2121
-
2122
-	/**
2123
-	 * @param IShareable $shareable
2124
-	 * @param array $add
2125
-	 * @param array $remove
2126
-	 */
2127
-	public function updateShares($shareable, $add, $remove) {
2128
-		$calendarId = $shareable->getResourceId();
2129
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2130
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2131
-			[
2132
-				'calendarId' => $calendarId,
2133
-				'calendarData' => $this->getCalendarById($calendarId),
2134
-				'shares' => $this->getShares($calendarId),
2135
-				'add' => $add,
2136
-				'remove' => $remove,
2137
-			]));
2138
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
2139
-	}
2140
-
2141
-	/**
2142
-	 * @param int $resourceId
2143
-	 * @return array
2144
-	 */
2145
-	public function getShares($resourceId) {
2146
-		return $this->sharingBackend->getShares($resourceId);
2147
-	}
2148
-
2149
-	/**
2150
-	 * @param boolean $value
2151
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2152
-	 * @return string|null
2153
-	 */
2154
-	public function setPublishStatus($value, $calendar) {
2155
-
2156
-		$calendarId = $calendar->getResourceId();
2157
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2158
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2159
-			[
2160
-				'calendarId' => $calendarId,
2161
-				'calendarData' => $this->getCalendarById($calendarId),
2162
-				'public' => $value,
2163
-			]));
2164
-
2165
-		$query = $this->db->getQueryBuilder();
2166
-		if ($value) {
2167
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2168
-			$query->insert('dav_shares')
2169
-				->values([
2170
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2171
-					'type' => $query->createNamedParameter('calendar'),
2172
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2173
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2174
-					'publicuri' => $query->createNamedParameter($publicUri)
2175
-				]);
2176
-			$query->execute();
2177
-			return $publicUri;
2178
-		}
2179
-		$query->delete('dav_shares')
2180
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2181
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2182
-		$query->execute();
2183
-		return null;
2184
-	}
2185
-
2186
-	/**
2187
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2188
-	 * @return mixed
2189
-	 */
2190
-	public function getPublishStatus($calendar) {
2191
-		$query = $this->db->getQueryBuilder();
2192
-		$result = $query->select('publicuri')
2193
-			->from('dav_shares')
2194
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2195
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2196
-			->execute();
2197
-
2198
-		$row = $result->fetch();
2199
-		$result->closeCursor();
2200
-		return $row ? reset($row) : false;
2201
-	}
2202
-
2203
-	/**
2204
-	 * @param int $resourceId
2205
-	 * @param array $acl
2206
-	 * @return array
2207
-	 */
2208
-	public function applyShareAcl($resourceId, $acl) {
2209
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2210
-	}
2211
-
2212
-
2213
-
2214
-	/**
2215
-	 * update properties table
2216
-	 *
2217
-	 * @param int $calendarId
2218
-	 * @param string $objectUri
2219
-	 * @param string $calendarData
2220
-	 */
2221
-	public function updateProperties($calendarId, $objectUri, $calendarData) {
2222
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2223
-
2224
-		try {
2225
-			$vCalendar = $this->readCalendarData($calendarData);
2226
-		} catch (\Exception $ex) {
2227
-			return;
2228
-		}
2229
-
2230
-		$this->purgeProperties($calendarId, $objectId);
2231
-
2232
-		$query = $this->db->getQueryBuilder();
2233
-		$query->insert($this->dbObjectPropertiesTable)
2234
-			->values(
2235
-				[
2236
-					'calendarid' => $query->createNamedParameter($calendarId),
2237
-					'objectid' => $query->createNamedParameter($objectId),
2238
-					'name' => $query->createParameter('name'),
2239
-					'parameter' => $query->createParameter('parameter'),
2240
-					'value' => $query->createParameter('value'),
2241
-				]
2242
-			);
2243
-
2244
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2245
-		foreach ($vCalendar->getComponents() as $component) {
2246
-			if (!in_array($component->name, $indexComponents)) {
2247
-				continue;
2248
-			}
2249
-
2250
-			foreach ($component->children() as $property) {
2251
-				if (in_array($property->name, self::$indexProperties)) {
2252
-					$value = $property->getValue();
2253
-					// is this a shitty db?
2254
-					if (!$this->db->supports4ByteText()) {
2255
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2256
-					}
2257
-					$value = mb_substr($value, 0, 254);
2258
-
2259
-					$query->setParameter('name', $property->name);
2260
-					$query->setParameter('parameter', null);
2261
-					$query->setParameter('value', $value);
2262
-					$query->execute();
2263
-				}
2264
-
2265
-				if (array_key_exists($property->name, self::$indexParameters)) {
2266
-					$parameters = $property->parameters();
2267
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2268
-
2269
-					foreach ($parameters as $key => $value) {
2270
-						if (in_array($key, $indexedParametersForProperty)) {
2271
-							// is this a shitty db?
2272
-							if ($this->db->supports4ByteText()) {
2273
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2274
-							}
2275
-							$value = mb_substr($value, 0, 254);
2276
-
2277
-							$query->setParameter('name', $property->name);
2278
-							$query->setParameter('parameter', substr($key, 0, 254));
2279
-							$query->setParameter('value', substr($value, 0, 254));
2280
-							$query->execute();
2281
-						}
2282
-					}
2283
-				}
2284
-			}
2285
-		}
2286
-	}
2287
-
2288
-	/**
2289
-	 * deletes all birthday calendars
2290
-	 */
2291
-	public function deleteAllBirthdayCalendars() {
2292
-		$query = $this->db->getQueryBuilder();
2293
-		$result = $query->select(['id'])->from('calendars')
2294
-			->where($query->expr()->eq('uri',
2295
-				$query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2296
-			->execute();
2297
-
2298
-		$ids = $result->fetchAll();
2299
-		foreach($ids as $id) {
2300
-			$this->deleteCalendar($id['id']);
2301
-		}
2302
-	}
2303
-
2304
-	/**
2305
-	 * read VCalendar data into a VCalendar object
2306
-	 *
2307
-	 * @param string $objectData
2308
-	 * @return VCalendar
2309
-	 */
2310
-	protected function readCalendarData($objectData) {
2311
-		return Reader::read($objectData);
2312
-	}
2313
-
2314
-	/**
2315
-	 * delete all properties from a given calendar object
2316
-	 *
2317
-	 * @param int $calendarId
2318
-	 * @param int $objectId
2319
-	 */
2320
-	protected function purgeProperties($calendarId, $objectId) {
2321
-		$query = $this->db->getQueryBuilder();
2322
-		$query->delete($this->dbObjectPropertiesTable)
2323
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2324
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2325
-		$query->execute();
2326
-	}
2327
-
2328
-	/**
2329
-	 * get ID from a given calendar object
2330
-	 *
2331
-	 * @param int $calendarId
2332
-	 * @param string $uri
2333
-	 * @return int
2334
-	 */
2335
-	protected function getCalendarObjectId($calendarId, $uri) {
2336
-		$query = $this->db->getQueryBuilder();
2337
-		$query->select('id')->from('calendarobjects')
2338
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2339
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2340
-
2341
-		$result = $query->execute();
2342
-		$objectIds = $result->fetch();
2343
-		$result->closeCursor();
2344
-
2345
-		if (!isset($objectIds['id'])) {
2346
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2347
-		}
2348
-
2349
-		return (int)$objectIds['id'];
2350
-	}
2351
-
2352
-	private function convertPrincipal($principalUri, $toV2) {
2353
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2354
-			list(, $name) = Uri\split($principalUri);
2355
-			if ($toV2 === true) {
2356
-				return "principals/users/$name";
2357
-			}
2358
-			return "principals/$name";
2359
-		}
2360
-		return $principalUri;
2361
-	}
2362
-
2363
-	private function addOwnerPrincipal(&$calendarInfo) {
2364
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2365
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2366
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2367
-			$uri = $calendarInfo[$ownerPrincipalKey];
2368
-		} else {
2369
-			$uri = $calendarInfo['principaluri'];
2370
-		}
2371
-
2372
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2373
-		if (isset($principalInformation['{DAV:}displayname'])) {
2374
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2375
-		}
2376
-	}
434
+    /**
435
+     * @return array
436
+     */
437
+    public function getPublicCalendars() {
438
+        $fields = array_values($this->propertyMap);
439
+        $fields[] = 'a.id';
440
+        $fields[] = 'a.uri';
441
+        $fields[] = 'a.synctoken';
442
+        $fields[] = 'a.components';
443
+        $fields[] = 'a.principaluri';
444
+        $fields[] = 'a.transparent';
445
+        $fields[] = 's.access';
446
+        $fields[] = 's.publicuri';
447
+        $calendars = [];
448
+        $query = $this->db->getQueryBuilder();
449
+        $result = $query->select($fields)
450
+            ->from('dav_shares', 's')
451
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
452
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
453
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
454
+            ->execute();
455
+
456
+        while($row = $result->fetch()) {
457
+            list(, $name) = Uri\split($row['principaluri']);
458
+            $row['displayname'] = $row['displayname'] . "($name)";
459
+            $components = [];
460
+            if ($row['components']) {
461
+                $components = explode(',',$row['components']);
462
+            }
463
+            $calendar = [
464
+                'id' => $row['id'],
465
+                'uri' => $row['publicuri'],
466
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
467
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
468
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
469
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
470
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
471
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
472
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
473
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
474
+            ];
475
+
476
+            foreach($this->propertyMap as $xmlName=>$dbName) {
477
+                $calendar[$xmlName] = $row[$dbName];
478
+            }
479
+
480
+            $this->addOwnerPrincipal($calendar);
481
+
482
+            if (!isset($calendars[$calendar['id']])) {
483
+                $calendars[$calendar['id']] = $calendar;
484
+            }
485
+        }
486
+        $result->closeCursor();
487
+
488
+        return array_values($calendars);
489
+    }
490
+
491
+    /**
492
+     * @param string $uri
493
+     * @return array
494
+     * @throws NotFound
495
+     */
496
+    public function getPublicCalendar($uri) {
497
+        $fields = array_values($this->propertyMap);
498
+        $fields[] = 'a.id';
499
+        $fields[] = 'a.uri';
500
+        $fields[] = 'a.synctoken';
501
+        $fields[] = 'a.components';
502
+        $fields[] = 'a.principaluri';
503
+        $fields[] = 'a.transparent';
504
+        $fields[] = 's.access';
505
+        $fields[] = 's.publicuri';
506
+        $query = $this->db->getQueryBuilder();
507
+        $result = $query->select($fields)
508
+            ->from('dav_shares', 's')
509
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
510
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
511
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
512
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
513
+            ->execute();
514
+
515
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
516
+
517
+        $result->closeCursor();
518
+
519
+        if ($row === false) {
520
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
521
+        }
522
+
523
+        list(, $name) = Uri\split($row['principaluri']);
524
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
525
+        $components = [];
526
+        if ($row['components']) {
527
+            $components = explode(',',$row['components']);
528
+        }
529
+        $calendar = [
530
+            'id' => $row['id'],
531
+            'uri' => $row['publicuri'],
532
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
533
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
534
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
535
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
536
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
537
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
538
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
539
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
540
+        ];
541
+
542
+        foreach($this->propertyMap as $xmlName=>$dbName) {
543
+            $calendar[$xmlName] = $row[$dbName];
544
+        }
545
+
546
+        $this->addOwnerPrincipal($calendar);
547
+
548
+        return $calendar;
549
+
550
+    }
551
+
552
+    /**
553
+     * @param string $principal
554
+     * @param string $uri
555
+     * @return array|null
556
+     */
557
+    public function getCalendarByUri($principal, $uri) {
558
+        $fields = array_values($this->propertyMap);
559
+        $fields[] = 'id';
560
+        $fields[] = 'uri';
561
+        $fields[] = 'synctoken';
562
+        $fields[] = 'components';
563
+        $fields[] = 'principaluri';
564
+        $fields[] = 'transparent';
565
+
566
+        // Making fields a comma-delimited list
567
+        $query = $this->db->getQueryBuilder();
568
+        $query->select($fields)->from('calendars')
569
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
570
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
571
+            ->setMaxResults(1);
572
+        $stmt = $query->execute();
573
+
574
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
575
+        $stmt->closeCursor();
576
+        if ($row === false) {
577
+            return null;
578
+        }
579
+
580
+        $components = [];
581
+        if ($row['components']) {
582
+            $components = explode(',',$row['components']);
583
+        }
584
+
585
+        $calendar = [
586
+            'id' => $row['id'],
587
+            'uri' => $row['uri'],
588
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
589
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
590
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
591
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
592
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
593
+        ];
594
+
595
+        foreach($this->propertyMap as $xmlName=>$dbName) {
596
+            $calendar[$xmlName] = $row[$dbName];
597
+        }
598
+
599
+        $this->addOwnerPrincipal($calendar);
600
+
601
+        return $calendar;
602
+    }
603
+
604
+    public function getCalendarById($calendarId) {
605
+        $fields = array_values($this->propertyMap);
606
+        $fields[] = 'id';
607
+        $fields[] = 'uri';
608
+        $fields[] = 'synctoken';
609
+        $fields[] = 'components';
610
+        $fields[] = 'principaluri';
611
+        $fields[] = 'transparent';
612
+
613
+        // Making fields a comma-delimited list
614
+        $query = $this->db->getQueryBuilder();
615
+        $query->select($fields)->from('calendars')
616
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
617
+            ->setMaxResults(1);
618
+        $stmt = $query->execute();
619
+
620
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
621
+        $stmt->closeCursor();
622
+        if ($row === false) {
623
+            return null;
624
+        }
625
+
626
+        $components = [];
627
+        if ($row['components']) {
628
+            $components = explode(',',$row['components']);
629
+        }
630
+
631
+        $calendar = [
632
+            'id' => $row['id'],
633
+            'uri' => $row['uri'],
634
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
635
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
636
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
637
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
638
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
639
+        ];
640
+
641
+        foreach($this->propertyMap as $xmlName=>$dbName) {
642
+            $calendar[$xmlName] = $row[$dbName];
643
+        }
644
+
645
+        $this->addOwnerPrincipal($calendar);
646
+
647
+        return $calendar;
648
+    }
649
+
650
+    /**
651
+     * Creates a new calendar for a principal.
652
+     *
653
+     * If the creation was a success, an id must be returned that can be used to reference
654
+     * this calendar in other methods, such as updateCalendar.
655
+     *
656
+     * @param string $principalUri
657
+     * @param string $calendarUri
658
+     * @param array $properties
659
+     * @return int
660
+     * @suppress SqlInjectionChecker
661
+     */
662
+    function createCalendar($principalUri, $calendarUri, array $properties) {
663
+        $values = [
664
+            'principaluri' => $this->convertPrincipal($principalUri, true),
665
+            'uri'          => $calendarUri,
666
+            'synctoken'    => 1,
667
+            'transparent'  => 0,
668
+            'components'   => 'VEVENT,VTODO',
669
+            'displayname'  => $calendarUri
670
+        ];
671
+
672
+        // Default value
673
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
674
+        if (isset($properties[$sccs])) {
675
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
676
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
677
+            }
678
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
679
+        }
680
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
681
+        if (isset($properties[$transp])) {
682
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
683
+        }
684
+
685
+        foreach($this->propertyMap as $xmlName=>$dbName) {
686
+            if (isset($properties[$xmlName])) {
687
+                $values[$dbName] = $properties[$xmlName];
688
+            }
689
+        }
690
+
691
+        $query = $this->db->getQueryBuilder();
692
+        $query->insert('calendars');
693
+        foreach($values as $column => $value) {
694
+            $query->setValue($column, $query->createNamedParameter($value));
695
+        }
696
+        $query->execute();
697
+        $calendarId = $query->getLastInsertId();
698
+
699
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
700
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
701
+            [
702
+                'calendarId' => $calendarId,
703
+                'calendarData' => $this->getCalendarById($calendarId),
704
+        ]));
705
+
706
+        return $calendarId;
707
+    }
708
+
709
+    /**
710
+     * Updates properties for a calendar.
711
+     *
712
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
713
+     * To do the actual updates, you must tell this object which properties
714
+     * you're going to process with the handle() method.
715
+     *
716
+     * Calling the handle method is like telling the PropPatch object "I
717
+     * promise I can handle updating this property".
718
+     *
719
+     * Read the PropPatch documentation for more info and examples.
720
+     *
721
+     * @param mixed $calendarId
722
+     * @param PropPatch $propPatch
723
+     * @return void
724
+     */
725
+    function updateCalendar($calendarId, PropPatch $propPatch) {
726
+        $supportedProperties = array_keys($this->propertyMap);
727
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
728
+
729
+        /**
730
+         * @suppress SqlInjectionChecker
731
+         */
732
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
733
+            $newValues = [];
734
+            foreach ($mutations as $propertyName => $propertyValue) {
735
+
736
+                switch ($propertyName) {
737
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
738
+                        $fieldName = 'transparent';
739
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
740
+                        break;
741
+                    default :
742
+                        $fieldName = $this->propertyMap[$propertyName];
743
+                        $newValues[$fieldName] = $propertyValue;
744
+                        break;
745
+                }
746
+
747
+            }
748
+            $query = $this->db->getQueryBuilder();
749
+            $query->update('calendars');
750
+            foreach ($newValues as $fieldName => $value) {
751
+                $query->set($fieldName, $query->createNamedParameter($value));
752
+            }
753
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
754
+            $query->execute();
755
+
756
+            $this->addChange($calendarId, "", 2);
757
+
758
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
759
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
760
+                [
761
+                    'calendarId' => $calendarId,
762
+                    'calendarData' => $this->getCalendarById($calendarId),
763
+                    'shares' => $this->getShares($calendarId),
764
+                    'propertyMutations' => $mutations,
765
+            ]));
766
+
767
+            return true;
768
+        });
769
+    }
770
+
771
+    /**
772
+     * Delete a calendar and all it's objects
773
+     *
774
+     * @param mixed $calendarId
775
+     * @return void
776
+     */
777
+    function deleteCalendar($calendarId) {
778
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
779
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
780
+            [
781
+                'calendarId' => $calendarId,
782
+                'calendarData' => $this->getCalendarById($calendarId),
783
+                'shares' => $this->getShares($calendarId),
784
+        ]));
785
+
786
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
787
+        $stmt->execute([$calendarId]);
788
+
789
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
790
+        $stmt->execute([$calendarId]);
791
+
792
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
793
+        $stmt->execute([$calendarId]);
794
+
795
+        $this->sharingBackend->deleteAllShares($calendarId);
796
+
797
+        $query = $this->db->getQueryBuilder();
798
+        $query->delete($this->dbObjectPropertiesTable)
799
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
800
+            ->execute();
801
+    }
802
+
803
+    /**
804
+     * Delete all of an user's shares
805
+     *
806
+     * @param string $principaluri
807
+     * @return void
808
+     */
809
+    function deleteAllSharesByUser($principaluri) {
810
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
811
+    }
812
+
813
+    /**
814
+     * Returns all calendar objects within a calendar.
815
+     *
816
+     * Every item contains an array with the following keys:
817
+     *   * calendardata - The iCalendar-compatible calendar data
818
+     *   * uri - a unique key which will be used to construct the uri. This can
819
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
820
+     *     good idea. This is only the basename, or filename, not the full
821
+     *     path.
822
+     *   * lastmodified - a timestamp of the last modification time
823
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
824
+     *   '"abcdef"')
825
+     *   * size - The size of the calendar objects, in bytes.
826
+     *   * component - optional, a string containing the type of object, such
827
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
828
+     *     the Content-Type header.
829
+     *
830
+     * Note that the etag is optional, but it's highly encouraged to return for
831
+     * speed reasons.
832
+     *
833
+     * The calendardata is also optional. If it's not returned
834
+     * 'getCalendarObject' will be called later, which *is* expected to return
835
+     * calendardata.
836
+     *
837
+     * If neither etag or size are specified, the calendardata will be
838
+     * used/fetched to determine these numbers. If both are specified the
839
+     * amount of times this is needed is reduced by a great degree.
840
+     *
841
+     * @param mixed $calendarId
842
+     * @return array
843
+     */
844
+    function getCalendarObjects($calendarId) {
845
+        $query = $this->db->getQueryBuilder();
846
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
847
+            ->from('calendarobjects')
848
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
849
+        $stmt = $query->execute();
850
+
851
+        $result = [];
852
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
853
+            $result[] = [
854
+                    'id'           => $row['id'],
855
+                    'uri'          => $row['uri'],
856
+                    'lastmodified' => $row['lastmodified'],
857
+                    'etag'         => '"' . $row['etag'] . '"',
858
+                    'calendarid'   => $row['calendarid'],
859
+                    'size'         => (int)$row['size'],
860
+                    'component'    => strtolower($row['componenttype']),
861
+                    'classification'=> (int)$row['classification']
862
+            ];
863
+        }
864
+
865
+        return $result;
866
+    }
867
+
868
+    /**
869
+     * Returns information from a single calendar object, based on it's object
870
+     * uri.
871
+     *
872
+     * The object uri is only the basename, or filename and not a full path.
873
+     *
874
+     * The returned array must have the same keys as getCalendarObjects. The
875
+     * 'calendardata' object is required here though, while it's not required
876
+     * for getCalendarObjects.
877
+     *
878
+     * This method must return null if the object did not exist.
879
+     *
880
+     * @param mixed $calendarId
881
+     * @param string $objectUri
882
+     * @return array|null
883
+     */
884
+    function getCalendarObject($calendarId, $objectUri) {
885
+
886
+        $query = $this->db->getQueryBuilder();
887
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
888
+                ->from('calendarobjects')
889
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
890
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
891
+        $stmt = $query->execute();
892
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
893
+
894
+        if(!$row) return null;
895
+
896
+        return [
897
+                'id'            => $row['id'],
898
+                'uri'           => $row['uri'],
899
+                'lastmodified'  => $row['lastmodified'],
900
+                'etag'          => '"' . $row['etag'] . '"',
901
+                'calendarid'    => $row['calendarid'],
902
+                'size'          => (int)$row['size'],
903
+                'calendardata'  => $this->readBlob($row['calendardata']),
904
+                'component'     => strtolower($row['componenttype']),
905
+                'classification'=> (int)$row['classification']
906
+        ];
907
+    }
908
+
909
+    /**
910
+     * Returns a list of calendar objects.
911
+     *
912
+     * This method should work identical to getCalendarObject, but instead
913
+     * return all the calendar objects in the list as an array.
914
+     *
915
+     * If the backend supports this, it may allow for some speed-ups.
916
+     *
917
+     * @param mixed $calendarId
918
+     * @param string[] $uris
919
+     * @return array
920
+     */
921
+    function getMultipleCalendarObjects($calendarId, array $uris) {
922
+        if (empty($uris)) {
923
+            return [];
924
+        }
925
+
926
+        $chunks = array_chunk($uris, 100);
927
+        $objects = [];
928
+
929
+        $query = $this->db->getQueryBuilder();
930
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
931
+            ->from('calendarobjects')
932
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
933
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
934
+
935
+        foreach ($chunks as $uris) {
936
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
937
+            $result = $query->execute();
938
+
939
+            while ($row = $result->fetch()) {
940
+                $objects[] = [
941
+                    'id'           => $row['id'],
942
+                    'uri'          => $row['uri'],
943
+                    'lastmodified' => $row['lastmodified'],
944
+                    'etag'         => '"' . $row['etag'] . '"',
945
+                    'calendarid'   => $row['calendarid'],
946
+                    'size'         => (int)$row['size'],
947
+                    'calendardata' => $this->readBlob($row['calendardata']),
948
+                    'component'    => strtolower($row['componenttype']),
949
+                    'classification' => (int)$row['classification']
950
+                ];
951
+            }
952
+            $result->closeCursor();
953
+        }
954
+        return $objects;
955
+    }
956
+
957
+    /**
958
+     * Creates a new calendar object.
959
+     *
960
+     * The object uri is only the basename, or filename and not a full path.
961
+     *
962
+     * It is possible return an etag from this function, which will be used in
963
+     * the response to this PUT request. Note that the ETag must be surrounded
964
+     * by double-quotes.
965
+     *
966
+     * However, you should only really return this ETag if you don't mangle the
967
+     * calendar-data. If the result of a subsequent GET to this object is not
968
+     * the exact same as this request body, you should omit the ETag.
969
+     *
970
+     * @param mixed $calendarId
971
+     * @param string $objectUri
972
+     * @param string $calendarData
973
+     * @return string
974
+     */
975
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
976
+        $extraData = $this->getDenormalizedData($calendarData);
977
+
978
+        $q = $this->db->getQueryBuilder();
979
+        $q->select($q->createFunction('COUNT(*)'))
980
+            ->from('calendarobjects')
981
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
982
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])));
983
+
984
+        $result = $q->execute();
985
+        $count = (int) $result->fetchColumn();
986
+        $result->closeCursor();
987
+
988
+        if ($count !== 0) {
989
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
990
+        }
991
+
992
+        $query = $this->db->getQueryBuilder();
993
+        $query->insert('calendarobjects')
994
+            ->values([
995
+                'calendarid' => $query->createNamedParameter($calendarId),
996
+                'uri' => $query->createNamedParameter($objectUri),
997
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
998
+                'lastmodified' => $query->createNamedParameter(time()),
999
+                'etag' => $query->createNamedParameter($extraData['etag']),
1000
+                'size' => $query->createNamedParameter($extraData['size']),
1001
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1002
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1003
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1004
+                'classification' => $query->createNamedParameter($extraData['classification']),
1005
+                'uid' => $query->createNamedParameter($extraData['uid']),
1006
+            ])
1007
+            ->execute();
1008
+
1009
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1010
+
1011
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1012
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1013
+            [
1014
+                'calendarId' => $calendarId,
1015
+                'calendarData' => $this->getCalendarById($calendarId),
1016
+                'shares' => $this->getShares($calendarId),
1017
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1018
+            ]
1019
+        ));
1020
+        $this->addChange($calendarId, $objectUri, 1);
1021
+
1022
+        return '"' . $extraData['etag'] . '"';
1023
+    }
1024
+
1025
+    /**
1026
+     * Updates an existing calendarobject, based on it's uri.
1027
+     *
1028
+     * The object uri is only the basename, or filename and not a full path.
1029
+     *
1030
+     * It is possible return an etag from this function, which will be used in
1031
+     * the response to this PUT request. Note that the ETag must be surrounded
1032
+     * by double-quotes.
1033
+     *
1034
+     * However, you should only really return this ETag if you don't mangle the
1035
+     * calendar-data. If the result of a subsequent GET to this object is not
1036
+     * the exact same as this request body, you should omit the ETag.
1037
+     *
1038
+     * @param mixed $calendarId
1039
+     * @param string $objectUri
1040
+     * @param string $calendarData
1041
+     * @return string
1042
+     */
1043
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
1044
+        $extraData = $this->getDenormalizedData($calendarData);
1045
+
1046
+        $query = $this->db->getQueryBuilder();
1047
+        $query->update('calendarobjects')
1048
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1049
+                ->set('lastmodified', $query->createNamedParameter(time()))
1050
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1051
+                ->set('size', $query->createNamedParameter($extraData['size']))
1052
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1053
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1054
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1055
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1056
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1057
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1058
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1059
+            ->execute();
1060
+
1061
+        $this->updateProperties($calendarId, $objectUri, $calendarData);
1062
+
1063
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1064
+        if (is_array($data)) {
1065
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1066
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1067
+                [
1068
+                    'calendarId' => $calendarId,
1069
+                    'calendarData' => $this->getCalendarById($calendarId),
1070
+                    'shares' => $this->getShares($calendarId),
1071
+                    'objectData' => $data,
1072
+                ]
1073
+            ));
1074
+        }
1075
+        $this->addChange($calendarId, $objectUri, 2);
1076
+
1077
+        return '"' . $extraData['etag'] . '"';
1078
+    }
1079
+
1080
+    /**
1081
+     * @param int $calendarObjectId
1082
+     * @param int $classification
1083
+     */
1084
+    public function setClassification($calendarObjectId, $classification) {
1085
+        if (!in_array($classification, [
1086
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1087
+        ])) {
1088
+            throw new \InvalidArgumentException();
1089
+        }
1090
+        $query = $this->db->getQueryBuilder();
1091
+        $query->update('calendarobjects')
1092
+            ->set('classification', $query->createNamedParameter($classification))
1093
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1094
+            ->execute();
1095
+    }
1096
+
1097
+    /**
1098
+     * Deletes an existing calendar object.
1099
+     *
1100
+     * The object uri is only the basename, or filename and not a full path.
1101
+     *
1102
+     * @param mixed $calendarId
1103
+     * @param string $objectUri
1104
+     * @return void
1105
+     */
1106
+    function deleteCalendarObject($calendarId, $objectUri) {
1107
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1108
+        if (is_array($data)) {
1109
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1110
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1111
+                [
1112
+                    'calendarId' => $calendarId,
1113
+                    'calendarData' => $this->getCalendarById($calendarId),
1114
+                    'shares' => $this->getShares($calendarId),
1115
+                    'objectData' => $data,
1116
+                ]
1117
+            ));
1118
+        }
1119
+
1120
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1121
+        $stmt->execute([$calendarId, $objectUri]);
1122
+
1123
+        $this->purgeProperties($calendarId, $data['id']);
1124
+
1125
+        $this->addChange($calendarId, $objectUri, 3);
1126
+    }
1127
+
1128
+    /**
1129
+     * Performs a calendar-query on the contents of this calendar.
1130
+     *
1131
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1132
+     * calendar-query it is possible for a client to request a specific set of
1133
+     * object, based on contents of iCalendar properties, date-ranges and
1134
+     * iCalendar component types (VTODO, VEVENT).
1135
+     *
1136
+     * This method should just return a list of (relative) urls that match this
1137
+     * query.
1138
+     *
1139
+     * The list of filters are specified as an array. The exact array is
1140
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1141
+     *
1142
+     * Note that it is extremely likely that getCalendarObject for every path
1143
+     * returned from this method will be called almost immediately after. You
1144
+     * may want to anticipate this to speed up these requests.
1145
+     *
1146
+     * This method provides a default implementation, which parses *all* the
1147
+     * iCalendar objects in the specified calendar.
1148
+     *
1149
+     * This default may well be good enough for personal use, and calendars
1150
+     * that aren't very large. But if you anticipate high usage, big calendars
1151
+     * or high loads, you are strongly advised to optimize certain paths.
1152
+     *
1153
+     * The best way to do so is override this method and to optimize
1154
+     * specifically for 'common filters'.
1155
+     *
1156
+     * Requests that are extremely common are:
1157
+     *   * requests for just VEVENTS
1158
+     *   * requests for just VTODO
1159
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1160
+     *
1161
+     * ..and combinations of these requests. It may not be worth it to try to
1162
+     * handle every possible situation and just rely on the (relatively
1163
+     * easy to use) CalendarQueryValidator to handle the rest.
1164
+     *
1165
+     * Note that especially time-range-filters may be difficult to parse. A
1166
+     * time-range filter specified on a VEVENT must for instance also handle
1167
+     * recurrence rules correctly.
1168
+     * A good example of how to interprete all these filters can also simply
1169
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1170
+     * as possible, so it gives you a good idea on what type of stuff you need
1171
+     * to think of.
1172
+     *
1173
+     * @param mixed $calendarId
1174
+     * @param array $filters
1175
+     * @return array
1176
+     */
1177
+    function calendarQuery($calendarId, array $filters) {
1178
+        $componentType = null;
1179
+        $requirePostFilter = true;
1180
+        $timeRange = null;
1181
+
1182
+        // if no filters were specified, we don't need to filter after a query
1183
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1184
+            $requirePostFilter = false;
1185
+        }
1186
+
1187
+        // Figuring out if there's a component filter
1188
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1189
+            $componentType = $filters['comp-filters'][0]['name'];
1190
+
1191
+            // Checking if we need post-filters
1192
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1193
+                $requirePostFilter = false;
1194
+            }
1195
+            // There was a time-range filter
1196
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1197
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1198
+
1199
+                // If start time OR the end time is not specified, we can do a
1200
+                // 100% accurate mysql query.
1201
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1202
+                    $requirePostFilter = false;
1203
+                }
1204
+            }
1205
+
1206
+        }
1207
+        $columns = ['uri'];
1208
+        if ($requirePostFilter) {
1209
+            $columns = ['uri', 'calendardata'];
1210
+        }
1211
+        $query = $this->db->getQueryBuilder();
1212
+        $query->select($columns)
1213
+            ->from('calendarobjects')
1214
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1215
+
1216
+        if ($componentType) {
1217
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1218
+        }
1219
+
1220
+        if ($timeRange && $timeRange['start']) {
1221
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1222
+        }
1223
+        if ($timeRange && $timeRange['end']) {
1224
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1225
+        }
1226
+
1227
+        $stmt = $query->execute();
1228
+
1229
+        $result = [];
1230
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1231
+            if ($requirePostFilter) {
1232
+                // validateFilterForObject will parse the calendar data
1233
+                // catch parsing errors
1234
+                try {
1235
+                    $matches = $this->validateFilterForObject($row, $filters);
1236
+                } catch(ParseException $ex) {
1237
+                    $this->logger->logException($ex, [
1238
+                        'app' => 'dav',
1239
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1240
+                    ]);
1241
+                    continue;
1242
+                } catch (InvalidDataException $ex) {
1243
+                    $this->logger->logException($ex, [
1244
+                        'app' => 'dav',
1245
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1246
+                    ]);
1247
+                    continue;
1248
+                }
1249
+
1250
+                if (!$matches) {
1251
+                    continue;
1252
+                }
1253
+            }
1254
+            $result[] = $row['uri'];
1255
+        }
1256
+
1257
+        return $result;
1258
+    }
1259
+
1260
+    /**
1261
+     * custom Nextcloud search extension for CalDAV
1262
+     *
1263
+     * @param string $principalUri
1264
+     * @param array $filters
1265
+     * @param integer|null $limit
1266
+     * @param integer|null $offset
1267
+     * @return array
1268
+     */
1269
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1270
+        $calendars = $this->getCalendarsForUser($principalUri);
1271
+        $ownCalendars = [];
1272
+        $sharedCalendars = [];
1273
+
1274
+        $uriMapper = [];
1275
+
1276
+        foreach($calendars as $calendar) {
1277
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1278
+                $ownCalendars[] = $calendar['id'];
1279
+            } else {
1280
+                $sharedCalendars[] = $calendar['id'];
1281
+            }
1282
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1283
+        }
1284
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1285
+            return [];
1286
+        }
1287
+
1288
+        $query = $this->db->getQueryBuilder();
1289
+        // Calendar id expressions
1290
+        $calendarExpressions = [];
1291
+        foreach($ownCalendars as $id) {
1292
+            $calendarExpressions[] = $query->expr()
1293
+                ->eq('c.calendarid', $query->createNamedParameter($id));
1294
+        }
1295
+        foreach($sharedCalendars as $id) {
1296
+            $calendarExpressions[] = $query->expr()->andX(
1297
+                $query->expr()->eq('c.calendarid',
1298
+                    $query->createNamedParameter($id)),
1299
+                $query->expr()->eq('c.classification',
1300
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC))
1301
+            );
1302
+        }
1303
+
1304
+        if (count($calendarExpressions) === 1) {
1305
+            $calExpr = $calendarExpressions[0];
1306
+        } else {
1307
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1308
+        }
1309
+
1310
+        // Component expressions
1311
+        $compExpressions = [];
1312
+        foreach($filters['comps'] as $comp) {
1313
+            $compExpressions[] = $query->expr()
1314
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1315
+        }
1316
+
1317
+        if (count($compExpressions) === 1) {
1318
+            $compExpr = $compExpressions[0];
1319
+        } else {
1320
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1321
+        }
1322
+
1323
+        if (!isset($filters['props'])) {
1324
+            $filters['props'] = [];
1325
+        }
1326
+        if (!isset($filters['params'])) {
1327
+            $filters['params'] = [];
1328
+        }
1329
+
1330
+        $propParamExpressions = [];
1331
+        foreach($filters['props'] as $prop) {
1332
+            $propParamExpressions[] = $query->expr()->andX(
1333
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1334
+                $query->expr()->isNull('i.parameter')
1335
+            );
1336
+        }
1337
+        foreach($filters['params'] as $param) {
1338
+            $propParamExpressions[] = $query->expr()->andX(
1339
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1340
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1341
+            );
1342
+        }
1343
+
1344
+        if (count($propParamExpressions) === 1) {
1345
+            $propParamExpr = $propParamExpressions[0];
1346
+        } else {
1347
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1348
+        }
1349
+
1350
+        $query->select(['c.calendarid', 'c.uri'])
1351
+            ->from($this->dbObjectPropertiesTable, 'i')
1352
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1353
+            ->where($calExpr)
1354
+            ->andWhere($compExpr)
1355
+            ->andWhere($propParamExpr)
1356
+            ->andWhere($query->expr()->iLike('i.value',
1357
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1358
+
1359
+        if ($offset) {
1360
+            $query->setFirstResult($offset);
1361
+        }
1362
+        if ($limit) {
1363
+            $query->setMaxResults($limit);
1364
+        }
1365
+
1366
+        $stmt = $query->execute();
1367
+
1368
+        $result = [];
1369
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1370
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1371
+            if (!in_array($path, $result)) {
1372
+                $result[] = $path;
1373
+            }
1374
+        }
1375
+
1376
+        return $result;
1377
+    }
1378
+
1379
+    /**
1380
+     * used for Nextcloud's calendar API
1381
+     *
1382
+     * @param array $calendarInfo
1383
+     * @param string $pattern
1384
+     * @param array $searchProperties
1385
+     * @param array $options
1386
+     * @param integer|null $limit
1387
+     * @param integer|null $offset
1388
+     *
1389
+     * @return array
1390
+     */
1391
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1392
+                            array $options, $limit, $offset) {
1393
+        $outerQuery = $this->db->getQueryBuilder();
1394
+        $innerQuery = $this->db->getQueryBuilder();
1395
+
1396
+        $innerQuery->selectDistinct('op.objectid')
1397
+            ->from($this->dbObjectPropertiesTable, 'op')
1398
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1399
+                $outerQuery->createNamedParameter($calendarInfo['id'])));
1400
+
1401
+        // only return public items for shared calendars for now
1402
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1403
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1404
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1405
+        }
1406
+
1407
+        $or = $innerQuery->expr()->orX();
1408
+        foreach($searchProperties as $searchProperty) {
1409
+            $or->add($innerQuery->expr()->eq('op.name',
1410
+                $outerQuery->createNamedParameter($searchProperty)));
1411
+        }
1412
+        $innerQuery->andWhere($or);
1413
+
1414
+        if ($pattern !== '') {
1415
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1416
+                $outerQuery->createNamedParameter('%' .
1417
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1418
+        }
1419
+
1420
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1421
+            ->from('calendarobjects', 'c');
1422
+
1423
+        if (isset($options['timerange'])) {
1424
+            if (isset($options['timerange']['start'])) {
1425
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1426
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1427
+
1428
+            }
1429
+            if (isset($options['timerange']['end'])) {
1430
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1431
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1432
+            }
1433
+        }
1434
+
1435
+        if (isset($options['types'])) {
1436
+            $or = $outerQuery->expr()->orX();
1437
+            foreach($options['types'] as $type) {
1438
+                $or->add($outerQuery->expr()->eq('componenttype',
1439
+                    $outerQuery->createNamedParameter($type)));
1440
+            }
1441
+            $outerQuery->andWhere($or);
1442
+        }
1443
+
1444
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1445
+            $outerQuery->createFunction($innerQuery->getSQL())));
1446
+
1447
+        if ($offset) {
1448
+            $outerQuery->setFirstResult($offset);
1449
+        }
1450
+        if ($limit) {
1451
+            $outerQuery->setMaxResults($limit);
1452
+        }
1453
+
1454
+        $result = $outerQuery->execute();
1455
+        $calendarObjects = $result->fetchAll();
1456
+
1457
+        return array_map(function($o) {
1458
+            $calendarData = Reader::read($o['calendardata']);
1459
+            $comps = $calendarData->getComponents();
1460
+            $objects = [];
1461
+            $timezones = [];
1462
+            foreach($comps as $comp) {
1463
+                if ($comp instanceof VTimeZone) {
1464
+                    $timezones[] = $comp;
1465
+                } else {
1466
+                    $objects[] = $comp;
1467
+                }
1468
+            }
1469
+
1470
+            return [
1471
+                'id' => $o['id'],
1472
+                'type' => $o['componenttype'],
1473
+                'uid' => $o['uid'],
1474
+                'uri' => $o['uri'],
1475
+                'objects' => array_map(function($c) {
1476
+                    return $this->transformSearchData($c);
1477
+                }, $objects),
1478
+                'timezones' => array_map(function($c) {
1479
+                    return $this->transformSearchData($c);
1480
+                }, $timezones),
1481
+            ];
1482
+        }, $calendarObjects);
1483
+    }
1484
+
1485
+    /**
1486
+     * @param Component $comp
1487
+     * @return array
1488
+     */
1489
+    private function transformSearchData(Component $comp) {
1490
+        $data = [];
1491
+        /** @var Component[] $subComponents */
1492
+        $subComponents = $comp->getComponents();
1493
+        /** @var Property[] $properties */
1494
+        $properties = array_filter($comp->children(), function($c) {
1495
+            return $c instanceof Property;
1496
+        });
1497
+        $validationRules = $comp->getValidationRules();
1498
+
1499
+        foreach($subComponents as $subComponent) {
1500
+            $name = $subComponent->name;
1501
+            if (!isset($data[$name])) {
1502
+                $data[$name] = [];
1503
+            }
1504
+            $data[$name][] = $this->transformSearchData($subComponent);
1505
+        }
1506
+
1507
+        foreach($properties as $property) {
1508
+            $name = $property->name;
1509
+            if (!isset($validationRules[$name])) {
1510
+                $validationRules[$name] = '*';
1511
+            }
1512
+
1513
+            $rule = $validationRules[$property->name];
1514
+            if ($rule === '+' || $rule === '*') { // multiple
1515
+                if (!isset($data[$name])) {
1516
+                    $data[$name] = [];
1517
+                }
1518
+
1519
+                $data[$name][] = $this->transformSearchProperty($property);
1520
+            } else { // once
1521
+                $data[$name] = $this->transformSearchProperty($property);
1522
+            }
1523
+        }
1524
+
1525
+        return $data;
1526
+    }
1527
+
1528
+    /**
1529
+     * @param Property $prop
1530
+     * @return array
1531
+     */
1532
+    private function transformSearchProperty(Property $prop) {
1533
+        // No need to check Date, as it extends DateTime
1534
+        if ($prop instanceof Property\ICalendar\DateTime) {
1535
+            $value = $prop->getDateTime();
1536
+        } else {
1537
+            $value = $prop->getValue();
1538
+        }
1539
+
1540
+        return [
1541
+            $value,
1542
+            $prop->parameters()
1543
+        ];
1544
+    }
1545
+
1546
+    /**
1547
+     * Searches through all of a users calendars and calendar objects to find
1548
+     * an object with a specific UID.
1549
+     *
1550
+     * This method should return the path to this object, relative to the
1551
+     * calendar home, so this path usually only contains two parts:
1552
+     *
1553
+     * calendarpath/objectpath.ics
1554
+     *
1555
+     * If the uid is not found, return null.
1556
+     *
1557
+     * This method should only consider * objects that the principal owns, so
1558
+     * any calendars owned by other principals that also appear in this
1559
+     * collection should be ignored.
1560
+     *
1561
+     * @param string $principalUri
1562
+     * @param string $uid
1563
+     * @return string|null
1564
+     */
1565
+    function getCalendarObjectByUID($principalUri, $uid) {
1566
+
1567
+        $query = $this->db->getQueryBuilder();
1568
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1569
+            ->from('calendarobjects', 'co')
1570
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1571
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1572
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1573
+
1574
+        $stmt = $query->execute();
1575
+
1576
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1577
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1578
+        }
1579
+
1580
+        return null;
1581
+    }
1582
+
1583
+    /**
1584
+     * The getChanges method returns all the changes that have happened, since
1585
+     * the specified syncToken in the specified calendar.
1586
+     *
1587
+     * This function should return an array, such as the following:
1588
+     *
1589
+     * [
1590
+     *   'syncToken' => 'The current synctoken',
1591
+     *   'added'   => [
1592
+     *      'new.txt',
1593
+     *   ],
1594
+     *   'modified'   => [
1595
+     *      'modified.txt',
1596
+     *   ],
1597
+     *   'deleted' => [
1598
+     *      'foo.php.bak',
1599
+     *      'old.txt'
1600
+     *   ]
1601
+     * );
1602
+     *
1603
+     * The returned syncToken property should reflect the *current* syncToken
1604
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1605
+     * property This is * needed here too, to ensure the operation is atomic.
1606
+     *
1607
+     * If the $syncToken argument is specified as null, this is an initial
1608
+     * sync, and all members should be reported.
1609
+     *
1610
+     * The modified property is an array of nodenames that have changed since
1611
+     * the last token.
1612
+     *
1613
+     * The deleted property is an array with nodenames, that have been deleted
1614
+     * from collection.
1615
+     *
1616
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1617
+     * 1, you only have to report changes that happened only directly in
1618
+     * immediate descendants. If it's 2, it should also include changes from
1619
+     * the nodes below the child collections. (grandchildren)
1620
+     *
1621
+     * The $limit argument allows a client to specify how many results should
1622
+     * be returned at most. If the limit is not specified, it should be treated
1623
+     * as infinite.
1624
+     *
1625
+     * If the limit (infinite or not) is higher than you're willing to return,
1626
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1627
+     *
1628
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1629
+     * return null.
1630
+     *
1631
+     * The limit is 'suggestive'. You are free to ignore it.
1632
+     *
1633
+     * @param string $calendarId
1634
+     * @param string $syncToken
1635
+     * @param int $syncLevel
1636
+     * @param int $limit
1637
+     * @return array
1638
+     */
1639
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1640
+        // Current synctoken
1641
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1642
+        $stmt->execute([ $calendarId ]);
1643
+        $currentToken = $stmt->fetchColumn(0);
1644
+
1645
+        if (is_null($currentToken)) {
1646
+            return null;
1647
+        }
1648
+
1649
+        $result = [
1650
+            'syncToken' => $currentToken,
1651
+            'added'     => [],
1652
+            'modified'  => [],
1653
+            'deleted'   => [],
1654
+        ];
1655
+
1656
+        if ($syncToken) {
1657
+
1658
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1659
+            if ($limit>0) {
1660
+                $query.= " LIMIT " . (int)$limit;
1661
+            }
1662
+
1663
+            // Fetching all changes
1664
+            $stmt = $this->db->prepare($query);
1665
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1666
+
1667
+            $changes = [];
1668
+
1669
+            // This loop ensures that any duplicates are overwritten, only the
1670
+            // last change on a node is relevant.
1671
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1672
+
1673
+                $changes[$row['uri']] = $row['operation'];
1674
+
1675
+            }
1676
+
1677
+            foreach($changes as $uri => $operation) {
1678
+
1679
+                switch($operation) {
1680
+                    case 1 :
1681
+                        $result['added'][] = $uri;
1682
+                        break;
1683
+                    case 2 :
1684
+                        $result['modified'][] = $uri;
1685
+                        break;
1686
+                    case 3 :
1687
+                        $result['deleted'][] = $uri;
1688
+                        break;
1689
+                }
1690
+
1691
+            }
1692
+        } else {
1693
+            // No synctoken supplied, this is the initial sync.
1694
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1695
+            $stmt = $this->db->prepare($query);
1696
+            $stmt->execute([$calendarId]);
1697
+
1698
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1699
+        }
1700
+        return $result;
1701
+
1702
+    }
1703
+
1704
+    /**
1705
+     * Returns a list of subscriptions for a principal.
1706
+     *
1707
+     * Every subscription is an array with the following keys:
1708
+     *  * id, a unique id that will be used by other functions to modify the
1709
+     *    subscription. This can be the same as the uri or a database key.
1710
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1711
+     *  * principaluri. The owner of the subscription. Almost always the same as
1712
+     *    principalUri passed to this method.
1713
+     *
1714
+     * Furthermore, all the subscription info must be returned too:
1715
+     *
1716
+     * 1. {DAV:}displayname
1717
+     * 2. {http://apple.com/ns/ical/}refreshrate
1718
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1719
+     *    should not be stripped).
1720
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1721
+     *    should not be stripped).
1722
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1723
+     *    attachments should not be stripped).
1724
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1725
+     *     Sabre\DAV\Property\Href).
1726
+     * 7. {http://apple.com/ns/ical/}calendar-color
1727
+     * 8. {http://apple.com/ns/ical/}calendar-order
1728
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1729
+     *    (should just be an instance of
1730
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1731
+     *    default components).
1732
+     *
1733
+     * @param string $principalUri
1734
+     * @return array
1735
+     */
1736
+    function getSubscriptionsForUser($principalUri) {
1737
+        $fields = array_values($this->subscriptionPropertyMap);
1738
+        $fields[] = 'id';
1739
+        $fields[] = 'uri';
1740
+        $fields[] = 'source';
1741
+        $fields[] = 'principaluri';
1742
+        $fields[] = 'lastmodified';
1743
+
1744
+        $query = $this->db->getQueryBuilder();
1745
+        $query->select($fields)
1746
+            ->from('calendarsubscriptions')
1747
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1748
+            ->orderBy('calendarorder', 'asc');
1749
+        $stmt =$query->execute();
1750
+
1751
+        $subscriptions = [];
1752
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1753
+
1754
+            $subscription = [
1755
+                'id'           => $row['id'],
1756
+                'uri'          => $row['uri'],
1757
+                'principaluri' => $row['principaluri'],
1758
+                'source'       => $row['source'],
1759
+                'lastmodified' => $row['lastmodified'],
1760
+
1761
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1762
+            ];
1763
+
1764
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1765
+                if (!is_null($row[$dbName])) {
1766
+                    $subscription[$xmlName] = $row[$dbName];
1767
+                }
1768
+            }
1769
+
1770
+            $subscriptions[] = $subscription;
1771
+
1772
+        }
1773
+
1774
+        return $subscriptions;
1775
+    }
1776
+
1777
+    /**
1778
+     * Creates a new subscription for a principal.
1779
+     *
1780
+     * If the creation was a success, an id must be returned that can be used to reference
1781
+     * this subscription in other methods, such as updateSubscription.
1782
+     *
1783
+     * @param string $principalUri
1784
+     * @param string $uri
1785
+     * @param array $properties
1786
+     * @return mixed
1787
+     */
1788
+    function createSubscription($principalUri, $uri, array $properties) {
1789
+
1790
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1791
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1792
+        }
1793
+
1794
+        $values = [
1795
+            'principaluri' => $principalUri,
1796
+            'uri'          => $uri,
1797
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1798
+            'lastmodified' => time(),
1799
+        ];
1800
+
1801
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1802
+
1803
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1804
+            if (array_key_exists($xmlName, $properties)) {
1805
+                    $values[$dbName] = $properties[$xmlName];
1806
+                    if (in_array($dbName, $propertiesBoolean)) {
1807
+                        $values[$dbName] = true;
1808
+                }
1809
+            }
1810
+        }
1811
+
1812
+        $valuesToInsert = array();
1813
+
1814
+        $query = $this->db->getQueryBuilder();
1815
+
1816
+        foreach (array_keys($values) as $name) {
1817
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1818
+        }
1819
+
1820
+        $query->insert('calendarsubscriptions')
1821
+            ->values($valuesToInsert)
1822
+            ->execute();
1823
+
1824
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1825
+    }
1826
+
1827
+    /**
1828
+     * Updates a subscription
1829
+     *
1830
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1831
+     * To do the actual updates, you must tell this object which properties
1832
+     * you're going to process with the handle() method.
1833
+     *
1834
+     * Calling the handle method is like telling the PropPatch object "I
1835
+     * promise I can handle updating this property".
1836
+     *
1837
+     * Read the PropPatch documentation for more info and examples.
1838
+     *
1839
+     * @param mixed $subscriptionId
1840
+     * @param PropPatch $propPatch
1841
+     * @return void
1842
+     */
1843
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1844
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1845
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1846
+
1847
+        /**
1848
+         * @suppress SqlInjectionChecker
1849
+         */
1850
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1851
+
1852
+            $newValues = [];
1853
+
1854
+            foreach($mutations as $propertyName=>$propertyValue) {
1855
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1856
+                    $newValues['source'] = $propertyValue->getHref();
1857
+                } else {
1858
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1859
+                    $newValues[$fieldName] = $propertyValue;
1860
+                }
1861
+            }
1862
+
1863
+            $query = $this->db->getQueryBuilder();
1864
+            $query->update('calendarsubscriptions')
1865
+                ->set('lastmodified', $query->createNamedParameter(time()));
1866
+            foreach($newValues as $fieldName=>$value) {
1867
+                $query->set($fieldName, $query->createNamedParameter($value));
1868
+            }
1869
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1870
+                ->execute();
1871
+
1872
+            return true;
1873
+
1874
+        });
1875
+    }
1876
+
1877
+    /**
1878
+     * Deletes a subscription.
1879
+     *
1880
+     * @param mixed $subscriptionId
1881
+     * @return void
1882
+     */
1883
+    function deleteSubscription($subscriptionId) {
1884
+        $query = $this->db->getQueryBuilder();
1885
+        $query->delete('calendarsubscriptions')
1886
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1887
+            ->execute();
1888
+    }
1889
+
1890
+    /**
1891
+     * Returns a single scheduling object for the inbox collection.
1892
+     *
1893
+     * The returned array should contain the following elements:
1894
+     *   * uri - A unique basename for the object. This will be used to
1895
+     *           construct a full uri.
1896
+     *   * calendardata - The iCalendar object
1897
+     *   * lastmodified - The last modification date. Can be an int for a unix
1898
+     *                    timestamp, or a PHP DateTime object.
1899
+     *   * etag - A unique token that must change if the object changed.
1900
+     *   * size - The size of the object, in bytes.
1901
+     *
1902
+     * @param string $principalUri
1903
+     * @param string $objectUri
1904
+     * @return array
1905
+     */
1906
+    function getSchedulingObject($principalUri, $objectUri) {
1907
+        $query = $this->db->getQueryBuilder();
1908
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1909
+            ->from('schedulingobjects')
1910
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1911
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1912
+            ->execute();
1913
+
1914
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1915
+
1916
+        if(!$row) {
1917
+            return null;
1918
+        }
1919
+
1920
+        return [
1921
+                'uri'          => $row['uri'],
1922
+                'calendardata' => $row['calendardata'],
1923
+                'lastmodified' => $row['lastmodified'],
1924
+                'etag'         => '"' . $row['etag'] . '"',
1925
+                'size'         => (int)$row['size'],
1926
+        ];
1927
+    }
1928
+
1929
+    /**
1930
+     * Returns all scheduling objects for the inbox collection.
1931
+     *
1932
+     * These objects should be returned as an array. Every item in the array
1933
+     * should follow the same structure as returned from getSchedulingObject.
1934
+     *
1935
+     * The main difference is that 'calendardata' is optional.
1936
+     *
1937
+     * @param string $principalUri
1938
+     * @return array
1939
+     */
1940
+    function getSchedulingObjects($principalUri) {
1941
+        $query = $this->db->getQueryBuilder();
1942
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1943
+                ->from('schedulingobjects')
1944
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1945
+                ->execute();
1946
+
1947
+        $result = [];
1948
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1949
+            $result[] = [
1950
+                    'calendardata' => $row['calendardata'],
1951
+                    'uri'          => $row['uri'],
1952
+                    'lastmodified' => $row['lastmodified'],
1953
+                    'etag'         => '"' . $row['etag'] . '"',
1954
+                    'size'         => (int)$row['size'],
1955
+            ];
1956
+        }
1957
+
1958
+        return $result;
1959
+    }
1960
+
1961
+    /**
1962
+     * Deletes a scheduling object from the inbox collection.
1963
+     *
1964
+     * @param string $principalUri
1965
+     * @param string $objectUri
1966
+     * @return void
1967
+     */
1968
+    function deleteSchedulingObject($principalUri, $objectUri) {
1969
+        $query = $this->db->getQueryBuilder();
1970
+        $query->delete('schedulingobjects')
1971
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1972
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1973
+                ->execute();
1974
+    }
1975
+
1976
+    /**
1977
+     * Creates a new scheduling object. This should land in a users' inbox.
1978
+     *
1979
+     * @param string $principalUri
1980
+     * @param string $objectUri
1981
+     * @param string $objectData
1982
+     * @return void
1983
+     */
1984
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1985
+        $query = $this->db->getQueryBuilder();
1986
+        $query->insert('schedulingobjects')
1987
+            ->values([
1988
+                'principaluri' => $query->createNamedParameter($principalUri),
1989
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
1990
+                'uri' => $query->createNamedParameter($objectUri),
1991
+                'lastmodified' => $query->createNamedParameter(time()),
1992
+                'etag' => $query->createNamedParameter(md5($objectData)),
1993
+                'size' => $query->createNamedParameter(strlen($objectData))
1994
+            ])
1995
+            ->execute();
1996
+    }
1997
+
1998
+    /**
1999
+     * Adds a change record to the calendarchanges table.
2000
+     *
2001
+     * @param mixed $calendarId
2002
+     * @param string $objectUri
2003
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2004
+     * @return void
2005
+     */
2006
+    protected function addChange($calendarId, $objectUri, $operation) {
2007
+
2008
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
2009
+        $stmt->execute([
2010
+            $objectUri,
2011
+            $calendarId,
2012
+            $operation,
2013
+            $calendarId
2014
+        ]);
2015
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
2016
+        $stmt->execute([
2017
+            $calendarId
2018
+        ]);
2019
+
2020
+    }
2021
+
2022
+    /**
2023
+     * Parses some information from calendar objects, used for optimized
2024
+     * calendar-queries.
2025
+     *
2026
+     * Returns an array with the following keys:
2027
+     *   * etag - An md5 checksum of the object without the quotes.
2028
+     *   * size - Size of the object in bytes
2029
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2030
+     *   * firstOccurence
2031
+     *   * lastOccurence
2032
+     *   * uid - value of the UID property
2033
+     *
2034
+     * @param string $calendarData
2035
+     * @return array
2036
+     */
2037
+    public function getDenormalizedData($calendarData) {
2038
+
2039
+        $vObject = Reader::read($calendarData);
2040
+        $componentType = null;
2041
+        $component = null;
2042
+        $firstOccurrence = null;
2043
+        $lastOccurrence = null;
2044
+        $uid = null;
2045
+        $classification = self::CLASSIFICATION_PUBLIC;
2046
+        foreach($vObject->getComponents() as $component) {
2047
+            if ($component->name!=='VTIMEZONE') {
2048
+                $componentType = $component->name;
2049
+                $uid = (string)$component->UID;
2050
+                break;
2051
+            }
2052
+        }
2053
+        if (!$componentType) {
2054
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2055
+        }
2056
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2057
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2058
+            // Finding the last occurrence is a bit harder
2059
+            if (!isset($component->RRULE)) {
2060
+                if (isset($component->DTEND)) {
2061
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2062
+                } elseif (isset($component->DURATION)) {
2063
+                    $endDate = clone $component->DTSTART->getDateTime();
2064
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2065
+                    $lastOccurrence = $endDate->getTimeStamp();
2066
+                } elseif (!$component->DTSTART->hasTime()) {
2067
+                    $endDate = clone $component->DTSTART->getDateTime();
2068
+                    $endDate->modify('+1 day');
2069
+                    $lastOccurrence = $endDate->getTimeStamp();
2070
+                } else {
2071
+                    $lastOccurrence = $firstOccurrence;
2072
+                }
2073
+            } else {
2074
+                $it = new EventIterator($vObject, (string)$component->UID);
2075
+                $maxDate = new \DateTime(self::MAX_DATE);
2076
+                if ($it->isInfinite()) {
2077
+                    $lastOccurrence = $maxDate->getTimestamp();
2078
+                } else {
2079
+                    $end = $it->getDtEnd();
2080
+                    while($it->valid() && $end < $maxDate) {
2081
+                        $end = $it->getDtEnd();
2082
+                        $it->next();
2083
+
2084
+                    }
2085
+                    $lastOccurrence = $end->getTimestamp();
2086
+                }
2087
+
2088
+            }
2089
+        }
2090
+
2091
+        if ($component->CLASS) {
2092
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2093
+            switch ($component->CLASS->getValue()) {
2094
+                case 'PUBLIC':
2095
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2096
+                    break;
2097
+                case 'CONFIDENTIAL':
2098
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2099
+                    break;
2100
+            }
2101
+        }
2102
+        return [
2103
+            'etag' => md5($calendarData),
2104
+            'size' => strlen($calendarData),
2105
+            'componentType' => $componentType,
2106
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2107
+            'lastOccurence'  => $lastOccurrence,
2108
+            'uid' => $uid,
2109
+            'classification' => $classification
2110
+        ];
2111
+
2112
+    }
2113
+
2114
+    private function readBlob($cardData) {
2115
+        if (is_resource($cardData)) {
2116
+            return stream_get_contents($cardData);
2117
+        }
2118
+
2119
+        return $cardData;
2120
+    }
2121
+
2122
+    /**
2123
+     * @param IShareable $shareable
2124
+     * @param array $add
2125
+     * @param array $remove
2126
+     */
2127
+    public function updateShares($shareable, $add, $remove) {
2128
+        $calendarId = $shareable->getResourceId();
2129
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2130
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2131
+            [
2132
+                'calendarId' => $calendarId,
2133
+                'calendarData' => $this->getCalendarById($calendarId),
2134
+                'shares' => $this->getShares($calendarId),
2135
+                'add' => $add,
2136
+                'remove' => $remove,
2137
+            ]));
2138
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
2139
+    }
2140
+
2141
+    /**
2142
+     * @param int $resourceId
2143
+     * @return array
2144
+     */
2145
+    public function getShares($resourceId) {
2146
+        return $this->sharingBackend->getShares($resourceId);
2147
+    }
2148
+
2149
+    /**
2150
+     * @param boolean $value
2151
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2152
+     * @return string|null
2153
+     */
2154
+    public function setPublishStatus($value, $calendar) {
2155
+
2156
+        $calendarId = $calendar->getResourceId();
2157
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2158
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2159
+            [
2160
+                'calendarId' => $calendarId,
2161
+                'calendarData' => $this->getCalendarById($calendarId),
2162
+                'public' => $value,
2163
+            ]));
2164
+
2165
+        $query = $this->db->getQueryBuilder();
2166
+        if ($value) {
2167
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2168
+            $query->insert('dav_shares')
2169
+                ->values([
2170
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2171
+                    'type' => $query->createNamedParameter('calendar'),
2172
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2173
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2174
+                    'publicuri' => $query->createNamedParameter($publicUri)
2175
+                ]);
2176
+            $query->execute();
2177
+            return $publicUri;
2178
+        }
2179
+        $query->delete('dav_shares')
2180
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2181
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2182
+        $query->execute();
2183
+        return null;
2184
+    }
2185
+
2186
+    /**
2187
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2188
+     * @return mixed
2189
+     */
2190
+    public function getPublishStatus($calendar) {
2191
+        $query = $this->db->getQueryBuilder();
2192
+        $result = $query->select('publicuri')
2193
+            ->from('dav_shares')
2194
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2195
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2196
+            ->execute();
2197
+
2198
+        $row = $result->fetch();
2199
+        $result->closeCursor();
2200
+        return $row ? reset($row) : false;
2201
+    }
2202
+
2203
+    /**
2204
+     * @param int $resourceId
2205
+     * @param array $acl
2206
+     * @return array
2207
+     */
2208
+    public function applyShareAcl($resourceId, $acl) {
2209
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
2210
+    }
2211
+
2212
+
2213
+
2214
+    /**
2215
+     * update properties table
2216
+     *
2217
+     * @param int $calendarId
2218
+     * @param string $objectUri
2219
+     * @param string $calendarData
2220
+     */
2221
+    public function updateProperties($calendarId, $objectUri, $calendarData) {
2222
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri);
2223
+
2224
+        try {
2225
+            $vCalendar = $this->readCalendarData($calendarData);
2226
+        } catch (\Exception $ex) {
2227
+            return;
2228
+        }
2229
+
2230
+        $this->purgeProperties($calendarId, $objectId);
2231
+
2232
+        $query = $this->db->getQueryBuilder();
2233
+        $query->insert($this->dbObjectPropertiesTable)
2234
+            ->values(
2235
+                [
2236
+                    'calendarid' => $query->createNamedParameter($calendarId),
2237
+                    'objectid' => $query->createNamedParameter($objectId),
2238
+                    'name' => $query->createParameter('name'),
2239
+                    'parameter' => $query->createParameter('parameter'),
2240
+                    'value' => $query->createParameter('value'),
2241
+                ]
2242
+            );
2243
+
2244
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2245
+        foreach ($vCalendar->getComponents() as $component) {
2246
+            if (!in_array($component->name, $indexComponents)) {
2247
+                continue;
2248
+            }
2249
+
2250
+            foreach ($component->children() as $property) {
2251
+                if (in_array($property->name, self::$indexProperties)) {
2252
+                    $value = $property->getValue();
2253
+                    // is this a shitty db?
2254
+                    if (!$this->db->supports4ByteText()) {
2255
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2256
+                    }
2257
+                    $value = mb_substr($value, 0, 254);
2258
+
2259
+                    $query->setParameter('name', $property->name);
2260
+                    $query->setParameter('parameter', null);
2261
+                    $query->setParameter('value', $value);
2262
+                    $query->execute();
2263
+                }
2264
+
2265
+                if (array_key_exists($property->name, self::$indexParameters)) {
2266
+                    $parameters = $property->parameters();
2267
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2268
+
2269
+                    foreach ($parameters as $key => $value) {
2270
+                        if (in_array($key, $indexedParametersForProperty)) {
2271
+                            // is this a shitty db?
2272
+                            if ($this->db->supports4ByteText()) {
2273
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2274
+                            }
2275
+                            $value = mb_substr($value, 0, 254);
2276
+
2277
+                            $query->setParameter('name', $property->name);
2278
+                            $query->setParameter('parameter', substr($key, 0, 254));
2279
+                            $query->setParameter('value', substr($value, 0, 254));
2280
+                            $query->execute();
2281
+                        }
2282
+                    }
2283
+                }
2284
+            }
2285
+        }
2286
+    }
2287
+
2288
+    /**
2289
+     * deletes all birthday calendars
2290
+     */
2291
+    public function deleteAllBirthdayCalendars() {
2292
+        $query = $this->db->getQueryBuilder();
2293
+        $result = $query->select(['id'])->from('calendars')
2294
+            ->where($query->expr()->eq('uri',
2295
+                $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2296
+            ->execute();
2297
+
2298
+        $ids = $result->fetchAll();
2299
+        foreach($ids as $id) {
2300
+            $this->deleteCalendar($id['id']);
2301
+        }
2302
+    }
2303
+
2304
+    /**
2305
+     * read VCalendar data into a VCalendar object
2306
+     *
2307
+     * @param string $objectData
2308
+     * @return VCalendar
2309
+     */
2310
+    protected function readCalendarData($objectData) {
2311
+        return Reader::read($objectData);
2312
+    }
2313
+
2314
+    /**
2315
+     * delete all properties from a given calendar object
2316
+     *
2317
+     * @param int $calendarId
2318
+     * @param int $objectId
2319
+     */
2320
+    protected function purgeProperties($calendarId, $objectId) {
2321
+        $query = $this->db->getQueryBuilder();
2322
+        $query->delete($this->dbObjectPropertiesTable)
2323
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2324
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2325
+        $query->execute();
2326
+    }
2327
+
2328
+    /**
2329
+     * get ID from a given calendar object
2330
+     *
2331
+     * @param int $calendarId
2332
+     * @param string $uri
2333
+     * @return int
2334
+     */
2335
+    protected function getCalendarObjectId($calendarId, $uri) {
2336
+        $query = $this->db->getQueryBuilder();
2337
+        $query->select('id')->from('calendarobjects')
2338
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2339
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2340
+
2341
+        $result = $query->execute();
2342
+        $objectIds = $result->fetch();
2343
+        $result->closeCursor();
2344
+
2345
+        if (!isset($objectIds['id'])) {
2346
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2347
+        }
2348
+
2349
+        return (int)$objectIds['id'];
2350
+    }
2351
+
2352
+    private function convertPrincipal($principalUri, $toV2) {
2353
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2354
+            list(, $name) = Uri\split($principalUri);
2355
+            if ($toV2 === true) {
2356
+                return "principals/users/$name";
2357
+            }
2358
+            return "principals/$name";
2359
+        }
2360
+        return $principalUri;
2361
+    }
2362
+
2363
+    private function addOwnerPrincipal(&$calendarInfo) {
2364
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2365
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2366
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2367
+            $uri = $calendarInfo[$ownerPrincipalKey];
2368
+        } else {
2369
+            $uri = $calendarInfo['principaluri'];
2370
+        }
2371
+
2372
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2373
+        if (isset($principalInformation['{DAV:}displayname'])) {
2374
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2375
+        }
2376
+    }
2377 2377
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 2 patches
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -26,58 +26,58 @@
 block discarded – undo
26 26
 
27 27
 class Publisher implements XmlSerializable {
28 28
 
29
-	/**
30
-	 * @var string $publishUrl
31
-	 */
32
-	protected $publishUrl;
29
+    /**
30
+     * @var string $publishUrl
31
+     */
32
+    protected $publishUrl;
33 33
 
34
-	/**
35
-	 * @var boolean $isPublished
36
-	 */
37
-	protected $isPublished;
34
+    /**
35
+     * @var boolean $isPublished
36
+     */
37
+    protected $isPublished;
38 38
 
39
-	/**
40
-	 * @param string $publishUrl
41
-	 * @param boolean $isPublished
42
-	 */
43
-	function __construct($publishUrl, $isPublished) {
44
-		$this->publishUrl = $publishUrl;
45
-		$this->isPublished = $isPublished;
46
-	}
39
+    /**
40
+     * @param string $publishUrl
41
+     * @param boolean $isPublished
42
+     */
43
+    function __construct($publishUrl, $isPublished) {
44
+        $this->publishUrl = $publishUrl;
45
+        $this->isPublished = $isPublished;
46
+    }
47 47
 
48
-	/**
49
-	 * @return string
50
-	 */
51
-	function getValue() {
52
-		return $this->publishUrl;
53
-	}
48
+    /**
49
+     * @return string
50
+     */
51
+    function getValue() {
52
+        return $this->publishUrl;
53
+    }
54 54
 
55
-	/**
56
-	 * The xmlSerialize metod is called during xml writing.
57
-	 *
58
-	 * Use the $writer argument to write its own xml serialization.
59
-	 *
60
-	 * An important note: do _not_ create a parent element. Any element
61
-	 * implementing XmlSerializble should only ever write what's considered
62
-	 * its 'inner xml'.
63
-	 *
64
-	 * The parent of the current element is responsible for writing a
65
-	 * containing element.
66
-	 *
67
-	 * This allows serializers to be re-used for different element names.
68
-	 *
69
-	 * If you are opening new elements, you must also close them again.
70
-	 *
71
-	 * @param Writer $writer
72
-	 * @return void
73
-	 */
74
-	function xmlSerialize(Writer $writer) {
75
-		if (!$this->isPublished) {
76
-			// for pre-publish-url
77
-			$writer->write($this->publishUrl);
78
-		} else {
79
-			// for publish-url
80
-			$writer->writeElement('{DAV:}href', $this->publishUrl);
81
-		}
82
-	}
55
+    /**
56
+     * The xmlSerialize metod is called during xml writing.
57
+     *
58
+     * Use the $writer argument to write its own xml serialization.
59
+     *
60
+     * An important note: do _not_ create a parent element. Any element
61
+     * implementing XmlSerializble should only ever write what's considered
62
+     * its 'inner xml'.
63
+     *
64
+     * The parent of the current element is responsible for writing a
65
+     * containing element.
66
+     *
67
+     * This allows serializers to be re-used for different element names.
68
+     *
69
+     * If you are opening new elements, you must also close them again.
70
+     *
71
+     * @param Writer $writer
72
+     * @return void
73
+     */
74
+    function xmlSerialize(Writer $writer) {
75
+        if (!$this->isPublished) {
76
+            // for pre-publish-url
77
+            $writer->write($this->publishUrl);
78
+        } else {
79
+            // for publish-url
80
+            $writer->writeElement('{DAV:}href', $this->publishUrl);
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookImpl.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		$update = false;
112 112
 		if (!isset($properties['URI'])) { // create a new contact
113 113
 			$uid = $this->createUid();
114
-			$uri = $uid . '.vcf';
114
+			$uri = $uid.'.vcf';
115 115
 			$vCard = $this->createEmptyVCard($uid);
116 116
 		} else { // update existing contact
117 117
 			$uri = $properties['URI'];
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		$permissions = $this->addressBook->getACL();
143 143
 		$result = 0;
144 144
 		foreach ($permissions as $permission) {
145
-			switch($permission['privilege']) {
145
+			switch ($permission['privilege']) {
146 146
 				case '{DAV:}read':
147 147
 					$result |= Constants::PERMISSION_READ;
148 148
 					break;
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 	protected function createUid() {
188 188
 		do {
189 189
 			$uid = $this->getUid();
190
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
190
+			$contact = $this->backend->getContact($this->getKey(), $uid.'.vcf');
191 191
 		} while (!empty($contact));
192 192
 
193 193
 		return $uid;
@@ -227,15 +227,15 @@  discard block
 block discarded – undo
227 227
 		foreach ($vCard->children() as $property) {
228 228
 			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
229 229
 				$url = $this->urlGenerator->getAbsoluteURL(
230
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
230
+					$this->urlGenerator->linkTo('', 'remote.php').'/dav/');
231 231
 				$url .= implode('/', [
232 232
 					'addressbooks',
233 233
 					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
234 234
 					$this->addressBookInfo['uri'],
235 235
 					$uri
236
-				]) . '?photo';
236
+				]).'?photo';
237 237
 
238
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
238
+				$result['PHOTO'] = 'VALUE=uri:'.$url;
239 239
 
240 240
 			} else if ($property->name === 'X-SOCIALPROFILE') {
241 241
 				$type = $this->getTypeFromProperty($property);
Please login to merge, or discard this patch.
Indentation   +274 added lines, -274 removed lines patch added patch discarded remove patch
@@ -35,278 +35,278 @@
 block discarded – undo
35 35
 
36 36
 class AddressBookImpl implements IAddressBook {
37 37
 
38
-	/** @var CardDavBackend */
39
-	private $backend;
40
-
41
-	/** @var array */
42
-	private $addressBookInfo;
43
-
44
-	/** @var AddressBook */
45
-	private $addressBook;
46
-
47
-	/** @var IURLGenerator */
48
-	private $urlGenerator;
49
-
50
-	/**
51
-	 * AddressBookImpl constructor.
52
-	 *
53
-	 * @param AddressBook $addressBook
54
-	 * @param array $addressBookInfo
55
-	 * @param CardDavBackend $backend
56
-	 * @param IUrlGenerator $urlGenerator
57
-	 */
58
-	public function __construct(
59
-			AddressBook $addressBook,
60
-			array $addressBookInfo,
61
-			CardDavBackend $backend,
62
-			IURLGenerator $urlGenerator) {
63
-
64
-		$this->addressBook = $addressBook;
65
-		$this->addressBookInfo = $addressBookInfo;
66
-		$this->backend = $backend;
67
-		$this->urlGenerator = $urlGenerator;
68
-	}
69
-
70
-	/**
71
-	 * @return string defining the technical unique key
72
-	 * @since 5.0.0
73
-	 */
74
-	public function getKey() {
75
-		return $this->addressBookInfo['id'];
76
-	}
77
-
78
-	/**
79
-	 * In comparison to getKey() this function returns a human readable (maybe translated) name
80
-	 *
81
-	 * @return mixed
82
-	 * @since 5.0.0
83
-	 */
84
-	public function getDisplayName() {
85
-		return $this->addressBookInfo['{DAV:}displayname'];
86
-	}
87
-
88
-	/**
89
-	 * @param string $pattern which should match within the $searchProperties
90
-	 * @param array $searchProperties defines the properties within the query pattern should match
91
-	 * @param array $options Options to define the output format
92
-	 * 	- types boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
93
-	 *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
94
-	 * @return array an array of contacts which are arrays of key-value-pairs
95
-	 *  example result:
96
-	 *  [
97
-	 *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
98
-	 *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
99
-	 *	]
100
-	 * @return array an array of contacts which are arrays of key-value-pairs
101
-	 * @since 5.0.0
102
-	 */
103
-	public function search($pattern, $searchProperties, $options) {
104
-		$results = $this->backend->search($this->getKey(), $pattern, $searchProperties);
105
-
106
-		$withTypes = \array_key_exists('types', $options) && $options['types'] === true;
107
-
108
-		$vCards = [];
109
-		foreach ($results as $result) {
110
-			$vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
111
-		}
112
-
113
-		return $vCards;
114
-	}
115
-
116
-	/**
117
-	 * @param array $properties this array if key-value-pairs defines a contact
118
-	 * @return array an array representing the contact just created or updated
119
-	 * @since 5.0.0
120
-	 */
121
-	public function createOrUpdate($properties) {
122
-		$update = false;
123
-		if (!isset($properties['URI'])) { // create a new contact
124
-			$uid = $this->createUid();
125
-			$uri = $uid . '.vcf';
126
-			$vCard = $this->createEmptyVCard($uid);
127
-		} else { // update existing contact
128
-			$uri = $properties['URI'];
129
-			$vCardData = $this->backend->getCard($this->getKey(), $uri);
130
-			$vCard = $this->readCard($vCardData['carddata']);
131
-			$update = true;
132
-		}
133
-
134
-		foreach ($properties as $key => $value) {
135
-			$vCard->$key = $vCard->createProperty($key, $value);
136
-		}
137
-
138
-		if ($update) {
139
-			$this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
140
-		} else {
141
-			$this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
142
-		}
143
-
144
-		return $this->vCard2Array($uri, $vCard);
145
-
146
-	}
147
-
148
-	/**
149
-	 * @return mixed
150
-	 * @since 5.0.0
151
-	 */
152
-	public function getPermissions() {
153
-		$permissions = $this->addressBook->getACL();
154
-		$result = 0;
155
-		foreach ($permissions as $permission) {
156
-			switch($permission['privilege']) {
157
-				case '{DAV:}read':
158
-					$result |= Constants::PERMISSION_READ;
159
-					break;
160
-				case '{DAV:}write':
161
-					$result |= Constants::PERMISSION_CREATE;
162
-					$result |= Constants::PERMISSION_UPDATE;
163
-					break;
164
-				case '{DAV:}all':
165
-					$result |= Constants::PERMISSION_ALL;
166
-					break;
167
-			}
168
-		}
169
-
170
-		return $result;
171
-	}
172
-
173
-	/**
174
-	 * @param object $id the unique identifier to a contact
175
-	 * @return bool successful or not
176
-	 * @since 5.0.0
177
-	 */
178
-	public function delete($id) {
179
-		$uri = $this->backend->getCardUri($id);
180
-		return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
181
-	}
182
-
183
-	/**
184
-	 * read vCard data into a vCard object
185
-	 *
186
-	 * @param string $cardData
187
-	 * @return VCard
188
-	 */
189
-	protected function readCard($cardData) {
190
-		return  Reader::read($cardData);
191
-	}
192
-
193
-	/**
194
-	 * create UID for contact
195
-	 *
196
-	 * @return string
197
-	 */
198
-	protected function createUid() {
199
-		do {
200
-			$uid = $this->getUid();
201
-			$contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
202
-		} while (!empty($contact));
203
-
204
-		return $uid;
205
-	}
206
-
207
-	/**
208
-	 * getUid is only there for testing, use createUid instead
209
-	 */
210
-	protected function getUid() {
211
-		return UUIDUtil::getUUID();
212
-	}
213
-
214
-	/**
215
-	 * create empty vcard
216
-	 *
217
-	 * @param string $uid
218
-	 * @return VCard
219
-	 */
220
-	protected function createEmptyVCard($uid) {
221
-		$vCard = new VCard();
222
-		$vCard->UID = $uid;
223
-		return $vCard;
224
-	}
225
-
226
-	/**
227
-	 * create array with all vCard properties
228
-	 *
229
-	 * @param string $uri
230
-	 * @param VCard $vCard
231
-	 * @return array
232
-	 */
233
-	protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
234
-		$result = [
235
-			'URI' => $uri,
236
-		];
237
-
238
-		foreach ($vCard->children() as $property) {
239
-			if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
240
-				$url = $this->urlGenerator->getAbsoluteURL(
241
-					$this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
242
-				$url .= implode('/', [
243
-					'addressbooks',
244
-					substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
245
-					$this->addressBookInfo['uri'],
246
-					$uri
247
-				]) . '?photo';
248
-
249
-				$result['PHOTO'] = 'VALUE=uri:' . $url;
250
-
251
-			} else if ($property->name === 'X-SOCIALPROFILE') {
252
-				$type = $this->getTypeFromProperty($property);
253
-
254
-				// Type is the social network, when it's empty we don't need this.
255
-				if ($type !== null) {
256
-					if (!isset($result[$property->name])) {
257
-						$result[$property->name] = [];
258
-					}
259
-					$result[$property->name][$type] = $property->getValue();
260
-				}
261
-
262
-			// The following properties can be set multiple times
263
-			} else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL'])) {
264
-				if (!isset($result[$property->name])) {
265
-					$result[$property->name] = [];
266
-				}
267
-
268
-				$type = $this->getTypeFromProperty($property);
269
-				if ($withTypes) {
270
-					$result[$property->name][] = [
271
-						'type' => $type,
272
-						'value' => $property->getValue()
273
-						];
274
-				} else {
275
-					$result[$property->name][] = $property->getValue();
276
-				}
277
-
278
-
279
-			} else {
280
-				$result[$property->name] = $property->getValue();
281
-			}
282
-		}
283
-
284
-		if (
285
-			$this->addressBookInfo['principaluri'] === 'principals/system/system' && (
286
-				$this->addressBookInfo['uri'] === 'system' ||
287
-				$this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
288
-			)
289
-		) {
290
-			$result['isLocalSystemBook'] = true;
291
-		}
292
-		return $result;
293
-	}
294
-
295
-	/**
296
-	 * Get the type of the current property
297
-	 *
298
-	 * @param Property $property
299
-	 * @return null|string
300
-	 */
301
-	protected function getTypeFromProperty(Property $property) {
302
-		$parameters = $property->parameters();
303
-		// Type is the social network, when it's empty we don't need this.
304
-		if (isset($parameters['TYPE'])) {
305
-			/** @var \Sabre\VObject\Parameter $type */
306
-			$type = $parameters['TYPE'];
307
-			return $type->getValue();
308
-		}
309
-
310
-		return null;
311
-	}
38
+    /** @var CardDavBackend */
39
+    private $backend;
40
+
41
+    /** @var array */
42
+    private $addressBookInfo;
43
+
44
+    /** @var AddressBook */
45
+    private $addressBook;
46
+
47
+    /** @var IURLGenerator */
48
+    private $urlGenerator;
49
+
50
+    /**
51
+     * AddressBookImpl constructor.
52
+     *
53
+     * @param AddressBook $addressBook
54
+     * @param array $addressBookInfo
55
+     * @param CardDavBackend $backend
56
+     * @param IUrlGenerator $urlGenerator
57
+     */
58
+    public function __construct(
59
+            AddressBook $addressBook,
60
+            array $addressBookInfo,
61
+            CardDavBackend $backend,
62
+            IURLGenerator $urlGenerator) {
63
+
64
+        $this->addressBook = $addressBook;
65
+        $this->addressBookInfo = $addressBookInfo;
66
+        $this->backend = $backend;
67
+        $this->urlGenerator = $urlGenerator;
68
+    }
69
+
70
+    /**
71
+     * @return string defining the technical unique key
72
+     * @since 5.0.0
73
+     */
74
+    public function getKey() {
75
+        return $this->addressBookInfo['id'];
76
+    }
77
+
78
+    /**
79
+     * In comparison to getKey() this function returns a human readable (maybe translated) name
80
+     *
81
+     * @return mixed
82
+     * @since 5.0.0
83
+     */
84
+    public function getDisplayName() {
85
+        return $this->addressBookInfo['{DAV:}displayname'];
86
+    }
87
+
88
+    /**
89
+     * @param string $pattern which should match within the $searchProperties
90
+     * @param array $searchProperties defines the properties within the query pattern should match
91
+     * @param array $options Options to define the output format
92
+     * 	- types boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
93
+     *    example: ['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['type => 'HOME', 'value' => '[email protected]']]
94
+     * @return array an array of contacts which are arrays of key-value-pairs
95
+     *  example result:
96
+     *  [
97
+     *		['id' => 0, 'FN' => 'Thomas Müller', 'EMAIL' => '[email protected]', 'GEO' => '37.386013;-122.082932'],
98
+     *		['id' => 5, 'FN' => 'Thomas Tanghus', 'EMAIL' => ['[email protected]', '[email protected]']]
99
+     *	]
100
+     * @return array an array of contacts which are arrays of key-value-pairs
101
+     * @since 5.0.0
102
+     */
103
+    public function search($pattern, $searchProperties, $options) {
104
+        $results = $this->backend->search($this->getKey(), $pattern, $searchProperties);
105
+
106
+        $withTypes = \array_key_exists('types', $options) && $options['types'] === true;
107
+
108
+        $vCards = [];
109
+        foreach ($results as $result) {
110
+            $vCards[] = $this->vCard2Array($result['uri'], $this->readCard($result['carddata']), $withTypes);
111
+        }
112
+
113
+        return $vCards;
114
+    }
115
+
116
+    /**
117
+     * @param array $properties this array if key-value-pairs defines a contact
118
+     * @return array an array representing the contact just created or updated
119
+     * @since 5.0.0
120
+     */
121
+    public function createOrUpdate($properties) {
122
+        $update = false;
123
+        if (!isset($properties['URI'])) { // create a new contact
124
+            $uid = $this->createUid();
125
+            $uri = $uid . '.vcf';
126
+            $vCard = $this->createEmptyVCard($uid);
127
+        } else { // update existing contact
128
+            $uri = $properties['URI'];
129
+            $vCardData = $this->backend->getCard($this->getKey(), $uri);
130
+            $vCard = $this->readCard($vCardData['carddata']);
131
+            $update = true;
132
+        }
133
+
134
+        foreach ($properties as $key => $value) {
135
+            $vCard->$key = $vCard->createProperty($key, $value);
136
+        }
137
+
138
+        if ($update) {
139
+            $this->backend->updateCard($this->getKey(), $uri, $vCard->serialize());
140
+        } else {
141
+            $this->backend->createCard($this->getKey(), $uri, $vCard->serialize());
142
+        }
143
+
144
+        return $this->vCard2Array($uri, $vCard);
145
+
146
+    }
147
+
148
+    /**
149
+     * @return mixed
150
+     * @since 5.0.0
151
+     */
152
+    public function getPermissions() {
153
+        $permissions = $this->addressBook->getACL();
154
+        $result = 0;
155
+        foreach ($permissions as $permission) {
156
+            switch($permission['privilege']) {
157
+                case '{DAV:}read':
158
+                    $result |= Constants::PERMISSION_READ;
159
+                    break;
160
+                case '{DAV:}write':
161
+                    $result |= Constants::PERMISSION_CREATE;
162
+                    $result |= Constants::PERMISSION_UPDATE;
163
+                    break;
164
+                case '{DAV:}all':
165
+                    $result |= Constants::PERMISSION_ALL;
166
+                    break;
167
+            }
168
+        }
169
+
170
+        return $result;
171
+    }
172
+
173
+    /**
174
+     * @param object $id the unique identifier to a contact
175
+     * @return bool successful or not
176
+     * @since 5.0.0
177
+     */
178
+    public function delete($id) {
179
+        $uri = $this->backend->getCardUri($id);
180
+        return $this->backend->deleteCard($this->addressBookInfo['id'], $uri);
181
+    }
182
+
183
+    /**
184
+     * read vCard data into a vCard object
185
+     *
186
+     * @param string $cardData
187
+     * @return VCard
188
+     */
189
+    protected function readCard($cardData) {
190
+        return  Reader::read($cardData);
191
+    }
192
+
193
+    /**
194
+     * create UID for contact
195
+     *
196
+     * @return string
197
+     */
198
+    protected function createUid() {
199
+        do {
200
+            $uid = $this->getUid();
201
+            $contact = $this->backend->getContact($this->getKey(), $uid . '.vcf');
202
+        } while (!empty($contact));
203
+
204
+        return $uid;
205
+    }
206
+
207
+    /**
208
+     * getUid is only there for testing, use createUid instead
209
+     */
210
+    protected function getUid() {
211
+        return UUIDUtil::getUUID();
212
+    }
213
+
214
+    /**
215
+     * create empty vcard
216
+     *
217
+     * @param string $uid
218
+     * @return VCard
219
+     */
220
+    protected function createEmptyVCard($uid) {
221
+        $vCard = new VCard();
222
+        $vCard->UID = $uid;
223
+        return $vCard;
224
+    }
225
+
226
+    /**
227
+     * create array with all vCard properties
228
+     *
229
+     * @param string $uri
230
+     * @param VCard $vCard
231
+     * @return array
232
+     */
233
+    protected function vCard2Array($uri, VCard $vCard, $withTypes = false) {
234
+        $result = [
235
+            'URI' => $uri,
236
+        ];
237
+
238
+        foreach ($vCard->children() as $property) {
239
+            if ($property->name === 'PHOTO' && $property->getValueType() === 'BINARY') {
240
+                $url = $this->urlGenerator->getAbsoluteURL(
241
+                    $this->urlGenerator->linkTo('', 'remote.php') . '/dav/');
242
+                $url .= implode('/', [
243
+                    'addressbooks',
244
+                    substr($this->addressBookInfo['principaluri'], 11), //cut off 'principals/'
245
+                    $this->addressBookInfo['uri'],
246
+                    $uri
247
+                ]) . '?photo';
248
+
249
+                $result['PHOTO'] = 'VALUE=uri:' . $url;
250
+
251
+            } else if ($property->name === 'X-SOCIALPROFILE') {
252
+                $type = $this->getTypeFromProperty($property);
253
+
254
+                // Type is the social network, when it's empty we don't need this.
255
+                if ($type !== null) {
256
+                    if (!isset($result[$property->name])) {
257
+                        $result[$property->name] = [];
258
+                    }
259
+                    $result[$property->name][$type] = $property->getValue();
260
+                }
261
+
262
+            // The following properties can be set multiple times
263
+            } else if (in_array($property->name, ['CLOUD', 'EMAIL', 'IMPP', 'TEL', 'URL'])) {
264
+                if (!isset($result[$property->name])) {
265
+                    $result[$property->name] = [];
266
+                }
267
+
268
+                $type = $this->getTypeFromProperty($property);
269
+                if ($withTypes) {
270
+                    $result[$property->name][] = [
271
+                        'type' => $type,
272
+                        'value' => $property->getValue()
273
+                        ];
274
+                } else {
275
+                    $result[$property->name][] = $property->getValue();
276
+                }
277
+
278
+
279
+            } else {
280
+                $result[$property->name] = $property->getValue();
281
+            }
282
+        }
283
+
284
+        if (
285
+            $this->addressBookInfo['principaluri'] === 'principals/system/system' && (
286
+                $this->addressBookInfo['uri'] === 'system' ||
287
+                $this->addressBookInfo['{DAV:}displayname'] === $this->urlGenerator->getBaseUrl()
288
+            )
289
+        ) {
290
+            $result['isLocalSystemBook'] = true;
291
+        }
292
+        return $result;
293
+    }
294
+
295
+    /**
296
+     * Get the type of the current property
297
+     *
298
+     * @param Property $property
299
+     * @return null|string
300
+     */
301
+    protected function getTypeFromProperty(Property $property) {
302
+        $parameters = $property->parameters();
303
+        // Type is the social network, when it's empty we don't need this.
304
+        if (isset($parameters['TYPE'])) {
305
+            /** @var \Sabre\VObject\Parameter $type */
306
+            $type = $parameters['TYPE'];
307
+            return $type->getValue();
308
+        }
309
+
310
+        return null;
311
+    }
312 312
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/Xml/Groups.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -26,21 +26,21 @@
 block discarded – undo
26 26
 use Sabre\Xml\Writer;
27 27
 
28 28
 class Groups implements XmlSerializable {
29
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
29
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
30 30
 
31
-	/** @var string[] of TYPE:CHECKSUM */
32
-	private $groups;
31
+    /** @var string[] of TYPE:CHECKSUM */
32
+    private $groups;
33 33
 
34
-	/**
35
-	 * @param string $groups
36
-	 */
37
-	public function __construct($groups) {
38
-		$this->groups = $groups;
39
-	}
34
+    /**
35
+     * @param string $groups
36
+     */
37
+    public function __construct($groups) {
38
+        $this->groups = $groups;
39
+    }
40 40
 
41
-	function xmlSerialize(Writer $writer) {
42
-		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
-		}
45
-	}
41
+    function xmlSerialize(Writer $writer) {
42
+        foreach ($this->groups as $group) {
43
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
44
+        }
45
+    }
46 46
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@
 block discarded – undo
40 40
 
41 41
 	function xmlSerialize(Writer $writer) {
42 42
 		foreach ($this->groups as $group) {
43
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}group', $group);
43
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}group', $group);
44 44
 		}
45 45
 	}
46 46
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 1 patch
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 3 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -745,7 +745,9 @@
 block discarded – undo
745 745
 		$stmt->execute([ $addressBookId ]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748
-		if (is_null($currentToken)) return null;
748
+		if (is_null($currentToken)) {
749
+		    return null;
750
+		}
749 751
 
750 752
 		$result = [
751 753
 			'syncToken' => $currentToken,
Please login to merge, or discard this patch.
Spacing   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			->from('addressbooks')
115 115
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116 116
 
117
-		return (int)$query->execute()->fetchColumn();
117
+		return (int) $query->execute()->fetchColumn();
118 118
 	}
119 119
 
120 120
 	/**
@@ -145,15 +145,15 @@  discard block
 block discarded – undo
145 145
 		$addressBooks = [];
146 146
 
147 147
 		$result = $query->execute();
148
-		while($row = $result->fetch()) {
148
+		while ($row = $result->fetch()) {
149 149
 			$addressBooks[$row['id']] = [
150 150
 				'id'  => $row['id'],
151 151
 				'uri' => $row['uri'],
152 152
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153 153
 				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
154
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
155 155
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
156
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
157 157
 			];
158 158
 
159 159
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 		$principals = array_map(function($principal) {
166 166
 			return urldecode($principal);
167 167
 		}, $principals);
168
-		$principals[]= $principalUri;
168
+		$principals[] = $principalUri;
169 169
 
170 170
 		$query = $this->db->getQueryBuilder();
171 171
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -177,8 +177,8 @@  discard block
 block discarded – undo
177 177
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
178 178
 			->execute();
179 179
 
180
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
181
-		while($row = $result->fetch()) {
180
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
181
+		while ($row = $result->fetch()) {
182 182
 			if ($row['principaluri'] === $principalUri) {
183 183
 				continue;
184 184
 			}
@@ -197,18 +197,18 @@  discard block
 block discarded – undo
197 197
 			}
198 198
 
199 199
 			list(, $name) = \Sabre\Uri\split($row['principaluri']);
200
-			$uri = $row['uri'] . '_shared_by_' . $name;
201
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
200
+			$uri = $row['uri'].'_shared_by_'.$name;
201
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
202 202
 
203 203
 			$addressBooks[$row['id']] = [
204 204
 				'id'  => $row['id'],
205 205
 				'uri' => $uri,
206 206
 				'principaluri' => $principalUriOriginal,
207 207
 				'{DAV:}displayname' => $displayName,
208
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
208
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
209 209
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
210
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
211
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
210
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
211
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
212 212
 				$readOnlyPropertyName => $readOnly,
213 213
 			];
214 214
 
@@ -229,15 +229,15 @@  discard block
 block discarded – undo
229 229
 		$addressBooks = [];
230 230
 
231 231
 		$result = $query->execute();
232
-		while($row = $result->fetch()) {
232
+		while ($row = $result->fetch()) {
233 233
 			$addressBooks[$row['id']] = [
234 234
 				'id'  => $row['id'],
235 235
 				'uri' => $row['uri'],
236 236
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
237 237
 				'{DAV:}displayname' => $row['displayname'],
238
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
238
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
239 239
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
240
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
240
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
241 241
 			];
242 242
 
243 243
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -282,9 +282,9 @@  discard block
 block discarded – undo
282 282
 			'uri' => $row['uri'],
283 283
 			'principaluri' => $row['principaluri'],
284 284
 			'{DAV:}displayname' => $row['displayname'],
285
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
285
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
286 286
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
287
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
287
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
288 288
 		];
289 289
 
290 290
 		$this->addOwnerPrincipal($addressBook);
@@ -316,9 +316,9 @@  discard block
 block discarded – undo
316 316
 			'uri' => $row['uri'],
317 317
 			'principaluri' => $row['principaluri'],
318 318
 			'{DAV:}displayname' => $row['displayname'],
319
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
319
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
320 320
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
321
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
321
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
322 322
 		];
323 323
 
324 324
 		$this->addOwnerPrincipal($addressBook);
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
346 346
 		$supportedProperties = [
347 347
 			'{DAV:}displayname',
348
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
348
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
349 349
 		];
350 350
 
351 351
 		/**
@@ -354,13 +354,13 @@  discard block
 block discarded – undo
354 354
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
355 355
 
356 356
 			$updates = [];
357
-			foreach($mutations as $property=>$newValue) {
357
+			foreach ($mutations as $property=>$newValue) {
358 358
 
359
-				switch($property) {
359
+				switch ($property) {
360 360
 					case '{DAV:}displayname' :
361 361
 						$updates['displayname'] = $newValue;
362 362
 						break;
363
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
363
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
364 364
 						$updates['description'] = $newValue;
365 365
 						break;
366 366
 				}
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
 			$query = $this->db->getQueryBuilder();
369 369
 			$query->update('addressbooks');
370 370
 
371
-			foreach($updates as $key=>$value) {
371
+			foreach ($updates as $key=>$value) {
372 372
 				$query->set($key, $query->createNamedParameter($value));
373 373
 			}
374 374
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -399,24 +399,24 @@  discard block
 block discarded – undo
399 399
 			'synctoken' => 1
400 400
 		];
401 401
 
402
-		foreach($properties as $property=>$newValue) {
402
+		foreach ($properties as $property=>$newValue) {
403 403
 
404
-			switch($property) {
404
+			switch ($property) {
405 405
 				case '{DAV:}displayname' :
406 406
 					$values['displayname'] = $newValue;
407 407
 					break;
408
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
408
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
409 409
 					$values['description'] = $newValue;
410 410
 					break;
411 411
 				default :
412
-					throw new BadRequest('Unknown property: ' . $property);
412
+					throw new BadRequest('Unknown property: '.$property);
413 413
 			}
414 414
 
415 415
 		}
416 416
 
417 417
 		// Fallback to make sure the displayname is set. Some clients may refuse
418 418
 		// to work with addressbooks not having a displayname.
419
-		if(is_null($values['displayname'])) {
419
+		if (is_null($values['displayname'])) {
420 420
 			$values['displayname'] = $url;
421 421
 		}
422 422
 
@@ -494,8 +494,8 @@  discard block
 block discarded – undo
494 494
 		$cards = [];
495 495
 
496 496
 		$result = $query->execute();
497
-		while($row = $result->fetch()) {
498
-			$row['etag'] = '"' . $row['etag'] . '"';
497
+		while ($row = $result->fetch()) {
498
+			$row['etag'] = '"'.$row['etag'].'"';
499 499
 			$row['carddata'] = $this->readBlob($row['carddata']);
500 500
 			$cards[] = $row;
501 501
 		}
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 		if (!$row) {
530 530
 			return false;
531 531
 		}
532
-		$row['etag'] = '"' . $row['etag'] . '"';
532
+		$row['etag'] = '"'.$row['etag'].'"';
533 533
 		$row['carddata'] = $this->readBlob($row['carddata']);
534 534
 
535 535
 		return $row;
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 			$result = $query->execute();
567 567
 
568 568
 			while ($row = $result->fetch()) {
569
-				$row['etag'] = '"' . $row['etag'] . '"';
569
+				$row['etag'] = '"'.$row['etag'].'"';
570 570
 				$row['carddata'] = $this->readBlob($row['carddata']);
571 571
 				$cards[] = $row;
572 572
 			}
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 				'cardUri' => $cardUri,
625 625
 				'cardData' => $cardData]));
626 626
 
627
-		return '"' . $etag . '"';
627
+		return '"'.$etag.'"';
628 628
 	}
629 629
 
630 630
 	/**
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
 				'cardUri' => $cardUri,
675 675
 				'cardData' => $cardData]));
676 676
 
677
-		return '"' . $etag . '"';
677
+		return '"'.$etag.'"';
678 678
 	}
679 679
 
680 680
 	/**
@@ -772,7 +772,7 @@  discard block
 block discarded – undo
772 772
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
773 773
 		// Current synctoken
774 774
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
775
-		$stmt->execute([ $addressBookId ]);
775
+		$stmt->execute([$addressBookId]);
776 776
 		$currentToken = $stmt->fetchColumn(0);
777 777
 
778 778
 		if (is_null($currentToken)) return null;
@@ -787,8 +787,8 @@  discard block
 block discarded – undo
787 787
 		if ($syncToken) {
788 788
 
789 789
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
790
-			if ($limit>0) {
791
-				$query .= " `LIMIT` " . (int)$limit;
790
+			if ($limit > 0) {
791
+				$query .= " `LIMIT` ".(int) $limit;
792 792
 			}
793 793
 
794 794
 			// Fetching all changes
@@ -799,15 +799,15 @@  discard block
 block discarded – undo
799 799
 
800 800
 			// This loop ensures that any duplicates are overwritten, only the
801 801
 			// last change on a node is relevant.
802
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
802
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
803 803
 
804 804
 				$changes[$row['uri']] = $row['operation'];
805 805
 
806 806
 			}
807 807
 
808
-			foreach($changes as $uri => $operation) {
808
+			foreach ($changes as $uri => $operation) {
809 809
 
810
-				switch($operation) {
810
+				switch ($operation) {
811 811
 					case 1:
812 812
 						$result['added'][] = $uri;
813 813
 						break;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 
894 894
 		// No need for like when the pattern is empty
895 895
 		if ('' !== $pattern) {
896
-			$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
896
+			$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
897 897
 		}
898 898
 
899 899
 		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
 		$result->closeCursor();
947 947
 
948 948
 		if (!isset($uri['uri'])) {
949
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
949
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
950 950
 		}
951 951
 
952 952
 		return $uri['uri'];
@@ -1018,11 +1018,11 @@  discard block
 block discarded – undo
1018 1018
 			);
1019 1019
 
1020 1020
 		foreach ($vCard->children() as $property) {
1021
-			if(!in_array($property->name, self::$indexProperties)) {
1021
+			if (!in_array($property->name, self::$indexProperties)) {
1022 1022
 				continue;
1023 1023
 			}
1024 1024
 			$preferred = 0;
1025
-			foreach($property->parameters as $parameter) {
1025
+			foreach ($property->parameters as $parameter) {
1026 1026
 				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1027 1027
 					$preferred = 1;
1028 1028
 					break;
@@ -1077,10 +1077,10 @@  discard block
 block discarded – undo
1077 1077
 		$result->closeCursor();
1078 1078
 
1079 1079
 		if (!isset($cardIds['id'])) {
1080
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1080
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1081 1081
 		}
1082 1082
 
1083
-		return (int)$cardIds['id'];
1083
+		return (int) $cardIds['id'];
1084 1084
 	}
1085 1085
 
1086 1086
 	/**
@@ -1105,8 +1105,8 @@  discard block
 block discarded – undo
1105 1105
 	}
1106 1106
 
1107 1107
 	private function addOwnerPrincipal(&$addressbookInfo) {
1108
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1109
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1108
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1109
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1110 1110
 		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1111 1111
 			$uri = $addressbookInfo[$ownerPrincipalKey];
1112 1112
 		} else {
Please login to merge, or discard this patch.
Indentation   +1072 added lines, -1072 removed lines patch added patch discarded remove patch
@@ -49,1076 +49,1076 @@
 block discarded – undo
49 49
 
50 50
 class CardDavBackend implements BackendInterface, SyncSupport {
51 51
 
52
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
53
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
54
-
55
-	/** @var Principal */
56
-	private $principalBackend;
57
-
58
-	/** @var string */
59
-	private $dbCardsTable = 'cards';
60
-
61
-	/** @var string */
62
-	private $dbCardsPropertiesTable = 'cards_properties';
63
-
64
-	/** @var IDBConnection */
65
-	private $db;
66
-
67
-	/** @var Backend */
68
-	private $sharingBackend;
69
-
70
-	/** @var array properties to index */
71
-	public static $indexProperties = array(
72
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
73
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
74
-
75
-	/**
76
-	 * @var string[] Map of uid => display name
77
-	 */
78
-	protected $userDisplayNames;
79
-
80
-	/** @var IUserManager */
81
-	private $userManager;
82
-
83
-	/** @var EventDispatcherInterface */
84
-	private $dispatcher;
85
-
86
-	/**
87
-	 * CardDavBackend constructor.
88
-	 *
89
-	 * @param IDBConnection $db
90
-	 * @param Principal $principalBackend
91
-	 * @param IUserManager $userManager
92
-	 * @param IGroupManager $groupManager
93
-	 * @param EventDispatcherInterface $dispatcher
94
-	 */
95
-	public function __construct(IDBConnection $db,
96
-								Principal $principalBackend,
97
-								IUserManager $userManager,
98
-								IGroupManager $groupManager,
99
-								EventDispatcherInterface $dispatcher) {
100
-		$this->db = $db;
101
-		$this->principalBackend = $principalBackend;
102
-		$this->userManager = $userManager;
103
-		$this->dispatcher = $dispatcher;
104
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
105
-	}
106
-
107
-	/**
108
-	 * Return the number of address books for a principal
109
-	 *
110
-	 * @param $principalUri
111
-	 * @return int
112
-	 */
113
-	public function getAddressBooksForUserCount($principalUri) {
114
-		$principalUri = $this->convertPrincipal($principalUri, true);
115
-		$query = $this->db->getQueryBuilder();
116
-		$query->select($query->createFunction('COUNT(*)'))
117
-			->from('addressbooks')
118
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
119
-
120
-		return (int)$query->execute()->fetchColumn();
121
-	}
122
-
123
-	/**
124
-	 * Returns the list of address books for a specific user.
125
-	 *
126
-	 * Every addressbook should have the following properties:
127
-	 *   id - an arbitrary unique id
128
-	 *   uri - the 'basename' part of the url
129
-	 *   principaluri - Same as the passed parameter
130
-	 *
131
-	 * Any additional clark-notation property may be passed besides this. Some
132
-	 * common ones are :
133
-	 *   {DAV:}displayname
134
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
135
-	 *   {http://calendarserver.org/ns/}getctag
136
-	 *
137
-	 * @param string $principalUri
138
-	 * @return array
139
-	 */
140
-	function getAddressBooksForUser($principalUri) {
141
-		$principalUriOriginal = $principalUri;
142
-		$principalUri = $this->convertPrincipal($principalUri, true);
143
-		$query = $this->db->getQueryBuilder();
144
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
145
-			->from('addressbooks')
146
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
147
-
148
-		$addressBooks = [];
149
-
150
-		$result = $query->execute();
151
-		while($row = $result->fetch()) {
152
-			$addressBooks[$row['id']] = [
153
-				'id'  => $row['id'],
154
-				'uri' => $row['uri'],
155
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
156
-				'{DAV:}displayname' => $row['displayname'],
157
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
158
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
159
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
160
-			];
161
-
162
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
163
-		}
164
-		$result->closeCursor();
165
-
166
-		// query for shared calendars
167
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
168
-		$principals = array_map(function($principal) {
169
-			return urldecode($principal);
170
-		}, $principals);
171
-		$principals[]= $principalUri;
172
-
173
-		$query = $this->db->getQueryBuilder();
174
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
175
-			->from('dav_shares', 's')
176
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
177
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
178
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
179
-			->setParameter('type', 'addressbook')
180
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
181
-			->execute();
182
-
183
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
184
-		while($row = $result->fetch()) {
185
-			if ($row['principaluri'] === $principalUri) {
186
-				continue;
187
-			}
188
-
189
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
190
-			if (isset($addressBooks[$row['id']])) {
191
-				if ($readOnly) {
192
-					// New share can not have more permissions then the old one.
193
-					continue;
194
-				}
195
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
196
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
197
-					// Old share is already read-write, no more permissions can be gained
198
-					continue;
199
-				}
200
-			}
201
-
202
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
203
-			$uri = $row['uri'] . '_shared_by_' . $name;
204
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
205
-
206
-			$addressBooks[$row['id']] = [
207
-				'id'  => $row['id'],
208
-				'uri' => $uri,
209
-				'principaluri' => $principalUriOriginal,
210
-				'{DAV:}displayname' => $displayName,
211
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
212
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
213
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
214
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
215
-				$readOnlyPropertyName => $readOnly,
216
-			];
217
-
218
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
219
-		}
220
-		$result->closeCursor();
221
-
222
-		return array_values($addressBooks);
223
-	}
224
-
225
-	public function getUsersOwnAddressBooks($principalUri) {
226
-		$principalUri = $this->convertPrincipal($principalUri, true);
227
-		$query = $this->db->getQueryBuilder();
228
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
229
-			  ->from('addressbooks')
230
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
231
-
232
-		$addressBooks = [];
233
-
234
-		$result = $query->execute();
235
-		while($row = $result->fetch()) {
236
-			$addressBooks[$row['id']] = [
237
-				'id'  => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
240
-				'{DAV:}displayname' => $row['displayname'],
241
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
242
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
243
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
244
-			];
245
-
246
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
247
-		}
248
-		$result->closeCursor();
249
-
250
-		return array_values($addressBooks);
251
-	}
252
-
253
-	private function getUserDisplayName($uid) {
254
-		if (!isset($this->userDisplayNames[$uid])) {
255
-			$user = $this->userManager->get($uid);
256
-
257
-			if ($user instanceof IUser) {
258
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
259
-			} else {
260
-				$this->userDisplayNames[$uid] = $uid;
261
-			}
262
-		}
263
-
264
-		return $this->userDisplayNames[$uid];
265
-	}
266
-
267
-	/**
268
-	 * @param int $addressBookId
269
-	 */
270
-	public function getAddressBookById($addressBookId) {
271
-		$query = $this->db->getQueryBuilder();
272
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
-			->from('addressbooks')
274
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
275
-			->execute();
276
-
277
-		$row = $result->fetch();
278
-		$result->closeCursor();
279
-		if ($row === false) {
280
-			return null;
281
-		}
282
-
283
-		$addressBook = [
284
-			'id'  => $row['id'],
285
-			'uri' => $row['uri'],
286
-			'principaluri' => $row['principaluri'],
287
-			'{DAV:}displayname' => $row['displayname'],
288
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
289
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
290
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
291
-		];
292
-
293
-		$this->addOwnerPrincipal($addressBook);
294
-
295
-		return $addressBook;
296
-	}
297
-
298
-	/**
299
-	 * @param $addressBookUri
300
-	 * @return array|null
301
-	 */
302
-	public function getAddressBooksByUri($principal, $addressBookUri) {
303
-		$query = $this->db->getQueryBuilder();
304
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
305
-			->from('addressbooks')
306
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
307
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
308
-			->setMaxResults(1)
309
-			->execute();
310
-
311
-		$row = $result->fetch();
312
-		$result->closeCursor();
313
-		if ($row === false) {
314
-			return null;
315
-		}
316
-
317
-		$addressBook = [
318
-			'id'  => $row['id'],
319
-			'uri' => $row['uri'],
320
-			'principaluri' => $row['principaluri'],
321
-			'{DAV:}displayname' => $row['displayname'],
322
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
323
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
324
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
325
-		];
326
-
327
-		$this->addOwnerPrincipal($addressBook);
328
-
329
-		return $addressBook;
330
-	}
331
-
332
-	/**
333
-	 * Updates properties for an address book.
334
-	 *
335
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
336
-	 * To do the actual updates, you must tell this object which properties
337
-	 * you're going to process with the handle() method.
338
-	 *
339
-	 * Calling the handle method is like telling the PropPatch object "I
340
-	 * promise I can handle updating this property".
341
-	 *
342
-	 * Read the PropPatch documentation for more info and examples.
343
-	 *
344
-	 * @param string $addressBookId
345
-	 * @param \Sabre\DAV\PropPatch $propPatch
346
-	 * @return void
347
-	 */
348
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
349
-		$supportedProperties = [
350
-			'{DAV:}displayname',
351
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
352
-		];
353
-
354
-		/**
355
-		 * @suppress SqlInjectionChecker
356
-		 */
357
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
358
-
359
-			$updates = [];
360
-			foreach($mutations as $property=>$newValue) {
361
-
362
-				switch($property) {
363
-					case '{DAV:}displayname' :
364
-						$updates['displayname'] = $newValue;
365
-						break;
366
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
367
-						$updates['description'] = $newValue;
368
-						break;
369
-				}
370
-			}
371
-			$query = $this->db->getQueryBuilder();
372
-			$query->update('addressbooks');
373
-
374
-			foreach($updates as $key=>$value) {
375
-				$query->set($key, $query->createNamedParameter($value));
376
-			}
377
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
378
-			->execute();
379
-
380
-			$this->addChange($addressBookId, "", 2);
381
-
382
-			return true;
383
-
384
-		});
385
-	}
386
-
387
-	/**
388
-	 * Creates a new address book
389
-	 *
390
-	 * @param string $principalUri
391
-	 * @param string $url Just the 'basename' of the url.
392
-	 * @param array $properties
393
-	 * @return int
394
-	 * @throws BadRequest
395
-	 */
396
-	function createAddressBook($principalUri, $url, array $properties) {
397
-		$values = [
398
-			'displayname' => null,
399
-			'description' => null,
400
-			'principaluri' => $principalUri,
401
-			'uri' => $url,
402
-			'synctoken' => 1
403
-		];
404
-
405
-		foreach($properties as $property=>$newValue) {
406
-
407
-			switch($property) {
408
-				case '{DAV:}displayname' :
409
-					$values['displayname'] = $newValue;
410
-					break;
411
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
412
-					$values['description'] = $newValue;
413
-					break;
414
-				default :
415
-					throw new BadRequest('Unknown property: ' . $property);
416
-			}
417
-
418
-		}
419
-
420
-		// Fallback to make sure the displayname is set. Some clients may refuse
421
-		// to work with addressbooks not having a displayname.
422
-		if(is_null($values['displayname'])) {
423
-			$values['displayname'] = $url;
424
-		}
425
-
426
-		$query = $this->db->getQueryBuilder();
427
-		$query->insert('addressbooks')
428
-			->values([
429
-				'uri' => $query->createParameter('uri'),
430
-				'displayname' => $query->createParameter('displayname'),
431
-				'description' => $query->createParameter('description'),
432
-				'principaluri' => $query->createParameter('principaluri'),
433
-				'synctoken' => $query->createParameter('synctoken'),
434
-			])
435
-			->setParameters($values)
436
-			->execute();
437
-
438
-		return $query->getLastInsertId();
439
-	}
440
-
441
-	/**
442
-	 * Deletes an entire addressbook and all its contents
443
-	 *
444
-	 * @param mixed $addressBookId
445
-	 * @return void
446
-	 */
447
-	function deleteAddressBook($addressBookId) {
448
-		$query = $this->db->getQueryBuilder();
449
-		$query->delete('cards')
450
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
451
-			->setParameter('addressbookid', $addressBookId)
452
-			->execute();
453
-
454
-		$query->delete('addressbookchanges')
455
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
456
-			->setParameter('addressbookid', $addressBookId)
457
-			->execute();
458
-
459
-		$query->delete('addressbooks')
460
-			->where($query->expr()->eq('id', $query->createParameter('id')))
461
-			->setParameter('id', $addressBookId)
462
-			->execute();
463
-
464
-		$this->sharingBackend->deleteAllShares($addressBookId);
465
-
466
-		$query->delete($this->dbCardsPropertiesTable)
467
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
468
-			->execute();
469
-
470
-	}
471
-
472
-	/**
473
-	 * Returns all cards for a specific addressbook id.
474
-	 *
475
-	 * This method should return the following properties for each card:
476
-	 *   * carddata - raw vcard data
477
-	 *   * uri - Some unique url
478
-	 *   * lastmodified - A unix timestamp
479
-	 *
480
-	 * It's recommended to also return the following properties:
481
-	 *   * etag - A unique etag. This must change every time the card changes.
482
-	 *   * size - The size of the card in bytes.
483
-	 *
484
-	 * If these last two properties are provided, less time will be spent
485
-	 * calculating them. If they are specified, you can also ommit carddata.
486
-	 * This may speed up certain requests, especially with large cards.
487
-	 *
488
-	 * @param mixed $addressBookId
489
-	 * @return array
490
-	 */
491
-	function getCards($addressBookId) {
492
-		$query = $this->db->getQueryBuilder();
493
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
494
-			->from('cards')
495
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
496
-
497
-		$cards = [];
498
-
499
-		$result = $query->execute();
500
-		while($row = $result->fetch()) {
501
-			$row['etag'] = '"' . $row['etag'] . '"';
502
-			$row['carddata'] = $this->readBlob($row['carddata']);
503
-			$cards[] = $row;
504
-		}
505
-		$result->closeCursor();
506
-
507
-		return $cards;
508
-	}
509
-
510
-	/**
511
-	 * Returns a specific card.
512
-	 *
513
-	 * The same set of properties must be returned as with getCards. The only
514
-	 * exception is that 'carddata' is absolutely required.
515
-	 *
516
-	 * If the card does not exist, you must return false.
517
-	 *
518
-	 * @param mixed $addressBookId
519
-	 * @param string $cardUri
520
-	 * @return array
521
-	 */
522
-	function getCard($addressBookId, $cardUri) {
523
-		$query = $this->db->getQueryBuilder();
524
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
525
-			->from('cards')
526
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
527
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
528
-			->setMaxResults(1);
529
-
530
-		$result = $query->execute();
531
-		$row = $result->fetch();
532
-		if (!$row) {
533
-			return false;
534
-		}
535
-		$row['etag'] = '"' . $row['etag'] . '"';
536
-		$row['carddata'] = $this->readBlob($row['carddata']);
537
-
538
-		return $row;
539
-	}
540
-
541
-	/**
542
-	 * Returns a list of cards.
543
-	 *
544
-	 * This method should work identical to getCard, but instead return all the
545
-	 * cards in the list as an array.
546
-	 *
547
-	 * If the backend supports this, it may allow for some speed-ups.
548
-	 *
549
-	 * @param mixed $addressBookId
550
-	 * @param string[] $uris
551
-	 * @return array
552
-	 */
553
-	function getMultipleCards($addressBookId, array $uris) {
554
-		if (empty($uris)) {
555
-			return [];
556
-		}
557
-
558
-		$chunks = array_chunk($uris, 100);
559
-		$cards = [];
560
-
561
-		$query = $this->db->getQueryBuilder();
562
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
563
-			->from('cards')
564
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
565
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
566
-
567
-		foreach ($chunks as $uris) {
568
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
569
-			$result = $query->execute();
570
-
571
-			while ($row = $result->fetch()) {
572
-				$row['etag'] = '"' . $row['etag'] . '"';
573
-				$row['carddata'] = $this->readBlob($row['carddata']);
574
-				$cards[] = $row;
575
-			}
576
-			$result->closeCursor();
577
-		}
578
-		return $cards;
579
-	}
580
-
581
-	/**
582
-	 * Creates a new card.
583
-	 *
584
-	 * The addressbook id will be passed as the first argument. This is the
585
-	 * same id as it is returned from the getAddressBooksForUser method.
586
-	 *
587
-	 * The cardUri is a base uri, and doesn't include the full path. The
588
-	 * cardData argument is the vcard body, and is passed as a string.
589
-	 *
590
-	 * It is possible to return an ETag from this method. This ETag is for the
591
-	 * newly created resource, and must be enclosed with double quotes (that
592
-	 * is, the string itself must contain the double quotes).
593
-	 *
594
-	 * You should only return the ETag if you store the carddata as-is. If a
595
-	 * subsequent GET request on the same card does not have the same body,
596
-	 * byte-by-byte and you did return an ETag here, clients tend to get
597
-	 * confused.
598
-	 *
599
-	 * If you don't return an ETag, you can just return null.
600
-	 *
601
-	 * @param mixed $addressBookId
602
-	 * @param string $cardUri
603
-	 * @param string $cardData
604
-	 * @return string
605
-	 */
606
-	function createCard($addressBookId, $cardUri, $cardData) {
607
-		$etag = md5($cardData);
608
-
609
-		$query = $this->db->getQueryBuilder();
610
-		$query->insert('cards')
611
-			->values([
612
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
613
-				'uri' => $query->createNamedParameter($cardUri),
614
-				'lastmodified' => $query->createNamedParameter(time()),
615
-				'addressbookid' => $query->createNamedParameter($addressBookId),
616
-				'size' => $query->createNamedParameter(strlen($cardData)),
617
-				'etag' => $query->createNamedParameter($etag),
618
-			])
619
-			->execute();
620
-
621
-		$this->addChange($addressBookId, $cardUri, 1);
622
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
623
-
624
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
625
-			new GenericEvent(null, [
626
-				'addressBookId' => $addressBookId,
627
-				'cardUri' => $cardUri,
628
-				'cardData' => $cardData]));
629
-
630
-		return '"' . $etag . '"';
631
-	}
632
-
633
-	/**
634
-	 * Updates a card.
635
-	 *
636
-	 * The addressbook id will be passed as the first argument. This is the
637
-	 * same id as it is returned from the getAddressBooksForUser method.
638
-	 *
639
-	 * The cardUri is a base uri, and doesn't include the full path. The
640
-	 * cardData argument is the vcard body, and is passed as a string.
641
-	 *
642
-	 * It is possible to return an ETag from this method. This ETag should
643
-	 * match that of the updated resource, and must be enclosed with double
644
-	 * quotes (that is: the string itself must contain the actual quotes).
645
-	 *
646
-	 * You should only return the ETag if you store the carddata as-is. If a
647
-	 * subsequent GET request on the same card does not have the same body,
648
-	 * byte-by-byte and you did return an ETag here, clients tend to get
649
-	 * confused.
650
-	 *
651
-	 * If you don't return an ETag, you can just return null.
652
-	 *
653
-	 * @param mixed $addressBookId
654
-	 * @param string $cardUri
655
-	 * @param string $cardData
656
-	 * @return string
657
-	 */
658
-	function updateCard($addressBookId, $cardUri, $cardData) {
659
-
660
-		$etag = md5($cardData);
661
-		$query = $this->db->getQueryBuilder();
662
-		$query->update('cards')
663
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
664
-			->set('lastmodified', $query->createNamedParameter(time()))
665
-			->set('size', $query->createNamedParameter(strlen($cardData)))
666
-			->set('etag', $query->createNamedParameter($etag))
667
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
668
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
669
-			->execute();
670
-
671
-		$this->addChange($addressBookId, $cardUri, 2);
672
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
673
-
674
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
675
-			new GenericEvent(null, [
676
-				'addressBookId' => $addressBookId,
677
-				'cardUri' => $cardUri,
678
-				'cardData' => $cardData]));
679
-
680
-		return '"' . $etag . '"';
681
-	}
682
-
683
-	/**
684
-	 * Deletes a card
685
-	 *
686
-	 * @param mixed $addressBookId
687
-	 * @param string $cardUri
688
-	 * @return bool
689
-	 */
690
-	function deleteCard($addressBookId, $cardUri) {
691
-		try {
692
-			$cardId = $this->getCardId($addressBookId, $cardUri);
693
-		} catch (\InvalidArgumentException $e) {
694
-			$cardId = null;
695
-		}
696
-		$query = $this->db->getQueryBuilder();
697
-		$ret = $query->delete('cards')
698
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
699
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
700
-			->execute();
701
-
702
-		$this->addChange($addressBookId, $cardUri, 3);
703
-
704
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
705
-			new GenericEvent(null, [
706
-				'addressBookId' => $addressBookId,
707
-				'cardUri' => $cardUri]));
708
-
709
-		if ($ret === 1) {
710
-			if ($cardId !== null) {
711
-				$this->purgeProperties($addressBookId, $cardId);
712
-			}
713
-			return true;
714
-		}
715
-
716
-		return false;
717
-	}
718
-
719
-	/**
720
-	 * The getChanges method returns all the changes that have happened, since
721
-	 * the specified syncToken in the specified address book.
722
-	 *
723
-	 * This function should return an array, such as the following:
724
-	 *
725
-	 * [
726
-	 *   'syncToken' => 'The current synctoken',
727
-	 *   'added'   => [
728
-	 *      'new.txt',
729
-	 *   ],
730
-	 *   'modified'   => [
731
-	 *      'modified.txt',
732
-	 *   ],
733
-	 *   'deleted' => [
734
-	 *      'foo.php.bak',
735
-	 *      'old.txt'
736
-	 *   ]
737
-	 * ];
738
-	 *
739
-	 * The returned syncToken property should reflect the *current* syncToken
740
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
741
-	 * property. This is needed here too, to ensure the operation is atomic.
742
-	 *
743
-	 * If the $syncToken argument is specified as null, this is an initial
744
-	 * sync, and all members should be reported.
745
-	 *
746
-	 * The modified property is an array of nodenames that have changed since
747
-	 * the last token.
748
-	 *
749
-	 * The deleted property is an array with nodenames, that have been deleted
750
-	 * from collection.
751
-	 *
752
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
753
-	 * 1, you only have to report changes that happened only directly in
754
-	 * immediate descendants. If it's 2, it should also include changes from
755
-	 * the nodes below the child collections. (grandchildren)
756
-	 *
757
-	 * The $limit argument allows a client to specify how many results should
758
-	 * be returned at most. If the limit is not specified, it should be treated
759
-	 * as infinite.
760
-	 *
761
-	 * If the limit (infinite or not) is higher than you're willing to return,
762
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
763
-	 *
764
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
765
-	 * return null.
766
-	 *
767
-	 * The limit is 'suggestive'. You are free to ignore it.
768
-	 *
769
-	 * @param string $addressBookId
770
-	 * @param string $syncToken
771
-	 * @param int $syncLevel
772
-	 * @param int $limit
773
-	 * @return array
774
-	 */
775
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
776
-		// Current synctoken
777
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
778
-		$stmt->execute([ $addressBookId ]);
779
-		$currentToken = $stmt->fetchColumn(0);
780
-
781
-		if (is_null($currentToken)) return null;
782
-
783
-		$result = [
784
-			'syncToken' => $currentToken,
785
-			'added'     => [],
786
-			'modified'  => [],
787
-			'deleted'   => [],
788
-		];
789
-
790
-		if ($syncToken) {
791
-
792
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
793
-			if ($limit>0) {
794
-				$query .= " `LIMIT` " . (int)$limit;
795
-			}
796
-
797
-			// Fetching all changes
798
-			$stmt = $this->db->prepare($query);
799
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
800
-
801
-			$changes = [];
802
-
803
-			// This loop ensures that any duplicates are overwritten, only the
804
-			// last change on a node is relevant.
805
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
806
-
807
-				$changes[$row['uri']] = $row['operation'];
808
-
809
-			}
810
-
811
-			foreach($changes as $uri => $operation) {
812
-
813
-				switch($operation) {
814
-					case 1:
815
-						$result['added'][] = $uri;
816
-						break;
817
-					case 2:
818
-						$result['modified'][] = $uri;
819
-						break;
820
-					case 3:
821
-						$result['deleted'][] = $uri;
822
-						break;
823
-				}
824
-
825
-			}
826
-		} else {
827
-			// No synctoken supplied, this is the initial sync.
828
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
829
-			$stmt = $this->db->prepare($query);
830
-			$stmt->execute([$addressBookId]);
831
-
832
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
833
-		}
834
-		return $result;
835
-	}
836
-
837
-	/**
838
-	 * Adds a change record to the addressbookchanges table.
839
-	 *
840
-	 * @param mixed $addressBookId
841
-	 * @param string $objectUri
842
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
843
-	 * @return void
844
-	 */
845
-	protected function addChange($addressBookId, $objectUri, $operation) {
846
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
847
-		$stmt = $this->db->prepare($sql);
848
-		$stmt->execute([
849
-			$objectUri,
850
-			$addressBookId,
851
-			$operation,
852
-			$addressBookId
853
-		]);
854
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
855
-		$stmt->execute([
856
-			$addressBookId
857
-		]);
858
-	}
859
-
860
-	private function readBlob($cardData) {
861
-		if (is_resource($cardData)) {
862
-			return stream_get_contents($cardData);
863
-		}
864
-
865
-		return $cardData;
866
-	}
867
-
868
-	/**
869
-	 * @param IShareable $shareable
870
-	 * @param string[] $add
871
-	 * @param string[] $remove
872
-	 */
873
-	public function updateShares(IShareable $shareable, $add, $remove) {
874
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
875
-	}
876
-
877
-	/**
878
-	 * search contact
879
-	 *
880
-	 * @param int $addressBookId
881
-	 * @param string $pattern which should match within the $searchProperties
882
-	 * @param array $searchProperties defines the properties within the query pattern should match
883
-	 * @return array an array of contacts which are arrays of key-value-pairs
884
-	 */
885
-	public function search($addressBookId, $pattern, $searchProperties) {
886
-		$query = $this->db->getQueryBuilder();
887
-		$query2 = $this->db->getQueryBuilder();
888
-
889
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
890
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
891
-		$or = $query2->expr()->orX();
892
-		foreach ($searchProperties as $property) {
893
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
894
-		}
895
-		$query2->andWhere($or);
896
-
897
-		// No need for like when the pattern is empty
898
-		if ('' !== $pattern) {
899
-			$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
900
-		}
901
-
902
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
903
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
904
-
905
-		$result = $query->execute();
906
-		$cards = $result->fetchAll();
907
-
908
-		$result->closeCursor();
909
-
910
-		return array_map(function($array) {
911
-			$array['carddata'] = $this->readBlob($array['carddata']);
912
-			return $array;
913
-		}, $cards);
914
-	}
915
-
916
-	/**
917
-	 * @param int $bookId
918
-	 * @param string $name
919
-	 * @return array
920
-	 */
921
-	public function collectCardProperties($bookId, $name) {
922
-		$query = $this->db->getQueryBuilder();
923
-		$result = $query->selectDistinct('value')
924
-			->from($this->dbCardsPropertiesTable)
925
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
926
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
927
-			->execute();
928
-
929
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
930
-		$result->closeCursor();
931
-
932
-		return $all;
933
-	}
934
-
935
-	/**
936
-	 * get URI from a given contact
937
-	 *
938
-	 * @param int $id
939
-	 * @return string
940
-	 */
941
-	public function getCardUri($id) {
942
-		$query = $this->db->getQueryBuilder();
943
-		$query->select('uri')->from($this->dbCardsTable)
944
-				->where($query->expr()->eq('id', $query->createParameter('id')))
945
-				->setParameter('id', $id);
946
-
947
-		$result = $query->execute();
948
-		$uri = $result->fetch();
949
-		$result->closeCursor();
950
-
951
-		if (!isset($uri['uri'])) {
952
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
953
-		}
954
-
955
-		return $uri['uri'];
956
-	}
957
-
958
-	/**
959
-	 * return contact with the given URI
960
-	 *
961
-	 * @param int $addressBookId
962
-	 * @param string $uri
963
-	 * @returns array
964
-	 */
965
-	public function getContact($addressBookId, $uri) {
966
-		$result = [];
967
-		$query = $this->db->getQueryBuilder();
968
-		$query->select('*')->from($this->dbCardsTable)
969
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
970
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
971
-		$queryResult = $query->execute();
972
-		$contact = $queryResult->fetch();
973
-		$queryResult->closeCursor();
974
-
975
-		if (is_array($contact)) {
976
-			$result = $contact;
977
-		}
978
-
979
-		return $result;
980
-	}
981
-
982
-	/**
983
-	 * Returns the list of people whom this address book is shared with.
984
-	 *
985
-	 * Every element in this array should have the following properties:
986
-	 *   * href - Often a mailto: address
987
-	 *   * commonName - Optional, for example a first + last name
988
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
989
-	 *   * readOnly - boolean
990
-	 *   * summary - Optional, a description for the share
991
-	 *
992
-	 * @return array
993
-	 */
994
-	public function getShares($addressBookId) {
995
-		return $this->sharingBackend->getShares($addressBookId);
996
-	}
997
-
998
-	/**
999
-	 * update properties table
1000
-	 *
1001
-	 * @param int $addressBookId
1002
-	 * @param string $cardUri
1003
-	 * @param string $vCardSerialized
1004
-	 */
1005
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1006
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1007
-		$vCard = $this->readCard($vCardSerialized);
1008
-
1009
-		$this->purgeProperties($addressBookId, $cardId);
1010
-
1011
-		$query = $this->db->getQueryBuilder();
1012
-		$query->insert($this->dbCardsPropertiesTable)
1013
-			->values(
1014
-				[
1015
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1016
-					'cardid' => $query->createNamedParameter($cardId),
1017
-					'name' => $query->createParameter('name'),
1018
-					'value' => $query->createParameter('value'),
1019
-					'preferred' => $query->createParameter('preferred')
1020
-				]
1021
-			);
1022
-
1023
-		foreach ($vCard->children() as $property) {
1024
-			if(!in_array($property->name, self::$indexProperties)) {
1025
-				continue;
1026
-			}
1027
-			$preferred = 0;
1028
-			foreach($property->parameters as $parameter) {
1029
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1030
-					$preferred = 1;
1031
-					break;
1032
-				}
1033
-			}
1034
-			$query->setParameter('name', $property->name);
1035
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1036
-			$query->setParameter('preferred', $preferred);
1037
-			$query->execute();
1038
-		}
1039
-	}
1040
-
1041
-	/**
1042
-	 * read vCard data into a vCard object
1043
-	 *
1044
-	 * @param string $cardData
1045
-	 * @return VCard
1046
-	 */
1047
-	protected function readCard($cardData) {
1048
-		return  Reader::read($cardData);
1049
-	}
1050
-
1051
-	/**
1052
-	 * delete all properties from a given card
1053
-	 *
1054
-	 * @param int $addressBookId
1055
-	 * @param int $cardId
1056
-	 */
1057
-	protected function purgeProperties($addressBookId, $cardId) {
1058
-		$query = $this->db->getQueryBuilder();
1059
-		$query->delete($this->dbCardsPropertiesTable)
1060
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1061
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1062
-		$query->execute();
1063
-	}
1064
-
1065
-	/**
1066
-	 * get ID from a given contact
1067
-	 *
1068
-	 * @param int $addressBookId
1069
-	 * @param string $uri
1070
-	 * @return int
1071
-	 */
1072
-	protected function getCardId($addressBookId, $uri) {
1073
-		$query = $this->db->getQueryBuilder();
1074
-		$query->select('id')->from($this->dbCardsTable)
1075
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1076
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1077
-
1078
-		$result = $query->execute();
1079
-		$cardIds = $result->fetch();
1080
-		$result->closeCursor();
1081
-
1082
-		if (!isset($cardIds['id'])) {
1083
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1084
-		}
1085
-
1086
-		return (int)$cardIds['id'];
1087
-	}
1088
-
1089
-	/**
1090
-	 * For shared address books the sharee is set in the ACL of the address book
1091
-	 * @param $addressBookId
1092
-	 * @param $acl
1093
-	 * @return array
1094
-	 */
1095
-	public function applyShareAcl($addressBookId, $acl) {
1096
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1097
-	}
1098
-
1099
-	private function convertPrincipal($principalUri, $toV2) {
1100
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1101
-			list(, $name) = \Sabre\Uri\split($principalUri);
1102
-			if ($toV2 === true) {
1103
-				return "principals/users/$name";
1104
-			}
1105
-			return "principals/$name";
1106
-		}
1107
-		return $principalUri;
1108
-	}
1109
-
1110
-	private function addOwnerPrincipal(&$addressbookInfo) {
1111
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1112
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1113
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1114
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1115
-		} else {
1116
-			$uri = $addressbookInfo['principaluri'];
1117
-		}
1118
-
1119
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1120
-		if (isset($principalInformation['{DAV:}displayname'])) {
1121
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1122
-		}
1123
-	}
52
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
53
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
54
+
55
+    /** @var Principal */
56
+    private $principalBackend;
57
+
58
+    /** @var string */
59
+    private $dbCardsTable = 'cards';
60
+
61
+    /** @var string */
62
+    private $dbCardsPropertiesTable = 'cards_properties';
63
+
64
+    /** @var IDBConnection */
65
+    private $db;
66
+
67
+    /** @var Backend */
68
+    private $sharingBackend;
69
+
70
+    /** @var array properties to index */
71
+    public static $indexProperties = array(
72
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
73
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
74
+
75
+    /**
76
+     * @var string[] Map of uid => display name
77
+     */
78
+    protected $userDisplayNames;
79
+
80
+    /** @var IUserManager */
81
+    private $userManager;
82
+
83
+    /** @var EventDispatcherInterface */
84
+    private $dispatcher;
85
+
86
+    /**
87
+     * CardDavBackend constructor.
88
+     *
89
+     * @param IDBConnection $db
90
+     * @param Principal $principalBackend
91
+     * @param IUserManager $userManager
92
+     * @param IGroupManager $groupManager
93
+     * @param EventDispatcherInterface $dispatcher
94
+     */
95
+    public function __construct(IDBConnection $db,
96
+                                Principal $principalBackend,
97
+                                IUserManager $userManager,
98
+                                IGroupManager $groupManager,
99
+                                EventDispatcherInterface $dispatcher) {
100
+        $this->db = $db;
101
+        $this->principalBackend = $principalBackend;
102
+        $this->userManager = $userManager;
103
+        $this->dispatcher = $dispatcher;
104
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
105
+    }
106
+
107
+    /**
108
+     * Return the number of address books for a principal
109
+     *
110
+     * @param $principalUri
111
+     * @return int
112
+     */
113
+    public function getAddressBooksForUserCount($principalUri) {
114
+        $principalUri = $this->convertPrincipal($principalUri, true);
115
+        $query = $this->db->getQueryBuilder();
116
+        $query->select($query->createFunction('COUNT(*)'))
117
+            ->from('addressbooks')
118
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
119
+
120
+        return (int)$query->execute()->fetchColumn();
121
+    }
122
+
123
+    /**
124
+     * Returns the list of address books for a specific user.
125
+     *
126
+     * Every addressbook should have the following properties:
127
+     *   id - an arbitrary unique id
128
+     *   uri - the 'basename' part of the url
129
+     *   principaluri - Same as the passed parameter
130
+     *
131
+     * Any additional clark-notation property may be passed besides this. Some
132
+     * common ones are :
133
+     *   {DAV:}displayname
134
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
135
+     *   {http://calendarserver.org/ns/}getctag
136
+     *
137
+     * @param string $principalUri
138
+     * @return array
139
+     */
140
+    function getAddressBooksForUser($principalUri) {
141
+        $principalUriOriginal = $principalUri;
142
+        $principalUri = $this->convertPrincipal($principalUri, true);
143
+        $query = $this->db->getQueryBuilder();
144
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
145
+            ->from('addressbooks')
146
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
147
+
148
+        $addressBooks = [];
149
+
150
+        $result = $query->execute();
151
+        while($row = $result->fetch()) {
152
+            $addressBooks[$row['id']] = [
153
+                'id'  => $row['id'],
154
+                'uri' => $row['uri'],
155
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
156
+                '{DAV:}displayname' => $row['displayname'],
157
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
158
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
159
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
160
+            ];
161
+
162
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
163
+        }
164
+        $result->closeCursor();
165
+
166
+        // query for shared calendars
167
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
168
+        $principals = array_map(function($principal) {
169
+            return urldecode($principal);
170
+        }, $principals);
171
+        $principals[]= $principalUri;
172
+
173
+        $query = $this->db->getQueryBuilder();
174
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
175
+            ->from('dav_shares', 's')
176
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
177
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
178
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
179
+            ->setParameter('type', 'addressbook')
180
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
181
+            ->execute();
182
+
183
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
184
+        while($row = $result->fetch()) {
185
+            if ($row['principaluri'] === $principalUri) {
186
+                continue;
187
+            }
188
+
189
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
190
+            if (isset($addressBooks[$row['id']])) {
191
+                if ($readOnly) {
192
+                    // New share can not have more permissions then the old one.
193
+                    continue;
194
+                }
195
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
196
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
197
+                    // Old share is already read-write, no more permissions can be gained
198
+                    continue;
199
+                }
200
+            }
201
+
202
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
203
+            $uri = $row['uri'] . '_shared_by_' . $name;
204
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
205
+
206
+            $addressBooks[$row['id']] = [
207
+                'id'  => $row['id'],
208
+                'uri' => $uri,
209
+                'principaluri' => $principalUriOriginal,
210
+                '{DAV:}displayname' => $displayName,
211
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
212
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
213
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
214
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
215
+                $readOnlyPropertyName => $readOnly,
216
+            ];
217
+
218
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
219
+        }
220
+        $result->closeCursor();
221
+
222
+        return array_values($addressBooks);
223
+    }
224
+
225
+    public function getUsersOwnAddressBooks($principalUri) {
226
+        $principalUri = $this->convertPrincipal($principalUri, true);
227
+        $query = $this->db->getQueryBuilder();
228
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
229
+                ->from('addressbooks')
230
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
231
+
232
+        $addressBooks = [];
233
+
234
+        $result = $query->execute();
235
+        while($row = $result->fetch()) {
236
+            $addressBooks[$row['id']] = [
237
+                'id'  => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
240
+                '{DAV:}displayname' => $row['displayname'],
241
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
242
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
243
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
244
+            ];
245
+
246
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
247
+        }
248
+        $result->closeCursor();
249
+
250
+        return array_values($addressBooks);
251
+    }
252
+
253
+    private function getUserDisplayName($uid) {
254
+        if (!isset($this->userDisplayNames[$uid])) {
255
+            $user = $this->userManager->get($uid);
256
+
257
+            if ($user instanceof IUser) {
258
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
259
+            } else {
260
+                $this->userDisplayNames[$uid] = $uid;
261
+            }
262
+        }
263
+
264
+        return $this->userDisplayNames[$uid];
265
+    }
266
+
267
+    /**
268
+     * @param int $addressBookId
269
+     */
270
+    public function getAddressBookById($addressBookId) {
271
+        $query = $this->db->getQueryBuilder();
272
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
273
+            ->from('addressbooks')
274
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
275
+            ->execute();
276
+
277
+        $row = $result->fetch();
278
+        $result->closeCursor();
279
+        if ($row === false) {
280
+            return null;
281
+        }
282
+
283
+        $addressBook = [
284
+            'id'  => $row['id'],
285
+            'uri' => $row['uri'],
286
+            'principaluri' => $row['principaluri'],
287
+            '{DAV:}displayname' => $row['displayname'],
288
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
289
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
290
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
291
+        ];
292
+
293
+        $this->addOwnerPrincipal($addressBook);
294
+
295
+        return $addressBook;
296
+    }
297
+
298
+    /**
299
+     * @param $addressBookUri
300
+     * @return array|null
301
+     */
302
+    public function getAddressBooksByUri($principal, $addressBookUri) {
303
+        $query = $this->db->getQueryBuilder();
304
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
305
+            ->from('addressbooks')
306
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
307
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
308
+            ->setMaxResults(1)
309
+            ->execute();
310
+
311
+        $row = $result->fetch();
312
+        $result->closeCursor();
313
+        if ($row === false) {
314
+            return null;
315
+        }
316
+
317
+        $addressBook = [
318
+            'id'  => $row['id'],
319
+            'uri' => $row['uri'],
320
+            'principaluri' => $row['principaluri'],
321
+            '{DAV:}displayname' => $row['displayname'],
322
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
323
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
324
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
325
+        ];
326
+
327
+        $this->addOwnerPrincipal($addressBook);
328
+
329
+        return $addressBook;
330
+    }
331
+
332
+    /**
333
+     * Updates properties for an address book.
334
+     *
335
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
336
+     * To do the actual updates, you must tell this object which properties
337
+     * you're going to process with the handle() method.
338
+     *
339
+     * Calling the handle method is like telling the PropPatch object "I
340
+     * promise I can handle updating this property".
341
+     *
342
+     * Read the PropPatch documentation for more info and examples.
343
+     *
344
+     * @param string $addressBookId
345
+     * @param \Sabre\DAV\PropPatch $propPatch
346
+     * @return void
347
+     */
348
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
349
+        $supportedProperties = [
350
+            '{DAV:}displayname',
351
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
352
+        ];
353
+
354
+        /**
355
+         * @suppress SqlInjectionChecker
356
+         */
357
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
358
+
359
+            $updates = [];
360
+            foreach($mutations as $property=>$newValue) {
361
+
362
+                switch($property) {
363
+                    case '{DAV:}displayname' :
364
+                        $updates['displayname'] = $newValue;
365
+                        break;
366
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
367
+                        $updates['description'] = $newValue;
368
+                        break;
369
+                }
370
+            }
371
+            $query = $this->db->getQueryBuilder();
372
+            $query->update('addressbooks');
373
+
374
+            foreach($updates as $key=>$value) {
375
+                $query->set($key, $query->createNamedParameter($value));
376
+            }
377
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
378
+            ->execute();
379
+
380
+            $this->addChange($addressBookId, "", 2);
381
+
382
+            return true;
383
+
384
+        });
385
+    }
386
+
387
+    /**
388
+     * Creates a new address book
389
+     *
390
+     * @param string $principalUri
391
+     * @param string $url Just the 'basename' of the url.
392
+     * @param array $properties
393
+     * @return int
394
+     * @throws BadRequest
395
+     */
396
+    function createAddressBook($principalUri, $url, array $properties) {
397
+        $values = [
398
+            'displayname' => null,
399
+            'description' => null,
400
+            'principaluri' => $principalUri,
401
+            'uri' => $url,
402
+            'synctoken' => 1
403
+        ];
404
+
405
+        foreach($properties as $property=>$newValue) {
406
+
407
+            switch($property) {
408
+                case '{DAV:}displayname' :
409
+                    $values['displayname'] = $newValue;
410
+                    break;
411
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
412
+                    $values['description'] = $newValue;
413
+                    break;
414
+                default :
415
+                    throw new BadRequest('Unknown property: ' . $property);
416
+            }
417
+
418
+        }
419
+
420
+        // Fallback to make sure the displayname is set. Some clients may refuse
421
+        // to work with addressbooks not having a displayname.
422
+        if(is_null($values['displayname'])) {
423
+            $values['displayname'] = $url;
424
+        }
425
+
426
+        $query = $this->db->getQueryBuilder();
427
+        $query->insert('addressbooks')
428
+            ->values([
429
+                'uri' => $query->createParameter('uri'),
430
+                'displayname' => $query->createParameter('displayname'),
431
+                'description' => $query->createParameter('description'),
432
+                'principaluri' => $query->createParameter('principaluri'),
433
+                'synctoken' => $query->createParameter('synctoken'),
434
+            ])
435
+            ->setParameters($values)
436
+            ->execute();
437
+
438
+        return $query->getLastInsertId();
439
+    }
440
+
441
+    /**
442
+     * Deletes an entire addressbook and all its contents
443
+     *
444
+     * @param mixed $addressBookId
445
+     * @return void
446
+     */
447
+    function deleteAddressBook($addressBookId) {
448
+        $query = $this->db->getQueryBuilder();
449
+        $query->delete('cards')
450
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
451
+            ->setParameter('addressbookid', $addressBookId)
452
+            ->execute();
453
+
454
+        $query->delete('addressbookchanges')
455
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
456
+            ->setParameter('addressbookid', $addressBookId)
457
+            ->execute();
458
+
459
+        $query->delete('addressbooks')
460
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
461
+            ->setParameter('id', $addressBookId)
462
+            ->execute();
463
+
464
+        $this->sharingBackend->deleteAllShares($addressBookId);
465
+
466
+        $query->delete($this->dbCardsPropertiesTable)
467
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
468
+            ->execute();
469
+
470
+    }
471
+
472
+    /**
473
+     * Returns all cards for a specific addressbook id.
474
+     *
475
+     * This method should return the following properties for each card:
476
+     *   * carddata - raw vcard data
477
+     *   * uri - Some unique url
478
+     *   * lastmodified - A unix timestamp
479
+     *
480
+     * It's recommended to also return the following properties:
481
+     *   * etag - A unique etag. This must change every time the card changes.
482
+     *   * size - The size of the card in bytes.
483
+     *
484
+     * If these last two properties are provided, less time will be spent
485
+     * calculating them. If they are specified, you can also ommit carddata.
486
+     * This may speed up certain requests, especially with large cards.
487
+     *
488
+     * @param mixed $addressBookId
489
+     * @return array
490
+     */
491
+    function getCards($addressBookId) {
492
+        $query = $this->db->getQueryBuilder();
493
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
494
+            ->from('cards')
495
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
496
+
497
+        $cards = [];
498
+
499
+        $result = $query->execute();
500
+        while($row = $result->fetch()) {
501
+            $row['etag'] = '"' . $row['etag'] . '"';
502
+            $row['carddata'] = $this->readBlob($row['carddata']);
503
+            $cards[] = $row;
504
+        }
505
+        $result->closeCursor();
506
+
507
+        return $cards;
508
+    }
509
+
510
+    /**
511
+     * Returns a specific card.
512
+     *
513
+     * The same set of properties must be returned as with getCards. The only
514
+     * exception is that 'carddata' is absolutely required.
515
+     *
516
+     * If the card does not exist, you must return false.
517
+     *
518
+     * @param mixed $addressBookId
519
+     * @param string $cardUri
520
+     * @return array
521
+     */
522
+    function getCard($addressBookId, $cardUri) {
523
+        $query = $this->db->getQueryBuilder();
524
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
525
+            ->from('cards')
526
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
527
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
528
+            ->setMaxResults(1);
529
+
530
+        $result = $query->execute();
531
+        $row = $result->fetch();
532
+        if (!$row) {
533
+            return false;
534
+        }
535
+        $row['etag'] = '"' . $row['etag'] . '"';
536
+        $row['carddata'] = $this->readBlob($row['carddata']);
537
+
538
+        return $row;
539
+    }
540
+
541
+    /**
542
+     * Returns a list of cards.
543
+     *
544
+     * This method should work identical to getCard, but instead return all the
545
+     * cards in the list as an array.
546
+     *
547
+     * If the backend supports this, it may allow for some speed-ups.
548
+     *
549
+     * @param mixed $addressBookId
550
+     * @param string[] $uris
551
+     * @return array
552
+     */
553
+    function getMultipleCards($addressBookId, array $uris) {
554
+        if (empty($uris)) {
555
+            return [];
556
+        }
557
+
558
+        $chunks = array_chunk($uris, 100);
559
+        $cards = [];
560
+
561
+        $query = $this->db->getQueryBuilder();
562
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
563
+            ->from('cards')
564
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
565
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
566
+
567
+        foreach ($chunks as $uris) {
568
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
569
+            $result = $query->execute();
570
+
571
+            while ($row = $result->fetch()) {
572
+                $row['etag'] = '"' . $row['etag'] . '"';
573
+                $row['carddata'] = $this->readBlob($row['carddata']);
574
+                $cards[] = $row;
575
+            }
576
+            $result->closeCursor();
577
+        }
578
+        return $cards;
579
+    }
580
+
581
+    /**
582
+     * Creates a new card.
583
+     *
584
+     * The addressbook id will be passed as the first argument. This is the
585
+     * same id as it is returned from the getAddressBooksForUser method.
586
+     *
587
+     * The cardUri is a base uri, and doesn't include the full path. The
588
+     * cardData argument is the vcard body, and is passed as a string.
589
+     *
590
+     * It is possible to return an ETag from this method. This ETag is for the
591
+     * newly created resource, and must be enclosed with double quotes (that
592
+     * is, the string itself must contain the double quotes).
593
+     *
594
+     * You should only return the ETag if you store the carddata as-is. If a
595
+     * subsequent GET request on the same card does not have the same body,
596
+     * byte-by-byte and you did return an ETag here, clients tend to get
597
+     * confused.
598
+     *
599
+     * If you don't return an ETag, you can just return null.
600
+     *
601
+     * @param mixed $addressBookId
602
+     * @param string $cardUri
603
+     * @param string $cardData
604
+     * @return string
605
+     */
606
+    function createCard($addressBookId, $cardUri, $cardData) {
607
+        $etag = md5($cardData);
608
+
609
+        $query = $this->db->getQueryBuilder();
610
+        $query->insert('cards')
611
+            ->values([
612
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
613
+                'uri' => $query->createNamedParameter($cardUri),
614
+                'lastmodified' => $query->createNamedParameter(time()),
615
+                'addressbookid' => $query->createNamedParameter($addressBookId),
616
+                'size' => $query->createNamedParameter(strlen($cardData)),
617
+                'etag' => $query->createNamedParameter($etag),
618
+            ])
619
+            ->execute();
620
+
621
+        $this->addChange($addressBookId, $cardUri, 1);
622
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
623
+
624
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
625
+            new GenericEvent(null, [
626
+                'addressBookId' => $addressBookId,
627
+                'cardUri' => $cardUri,
628
+                'cardData' => $cardData]));
629
+
630
+        return '"' . $etag . '"';
631
+    }
632
+
633
+    /**
634
+     * Updates a card.
635
+     *
636
+     * The addressbook id will be passed as the first argument. This is the
637
+     * same id as it is returned from the getAddressBooksForUser method.
638
+     *
639
+     * The cardUri is a base uri, and doesn't include the full path. The
640
+     * cardData argument is the vcard body, and is passed as a string.
641
+     *
642
+     * It is possible to return an ETag from this method. This ETag should
643
+     * match that of the updated resource, and must be enclosed with double
644
+     * quotes (that is: the string itself must contain the actual quotes).
645
+     *
646
+     * You should only return the ETag if you store the carddata as-is. If a
647
+     * subsequent GET request on the same card does not have the same body,
648
+     * byte-by-byte and you did return an ETag here, clients tend to get
649
+     * confused.
650
+     *
651
+     * If you don't return an ETag, you can just return null.
652
+     *
653
+     * @param mixed $addressBookId
654
+     * @param string $cardUri
655
+     * @param string $cardData
656
+     * @return string
657
+     */
658
+    function updateCard($addressBookId, $cardUri, $cardData) {
659
+
660
+        $etag = md5($cardData);
661
+        $query = $this->db->getQueryBuilder();
662
+        $query->update('cards')
663
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
664
+            ->set('lastmodified', $query->createNamedParameter(time()))
665
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
666
+            ->set('etag', $query->createNamedParameter($etag))
667
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
668
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
669
+            ->execute();
670
+
671
+        $this->addChange($addressBookId, $cardUri, 2);
672
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
673
+
674
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
675
+            new GenericEvent(null, [
676
+                'addressBookId' => $addressBookId,
677
+                'cardUri' => $cardUri,
678
+                'cardData' => $cardData]));
679
+
680
+        return '"' . $etag . '"';
681
+    }
682
+
683
+    /**
684
+     * Deletes a card
685
+     *
686
+     * @param mixed $addressBookId
687
+     * @param string $cardUri
688
+     * @return bool
689
+     */
690
+    function deleteCard($addressBookId, $cardUri) {
691
+        try {
692
+            $cardId = $this->getCardId($addressBookId, $cardUri);
693
+        } catch (\InvalidArgumentException $e) {
694
+            $cardId = null;
695
+        }
696
+        $query = $this->db->getQueryBuilder();
697
+        $ret = $query->delete('cards')
698
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
699
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
700
+            ->execute();
701
+
702
+        $this->addChange($addressBookId, $cardUri, 3);
703
+
704
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
705
+            new GenericEvent(null, [
706
+                'addressBookId' => $addressBookId,
707
+                'cardUri' => $cardUri]));
708
+
709
+        if ($ret === 1) {
710
+            if ($cardId !== null) {
711
+                $this->purgeProperties($addressBookId, $cardId);
712
+            }
713
+            return true;
714
+        }
715
+
716
+        return false;
717
+    }
718
+
719
+    /**
720
+     * The getChanges method returns all the changes that have happened, since
721
+     * the specified syncToken in the specified address book.
722
+     *
723
+     * This function should return an array, such as the following:
724
+     *
725
+     * [
726
+     *   'syncToken' => 'The current synctoken',
727
+     *   'added'   => [
728
+     *      'new.txt',
729
+     *   ],
730
+     *   'modified'   => [
731
+     *      'modified.txt',
732
+     *   ],
733
+     *   'deleted' => [
734
+     *      'foo.php.bak',
735
+     *      'old.txt'
736
+     *   ]
737
+     * ];
738
+     *
739
+     * The returned syncToken property should reflect the *current* syncToken
740
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
741
+     * property. This is needed here too, to ensure the operation is atomic.
742
+     *
743
+     * If the $syncToken argument is specified as null, this is an initial
744
+     * sync, and all members should be reported.
745
+     *
746
+     * The modified property is an array of nodenames that have changed since
747
+     * the last token.
748
+     *
749
+     * The deleted property is an array with nodenames, that have been deleted
750
+     * from collection.
751
+     *
752
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
753
+     * 1, you only have to report changes that happened only directly in
754
+     * immediate descendants. If it's 2, it should also include changes from
755
+     * the nodes below the child collections. (grandchildren)
756
+     *
757
+     * The $limit argument allows a client to specify how many results should
758
+     * be returned at most. If the limit is not specified, it should be treated
759
+     * as infinite.
760
+     *
761
+     * If the limit (infinite or not) is higher than you're willing to return,
762
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
763
+     *
764
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
765
+     * return null.
766
+     *
767
+     * The limit is 'suggestive'. You are free to ignore it.
768
+     *
769
+     * @param string $addressBookId
770
+     * @param string $syncToken
771
+     * @param int $syncLevel
772
+     * @param int $limit
773
+     * @return array
774
+     */
775
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
776
+        // Current synctoken
777
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
778
+        $stmt->execute([ $addressBookId ]);
779
+        $currentToken = $stmt->fetchColumn(0);
780
+
781
+        if (is_null($currentToken)) return null;
782
+
783
+        $result = [
784
+            'syncToken' => $currentToken,
785
+            'added'     => [],
786
+            'modified'  => [],
787
+            'deleted'   => [],
788
+        ];
789
+
790
+        if ($syncToken) {
791
+
792
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
793
+            if ($limit>0) {
794
+                $query .= " `LIMIT` " . (int)$limit;
795
+            }
796
+
797
+            // Fetching all changes
798
+            $stmt = $this->db->prepare($query);
799
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
800
+
801
+            $changes = [];
802
+
803
+            // This loop ensures that any duplicates are overwritten, only the
804
+            // last change on a node is relevant.
805
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
806
+
807
+                $changes[$row['uri']] = $row['operation'];
808
+
809
+            }
810
+
811
+            foreach($changes as $uri => $operation) {
812
+
813
+                switch($operation) {
814
+                    case 1:
815
+                        $result['added'][] = $uri;
816
+                        break;
817
+                    case 2:
818
+                        $result['modified'][] = $uri;
819
+                        break;
820
+                    case 3:
821
+                        $result['deleted'][] = $uri;
822
+                        break;
823
+                }
824
+
825
+            }
826
+        } else {
827
+            // No synctoken supplied, this is the initial sync.
828
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
829
+            $stmt = $this->db->prepare($query);
830
+            $stmt->execute([$addressBookId]);
831
+
832
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
833
+        }
834
+        return $result;
835
+    }
836
+
837
+    /**
838
+     * Adds a change record to the addressbookchanges table.
839
+     *
840
+     * @param mixed $addressBookId
841
+     * @param string $objectUri
842
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
843
+     * @return void
844
+     */
845
+    protected function addChange($addressBookId, $objectUri, $operation) {
846
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
847
+        $stmt = $this->db->prepare($sql);
848
+        $stmt->execute([
849
+            $objectUri,
850
+            $addressBookId,
851
+            $operation,
852
+            $addressBookId
853
+        ]);
854
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
855
+        $stmt->execute([
856
+            $addressBookId
857
+        ]);
858
+    }
859
+
860
+    private function readBlob($cardData) {
861
+        if (is_resource($cardData)) {
862
+            return stream_get_contents($cardData);
863
+        }
864
+
865
+        return $cardData;
866
+    }
867
+
868
+    /**
869
+     * @param IShareable $shareable
870
+     * @param string[] $add
871
+     * @param string[] $remove
872
+     */
873
+    public function updateShares(IShareable $shareable, $add, $remove) {
874
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
875
+    }
876
+
877
+    /**
878
+     * search contact
879
+     *
880
+     * @param int $addressBookId
881
+     * @param string $pattern which should match within the $searchProperties
882
+     * @param array $searchProperties defines the properties within the query pattern should match
883
+     * @return array an array of contacts which are arrays of key-value-pairs
884
+     */
885
+    public function search($addressBookId, $pattern, $searchProperties) {
886
+        $query = $this->db->getQueryBuilder();
887
+        $query2 = $this->db->getQueryBuilder();
888
+
889
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
890
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
891
+        $or = $query2->expr()->orX();
892
+        foreach ($searchProperties as $property) {
893
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
894
+        }
895
+        $query2->andWhere($or);
896
+
897
+        // No need for like when the pattern is empty
898
+        if ('' !== $pattern) {
899
+            $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
900
+        }
901
+
902
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
903
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
904
+
905
+        $result = $query->execute();
906
+        $cards = $result->fetchAll();
907
+
908
+        $result->closeCursor();
909
+
910
+        return array_map(function($array) {
911
+            $array['carddata'] = $this->readBlob($array['carddata']);
912
+            return $array;
913
+        }, $cards);
914
+    }
915
+
916
+    /**
917
+     * @param int $bookId
918
+     * @param string $name
919
+     * @return array
920
+     */
921
+    public function collectCardProperties($bookId, $name) {
922
+        $query = $this->db->getQueryBuilder();
923
+        $result = $query->selectDistinct('value')
924
+            ->from($this->dbCardsPropertiesTable)
925
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
926
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
927
+            ->execute();
928
+
929
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
930
+        $result->closeCursor();
931
+
932
+        return $all;
933
+    }
934
+
935
+    /**
936
+     * get URI from a given contact
937
+     *
938
+     * @param int $id
939
+     * @return string
940
+     */
941
+    public function getCardUri($id) {
942
+        $query = $this->db->getQueryBuilder();
943
+        $query->select('uri')->from($this->dbCardsTable)
944
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
945
+                ->setParameter('id', $id);
946
+
947
+        $result = $query->execute();
948
+        $uri = $result->fetch();
949
+        $result->closeCursor();
950
+
951
+        if (!isset($uri['uri'])) {
952
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
953
+        }
954
+
955
+        return $uri['uri'];
956
+    }
957
+
958
+    /**
959
+     * return contact with the given URI
960
+     *
961
+     * @param int $addressBookId
962
+     * @param string $uri
963
+     * @returns array
964
+     */
965
+    public function getContact($addressBookId, $uri) {
966
+        $result = [];
967
+        $query = $this->db->getQueryBuilder();
968
+        $query->select('*')->from($this->dbCardsTable)
969
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
970
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
971
+        $queryResult = $query->execute();
972
+        $contact = $queryResult->fetch();
973
+        $queryResult->closeCursor();
974
+
975
+        if (is_array($contact)) {
976
+            $result = $contact;
977
+        }
978
+
979
+        return $result;
980
+    }
981
+
982
+    /**
983
+     * Returns the list of people whom this address book is shared with.
984
+     *
985
+     * Every element in this array should have the following properties:
986
+     *   * href - Often a mailto: address
987
+     *   * commonName - Optional, for example a first + last name
988
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
989
+     *   * readOnly - boolean
990
+     *   * summary - Optional, a description for the share
991
+     *
992
+     * @return array
993
+     */
994
+    public function getShares($addressBookId) {
995
+        return $this->sharingBackend->getShares($addressBookId);
996
+    }
997
+
998
+    /**
999
+     * update properties table
1000
+     *
1001
+     * @param int $addressBookId
1002
+     * @param string $cardUri
1003
+     * @param string $vCardSerialized
1004
+     */
1005
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1006
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1007
+        $vCard = $this->readCard($vCardSerialized);
1008
+
1009
+        $this->purgeProperties($addressBookId, $cardId);
1010
+
1011
+        $query = $this->db->getQueryBuilder();
1012
+        $query->insert($this->dbCardsPropertiesTable)
1013
+            ->values(
1014
+                [
1015
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1016
+                    'cardid' => $query->createNamedParameter($cardId),
1017
+                    'name' => $query->createParameter('name'),
1018
+                    'value' => $query->createParameter('value'),
1019
+                    'preferred' => $query->createParameter('preferred')
1020
+                ]
1021
+            );
1022
+
1023
+        foreach ($vCard->children() as $property) {
1024
+            if(!in_array($property->name, self::$indexProperties)) {
1025
+                continue;
1026
+            }
1027
+            $preferred = 0;
1028
+            foreach($property->parameters as $parameter) {
1029
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1030
+                    $preferred = 1;
1031
+                    break;
1032
+                }
1033
+            }
1034
+            $query->setParameter('name', $property->name);
1035
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1036
+            $query->setParameter('preferred', $preferred);
1037
+            $query->execute();
1038
+        }
1039
+    }
1040
+
1041
+    /**
1042
+     * read vCard data into a vCard object
1043
+     *
1044
+     * @param string $cardData
1045
+     * @return VCard
1046
+     */
1047
+    protected function readCard($cardData) {
1048
+        return  Reader::read($cardData);
1049
+    }
1050
+
1051
+    /**
1052
+     * delete all properties from a given card
1053
+     *
1054
+     * @param int $addressBookId
1055
+     * @param int $cardId
1056
+     */
1057
+    protected function purgeProperties($addressBookId, $cardId) {
1058
+        $query = $this->db->getQueryBuilder();
1059
+        $query->delete($this->dbCardsPropertiesTable)
1060
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1061
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1062
+        $query->execute();
1063
+    }
1064
+
1065
+    /**
1066
+     * get ID from a given contact
1067
+     *
1068
+     * @param int $addressBookId
1069
+     * @param string $uri
1070
+     * @return int
1071
+     */
1072
+    protected function getCardId($addressBookId, $uri) {
1073
+        $query = $this->db->getQueryBuilder();
1074
+        $query->select('id')->from($this->dbCardsTable)
1075
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1076
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1077
+
1078
+        $result = $query->execute();
1079
+        $cardIds = $result->fetch();
1080
+        $result->closeCursor();
1081
+
1082
+        if (!isset($cardIds['id'])) {
1083
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1084
+        }
1085
+
1086
+        return (int)$cardIds['id'];
1087
+    }
1088
+
1089
+    /**
1090
+     * For shared address books the sharee is set in the ACL of the address book
1091
+     * @param $addressBookId
1092
+     * @param $acl
1093
+     * @return array
1094
+     */
1095
+    public function applyShareAcl($addressBookId, $acl) {
1096
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1097
+    }
1098
+
1099
+    private function convertPrincipal($principalUri, $toV2) {
1100
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1101
+            list(, $name) = \Sabre\Uri\split($principalUri);
1102
+            if ($toV2 === true) {
1103
+                return "principals/users/$name";
1104
+            }
1105
+            return "principals/$name";
1106
+        }
1107
+        return $principalUri;
1108
+    }
1109
+
1110
+    private function addOwnerPrincipal(&$addressbookInfo) {
1111
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1112
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1113
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1114
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1115
+        } else {
1116
+            $uri = $addressbookInfo['principaluri'];
1117
+        }
1118
+
1119
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1120
+        if (isset($principalInformation['{DAV:}displayname'])) {
1121
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1122
+        }
1123
+    }
1124 1124
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/UserAddressBooks.php 2 patches
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -25,52 +25,52 @@
 block discarded – undo
25 25
 
26 26
 class UserAddressBooks extends \Sabre\CardDAV\AddressBookHome {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * Returns a list of addressbooks
33
-	 *
34
-	 * @return array
35
-	 */
36
-	function getChildren() {
37
-		if ($this->l10n === null) {
38
-			$this->l10n = \OC::$server->getL10N('dav');
39
-		}
31
+    /**
32
+     * Returns a list of addressbooks
33
+     *
34
+     * @return array
35
+     */
36
+    function getChildren() {
37
+        if ($this->l10n === null) {
38
+            $this->l10n = \OC::$server->getL10N('dav');
39
+        }
40 40
 
41
-		$addressBooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri);
42
-		$objects = [];
43
-		foreach($addressBooks as $addressBook) {
44
-			$objects[] = new AddressBook($this->carddavBackend, $addressBook, $this->l10n);
45
-		}
46
-		return $objects;
41
+        $addressBooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri);
42
+        $objects = [];
43
+        foreach($addressBooks as $addressBook) {
44
+            $objects[] = new AddressBook($this->carddavBackend, $addressBook, $this->l10n);
45
+        }
46
+        return $objects;
47 47
 
48
-	}
48
+    }
49 49
 
50
-	/**
51
-	 * Returns a list of ACE's for this node.
52
-	 *
53
-	 * Each ACE has the following properties:
54
-	 *   * 'privilege', a string such as {DAV:}read or {DAV:}write. These are
55
-	 *     currently the only supported privileges
56
-	 *   * 'principal', a url to the principal who owns the node
57
-	 *   * 'protected' (optional), indicating that this ACE is not allowed to
58
-	 *      be updated.
59
-	 *
60
-	 * @return array
61
-	 */
62
-	function getACL() {
50
+    /**
51
+     * Returns a list of ACE's for this node.
52
+     *
53
+     * Each ACE has the following properties:
54
+     *   * 'privilege', a string such as {DAV:}read or {DAV:}write. These are
55
+     *     currently the only supported privileges
56
+     *   * 'principal', a url to the principal who owns the node
57
+     *   * 'protected' (optional), indicating that this ACE is not allowed to
58
+     *      be updated.
59
+     *
60
+     * @return array
61
+     */
62
+    function getACL() {
63 63
 
64
-		$acl = parent::getACL();
65
-		if ($this->principalUri === 'principals/system/system') {
66
-			$acl[] = [
67
-					'privilege' => '{DAV:}read',
68
-					'principal' => '{DAV:}authenticated',
69
-					'protected' => true,
70
-			];
71
-		}
64
+        $acl = parent::getACL();
65
+        if ($this->principalUri === 'principals/system/system') {
66
+            $acl[] = [
67
+                    'privilege' => '{DAV:}read',
68
+                    'principal' => '{DAV:}authenticated',
69
+                    'protected' => true,
70
+            ];
71
+        }
72 72
 
73
-		return $acl;
74
-	}
73
+        return $acl;
74
+    }
75 75
 
76 76
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@
 block discarded – undo
40 40
 
41 41
 		$addressBooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri);
42 42
 		$objects = [];
43
-		foreach($addressBooks as $addressBook) {
43
+		foreach ($addressBooks as $addressBook) {
44 44
 			$objects[] = new AddressBook($this->carddavBackend, $addressBook, $this->l10n);
45 45
 		}
46 46
 		return $objects;
Please login to merge, or discard this patch.