Completed
Push — master ( 4dab01...3e37a5 )
by Morris
11:50
created
apps/dav/lib/CardDAV/CardDavBackend.php 2 patches
Indentation   +1066 added lines, -1066 removed lines patch added patch discarded remove patch
@@ -48,1070 +48,1070 @@
 block discarded – undo
48 48
 
49 49
 class CardDavBackend implements BackendInterface, SyncSupport {
50 50
 
51
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
-
54
-	/** @var Principal */
55
-	private $principalBackend;
56
-
57
-	/** @var string */
58
-	private $dbCardsTable = 'cards';
59
-
60
-	/** @var string */
61
-	private $dbCardsPropertiesTable = 'cards_properties';
62
-
63
-	/** @var IDBConnection */
64
-	private $db;
65
-
66
-	/** @var Backend */
67
-	private $sharingBackend;
68
-
69
-	/** @var array properties to index */
70
-	public static $indexProperties = array(
71
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
-
74
-	/**
75
-	 * @var string[] Map of uid => display name
76
-	 */
77
-	protected $userDisplayNames;
78
-
79
-	/** @var IUserManager */
80
-	private $userManager;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	/**
86
-	 * CardDavBackend constructor.
87
-	 *
88
-	 * @param IDBConnection $db
89
-	 * @param Principal $principalBackend
90
-	 * @param IUserManager $userManager
91
-	 * @param EventDispatcherInterface $dispatcher
92
-	 */
93
-	public function __construct(IDBConnection $db,
94
-								Principal $principalBackend,
95
-								IUserManager $userManager,
96
-								EventDispatcherInterface $dispatcher = null) {
97
-		$this->db = $db;
98
-		$this->principalBackend = $principalBackend;
99
-		$this->userManager = $userManager;
100
-		$this->dispatcher = $dispatcher;
101
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
-	}
103
-
104
-	/**
105
-	 * Return the number of address books for a principal
106
-	 *
107
-	 * @param $principalUri
108
-	 * @return int
109
-	 */
110
-	public function getAddressBooksForUserCount($principalUri) {
111
-		$principalUri = $this->convertPrincipal($principalUri, true);
112
-		$query = $this->db->getQueryBuilder();
113
-		$query->select($query->createFunction('COUNT(*)'))
114
-			->from('addressbooks')
115
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
-
117
-		return (int)$query->execute()->fetchColumn();
118
-	}
119
-
120
-	/**
121
-	 * Returns the list of address books for a specific user.
122
-	 *
123
-	 * Every addressbook should have the following properties:
124
-	 *   id - an arbitrary unique id
125
-	 *   uri - the 'basename' part of the url
126
-	 *   principaluri - Same as the passed parameter
127
-	 *
128
-	 * Any additional clark-notation property may be passed besides this. Some
129
-	 * common ones are :
130
-	 *   {DAV:}displayname
131
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
-	 *   {http://calendarserver.org/ns/}getctag
133
-	 *
134
-	 * @param string $principalUri
135
-	 * @return array
136
-	 */
137
-	function getAddressBooksForUser($principalUri) {
138
-		$principalUriOriginal = $principalUri;
139
-		$principalUri = $this->convertPrincipal($principalUri, true);
140
-		$query = $this->db->getQueryBuilder();
141
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
-			->from('addressbooks')
143
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
-
145
-		$addressBooks = [];
146
-
147
-		$result = $query->execute();
148
-		while($row = $result->fetch()) {
149
-			$addressBooks[$row['id']] = [
150
-				'id'  => $row['id'],
151
-				'uri' => $row['uri'],
152
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
-				'{DAV:}displayname' => $row['displayname'],
154
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
-			];
158
-
159
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
160
-		}
161
-		$result->closeCursor();
162
-
163
-		// query for shared calendars
164
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
165
-		$principals[]= $principalUri;
166
-
167
-		$query = $this->db->getQueryBuilder();
168
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
169
-			->from('dav_shares', 's')
170
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
171
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
172
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
173
-			->setParameter('type', 'addressbook')
174
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
175
-			->execute();
176
-
177
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
178
-		while($row = $result->fetch()) {
179
-			if ($row['principaluri'] === $principalUri) {
180
-				continue;
181
-			}
182
-
183
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
184
-			if (isset($addressBooks[$row['id']])) {
185
-				if ($readOnly) {
186
-					// New share can not have more permissions then the old one.
187
-					continue;
188
-				}
189
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
190
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
191
-					// Old share is already read-write, no more permissions can be gained
192
-					continue;
193
-				}
194
-			}
195
-
196
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
197
-			$uri = $row['uri'] . '_shared_by_' . $name;
198
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
199
-
200
-			$addressBooks[$row['id']] = [
201
-				'id'  => $row['id'],
202
-				'uri' => $uri,
203
-				'principaluri' => $principalUriOriginal,
204
-				'{DAV:}displayname' => $displayName,
205
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
206
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
207
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
208
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
209
-				$readOnlyPropertyName => $readOnly,
210
-			];
211
-
212
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
213
-		}
214
-		$result->closeCursor();
215
-
216
-		return array_values($addressBooks);
217
-	}
218
-
219
-	public function getUsersOwnAddressBooks($principalUri) {
220
-		$principalUri = $this->convertPrincipal($principalUri, true);
221
-		$query = $this->db->getQueryBuilder();
222
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
223
-			  ->from('addressbooks')
224
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
225
-
226
-		$addressBooks = [];
227
-
228
-		$result = $query->execute();
229
-		while($row = $result->fetch()) {
230
-			$addressBooks[$row['id']] = [
231
-				'id'  => $row['id'],
232
-				'uri' => $row['uri'],
233
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
234
-				'{DAV:}displayname' => $row['displayname'],
235
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
236
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
237
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
238
-			];
239
-
240
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
241
-		}
242
-		$result->closeCursor();
243
-
244
-		return array_values($addressBooks);
245
-	}
246
-
247
-	private function getUserDisplayName($uid) {
248
-		if (!isset($this->userDisplayNames[$uid])) {
249
-			$user = $this->userManager->get($uid);
250
-
251
-			if ($user instanceof IUser) {
252
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
253
-			} else {
254
-				$this->userDisplayNames[$uid] = $uid;
255
-			}
256
-		}
257
-
258
-		return $this->userDisplayNames[$uid];
259
-	}
260
-
261
-	/**
262
-	 * @param int $addressBookId
263
-	 */
264
-	public function getAddressBookById($addressBookId) {
265
-		$query = $this->db->getQueryBuilder();
266
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
267
-			->from('addressbooks')
268
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
269
-			->execute();
270
-
271
-		$row = $result->fetch();
272
-		$result->closeCursor();
273
-		if ($row === false) {
274
-			return null;
275
-		}
276
-
277
-		$addressBook = [
278
-			'id'  => $row['id'],
279
-			'uri' => $row['uri'],
280
-			'principaluri' => $row['principaluri'],
281
-			'{DAV:}displayname' => $row['displayname'],
282
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
283
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
284
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
285
-		];
286
-
287
-		$this->addOwnerPrincipal($addressBook);
288
-
289
-		return $addressBook;
290
-	}
291
-
292
-	/**
293
-	 * @param $addressBookUri
294
-	 * @return array|null
295
-	 */
296
-	public function getAddressBooksByUri($principal, $addressBookUri) {
297
-		$query = $this->db->getQueryBuilder();
298
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
299
-			->from('addressbooks')
300
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
301
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
302
-			->setMaxResults(1)
303
-			->execute();
304
-
305
-		$row = $result->fetch();
306
-		$result->closeCursor();
307
-		if ($row === false) {
308
-			return null;
309
-		}
310
-
311
-		$addressBook = [
312
-			'id'  => $row['id'],
313
-			'uri' => $row['uri'],
314
-			'principaluri' => $row['principaluri'],
315
-			'{DAV:}displayname' => $row['displayname'],
316
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
317
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
318
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
319
-		];
320
-
321
-		$this->addOwnerPrincipal($addressBook);
322
-
323
-		return $addressBook;
324
-	}
325
-
326
-	/**
327
-	 * Updates properties for an address book.
328
-	 *
329
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
330
-	 * To do the actual updates, you must tell this object which properties
331
-	 * you're going to process with the handle() method.
332
-	 *
333
-	 * Calling the handle method is like telling the PropPatch object "I
334
-	 * promise I can handle updating this property".
335
-	 *
336
-	 * Read the PropPatch documentation for more info and examples.
337
-	 *
338
-	 * @param string $addressBookId
339
-	 * @param \Sabre\DAV\PropPatch $propPatch
340
-	 * @return void
341
-	 */
342
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
343
-		$supportedProperties = [
344
-			'{DAV:}displayname',
345
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
346
-		];
347
-
348
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
349
-
350
-			$updates = [];
351
-			foreach($mutations as $property=>$newValue) {
352
-
353
-				switch($property) {
354
-					case '{DAV:}displayname' :
355
-						$updates['displayname'] = $newValue;
356
-						break;
357
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
358
-						$updates['description'] = $newValue;
359
-						break;
360
-				}
361
-			}
362
-			$query = $this->db->getQueryBuilder();
363
-			$query->update('addressbooks');
364
-
365
-			foreach($updates as $key=>$value) {
366
-				$query->set($key, $query->createNamedParameter($value));
367
-			}
368
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
369
-			->execute();
370
-
371
-			$this->addChange($addressBookId, "", 2);
372
-
373
-			return true;
374
-
375
-		});
376
-	}
377
-
378
-	/**
379
-	 * Creates a new address book
380
-	 *
381
-	 * @param string $principalUri
382
-	 * @param string $url Just the 'basename' of the url.
383
-	 * @param array $properties
384
-	 * @return int
385
-	 * @throws BadRequest
386
-	 */
387
-	function createAddressBook($principalUri, $url, array $properties) {
388
-		$values = [
389
-			'displayname' => null,
390
-			'description' => null,
391
-			'principaluri' => $principalUri,
392
-			'uri' => $url,
393
-			'synctoken' => 1
394
-		];
395
-
396
-		foreach($properties as $property=>$newValue) {
397
-
398
-			switch($property) {
399
-				case '{DAV:}displayname' :
400
-					$values['displayname'] = $newValue;
401
-					break;
402
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
403
-					$values['description'] = $newValue;
404
-					break;
405
-				default :
406
-					throw new BadRequest('Unknown property: ' . $property);
407
-			}
408
-
409
-		}
410
-
411
-		// Fallback to make sure the displayname is set. Some clients may refuse
412
-		// to work with addressbooks not having a displayname.
413
-		if(is_null($values['displayname'])) {
414
-			$values['displayname'] = $url;
415
-		}
416
-
417
-		$query = $this->db->getQueryBuilder();
418
-		$query->insert('addressbooks')
419
-			->values([
420
-				'uri' => $query->createParameter('uri'),
421
-				'displayname' => $query->createParameter('displayname'),
422
-				'description' => $query->createParameter('description'),
423
-				'principaluri' => $query->createParameter('principaluri'),
424
-				'synctoken' => $query->createParameter('synctoken'),
425
-			])
426
-			->setParameters($values)
427
-			->execute();
428
-
429
-		return $query->getLastInsertId();
430
-	}
431
-
432
-	/**
433
-	 * Deletes an entire addressbook and all its contents
434
-	 *
435
-	 * @param mixed $addressBookId
436
-	 * @return void
437
-	 */
438
-	function deleteAddressBook($addressBookId) {
439
-		$query = $this->db->getQueryBuilder();
440
-		$query->delete('cards')
441
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
442
-			->setParameter('addressbookid', $addressBookId)
443
-			->execute();
444
-
445
-		$query->delete('addressbookchanges')
446
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
447
-			->setParameter('addressbookid', $addressBookId)
448
-			->execute();
449
-
450
-		$query->delete('addressbooks')
451
-			->where($query->expr()->eq('id', $query->createParameter('id')))
452
-			->setParameter('id', $addressBookId)
453
-			->execute();
454
-
455
-		$this->sharingBackend->deleteAllShares($addressBookId);
456
-
457
-		$query->delete($this->dbCardsPropertiesTable)
458
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
459
-			->execute();
460
-
461
-	}
462
-
463
-	/**
464
-	 * Returns all cards for a specific addressbook id.
465
-	 *
466
-	 * This method should return the following properties for each card:
467
-	 *   * carddata - raw vcard data
468
-	 *   * uri - Some unique url
469
-	 *   * lastmodified - A unix timestamp
470
-	 *
471
-	 * It's recommended to also return the following properties:
472
-	 *   * etag - A unique etag. This must change every time the card changes.
473
-	 *   * size - The size of the card in bytes.
474
-	 *
475
-	 * If these last two properties are provided, less time will be spent
476
-	 * calculating them. If they are specified, you can also ommit carddata.
477
-	 * This may speed up certain requests, especially with large cards.
478
-	 *
479
-	 * @param mixed $addressBookId
480
-	 * @return array
481
-	 */
482
-	function getCards($addressBookId) {
483
-		$query = $this->db->getQueryBuilder();
484
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
485
-			->from('cards')
486
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
487
-
488
-		$cards = [];
489
-
490
-		$result = $query->execute();
491
-		while($row = $result->fetch()) {
492
-			$row['etag'] = '"' . $row['etag'] . '"';
493
-			$row['carddata'] = $this->readBlob($row['carddata']);
494
-			$cards[] = $row;
495
-		}
496
-		$result->closeCursor();
497
-
498
-		return $cards;
499
-	}
500
-
501
-	/**
502
-	 * Returns a specific card.
503
-	 *
504
-	 * The same set of properties must be returned as with getCards. The only
505
-	 * exception is that 'carddata' is absolutely required.
506
-	 *
507
-	 * If the card does not exist, you must return false.
508
-	 *
509
-	 * @param mixed $addressBookId
510
-	 * @param string $cardUri
511
-	 * @return array
512
-	 */
513
-	function getCard($addressBookId, $cardUri) {
514
-		$query = $this->db->getQueryBuilder();
515
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
516
-			->from('cards')
517
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
518
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
519
-			->setMaxResults(1);
520
-
521
-		$result = $query->execute();
522
-		$row = $result->fetch();
523
-		if (!$row) {
524
-			return false;
525
-		}
526
-		$row['etag'] = '"' . $row['etag'] . '"';
527
-		$row['carddata'] = $this->readBlob($row['carddata']);
528
-
529
-		return $row;
530
-	}
531
-
532
-	/**
533
-	 * Returns a list of cards.
534
-	 *
535
-	 * This method should work identical to getCard, but instead return all the
536
-	 * cards in the list as an array.
537
-	 *
538
-	 * If the backend supports this, it may allow for some speed-ups.
539
-	 *
540
-	 * @param mixed $addressBookId
541
-	 * @param string[] $uris
542
-	 * @return array
543
-	 */
544
-	function getMultipleCards($addressBookId, array $uris) {
545
-		if (empty($uris)) {
546
-			return [];
547
-		}
548
-
549
-		$chunks = array_chunk($uris, 100);
550
-		$cards = [];
551
-
552
-		$query = $this->db->getQueryBuilder();
553
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
554
-			->from('cards')
555
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
556
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
557
-
558
-		foreach ($chunks as $uris) {
559
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
560
-			$result = $query->execute();
561
-
562
-			while ($row = $result->fetch()) {
563
-				$row['etag'] = '"' . $row['etag'] . '"';
564
-				$row['carddata'] = $this->readBlob($row['carddata']);
565
-				$cards[] = $row;
566
-			}
567
-			$result->closeCursor();
568
-		}
569
-		return $cards;
570
-	}
571
-
572
-	/**
573
-	 * Creates a new card.
574
-	 *
575
-	 * The addressbook id will be passed as the first argument. This is the
576
-	 * same id as it is returned from the getAddressBooksForUser method.
577
-	 *
578
-	 * The cardUri is a base uri, and doesn't include the full path. The
579
-	 * cardData argument is the vcard body, and is passed as a string.
580
-	 *
581
-	 * It is possible to return an ETag from this method. This ETag is for the
582
-	 * newly created resource, and must be enclosed with double quotes (that
583
-	 * is, the string itself must contain the double quotes).
584
-	 *
585
-	 * You should only return the ETag if you store the carddata as-is. If a
586
-	 * subsequent GET request on the same card does not have the same body,
587
-	 * byte-by-byte and you did return an ETag here, clients tend to get
588
-	 * confused.
589
-	 *
590
-	 * If you don't return an ETag, you can just return null.
591
-	 *
592
-	 * @param mixed $addressBookId
593
-	 * @param string $cardUri
594
-	 * @param string $cardData
595
-	 * @return string
596
-	 */
597
-	function createCard($addressBookId, $cardUri, $cardData) {
598
-		$etag = md5($cardData);
599
-
600
-		$query = $this->db->getQueryBuilder();
601
-		$query->insert('cards')
602
-			->values([
603
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
604
-				'uri' => $query->createNamedParameter($cardUri),
605
-				'lastmodified' => $query->createNamedParameter(time()),
606
-				'addressbookid' => $query->createNamedParameter($addressBookId),
607
-				'size' => $query->createNamedParameter(strlen($cardData)),
608
-				'etag' => $query->createNamedParameter($etag),
609
-			])
610
-			->execute();
611
-
612
-		$this->addChange($addressBookId, $cardUri, 1);
613
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
614
-
615
-		if (!is_null($this->dispatcher)) {
616
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
617
-				new GenericEvent(null, [
618
-					'addressBookId' => $addressBookId,
619
-					'cardUri' => $cardUri,
620
-					'cardData' => $cardData]));
621
-		}
622
-
623
-		return '"' . $etag . '"';
624
-	}
625
-
626
-	/**
627
-	 * Updates a card.
628
-	 *
629
-	 * The addressbook id will be passed as the first argument. This is the
630
-	 * same id as it is returned from the getAddressBooksForUser method.
631
-	 *
632
-	 * The cardUri is a base uri, and doesn't include the full path. The
633
-	 * cardData argument is the vcard body, and is passed as a string.
634
-	 *
635
-	 * It is possible to return an ETag from this method. This ETag should
636
-	 * match that of the updated resource, and must be enclosed with double
637
-	 * quotes (that is: the string itself must contain the actual quotes).
638
-	 *
639
-	 * You should only return the ETag if you store the carddata as-is. If a
640
-	 * subsequent GET request on the same card does not have the same body,
641
-	 * byte-by-byte and you did return an ETag here, clients tend to get
642
-	 * confused.
643
-	 *
644
-	 * If you don't return an ETag, you can just return null.
645
-	 *
646
-	 * @param mixed $addressBookId
647
-	 * @param string $cardUri
648
-	 * @param string $cardData
649
-	 * @return string
650
-	 */
651
-	function updateCard($addressBookId, $cardUri, $cardData) {
652
-
653
-		$etag = md5($cardData);
654
-		$query = $this->db->getQueryBuilder();
655
-		$query->update('cards')
656
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
657
-			->set('lastmodified', $query->createNamedParameter(time()))
658
-			->set('size', $query->createNamedParameter(strlen($cardData)))
659
-			->set('etag', $query->createNamedParameter($etag))
660
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
661
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
662
-			->execute();
663
-
664
-		$this->addChange($addressBookId, $cardUri, 2);
665
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
666
-
667
-		if (!is_null($this->dispatcher)) {
668
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
669
-				new GenericEvent(null, [
670
-					'addressBookId' => $addressBookId,
671
-					'cardUri' => $cardUri,
672
-					'cardData' => $cardData]));
673
-		}
674
-
675
-		return '"' . $etag . '"';
676
-	}
677
-
678
-	/**
679
-	 * Deletes a card
680
-	 *
681
-	 * @param mixed $addressBookId
682
-	 * @param string $cardUri
683
-	 * @return bool
684
-	 */
685
-	function deleteCard($addressBookId, $cardUri) {
686
-		try {
687
-			$cardId = $this->getCardId($addressBookId, $cardUri);
688
-		} catch (\InvalidArgumentException $e) {
689
-			$cardId = null;
690
-		}
691
-		$query = $this->db->getQueryBuilder();
692
-		$ret = $query->delete('cards')
693
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
695
-			->execute();
696
-
697
-		$this->addChange($addressBookId, $cardUri, 3);
698
-
699
-		if (!is_null($this->dispatcher)) {
700
-			$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
701
-				new GenericEvent(null, [
702
-					'addressBookId' => $addressBookId,
703
-					'cardUri' => $cardUri]));
704
-		}
705
-
706
-		if ($ret === 1) {
707
-			if ($cardId !== null) {
708
-				$this->purgeProperties($addressBookId, $cardId);
709
-			}
710
-			return true;
711
-		}
712
-
713
-		return false;
714
-	}
715
-
716
-	/**
717
-	 * The getChanges method returns all the changes that have happened, since
718
-	 * the specified syncToken in the specified address book.
719
-	 *
720
-	 * This function should return an array, such as the following:
721
-	 *
722
-	 * [
723
-	 *   'syncToken' => 'The current synctoken',
724
-	 *   'added'   => [
725
-	 *      'new.txt',
726
-	 *   ],
727
-	 *   'modified'   => [
728
-	 *      'modified.txt',
729
-	 *   ],
730
-	 *   'deleted' => [
731
-	 *      'foo.php.bak',
732
-	 *      'old.txt'
733
-	 *   ]
734
-	 * ];
735
-	 *
736
-	 * The returned syncToken property should reflect the *current* syncToken
737
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
738
-	 * property. This is needed here too, to ensure the operation is atomic.
739
-	 *
740
-	 * If the $syncToken argument is specified as null, this is an initial
741
-	 * sync, and all members should be reported.
742
-	 *
743
-	 * The modified property is an array of nodenames that have changed since
744
-	 * the last token.
745
-	 *
746
-	 * The deleted property is an array with nodenames, that have been deleted
747
-	 * from collection.
748
-	 *
749
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
750
-	 * 1, you only have to report changes that happened only directly in
751
-	 * immediate descendants. If it's 2, it should also include changes from
752
-	 * the nodes below the child collections. (grandchildren)
753
-	 *
754
-	 * The $limit argument allows a client to specify how many results should
755
-	 * be returned at most. If the limit is not specified, it should be treated
756
-	 * as infinite.
757
-	 *
758
-	 * If the limit (infinite or not) is higher than you're willing to return,
759
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
760
-	 *
761
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
762
-	 * return null.
763
-	 *
764
-	 * The limit is 'suggestive'. You are free to ignore it.
765
-	 *
766
-	 * @param string $addressBookId
767
-	 * @param string $syncToken
768
-	 * @param int $syncLevel
769
-	 * @param int $limit
770
-	 * @return array
771
-	 */
772
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
773
-		// Current synctoken
774
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
775
-		$stmt->execute([ $addressBookId ]);
776
-		$currentToken = $stmt->fetchColumn(0);
777
-
778
-		if (is_null($currentToken)) return null;
779
-
780
-		$result = [
781
-			'syncToken' => $currentToken,
782
-			'added'     => [],
783
-			'modified'  => [],
784
-			'deleted'   => [],
785
-		];
786
-
787
-		if ($syncToken) {
788
-
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;
792
-			}
793
-
794
-			// Fetching all changes
795
-			$stmt = $this->db->prepare($query);
796
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
797
-
798
-			$changes = [];
799
-
800
-			// This loop ensures that any duplicates are overwritten, only the
801
-			// last change on a node is relevant.
802
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
803
-
804
-				$changes[$row['uri']] = $row['operation'];
805
-
806
-			}
807
-
808
-			foreach($changes as $uri => $operation) {
809
-
810
-				switch($operation) {
811
-					case 1:
812
-						$result['added'][] = $uri;
813
-						break;
814
-					case 2:
815
-						$result['modified'][] = $uri;
816
-						break;
817
-					case 3:
818
-						$result['deleted'][] = $uri;
819
-						break;
820
-				}
821
-
822
-			}
823
-		} else {
824
-			// No synctoken supplied, this is the initial sync.
825
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
826
-			$stmt = $this->db->prepare($query);
827
-			$stmt->execute([$addressBookId]);
828
-
829
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
830
-		}
831
-		return $result;
832
-	}
833
-
834
-	/**
835
-	 * Adds a change record to the addressbookchanges table.
836
-	 *
837
-	 * @param mixed $addressBookId
838
-	 * @param string $objectUri
839
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
840
-	 * @return void
841
-	 */
842
-	protected function addChange($addressBookId, $objectUri, $operation) {
843
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
844
-		$stmt = $this->db->prepare($sql);
845
-		$stmt->execute([
846
-			$objectUri,
847
-			$addressBookId,
848
-			$operation,
849
-			$addressBookId
850
-		]);
851
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
852
-		$stmt->execute([
853
-			$addressBookId
854
-		]);
855
-	}
856
-
857
-	private function readBlob($cardData) {
858
-		if (is_resource($cardData)) {
859
-			return stream_get_contents($cardData);
860
-		}
861
-
862
-		return $cardData;
863
-	}
864
-
865
-	/**
866
-	 * @param IShareable $shareable
867
-	 * @param string[] $add
868
-	 * @param string[] $remove
869
-	 */
870
-	public function updateShares(IShareable $shareable, $add, $remove) {
871
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
872
-	}
873
-
874
-	/**
875
-	 * search contact
876
-	 *
877
-	 * @param int $addressBookId
878
-	 * @param string $pattern which should match within the $searchProperties
879
-	 * @param array $searchProperties defines the properties within the query pattern should match
880
-	 * @return array an array of contacts which are arrays of key-value-pairs
881
-	 */
882
-	public function search($addressBookId, $pattern, $searchProperties) {
883
-		$query = $this->db->getQueryBuilder();
884
-		$query2 = $this->db->getQueryBuilder();
885
-
886
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
887
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
888
-		$or = $query2->expr()->orX();
889
-		foreach ($searchProperties as $property) {
890
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
891
-		}
892
-		$query2->andWhere($or);
893
-		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
894
-
895
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
896
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
897
-
898
-		$result = $query->execute();
899
-		$cards = $result->fetchAll();
900
-
901
-		$result->closeCursor();
902
-
903
-		return array_map(function($array) {
904
-			$array['carddata'] = $this->readBlob($array['carddata']);
905
-			return $array;
906
-		}, $cards);
907
-	}
908
-
909
-	/**
910
-	 * @param int $bookId
911
-	 * @param string $name
912
-	 * @return array
913
-	 */
914
-	public function collectCardProperties($bookId, $name) {
915
-		$query = $this->db->getQueryBuilder();
916
-		$result = $query->selectDistinct('value')
917
-			->from($this->dbCardsPropertiesTable)
918
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
919
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
920
-			->execute();
921
-
922
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
923
-		$result->closeCursor();
924
-
925
-		return $all;
926
-	}
927
-
928
-	/**
929
-	 * get URI from a given contact
930
-	 *
931
-	 * @param int $id
932
-	 * @return string
933
-	 */
934
-	public function getCardUri($id) {
935
-		$query = $this->db->getQueryBuilder();
936
-		$query->select('uri')->from($this->dbCardsTable)
937
-				->where($query->expr()->eq('id', $query->createParameter('id')))
938
-				->setParameter('id', $id);
939
-
940
-		$result = $query->execute();
941
-		$uri = $result->fetch();
942
-		$result->closeCursor();
943
-
944
-		if (!isset($uri['uri'])) {
945
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
946
-		}
947
-
948
-		return $uri['uri'];
949
-	}
950
-
951
-	/**
952
-	 * return contact with the given URI
953
-	 *
954
-	 * @param int $addressBookId
955
-	 * @param string $uri
956
-	 * @returns array
957
-	 */
958
-	public function getContact($addressBookId, $uri) {
959
-		$result = [];
960
-		$query = $this->db->getQueryBuilder();
961
-		$query->select('*')->from($this->dbCardsTable)
962
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
963
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
964
-		$queryResult = $query->execute();
965
-		$contact = $queryResult->fetch();
966
-		$queryResult->closeCursor();
967
-
968
-		if (is_array($contact)) {
969
-			$result = $contact;
970
-		}
971
-
972
-		return $result;
973
-	}
974
-
975
-	/**
976
-	 * Returns the list of people whom this address book is shared with.
977
-	 *
978
-	 * Every element in this array should have the following properties:
979
-	 *   * href - Often a mailto: address
980
-	 *   * commonName - Optional, for example a first + last name
981
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
982
-	 *   * readOnly - boolean
983
-	 *   * summary - Optional, a description for the share
984
-	 *
985
-	 * @return array
986
-	 */
987
-	public function getShares($addressBookId) {
988
-		return $this->sharingBackend->getShares($addressBookId);
989
-	}
990
-
991
-	/**
992
-	 * update properties table
993
-	 *
994
-	 * @param int $addressBookId
995
-	 * @param string $cardUri
996
-	 * @param string $vCardSerialized
997
-	 */
998
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
999
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1000
-		$vCard = $this->readCard($vCardSerialized);
1001
-
1002
-		$this->purgeProperties($addressBookId, $cardId);
1003
-
1004
-		$query = $this->db->getQueryBuilder();
1005
-		$query->insert($this->dbCardsPropertiesTable)
1006
-			->values(
1007
-				[
1008
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1009
-					'cardid' => $query->createNamedParameter($cardId),
1010
-					'name' => $query->createParameter('name'),
1011
-					'value' => $query->createParameter('value'),
1012
-					'preferred' => $query->createParameter('preferred')
1013
-				]
1014
-			);
1015
-
1016
-		foreach ($vCard->children() as $property) {
1017
-			if(!in_array($property->name, self::$indexProperties)) {
1018
-				continue;
1019
-			}
1020
-			$preferred = 0;
1021
-			foreach($property->parameters as $parameter) {
1022
-				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1023
-					$preferred = 1;
1024
-					break;
1025
-				}
1026
-			}
1027
-			$query->setParameter('name', $property->name);
1028
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1029
-			$query->setParameter('preferred', $preferred);
1030
-			$query->execute();
1031
-		}
1032
-	}
1033
-
1034
-	/**
1035
-	 * read vCard data into a vCard object
1036
-	 *
1037
-	 * @param string $cardData
1038
-	 * @return VCard
1039
-	 */
1040
-	protected function readCard($cardData) {
1041
-		return  Reader::read($cardData);
1042
-	}
1043
-
1044
-	/**
1045
-	 * delete all properties from a given card
1046
-	 *
1047
-	 * @param int $addressBookId
1048
-	 * @param int $cardId
1049
-	 */
1050
-	protected function purgeProperties($addressBookId, $cardId) {
1051
-		$query = $this->db->getQueryBuilder();
1052
-		$query->delete($this->dbCardsPropertiesTable)
1053
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1054
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1055
-		$query->execute();
1056
-	}
1057
-
1058
-	/**
1059
-	 * get ID from a given contact
1060
-	 *
1061
-	 * @param int $addressBookId
1062
-	 * @param string $uri
1063
-	 * @return int
1064
-	 */
1065
-	protected function getCardId($addressBookId, $uri) {
1066
-		$query = $this->db->getQueryBuilder();
1067
-		$query->select('id')->from($this->dbCardsTable)
1068
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1069
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1070
-
1071
-		$result = $query->execute();
1072
-		$cardIds = $result->fetch();
1073
-		$result->closeCursor();
1074
-
1075
-		if (!isset($cardIds['id'])) {
1076
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1077
-		}
1078
-
1079
-		return (int)$cardIds['id'];
1080
-	}
1081
-
1082
-	/**
1083
-	 * For shared address books the sharee is set in the ACL of the address book
1084
-	 * @param $addressBookId
1085
-	 * @param $acl
1086
-	 * @return array
1087
-	 */
1088
-	public function applyShareAcl($addressBookId, $acl) {
1089
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1090
-	}
1091
-
1092
-	private function convertPrincipal($principalUri, $toV2) {
1093
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1094
-			list(, $name) = URLUtil::splitPath($principalUri);
1095
-			if ($toV2 === true) {
1096
-				return "principals/users/$name";
1097
-			}
1098
-			return "principals/$name";
1099
-		}
1100
-		return $principalUri;
1101
-	}
1102
-
1103
-	private function addOwnerPrincipal(&$addressbookInfo) {
1104
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1105
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1106
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1107
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1108
-		} else {
1109
-			$uri = $addressbookInfo['principaluri'];
1110
-		}
1111
-
1112
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1113
-		if (isset($principalInformation['{DAV:}displayname'])) {
1114
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1115
-		}
1116
-	}
51
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
52
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
53
+
54
+    /** @var Principal */
55
+    private $principalBackend;
56
+
57
+    /** @var string */
58
+    private $dbCardsTable = 'cards';
59
+
60
+    /** @var string */
61
+    private $dbCardsPropertiesTable = 'cards_properties';
62
+
63
+    /** @var IDBConnection */
64
+    private $db;
65
+
66
+    /** @var Backend */
67
+    private $sharingBackend;
68
+
69
+    /** @var array properties to index */
70
+    public static $indexProperties = array(
71
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
72
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
73
+
74
+    /**
75
+     * @var string[] Map of uid => display name
76
+     */
77
+    protected $userDisplayNames;
78
+
79
+    /** @var IUserManager */
80
+    private $userManager;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    /**
86
+     * CardDavBackend constructor.
87
+     *
88
+     * @param IDBConnection $db
89
+     * @param Principal $principalBackend
90
+     * @param IUserManager $userManager
91
+     * @param EventDispatcherInterface $dispatcher
92
+     */
93
+    public function __construct(IDBConnection $db,
94
+                                Principal $principalBackend,
95
+                                IUserManager $userManager,
96
+                                EventDispatcherInterface $dispatcher = null) {
97
+        $this->db = $db;
98
+        $this->principalBackend = $principalBackend;
99
+        $this->userManager = $userManager;
100
+        $this->dispatcher = $dispatcher;
101
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'addressbook');
102
+    }
103
+
104
+    /**
105
+     * Return the number of address books for a principal
106
+     *
107
+     * @param $principalUri
108
+     * @return int
109
+     */
110
+    public function getAddressBooksForUserCount($principalUri) {
111
+        $principalUri = $this->convertPrincipal($principalUri, true);
112
+        $query = $this->db->getQueryBuilder();
113
+        $query->select($query->createFunction('COUNT(*)'))
114
+            ->from('addressbooks')
115
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
116
+
117
+        return (int)$query->execute()->fetchColumn();
118
+    }
119
+
120
+    /**
121
+     * Returns the list of address books for a specific user.
122
+     *
123
+     * Every addressbook should have the following properties:
124
+     *   id - an arbitrary unique id
125
+     *   uri - the 'basename' part of the url
126
+     *   principaluri - Same as the passed parameter
127
+     *
128
+     * Any additional clark-notation property may be passed besides this. Some
129
+     * common ones are :
130
+     *   {DAV:}displayname
131
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
132
+     *   {http://calendarserver.org/ns/}getctag
133
+     *
134
+     * @param string $principalUri
135
+     * @return array
136
+     */
137
+    function getAddressBooksForUser($principalUri) {
138
+        $principalUriOriginal = $principalUri;
139
+        $principalUri = $this->convertPrincipal($principalUri, true);
140
+        $query = $this->db->getQueryBuilder();
141
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
142
+            ->from('addressbooks')
143
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
144
+
145
+        $addressBooks = [];
146
+
147
+        $result = $query->execute();
148
+        while($row = $result->fetch()) {
149
+            $addressBooks[$row['id']] = [
150
+                'id'  => $row['id'],
151
+                'uri' => $row['uri'],
152
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
153
+                '{DAV:}displayname' => $row['displayname'],
154
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
155
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
156
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
157
+            ];
158
+
159
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
160
+        }
161
+        $result->closeCursor();
162
+
163
+        // query for shared calendars
164
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
165
+        $principals[]= $principalUri;
166
+
167
+        $query = $this->db->getQueryBuilder();
168
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
169
+            ->from('dav_shares', 's')
170
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
171
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
172
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
173
+            ->setParameter('type', 'addressbook')
174
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
175
+            ->execute();
176
+
177
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
178
+        while($row = $result->fetch()) {
179
+            if ($row['principaluri'] === $principalUri) {
180
+                continue;
181
+            }
182
+
183
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
184
+            if (isset($addressBooks[$row['id']])) {
185
+                if ($readOnly) {
186
+                    // New share can not have more permissions then the old one.
187
+                    continue;
188
+                }
189
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
190
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
191
+                    // Old share is already read-write, no more permissions can be gained
192
+                    continue;
193
+                }
194
+            }
195
+
196
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
197
+            $uri = $row['uri'] . '_shared_by_' . $name;
198
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
199
+
200
+            $addressBooks[$row['id']] = [
201
+                'id'  => $row['id'],
202
+                'uri' => $uri,
203
+                'principaluri' => $principalUriOriginal,
204
+                '{DAV:}displayname' => $displayName,
205
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
206
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
207
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
208
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
209
+                $readOnlyPropertyName => $readOnly,
210
+            ];
211
+
212
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
213
+        }
214
+        $result->closeCursor();
215
+
216
+        return array_values($addressBooks);
217
+    }
218
+
219
+    public function getUsersOwnAddressBooks($principalUri) {
220
+        $principalUri = $this->convertPrincipal($principalUri, true);
221
+        $query = $this->db->getQueryBuilder();
222
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
223
+                ->from('addressbooks')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
225
+
226
+        $addressBooks = [];
227
+
228
+        $result = $query->execute();
229
+        while($row = $result->fetch()) {
230
+            $addressBooks[$row['id']] = [
231
+                'id'  => $row['id'],
232
+                'uri' => $row['uri'],
233
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
234
+                '{DAV:}displayname' => $row['displayname'],
235
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
236
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
237
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
238
+            ];
239
+
240
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
241
+        }
242
+        $result->closeCursor();
243
+
244
+        return array_values($addressBooks);
245
+    }
246
+
247
+    private function getUserDisplayName($uid) {
248
+        if (!isset($this->userDisplayNames[$uid])) {
249
+            $user = $this->userManager->get($uid);
250
+
251
+            if ($user instanceof IUser) {
252
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
253
+            } else {
254
+                $this->userDisplayNames[$uid] = $uid;
255
+            }
256
+        }
257
+
258
+        return $this->userDisplayNames[$uid];
259
+    }
260
+
261
+    /**
262
+     * @param int $addressBookId
263
+     */
264
+    public function getAddressBookById($addressBookId) {
265
+        $query = $this->db->getQueryBuilder();
266
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
267
+            ->from('addressbooks')
268
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
269
+            ->execute();
270
+
271
+        $row = $result->fetch();
272
+        $result->closeCursor();
273
+        if ($row === false) {
274
+            return null;
275
+        }
276
+
277
+        $addressBook = [
278
+            'id'  => $row['id'],
279
+            'uri' => $row['uri'],
280
+            'principaluri' => $row['principaluri'],
281
+            '{DAV:}displayname' => $row['displayname'],
282
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
283
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
284
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
285
+        ];
286
+
287
+        $this->addOwnerPrincipal($addressBook);
288
+
289
+        return $addressBook;
290
+    }
291
+
292
+    /**
293
+     * @param $addressBookUri
294
+     * @return array|null
295
+     */
296
+    public function getAddressBooksByUri($principal, $addressBookUri) {
297
+        $query = $this->db->getQueryBuilder();
298
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
299
+            ->from('addressbooks')
300
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
301
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
302
+            ->setMaxResults(1)
303
+            ->execute();
304
+
305
+        $row = $result->fetch();
306
+        $result->closeCursor();
307
+        if ($row === false) {
308
+            return null;
309
+        }
310
+
311
+        $addressBook = [
312
+            'id'  => $row['id'],
313
+            'uri' => $row['uri'],
314
+            'principaluri' => $row['principaluri'],
315
+            '{DAV:}displayname' => $row['displayname'],
316
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
317
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
318
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
319
+        ];
320
+
321
+        $this->addOwnerPrincipal($addressBook);
322
+
323
+        return $addressBook;
324
+    }
325
+
326
+    /**
327
+     * Updates properties for an address book.
328
+     *
329
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
330
+     * To do the actual updates, you must tell this object which properties
331
+     * you're going to process with the handle() method.
332
+     *
333
+     * Calling the handle method is like telling the PropPatch object "I
334
+     * promise I can handle updating this property".
335
+     *
336
+     * Read the PropPatch documentation for more info and examples.
337
+     *
338
+     * @param string $addressBookId
339
+     * @param \Sabre\DAV\PropPatch $propPatch
340
+     * @return void
341
+     */
342
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
343
+        $supportedProperties = [
344
+            '{DAV:}displayname',
345
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
346
+        ];
347
+
348
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
349
+
350
+            $updates = [];
351
+            foreach($mutations as $property=>$newValue) {
352
+
353
+                switch($property) {
354
+                    case '{DAV:}displayname' :
355
+                        $updates['displayname'] = $newValue;
356
+                        break;
357
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
358
+                        $updates['description'] = $newValue;
359
+                        break;
360
+                }
361
+            }
362
+            $query = $this->db->getQueryBuilder();
363
+            $query->update('addressbooks');
364
+
365
+            foreach($updates as $key=>$value) {
366
+                $query->set($key, $query->createNamedParameter($value));
367
+            }
368
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
369
+            ->execute();
370
+
371
+            $this->addChange($addressBookId, "", 2);
372
+
373
+            return true;
374
+
375
+        });
376
+    }
377
+
378
+    /**
379
+     * Creates a new address book
380
+     *
381
+     * @param string $principalUri
382
+     * @param string $url Just the 'basename' of the url.
383
+     * @param array $properties
384
+     * @return int
385
+     * @throws BadRequest
386
+     */
387
+    function createAddressBook($principalUri, $url, array $properties) {
388
+        $values = [
389
+            'displayname' => null,
390
+            'description' => null,
391
+            'principaluri' => $principalUri,
392
+            'uri' => $url,
393
+            'synctoken' => 1
394
+        ];
395
+
396
+        foreach($properties as $property=>$newValue) {
397
+
398
+            switch($property) {
399
+                case '{DAV:}displayname' :
400
+                    $values['displayname'] = $newValue;
401
+                    break;
402
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
403
+                    $values['description'] = $newValue;
404
+                    break;
405
+                default :
406
+                    throw new BadRequest('Unknown property: ' . $property);
407
+            }
408
+
409
+        }
410
+
411
+        // Fallback to make sure the displayname is set. Some clients may refuse
412
+        // to work with addressbooks not having a displayname.
413
+        if(is_null($values['displayname'])) {
414
+            $values['displayname'] = $url;
415
+        }
416
+
417
+        $query = $this->db->getQueryBuilder();
418
+        $query->insert('addressbooks')
419
+            ->values([
420
+                'uri' => $query->createParameter('uri'),
421
+                'displayname' => $query->createParameter('displayname'),
422
+                'description' => $query->createParameter('description'),
423
+                'principaluri' => $query->createParameter('principaluri'),
424
+                'synctoken' => $query->createParameter('synctoken'),
425
+            ])
426
+            ->setParameters($values)
427
+            ->execute();
428
+
429
+        return $query->getLastInsertId();
430
+    }
431
+
432
+    /**
433
+     * Deletes an entire addressbook and all its contents
434
+     *
435
+     * @param mixed $addressBookId
436
+     * @return void
437
+     */
438
+    function deleteAddressBook($addressBookId) {
439
+        $query = $this->db->getQueryBuilder();
440
+        $query->delete('cards')
441
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
442
+            ->setParameter('addressbookid', $addressBookId)
443
+            ->execute();
444
+
445
+        $query->delete('addressbookchanges')
446
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
447
+            ->setParameter('addressbookid', $addressBookId)
448
+            ->execute();
449
+
450
+        $query->delete('addressbooks')
451
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
452
+            ->setParameter('id', $addressBookId)
453
+            ->execute();
454
+
455
+        $this->sharingBackend->deleteAllShares($addressBookId);
456
+
457
+        $query->delete($this->dbCardsPropertiesTable)
458
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
459
+            ->execute();
460
+
461
+    }
462
+
463
+    /**
464
+     * Returns all cards for a specific addressbook id.
465
+     *
466
+     * This method should return the following properties for each card:
467
+     *   * carddata - raw vcard data
468
+     *   * uri - Some unique url
469
+     *   * lastmodified - A unix timestamp
470
+     *
471
+     * It's recommended to also return the following properties:
472
+     *   * etag - A unique etag. This must change every time the card changes.
473
+     *   * size - The size of the card in bytes.
474
+     *
475
+     * If these last two properties are provided, less time will be spent
476
+     * calculating them. If they are specified, you can also ommit carddata.
477
+     * This may speed up certain requests, especially with large cards.
478
+     *
479
+     * @param mixed $addressBookId
480
+     * @return array
481
+     */
482
+    function getCards($addressBookId) {
483
+        $query = $this->db->getQueryBuilder();
484
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
485
+            ->from('cards')
486
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
487
+
488
+        $cards = [];
489
+
490
+        $result = $query->execute();
491
+        while($row = $result->fetch()) {
492
+            $row['etag'] = '"' . $row['etag'] . '"';
493
+            $row['carddata'] = $this->readBlob($row['carddata']);
494
+            $cards[] = $row;
495
+        }
496
+        $result->closeCursor();
497
+
498
+        return $cards;
499
+    }
500
+
501
+    /**
502
+     * Returns a specific card.
503
+     *
504
+     * The same set of properties must be returned as with getCards. The only
505
+     * exception is that 'carddata' is absolutely required.
506
+     *
507
+     * If the card does not exist, you must return false.
508
+     *
509
+     * @param mixed $addressBookId
510
+     * @param string $cardUri
511
+     * @return array
512
+     */
513
+    function getCard($addressBookId, $cardUri) {
514
+        $query = $this->db->getQueryBuilder();
515
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
516
+            ->from('cards')
517
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
518
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
519
+            ->setMaxResults(1);
520
+
521
+        $result = $query->execute();
522
+        $row = $result->fetch();
523
+        if (!$row) {
524
+            return false;
525
+        }
526
+        $row['etag'] = '"' . $row['etag'] . '"';
527
+        $row['carddata'] = $this->readBlob($row['carddata']);
528
+
529
+        return $row;
530
+    }
531
+
532
+    /**
533
+     * Returns a list of cards.
534
+     *
535
+     * This method should work identical to getCard, but instead return all the
536
+     * cards in the list as an array.
537
+     *
538
+     * If the backend supports this, it may allow for some speed-ups.
539
+     *
540
+     * @param mixed $addressBookId
541
+     * @param string[] $uris
542
+     * @return array
543
+     */
544
+    function getMultipleCards($addressBookId, array $uris) {
545
+        if (empty($uris)) {
546
+            return [];
547
+        }
548
+
549
+        $chunks = array_chunk($uris, 100);
550
+        $cards = [];
551
+
552
+        $query = $this->db->getQueryBuilder();
553
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
554
+            ->from('cards')
555
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
556
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
557
+
558
+        foreach ($chunks as $uris) {
559
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
560
+            $result = $query->execute();
561
+
562
+            while ($row = $result->fetch()) {
563
+                $row['etag'] = '"' . $row['etag'] . '"';
564
+                $row['carddata'] = $this->readBlob($row['carddata']);
565
+                $cards[] = $row;
566
+            }
567
+            $result->closeCursor();
568
+        }
569
+        return $cards;
570
+    }
571
+
572
+    /**
573
+     * Creates a new card.
574
+     *
575
+     * The addressbook id will be passed as the first argument. This is the
576
+     * same id as it is returned from the getAddressBooksForUser method.
577
+     *
578
+     * The cardUri is a base uri, and doesn't include the full path. The
579
+     * cardData argument is the vcard body, and is passed as a string.
580
+     *
581
+     * It is possible to return an ETag from this method. This ETag is for the
582
+     * newly created resource, and must be enclosed with double quotes (that
583
+     * is, the string itself must contain the double quotes).
584
+     *
585
+     * You should only return the ETag if you store the carddata as-is. If a
586
+     * subsequent GET request on the same card does not have the same body,
587
+     * byte-by-byte and you did return an ETag here, clients tend to get
588
+     * confused.
589
+     *
590
+     * If you don't return an ETag, you can just return null.
591
+     *
592
+     * @param mixed $addressBookId
593
+     * @param string $cardUri
594
+     * @param string $cardData
595
+     * @return string
596
+     */
597
+    function createCard($addressBookId, $cardUri, $cardData) {
598
+        $etag = md5($cardData);
599
+
600
+        $query = $this->db->getQueryBuilder();
601
+        $query->insert('cards')
602
+            ->values([
603
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
604
+                'uri' => $query->createNamedParameter($cardUri),
605
+                'lastmodified' => $query->createNamedParameter(time()),
606
+                'addressbookid' => $query->createNamedParameter($addressBookId),
607
+                'size' => $query->createNamedParameter(strlen($cardData)),
608
+                'etag' => $query->createNamedParameter($etag),
609
+            ])
610
+            ->execute();
611
+
612
+        $this->addChange($addressBookId, $cardUri, 1);
613
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
614
+
615
+        if (!is_null($this->dispatcher)) {
616
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
617
+                new GenericEvent(null, [
618
+                    'addressBookId' => $addressBookId,
619
+                    'cardUri' => $cardUri,
620
+                    'cardData' => $cardData]));
621
+        }
622
+
623
+        return '"' . $etag . '"';
624
+    }
625
+
626
+    /**
627
+     * Updates a card.
628
+     *
629
+     * The addressbook id will be passed as the first argument. This is the
630
+     * same id as it is returned from the getAddressBooksForUser method.
631
+     *
632
+     * The cardUri is a base uri, and doesn't include the full path. The
633
+     * cardData argument is the vcard body, and is passed as a string.
634
+     *
635
+     * It is possible to return an ETag from this method. This ETag should
636
+     * match that of the updated resource, and must be enclosed with double
637
+     * quotes (that is: the string itself must contain the actual quotes).
638
+     *
639
+     * You should only return the ETag if you store the carddata as-is. If a
640
+     * subsequent GET request on the same card does not have the same body,
641
+     * byte-by-byte and you did return an ETag here, clients tend to get
642
+     * confused.
643
+     *
644
+     * If you don't return an ETag, you can just return null.
645
+     *
646
+     * @param mixed $addressBookId
647
+     * @param string $cardUri
648
+     * @param string $cardData
649
+     * @return string
650
+     */
651
+    function updateCard($addressBookId, $cardUri, $cardData) {
652
+
653
+        $etag = md5($cardData);
654
+        $query = $this->db->getQueryBuilder();
655
+        $query->update('cards')
656
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
657
+            ->set('lastmodified', $query->createNamedParameter(time()))
658
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
659
+            ->set('etag', $query->createNamedParameter($etag))
660
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
661
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
662
+            ->execute();
663
+
664
+        $this->addChange($addressBookId, $cardUri, 2);
665
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
666
+
667
+        if (!is_null($this->dispatcher)) {
668
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
669
+                new GenericEvent(null, [
670
+                    'addressBookId' => $addressBookId,
671
+                    'cardUri' => $cardUri,
672
+                    'cardData' => $cardData]));
673
+        }
674
+
675
+        return '"' . $etag . '"';
676
+    }
677
+
678
+    /**
679
+     * Deletes a card
680
+     *
681
+     * @param mixed $addressBookId
682
+     * @param string $cardUri
683
+     * @return bool
684
+     */
685
+    function deleteCard($addressBookId, $cardUri) {
686
+        try {
687
+            $cardId = $this->getCardId($addressBookId, $cardUri);
688
+        } catch (\InvalidArgumentException $e) {
689
+            $cardId = null;
690
+        }
691
+        $query = $this->db->getQueryBuilder();
692
+        $ret = $query->delete('cards')
693
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
695
+            ->execute();
696
+
697
+        $this->addChange($addressBookId, $cardUri, 3);
698
+
699
+        if (!is_null($this->dispatcher)) {
700
+            $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
701
+                new GenericEvent(null, [
702
+                    'addressBookId' => $addressBookId,
703
+                    'cardUri' => $cardUri]));
704
+        }
705
+
706
+        if ($ret === 1) {
707
+            if ($cardId !== null) {
708
+                $this->purgeProperties($addressBookId, $cardId);
709
+            }
710
+            return true;
711
+        }
712
+
713
+        return false;
714
+    }
715
+
716
+    /**
717
+     * The getChanges method returns all the changes that have happened, since
718
+     * the specified syncToken in the specified address book.
719
+     *
720
+     * This function should return an array, such as the following:
721
+     *
722
+     * [
723
+     *   'syncToken' => 'The current synctoken',
724
+     *   'added'   => [
725
+     *      'new.txt',
726
+     *   ],
727
+     *   'modified'   => [
728
+     *      'modified.txt',
729
+     *   ],
730
+     *   'deleted' => [
731
+     *      'foo.php.bak',
732
+     *      'old.txt'
733
+     *   ]
734
+     * ];
735
+     *
736
+     * The returned syncToken property should reflect the *current* syncToken
737
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
738
+     * property. This is needed here too, to ensure the operation is atomic.
739
+     *
740
+     * If the $syncToken argument is specified as null, this is an initial
741
+     * sync, and all members should be reported.
742
+     *
743
+     * The modified property is an array of nodenames that have changed since
744
+     * the last token.
745
+     *
746
+     * The deleted property is an array with nodenames, that have been deleted
747
+     * from collection.
748
+     *
749
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
750
+     * 1, you only have to report changes that happened only directly in
751
+     * immediate descendants. If it's 2, it should also include changes from
752
+     * the nodes below the child collections. (grandchildren)
753
+     *
754
+     * The $limit argument allows a client to specify how many results should
755
+     * be returned at most. If the limit is not specified, it should be treated
756
+     * as infinite.
757
+     *
758
+     * If the limit (infinite or not) is higher than you're willing to return,
759
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
760
+     *
761
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
762
+     * return null.
763
+     *
764
+     * The limit is 'suggestive'. You are free to ignore it.
765
+     *
766
+     * @param string $addressBookId
767
+     * @param string $syncToken
768
+     * @param int $syncLevel
769
+     * @param int $limit
770
+     * @return array
771
+     */
772
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
773
+        // Current synctoken
774
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
775
+        $stmt->execute([ $addressBookId ]);
776
+        $currentToken = $stmt->fetchColumn(0);
777
+
778
+        if (is_null($currentToken)) return null;
779
+
780
+        $result = [
781
+            'syncToken' => $currentToken,
782
+            'added'     => [],
783
+            'modified'  => [],
784
+            'deleted'   => [],
785
+        ];
786
+
787
+        if ($syncToken) {
788
+
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;
792
+            }
793
+
794
+            // Fetching all changes
795
+            $stmt = $this->db->prepare($query);
796
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
797
+
798
+            $changes = [];
799
+
800
+            // This loop ensures that any duplicates are overwritten, only the
801
+            // last change on a node is relevant.
802
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
803
+
804
+                $changes[$row['uri']] = $row['operation'];
805
+
806
+            }
807
+
808
+            foreach($changes as $uri => $operation) {
809
+
810
+                switch($operation) {
811
+                    case 1:
812
+                        $result['added'][] = $uri;
813
+                        break;
814
+                    case 2:
815
+                        $result['modified'][] = $uri;
816
+                        break;
817
+                    case 3:
818
+                        $result['deleted'][] = $uri;
819
+                        break;
820
+                }
821
+
822
+            }
823
+        } else {
824
+            // No synctoken supplied, this is the initial sync.
825
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
826
+            $stmt = $this->db->prepare($query);
827
+            $stmt->execute([$addressBookId]);
828
+
829
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
830
+        }
831
+        return $result;
832
+    }
833
+
834
+    /**
835
+     * Adds a change record to the addressbookchanges table.
836
+     *
837
+     * @param mixed $addressBookId
838
+     * @param string $objectUri
839
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
840
+     * @return void
841
+     */
842
+    protected function addChange($addressBookId, $objectUri, $operation) {
843
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
844
+        $stmt = $this->db->prepare($sql);
845
+        $stmt->execute([
846
+            $objectUri,
847
+            $addressBookId,
848
+            $operation,
849
+            $addressBookId
850
+        ]);
851
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
852
+        $stmt->execute([
853
+            $addressBookId
854
+        ]);
855
+    }
856
+
857
+    private function readBlob($cardData) {
858
+        if (is_resource($cardData)) {
859
+            return stream_get_contents($cardData);
860
+        }
861
+
862
+        return $cardData;
863
+    }
864
+
865
+    /**
866
+     * @param IShareable $shareable
867
+     * @param string[] $add
868
+     * @param string[] $remove
869
+     */
870
+    public function updateShares(IShareable $shareable, $add, $remove) {
871
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
872
+    }
873
+
874
+    /**
875
+     * search contact
876
+     *
877
+     * @param int $addressBookId
878
+     * @param string $pattern which should match within the $searchProperties
879
+     * @param array $searchProperties defines the properties within the query pattern should match
880
+     * @return array an array of contacts which are arrays of key-value-pairs
881
+     */
882
+    public function search($addressBookId, $pattern, $searchProperties) {
883
+        $query = $this->db->getQueryBuilder();
884
+        $query2 = $this->db->getQueryBuilder();
885
+
886
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
887
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
888
+        $or = $query2->expr()->orX();
889
+        foreach ($searchProperties as $property) {
890
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
891
+        }
892
+        $query2->andWhere($or);
893
+        $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
894
+
895
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
896
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
897
+
898
+        $result = $query->execute();
899
+        $cards = $result->fetchAll();
900
+
901
+        $result->closeCursor();
902
+
903
+        return array_map(function($array) {
904
+            $array['carddata'] = $this->readBlob($array['carddata']);
905
+            return $array;
906
+        }, $cards);
907
+    }
908
+
909
+    /**
910
+     * @param int $bookId
911
+     * @param string $name
912
+     * @return array
913
+     */
914
+    public function collectCardProperties($bookId, $name) {
915
+        $query = $this->db->getQueryBuilder();
916
+        $result = $query->selectDistinct('value')
917
+            ->from($this->dbCardsPropertiesTable)
918
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
919
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
920
+            ->execute();
921
+
922
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
923
+        $result->closeCursor();
924
+
925
+        return $all;
926
+    }
927
+
928
+    /**
929
+     * get URI from a given contact
930
+     *
931
+     * @param int $id
932
+     * @return string
933
+     */
934
+    public function getCardUri($id) {
935
+        $query = $this->db->getQueryBuilder();
936
+        $query->select('uri')->from($this->dbCardsTable)
937
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
938
+                ->setParameter('id', $id);
939
+
940
+        $result = $query->execute();
941
+        $uri = $result->fetch();
942
+        $result->closeCursor();
943
+
944
+        if (!isset($uri['uri'])) {
945
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
946
+        }
947
+
948
+        return $uri['uri'];
949
+    }
950
+
951
+    /**
952
+     * return contact with the given URI
953
+     *
954
+     * @param int $addressBookId
955
+     * @param string $uri
956
+     * @returns array
957
+     */
958
+    public function getContact($addressBookId, $uri) {
959
+        $result = [];
960
+        $query = $this->db->getQueryBuilder();
961
+        $query->select('*')->from($this->dbCardsTable)
962
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
963
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
964
+        $queryResult = $query->execute();
965
+        $contact = $queryResult->fetch();
966
+        $queryResult->closeCursor();
967
+
968
+        if (is_array($contact)) {
969
+            $result = $contact;
970
+        }
971
+
972
+        return $result;
973
+    }
974
+
975
+    /**
976
+     * Returns the list of people whom this address book is shared with.
977
+     *
978
+     * Every element in this array should have the following properties:
979
+     *   * href - Often a mailto: address
980
+     *   * commonName - Optional, for example a first + last name
981
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
982
+     *   * readOnly - boolean
983
+     *   * summary - Optional, a description for the share
984
+     *
985
+     * @return array
986
+     */
987
+    public function getShares($addressBookId) {
988
+        return $this->sharingBackend->getShares($addressBookId);
989
+    }
990
+
991
+    /**
992
+     * update properties table
993
+     *
994
+     * @param int $addressBookId
995
+     * @param string $cardUri
996
+     * @param string $vCardSerialized
997
+     */
998
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
999
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1000
+        $vCard = $this->readCard($vCardSerialized);
1001
+
1002
+        $this->purgeProperties($addressBookId, $cardId);
1003
+
1004
+        $query = $this->db->getQueryBuilder();
1005
+        $query->insert($this->dbCardsPropertiesTable)
1006
+            ->values(
1007
+                [
1008
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1009
+                    'cardid' => $query->createNamedParameter($cardId),
1010
+                    'name' => $query->createParameter('name'),
1011
+                    'value' => $query->createParameter('value'),
1012
+                    'preferred' => $query->createParameter('preferred')
1013
+                ]
1014
+            );
1015
+
1016
+        foreach ($vCard->children() as $property) {
1017
+            if(!in_array($property->name, self::$indexProperties)) {
1018
+                continue;
1019
+            }
1020
+            $preferred = 0;
1021
+            foreach($property->parameters as $parameter) {
1022
+                if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1023
+                    $preferred = 1;
1024
+                    break;
1025
+                }
1026
+            }
1027
+            $query->setParameter('name', $property->name);
1028
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1029
+            $query->setParameter('preferred', $preferred);
1030
+            $query->execute();
1031
+        }
1032
+    }
1033
+
1034
+    /**
1035
+     * read vCard data into a vCard object
1036
+     *
1037
+     * @param string $cardData
1038
+     * @return VCard
1039
+     */
1040
+    protected function readCard($cardData) {
1041
+        return  Reader::read($cardData);
1042
+    }
1043
+
1044
+    /**
1045
+     * delete all properties from a given card
1046
+     *
1047
+     * @param int $addressBookId
1048
+     * @param int $cardId
1049
+     */
1050
+    protected function purgeProperties($addressBookId, $cardId) {
1051
+        $query = $this->db->getQueryBuilder();
1052
+        $query->delete($this->dbCardsPropertiesTable)
1053
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1054
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1055
+        $query->execute();
1056
+    }
1057
+
1058
+    /**
1059
+     * get ID from a given contact
1060
+     *
1061
+     * @param int $addressBookId
1062
+     * @param string $uri
1063
+     * @return int
1064
+     */
1065
+    protected function getCardId($addressBookId, $uri) {
1066
+        $query = $this->db->getQueryBuilder();
1067
+        $query->select('id')->from($this->dbCardsTable)
1068
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1069
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1070
+
1071
+        $result = $query->execute();
1072
+        $cardIds = $result->fetch();
1073
+        $result->closeCursor();
1074
+
1075
+        if (!isset($cardIds['id'])) {
1076
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1077
+        }
1078
+
1079
+        return (int)$cardIds['id'];
1080
+    }
1081
+
1082
+    /**
1083
+     * For shared address books the sharee is set in the ACL of the address book
1084
+     * @param $addressBookId
1085
+     * @param $acl
1086
+     * @return array
1087
+     */
1088
+    public function applyShareAcl($addressBookId, $acl) {
1089
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1090
+    }
1091
+
1092
+    private function convertPrincipal($principalUri, $toV2) {
1093
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1094
+            list(, $name) = URLUtil::splitPath($principalUri);
1095
+            if ($toV2 === true) {
1096
+                return "principals/users/$name";
1097
+            }
1098
+            return "principals/$name";
1099
+        }
1100
+        return $principalUri;
1101
+    }
1102
+
1103
+    private function addOwnerPrincipal(&$addressbookInfo) {
1104
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1105
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1106
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1107
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1108
+        } else {
1109
+            $uri = $addressbookInfo['principaluri'];
1110
+        }
1111
+
1112
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1113
+        if (isset($principalInformation['{DAV:}displayname'])) {
1114
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1115
+        }
1116
+    }
1117 1117
 }
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']]);
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 
163 163
 		// query for shared calendars
164 164
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
165
-		$principals[]= $principalUri;
165
+		$principals[] = $principalUri;
166 166
 
167 167
 		$query = $this->db->getQueryBuilder();
168 168
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -174,8 +174,8 @@  discard block
 block discarded – undo
174 174
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
175 175
 			->execute();
176 176
 
177
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
178
-		while($row = $result->fetch()) {
177
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
178
+		while ($row = $result->fetch()) {
179 179
 			if ($row['principaluri'] === $principalUri) {
180 180
 				continue;
181 181
 			}
@@ -194,18 +194,18 @@  discard block
 block discarded – undo
194 194
 			}
195 195
 
196 196
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
197
-			$uri = $row['uri'] . '_shared_by_' . $name;
198
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
197
+			$uri = $row['uri'].'_shared_by_'.$name;
198
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
199 199
 
200 200
 			$addressBooks[$row['id']] = [
201 201
 				'id'  => $row['id'],
202 202
 				'uri' => $uri,
203 203
 				'principaluri' => $principalUriOriginal,
204 204
 				'{DAV:}displayname' => $displayName,
205
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
205
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
206 206
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
207
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
208
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
207
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
208
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
209 209
 				$readOnlyPropertyName => $readOnly,
210 210
 			];
211 211
 
@@ -226,15 +226,15 @@  discard block
 block discarded – undo
226 226
 		$addressBooks = [];
227 227
 
228 228
 		$result = $query->execute();
229
-		while($row = $result->fetch()) {
229
+		while ($row = $result->fetch()) {
230 230
 			$addressBooks[$row['id']] = [
231 231
 				'id'  => $row['id'],
232 232
 				'uri' => $row['uri'],
233 233
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
234 234
 				'{DAV:}displayname' => $row['displayname'],
235
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
235
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
236 236
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
237
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
237
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
238 238
 			];
239 239
 
240 240
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -279,9 +279,9 @@  discard block
 block discarded – undo
279 279
 			'uri' => $row['uri'],
280 280
 			'principaluri' => $row['principaluri'],
281 281
 			'{DAV:}displayname' => $row['displayname'],
282
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
282
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
283 283
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
284
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
285 285
 		];
286 286
 
287 287
 		$this->addOwnerPrincipal($addressBook);
@@ -313,9 +313,9 @@  discard block
 block discarded – undo
313 313
 			'uri' => $row['uri'],
314 314
 			'principaluri' => $row['principaluri'],
315 315
 			'{DAV:}displayname' => $row['displayname'],
316
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
316
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
317 317
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
318
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
318
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
319 319
 		];
320 320
 
321 321
 		$this->addOwnerPrincipal($addressBook);
@@ -342,19 +342,19 @@  discard block
 block discarded – undo
342 342
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
343 343
 		$supportedProperties = [
344 344
 			'{DAV:}displayname',
345
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
345
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
346 346
 		];
347 347
 
348 348
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
349 349
 
350 350
 			$updates = [];
351
-			foreach($mutations as $property=>$newValue) {
351
+			foreach ($mutations as $property=>$newValue) {
352 352
 
353
-				switch($property) {
353
+				switch ($property) {
354 354
 					case '{DAV:}displayname' :
355 355
 						$updates['displayname'] = $newValue;
356 356
 						break;
357
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
357
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
358 358
 						$updates['description'] = $newValue;
359 359
 						break;
360 360
 				}
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			$query = $this->db->getQueryBuilder();
363 363
 			$query->update('addressbooks');
364 364
 
365
-			foreach($updates as $key=>$value) {
365
+			foreach ($updates as $key=>$value) {
366 366
 				$query->set($key, $query->createNamedParameter($value));
367 367
 			}
368 368
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -393,24 +393,24 @@  discard block
 block discarded – undo
393 393
 			'synctoken' => 1
394 394
 		];
395 395
 
396
-		foreach($properties as $property=>$newValue) {
396
+		foreach ($properties as $property=>$newValue) {
397 397
 
398
-			switch($property) {
398
+			switch ($property) {
399 399
 				case '{DAV:}displayname' :
400 400
 					$values['displayname'] = $newValue;
401 401
 					break;
402
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
402
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
403 403
 					$values['description'] = $newValue;
404 404
 					break;
405 405
 				default :
406
-					throw new BadRequest('Unknown property: ' . $property);
406
+					throw new BadRequest('Unknown property: '.$property);
407 407
 			}
408 408
 
409 409
 		}
410 410
 
411 411
 		// Fallback to make sure the displayname is set. Some clients may refuse
412 412
 		// to work with addressbooks not having a displayname.
413
-		if(is_null($values['displayname'])) {
413
+		if (is_null($values['displayname'])) {
414 414
 			$values['displayname'] = $url;
415 415
 		}
416 416
 
@@ -488,8 +488,8 @@  discard block
 block discarded – undo
488 488
 		$cards = [];
489 489
 
490 490
 		$result = $query->execute();
491
-		while($row = $result->fetch()) {
492
-			$row['etag'] = '"' . $row['etag'] . '"';
491
+		while ($row = $result->fetch()) {
492
+			$row['etag'] = '"'.$row['etag'].'"';
493 493
 			$row['carddata'] = $this->readBlob($row['carddata']);
494 494
 			$cards[] = $row;
495 495
 		}
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
 		if (!$row) {
524 524
 			return false;
525 525
 		}
526
-		$row['etag'] = '"' . $row['etag'] . '"';
526
+		$row['etag'] = '"'.$row['etag'].'"';
527 527
 		$row['carddata'] = $this->readBlob($row['carddata']);
528 528
 
529 529
 		return $row;
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
 			$result = $query->execute();
561 561
 
562 562
 			while ($row = $result->fetch()) {
563
-				$row['etag'] = '"' . $row['etag'] . '"';
563
+				$row['etag'] = '"'.$row['etag'].'"';
564 564
 				$row['carddata'] = $this->readBlob($row['carddata']);
565 565
 				$cards[] = $row;
566 566
 			}
@@ -620,7 +620,7 @@  discard block
 block discarded – undo
620 620
 					'cardData' => $cardData]));
621 621
 		}
622 622
 
623
-		return '"' . $etag . '"';
623
+		return '"'.$etag.'"';
624 624
 	}
625 625
 
626 626
 	/**
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
 					'cardData' => $cardData]));
673 673
 		}
674 674
 
675
-		return '"' . $etag . '"';
675
+		return '"'.$etag.'"';
676 676
 	}
677 677
 
678 678
 	/**
@@ -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;
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
891 891
 		}
892 892
 		$query2->andWhere($or);
893
-		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
893
+		$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
894 894
 
895 895
 		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
896 896
 			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
@@ -942,7 +942,7 @@  discard block
 block discarded – undo
942 942
 		$result->closeCursor();
943 943
 
944 944
 		if (!isset($uri['uri'])) {
945
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
945
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
946 946
 		}
947 947
 
948 948
 		return $uri['uri'];
@@ -1014,11 +1014,11 @@  discard block
 block discarded – undo
1014 1014
 			);
1015 1015
 
1016 1016
 		foreach ($vCard->children() as $property) {
1017
-			if(!in_array($property->name, self::$indexProperties)) {
1017
+			if (!in_array($property->name, self::$indexProperties)) {
1018 1018
 				continue;
1019 1019
 			}
1020 1020
 			$preferred = 0;
1021
-			foreach($property->parameters as $parameter) {
1021
+			foreach ($property->parameters as $parameter) {
1022 1022
 				if ($parameter->name == 'TYPE' && strtoupper($parameter->getValue()) == 'PREF') {
1023 1023
 					$preferred = 1;
1024 1024
 					break;
@@ -1073,10 +1073,10 @@  discard block
 block discarded – undo
1073 1073
 		$result->closeCursor();
1074 1074
 
1075 1075
 		if (!isset($cardIds['id'])) {
1076
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1076
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1077 1077
 		}
1078 1078
 
1079
-		return (int)$cardIds['id'];
1079
+		return (int) $cardIds['id'];
1080 1080
 	}
1081 1081
 
1082 1082
 	/**
@@ -1101,8 +1101,8 @@  discard block
 block discarded – undo
1101 1101
 	}
1102 1102
 
1103 1103
 	private function addOwnerPrincipal(&$addressbookInfo) {
1104
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1105
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1104
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1105
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1106 1106
 		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1107 1107
 			$uri = $addressbookInfo[$ownerPrincipalKey];
1108 1108
 		} else {
Please login to merge, or discard this patch.