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