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