Passed
Push — master ( dc0ee3...12e540 )
by Robin
12:40 queued 10s
created
apps/dav/lib/CardDAV/CardDavBackend.php 3 patches
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -745,7 +745,9 @@
 block discarded – undo
745 745
 		$stmt->execute([ $addressBookId ]);
746 746
 		$currentToken = $stmt->fetchColumn(0);
747 747
 
748
-		if (is_null($currentToken)) return null;
748
+		if (is_null($currentToken)) {
749
+		    return null;
750
+		}
749 751
 
750 752
 		$result = [
751 753
 			'syncToken' => $currentToken,
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 			->from('addressbooks')
122 122
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123 123
 
124
-		return (int)$query->execute()->fetchColumn();
124
+		return (int) $query->execute()->fetchColumn();
125 125
 	}
126 126
 
127 127
 	/**
@@ -152,15 +152,15 @@  discard block
 block discarded – undo
152 152
 		$addressBooks = [];
153 153
 
154 154
 		$result = $query->execute();
155
-		while($row = $result->fetch()) {
155
+		while ($row = $result->fetch()) {
156 156
 			$addressBooks[$row['id']] = [
157 157
 				'id'  => $row['id'],
158 158
 				'uri' => $row['uri'],
159 159
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160 160
 				'{DAV:}displayname' => $row['displayname'],
161
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
161
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
162 162
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
163
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
164 164
 			];
165 165
 
166 166
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
 		$principals = array_map(function($principal) {
175 175
 			return urldecode($principal);
176 176
 		}, $principals);
177
-		$principals[]= $principalUri;
177
+		$principals[] = $principalUri;
178 178
 
179 179
 		$query = $this->db->getQueryBuilder();
180 180
 		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
@@ -186,8 +186,8 @@  discard block
 block discarded – undo
186 186
 			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
187 187
 			->execute();
188 188
 
189
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
190
-		while($row = $result->fetch()) {
189
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
190
+		while ($row = $result->fetch()) {
191 191
 			if ($row['principaluri'] === $principalUri) {
192 192
 				continue;
193 193
 			}
@@ -206,18 +206,18 @@  discard block
 block discarded – undo
206 206
 			}
207 207
 
208 208
 			list(, $name) = \Sabre\Uri\split($row['principaluri']);
209
-			$uri = $row['uri'] . '_shared_by_' . $name;
210
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
209
+			$uri = $row['uri'].'_shared_by_'.$name;
210
+			$displayName = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
211 211
 
212 212
 			$addressBooks[$row['id']] = [
213 213
 				'id'  => $row['id'],
214 214
 				'uri' => $uri,
215 215
 				'principaluri' => $principalUriOriginal,
216 216
 				'{DAV:}displayname' => $displayName,
217
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
217
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
218 218
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
219
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
220
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
219
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
220
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $row['principaluri'],
221 221
 				$readOnlyPropertyName => $readOnly,
222 222
 			];
223 223
 
@@ -238,15 +238,15 @@  discard block
 block discarded – undo
238 238
 		$addressBooks = [];
239 239
 
240 240
 		$result = $query->execute();
241
-		while($row = $result->fetch()) {
241
+		while ($row = $result->fetch()) {
242 242
 			$addressBooks[$row['id']] = [
243 243
 				'id'  => $row['id'],
244 244
 				'uri' => $row['uri'],
245 245
 				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
246 246
 				'{DAV:}displayname' => $row['displayname'],
247
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
247
+				'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
248 248
 				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
249
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
249
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
250 250
 			];
251 251
 
252 252
 			$this->addOwnerPrincipal($addressBooks[$row['id']]);
@@ -291,9 +291,9 @@  discard block
 block discarded – undo
291 291
 			'uri' => $row['uri'],
292 292
 			'principaluri' => $row['principaluri'],
293 293
 			'{DAV:}displayname' => $row['displayname'],
294
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
294
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
295 295
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
296
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
296
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
297 297
 		];
298 298
 
299 299
 		$this->addOwnerPrincipal($addressBook);
@@ -325,9 +325,9 @@  discard block
 block discarded – undo
325 325
 			'uri' => $row['uri'],
326 326
 			'principaluri' => $row['principaluri'],
327 327
 			'{DAV:}displayname' => $row['displayname'],
328
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
328
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'],
329 329
 			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
330
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
330
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
331 331
 		];
332 332
 
333 333
 		$this->addOwnerPrincipal($addressBook);
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
355 355
 		$supportedProperties = [
356 356
 			'{DAV:}displayname',
357
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
357
+			'{'.Plugin::NS_CARDDAV.'}addressbook-description',
358 358
 		];
359 359
 
360 360
 		/**
@@ -363,13 +363,13 @@  discard block
 block discarded – undo
363 363
 		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
364 364
 
365 365
 			$updates = [];
366
-			foreach($mutations as $property=>$newValue) {
366
+			foreach ($mutations as $property=>$newValue) {
367 367
 
368
-				switch($property) {
368
+				switch ($property) {
369 369
 					case '{DAV:}displayname' :
370 370
 						$updates['displayname'] = $newValue;
371 371
 						break;
372
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
372
+					case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
373 373
 						$updates['description'] = $newValue;
374 374
 						break;
375 375
 				}
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 			$query = $this->db->getQueryBuilder();
378 378
 			$query->update('addressbooks');
379 379
 
380
-			foreach($updates as $key=>$value) {
380
+			foreach ($updates as $key=>$value) {
381 381
 				$query->set($key, $query->createNamedParameter($value));
382 382
 			}
383 383
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
@@ -408,24 +408,24 @@  discard block
 block discarded – undo
408 408
 			'synctoken' => 1
409 409
 		];
410 410
 
411
-		foreach($properties as $property=>$newValue) {
411
+		foreach ($properties as $property=>$newValue) {
412 412
 
413
-			switch($property) {
413
+			switch ($property) {
414 414
 				case '{DAV:}displayname' :
415 415
 					$values['displayname'] = $newValue;
416 416
 					break;
417
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
417
+				case '{'.Plugin::NS_CARDDAV.'}addressbook-description' :
418 418
 					$values['description'] = $newValue;
419 419
 					break;
420 420
 				default :
421
-					throw new BadRequest('Unknown property: ' . $property);
421
+					throw new BadRequest('Unknown property: '.$property);
422 422
 			}
423 423
 
424 424
 		}
425 425
 
426 426
 		// Fallback to make sure the displayname is set. Some clients may refuse
427 427
 		// to work with addressbooks not having a displayname.
428
-		if(is_null($values['displayname'])) {
428
+		if (is_null($values['displayname'])) {
429 429
 			$values['displayname'] = $url;
430 430
 		}
431 431
 
@@ -503,8 +503,8 @@  discard block
 block discarded – undo
503 503
 		$cards = [];
504 504
 
505 505
 		$result = $query->execute();
506
-		while($row = $result->fetch()) {
507
-			$row['etag'] = '"' . $row['etag'] . '"';
506
+		while ($row = $result->fetch()) {
507
+			$row['etag'] = '"'.$row['etag'].'"';
508 508
 			$row['carddata'] = $this->readBlob($row['carddata']);
509 509
 			$cards[] = $row;
510 510
 		}
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
 		if (!$row) {
539 539
 			return false;
540 540
 		}
541
-		$row['etag'] = '"' . $row['etag'] . '"';
541
+		$row['etag'] = '"'.$row['etag'].'"';
542 542
 		$row['carddata'] = $this->readBlob($row['carddata']);
543 543
 
544 544
 		return $row;
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
 			$result = $query->execute();
576 576
 
577 577
 			while ($row = $result->fetch()) {
578
-				$row['etag'] = '"' . $row['etag'] . '"';
578
+				$row['etag'] = '"'.$row['etag'].'"';
579 579
 				$row['carddata'] = $this->readBlob($row['carddata']);
580 580
 				$cards[] = $row;
581 581
 			}
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
 				'cardUri' => $cardUri,
649 649
 				'cardData' => $cardData]));
650 650
 
651
-		return '"' . $etag . '"';
651
+		return '"'.$etag.'"';
652 652
 	}
653 653
 
654 654
 	/**
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 				'cardUri' => $cardUri,
701 701
 				'cardData' => $cardData]));
702 702
 
703
-		return '"' . $etag . '"';
703
+		return '"'.$etag.'"';
704 704
 	}
705 705
 
706 706
 	/**
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
799 799
 		// Current synctoken
800 800
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
801
-		$stmt->execute([ $addressBookId ]);
801
+		$stmt->execute([$addressBookId]);
802 802
 		$currentToken = $stmt->fetchColumn(0);
803 803
 
804 804
 		if (is_null($currentToken)) return null;
@@ -813,8 +813,8 @@  discard block
 block discarded – undo
813 813
 		if ($syncToken) {
814 814
 
815 815
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
816
-			if ($limit>0) {
817
-				$query .= " LIMIT " . (int)$limit;
816
+			if ($limit > 0) {
817
+				$query .= " LIMIT ".(int) $limit;
818 818
 			}
819 819
 
820 820
 			// Fetching all changes
@@ -825,15 +825,15 @@  discard block
 block discarded – undo
825 825
 
826 826
 			// This loop ensures that any duplicates are overwritten, only the
827 827
 			// last change on a node is relevant.
828
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
828
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
829 829
 
830 830
 				$changes[$row['uri']] = $row['operation'];
831 831
 
832 832
 			}
833 833
 
834
-			foreach($changes as $uri => $operation) {
834
+			foreach ($changes as $uri => $operation) {
835 835
 
836
-				switch($operation) {
836
+				switch ($operation) {
837 837
 					case 1:
838 838
 						$result['added'][] = $uri;
839 839
 						break;
@@ -921,10 +921,10 @@  discard block
 block discarded – undo
921 921
 
922 922
 		// No need for like when the pattern is empty
923 923
 		if ('' !== $pattern) {
924
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
924
+			if (\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
925 925
 				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
926 926
 			} else {
927
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
927
+				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
928 928
 			}
929 929
 		}
930 930
 
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
 		$result->closeCursor();
979 979
 
980 980
 		if (!isset($uri['uri'])) {
981
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
981
+			throw new \InvalidArgumentException('Card does not exists: '.$id);
982 982
 		}
983 983
 
984 984
 		return $uri['uri'];
@@ -1050,11 +1050,11 @@  discard block
 block discarded – undo
1050 1050
 			);
1051 1051
 
1052 1052
 		foreach ($vCard->children() as $property) {
1053
-			if(!in_array($property->name, self::$indexProperties)) {
1053
+			if (!in_array($property->name, self::$indexProperties)) {
1054 1054
 				continue;
1055 1055
 			}
1056 1056
 			$preferred = 0;
1057
-			foreach($property->parameters as $parameter) {
1057
+			foreach ($property->parameters as $parameter) {
1058 1058
 				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1059 1059
 					$preferred = 1;
1060 1060
 					break;
@@ -1109,10 +1109,10 @@  discard block
 block discarded – undo
1109 1109
 		$result->closeCursor();
1110 1110
 
1111 1111
 		if (!isset($cardIds['id'])) {
1112
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1112
+			throw new \InvalidArgumentException('Card does not exists: '.$uri);
1113 1113
 		}
1114 1114
 
1115
-		return (int)$cardIds['id'];
1115
+		return (int) $cardIds['id'];
1116 1116
 	}
1117 1117
 
1118 1118
 	/**
@@ -1137,8 +1137,8 @@  discard block
 block discarded – undo
1137 1137
 	}
1138 1138
 
1139 1139
 	private function addOwnerPrincipal(&$addressbookInfo) {
1140
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1141
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1140
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
1141
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
1142 1142
 		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1143 1143
 			$uri = $addressbookInfo[$ownerPrincipalKey];
1144 1144
 		} else {
Please login to merge, or discard this patch.
Indentation   +1118 added lines, -1118 removed lines patch added patch discarded remove patch
@@ -55,1122 +55,1122 @@
 block discarded – undo
55 55
 
56 56
 class CardDavBackend implements BackendInterface, SyncSupport {
57 57
 
58
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
59
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
60
-
61
-	/** @var Principal */
62
-	private $principalBackend;
63
-
64
-	/** @var string */
65
-	private $dbCardsTable = 'cards';
66
-
67
-	/** @var string */
68
-	private $dbCardsPropertiesTable = 'cards_properties';
69
-
70
-	/** @var IDBConnection */
71
-	private $db;
72
-
73
-	/** @var Backend */
74
-	private $sharingBackend;
75
-
76
-	/** @var array properties to index */
77
-	public static $indexProperties = array(
78
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
79
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
80
-
81
-	/**
82
-	 * @var string[] Map of uid => display name
83
-	 */
84
-	protected $userDisplayNames;
85
-
86
-	/** @var IUserManager */
87
-	private $userManager;
88
-
89
-	/** @var EventDispatcherInterface */
90
-	private $dispatcher;
91
-
92
-	/**
93
-	 * CardDavBackend constructor.
94
-	 *
95
-	 * @param IDBConnection $db
96
-	 * @param Principal $principalBackend
97
-	 * @param IUserManager $userManager
98
-	 * @param IGroupManager $groupManager
99
-	 * @param EventDispatcherInterface $dispatcher
100
-	 */
101
-	public function __construct(IDBConnection $db,
102
-								Principal $principalBackend,
103
-								IUserManager $userManager,
104
-								IGroupManager $groupManager,
105
-								EventDispatcherInterface $dispatcher) {
106
-		$this->db = $db;
107
-		$this->principalBackend = $principalBackend;
108
-		$this->userManager = $userManager;
109
-		$this->dispatcher = $dispatcher;
110
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
111
-	}
112
-
113
-	/**
114
-	 * Return the number of address books for a principal
115
-	 *
116
-	 * @param $principalUri
117
-	 * @return int
118
-	 */
119
-	public function getAddressBooksForUserCount($principalUri) {
120
-		$principalUri = $this->convertPrincipal($principalUri, true);
121
-		$query = $this->db->getQueryBuilder();
122
-		$query->select($query->func()->count('*'))
123
-			->from('addressbooks')
124
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
125
-
126
-		return (int)$query->execute()->fetchColumn();
127
-	}
128
-
129
-	/**
130
-	 * Returns the list of address books for a specific user.
131
-	 *
132
-	 * Every addressbook should have the following properties:
133
-	 *   id - an arbitrary unique id
134
-	 *   uri - the 'basename' part of the url
135
-	 *   principaluri - Same as the passed parameter
136
-	 *
137
-	 * Any additional clark-notation property may be passed besides this. Some
138
-	 * common ones are :
139
-	 *   {DAV:}displayname
140
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
141
-	 *   {http://calendarserver.org/ns/}getctag
142
-	 *
143
-	 * @param string $principalUri
144
-	 * @return array
145
-	 */
146
-	function getAddressBooksForUser($principalUri) {
147
-		$principalUriOriginal = $principalUri;
148
-		$principalUri = $this->convertPrincipal($principalUri, true);
149
-		$query = $this->db->getQueryBuilder();
150
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
151
-			->from('addressbooks')
152
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
153
-
154
-		$addressBooks = [];
155
-
156
-		$result = $query->execute();
157
-		while($row = $result->fetch()) {
158
-			$addressBooks[$row['id']] = [
159
-				'id'  => $row['id'],
160
-				'uri' => $row['uri'],
161
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
162
-				'{DAV:}displayname' => $row['displayname'],
163
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
164
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
165
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
166
-			];
167
-
168
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
169
-		}
170
-		$result->closeCursor();
171
-
172
-		// query for shared addressbooks
173
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
174
-		$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
175
-
176
-		$principals = array_map(function($principal) {
177
-			return urldecode($principal);
178
-		}, $principals);
179
-		$principals[]= $principalUri;
180
-
181
-		$query = $this->db->getQueryBuilder();
182
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
183
-			->from('dav_shares', 's')
184
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
185
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
186
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
187
-			->setParameter('type', 'addressbook')
188
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
189
-			->execute();
190
-
191
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
192
-		while($row = $result->fetch()) {
193
-			if ($row['principaluri'] === $principalUri) {
194
-				continue;
195
-			}
196
-
197
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
198
-			if (isset($addressBooks[$row['id']])) {
199
-				if ($readOnly) {
200
-					// New share can not have more permissions then the old one.
201
-					continue;
202
-				}
203
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
204
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
205
-					// Old share is already read-write, no more permissions can be gained
206
-					continue;
207
-				}
208
-			}
209
-
210
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
211
-			$uri = $row['uri'] . '_shared_by_' . $name;
212
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
213
-
214
-			$addressBooks[$row['id']] = [
215
-				'id'  => $row['id'],
216
-				'uri' => $uri,
217
-				'principaluri' => $principalUriOriginal,
218
-				'{DAV:}displayname' => $displayName,
219
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
220
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
221
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
222
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
223
-				$readOnlyPropertyName => $readOnly,
224
-			];
225
-
226
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
227
-		}
228
-		$result->closeCursor();
229
-
230
-		return array_values($addressBooks);
231
-	}
232
-
233
-	public function getUsersOwnAddressBooks($principalUri) {
234
-		$principalUri = $this->convertPrincipal($principalUri, true);
235
-		$query = $this->db->getQueryBuilder();
236
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
237
-			  ->from('addressbooks')
238
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
239
-
240
-		$addressBooks = [];
241
-
242
-		$result = $query->execute();
243
-		while($row = $result->fetch()) {
244
-			$addressBooks[$row['id']] = [
245
-				'id'  => $row['id'],
246
-				'uri' => $row['uri'],
247
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
248
-				'{DAV:}displayname' => $row['displayname'],
249
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
250
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
251
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
252
-			];
253
-
254
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
255
-		}
256
-		$result->closeCursor();
257
-
258
-		return array_values($addressBooks);
259
-	}
260
-
261
-	private function getUserDisplayName($uid) {
262
-		if (!isset($this->userDisplayNames[$uid])) {
263
-			$user = $this->userManager->get($uid);
264
-
265
-			if ($user instanceof IUser) {
266
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
267
-			} else {
268
-				$this->userDisplayNames[$uid] = $uid;
269
-			}
270
-		}
271
-
272
-		return $this->userDisplayNames[$uid];
273
-	}
274
-
275
-	/**
276
-	 * @param int $addressBookId
277
-	 */
278
-	public function getAddressBookById($addressBookId) {
279
-		$query = $this->db->getQueryBuilder();
280
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
281
-			->from('addressbooks')
282
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
283
-			->execute();
284
-
285
-		$row = $result->fetch();
286
-		$result->closeCursor();
287
-		if ($row === false) {
288
-			return null;
289
-		}
290
-
291
-		$addressBook = [
292
-			'id'  => $row['id'],
293
-			'uri' => $row['uri'],
294
-			'principaluri' => $row['principaluri'],
295
-			'{DAV:}displayname' => $row['displayname'],
296
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
297
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
298
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
299
-		];
300
-
301
-		$this->addOwnerPrincipal($addressBook);
302
-
303
-		return $addressBook;
304
-	}
305
-
306
-	/**
307
-	 * @param $addressBookUri
308
-	 * @return array|null
309
-	 */
310
-	public function getAddressBooksByUri($principal, $addressBookUri) {
311
-		$query = $this->db->getQueryBuilder();
312
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
313
-			->from('addressbooks')
314
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
315
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
316
-			->setMaxResults(1)
317
-			->execute();
318
-
319
-		$row = $result->fetch();
320
-		$result->closeCursor();
321
-		if ($row === false) {
322
-			return null;
323
-		}
324
-
325
-		$addressBook = [
326
-			'id'  => $row['id'],
327
-			'uri' => $row['uri'],
328
-			'principaluri' => $row['principaluri'],
329
-			'{DAV:}displayname' => $row['displayname'],
330
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
331
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
332
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
-		];
334
-
335
-		$this->addOwnerPrincipal($addressBook);
336
-
337
-		return $addressBook;
338
-	}
339
-
340
-	/**
341
-	 * Updates properties for an address book.
342
-	 *
343
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
344
-	 * To do the actual updates, you must tell this object which properties
345
-	 * you're going to process with the handle() method.
346
-	 *
347
-	 * Calling the handle method is like telling the PropPatch object "I
348
-	 * promise I can handle updating this property".
349
-	 *
350
-	 * Read the PropPatch documentation for more info and examples.
351
-	 *
352
-	 * @param string $addressBookId
353
-	 * @param \Sabre\DAV\PropPatch $propPatch
354
-	 * @return void
355
-	 */
356
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
357
-		$supportedProperties = [
358
-			'{DAV:}displayname',
359
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
360
-		];
361
-
362
-		/**
363
-		 * @suppress SqlInjectionChecker
364
-		 */
365
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
366
-
367
-			$updates = [];
368
-			foreach($mutations as $property=>$newValue) {
369
-
370
-				switch($property) {
371
-					case '{DAV:}displayname' :
372
-						$updates['displayname'] = $newValue;
373
-						break;
374
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
375
-						$updates['description'] = $newValue;
376
-						break;
377
-				}
378
-			}
379
-			$query = $this->db->getQueryBuilder();
380
-			$query->update('addressbooks');
381
-
382
-			foreach($updates as $key=>$value) {
383
-				$query->set($key, $query->createNamedParameter($value));
384
-			}
385
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
386
-			->execute();
387
-
388
-			$this->addChange($addressBookId, "", 2);
389
-
390
-			return true;
391
-
392
-		});
393
-	}
394
-
395
-	/**
396
-	 * Creates a new address book
397
-	 *
398
-	 * @param string $principalUri
399
-	 * @param string $url Just the 'basename' of the url.
400
-	 * @param array $properties
401
-	 * @return int
402
-	 * @throws BadRequest
403
-	 */
404
-	function createAddressBook($principalUri, $url, array $properties) {
405
-		$values = [
406
-			'displayname' => null,
407
-			'description' => null,
408
-			'principaluri' => $principalUri,
409
-			'uri' => $url,
410
-			'synctoken' => 1
411
-		];
412
-
413
-		foreach($properties as $property=>$newValue) {
414
-
415
-			switch($property) {
416
-				case '{DAV:}displayname' :
417
-					$values['displayname'] = $newValue;
418
-					break;
419
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
420
-					$values['description'] = $newValue;
421
-					break;
422
-				default :
423
-					throw new BadRequest('Unknown property: ' . $property);
424
-			}
425
-
426
-		}
427
-
428
-		// Fallback to make sure the displayname is set. Some clients may refuse
429
-		// to work with addressbooks not having a displayname.
430
-		if(is_null($values['displayname'])) {
431
-			$values['displayname'] = $url;
432
-		}
433
-
434
-		$query = $this->db->getQueryBuilder();
435
-		$query->insert('addressbooks')
436
-			->values([
437
-				'uri' => $query->createParameter('uri'),
438
-				'displayname' => $query->createParameter('displayname'),
439
-				'description' => $query->createParameter('description'),
440
-				'principaluri' => $query->createParameter('principaluri'),
441
-				'synctoken' => $query->createParameter('synctoken'),
442
-			])
443
-			->setParameters($values)
444
-			->execute();
445
-
446
-		return $query->getLastInsertId();
447
-	}
448
-
449
-	/**
450
-	 * Deletes an entire addressbook and all its contents
451
-	 *
452
-	 * @param mixed $addressBookId
453
-	 * @return void
454
-	 */
455
-	function deleteAddressBook($addressBookId) {
456
-		$query = $this->db->getQueryBuilder();
457
-		$query->delete('cards')
458
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
459
-			->setParameter('addressbookid', $addressBookId)
460
-			->execute();
461
-
462
-		$query->delete('addressbookchanges')
463
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
464
-			->setParameter('addressbookid', $addressBookId)
465
-			->execute();
466
-
467
-		$query->delete('addressbooks')
468
-			->where($query->expr()->eq('id', $query->createParameter('id')))
469
-			->setParameter('id', $addressBookId)
470
-			->execute();
471
-
472
-		$this->sharingBackend->deleteAllShares($addressBookId);
473
-
474
-		$query->delete($this->dbCardsPropertiesTable)
475
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
476
-			->execute();
477
-
478
-	}
479
-
480
-	/**
481
-	 * Returns all cards for a specific addressbook id.
482
-	 *
483
-	 * This method should return the following properties for each card:
484
-	 *   * carddata - raw vcard data
485
-	 *   * uri - Some unique url
486
-	 *   * lastmodified - A unix timestamp
487
-	 *
488
-	 * It's recommended to also return the following properties:
489
-	 *   * etag - A unique etag. This must change every time the card changes.
490
-	 *   * size - The size of the card in bytes.
491
-	 *
492
-	 * If these last two properties are provided, less time will be spent
493
-	 * calculating them. If they are specified, you can also ommit carddata.
494
-	 * This may speed up certain requests, especially with large cards.
495
-	 *
496
-	 * @param mixed $addressBookId
497
-	 * @return array
498
-	 */
499
-	function getCards($addressBookId) {
500
-		$query = $this->db->getQueryBuilder();
501
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
502
-			->from('cards')
503
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
504
-
505
-		$cards = [];
506
-
507
-		$result = $query->execute();
508
-		while($row = $result->fetch()) {
509
-			$row['etag'] = '"' . $row['etag'] . '"';
510
-			$row['carddata'] = $this->readBlob($row['carddata']);
511
-			$cards[] = $row;
512
-		}
513
-		$result->closeCursor();
514
-
515
-		return $cards;
516
-	}
517
-
518
-	/**
519
-	 * Returns a specific card.
520
-	 *
521
-	 * The same set of properties must be returned as with getCards. The only
522
-	 * exception is that 'carddata' is absolutely required.
523
-	 *
524
-	 * If the card does not exist, you must return false.
525
-	 *
526
-	 * @param mixed $addressBookId
527
-	 * @param string $cardUri
528
-	 * @return array
529
-	 */
530
-	function getCard($addressBookId, $cardUri) {
531
-		$query = $this->db->getQueryBuilder();
532
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
533
-			->from('cards')
534
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
535
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
536
-			->setMaxResults(1);
537
-
538
-		$result = $query->execute();
539
-		$row = $result->fetch();
540
-		if (!$row) {
541
-			return false;
542
-		}
543
-		$row['etag'] = '"' . $row['etag'] . '"';
544
-		$row['carddata'] = $this->readBlob($row['carddata']);
545
-
546
-		return $row;
547
-	}
548
-
549
-	/**
550
-	 * Returns a list of cards.
551
-	 *
552
-	 * This method should work identical to getCard, but instead return all the
553
-	 * cards in the list as an array.
554
-	 *
555
-	 * If the backend supports this, it may allow for some speed-ups.
556
-	 *
557
-	 * @param mixed $addressBookId
558
-	 * @param string[] $uris
559
-	 * @return array
560
-	 */
561
-	function getMultipleCards($addressBookId, array $uris) {
562
-		if (empty($uris)) {
563
-			return [];
564
-		}
565
-
566
-		$chunks = array_chunk($uris, 100);
567
-		$cards = [];
568
-
569
-		$query = $this->db->getQueryBuilder();
570
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
571
-			->from('cards')
572
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
573
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
574
-
575
-		foreach ($chunks as $uris) {
576
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
577
-			$result = $query->execute();
578
-
579
-			while ($row = $result->fetch()) {
580
-				$row['etag'] = '"' . $row['etag'] . '"';
581
-				$row['carddata'] = $this->readBlob($row['carddata']);
582
-				$cards[] = $row;
583
-			}
584
-			$result->closeCursor();
585
-		}
586
-		return $cards;
587
-	}
588
-
589
-	/**
590
-	 * Creates a new card.
591
-	 *
592
-	 * The addressbook id will be passed as the first argument. This is the
593
-	 * same id as it is returned from the getAddressBooksForUser method.
594
-	 *
595
-	 * The cardUri is a base uri, and doesn't include the full path. The
596
-	 * cardData argument is the vcard body, and is passed as a string.
597
-	 *
598
-	 * It is possible to return an ETag from this method. This ETag is for the
599
-	 * newly created resource, and must be enclosed with double quotes (that
600
-	 * is, the string itself must contain the double quotes).
601
-	 *
602
-	 * You should only return the ETag if you store the carddata as-is. If a
603
-	 * subsequent GET request on the same card does not have the same body,
604
-	 * byte-by-byte and you did return an ETag here, clients tend to get
605
-	 * confused.
606
-	 *
607
-	 * If you don't return an ETag, you can just return null.
608
-	 *
609
-	 * @param mixed $addressBookId
610
-	 * @param string $cardUri
611
-	 * @param string $cardData
612
-	 * @return string
613
-	 */
614
-	function createCard($addressBookId, $cardUri, $cardData) {
615
-		$etag = md5($cardData);
616
-		$uid = $this->getUID($cardData);
617
-
618
-		$q = $this->db->getQueryBuilder();
619
-		$q->select('uid')
620
-			->from('cards')
621
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
622
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
623
-			->setMaxResults(1);
624
-		$result = $q->execute();
625
-		$count = (bool) $result->fetchColumn();
626
-		$result->closeCursor();
627
-		if ($count) {
628
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
629
-		}
630
-
631
-		$query = $this->db->getQueryBuilder();
632
-		$query->insert('cards')
633
-			->values([
634
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
635
-				'uri' => $query->createNamedParameter($cardUri),
636
-				'lastmodified' => $query->createNamedParameter(time()),
637
-				'addressbookid' => $query->createNamedParameter($addressBookId),
638
-				'size' => $query->createNamedParameter(strlen($cardData)),
639
-				'etag' => $query->createNamedParameter($etag),
640
-				'uid' => $query->createNamedParameter($uid),
641
-			])
642
-			->execute();
643
-
644
-		$this->addChange($addressBookId, $cardUri, 1);
645
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
646
-
647
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
648
-			new GenericEvent(null, [
649
-				'addressBookId' => $addressBookId,
650
-				'cardUri' => $cardUri,
651
-				'cardData' => $cardData]));
652
-
653
-		return '"' . $etag . '"';
654
-	}
655
-
656
-	/**
657
-	 * Updates a card.
658
-	 *
659
-	 * The addressbook id will be passed as the first argument. This is the
660
-	 * same id as it is returned from the getAddressBooksForUser method.
661
-	 *
662
-	 * The cardUri is a base uri, and doesn't include the full path. The
663
-	 * cardData argument is the vcard body, and is passed as a string.
664
-	 *
665
-	 * It is possible to return an ETag from this method. This ETag should
666
-	 * match that of the updated resource, and must be enclosed with double
667
-	 * quotes (that is: the string itself must contain the actual quotes).
668
-	 *
669
-	 * You should only return the ETag if you store the carddata as-is. If a
670
-	 * subsequent GET request on the same card does not have the same body,
671
-	 * byte-by-byte and you did return an ETag here, clients tend to get
672
-	 * confused.
673
-	 *
674
-	 * If you don't return an ETag, you can just return null.
675
-	 *
676
-	 * @param mixed $addressBookId
677
-	 * @param string $cardUri
678
-	 * @param string $cardData
679
-	 * @return string
680
-	 */
681
-	function updateCard($addressBookId, $cardUri, $cardData) {
682
-
683
-		$uid = $this->getUID($cardData);
684
-		$etag = md5($cardData);
685
-		$query = $this->db->getQueryBuilder();
686
-		$query->update('cards')
687
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
688
-			->set('lastmodified', $query->createNamedParameter(time()))
689
-			->set('size', $query->createNamedParameter(strlen($cardData)))
690
-			->set('etag', $query->createNamedParameter($etag))
691
-			->set('uid', $query->createNamedParameter($uid))
692
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
693
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
-			->execute();
695
-
696
-		$this->addChange($addressBookId, $cardUri, 2);
697
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
698
-
699
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
700
-			new GenericEvent(null, [
701
-				'addressBookId' => $addressBookId,
702
-				'cardUri' => $cardUri,
703
-				'cardData' => $cardData]));
704
-
705
-		return '"' . $etag . '"';
706
-	}
707
-
708
-	/**
709
-	 * Deletes a card
710
-	 *
711
-	 * @param mixed $addressBookId
712
-	 * @param string $cardUri
713
-	 * @return bool
714
-	 */
715
-	function deleteCard($addressBookId, $cardUri) {
716
-		try {
717
-			$cardId = $this->getCardId($addressBookId, $cardUri);
718
-		} catch (\InvalidArgumentException $e) {
719
-			$cardId = null;
720
-		}
721
-		$query = $this->db->getQueryBuilder();
722
-		$ret = $query->delete('cards')
723
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
724
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
725
-			->execute();
726
-
727
-		$this->addChange($addressBookId, $cardUri, 3);
728
-
729
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
730
-			new GenericEvent(null, [
731
-				'addressBookId' => $addressBookId,
732
-				'cardUri' => $cardUri]));
733
-
734
-		if ($ret === 1) {
735
-			if ($cardId !== null) {
736
-				$this->purgeProperties($addressBookId, $cardId);
737
-			}
738
-			return true;
739
-		}
740
-
741
-		return false;
742
-	}
743
-
744
-	/**
745
-	 * The getChanges method returns all the changes that have happened, since
746
-	 * the specified syncToken in the specified address book.
747
-	 *
748
-	 * This function should return an array, such as the following:
749
-	 *
750
-	 * [
751
-	 *   'syncToken' => 'The current synctoken',
752
-	 *   'added'   => [
753
-	 *      'new.txt',
754
-	 *   ],
755
-	 *   'modified'   => [
756
-	 *      'modified.txt',
757
-	 *   ],
758
-	 *   'deleted' => [
759
-	 *      'foo.php.bak',
760
-	 *      'old.txt'
761
-	 *   ]
762
-	 * ];
763
-	 *
764
-	 * The returned syncToken property should reflect the *current* syncToken
765
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
766
-	 * property. This is needed here too, to ensure the operation is atomic.
767
-	 *
768
-	 * If the $syncToken argument is specified as null, this is an initial
769
-	 * sync, and all members should be reported.
770
-	 *
771
-	 * The modified property is an array of nodenames that have changed since
772
-	 * the last token.
773
-	 *
774
-	 * The deleted property is an array with nodenames, that have been deleted
775
-	 * from collection.
776
-	 *
777
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
778
-	 * 1, you only have to report changes that happened only directly in
779
-	 * immediate descendants. If it's 2, it should also include changes from
780
-	 * the nodes below the child collections. (grandchildren)
781
-	 *
782
-	 * The $limit argument allows a client to specify how many results should
783
-	 * be returned at most. If the limit is not specified, it should be treated
784
-	 * as infinite.
785
-	 *
786
-	 * If the limit (infinite or not) is higher than you're willing to return,
787
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
788
-	 *
789
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
790
-	 * return null.
791
-	 *
792
-	 * The limit is 'suggestive'. You are free to ignore it.
793
-	 *
794
-	 * @param string $addressBookId
795
-	 * @param string $syncToken
796
-	 * @param int $syncLevel
797
-	 * @param int $limit
798
-	 * @return array
799
-	 */
800
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
801
-		// Current synctoken
802
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
803
-		$stmt->execute([ $addressBookId ]);
804
-		$currentToken = $stmt->fetchColumn(0);
805
-
806
-		if (is_null($currentToken)) return null;
807
-
808
-		$result = [
809
-			'syncToken' => $currentToken,
810
-			'added'     => [],
811
-			'modified'  => [],
812
-			'deleted'   => [],
813
-		];
814
-
815
-		if ($syncToken) {
816
-
817
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
818
-			if ($limit>0) {
819
-				$query .= " LIMIT " . (int)$limit;
820
-			}
821
-
822
-			// Fetching all changes
823
-			$stmt = $this->db->prepare($query);
824
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
825
-
826
-			$changes = [];
827
-
828
-			// This loop ensures that any duplicates are overwritten, only the
829
-			// last change on a node is relevant.
830
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
831
-
832
-				$changes[$row['uri']] = $row['operation'];
833
-
834
-			}
835
-
836
-			foreach($changes as $uri => $operation) {
837
-
838
-				switch($operation) {
839
-					case 1:
840
-						$result['added'][] = $uri;
841
-						break;
842
-					case 2:
843
-						$result['modified'][] = $uri;
844
-						break;
845
-					case 3:
846
-						$result['deleted'][] = $uri;
847
-						break;
848
-				}
849
-
850
-			}
851
-		} else {
852
-			// No synctoken supplied, this is the initial sync.
853
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
854
-			$stmt = $this->db->prepare($query);
855
-			$stmt->execute([$addressBookId]);
856
-
857
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
858
-		}
859
-		return $result;
860
-	}
861
-
862
-	/**
863
-	 * Adds a change record to the addressbookchanges table.
864
-	 *
865
-	 * @param mixed $addressBookId
866
-	 * @param string $objectUri
867
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
868
-	 * @return void
869
-	 */
870
-	protected function addChange($addressBookId, $objectUri, $operation) {
871
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
872
-		$stmt = $this->db->prepare($sql);
873
-		$stmt->execute([
874
-			$objectUri,
875
-			$addressBookId,
876
-			$operation,
877
-			$addressBookId
878
-		]);
879
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
880
-		$stmt->execute([
881
-			$addressBookId
882
-		]);
883
-	}
884
-
885
-	private function readBlob($cardData) {
886
-		if (is_resource($cardData)) {
887
-			return stream_get_contents($cardData);
888
-		}
889
-
890
-		return $cardData;
891
-	}
892
-
893
-	/**
894
-	 * @param IShareable $shareable
895
-	 * @param string[] $add
896
-	 * @param string[] $remove
897
-	 */
898
-	public function updateShares(IShareable $shareable, $add, $remove) {
899
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
900
-	}
901
-
902
-	/**
903
-	 * search contact
904
-	 *
905
-	 * @param int $addressBookId
906
-	 * @param string $pattern which should match within the $searchProperties
907
-	 * @param array $searchProperties defines the properties within the query pattern should match
908
-	 * @param array $options = array() to define the search behavior
909
-	 * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
910
-	 * @return array an array of contacts which are arrays of key-value-pairs
911
-	 */
912
-	public function search($addressBookId, $pattern, $searchProperties, $options = array()) {
913
-		$query = $this->db->getQueryBuilder();
914
-		$query2 = $this->db->getQueryBuilder();
915
-
916
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
917
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
918
-		$or = $query2->expr()->orX();
919
-		foreach ($searchProperties as $property) {
920
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
921
-		}
922
-		$query2->andWhere($or);
923
-
924
-		// No need for like when the pattern is empty
925
-		if ('' !== $pattern) {
926
-			if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
927
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
928
-			} else {
929
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
930
-			}
931
-		}
932
-
933
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
934
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
935
-
936
-		$result = $query->execute();
937
-		$cards = $result->fetchAll();
938
-
939
-		$result->closeCursor();
940
-
941
-		return array_map(function($array) {
942
-			$array['carddata'] = $this->readBlob($array['carddata']);
943
-			return $array;
944
-		}, $cards);
945
-	}
946
-
947
-	/**
948
-	 * @param int $bookId
949
-	 * @param string $name
950
-	 * @return array
951
-	 */
952
-	public function collectCardProperties($bookId, $name) {
953
-		$query = $this->db->getQueryBuilder();
954
-		$result = $query->selectDistinct('value')
955
-			->from($this->dbCardsPropertiesTable)
956
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
957
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
958
-			->execute();
959
-
960
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
961
-		$result->closeCursor();
962
-
963
-		return $all;
964
-	}
965
-
966
-	/**
967
-	 * get URI from a given contact
968
-	 *
969
-	 * @param int $id
970
-	 * @return string
971
-	 */
972
-	public function getCardUri($id) {
973
-		$query = $this->db->getQueryBuilder();
974
-		$query->select('uri')->from($this->dbCardsTable)
975
-				->where($query->expr()->eq('id', $query->createParameter('id')))
976
-				->setParameter('id', $id);
977
-
978
-		$result = $query->execute();
979
-		$uri = $result->fetch();
980
-		$result->closeCursor();
981
-
982
-		if (!isset($uri['uri'])) {
983
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
984
-		}
985
-
986
-		return $uri['uri'];
987
-	}
988
-
989
-	/**
990
-	 * return contact with the given URI
991
-	 *
992
-	 * @param int $addressBookId
993
-	 * @param string $uri
994
-	 * @returns array
995
-	 */
996
-	public function getContact($addressBookId, $uri) {
997
-		$result = [];
998
-		$query = $this->db->getQueryBuilder();
999
-		$query->select('*')->from($this->dbCardsTable)
1000
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1001
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1002
-		$queryResult = $query->execute();
1003
-		$contact = $queryResult->fetch();
1004
-		$queryResult->closeCursor();
1005
-
1006
-		if (is_array($contact)) {
1007
-			$result = $contact;
1008
-		}
1009
-
1010
-		return $result;
1011
-	}
1012
-
1013
-	/**
1014
-	 * Returns the list of people whom this address book is shared with.
1015
-	 *
1016
-	 * Every element in this array should have the following properties:
1017
-	 *   * href - Often a mailto: address
1018
-	 *   * commonName - Optional, for example a first + last name
1019
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1020
-	 *   * readOnly - boolean
1021
-	 *   * summary - Optional, a description for the share
1022
-	 *
1023
-	 * @return array
1024
-	 */
1025
-	public function getShares($addressBookId) {
1026
-		return $this->sharingBackend->getShares($addressBookId);
1027
-	}
1028
-
1029
-	/**
1030
-	 * update properties table
1031
-	 *
1032
-	 * @param int $addressBookId
1033
-	 * @param string $cardUri
1034
-	 * @param string $vCardSerialized
1035
-	 */
1036
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1037
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1038
-		$vCard = $this->readCard($vCardSerialized);
1039
-
1040
-		$this->purgeProperties($addressBookId, $cardId);
1041
-
1042
-		$query = $this->db->getQueryBuilder();
1043
-		$query->insert($this->dbCardsPropertiesTable)
1044
-			->values(
1045
-				[
1046
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1047
-					'cardid' => $query->createNamedParameter($cardId),
1048
-					'name' => $query->createParameter('name'),
1049
-					'value' => $query->createParameter('value'),
1050
-					'preferred' => $query->createParameter('preferred')
1051
-				]
1052
-			);
1053
-
1054
-		foreach ($vCard->children() as $property) {
1055
-			if(!in_array($property->name, self::$indexProperties)) {
1056
-				continue;
1057
-			}
1058
-			$preferred = 0;
1059
-			foreach($property->parameters as $parameter) {
1060
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1061
-					$preferred = 1;
1062
-					break;
1063
-				}
1064
-			}
1065
-			$query->setParameter('name', $property->name);
1066
-			$query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1067
-			$query->setParameter('preferred', $preferred);
1068
-			$query->execute();
1069
-		}
1070
-	}
1071
-
1072
-	/**
1073
-	 * read vCard data into a vCard object
1074
-	 *
1075
-	 * @param string $cardData
1076
-	 * @return VCard
1077
-	 */
1078
-	protected function readCard($cardData) {
1079
-		return  Reader::read($cardData);
1080
-	}
1081
-
1082
-	/**
1083
-	 * delete all properties from a given card
1084
-	 *
1085
-	 * @param int $addressBookId
1086
-	 * @param int $cardId
1087
-	 */
1088
-	protected function purgeProperties($addressBookId, $cardId) {
1089
-		$query = $this->db->getQueryBuilder();
1090
-		$query->delete($this->dbCardsPropertiesTable)
1091
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1092
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1093
-		$query->execute();
1094
-	}
1095
-
1096
-	/**
1097
-	 * get ID from a given contact
1098
-	 *
1099
-	 * @param int $addressBookId
1100
-	 * @param string $uri
1101
-	 * @return int
1102
-	 */
1103
-	protected function getCardId($addressBookId, $uri) {
1104
-		$query = $this->db->getQueryBuilder();
1105
-		$query->select('id')->from($this->dbCardsTable)
1106
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1107
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1108
-
1109
-		$result = $query->execute();
1110
-		$cardIds = $result->fetch();
1111
-		$result->closeCursor();
1112
-
1113
-		if (!isset($cardIds['id'])) {
1114
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1115
-		}
1116
-
1117
-		return (int)$cardIds['id'];
1118
-	}
1119
-
1120
-	/**
1121
-	 * For shared address books the sharee is set in the ACL of the address book
1122
-	 * @param $addressBookId
1123
-	 * @param $acl
1124
-	 * @return array
1125
-	 */
1126
-	public function applyShareAcl($addressBookId, $acl) {
1127
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1128
-	}
1129
-
1130
-	private function convertPrincipal($principalUri, $toV2) {
1131
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1132
-			list(, $name) = \Sabre\Uri\split($principalUri);
1133
-			if ($toV2 === true) {
1134
-				return "principals/users/$name";
1135
-			}
1136
-			return "principals/$name";
1137
-		}
1138
-		return $principalUri;
1139
-	}
1140
-
1141
-	private function addOwnerPrincipal(&$addressbookInfo) {
1142
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1143
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1144
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1145
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1146
-		} else {
1147
-			$uri = $addressbookInfo['principaluri'];
1148
-		}
1149
-
1150
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1151
-		if (isset($principalInformation['{DAV:}displayname'])) {
1152
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1153
-		}
1154
-	}
1155
-
1156
-	/**
1157
-	 * Extract UID from vcard
1158
-	 *
1159
-	 * @param string $cardData the vcard raw data
1160
-	 * @return string the uid
1161
-	 * @throws BadRequest if no UID is available
1162
-	 */
1163
-	private function getUID($cardData) {
1164
-		if ($cardData != '') {
1165
-			$vCard = Reader::read($cardData);
1166
-			if ($vCard->UID) {
1167
-				$uid = $vCard->UID->getValue();
1168
-				return $uid;
1169
-			}
1170
-			// should already be handled, but just in case
1171
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1172
-		}
1173
-		// should already be handled, but just in case
1174
-		throw new BadRequest('vCard can not be empty');
1175
-	}
58
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
59
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
60
+
61
+    /** @var Principal */
62
+    private $principalBackend;
63
+
64
+    /** @var string */
65
+    private $dbCardsTable = 'cards';
66
+
67
+    /** @var string */
68
+    private $dbCardsPropertiesTable = 'cards_properties';
69
+
70
+    /** @var IDBConnection */
71
+    private $db;
72
+
73
+    /** @var Backend */
74
+    private $sharingBackend;
75
+
76
+    /** @var array properties to index */
77
+    public static $indexProperties = array(
78
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
79
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
80
+
81
+    /**
82
+     * @var string[] Map of uid => display name
83
+     */
84
+    protected $userDisplayNames;
85
+
86
+    /** @var IUserManager */
87
+    private $userManager;
88
+
89
+    /** @var EventDispatcherInterface */
90
+    private $dispatcher;
91
+
92
+    /**
93
+     * CardDavBackend constructor.
94
+     *
95
+     * @param IDBConnection $db
96
+     * @param Principal $principalBackend
97
+     * @param IUserManager $userManager
98
+     * @param IGroupManager $groupManager
99
+     * @param EventDispatcherInterface $dispatcher
100
+     */
101
+    public function __construct(IDBConnection $db,
102
+                                Principal $principalBackend,
103
+                                IUserManager $userManager,
104
+                                IGroupManager $groupManager,
105
+                                EventDispatcherInterface $dispatcher) {
106
+        $this->db = $db;
107
+        $this->principalBackend = $principalBackend;
108
+        $this->userManager = $userManager;
109
+        $this->dispatcher = $dispatcher;
110
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
111
+    }
112
+
113
+    /**
114
+     * Return the number of address books for a principal
115
+     *
116
+     * @param $principalUri
117
+     * @return int
118
+     */
119
+    public function getAddressBooksForUserCount($principalUri) {
120
+        $principalUri = $this->convertPrincipal($principalUri, true);
121
+        $query = $this->db->getQueryBuilder();
122
+        $query->select($query->func()->count('*'))
123
+            ->from('addressbooks')
124
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
125
+
126
+        return (int)$query->execute()->fetchColumn();
127
+    }
128
+
129
+    /**
130
+     * Returns the list of address books for a specific user.
131
+     *
132
+     * Every addressbook should have the following properties:
133
+     *   id - an arbitrary unique id
134
+     *   uri - the 'basename' part of the url
135
+     *   principaluri - Same as the passed parameter
136
+     *
137
+     * Any additional clark-notation property may be passed besides this. Some
138
+     * common ones are :
139
+     *   {DAV:}displayname
140
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
141
+     *   {http://calendarserver.org/ns/}getctag
142
+     *
143
+     * @param string $principalUri
144
+     * @return array
145
+     */
146
+    function getAddressBooksForUser($principalUri) {
147
+        $principalUriOriginal = $principalUri;
148
+        $principalUri = $this->convertPrincipal($principalUri, true);
149
+        $query = $this->db->getQueryBuilder();
150
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
151
+            ->from('addressbooks')
152
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
153
+
154
+        $addressBooks = [];
155
+
156
+        $result = $query->execute();
157
+        while($row = $result->fetch()) {
158
+            $addressBooks[$row['id']] = [
159
+                'id'  => $row['id'],
160
+                'uri' => $row['uri'],
161
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
162
+                '{DAV:}displayname' => $row['displayname'],
163
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
164
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
165
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
166
+            ];
167
+
168
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
169
+        }
170
+        $result->closeCursor();
171
+
172
+        // query for shared addressbooks
173
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
174
+        $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
175
+
176
+        $principals = array_map(function($principal) {
177
+            return urldecode($principal);
178
+        }, $principals);
179
+        $principals[]= $principalUri;
180
+
181
+        $query = $this->db->getQueryBuilder();
182
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
183
+            ->from('dav_shares', 's')
184
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
185
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
186
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
187
+            ->setParameter('type', 'addressbook')
188
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
189
+            ->execute();
190
+
191
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
192
+        while($row = $result->fetch()) {
193
+            if ($row['principaluri'] === $principalUri) {
194
+                continue;
195
+            }
196
+
197
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
198
+            if (isset($addressBooks[$row['id']])) {
199
+                if ($readOnly) {
200
+                    // New share can not have more permissions then the old one.
201
+                    continue;
202
+                }
203
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
204
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
205
+                    // Old share is already read-write, no more permissions can be gained
206
+                    continue;
207
+                }
208
+            }
209
+
210
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
211
+            $uri = $row['uri'] . '_shared_by_' . $name;
212
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
213
+
214
+            $addressBooks[$row['id']] = [
215
+                'id'  => $row['id'],
216
+                'uri' => $uri,
217
+                'principaluri' => $principalUriOriginal,
218
+                '{DAV:}displayname' => $displayName,
219
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
220
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
221
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
222
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
223
+                $readOnlyPropertyName => $readOnly,
224
+            ];
225
+
226
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
227
+        }
228
+        $result->closeCursor();
229
+
230
+        return array_values($addressBooks);
231
+    }
232
+
233
+    public function getUsersOwnAddressBooks($principalUri) {
234
+        $principalUri = $this->convertPrincipal($principalUri, true);
235
+        $query = $this->db->getQueryBuilder();
236
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
237
+                ->from('addressbooks')
238
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
239
+
240
+        $addressBooks = [];
241
+
242
+        $result = $query->execute();
243
+        while($row = $result->fetch()) {
244
+            $addressBooks[$row['id']] = [
245
+                'id'  => $row['id'],
246
+                'uri' => $row['uri'],
247
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
248
+                '{DAV:}displayname' => $row['displayname'],
249
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
250
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
251
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
252
+            ];
253
+
254
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
255
+        }
256
+        $result->closeCursor();
257
+
258
+        return array_values($addressBooks);
259
+    }
260
+
261
+    private function getUserDisplayName($uid) {
262
+        if (!isset($this->userDisplayNames[$uid])) {
263
+            $user = $this->userManager->get($uid);
264
+
265
+            if ($user instanceof IUser) {
266
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
267
+            } else {
268
+                $this->userDisplayNames[$uid] = $uid;
269
+            }
270
+        }
271
+
272
+        return $this->userDisplayNames[$uid];
273
+    }
274
+
275
+    /**
276
+     * @param int $addressBookId
277
+     */
278
+    public function getAddressBookById($addressBookId) {
279
+        $query = $this->db->getQueryBuilder();
280
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
281
+            ->from('addressbooks')
282
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
283
+            ->execute();
284
+
285
+        $row = $result->fetch();
286
+        $result->closeCursor();
287
+        if ($row === false) {
288
+            return null;
289
+        }
290
+
291
+        $addressBook = [
292
+            'id'  => $row['id'],
293
+            'uri' => $row['uri'],
294
+            'principaluri' => $row['principaluri'],
295
+            '{DAV:}displayname' => $row['displayname'],
296
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
297
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
298
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
299
+        ];
300
+
301
+        $this->addOwnerPrincipal($addressBook);
302
+
303
+        return $addressBook;
304
+    }
305
+
306
+    /**
307
+     * @param $addressBookUri
308
+     * @return array|null
309
+     */
310
+    public function getAddressBooksByUri($principal, $addressBookUri) {
311
+        $query = $this->db->getQueryBuilder();
312
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
313
+            ->from('addressbooks')
314
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
315
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
316
+            ->setMaxResults(1)
317
+            ->execute();
318
+
319
+        $row = $result->fetch();
320
+        $result->closeCursor();
321
+        if ($row === false) {
322
+            return null;
323
+        }
324
+
325
+        $addressBook = [
326
+            'id'  => $row['id'],
327
+            'uri' => $row['uri'],
328
+            'principaluri' => $row['principaluri'],
329
+            '{DAV:}displayname' => $row['displayname'],
330
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
331
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
332
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
333
+        ];
334
+
335
+        $this->addOwnerPrincipal($addressBook);
336
+
337
+        return $addressBook;
338
+    }
339
+
340
+    /**
341
+     * Updates properties for an address book.
342
+     *
343
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
344
+     * To do the actual updates, you must tell this object which properties
345
+     * you're going to process with the handle() method.
346
+     *
347
+     * Calling the handle method is like telling the PropPatch object "I
348
+     * promise I can handle updating this property".
349
+     *
350
+     * Read the PropPatch documentation for more info and examples.
351
+     *
352
+     * @param string $addressBookId
353
+     * @param \Sabre\DAV\PropPatch $propPatch
354
+     * @return void
355
+     */
356
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
357
+        $supportedProperties = [
358
+            '{DAV:}displayname',
359
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
360
+        ];
361
+
362
+        /**
363
+         * @suppress SqlInjectionChecker
364
+         */
365
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
366
+
367
+            $updates = [];
368
+            foreach($mutations as $property=>$newValue) {
369
+
370
+                switch($property) {
371
+                    case '{DAV:}displayname' :
372
+                        $updates['displayname'] = $newValue;
373
+                        break;
374
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
375
+                        $updates['description'] = $newValue;
376
+                        break;
377
+                }
378
+            }
379
+            $query = $this->db->getQueryBuilder();
380
+            $query->update('addressbooks');
381
+
382
+            foreach($updates as $key=>$value) {
383
+                $query->set($key, $query->createNamedParameter($value));
384
+            }
385
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
386
+            ->execute();
387
+
388
+            $this->addChange($addressBookId, "", 2);
389
+
390
+            return true;
391
+
392
+        });
393
+    }
394
+
395
+    /**
396
+     * Creates a new address book
397
+     *
398
+     * @param string $principalUri
399
+     * @param string $url Just the 'basename' of the url.
400
+     * @param array $properties
401
+     * @return int
402
+     * @throws BadRequest
403
+     */
404
+    function createAddressBook($principalUri, $url, array $properties) {
405
+        $values = [
406
+            'displayname' => null,
407
+            'description' => null,
408
+            'principaluri' => $principalUri,
409
+            'uri' => $url,
410
+            'synctoken' => 1
411
+        ];
412
+
413
+        foreach($properties as $property=>$newValue) {
414
+
415
+            switch($property) {
416
+                case '{DAV:}displayname' :
417
+                    $values['displayname'] = $newValue;
418
+                    break;
419
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
420
+                    $values['description'] = $newValue;
421
+                    break;
422
+                default :
423
+                    throw new BadRequest('Unknown property: ' . $property);
424
+            }
425
+
426
+        }
427
+
428
+        // Fallback to make sure the displayname is set. Some clients may refuse
429
+        // to work with addressbooks not having a displayname.
430
+        if(is_null($values['displayname'])) {
431
+            $values['displayname'] = $url;
432
+        }
433
+
434
+        $query = $this->db->getQueryBuilder();
435
+        $query->insert('addressbooks')
436
+            ->values([
437
+                'uri' => $query->createParameter('uri'),
438
+                'displayname' => $query->createParameter('displayname'),
439
+                'description' => $query->createParameter('description'),
440
+                'principaluri' => $query->createParameter('principaluri'),
441
+                'synctoken' => $query->createParameter('synctoken'),
442
+            ])
443
+            ->setParameters($values)
444
+            ->execute();
445
+
446
+        return $query->getLastInsertId();
447
+    }
448
+
449
+    /**
450
+     * Deletes an entire addressbook and all its contents
451
+     *
452
+     * @param mixed $addressBookId
453
+     * @return void
454
+     */
455
+    function deleteAddressBook($addressBookId) {
456
+        $query = $this->db->getQueryBuilder();
457
+        $query->delete('cards')
458
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
459
+            ->setParameter('addressbookid', $addressBookId)
460
+            ->execute();
461
+
462
+        $query->delete('addressbookchanges')
463
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
464
+            ->setParameter('addressbookid', $addressBookId)
465
+            ->execute();
466
+
467
+        $query->delete('addressbooks')
468
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
469
+            ->setParameter('id', $addressBookId)
470
+            ->execute();
471
+
472
+        $this->sharingBackend->deleteAllShares($addressBookId);
473
+
474
+        $query->delete($this->dbCardsPropertiesTable)
475
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
476
+            ->execute();
477
+
478
+    }
479
+
480
+    /**
481
+     * Returns all cards for a specific addressbook id.
482
+     *
483
+     * This method should return the following properties for each card:
484
+     *   * carddata - raw vcard data
485
+     *   * uri - Some unique url
486
+     *   * lastmodified - A unix timestamp
487
+     *
488
+     * It's recommended to also return the following properties:
489
+     *   * etag - A unique etag. This must change every time the card changes.
490
+     *   * size - The size of the card in bytes.
491
+     *
492
+     * If these last two properties are provided, less time will be spent
493
+     * calculating them. If they are specified, you can also ommit carddata.
494
+     * This may speed up certain requests, especially with large cards.
495
+     *
496
+     * @param mixed $addressBookId
497
+     * @return array
498
+     */
499
+    function getCards($addressBookId) {
500
+        $query = $this->db->getQueryBuilder();
501
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
502
+            ->from('cards')
503
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
504
+
505
+        $cards = [];
506
+
507
+        $result = $query->execute();
508
+        while($row = $result->fetch()) {
509
+            $row['etag'] = '"' . $row['etag'] . '"';
510
+            $row['carddata'] = $this->readBlob($row['carddata']);
511
+            $cards[] = $row;
512
+        }
513
+        $result->closeCursor();
514
+
515
+        return $cards;
516
+    }
517
+
518
+    /**
519
+     * Returns a specific card.
520
+     *
521
+     * The same set of properties must be returned as with getCards. The only
522
+     * exception is that 'carddata' is absolutely required.
523
+     *
524
+     * If the card does not exist, you must return false.
525
+     *
526
+     * @param mixed $addressBookId
527
+     * @param string $cardUri
528
+     * @return array
529
+     */
530
+    function getCard($addressBookId, $cardUri) {
531
+        $query = $this->db->getQueryBuilder();
532
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
533
+            ->from('cards')
534
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
535
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
536
+            ->setMaxResults(1);
537
+
538
+        $result = $query->execute();
539
+        $row = $result->fetch();
540
+        if (!$row) {
541
+            return false;
542
+        }
543
+        $row['etag'] = '"' . $row['etag'] . '"';
544
+        $row['carddata'] = $this->readBlob($row['carddata']);
545
+
546
+        return $row;
547
+    }
548
+
549
+    /**
550
+     * Returns a list of cards.
551
+     *
552
+     * This method should work identical to getCard, but instead return all the
553
+     * cards in the list as an array.
554
+     *
555
+     * If the backend supports this, it may allow for some speed-ups.
556
+     *
557
+     * @param mixed $addressBookId
558
+     * @param string[] $uris
559
+     * @return array
560
+     */
561
+    function getMultipleCards($addressBookId, array $uris) {
562
+        if (empty($uris)) {
563
+            return [];
564
+        }
565
+
566
+        $chunks = array_chunk($uris, 100);
567
+        $cards = [];
568
+
569
+        $query = $this->db->getQueryBuilder();
570
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
571
+            ->from('cards')
572
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
573
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
574
+
575
+        foreach ($chunks as $uris) {
576
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
577
+            $result = $query->execute();
578
+
579
+            while ($row = $result->fetch()) {
580
+                $row['etag'] = '"' . $row['etag'] . '"';
581
+                $row['carddata'] = $this->readBlob($row['carddata']);
582
+                $cards[] = $row;
583
+            }
584
+            $result->closeCursor();
585
+        }
586
+        return $cards;
587
+    }
588
+
589
+    /**
590
+     * Creates a new card.
591
+     *
592
+     * The addressbook id will be passed as the first argument. This is the
593
+     * same id as it is returned from the getAddressBooksForUser method.
594
+     *
595
+     * The cardUri is a base uri, and doesn't include the full path. The
596
+     * cardData argument is the vcard body, and is passed as a string.
597
+     *
598
+     * It is possible to return an ETag from this method. This ETag is for the
599
+     * newly created resource, and must be enclosed with double quotes (that
600
+     * is, the string itself must contain the double quotes).
601
+     *
602
+     * You should only return the ETag if you store the carddata as-is. If a
603
+     * subsequent GET request on the same card does not have the same body,
604
+     * byte-by-byte and you did return an ETag here, clients tend to get
605
+     * confused.
606
+     *
607
+     * If you don't return an ETag, you can just return null.
608
+     *
609
+     * @param mixed $addressBookId
610
+     * @param string $cardUri
611
+     * @param string $cardData
612
+     * @return string
613
+     */
614
+    function createCard($addressBookId, $cardUri, $cardData) {
615
+        $etag = md5($cardData);
616
+        $uid = $this->getUID($cardData);
617
+
618
+        $q = $this->db->getQueryBuilder();
619
+        $q->select('uid')
620
+            ->from('cards')
621
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
622
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
623
+            ->setMaxResults(1);
624
+        $result = $q->execute();
625
+        $count = (bool) $result->fetchColumn();
626
+        $result->closeCursor();
627
+        if ($count) {
628
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
629
+        }
630
+
631
+        $query = $this->db->getQueryBuilder();
632
+        $query->insert('cards')
633
+            ->values([
634
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
635
+                'uri' => $query->createNamedParameter($cardUri),
636
+                'lastmodified' => $query->createNamedParameter(time()),
637
+                'addressbookid' => $query->createNamedParameter($addressBookId),
638
+                'size' => $query->createNamedParameter(strlen($cardData)),
639
+                'etag' => $query->createNamedParameter($etag),
640
+                'uid' => $query->createNamedParameter($uid),
641
+            ])
642
+            ->execute();
643
+
644
+        $this->addChange($addressBookId, $cardUri, 1);
645
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
646
+
647
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
648
+            new GenericEvent(null, [
649
+                'addressBookId' => $addressBookId,
650
+                'cardUri' => $cardUri,
651
+                'cardData' => $cardData]));
652
+
653
+        return '"' . $etag . '"';
654
+    }
655
+
656
+    /**
657
+     * Updates a card.
658
+     *
659
+     * The addressbook id will be passed as the first argument. This is the
660
+     * same id as it is returned from the getAddressBooksForUser method.
661
+     *
662
+     * The cardUri is a base uri, and doesn't include the full path. The
663
+     * cardData argument is the vcard body, and is passed as a string.
664
+     *
665
+     * It is possible to return an ETag from this method. This ETag should
666
+     * match that of the updated resource, and must be enclosed with double
667
+     * quotes (that is: the string itself must contain the actual quotes).
668
+     *
669
+     * You should only return the ETag if you store the carddata as-is. If a
670
+     * subsequent GET request on the same card does not have the same body,
671
+     * byte-by-byte and you did return an ETag here, clients tend to get
672
+     * confused.
673
+     *
674
+     * If you don't return an ETag, you can just return null.
675
+     *
676
+     * @param mixed $addressBookId
677
+     * @param string $cardUri
678
+     * @param string $cardData
679
+     * @return string
680
+     */
681
+    function updateCard($addressBookId, $cardUri, $cardData) {
682
+
683
+        $uid = $this->getUID($cardData);
684
+        $etag = md5($cardData);
685
+        $query = $this->db->getQueryBuilder();
686
+        $query->update('cards')
687
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
688
+            ->set('lastmodified', $query->createNamedParameter(time()))
689
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
690
+            ->set('etag', $query->createNamedParameter($etag))
691
+            ->set('uid', $query->createNamedParameter($uid))
692
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
693
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
694
+            ->execute();
695
+
696
+        $this->addChange($addressBookId, $cardUri, 2);
697
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
698
+
699
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
700
+            new GenericEvent(null, [
701
+                'addressBookId' => $addressBookId,
702
+                'cardUri' => $cardUri,
703
+                'cardData' => $cardData]));
704
+
705
+        return '"' . $etag . '"';
706
+    }
707
+
708
+    /**
709
+     * Deletes a card
710
+     *
711
+     * @param mixed $addressBookId
712
+     * @param string $cardUri
713
+     * @return bool
714
+     */
715
+    function deleteCard($addressBookId, $cardUri) {
716
+        try {
717
+            $cardId = $this->getCardId($addressBookId, $cardUri);
718
+        } catch (\InvalidArgumentException $e) {
719
+            $cardId = null;
720
+        }
721
+        $query = $this->db->getQueryBuilder();
722
+        $ret = $query->delete('cards')
723
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
724
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
725
+            ->execute();
726
+
727
+        $this->addChange($addressBookId, $cardUri, 3);
728
+
729
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
730
+            new GenericEvent(null, [
731
+                'addressBookId' => $addressBookId,
732
+                'cardUri' => $cardUri]));
733
+
734
+        if ($ret === 1) {
735
+            if ($cardId !== null) {
736
+                $this->purgeProperties($addressBookId, $cardId);
737
+            }
738
+            return true;
739
+        }
740
+
741
+        return false;
742
+    }
743
+
744
+    /**
745
+     * The getChanges method returns all the changes that have happened, since
746
+     * the specified syncToken in the specified address book.
747
+     *
748
+     * This function should return an array, such as the following:
749
+     *
750
+     * [
751
+     *   'syncToken' => 'The current synctoken',
752
+     *   'added'   => [
753
+     *      'new.txt',
754
+     *   ],
755
+     *   'modified'   => [
756
+     *      'modified.txt',
757
+     *   ],
758
+     *   'deleted' => [
759
+     *      'foo.php.bak',
760
+     *      'old.txt'
761
+     *   ]
762
+     * ];
763
+     *
764
+     * The returned syncToken property should reflect the *current* syncToken
765
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
766
+     * property. This is needed here too, to ensure the operation is atomic.
767
+     *
768
+     * If the $syncToken argument is specified as null, this is an initial
769
+     * sync, and all members should be reported.
770
+     *
771
+     * The modified property is an array of nodenames that have changed since
772
+     * the last token.
773
+     *
774
+     * The deleted property is an array with nodenames, that have been deleted
775
+     * from collection.
776
+     *
777
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
778
+     * 1, you only have to report changes that happened only directly in
779
+     * immediate descendants. If it's 2, it should also include changes from
780
+     * the nodes below the child collections. (grandchildren)
781
+     *
782
+     * The $limit argument allows a client to specify how many results should
783
+     * be returned at most. If the limit is not specified, it should be treated
784
+     * as infinite.
785
+     *
786
+     * If the limit (infinite or not) is higher than you're willing to return,
787
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
788
+     *
789
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
790
+     * return null.
791
+     *
792
+     * The limit is 'suggestive'. You are free to ignore it.
793
+     *
794
+     * @param string $addressBookId
795
+     * @param string $syncToken
796
+     * @param int $syncLevel
797
+     * @param int $limit
798
+     * @return array
799
+     */
800
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
801
+        // Current synctoken
802
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
803
+        $stmt->execute([ $addressBookId ]);
804
+        $currentToken = $stmt->fetchColumn(0);
805
+
806
+        if (is_null($currentToken)) return null;
807
+
808
+        $result = [
809
+            'syncToken' => $currentToken,
810
+            'added'     => [],
811
+            'modified'  => [],
812
+            'deleted'   => [],
813
+        ];
814
+
815
+        if ($syncToken) {
816
+
817
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
818
+            if ($limit>0) {
819
+                $query .= " LIMIT " . (int)$limit;
820
+            }
821
+
822
+            // Fetching all changes
823
+            $stmt = $this->db->prepare($query);
824
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
825
+
826
+            $changes = [];
827
+
828
+            // This loop ensures that any duplicates are overwritten, only the
829
+            // last change on a node is relevant.
830
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
831
+
832
+                $changes[$row['uri']] = $row['operation'];
833
+
834
+            }
835
+
836
+            foreach($changes as $uri => $operation) {
837
+
838
+                switch($operation) {
839
+                    case 1:
840
+                        $result['added'][] = $uri;
841
+                        break;
842
+                    case 2:
843
+                        $result['modified'][] = $uri;
844
+                        break;
845
+                    case 3:
846
+                        $result['deleted'][] = $uri;
847
+                        break;
848
+                }
849
+
850
+            }
851
+        } else {
852
+            // No synctoken supplied, this is the initial sync.
853
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
854
+            $stmt = $this->db->prepare($query);
855
+            $stmt->execute([$addressBookId]);
856
+
857
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
858
+        }
859
+        return $result;
860
+    }
861
+
862
+    /**
863
+     * Adds a change record to the addressbookchanges table.
864
+     *
865
+     * @param mixed $addressBookId
866
+     * @param string $objectUri
867
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
868
+     * @return void
869
+     */
870
+    protected function addChange($addressBookId, $objectUri, $operation) {
871
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
872
+        $stmt = $this->db->prepare($sql);
873
+        $stmt->execute([
874
+            $objectUri,
875
+            $addressBookId,
876
+            $operation,
877
+            $addressBookId
878
+        ]);
879
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
880
+        $stmt->execute([
881
+            $addressBookId
882
+        ]);
883
+    }
884
+
885
+    private function readBlob($cardData) {
886
+        if (is_resource($cardData)) {
887
+            return stream_get_contents($cardData);
888
+        }
889
+
890
+        return $cardData;
891
+    }
892
+
893
+    /**
894
+     * @param IShareable $shareable
895
+     * @param string[] $add
896
+     * @param string[] $remove
897
+     */
898
+    public function updateShares(IShareable $shareable, $add, $remove) {
899
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
900
+    }
901
+
902
+    /**
903
+     * search contact
904
+     *
905
+     * @param int $addressBookId
906
+     * @param string $pattern which should match within the $searchProperties
907
+     * @param array $searchProperties defines the properties within the query pattern should match
908
+     * @param array $options = array() to define the search behavior
909
+     * 	- 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
910
+     * @return array an array of contacts which are arrays of key-value-pairs
911
+     */
912
+    public function search($addressBookId, $pattern, $searchProperties, $options = array()) {
913
+        $query = $this->db->getQueryBuilder();
914
+        $query2 = $this->db->getQueryBuilder();
915
+
916
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
917
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
918
+        $or = $query2->expr()->orX();
919
+        foreach ($searchProperties as $property) {
920
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
921
+        }
922
+        $query2->andWhere($or);
923
+
924
+        // No need for like when the pattern is empty
925
+        if ('' !== $pattern) {
926
+            if(\array_key_exists('escape_like_param', $options) && $options['escape_like_param'] === false) {
927
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter($pattern)));
928
+            } else {
929
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
930
+            }
931
+        }
932
+
933
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
934
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
935
+
936
+        $result = $query->execute();
937
+        $cards = $result->fetchAll();
938
+
939
+        $result->closeCursor();
940
+
941
+        return array_map(function($array) {
942
+            $array['carddata'] = $this->readBlob($array['carddata']);
943
+            return $array;
944
+        }, $cards);
945
+    }
946
+
947
+    /**
948
+     * @param int $bookId
949
+     * @param string $name
950
+     * @return array
951
+     */
952
+    public function collectCardProperties($bookId, $name) {
953
+        $query = $this->db->getQueryBuilder();
954
+        $result = $query->selectDistinct('value')
955
+            ->from($this->dbCardsPropertiesTable)
956
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
957
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
958
+            ->execute();
959
+
960
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
961
+        $result->closeCursor();
962
+
963
+        return $all;
964
+    }
965
+
966
+    /**
967
+     * get URI from a given contact
968
+     *
969
+     * @param int $id
970
+     * @return string
971
+     */
972
+    public function getCardUri($id) {
973
+        $query = $this->db->getQueryBuilder();
974
+        $query->select('uri')->from($this->dbCardsTable)
975
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
976
+                ->setParameter('id', $id);
977
+
978
+        $result = $query->execute();
979
+        $uri = $result->fetch();
980
+        $result->closeCursor();
981
+
982
+        if (!isset($uri['uri'])) {
983
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
984
+        }
985
+
986
+        return $uri['uri'];
987
+    }
988
+
989
+    /**
990
+     * return contact with the given URI
991
+     *
992
+     * @param int $addressBookId
993
+     * @param string $uri
994
+     * @returns array
995
+     */
996
+    public function getContact($addressBookId, $uri) {
997
+        $result = [];
998
+        $query = $this->db->getQueryBuilder();
999
+        $query->select('*')->from($this->dbCardsTable)
1000
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1001
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1002
+        $queryResult = $query->execute();
1003
+        $contact = $queryResult->fetch();
1004
+        $queryResult->closeCursor();
1005
+
1006
+        if (is_array($contact)) {
1007
+            $result = $contact;
1008
+        }
1009
+
1010
+        return $result;
1011
+    }
1012
+
1013
+    /**
1014
+     * Returns the list of people whom this address book is shared with.
1015
+     *
1016
+     * Every element in this array should have the following properties:
1017
+     *   * href - Often a mailto: address
1018
+     *   * commonName - Optional, for example a first + last name
1019
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1020
+     *   * readOnly - boolean
1021
+     *   * summary - Optional, a description for the share
1022
+     *
1023
+     * @return array
1024
+     */
1025
+    public function getShares($addressBookId) {
1026
+        return $this->sharingBackend->getShares($addressBookId);
1027
+    }
1028
+
1029
+    /**
1030
+     * update properties table
1031
+     *
1032
+     * @param int $addressBookId
1033
+     * @param string $cardUri
1034
+     * @param string $vCardSerialized
1035
+     */
1036
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1037
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1038
+        $vCard = $this->readCard($vCardSerialized);
1039
+
1040
+        $this->purgeProperties($addressBookId, $cardId);
1041
+
1042
+        $query = $this->db->getQueryBuilder();
1043
+        $query->insert($this->dbCardsPropertiesTable)
1044
+            ->values(
1045
+                [
1046
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1047
+                    'cardid' => $query->createNamedParameter($cardId),
1048
+                    'name' => $query->createParameter('name'),
1049
+                    'value' => $query->createParameter('value'),
1050
+                    'preferred' => $query->createParameter('preferred')
1051
+                ]
1052
+            );
1053
+
1054
+        foreach ($vCard->children() as $property) {
1055
+            if(!in_array($property->name, self::$indexProperties)) {
1056
+                continue;
1057
+            }
1058
+            $preferred = 0;
1059
+            foreach($property->parameters as $parameter) {
1060
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1061
+                    $preferred = 1;
1062
+                    break;
1063
+                }
1064
+            }
1065
+            $query->setParameter('name', $property->name);
1066
+            $query->setParameter('value', mb_substr($property->getValue(), 0, 254));
1067
+            $query->setParameter('preferred', $preferred);
1068
+            $query->execute();
1069
+        }
1070
+    }
1071
+
1072
+    /**
1073
+     * read vCard data into a vCard object
1074
+     *
1075
+     * @param string $cardData
1076
+     * @return VCard
1077
+     */
1078
+    protected function readCard($cardData) {
1079
+        return  Reader::read($cardData);
1080
+    }
1081
+
1082
+    /**
1083
+     * delete all properties from a given card
1084
+     *
1085
+     * @param int $addressBookId
1086
+     * @param int $cardId
1087
+     */
1088
+    protected function purgeProperties($addressBookId, $cardId) {
1089
+        $query = $this->db->getQueryBuilder();
1090
+        $query->delete($this->dbCardsPropertiesTable)
1091
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1092
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1093
+        $query->execute();
1094
+    }
1095
+
1096
+    /**
1097
+     * get ID from a given contact
1098
+     *
1099
+     * @param int $addressBookId
1100
+     * @param string $uri
1101
+     * @return int
1102
+     */
1103
+    protected function getCardId($addressBookId, $uri) {
1104
+        $query = $this->db->getQueryBuilder();
1105
+        $query->select('id')->from($this->dbCardsTable)
1106
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1107
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1108
+
1109
+        $result = $query->execute();
1110
+        $cardIds = $result->fetch();
1111
+        $result->closeCursor();
1112
+
1113
+        if (!isset($cardIds['id'])) {
1114
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1115
+        }
1116
+
1117
+        return (int)$cardIds['id'];
1118
+    }
1119
+
1120
+    /**
1121
+     * For shared address books the sharee is set in the ACL of the address book
1122
+     * @param $addressBookId
1123
+     * @param $acl
1124
+     * @return array
1125
+     */
1126
+    public function applyShareAcl($addressBookId, $acl) {
1127
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1128
+    }
1129
+
1130
+    private function convertPrincipal($principalUri, $toV2) {
1131
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1132
+            list(, $name) = \Sabre\Uri\split($principalUri);
1133
+            if ($toV2 === true) {
1134
+                return "principals/users/$name";
1135
+            }
1136
+            return "principals/$name";
1137
+        }
1138
+        return $principalUri;
1139
+    }
1140
+
1141
+    private function addOwnerPrincipal(&$addressbookInfo) {
1142
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1143
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1144
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1145
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1146
+        } else {
1147
+            $uri = $addressbookInfo['principaluri'];
1148
+        }
1149
+
1150
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1151
+        if (isset($principalInformation['{DAV:}displayname'])) {
1152
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1153
+        }
1154
+    }
1155
+
1156
+    /**
1157
+     * Extract UID from vcard
1158
+     *
1159
+     * @param string $cardData the vcard raw data
1160
+     * @return string the uid
1161
+     * @throws BadRequest if no UID is available
1162
+     */
1163
+    private function getUID($cardData) {
1164
+        if ($cardData != '') {
1165
+            $vCard = Reader::read($cardData);
1166
+            if ($vCard->UID) {
1167
+                $uid = $vCard->UID->getValue();
1168
+                return $uid;
1169
+            }
1170
+            // should already be handled, but just in case
1171
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1172
+        }
1173
+        // should already be handled, but just in case
1174
+        throw new BadRequest('vCard can not be empty');
1175
+    }
1176 1176
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagNode.php 2 patches
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -39,136 +39,136 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagNode implements \Sabre\DAV\INode {
41 41
 
42
-	/**
43
-	 * @var ISystemTag
44
-	 */
45
-	protected $tag;
46
-
47
-	/**
48
-	 * @var ISystemTagManager
49
-	 */
50
-	protected $tagManager;
51
-
52
-	/**
53
-	 * User
54
-	 *
55
-	 * @var IUser
56
-	 */
57
-	protected $user;
58
-
59
-	/**
60
-	 * Whether to allow permissions for admins
61
-	 *
62
-	 * @var bool
63
-	 */
64
-	protected $isAdmin;
65
-
66
-	/**
67
-	 * Sets up the node, expects a full path name
68
-	 *
69
-	 * @param ISystemTag $tag system tag
70
-	 * @param IUser $user user
71
-	 * @param bool $isAdmin whether to allow operations for admins
72
-	 * @param ISystemTagManager $tagManager tag manager
73
-	 */
74
-	public function __construct(ISystemTag $tag, IUser $user, $isAdmin, ISystemTagManager $tagManager) {
75
-		$this->tag = $tag;
76
-		$this->user = $user;
77
-		$this->isAdmin = $isAdmin;
78
-		$this->tagManager = $tagManager;
79
-	}
80
-
81
-	/**
82
-	 *  Returns the id of the tag
83
-	 *
84
-	 * @return string
85
-	 */
86
-	public function getName() {
87
-		return $this->tag->getId();
88
-	}
89
-
90
-	/**
91
-	 * Returns the system tag represented by this node
92
-	 *
93
-	 * @return ISystemTag system tag
94
-	 */
95
-	public function getSystemTag() {
96
-		return $this->tag;
97
-	}
98
-
99
-	/**
100
-	 * Renames the node
101
-	 *
102
-	 * @param string $name The new name
103
-	 *
104
-	 * @throws MethodNotAllowed not allowed to rename node
105
-	 */
106
-	public function setName($name) {
107
-		throw new MethodNotAllowed();
108
-	}
109
-
110
-	/**
111
-	 * Update tag
112
-	 *
113
-	 * @param string $name new tag name
114
-	 * @param bool $userVisible user visible
115
-	 * @param bool $userAssignable user assignable
116
-	 * @throws NotFound whenever the given tag id does not exist
117
-	 * @throws Forbidden whenever there is no permission to update said tag
118
-	 * @throws Conflict whenever a tag already exists with the given attributes
119
-	 */
120
-	public function update($name, $userVisible, $userAssignable) {
121
-		try {
122
-			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
123
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
124
-			}
125
-			if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
126
-				throw new Forbidden('No permission to update tag ' . $this->tag->getId());
127
-			}
128
-
129
-			// only admin is able to change permissions, regular users can only rename
130
-			if (!$this->isAdmin) {
131
-				// only renaming is allowed for regular users
132
-				if ($userVisible !== $this->tag->isUserVisible()
133
-					|| $userAssignable !== $this->tag->isUserAssignable()
134
-				) {
135
-					throw new Forbidden('No permission to update permissions for tag ' . $this->tag->getId());
136
-				}
137
-			}
138
-
139
-			$this->tagManager->updateTag($this->tag->getId(), $name, $userVisible, $userAssignable);
140
-		} catch (TagNotFoundException $e) {
141
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
142
-		} catch (TagAlreadyExistsException $e) {
143
-			throw new Conflict(
144
-				'Tag with the properties "' . $name . '", ' .
145
-				$userVisible . ', ' . $userAssignable . ' already exists'
146
-			);
147
-		}
148
-	}
149
-
150
-	/**
151
-	 * Returns null, not supported
152
-	 *
153
-	 */
154
-	public function getLastModified() {
155
-		return null;
156
-	}
157
-
158
-	public function delete() {
159
-		try {
160
-			if (!$this->isAdmin) {
161
-				throw new Forbidden('No permission to delete tag ' . $this->tag->getId());
162
-			}
163
-
164
-			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
165
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
166
-			}
167
-
168
-			$this->tagManager->deleteTags($this->tag->getId());
169
-		} catch (TagNotFoundException $e) {
170
-			// can happen if concurrent deletion occurred
171
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
172
-		}
173
-	}
42
+    /**
43
+     * @var ISystemTag
44
+     */
45
+    protected $tag;
46
+
47
+    /**
48
+     * @var ISystemTagManager
49
+     */
50
+    protected $tagManager;
51
+
52
+    /**
53
+     * User
54
+     *
55
+     * @var IUser
56
+     */
57
+    protected $user;
58
+
59
+    /**
60
+     * Whether to allow permissions for admins
61
+     *
62
+     * @var bool
63
+     */
64
+    protected $isAdmin;
65
+
66
+    /**
67
+     * Sets up the node, expects a full path name
68
+     *
69
+     * @param ISystemTag $tag system tag
70
+     * @param IUser $user user
71
+     * @param bool $isAdmin whether to allow operations for admins
72
+     * @param ISystemTagManager $tagManager tag manager
73
+     */
74
+    public function __construct(ISystemTag $tag, IUser $user, $isAdmin, ISystemTagManager $tagManager) {
75
+        $this->tag = $tag;
76
+        $this->user = $user;
77
+        $this->isAdmin = $isAdmin;
78
+        $this->tagManager = $tagManager;
79
+    }
80
+
81
+    /**
82
+     *  Returns the id of the tag
83
+     *
84
+     * @return string
85
+     */
86
+    public function getName() {
87
+        return $this->tag->getId();
88
+    }
89
+
90
+    /**
91
+     * Returns the system tag represented by this node
92
+     *
93
+     * @return ISystemTag system tag
94
+     */
95
+    public function getSystemTag() {
96
+        return $this->tag;
97
+    }
98
+
99
+    /**
100
+     * Renames the node
101
+     *
102
+     * @param string $name The new name
103
+     *
104
+     * @throws MethodNotAllowed not allowed to rename node
105
+     */
106
+    public function setName($name) {
107
+        throw new MethodNotAllowed();
108
+    }
109
+
110
+    /**
111
+     * Update tag
112
+     *
113
+     * @param string $name new tag name
114
+     * @param bool $userVisible user visible
115
+     * @param bool $userAssignable user assignable
116
+     * @throws NotFound whenever the given tag id does not exist
117
+     * @throws Forbidden whenever there is no permission to update said tag
118
+     * @throws Conflict whenever a tag already exists with the given attributes
119
+     */
120
+    public function update($name, $userVisible, $userAssignable) {
121
+        try {
122
+            if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
123
+                throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
124
+            }
125
+            if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
126
+                throw new Forbidden('No permission to update tag ' . $this->tag->getId());
127
+            }
128
+
129
+            // only admin is able to change permissions, regular users can only rename
130
+            if (!$this->isAdmin) {
131
+                // only renaming is allowed for regular users
132
+                if ($userVisible !== $this->tag->isUserVisible()
133
+                    || $userAssignable !== $this->tag->isUserAssignable()
134
+                ) {
135
+                    throw new Forbidden('No permission to update permissions for tag ' . $this->tag->getId());
136
+                }
137
+            }
138
+
139
+            $this->tagManager->updateTag($this->tag->getId(), $name, $userVisible, $userAssignable);
140
+        } catch (TagNotFoundException $e) {
141
+            throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
142
+        } catch (TagAlreadyExistsException $e) {
143
+            throw new Conflict(
144
+                'Tag with the properties "' . $name . '", ' .
145
+                $userVisible . ', ' . $userAssignable . ' already exists'
146
+            );
147
+        }
148
+    }
149
+
150
+    /**
151
+     * Returns null, not supported
152
+     *
153
+     */
154
+    public function getLastModified() {
155
+        return null;
156
+    }
157
+
158
+    public function delete() {
159
+        try {
160
+            if (!$this->isAdmin) {
161
+                throw new Forbidden('No permission to delete tag ' . $this->tag->getId());
162
+            }
163
+
164
+            if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
165
+                throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
166
+            }
167
+
168
+            $this->tagManager->deleteTags($this->tag->getId());
169
+        } catch (TagNotFoundException $e) {
170
+            // can happen if concurrent deletion occurred
171
+            throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
172
+        }
173
+    }
174 174
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -120,10 +120,10 @@  discard block
 block discarded – undo
120 120
 	public function update($name, $userVisible, $userAssignable) {
121 121
 		try {
122 122
 			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
123
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
123
+				throw new NotFound('Tag with id '.$this->tag->getId().' does not exist');
124 124
 			}
125 125
 			if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
126
-				throw new Forbidden('No permission to update tag ' . $this->tag->getId());
126
+				throw new Forbidden('No permission to update tag '.$this->tag->getId());
127 127
 			}
128 128
 
129 129
 			// only admin is able to change permissions, regular users can only rename
@@ -132,17 +132,17 @@  discard block
 block discarded – undo
132 132
 				if ($userVisible !== $this->tag->isUserVisible()
133 133
 					|| $userAssignable !== $this->tag->isUserAssignable()
134 134
 				) {
135
-					throw new Forbidden('No permission to update permissions for tag ' . $this->tag->getId());
135
+					throw new Forbidden('No permission to update permissions for tag '.$this->tag->getId());
136 136
 				}
137 137
 			}
138 138
 
139 139
 			$this->tagManager->updateTag($this->tag->getId(), $name, $userVisible, $userAssignable);
140 140
 		} catch (TagNotFoundException $e) {
141
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' does not exist');
141
+			throw new NotFound('Tag with id '.$this->tag->getId().' does not exist');
142 142
 		} catch (TagAlreadyExistsException $e) {
143 143
 			throw new Conflict(
144
-				'Tag with the properties "' . $name . '", ' .
145
-				$userVisible . ', ' . $userAssignable . ' already exists'
144
+				'Tag with the properties "'.$name.'", '.
145
+				$userVisible.', '.$userAssignable.' already exists'
146 146
 			);
147 147
 		}
148 148
 	}
@@ -158,17 +158,17 @@  discard block
 block discarded – undo
158 158
 	public function delete() {
159 159
 		try {
160 160
 			if (!$this->isAdmin) {
161
-				throw new Forbidden('No permission to delete tag ' . $this->tag->getId());
161
+				throw new Forbidden('No permission to delete tag '.$this->tag->getId());
162 162
 			}
163 163
 
164 164
 			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
165
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
165
+				throw new NotFound('Tag with id '.$this->tag->getId().' not found');
166 166
 			}
167 167
 
168 168
 			$this->tagManager->deleteTags($this->tag->getId());
169 169
 		} catch (TagNotFoundException $e) {
170 170
 			// can happen if concurrent deletion occurred
171
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
171
+			throw new NotFound('Tag with id '.$this->tag->getId().' not found', 0, $e);
172 172
 		}
173 173
 	}
174 174
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsByIdCollection.php 2 patches
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -37,144 +37,144 @@
 block discarded – undo
37 37
 
38 38
 class SystemTagsByIdCollection implements ICollection {
39 39
 
40
-	/**
41
-	 * @var ISystemTagManager
42
-	 */
43
-	private $tagManager;
44
-
45
-	/**
46
-	 * @var IGroupManager
47
-	 */
48
-	private $groupManager;
49
-
50
-	/**
51
-	 * @var IUserSession
52
-	 */
53
-	private $userSession;
54
-
55
-	/**
56
-	 * SystemTagsByIdCollection constructor.
57
-	 *
58
-	 * @param ISystemTagManager $tagManager
59
-	 * @param IUserSession $userSession
60
-	 * @param IGroupManager $groupManager
61
-	 */
62
-	public function __construct(
63
-		ISystemTagManager $tagManager,
64
-		IUserSession $userSession,
65
-		IGroupManager $groupManager
66
-	) {
67
-		$this->tagManager = $tagManager;
68
-		$this->userSession = $userSession;
69
-		$this->groupManager = $groupManager;
70
-	}
71
-
72
-	/**
73
-	 * Returns whether the currently logged in user is an administrator
74
-	 *
75
-	 * @return bool true if the user is an admin
76
-	 */
77
-	private function isAdmin() {
78
-		$user = $this->userSession->getUser();
79
-		if ($user !== null) {
80
-			return $this->groupManager->isAdmin($user->getUID());
81
-		}
82
-		return false;
83
-	}
84
-
85
-	/**
86
-	 * @param string $name
87
-	 * @param resource|string $data Initial payload
88
-	 * @throws Forbidden
89
-	 */
90
-	function createFile($name, $data = null) {
91
-		throw new Forbidden('Cannot create tags by id');
92
-	}
93
-
94
-	/**
95
-	 * @param string $name
96
-	 */
97
-	function createDirectory($name) {
98
-		throw new Forbidden('Permission denied to create collections');
99
-	}
100
-
101
-	/**
102
-	 * @param string $name
103
-	 */
104
-	function getChild($name) {
105
-		try {
106
-			$tag = $this->tagManager->getTagsByIds([$name]);
107
-			$tag = current($tag);
108
-			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
-				throw new NotFound('Tag with id ' . $name . ' not found');
110
-			}
111
-			return $this->makeNode($tag);
112
-		} catch (\InvalidArgumentException $e) {
113
-			throw new BadRequest('Invalid tag id', 0, $e);
114
-		} catch (TagNotFoundException $e) {
115
-			throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
116
-		}
117
-	}
118
-
119
-	function getChildren() {
120
-		$visibilityFilter = true;
121
-		if ($this->isAdmin()) {
122
-			$visibilityFilter = null;
123
-		}
124
-
125
-		$tags = $this->tagManager->getAllTags($visibilityFilter);
126
-		return array_map(function($tag) {
127
-			return $this->makeNode($tag);
128
-		}, $tags);
129
-	}
130
-
131
-	/**
132
-	 * @param string $name
133
-	 */
134
-	function childExists($name) {
135
-		try {
136
-			$tag = $this->tagManager->getTagsByIds([$name]);
137
-			$tag = current($tag);
138
-			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
139
-				return false;
140
-			}
141
-			return true;
142
-		} catch (\InvalidArgumentException $e) {
143
-			throw new BadRequest('Invalid tag id', 0, $e);
144
-		} catch (TagNotFoundException $e) {
145
-			return false;
146
-		}
147
-	}
148
-
149
-	function delete() {
150
-		throw new Forbidden('Permission denied to delete this collection');
151
-	}
152
-
153
-	function getName() {
154
-		return 'systemtags';
155
-	}
156
-
157
-	function setName($name) {
158
-		throw new Forbidden('Permission denied to rename this collection');
159
-	}
160
-
161
-	/**
162
-	 * Returns the last modification time, as a unix timestamp
163
-	 *
164
-	 * @return int
165
-	 */
166
-	function getLastModified() {
167
-		return null;
168
-	}
169
-
170
-	/**
171
-	 * Create a sabre node for the given system tag
172
-	 *
173
-	 * @param ISystemTag $tag
174
-	 *
175
-	 * @return SystemTagNode
176
-	 */
177
-	private function makeNode(ISystemTag $tag) {
178
-		return new SystemTagNode($tag, $this->userSession->getUser(), $this->isAdmin(), $this->tagManager);
179
-	}
40
+    /**
41
+     * @var ISystemTagManager
42
+     */
43
+    private $tagManager;
44
+
45
+    /**
46
+     * @var IGroupManager
47
+     */
48
+    private $groupManager;
49
+
50
+    /**
51
+     * @var IUserSession
52
+     */
53
+    private $userSession;
54
+
55
+    /**
56
+     * SystemTagsByIdCollection constructor.
57
+     *
58
+     * @param ISystemTagManager $tagManager
59
+     * @param IUserSession $userSession
60
+     * @param IGroupManager $groupManager
61
+     */
62
+    public function __construct(
63
+        ISystemTagManager $tagManager,
64
+        IUserSession $userSession,
65
+        IGroupManager $groupManager
66
+    ) {
67
+        $this->tagManager = $tagManager;
68
+        $this->userSession = $userSession;
69
+        $this->groupManager = $groupManager;
70
+    }
71
+
72
+    /**
73
+     * Returns whether the currently logged in user is an administrator
74
+     *
75
+     * @return bool true if the user is an admin
76
+     */
77
+    private function isAdmin() {
78
+        $user = $this->userSession->getUser();
79
+        if ($user !== null) {
80
+            return $this->groupManager->isAdmin($user->getUID());
81
+        }
82
+        return false;
83
+    }
84
+
85
+    /**
86
+     * @param string $name
87
+     * @param resource|string $data Initial payload
88
+     * @throws Forbidden
89
+     */
90
+    function createFile($name, $data = null) {
91
+        throw new Forbidden('Cannot create tags by id');
92
+    }
93
+
94
+    /**
95
+     * @param string $name
96
+     */
97
+    function createDirectory($name) {
98
+        throw new Forbidden('Permission denied to create collections');
99
+    }
100
+
101
+    /**
102
+     * @param string $name
103
+     */
104
+    function getChild($name) {
105
+        try {
106
+            $tag = $this->tagManager->getTagsByIds([$name]);
107
+            $tag = current($tag);
108
+            if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
+                throw new NotFound('Tag with id ' . $name . ' not found');
110
+            }
111
+            return $this->makeNode($tag);
112
+        } catch (\InvalidArgumentException $e) {
113
+            throw new BadRequest('Invalid tag id', 0, $e);
114
+        } catch (TagNotFoundException $e) {
115
+            throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
116
+        }
117
+    }
118
+
119
+    function getChildren() {
120
+        $visibilityFilter = true;
121
+        if ($this->isAdmin()) {
122
+            $visibilityFilter = null;
123
+        }
124
+
125
+        $tags = $this->tagManager->getAllTags($visibilityFilter);
126
+        return array_map(function($tag) {
127
+            return $this->makeNode($tag);
128
+        }, $tags);
129
+    }
130
+
131
+    /**
132
+     * @param string $name
133
+     */
134
+    function childExists($name) {
135
+        try {
136
+            $tag = $this->tagManager->getTagsByIds([$name]);
137
+            $tag = current($tag);
138
+            if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
139
+                return false;
140
+            }
141
+            return true;
142
+        } catch (\InvalidArgumentException $e) {
143
+            throw new BadRequest('Invalid tag id', 0, $e);
144
+        } catch (TagNotFoundException $e) {
145
+            return false;
146
+        }
147
+    }
148
+
149
+    function delete() {
150
+        throw new Forbidden('Permission denied to delete this collection');
151
+    }
152
+
153
+    function getName() {
154
+        return 'systemtags';
155
+    }
156
+
157
+    function setName($name) {
158
+        throw new Forbidden('Permission denied to rename this collection');
159
+    }
160
+
161
+    /**
162
+     * Returns the last modification time, as a unix timestamp
163
+     *
164
+     * @return int
165
+     */
166
+    function getLastModified() {
167
+        return null;
168
+    }
169
+
170
+    /**
171
+     * Create a sabre node for the given system tag
172
+     *
173
+     * @param ISystemTag $tag
174
+     *
175
+     * @return SystemTagNode
176
+     */
177
+    private function makeNode(ISystemTag $tag) {
178
+        return new SystemTagNode($tag, $this->userSession->getUser(), $this->isAdmin(), $this->tagManager);
179
+    }
180 180
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -106,13 +106,13 @@
 block discarded – undo
106 106
 			$tag = $this->tagManager->getTagsByIds([$name]);
107 107
 			$tag = current($tag);
108 108
 			if (!$this->tagManager->canUserSeeTag($tag, $this->userSession->getUser())) {
109
-				throw new NotFound('Tag with id ' . $name . ' not found');
109
+				throw new NotFound('Tag with id '.$name.' not found');
110 110
 			}
111 111
 			return $this->makeNode($tag);
112 112
 		} catch (\InvalidArgumentException $e) {
113 113
 			throw new BadRequest('Invalid tag id', 0, $e);
114 114
 		} catch (TagNotFoundException $e) {
115
-			throw new NotFound('Tag with id ' . $name . ' not found', 0, $e);
115
+			throw new NotFound('Tag with id '.$name.' not found', 0, $e);
116 116
 		}
117 117
 	}
118 118
 
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php 2 patches
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -39,136 +39,136 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectTypeCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectType;
46
-
47
-	/**
48
-	 * @var ISystemTagManager
49
-	 */
50
-	private $tagManager;
51
-
52
-	/**
53
-	 * @var ISystemTagObjectMapper
54
-	 */
55
-	private $tagMapper;
56
-
57
-	/**
58
-	 * @var IGroupManager
59
-	 */
60
-	private $groupManager;
61
-
62
-	/**
63
-	 * @var IUserSession
64
-	 */
65
-	private $userSession;
66
-
67
-	/**
68
-	 * @var \Closure
69
-	 **/
70
-	protected $childExistsFunction;
71
-
72
-	/**
73
-	 * Constructor
74
-	 *
75
-	 * @param string $objectType object type
76
-	 * @param ISystemTagManager $tagManager
77
-	 * @param ISystemTagObjectMapper $tagMapper
78
-	 * @param IUserSession $userSession
79
-	 * @param IGroupManager $groupManager
80
-	 * @param \Closure $childExistsFunction
81
-	 */
82
-	public function __construct(
83
-		$objectType, 
84
-		ISystemTagManager $tagManager,
85
-		ISystemTagObjectMapper $tagMapper,
86
-		IUserSession $userSession,
87
-		IGroupManager $groupManager,
88
-		\Closure $childExistsFunction
89
-	) {
90
-		$this->tagManager = $tagManager;
91
-		$this->tagMapper = $tagMapper;
92
-		$this->objectType = $objectType;
93
-		$this->userSession = $userSession;
94
-		$this->groupManager = $groupManager;
95
-		$this->childExistsFunction = $childExistsFunction;
96
-	}
97
-
98
-	/**
99
-	 * @param string $name
100
-	 * @param resource|string $data Initial payload
101
-	 * @return null|string
102
-	 * @throws Forbidden
103
-	 */
104
-	function createFile($name, $data = null) {
105
-		throw new Forbidden('Permission denied to create nodes');
106
-	}
107
-
108
-	/**
109
-	 * @param string $name
110
-	 * @throws Forbidden
111
-	 */
112
-	function createDirectory($name) {
113
-		throw new Forbidden('Permission denied to create collections');
114
-	}
115
-
116
-	/**
117
-	 * @param string $objectId
118
-	 * @return SystemTagsObjectMappingCollection
119
-	 * @throws NotFound
120
-	 */
121
-	function getChild($objectId) {
122
-		// make sure the object exists and is reachable
123
-		if(!$this->childExists($objectId)) {
124
-			throw new NotFound('Entity does not exist or is not available');
125
-		}
126
-		return new SystemTagsObjectMappingCollection(
127
-			$objectId,
128
-			$this->objectType,
129
-			$this->userSession->getUser(),
130
-			$this->tagManager,
131
-			$this->tagMapper
132
-		);
133
-	}
134
-
135
-	function getChildren() {
136
-		// do not list object ids
137
-		throw new MethodNotAllowed();
138
-	}
139
-
140
-	/**
141
-	 * Checks if a child-node with the specified name exists
142
-	 *
143
-	 * @param string $name
144
-	 * @return bool
145
-	 */
146
-	function childExists($name) {
147
-		return call_user_func($this->childExistsFunction, $name);
148
-	}
149
-
150
-	function delete() {
151
-		throw new Forbidden('Permission denied to delete this collection');
152
-	}
153
-
154
-	function getName() {
155
-		return $this->objectType;
156
-	}
157
-
158
-	/**
159
-	 * @param string $name
160
-	 * @throws Forbidden
161
-	 */
162
-	function setName($name) {
163
-		throw new Forbidden('Permission denied to rename this collection');
164
-	}
165
-
166
-	/**
167
-	 * Returns the last modification time, as a unix timestamp
168
-	 *
169
-	 * @return int
170
-	 */
171
-	function getLastModified() {
172
-		return null;
173
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectType;
46
+
47
+    /**
48
+     * @var ISystemTagManager
49
+     */
50
+    private $tagManager;
51
+
52
+    /**
53
+     * @var ISystemTagObjectMapper
54
+     */
55
+    private $tagMapper;
56
+
57
+    /**
58
+     * @var IGroupManager
59
+     */
60
+    private $groupManager;
61
+
62
+    /**
63
+     * @var IUserSession
64
+     */
65
+    private $userSession;
66
+
67
+    /**
68
+     * @var \Closure
69
+     **/
70
+    protected $childExistsFunction;
71
+
72
+    /**
73
+     * Constructor
74
+     *
75
+     * @param string $objectType object type
76
+     * @param ISystemTagManager $tagManager
77
+     * @param ISystemTagObjectMapper $tagMapper
78
+     * @param IUserSession $userSession
79
+     * @param IGroupManager $groupManager
80
+     * @param \Closure $childExistsFunction
81
+     */
82
+    public function __construct(
83
+        $objectType, 
84
+        ISystemTagManager $tagManager,
85
+        ISystemTagObjectMapper $tagMapper,
86
+        IUserSession $userSession,
87
+        IGroupManager $groupManager,
88
+        \Closure $childExistsFunction
89
+    ) {
90
+        $this->tagManager = $tagManager;
91
+        $this->tagMapper = $tagMapper;
92
+        $this->objectType = $objectType;
93
+        $this->userSession = $userSession;
94
+        $this->groupManager = $groupManager;
95
+        $this->childExistsFunction = $childExistsFunction;
96
+    }
97
+
98
+    /**
99
+     * @param string $name
100
+     * @param resource|string $data Initial payload
101
+     * @return null|string
102
+     * @throws Forbidden
103
+     */
104
+    function createFile($name, $data = null) {
105
+        throw new Forbidden('Permission denied to create nodes');
106
+    }
107
+
108
+    /**
109
+     * @param string $name
110
+     * @throws Forbidden
111
+     */
112
+    function createDirectory($name) {
113
+        throw new Forbidden('Permission denied to create collections');
114
+    }
115
+
116
+    /**
117
+     * @param string $objectId
118
+     * @return SystemTagsObjectMappingCollection
119
+     * @throws NotFound
120
+     */
121
+    function getChild($objectId) {
122
+        // make sure the object exists and is reachable
123
+        if(!$this->childExists($objectId)) {
124
+            throw new NotFound('Entity does not exist or is not available');
125
+        }
126
+        return new SystemTagsObjectMappingCollection(
127
+            $objectId,
128
+            $this->objectType,
129
+            $this->userSession->getUser(),
130
+            $this->tagManager,
131
+            $this->tagMapper
132
+        );
133
+    }
134
+
135
+    function getChildren() {
136
+        // do not list object ids
137
+        throw new MethodNotAllowed();
138
+    }
139
+
140
+    /**
141
+     * Checks if a child-node with the specified name exists
142
+     *
143
+     * @param string $name
144
+     * @return bool
145
+     */
146
+    function childExists($name) {
147
+        return call_user_func($this->childExistsFunction, $name);
148
+    }
149
+
150
+    function delete() {
151
+        throw new Forbidden('Permission denied to delete this collection');
152
+    }
153
+
154
+    function getName() {
155
+        return $this->objectType;
156
+    }
157
+
158
+    /**
159
+     * @param string $name
160
+     * @throws Forbidden
161
+     */
162
+    function setName($name) {
163
+        throw new Forbidden('Permission denied to rename this collection');
164
+    }
165
+
166
+    /**
167
+     * Returns the last modification time, as a unix timestamp
168
+     *
169
+     * @return int
170
+     */
171
+    function getLastModified() {
172
+        return null;
173
+    }
174 174
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@
 block discarded – undo
120 120
 	 */
121 121
 	function getChild($objectId) {
122 122
 		// make sure the object exists and is reachable
123
-		if(!$this->childExists($objectId)) {
123
+		if (!$this->childExists($objectId)) {
124 124
 			throw new NotFound('Entity does not exist or is not available');
125 125
 		}
126 126
 		return new SystemTagsObjectMappingCollection(
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagMappingNode.php 2 patches
Indentation   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -37,134 +37,134 @@
 block discarded – undo
37 37
  * Mapping node for system tag to object id
38 38
  */
39 39
 class SystemTagMappingNode implements \Sabre\DAV\INode {
40
-	/**
41
-	 * @var ISystemTag
42
-	 */
43
-	protected $tag;
44
-
45
-	/**
46
-	 * @var string
47
-	 */
48
-	private $objectId;
49
-
50
-	/**
51
-	 * @var string
52
-	 */
53
-	private $objectType;
54
-
55
-	/**
56
-	 * User
57
-	 *
58
-	 * @var IUser
59
-	 */
60
-	protected $user;
61
-
62
-	/**
63
-	 * @var ISystemTagManager
64
-	 */
65
-	protected $tagManager;
66
-
67
-	/**
68
-	 * @var ISystemTagObjectMapper
69
-	 */
70
-	private $tagMapper;
71
-
72
-	/**
73
-	 * Sets up the node, expects a full path name
74
-	 *
75
-	 * @param ISystemTag $tag system tag
76
-	 * @param string $objectId
77
-	 * @param string $objectType
78
-	 * @param IUser $user user
79
-	 * @param ISystemTagManager $tagManager
80
-	 * @param ISystemTagObjectMapper $tagMapper
81
-	 */
82
-	public function __construct(
83
-		ISystemTag $tag,
84
-		$objectId,
85
-		$objectType,
86
-		IUser $user,
87
-		ISystemTagManager $tagManager,
88
-		ISystemTagObjectMapper $tagMapper
89
-	) {
90
-		$this->tag = $tag;
91
-		$this->objectId = $objectId;
92
-		$this->objectType = $objectType;
93
-		$this->user = $user;
94
-		$this->tagManager = $tagManager;
95
-		$this->tagMapper = $tagMapper;
96
-	}
97
-
98
-	/**
99
-	 * Returns the object id of the relationship
100
-	 *
101
-	 * @return string object id
102
-	 */
103
-	public function getObjectId() {
104
-		return $this->objectId;
105
-	}
106
-
107
-	/**
108
-	 * Returns the object type of the relationship
109
-	 *
110
-	 * @return string object type
111
-	 */
112
-	public function getObjectType() {
113
-		return $this->objectType;
114
-	}
115
-
116
-	/**
117
-	 * Returns the system tag represented by this node
118
-	 *
119
-	 * @return ISystemTag system tag
120
-	 */
121
-	public function getSystemTag() {
122
-		return $this->tag;
123
-	}
124
-
125
-	/**
126
-	 *  Returns the id of the tag
127
-	 *
128
-	 * @return string
129
-	 */
130
-	public function getName() {
131
-		return $this->tag->getId();
132
-	}
133
-
134
-	/**
135
-	 * Renames the node
136
-	 *
137
-	 * @param string $name The new name
138
-	 *
139
-	 * @throws MethodNotAllowed not allowed to rename node
140
-	 */
141
-	public function setName($name) {
142
-		throw new MethodNotAllowed();
143
-	}
144
-
145
-	/**
146
-	 * Returns null, not supported
147
-	 *
148
-	 */
149
-	public function getLastModified() {
150
-		return null;
151
-	}
152
-
153
-	/**
154
-	 * Delete tag to object association
155
-	 */
156
-	public function delete() {
157
-		try {
158
-			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
159
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
160
-			}
161
-			if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
162
-				throw new Forbidden('No permission to unassign tag ' . $this->tag->getId());
163
-			}
164
-			$this->tagMapper->unassignTags($this->objectId, $this->objectType, $this->tag->getId());
165
-		} catch (TagNotFoundException $e) {
166
-			// can happen if concurrent deletion occurred
167
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
168
-		}
169
-	}
40
+    /**
41
+     * @var ISystemTag
42
+     */
43
+    protected $tag;
44
+
45
+    /**
46
+     * @var string
47
+     */
48
+    private $objectId;
49
+
50
+    /**
51
+     * @var string
52
+     */
53
+    private $objectType;
54
+
55
+    /**
56
+     * User
57
+     *
58
+     * @var IUser
59
+     */
60
+    protected $user;
61
+
62
+    /**
63
+     * @var ISystemTagManager
64
+     */
65
+    protected $tagManager;
66
+
67
+    /**
68
+     * @var ISystemTagObjectMapper
69
+     */
70
+    private $tagMapper;
71
+
72
+    /**
73
+     * Sets up the node, expects a full path name
74
+     *
75
+     * @param ISystemTag $tag system tag
76
+     * @param string $objectId
77
+     * @param string $objectType
78
+     * @param IUser $user user
79
+     * @param ISystemTagManager $tagManager
80
+     * @param ISystemTagObjectMapper $tagMapper
81
+     */
82
+    public function __construct(
83
+        ISystemTag $tag,
84
+        $objectId,
85
+        $objectType,
86
+        IUser $user,
87
+        ISystemTagManager $tagManager,
88
+        ISystemTagObjectMapper $tagMapper
89
+    ) {
90
+        $this->tag = $tag;
91
+        $this->objectId = $objectId;
92
+        $this->objectType = $objectType;
93
+        $this->user = $user;
94
+        $this->tagManager = $tagManager;
95
+        $this->tagMapper = $tagMapper;
96
+    }
97
+
98
+    /**
99
+     * Returns the object id of the relationship
100
+     *
101
+     * @return string object id
102
+     */
103
+    public function getObjectId() {
104
+        return $this->objectId;
105
+    }
106
+
107
+    /**
108
+     * Returns the object type of the relationship
109
+     *
110
+     * @return string object type
111
+     */
112
+    public function getObjectType() {
113
+        return $this->objectType;
114
+    }
115
+
116
+    /**
117
+     * Returns the system tag represented by this node
118
+     *
119
+     * @return ISystemTag system tag
120
+     */
121
+    public function getSystemTag() {
122
+        return $this->tag;
123
+    }
124
+
125
+    /**
126
+     *  Returns the id of the tag
127
+     *
128
+     * @return string
129
+     */
130
+    public function getName() {
131
+        return $this->tag->getId();
132
+    }
133
+
134
+    /**
135
+     * Renames the node
136
+     *
137
+     * @param string $name The new name
138
+     *
139
+     * @throws MethodNotAllowed not allowed to rename node
140
+     */
141
+    public function setName($name) {
142
+        throw new MethodNotAllowed();
143
+    }
144
+
145
+    /**
146
+     * Returns null, not supported
147
+     *
148
+     */
149
+    public function getLastModified() {
150
+        return null;
151
+    }
152
+
153
+    /**
154
+     * Delete tag to object association
155
+     */
156
+    public function delete() {
157
+        try {
158
+            if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
159
+                throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
160
+            }
161
+            if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
162
+                throw new Forbidden('No permission to unassign tag ' . $this->tag->getId());
163
+            }
164
+            $this->tagMapper->unassignTags($this->objectId, $this->objectType, $this->tag->getId());
165
+        } catch (TagNotFoundException $e) {
166
+            // can happen if concurrent deletion occurred
167
+            throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
168
+        }
169
+    }
170 170
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -156,15 +156,15 @@
 block discarded – undo
156 156
 	public function delete() {
157 157
 		try {
158 158
 			if (!$this->tagManager->canUserSeeTag($this->tag, $this->user)) {
159
-				throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found');
159
+				throw new NotFound('Tag with id '.$this->tag->getId().' not found');
160 160
 			}
161 161
 			if (!$this->tagManager->canUserAssignTag($this->tag, $this->user)) {
162
-				throw new Forbidden('No permission to unassign tag ' . $this->tag->getId());
162
+				throw new Forbidden('No permission to unassign tag '.$this->tag->getId());
163 163
 			}
164 164
 			$this->tagMapper->unassignTags($this->objectId, $this->objectType, $this->tag->getId());
165 165
 		} catch (TagNotFoundException $e) {
166 166
 			// can happen if concurrent deletion occurred
167
-			throw new NotFound('Tag with id ' . $this->tag->getId() . ' not found', 0, $e);
167
+			throw new NotFound('Tag with id '.$this->tag->getId().' not found', 0, $e);
168 168
 		}
169 169
 	}
170 170
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagPlugin.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 			if ($node instanceof SystemTagsObjectMappingCollection) {
136 136
 				// also add to collection
137 137
 				$node->createFile($tag->getId());
138
-				$url = $request->getBaseUrl() . 'systemtags/';
138
+				$url = $request->getBaseUrl().'systemtags/';
139 139
 			} else {
140 140
 				$url = $request->getUrl();
141 141
 			}
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 				$url .= '/';
145 145
 			}
146 146
 
147
-			$response->setHeader('Content-Location', $url . $tag->getId());
147
+			$response->setHeader('Content-Location', $url.$tag->getId());
148 148
 
149 149
 			// created
150 150
 			$response->setStatus(201);
@@ -179,11 +179,11 @@  discard block
 block discarded – undo
179 179
 		$userAssignable = true;
180 180
 
181 181
 		if (isset($data['userVisible'])) {
182
-			$userVisible = (bool)$data['userVisible'];
182
+			$userVisible = (bool) $data['userVisible'];
183 183
 		}
184 184
 
185 185
 		if (isset($data['userAssignable'])) {
186
-			$userAssignable = (bool)$data['userAssignable'];
186
+			$userAssignable = (bool) $data['userAssignable'];
187 187
 		}
188 188
 
189 189
 		$groups = [];
@@ -194,8 +194,8 @@  discard block
 block discarded – undo
194 194
 			}
195 195
 		}
196 196
 
197
-		if($userVisible === false || $userAssignable === false || !empty($groups)) {
198
-			if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
197
+		if ($userVisible === false || $userAssignable === false || !empty($groups)) {
198
+			if (!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
199 199
 				throw new BadRequest('Not sufficient permissions');
200 200
 			}
201 201
 		}
Please login to merge, or discard this patch.
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -46,280 +46,280 @@
 block discarded – undo
46 46
  */
47 47
 class SystemTagPlugin extends \Sabre\DAV\ServerPlugin {
48 48
 
49
-	// namespace
50
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
51
-	const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
52
-	const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
53
-	const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
54
-	const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
55
-	const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
56
-	const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
57
-
58
-	/**
59
-	 * @var \Sabre\DAV\Server $server
60
-	 */
61
-	private $server;
62
-
63
-	/**
64
-	 * @var ISystemTagManager
65
-	 */
66
-	protected $tagManager;
67
-
68
-	/**
69
-	 * @var IUserSession
70
-	 */
71
-	protected $userSession;
72
-
73
-	/**
74
-	 * @var IGroupManager
75
-	 */
76
-	protected $groupManager;
77
-
78
-	/**
79
-	 * @param ISystemTagManager $tagManager tag manager
80
-	 * @param IGroupManager $groupManager
81
-	 * @param IUserSession $userSession
82
-	 */
83
-	public function __construct(ISystemTagManager $tagManager,
84
-								IGroupManager $groupManager,
85
-								IUserSession $userSession) {
86
-		$this->tagManager = $tagManager;
87
-		$this->userSession = $userSession;
88
-		$this->groupManager = $groupManager;
89
-	}
90
-
91
-	/**
92
-	 * This initializes the plugin.
93
-	 *
94
-	 * This function is called by \Sabre\DAV\Server, after
95
-	 * addPlugin is called.
96
-	 *
97
-	 * This method should set up the required event subscriptions.
98
-	 *
99
-	 * @param \Sabre\DAV\Server $server
100
-	 * @return void
101
-	 */
102
-	public function initialize(\Sabre\DAV\Server $server) {
103
-
104
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
105
-
106
-		$server->protectedProperties[] = self::ID_PROPERTYNAME;
107
-
108
-		$server->on('propFind', array($this, 'handleGetProperties'));
109
-		$server->on('propPatch', array($this, 'handleUpdateProperties'));
110
-		$server->on('method:POST', [$this, 'httpPost']);
111
-
112
-		$this->server = $server;
113
-	}
114
-
115
-	/**
116
-	 * POST operation on system tag collections
117
-	 *
118
-	 * @param RequestInterface $request request object
119
-	 * @param ResponseInterface $response response object
120
-	 * @return null|false
121
-	 */
122
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
123
-		$path = $request->getPath();
124
-
125
-		// Making sure the node exists
126
-		$node = $this->server->tree->getNodeForPath($path);
127
-		if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
128
-			$data = $request->getBodyAsString();
129
-
130
-			$tag = $this->createTag($data, $request->getHeader('Content-Type'));
131
-
132
-			if ($node instanceof SystemTagsObjectMappingCollection) {
133
-				// also add to collection
134
-				$node->createFile($tag->getId());
135
-				$url = $request->getBaseUrl() . 'systemtags/';
136
-			} else {
137
-				$url = $request->getUrl();
138
-			}
139
-
140
-			if ($url[strlen($url) - 1] !== '/') {
141
-				$url .= '/';
142
-			}
143
-
144
-			$response->setHeader('Content-Location', $url . $tag->getId());
145
-
146
-			// created
147
-			$response->setStatus(201);
148
-			return false;
149
-		}
150
-	}
151
-
152
-	/**
153
-	 * Creates a new tag
154
-	 *
155
-	 * @param string $data JSON encoded string containing the properties of the tag to create
156
-	 * @param string $contentType content type of the data
157
-	 * @return ISystemTag newly created system tag
158
-	 *
159
-	 * @throws BadRequest if a field was missing
160
-	 * @throws Conflict if a tag with the same properties already exists
161
-	 * @throws UnsupportedMediaType if the content type is not supported
162
-	 */
163
-	private function createTag($data, $contentType = 'application/json') {
164
-		if (explode(';', $contentType)[0] === 'application/json') {
165
-			$data = json_decode($data, true);
166
-		} else {
167
-			throw new UnsupportedMediaType();
168
-		}
169
-
170
-		if (!isset($data['name'])) {
171
-			throw new BadRequest('Missing "name" attribute');
172
-		}
173
-
174
-		$tagName = $data['name'];
175
-		$userVisible = true;
176
-		$userAssignable = true;
177
-
178
-		if (isset($data['userVisible'])) {
179
-			$userVisible = (bool)$data['userVisible'];
180
-		}
181
-
182
-		if (isset($data['userAssignable'])) {
183
-			$userAssignable = (bool)$data['userAssignable'];
184
-		}
185
-
186
-		$groups = [];
187
-		if (isset($data['groups'])) {
188
-			$groups = $data['groups'];
189
-			if (is_string($groups)) {
190
-				$groups = explode('|', $groups);
191
-			}
192
-		}
193
-
194
-		if($userVisible === false || $userAssignable === false || !empty($groups)) {
195
-			if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
196
-				throw new BadRequest('Not sufficient permissions');
197
-			}
198
-		}
199
-
200
-		try {
201
-			$tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
202
-			if (!empty($groups)) {
203
-				$this->tagManager->setTagGroups($tag, $groups);
204
-			}
205
-			return $tag;
206
-		} catch (TagAlreadyExistsException $e) {
207
-			throw new Conflict('Tag already exists', 0, $e);
208
-		}
209
-	}
210
-
211
-
212
-	/**
213
-	 * Retrieves system tag properties
214
-	 *
215
-	 * @param PropFind $propFind
216
-	 * @param \Sabre\DAV\INode $node
217
-	 */
218
-	public function handleGetProperties(
219
-		PropFind $propFind,
220
-		\Sabre\DAV\INode $node
221
-	) {
222
-		if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
223
-			return;
224
-		}
225
-
226
-		$propFind->handle(self::ID_PROPERTYNAME, function() use ($node) {
227
-			return $node->getSystemTag()->getId();
228
-		});
229
-
230
-		$propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function() use ($node) {
231
-			return $node->getSystemTag()->getName();
232
-		});
233
-
234
-		$propFind->handle(self::USERVISIBLE_PROPERTYNAME, function() use ($node) {
235
-			return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
236
-		});
237
-
238
-		$propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function() use ($node) {
239
-			// this is the tag's inherent property "is user assignable"
240
-			return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
241
-		});
242
-
243
-		$propFind->handle(self::CANASSIGN_PROPERTYNAME, function() use ($node) {
244
-			// this is the effective permission for the current user
245
-			return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
246
-		});
247
-
248
-		$propFind->handle(self::GROUPS_PROPERTYNAME, function() use ($node) {
249
-			if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
250
-				// property only available for admins
251
-				throw new Forbidden();
252
-			}
253
-			$groups = [];
254
-			// no need to retrieve groups for namespaces that don't qualify
255
-			if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
256
-				$groups = $this->tagManager->getTagGroups($node->getSystemTag());
257
-			}
258
-			return implode('|', $groups);
259
-		});
260
-	}
261
-
262
-	/**
263
-	 * Updates tag attributes
264
-	 *
265
-	 * @param string $path
266
-	 * @param PropPatch $propPatch
267
-	 *
268
-	 * @return void
269
-	 */
270
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
271
-		$node = $this->server->tree->getNodeForPath($path);
272
-		if (!($node instanceof SystemTagNode)) {
273
-			return;
274
-		}
275
-
276
-		$propPatch->handle([
277
-			self::DISPLAYNAME_PROPERTYNAME,
278
-			self::USERVISIBLE_PROPERTYNAME,
279
-			self::USERASSIGNABLE_PROPERTYNAME,
280
-			self::GROUPS_PROPERTYNAME,
281
-		], function($props) use ($node) {
282
-			$tag = $node->getSystemTag();
283
-			$name = $tag->getName();
284
-			$userVisible = $tag->isUserVisible();
285
-			$userAssignable = $tag->isUserAssignable();
286
-
287
-			$updateTag = false;
288
-
289
-			if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
290
-				$name = $props[self::DISPLAYNAME_PROPERTYNAME];
291
-				$updateTag = true;
292
-			}
293
-
294
-			if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
295
-				$propValue = $props[self::USERVISIBLE_PROPERTYNAME];
296
-				$userVisible = ($propValue !== 'false' && $propValue !== '0');
297
-				$updateTag = true;
298
-			}
299
-
300
-			if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
301
-				$propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
302
-				$userAssignable = ($propValue !== 'false' && $propValue !== '0');
303
-				$updateTag = true;
304
-			}
305
-
306
-			if (isset($props[self::GROUPS_PROPERTYNAME])) {
307
-				if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
308
-					// property only available for admins
309
-					throw new Forbidden();
310
-				}
311
-
312
-				$propValue = $props[self::GROUPS_PROPERTYNAME];
313
-				$groupIds = explode('|', $propValue);
314
-				$this->tagManager->setTagGroups($tag, $groupIds);
315
-			}
316
-
317
-			if ($updateTag) {
318
-				$node->update($name, $userVisible, $userAssignable);
319
-			}
320
-
321
-			return true;
322
-		});
323
-
324
-	}
49
+    // namespace
50
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
51
+    const ID_PROPERTYNAME = '{http://owncloud.org/ns}id';
52
+    const DISPLAYNAME_PROPERTYNAME = '{http://owncloud.org/ns}display-name';
53
+    const USERVISIBLE_PROPERTYNAME = '{http://owncloud.org/ns}user-visible';
54
+    const USERASSIGNABLE_PROPERTYNAME = '{http://owncloud.org/ns}user-assignable';
55
+    const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups';
56
+    const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign';
57
+
58
+    /**
59
+     * @var \Sabre\DAV\Server $server
60
+     */
61
+    private $server;
62
+
63
+    /**
64
+     * @var ISystemTagManager
65
+     */
66
+    protected $tagManager;
67
+
68
+    /**
69
+     * @var IUserSession
70
+     */
71
+    protected $userSession;
72
+
73
+    /**
74
+     * @var IGroupManager
75
+     */
76
+    protected $groupManager;
77
+
78
+    /**
79
+     * @param ISystemTagManager $tagManager tag manager
80
+     * @param IGroupManager $groupManager
81
+     * @param IUserSession $userSession
82
+     */
83
+    public function __construct(ISystemTagManager $tagManager,
84
+                                IGroupManager $groupManager,
85
+                                IUserSession $userSession) {
86
+        $this->tagManager = $tagManager;
87
+        $this->userSession = $userSession;
88
+        $this->groupManager = $groupManager;
89
+    }
90
+
91
+    /**
92
+     * This initializes the plugin.
93
+     *
94
+     * This function is called by \Sabre\DAV\Server, after
95
+     * addPlugin is called.
96
+     *
97
+     * This method should set up the required event subscriptions.
98
+     *
99
+     * @param \Sabre\DAV\Server $server
100
+     * @return void
101
+     */
102
+    public function initialize(\Sabre\DAV\Server $server) {
103
+
104
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
105
+
106
+        $server->protectedProperties[] = self::ID_PROPERTYNAME;
107
+
108
+        $server->on('propFind', array($this, 'handleGetProperties'));
109
+        $server->on('propPatch', array($this, 'handleUpdateProperties'));
110
+        $server->on('method:POST', [$this, 'httpPost']);
111
+
112
+        $this->server = $server;
113
+    }
114
+
115
+    /**
116
+     * POST operation on system tag collections
117
+     *
118
+     * @param RequestInterface $request request object
119
+     * @param ResponseInterface $response response object
120
+     * @return null|false
121
+     */
122
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
123
+        $path = $request->getPath();
124
+
125
+        // Making sure the node exists
126
+        $node = $this->server->tree->getNodeForPath($path);
127
+        if ($node instanceof SystemTagsByIdCollection || $node instanceof SystemTagsObjectMappingCollection) {
128
+            $data = $request->getBodyAsString();
129
+
130
+            $tag = $this->createTag($data, $request->getHeader('Content-Type'));
131
+
132
+            if ($node instanceof SystemTagsObjectMappingCollection) {
133
+                // also add to collection
134
+                $node->createFile($tag->getId());
135
+                $url = $request->getBaseUrl() . 'systemtags/';
136
+            } else {
137
+                $url = $request->getUrl();
138
+            }
139
+
140
+            if ($url[strlen($url) - 1] !== '/') {
141
+                $url .= '/';
142
+            }
143
+
144
+            $response->setHeader('Content-Location', $url . $tag->getId());
145
+
146
+            // created
147
+            $response->setStatus(201);
148
+            return false;
149
+        }
150
+    }
151
+
152
+    /**
153
+     * Creates a new tag
154
+     *
155
+     * @param string $data JSON encoded string containing the properties of the tag to create
156
+     * @param string $contentType content type of the data
157
+     * @return ISystemTag newly created system tag
158
+     *
159
+     * @throws BadRequest if a field was missing
160
+     * @throws Conflict if a tag with the same properties already exists
161
+     * @throws UnsupportedMediaType if the content type is not supported
162
+     */
163
+    private function createTag($data, $contentType = 'application/json') {
164
+        if (explode(';', $contentType)[0] === 'application/json') {
165
+            $data = json_decode($data, true);
166
+        } else {
167
+            throw new UnsupportedMediaType();
168
+        }
169
+
170
+        if (!isset($data['name'])) {
171
+            throw new BadRequest('Missing "name" attribute');
172
+        }
173
+
174
+        $tagName = $data['name'];
175
+        $userVisible = true;
176
+        $userAssignable = true;
177
+
178
+        if (isset($data['userVisible'])) {
179
+            $userVisible = (bool)$data['userVisible'];
180
+        }
181
+
182
+        if (isset($data['userAssignable'])) {
183
+            $userAssignable = (bool)$data['userAssignable'];
184
+        }
185
+
186
+        $groups = [];
187
+        if (isset($data['groups'])) {
188
+            $groups = $data['groups'];
189
+            if (is_string($groups)) {
190
+                $groups = explode('|', $groups);
191
+            }
192
+        }
193
+
194
+        if($userVisible === false || $userAssignable === false || !empty($groups)) {
195
+            if(!$this->userSession->isLoggedIn() || !$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
196
+                throw new BadRequest('Not sufficient permissions');
197
+            }
198
+        }
199
+
200
+        try {
201
+            $tag = $this->tagManager->createTag($tagName, $userVisible, $userAssignable);
202
+            if (!empty($groups)) {
203
+                $this->tagManager->setTagGroups($tag, $groups);
204
+            }
205
+            return $tag;
206
+        } catch (TagAlreadyExistsException $e) {
207
+            throw new Conflict('Tag already exists', 0, $e);
208
+        }
209
+    }
210
+
211
+
212
+    /**
213
+     * Retrieves system tag properties
214
+     *
215
+     * @param PropFind $propFind
216
+     * @param \Sabre\DAV\INode $node
217
+     */
218
+    public function handleGetProperties(
219
+        PropFind $propFind,
220
+        \Sabre\DAV\INode $node
221
+    ) {
222
+        if (!($node instanceof SystemTagNode) && !($node instanceof SystemTagMappingNode)) {
223
+            return;
224
+        }
225
+
226
+        $propFind->handle(self::ID_PROPERTYNAME, function() use ($node) {
227
+            return $node->getSystemTag()->getId();
228
+        });
229
+
230
+        $propFind->handle(self::DISPLAYNAME_PROPERTYNAME, function() use ($node) {
231
+            return $node->getSystemTag()->getName();
232
+        });
233
+
234
+        $propFind->handle(self::USERVISIBLE_PROPERTYNAME, function() use ($node) {
235
+            return $node->getSystemTag()->isUserVisible() ? 'true' : 'false';
236
+        });
237
+
238
+        $propFind->handle(self::USERASSIGNABLE_PROPERTYNAME, function() use ($node) {
239
+            // this is the tag's inherent property "is user assignable"
240
+            return $node->getSystemTag()->isUserAssignable() ? 'true' : 'false';
241
+        });
242
+
243
+        $propFind->handle(self::CANASSIGN_PROPERTYNAME, function() use ($node) {
244
+            // this is the effective permission for the current user
245
+            return $this->tagManager->canUserAssignTag($node->getSystemTag(), $this->userSession->getUser()) ? 'true' : 'false';
246
+        });
247
+
248
+        $propFind->handle(self::GROUPS_PROPERTYNAME, function() use ($node) {
249
+            if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
250
+                // property only available for admins
251
+                throw new Forbidden();
252
+            }
253
+            $groups = [];
254
+            // no need to retrieve groups for namespaces that don't qualify
255
+            if ($node->getSystemTag()->isUserVisible() && !$node->getSystemTag()->isUserAssignable()) {
256
+                $groups = $this->tagManager->getTagGroups($node->getSystemTag());
257
+            }
258
+            return implode('|', $groups);
259
+        });
260
+    }
261
+
262
+    /**
263
+     * Updates tag attributes
264
+     *
265
+     * @param string $path
266
+     * @param PropPatch $propPatch
267
+     *
268
+     * @return void
269
+     */
270
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
271
+        $node = $this->server->tree->getNodeForPath($path);
272
+        if (!($node instanceof SystemTagNode)) {
273
+            return;
274
+        }
275
+
276
+        $propPatch->handle([
277
+            self::DISPLAYNAME_PROPERTYNAME,
278
+            self::USERVISIBLE_PROPERTYNAME,
279
+            self::USERASSIGNABLE_PROPERTYNAME,
280
+            self::GROUPS_PROPERTYNAME,
281
+        ], function($props) use ($node) {
282
+            $tag = $node->getSystemTag();
283
+            $name = $tag->getName();
284
+            $userVisible = $tag->isUserVisible();
285
+            $userAssignable = $tag->isUserAssignable();
286
+
287
+            $updateTag = false;
288
+
289
+            if (isset($props[self::DISPLAYNAME_PROPERTYNAME])) {
290
+                $name = $props[self::DISPLAYNAME_PROPERTYNAME];
291
+                $updateTag = true;
292
+            }
293
+
294
+            if (isset($props[self::USERVISIBLE_PROPERTYNAME])) {
295
+                $propValue = $props[self::USERVISIBLE_PROPERTYNAME];
296
+                $userVisible = ($propValue !== 'false' && $propValue !== '0');
297
+                $updateTag = true;
298
+            }
299
+
300
+            if (isset($props[self::USERASSIGNABLE_PROPERTYNAME])) {
301
+                $propValue = $props[self::USERASSIGNABLE_PROPERTYNAME];
302
+                $userAssignable = ($propValue !== 'false' && $propValue !== '0');
303
+                $updateTag = true;
304
+            }
305
+
306
+            if (isset($props[self::GROUPS_PROPERTYNAME])) {
307
+                if (!$this->groupManager->isAdmin($this->userSession->getUser()->getUID())) {
308
+                    // property only available for admins
309
+                    throw new Forbidden();
310
+                }
311
+
312
+                $propValue = $props[self::GROUPS_PROPERTYNAME];
313
+                $groupIds = explode('|', $propValue);
314
+                $this->tagManager->setTagGroups($tag, $groupIds);
315
+            }
316
+
317
+            if ($updateTag) {
318
+                $node->update($name, $userVisible, $userAssignable);
319
+            }
320
+
321
+            return true;
322
+        });
323
+
324
+    }
325 325
 }
Please login to merge, or discard this patch.
apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -95,15 +95,15 @@  discard block
 block discarded – undo
95 95
 			$tags = $this->tagManager->getTagsByIds([$tagId]);
96 96
 			$tag = current($tags);
97 97
 			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
98
+				throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
99 99
 			}
100 100
 			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
101
+				throw new Forbidden('No permission to assign tag '.$tagId);
102 102
 			}
103 103
 
104 104
 			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105 105
 		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
106
+			throw new PreconditionFailed('Tag with id '.$tagId.' does not exist, cannot assign');
107 107
 		}
108 108
 	}
109 109
 
@@ -120,11 +120,11 @@  discard block
 block discarded – undo
120 120
 					return $this->makeNode($tag);
121 121
 				}
122 122
 			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
123
+			throw new NotFound('Tag with id '.$tagId.' not present for object '.$this->objectId);
124 124
 		} catch (\InvalidArgumentException $e) {
125 125
 			throw new BadRequest('Invalid tag id', 0, $e);
126 126
 		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
127
+			throw new NotFound('Tag with id '.$tagId.' not found', 0, $e);
128 128
 		}
129 129
 	}
130 130
 
Please login to merge, or discard this patch.
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -39,169 +39,169 @@
 block discarded – undo
39 39
  */
40 40
 class SystemTagsObjectMappingCollection implements ICollection {
41 41
 
42
-	/**
43
-	 * @var string
44
-	 */
45
-	private $objectId;
46
-
47
-	/**
48
-	 * @var string
49
-	 */
50
-	private $objectType;
51
-
52
-	/**
53
-	 * @var ISystemTagManager
54
-	 */
55
-	private $tagManager;
56
-
57
-	/**
58
-	 * @var ISystemTagObjectMapper
59
-	 */
60
-	private $tagMapper;
61
-
62
-	/**
63
-	 * User
64
-	 *
65
-	 * @var IUser
66
-	 */
67
-	private $user;
68
-
69
-
70
-	/**
71
-	 * Constructor
72
-	 *
73
-	 * @param string $objectId object id
74
-	 * @param string $objectType object type
75
-	 * @param IUser $user user
76
-	 * @param ISystemTagManager $tagManager tag manager
77
-	 * @param ISystemTagObjectMapper $tagMapper tag mapper
78
-	 */
79
-	public function __construct(
80
-		$objectId,
81
-		$objectType,
82
-		IUser $user,
83
-		ISystemTagManager $tagManager,
84
-		ISystemTagObjectMapper $tagMapper
85
-	) {
86
-		$this->tagManager = $tagManager;
87
-		$this->tagMapper = $tagMapper;
88
-		$this->objectId = $objectId;
89
-		$this->objectType = $objectType;
90
-		$this->user = $user;
91
-	}
92
-
93
-	function createFile($tagId, $data = null) {
94
-		try {
95
-			$tags = $this->tagManager->getTagsByIds([$tagId]);
96
-			$tag = current($tags);
97
-			if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
-				throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
-			}
100
-			if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
-				throw new Forbidden('No permission to assign tag ' . $tagId);
102
-			}
103
-
104
-			$this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
-		} catch (TagNotFoundException $e) {
106
-			throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
-		}
108
-	}
109
-
110
-	function createDirectory($name) {
111
-		throw new Forbidden('Permission denied to create collections');
112
-	}
113
-
114
-	function getChild($tagId) {
115
-		try {
116
-			if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
-				$tag = $this->tagManager->getTagsByIds([$tagId]);
118
-				$tag = current($tag);
119
-				if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
-					return $this->makeNode($tag);
121
-				}
122
-			}
123
-			throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
-		} catch (\InvalidArgumentException $e) {
125
-			throw new BadRequest('Invalid tag id', 0, $e);
126
-		} catch (TagNotFoundException $e) {
127
-			throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
-		}
129
-	}
130
-
131
-	function getChildren() {
132
-		$tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
-		if (empty($tagIds)) {
134
-			return [];
135
-		}
136
-		$tags = $this->tagManager->getTagsByIds($tagIds);
137
-
138
-		// filter out non-visible tags
139
-		$tags = array_filter($tags, function($tag) {
140
-			return $this->tagManager->canUserSeeTag($tag, $this->user);
141
-		});
142
-
143
-		return array_values(array_map(function($tag) {
144
-			return $this->makeNode($tag);
145
-		}, $tags));
146
-	}
147
-
148
-	function childExists($tagId) {
149
-		try {
150
-			$result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
151
-
152
-			if ($result) {
153
-				$tags = $this->tagManager->getTagsByIds([$tagId]);
154
-				$tag = current($tags);
155
-				if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
-					return false;
157
-				}
158
-			}
159
-
160
-			return $result;
161
-		} catch (\InvalidArgumentException $e) {
162
-			throw new BadRequest('Invalid tag id', 0, $e);
163
-		} catch (TagNotFoundException $e) {
164
-			return false;
165
-		}
166
-	}
167
-
168
-	function delete() {
169
-		throw new Forbidden('Permission denied to delete this collection');
170
-	}
171
-
172
-	function getName() {
173
-		return $this->objectId;
174
-	}
175
-
176
-	function setName($name) {
177
-		throw new Forbidden('Permission denied to rename this collection');
178
-	}
179
-
180
-	/**
181
-	 * Returns the last modification time, as a unix timestamp
182
-	 *
183
-	 * @return int
184
-	 */
185
-	function getLastModified() {
186
-		return null;
187
-	}
188
-
189
-	/**
190
-	 * Create a sabre node for the mapping of the 
191
-	 * given system tag to the collection's object
192
-	 *
193
-	 * @param ISystemTag $tag
194
-	 *
195
-	 * @return SystemTagMappingNode
196
-	 */
197
-	private function makeNode(ISystemTag $tag) {
198
-		return new SystemTagMappingNode(
199
-			$tag,
200
-			$this->objectId,
201
-			$this->objectType,
202
-			$this->user,
203
-			$this->tagManager,
204
-			$this->tagMapper
205
-		);
206
-	}
42
+    /**
43
+     * @var string
44
+     */
45
+    private $objectId;
46
+
47
+    /**
48
+     * @var string
49
+     */
50
+    private $objectType;
51
+
52
+    /**
53
+     * @var ISystemTagManager
54
+     */
55
+    private $tagManager;
56
+
57
+    /**
58
+     * @var ISystemTagObjectMapper
59
+     */
60
+    private $tagMapper;
61
+
62
+    /**
63
+     * User
64
+     *
65
+     * @var IUser
66
+     */
67
+    private $user;
68
+
69
+
70
+    /**
71
+     * Constructor
72
+     *
73
+     * @param string $objectId object id
74
+     * @param string $objectType object type
75
+     * @param IUser $user user
76
+     * @param ISystemTagManager $tagManager tag manager
77
+     * @param ISystemTagObjectMapper $tagMapper tag mapper
78
+     */
79
+    public function __construct(
80
+        $objectId,
81
+        $objectType,
82
+        IUser $user,
83
+        ISystemTagManager $tagManager,
84
+        ISystemTagObjectMapper $tagMapper
85
+    ) {
86
+        $this->tagManager = $tagManager;
87
+        $this->tagMapper = $tagMapper;
88
+        $this->objectId = $objectId;
89
+        $this->objectType = $objectType;
90
+        $this->user = $user;
91
+    }
92
+
93
+    function createFile($tagId, $data = null) {
94
+        try {
95
+            $tags = $this->tagManager->getTagsByIds([$tagId]);
96
+            $tag = current($tags);
97
+            if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
98
+                throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
99
+            }
100
+            if (!$this->tagManager->canUserAssignTag($tag, $this->user)) {
101
+                throw new Forbidden('No permission to assign tag ' . $tagId);
102
+            }
103
+
104
+            $this->tagMapper->assignTags($this->objectId, $this->objectType, $tagId);
105
+        } catch (TagNotFoundException $e) {
106
+            throw new PreconditionFailed('Tag with id ' . $tagId . ' does not exist, cannot assign');
107
+        }
108
+    }
109
+
110
+    function createDirectory($name) {
111
+        throw new Forbidden('Permission denied to create collections');
112
+    }
113
+
114
+    function getChild($tagId) {
115
+        try {
116
+            if ($this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true)) {
117
+                $tag = $this->tagManager->getTagsByIds([$tagId]);
118
+                $tag = current($tag);
119
+                if ($this->tagManager->canUserSeeTag($tag, $this->user)) {
120
+                    return $this->makeNode($tag);
121
+                }
122
+            }
123
+            throw new NotFound('Tag with id ' . $tagId . ' not present for object ' . $this->objectId);
124
+        } catch (\InvalidArgumentException $e) {
125
+            throw new BadRequest('Invalid tag id', 0, $e);
126
+        } catch (TagNotFoundException $e) {
127
+            throw new NotFound('Tag with id ' . $tagId . ' not found', 0, $e);
128
+        }
129
+    }
130
+
131
+    function getChildren() {
132
+        $tagIds = current($this->tagMapper->getTagIdsForObjects([$this->objectId], $this->objectType));
133
+        if (empty($tagIds)) {
134
+            return [];
135
+        }
136
+        $tags = $this->tagManager->getTagsByIds($tagIds);
137
+
138
+        // filter out non-visible tags
139
+        $tags = array_filter($tags, function($tag) {
140
+            return $this->tagManager->canUserSeeTag($tag, $this->user);
141
+        });
142
+
143
+        return array_values(array_map(function($tag) {
144
+            return $this->makeNode($tag);
145
+        }, $tags));
146
+    }
147
+
148
+    function childExists($tagId) {
149
+        try {
150
+            $result = $this->tagMapper->haveTag([$this->objectId], $this->objectType, $tagId, true);
151
+
152
+            if ($result) {
153
+                $tags = $this->tagManager->getTagsByIds([$tagId]);
154
+                $tag = current($tags);
155
+                if (!$this->tagManager->canUserSeeTag($tag, $this->user)) {
156
+                    return false;
157
+                }
158
+            }
159
+
160
+            return $result;
161
+        } catch (\InvalidArgumentException $e) {
162
+            throw new BadRequest('Invalid tag id', 0, $e);
163
+        } catch (TagNotFoundException $e) {
164
+            return false;
165
+        }
166
+    }
167
+
168
+    function delete() {
169
+        throw new Forbidden('Permission denied to delete this collection');
170
+    }
171
+
172
+    function getName() {
173
+        return $this->objectId;
174
+    }
175
+
176
+    function setName($name) {
177
+        throw new Forbidden('Permission denied to rename this collection');
178
+    }
179
+
180
+    /**
181
+     * Returns the last modification time, as a unix timestamp
182
+     *
183
+     * @return int
184
+     */
185
+    function getLastModified() {
186
+        return null;
187
+    }
188
+
189
+    /**
190
+     * Create a sabre node for the mapping of the 
191
+     * given system tag to the collection's object
192
+     *
193
+     * @param ISystemTag $tag
194
+     *
195
+     * @return SystemTagMappingNode
196
+     */
197
+    private function makeNode(ISystemTag $tag) {
198
+        return new SystemTagMappingNode(
199
+            $tag,
200
+            $this->objectId,
201
+            $this->objectType,
202
+            $this->user,
203
+            $this->tagManager,
204
+            $this->tagMapper
205
+        );
206
+    }
207 207
 }
Please login to merge, or discard this patch.
apps/dav/bin/chunkperf.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
 require '../../../../3rdparty/autoload.php';
24 24
 
25 25
 if ($argc !== 6) {
26
-	echo "Invalid number of arguments" . PHP_EOL;
26
+	echo "Invalid number of arguments".PHP_EOL;
27 27
 	exit;
28 28
 }
29 29
 
@@ -37,9 +37,9 @@  discard block
 block discarded – undo
37 37
 	$t0 = microtime(true);
38 38
 	$result = $client->request($method, $uploadUrl, $data, $headers);
39 39
 	$t1 = microtime(true);
40
-	echo $result['statusCode'] . " - " . ($t1 - $t0) . ' seconds' . PHP_EOL;
41
-	if (!in_array($result['statusCode'],  [200, 201])) {
42
-		echo $result['body'] . PHP_EOL;
40
+	echo $result['statusCode']." - ".($t1 - $t0).' seconds'.PHP_EOL;
41
+	if (!in_array($result['statusCode'], [200, 201])) {
42
+		echo $result['body'].PHP_EOL;
43 43
 	}
44 44
 	return $result;
45 45
 }
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 $stream = fopen($file, 'r');
66 66
 
67 67
 $index = 0;
68
-while(!feof($stream)) {
68
+while (!feof($stream)) {
69 69
 	request($client, 'PUT', "$uploadUrl/$index", fread($stream, $chunkSize));
70 70
 	$index++;
71 71
 }
Please login to merge, or discard this patch.
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -23,8 +23,8 @@  discard block
 block discarded – undo
23 23
 require '../../../../3rdparty/autoload.php';
24 24
 
25 25
 if ($argc !== 6) {
26
-	echo "Invalid number of arguments" . PHP_EOL;
27
-	exit;
26
+    echo "Invalid number of arguments" . PHP_EOL;
27
+    exit;
28 28
 }
29 29
 
30 30
 /**
@@ -33,15 +33,15 @@  discard block
 block discarded – undo
33 33
  * @return mixed
34 34
  */
35 35
 function request($client, $method, $uploadUrl, $data = null, $headers = []) {
36
-	echo "$method $uploadUrl ... ";
37
-	$t0 = microtime(true);
38
-	$result = $client->request($method, $uploadUrl, $data, $headers);
39
-	$t1 = microtime(true);
40
-	echo $result['statusCode'] . " - " . ($t1 - $t0) . ' seconds' . PHP_EOL;
41
-	if (!in_array($result['statusCode'],  [200, 201])) {
42
-		echo $result['body'] . PHP_EOL;
43
-	}
44
-	return $result;
36
+    echo "$method $uploadUrl ... ";
37
+    $t0 = microtime(true);
38
+    $result = $client->request($method, $uploadUrl, $data, $headers);
39
+    $t1 = microtime(true);
40
+    echo $result['statusCode'] . " - " . ($t1 - $t0) . ' seconds' . PHP_EOL;
41
+    if (!in_array($result['statusCode'],  [200, 201])) {
42
+        echo $result['body'] . PHP_EOL;
43
+    }
44
+    return $result;
45 45
 }
46 46
 
47 47
 $baseUri = $argv[1];
@@ -51,9 +51,9 @@  discard block
 block discarded – undo
51 51
 $chunkSize = $argv[5] * 1024 * 1024;
52 52
 
53 53
 $client = new \Sabre\DAV\Client([
54
-	'baseUri' => $baseUri,
55
-	'userName' => $userName,
56
-	'password' => $password
54
+    'baseUri' => $baseUri,
55
+    'userName' => $userName,
56
+    'password' => $password
57 57
 ]);
58 58
 
59 59
 $transfer = uniqid('transfer', true);
@@ -66,14 +66,14 @@  discard block
 block discarded – undo
66 66
 
67 67
 $index = 0;
68 68
 while(!feof($stream)) {
69
-	request($client, 'PUT', "$uploadUrl/$index", fread($stream, $chunkSize));
70
-	$index++;
69
+    request($client, 'PUT', "$uploadUrl/$index", fread($stream, $chunkSize));
70
+    $index++;
71 71
 }
72 72
 
73 73
 $destination = pathinfo($file, PATHINFO_BASENAME);
74 74
 //echo "Moving $uploadUrl/.file to it's final destination $baseUri/files/$userName/$destination" . PHP_EOL;
75 75
 request($client, 'MOVE', "$uploadUrl/.file", null, [
76
-	'Destination' => "$baseUri/files/$userName/$destination",
77
-	'OC-Total-Length' => filesize($file),
78
-	'X-OC-MTime' => filemtime($file)
76
+    'Destination' => "$baseUri/files/$userName/$destination",
77
+    'OC-Total-Length' => filesize($file),
78
+    'X-OC-MTime' => filemtime($file)
79 79
 ]);
Please login to merge, or discard this patch.
apps/files_versions/lib/Command/ExpireVersions.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@
 block discarded – undo
115 115
 		\OC_Util::setupFS($user);
116 116
 
117 117
 		// Check if this user has a version directory
118
-		$view = new \OC\Files\View('/' . $user);
118
+		$view = new \OC\Files\View('/'.$user);
119 119
 		if (!$view->is_dir('/files_versions')) {
120 120
 			return false;
121 121
 		}
Please login to merge, or discard this patch.
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -35,93 +35,93 @@
 block discarded – undo
35 35
 
36 36
 class ExpireVersions extends Command {
37 37
 
38
-	/**
39
-	 * @var Expiration
40
-	 */
41
-	private $expiration;
38
+    /**
39
+     * @var Expiration
40
+     */
41
+    private $expiration;
42 42
 	
43
-	/**
44
-	 * @var IUserManager
45
-	 */
46
-	private $userManager;
43
+    /**
44
+     * @var IUserManager
45
+     */
46
+    private $userManager;
47 47
 
48
-	/**
49
-	 * @param IUserManager $userManager
50
-	 * @param Expiration $expiration
51
-	 */
52
-	public function __construct(IUserManager $userManager,
53
-								Expiration $expiration) {
54
-		parent::__construct();
48
+    /**
49
+     * @param IUserManager $userManager
50
+     * @param Expiration $expiration
51
+     */
52
+    public function __construct(IUserManager $userManager,
53
+                                Expiration $expiration) {
54
+        parent::__construct();
55 55
 
56
-		$this->userManager = $userManager;
57
-		$this->expiration = $expiration;
58
-	}
56
+        $this->userManager = $userManager;
57
+        $this->expiration = $expiration;
58
+    }
59 59
 
60
-	protected function configure() {
61
-		$this
62
-			->setName('versions:expire')
63
-			->setDescription('Expires the users file versions')
64
-			->addArgument(
65
-				'user_id',
66
-				InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
67
-				'expire file versions of the given user(s), if no user is given file versions for all users will be expired.'
68
-			);
69
-	}
60
+    protected function configure() {
61
+        $this
62
+            ->setName('versions:expire')
63
+            ->setDescription('Expires the users file versions')
64
+            ->addArgument(
65
+                'user_id',
66
+                InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
67
+                'expire file versions of the given user(s), if no user is given file versions for all users will be expired.'
68
+            );
69
+    }
70 70
 
71
-	protected function execute(InputInterface $input, OutputInterface $output) {
71
+    protected function execute(InputInterface $input, OutputInterface $output) {
72 72
 
73
-		$maxAge = $this->expiration->getMaxAgeAsTimestamp();
74
-		if (!$maxAge) {
75
-			$output->writeln("No expiry configured.");
76
-			return;
77
-		}
73
+        $maxAge = $this->expiration->getMaxAgeAsTimestamp();
74
+        if (!$maxAge) {
75
+            $output->writeln("No expiry configured.");
76
+            return;
77
+        }
78 78
 
79
-		$users = $input->getArgument('user_id');
80
-		if (!empty($users)) {
81
-			foreach ($users as $user) {
82
-				if ($this->userManager->userExists($user)) {
83
-					$output->writeln("Remove deleted files of   <info>$user</info>");
84
-					$userObject = $this->userManager->get($user);
85
-					$this->expireVersionsForUser($userObject);
86
-				} else {
87
-					$output->writeln("<error>Unknown user $user</error>");
88
-				}
89
-			}
90
-		} else {
91
-			$p = new ProgressBar($output);
92
-			$p->start();
93
-			$this->userManager->callForSeenUsers(function(IUser $user) use ($p) {
94
-				$p->advance();
95
-				$this->expireVersionsForUser($user);
96
-			});
97
-			$p->finish();
98
-			$output->writeln('');
99
-		}
100
-	}
79
+        $users = $input->getArgument('user_id');
80
+        if (!empty($users)) {
81
+            foreach ($users as $user) {
82
+                if ($this->userManager->userExists($user)) {
83
+                    $output->writeln("Remove deleted files of   <info>$user</info>");
84
+                    $userObject = $this->userManager->get($user);
85
+                    $this->expireVersionsForUser($userObject);
86
+                } else {
87
+                    $output->writeln("<error>Unknown user $user</error>");
88
+                }
89
+            }
90
+        } else {
91
+            $p = new ProgressBar($output);
92
+            $p->start();
93
+            $this->userManager->callForSeenUsers(function(IUser $user) use ($p) {
94
+                $p->advance();
95
+                $this->expireVersionsForUser($user);
96
+            });
97
+            $p->finish();
98
+            $output->writeln('');
99
+        }
100
+    }
101 101
 
102
-	function expireVersionsForUser(IUser $user) {
103
-		$uid = $user->getUID();
104
-		if (!$this->setupFS($uid)) {
105
-			return;
106
-		}
107
-		Storage::expireOlderThanMaxForUser($uid);
108
-	}
102
+    function expireVersionsForUser(IUser $user) {
103
+        $uid = $user->getUID();
104
+        if (!$this->setupFS($uid)) {
105
+            return;
106
+        }
107
+        Storage::expireOlderThanMaxForUser($uid);
108
+    }
109 109
 
110
-	/**
111
-	 * Act on behalf on versions item owner
112
-	 * @param string $user
113
-	 * @return boolean
114
-	 */
115
-	protected function setupFS($user) {
116
-		\OC_Util::tearDownFS();
117
-		\OC_Util::setupFS($user);
110
+    /**
111
+     * Act on behalf on versions item owner
112
+     * @param string $user
113
+     * @return boolean
114
+     */
115
+    protected function setupFS($user) {
116
+        \OC_Util::tearDownFS();
117
+        \OC_Util::setupFS($user);
118 118
 
119
-		// Check if this user has a version directory
120
-		$view = new \OC\Files\View('/' . $user);
121
-		if (!$view->is_dir('/files_versions')) {
122
-			return false;
123
-		}
119
+        // Check if this user has a version directory
120
+        $view = new \OC\Files\View('/' . $user);
121
+        if (!$view->is_dir('/files_versions')) {
122
+            return false;
123
+        }
124 124
 
125
-		return true;
126
-	}
125
+        return true;
126
+    }
127 127
 }
Please login to merge, or discard this patch.