Completed
Pull Request — master (#8096)
by Joas
21:24 queued 03:34
created
apps/files_external/lib/Service/DBConfigService.php 3 patches
Doc Comments   +16 added lines patch added patch discarded remove patch
@@ -89,6 +89,9 @@  discard block
 block discarded – undo
89 89
 		return $this->getMountsFromQuery($query);
90 90
 	}
91 91
 
92
+	/**
93
+	 * @param string $userId
94
+	 */
92 95
 	public function getMountsForUser($userId, $groupIds) {
93 96
 		$builder = $this->connection->getQueryBuilder();
94 97
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
@@ -125,6 +128,10 @@  discard block
 block discarded – undo
125 128
 		return $this->getMountsFromQuery($query);
126 129
 	}
127 130
 
131
+	/**
132
+	 * @param integer $type
133
+	 * @param string|null $value
134
+	 */
128 135
 	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129 136
 		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130 137
 			->from('external_mounts', 'm')
@@ -332,6 +339,9 @@  discard block
 block discarded – undo
332 339
 		}
333 340
 	}
334 341
 
342
+	/**
343
+	 * @param integer $mountId
344
+	 */
335 345
 	public function addApplicable($mountId, $type, $value) {
336 346
 		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337 347
 			'mount_id' => $mountId,
@@ -340,6 +350,9 @@  discard block
 block discarded – undo
340 350
 		], ['mount_id', 'type', 'value']);
341 351
 	}
342 352
 
353
+	/**
354
+	 * @param integer $mountId
355
+	 */
343 356
 	public function removeApplicable($mountId, $type, $value) {
344 357
 		$builder = $this->connection->getQueryBuilder();
345 358
 		$query = $builder->delete('external_applicable')
@@ -473,6 +486,9 @@  discard block
 block discarded – undo
473 486
 		return array_combine($keys, $values);
474 487
 	}
475 488
 
489
+	/**
490
+	 * @param string $value
491
+	 */
476 492
 	private function encryptValue($value) {
477 493
 		return $this->crypto->encrypt($value);
478 494
 	}
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 	 */
179 179
 	public function getAdminMountsForMultiple($type, array $values) {
180 180
 		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
181
+		$params = array_map(function($value) use ($builder) {
182 182
 			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183 183
 		}, $values);
184 184
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232 232
 			]);
233 233
 		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
234
+		return (int) $this->connection->lastInsertId('*PREFIX*external_mounts');
235 235
 	}
236 236
 
237 237
 	/**
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
 		}
368 368
 		$uniqueMounts = array_values($uniqueMounts);
369 369
 
370
-		$mountIds = array_map(function ($mount) {
370
+		$mountIds = array_map(function($mount) {
371 371
 			return $mount['mount_id'];
372 372
 		}, $uniqueMounts);
373 373
 		$mountIds = array_values(array_unique($mountIds));
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		$config = $this->getConfigForMounts($mountIds);
377 377
 		$options = $this->getOptionsForMounts($mountIds);
378 378
 
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
379
+		return array_map(function($mount, $applicable, $config, $options) {
380
+			$mount['type'] = (int) $mount['type'];
381
+			$mount['priority'] = (int) $mount['priority'];
382 382
 			$mount['applicable'] = $applicable;
383 383
 			$mount['config'] = $config;
384 384
 			$mount['options'] = $options;
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		}
401 401
 		$builder = $this->connection->getQueryBuilder();
402 402
 		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
403
+		$placeHolders = array_map(function($id) use ($builder) {
404 404
 			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405 405
 		}, $mountIds);
406 406
 		$query = $builder->select($fields)
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		foreach ($rows as $row) {
416 416
 			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
417
+				$row['type'] = (int) $row['type'];
418 418
 			}
419 419
 			$result[$row['mount_id']][] = $row;
420 420
 		}
@@ -445,8 +445,8 @@  discard block
 block discarded – undo
445 445
 	public function getOptionsForMounts($mountIds) {
446 446
 		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447 447
 		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
448
+		return array_map(function(array $options) {
449
+			return array_map(function($option) {
450 450
 				return json_decode($option);
451 451
 			}, $options);
452 452
 		}, $optionsMap);
@@ -457,16 +457,16 @@  discard block
 block discarded – undo
457 457
 	 * @return array ['key1' => $value1, ...]
458 458
 	 */
459 459
 	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
460
+		$decryptedPairts = array_map(function($pair) {
461 461
 			if ($pair['key'] === 'password') {
462 462
 				$pair['value'] = $this->decryptValue($pair['value']);
463 463
 			}
464 464
 			return $pair;
465 465
 		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
466
+		$keys = array_map(function($pair) {
467 467
 			return $pair['key'];
468 468
 		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
469
+		$values = array_map(function($pair) {
470 470
 			return $pair['value'];
471 471
 		}, $decryptedPairts);
472 472
 
Please login to merge, or discard this patch.
Indentation   +456 added lines, -456 removed lines patch added patch discarded remove patch
@@ -32,460 +32,460 @@
 block discarded – undo
32 32
  * Stores the mount config in the database
33 33
  */
34 34
 class DBConfigService {
35
-	const MOUNT_TYPE_ADMIN = 1;
36
-	const MOUNT_TYPE_PERSONAl = 2;
37
-
38
-	const APPLICABLE_TYPE_GLOBAL = 1;
39
-	const APPLICABLE_TYPE_GROUP = 2;
40
-	const APPLICABLE_TYPE_USER = 3;
41
-
42
-	/**
43
-	 * @var IDBConnection
44
-	 */
45
-	private $connection;
46
-
47
-	/**
48
-	 * @var ICrypto
49
-	 */
50
-	private $crypto;
51
-
52
-	/**
53
-	 * DBConfigService constructor.
54
-	 *
55
-	 * @param IDBConnection $connection
56
-	 * @param ICrypto $crypto
57
-	 */
58
-	public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
-		$this->connection = $connection;
60
-		$this->crypto = $crypto;
61
-	}
62
-
63
-	/**
64
-	 * @param int $mountId
65
-	 * @return array
66
-	 */
67
-	public function getMountById($mountId) {
68
-		$builder = $this->connection->getQueryBuilder();
69
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
-			->from('external_mounts', 'm')
71
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
-		$mounts = $this->getMountsFromQuery($query);
73
-		if (count($mounts) > 0) {
74
-			return $mounts[0];
75
-		} else {
76
-			return null;
77
-		}
78
-	}
79
-
80
-	/**
81
-	 * Get all configured mounts
82
-	 *
83
-	 * @return array
84
-	 */
85
-	public function getAllMounts() {
86
-		$builder = $this->connection->getQueryBuilder();
87
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
-			->from('external_mounts');
89
-		return $this->getMountsFromQuery($query);
90
-	}
91
-
92
-	public function getMountsForUser($userId, $groupIds) {
93
-		$builder = $this->connection->getQueryBuilder();
94
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
-			->from('external_mounts', 'm')
96
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
-			->where($builder->expr()->orX(
98
-				$builder->expr()->andX( // global mounts
99
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
-					$builder->expr()->isNull('a.value')
101
-				),
102
-				$builder->expr()->andX( // mounts for user
103
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
-					$builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
-				),
106
-				$builder->expr()->andX( // mounts for group
107
-					$builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
-					$builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 * @suppress SqlInjectionChecker
120
-	 */
121
-	public function getAdminMounts() {
122
-		$builder = $this->connection->getQueryBuilder();
123
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
-			->from('external_mounts')
125
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
-		return $this->getMountsFromQuery($query);
127
-	}
128
-
129
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
-			->from('external_mounts', 'm')
132
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
-
135
-		if (is_null($value)) {
136
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
137
-		} else {
138
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
-		}
140
-
141
-		return $query;
142
-	}
143
-
144
-	/**
145
-	 * Get mounts by applicable
146
-	 *
147
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
-	 * @param string|null $value user_id, group_id or null for global mounts
149
-	 * @return array
150
-	 */
151
-	public function getMountsFor($type, $value) {
152
-		$builder = $this->connection->getQueryBuilder();
153
-		$query = $this->getForQuery($builder, $type, $value);
154
-
155
-		return $this->getMountsFromQuery($query);
156
-	}
157
-
158
-	/**
159
-	 * Get admin defined mounts by applicable
160
-	 *
161
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
-	 * @param string|null $value user_id, group_id or null for global mounts
163
-	 * @return array
164
-	 * @suppress SqlInjectionChecker
165
-	 */
166
-	public function getAdminMountsFor($type, $value) {
167
-		$builder = $this->connection->getQueryBuilder();
168
-		$query = $this->getForQuery($builder, $type, $value);
169
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
-
171
-		return $this->getMountsFromQuery($query);
172
-	}
173
-
174
-	/**
175
-	 * Get admin defined mounts for multiple applicable
176
-	 *
177
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
-	 * @param string[] $values user_ids or group_ids
179
-	 * @return array
180
-	 * @suppress SqlInjectionChecker
181
-	 */
182
-	public function getAdminMountsForMultiple($type, array $values) {
183
-		$builder = $this->connection->getQueryBuilder();
184
-		$params = array_map(function ($value) use ($builder) {
185
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
-		}, $values);
187
-
188
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
-			->from('external_mounts', 'm')
190
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
-			->andWhere($builder->expr()->in('a.value', $params));
193
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
-
195
-		return $this->getMountsFromQuery($query);
196
-	}
197
-
198
-	/**
199
-	 * Get user defined mounts by applicable
200
-	 *
201
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
-	 * @param string|null $value user_id, group_id or null for global mounts
203
-	 * @return array
204
-	 * @suppress SqlInjectionChecker
205
-	 */
206
-	public function getUserMountsFor($type, $value) {
207
-		$builder = $this->connection->getQueryBuilder();
208
-		$query = $this->getForQuery($builder, $type, $value);
209
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
-
211
-		return $this->getMountsFromQuery($query);
212
-	}
213
-
214
-	/**
215
-	 * Add a mount to the database
216
-	 *
217
-	 * @param string $mountPoint
218
-	 * @param string $storageBackend
219
-	 * @param string $authBackend
220
-	 * @param int $priority
221
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
-	 * @return int the id of the new mount
223
-	 */
224
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
-		if (!$priority) {
226
-			$priority = 100;
227
-		}
228
-		$builder = $this->connection->getQueryBuilder();
229
-		$query = $builder->insert('external_mounts')
230
-			->values([
231
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
-			]);
237
-		$query->execute();
238
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
-	}
240
-
241
-	/**
242
-	 * Remove a mount from the database
243
-	 *
244
-	 * @param int $mountId
245
-	 */
246
-	public function removeMount($mountId) {
247
-		$builder = $this->connection->getQueryBuilder();
248
-		$query = $builder->delete('external_mounts')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_applicable')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_config')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-
260
-		$query = $builder->delete('external_options')
261
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
-		$query->execute();
263
-	}
264
-
265
-	/**
266
-	 * @param int $mountId
267
-	 * @param string $newMountPoint
268
-	 */
269
-	public function setMountPoint($mountId, $newMountPoint) {
270
-		$builder = $this->connection->getQueryBuilder();
271
-
272
-		$query = $builder->update('external_mounts')
273
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
-
276
-		$query->execute();
277
-	}
278
-
279
-	/**
280
-	 * @param int $mountId
281
-	 * @param string $newAuthBackend
282
-	 */
283
-	public function setAuthBackend($mountId, $newAuthBackend) {
284
-		$builder = $this->connection->getQueryBuilder();
285
-
286
-		$query = $builder->update('external_mounts')
287
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
-
290
-		$query->execute();
291
-	}
292
-
293
-	/**
294
-	 * @param int $mountId
295
-	 * @param string $key
296
-	 * @param string $value
297
-	 */
298
-	public function setConfig($mountId, $key, $value) {
299
-		if ($key === 'password') {
300
-			$value = $this->encryptValue($value);
301
-		}
302
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
-			'mount_id' => $mountId,
304
-			'key' => $key,
305
-			'value' => $value
306
-		], ['mount_id', 'key']);
307
-		if ($count === 0) {
308
-			$builder = $this->connection->getQueryBuilder();
309
-			$query = $builder->update('external_config')
310
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
-			$query->execute();
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * @param int $mountId
319
-	 * @param string $key
320
-	 * @param string $value
321
-	 */
322
-	public function setOption($mountId, $key, $value) {
323
-
324
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
-			'mount_id' => $mountId,
326
-			'key' => $key,
327
-			'value' => json_encode($value)
328
-		], ['mount_id', 'key']);
329
-		if ($count === 0) {
330
-			$builder = $this->connection->getQueryBuilder();
331
-			$query = $builder->update('external_options')
332
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
-			$query->execute();
336
-		}
337
-	}
338
-
339
-	public function addApplicable($mountId, $type, $value) {
340
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
-			'mount_id' => $mountId,
342
-			'type' => $type,
343
-			'value' => $value
344
-		], ['mount_id', 'type', 'value']);
345
-	}
346
-
347
-	public function removeApplicable($mountId, $type, $value) {
348
-		$builder = $this->connection->getQueryBuilder();
349
-		$query = $builder->delete('external_applicable')
350
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
-
353
-		if (is_null($value)) {
354
-			$query = $query->andWhere($builder->expr()->isNull('value'));
355
-		} else {
356
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
-		}
358
-
359
-		$query->execute();
360
-	}
361
-
362
-	private function getMountsFromQuery(IQueryBuilder $query) {
363
-		$result = $query->execute();
364
-		$mounts = $result->fetchAll();
365
-		$uniqueMounts = [];
366
-		foreach ($mounts as $mount) {
367
-			$id = $mount['mount_id'];
368
-			if (!isset($uniqueMounts[$id])) {
369
-				$uniqueMounts[$id] = $mount;
370
-			}
371
-		}
372
-		$uniqueMounts = array_values($uniqueMounts);
373
-
374
-		$mountIds = array_map(function ($mount) {
375
-			return $mount['mount_id'];
376
-		}, $uniqueMounts);
377
-		$mountIds = array_values(array_unique($mountIds));
378
-
379
-		$applicable = $this->getApplicableForMounts($mountIds);
380
-		$config = $this->getConfigForMounts($mountIds);
381
-		$options = $this->getOptionsForMounts($mountIds);
382
-
383
-		return array_map(function ($mount, $applicable, $config, $options) {
384
-			$mount['type'] = (int)$mount['type'];
385
-			$mount['priority'] = (int)$mount['priority'];
386
-			$mount['applicable'] = $applicable;
387
-			$mount['config'] = $config;
388
-			$mount['options'] = $options;
389
-			return $mount;
390
-		}, $uniqueMounts, $applicable, $config, $options);
391
-	}
392
-
393
-	/**
394
-	 * Get mount options from a table grouped by mount id
395
-	 *
396
-	 * @param string $table
397
-	 * @param string[] $fields
398
-	 * @param int[] $mountIds
399
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
-	 */
401
-	private function selectForMounts($table, array $fields, array $mountIds) {
402
-		if (count($mountIds) === 0) {
403
-			return [];
404
-		}
405
-		$builder = $this->connection->getQueryBuilder();
406
-		$fields[] = 'mount_id';
407
-		$placeHolders = array_map(function ($id) use ($builder) {
408
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
-		}, $mountIds);
410
-		$query = $builder->select($fields)
411
-			->from($table)
412
-			->where($builder->expr()->in('mount_id', $placeHolders));
413
-		$rows = $query->execute()->fetchAll();
414
-
415
-		$result = [];
416
-		foreach ($mountIds as $mountId) {
417
-			$result[$mountId] = [];
418
-		}
419
-		foreach ($rows as $row) {
420
-			if (isset($row['type'])) {
421
-				$row['type'] = (int)$row['type'];
422
-			}
423
-			$result[$row['mount_id']][] = $row;
424
-		}
425
-		return $result;
426
-	}
427
-
428
-	/**
429
-	 * @param int[] $mountIds
430
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
-	 */
432
-	public function getApplicableForMounts($mountIds) {
433
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
-	}
435
-
436
-	/**
437
-	 * @param int[] $mountIds
438
-	 * @return array [$id => ['key1' => $value1, ...], ...]
439
-	 */
440
-	public function getConfigForMounts($mountIds) {
441
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
-	}
444
-
445
-	/**
446
-	 * @param int[] $mountIds
447
-	 * @return array [$id => ['key1' => $value1, ...], ...]
448
-	 */
449
-	public function getOptionsForMounts($mountIds) {
450
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
-		return array_map(function (array $options) {
453
-			return array_map(function ($option) {
454
-				return json_decode($option);
455
-			}, $options);
456
-		}, $optionsMap);
457
-	}
458
-
459
-	/**
460
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
-	 * @return array ['key1' => $value1, ...]
462
-	 */
463
-	private function createKeyValueMap(array $keyValuePairs) {
464
-		$decryptedPairts = array_map(function ($pair) {
465
-			if ($pair['key'] === 'password') {
466
-				$pair['value'] = $this->decryptValue($pair['value']);
467
-			}
468
-			return $pair;
469
-		}, $keyValuePairs);
470
-		$keys = array_map(function ($pair) {
471
-			return $pair['key'];
472
-		}, $decryptedPairts);
473
-		$values = array_map(function ($pair) {
474
-			return $pair['value'];
475
-		}, $decryptedPairts);
476
-
477
-		return array_combine($keys, $values);
478
-	}
479
-
480
-	private function encryptValue($value) {
481
-		return $this->crypto->encrypt($value);
482
-	}
483
-
484
-	private function decryptValue($value) {
485
-		try {
486
-			return $this->crypto->decrypt($value);
487
-		} catch (\Exception $e) {
488
-			return $value;
489
-		}
490
-	}
35
+    const MOUNT_TYPE_ADMIN = 1;
36
+    const MOUNT_TYPE_PERSONAl = 2;
37
+
38
+    const APPLICABLE_TYPE_GLOBAL = 1;
39
+    const APPLICABLE_TYPE_GROUP = 2;
40
+    const APPLICABLE_TYPE_USER = 3;
41
+
42
+    /**
43
+     * @var IDBConnection
44
+     */
45
+    private $connection;
46
+
47
+    /**
48
+     * @var ICrypto
49
+     */
50
+    private $crypto;
51
+
52
+    /**
53
+     * DBConfigService constructor.
54
+     *
55
+     * @param IDBConnection $connection
56
+     * @param ICrypto $crypto
57
+     */
58
+    public function __construct(IDBConnection $connection, ICrypto $crypto) {
59
+        $this->connection = $connection;
60
+        $this->crypto = $crypto;
61
+    }
62
+
63
+    /**
64
+     * @param int $mountId
65
+     * @return array
66
+     */
67
+    public function getMountById($mountId) {
68
+        $builder = $this->connection->getQueryBuilder();
69
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
70
+            ->from('external_mounts', 'm')
71
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
72
+        $mounts = $this->getMountsFromQuery($query);
73
+        if (count($mounts) > 0) {
74
+            return $mounts[0];
75
+        } else {
76
+            return null;
77
+        }
78
+    }
79
+
80
+    /**
81
+     * Get all configured mounts
82
+     *
83
+     * @return array
84
+     */
85
+    public function getAllMounts() {
86
+        $builder = $this->connection->getQueryBuilder();
87
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
88
+            ->from('external_mounts');
89
+        return $this->getMountsFromQuery($query);
90
+    }
91
+
92
+    public function getMountsForUser($userId, $groupIds) {
93
+        $builder = $this->connection->getQueryBuilder();
94
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
95
+            ->from('external_mounts', 'm')
96
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
97
+            ->where($builder->expr()->orX(
98
+                $builder->expr()->andX( // global mounts
99
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GLOBAL, IQueryBuilder::PARAM_INT)),
100
+                    $builder->expr()->isNull('a.value')
101
+                ),
102
+                $builder->expr()->andX( // mounts for user
103
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_USER, IQueryBuilder::PARAM_INT)),
104
+                    $builder->expr()->eq('a.value', $builder->createNamedParameter($userId))
105
+                ),
106
+                $builder->expr()->andX( // mounts for group
107
+                    $builder->expr()->eq('a.type', $builder->createNamedParameter(self::APPLICABLE_TYPE_GROUP, IQueryBuilder::PARAM_INT)),
108
+                    $builder->expr()->in('a.value', $builder->createNamedParameter($groupIds, IQueryBuilder::PARAM_STR_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     * @suppress SqlInjectionChecker
120
+     */
121
+    public function getAdminMounts() {
122
+        $builder = $this->connection->getQueryBuilder();
123
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
124
+            ->from('external_mounts')
125
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
126
+        return $this->getMountsFromQuery($query);
127
+    }
128
+
129
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
130
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
131
+            ->from('external_mounts', 'm')
132
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
133
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
134
+
135
+        if (is_null($value)) {
136
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
137
+        } else {
138
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
139
+        }
140
+
141
+        return $query;
142
+    }
143
+
144
+    /**
145
+     * Get mounts by applicable
146
+     *
147
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
148
+     * @param string|null $value user_id, group_id or null for global mounts
149
+     * @return array
150
+     */
151
+    public function getMountsFor($type, $value) {
152
+        $builder = $this->connection->getQueryBuilder();
153
+        $query = $this->getForQuery($builder, $type, $value);
154
+
155
+        return $this->getMountsFromQuery($query);
156
+    }
157
+
158
+    /**
159
+     * Get admin defined mounts by applicable
160
+     *
161
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
162
+     * @param string|null $value user_id, group_id or null for global mounts
163
+     * @return array
164
+     * @suppress SqlInjectionChecker
165
+     */
166
+    public function getAdminMountsFor($type, $value) {
167
+        $builder = $this->connection->getQueryBuilder();
168
+        $query = $this->getForQuery($builder, $type, $value);
169
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
170
+
171
+        return $this->getMountsFromQuery($query);
172
+    }
173
+
174
+    /**
175
+     * Get admin defined mounts for multiple applicable
176
+     *
177
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
178
+     * @param string[] $values user_ids or group_ids
179
+     * @return array
180
+     * @suppress SqlInjectionChecker
181
+     */
182
+    public function getAdminMountsForMultiple($type, array $values) {
183
+        $builder = $this->connection->getQueryBuilder();
184
+        $params = array_map(function ($value) use ($builder) {
185
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
186
+        }, $values);
187
+
188
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
189
+            ->from('external_mounts', 'm')
190
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
191
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
192
+            ->andWhere($builder->expr()->in('a.value', $params));
193
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
194
+
195
+        return $this->getMountsFromQuery($query);
196
+    }
197
+
198
+    /**
199
+     * Get user defined mounts by applicable
200
+     *
201
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
202
+     * @param string|null $value user_id, group_id or null for global mounts
203
+     * @return array
204
+     * @suppress SqlInjectionChecker
205
+     */
206
+    public function getUserMountsFor($type, $value) {
207
+        $builder = $this->connection->getQueryBuilder();
208
+        $query = $this->getForQuery($builder, $type, $value);
209
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
210
+
211
+        return $this->getMountsFromQuery($query);
212
+    }
213
+
214
+    /**
215
+     * Add a mount to the database
216
+     *
217
+     * @param string $mountPoint
218
+     * @param string $storageBackend
219
+     * @param string $authBackend
220
+     * @param int $priority
221
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
222
+     * @return int the id of the new mount
223
+     */
224
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
225
+        if (!$priority) {
226
+            $priority = 100;
227
+        }
228
+        $builder = $this->connection->getQueryBuilder();
229
+        $query = $builder->insert('external_mounts')
230
+            ->values([
231
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
232
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
233
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
234
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
235
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
236
+            ]);
237
+        $query->execute();
238
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
239
+    }
240
+
241
+    /**
242
+     * Remove a mount from the database
243
+     *
244
+     * @param int $mountId
245
+     */
246
+    public function removeMount($mountId) {
247
+        $builder = $this->connection->getQueryBuilder();
248
+        $query = $builder->delete('external_mounts')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_applicable')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_config')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+
260
+        $query = $builder->delete('external_options')
261
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
262
+        $query->execute();
263
+    }
264
+
265
+    /**
266
+     * @param int $mountId
267
+     * @param string $newMountPoint
268
+     */
269
+    public function setMountPoint($mountId, $newMountPoint) {
270
+        $builder = $this->connection->getQueryBuilder();
271
+
272
+        $query = $builder->update('external_mounts')
273
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
274
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
275
+
276
+        $query->execute();
277
+    }
278
+
279
+    /**
280
+     * @param int $mountId
281
+     * @param string $newAuthBackend
282
+     */
283
+    public function setAuthBackend($mountId, $newAuthBackend) {
284
+        $builder = $this->connection->getQueryBuilder();
285
+
286
+        $query = $builder->update('external_mounts')
287
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
288
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
289
+
290
+        $query->execute();
291
+    }
292
+
293
+    /**
294
+     * @param int $mountId
295
+     * @param string $key
296
+     * @param string $value
297
+     */
298
+    public function setConfig($mountId, $key, $value) {
299
+        if ($key === 'password') {
300
+            $value = $this->encryptValue($value);
301
+        }
302
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
303
+            'mount_id' => $mountId,
304
+            'key' => $key,
305
+            'value' => $value
306
+        ], ['mount_id', 'key']);
307
+        if ($count === 0) {
308
+            $builder = $this->connection->getQueryBuilder();
309
+            $query = $builder->update('external_config')
310
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
311
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
312
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
313
+            $query->execute();
314
+        }
315
+    }
316
+
317
+    /**
318
+     * @param int $mountId
319
+     * @param string $key
320
+     * @param string $value
321
+     */
322
+    public function setOption($mountId, $key, $value) {
323
+
324
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
325
+            'mount_id' => $mountId,
326
+            'key' => $key,
327
+            'value' => json_encode($value)
328
+        ], ['mount_id', 'key']);
329
+        if ($count === 0) {
330
+            $builder = $this->connection->getQueryBuilder();
331
+            $query = $builder->update('external_options')
332
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
333
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
334
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
335
+            $query->execute();
336
+        }
337
+    }
338
+
339
+    public function addApplicable($mountId, $type, $value) {
340
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
341
+            'mount_id' => $mountId,
342
+            'type' => $type,
343
+            'value' => $value
344
+        ], ['mount_id', 'type', 'value']);
345
+    }
346
+
347
+    public function removeApplicable($mountId, $type, $value) {
348
+        $builder = $this->connection->getQueryBuilder();
349
+        $query = $builder->delete('external_applicable')
350
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
351
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
352
+
353
+        if (is_null($value)) {
354
+            $query = $query->andWhere($builder->expr()->isNull('value'));
355
+        } else {
356
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
357
+        }
358
+
359
+        $query->execute();
360
+    }
361
+
362
+    private function getMountsFromQuery(IQueryBuilder $query) {
363
+        $result = $query->execute();
364
+        $mounts = $result->fetchAll();
365
+        $uniqueMounts = [];
366
+        foreach ($mounts as $mount) {
367
+            $id = $mount['mount_id'];
368
+            if (!isset($uniqueMounts[$id])) {
369
+                $uniqueMounts[$id] = $mount;
370
+            }
371
+        }
372
+        $uniqueMounts = array_values($uniqueMounts);
373
+
374
+        $mountIds = array_map(function ($mount) {
375
+            return $mount['mount_id'];
376
+        }, $uniqueMounts);
377
+        $mountIds = array_values(array_unique($mountIds));
378
+
379
+        $applicable = $this->getApplicableForMounts($mountIds);
380
+        $config = $this->getConfigForMounts($mountIds);
381
+        $options = $this->getOptionsForMounts($mountIds);
382
+
383
+        return array_map(function ($mount, $applicable, $config, $options) {
384
+            $mount['type'] = (int)$mount['type'];
385
+            $mount['priority'] = (int)$mount['priority'];
386
+            $mount['applicable'] = $applicable;
387
+            $mount['config'] = $config;
388
+            $mount['options'] = $options;
389
+            return $mount;
390
+        }, $uniqueMounts, $applicable, $config, $options);
391
+    }
392
+
393
+    /**
394
+     * Get mount options from a table grouped by mount id
395
+     *
396
+     * @param string $table
397
+     * @param string[] $fields
398
+     * @param int[] $mountIds
399
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
400
+     */
401
+    private function selectForMounts($table, array $fields, array $mountIds) {
402
+        if (count($mountIds) === 0) {
403
+            return [];
404
+        }
405
+        $builder = $this->connection->getQueryBuilder();
406
+        $fields[] = 'mount_id';
407
+        $placeHolders = array_map(function ($id) use ($builder) {
408
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
409
+        }, $mountIds);
410
+        $query = $builder->select($fields)
411
+            ->from($table)
412
+            ->where($builder->expr()->in('mount_id', $placeHolders));
413
+        $rows = $query->execute()->fetchAll();
414
+
415
+        $result = [];
416
+        foreach ($mountIds as $mountId) {
417
+            $result[$mountId] = [];
418
+        }
419
+        foreach ($rows as $row) {
420
+            if (isset($row['type'])) {
421
+                $row['type'] = (int)$row['type'];
422
+            }
423
+            $result[$row['mount_id']][] = $row;
424
+        }
425
+        return $result;
426
+    }
427
+
428
+    /**
429
+     * @param int[] $mountIds
430
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
431
+     */
432
+    public function getApplicableForMounts($mountIds) {
433
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
434
+    }
435
+
436
+    /**
437
+     * @param int[] $mountIds
438
+     * @return array [$id => ['key1' => $value1, ...], ...]
439
+     */
440
+    public function getConfigForMounts($mountIds) {
441
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
442
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
443
+    }
444
+
445
+    /**
446
+     * @param int[] $mountIds
447
+     * @return array [$id => ['key1' => $value1, ...], ...]
448
+     */
449
+    public function getOptionsForMounts($mountIds) {
450
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
451
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
452
+        return array_map(function (array $options) {
453
+            return array_map(function ($option) {
454
+                return json_decode($option);
455
+            }, $options);
456
+        }, $optionsMap);
457
+    }
458
+
459
+    /**
460
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
461
+     * @return array ['key1' => $value1, ...]
462
+     */
463
+    private function createKeyValueMap(array $keyValuePairs) {
464
+        $decryptedPairts = array_map(function ($pair) {
465
+            if ($pair['key'] === 'password') {
466
+                $pair['value'] = $this->decryptValue($pair['value']);
467
+            }
468
+            return $pair;
469
+        }, $keyValuePairs);
470
+        $keys = array_map(function ($pair) {
471
+            return $pair['key'];
472
+        }, $decryptedPairts);
473
+        $values = array_map(function ($pair) {
474
+            return $pair['value'];
475
+        }, $decryptedPairts);
476
+
477
+        return array_combine($keys, $values);
478
+    }
479
+
480
+    private function encryptValue($value) {
481
+        return $this->crypto->encrypt($value);
482
+    }
483
+
484
+    private function decryptValue($value) {
485
+        try {
486
+            return $this->crypto->decrypt($value);
487
+        } catch (\Exception $e) {
488
+            return $value;
489
+        }
490
+    }
491 491
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/OCS/BaseResponse.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
 	/**
25 25
 	 * BaseResponse constructor.
26 26
 	 *
27
-	 * @param DataResponse|null $dataResponse
27
+	 * @param DataResponse $dataResponse
28 28
 	 * @param string $format
29 29
 	 * @param string|null $statusMessage
30 30
 	 * @param int|null $itemsCount
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -27,70 +27,70 @@
 block discarded – undo
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29 29
 abstract class BaseResponse extends Response   {
30
-	/** @var array */
31
-	protected $data;
30
+    /** @var array */
31
+    protected $data;
32 32
 
33
-	/** @var string */
34
-	protected $format;
33
+    /** @var string */
34
+    protected $format;
35 35
 
36
-	/** @var string */
37
-	protected $statusMessage;
36
+    /** @var string */
37
+    protected $statusMessage;
38 38
 
39
-	/** @var int */
40
-	protected $itemsCount;
39
+    /** @var int */
40
+    protected $itemsCount;
41 41
 
42
-	/** @var int */
43
-	protected $itemsPerPage;
42
+    /** @var int */
43
+    protected $itemsPerPage;
44 44
 
45
-	/**
46
-	 * BaseResponse constructor.
47
-	 *
48
-	 * @param DataResponse|null $dataResponse
49
-	 * @param string $format
50
-	 * @param string|null $statusMessage
51
-	 * @param int|null $itemsCount
52
-	 * @param int|null $itemsPerPage
53
-	 */
54
-	public function __construct(DataResponse $dataResponse,
55
-								$format = 'xml',
56
-								$statusMessage = null,
57
-								$itemsCount = null,
58
-								$itemsPerPage = null) {
59
-		$this->format = $format;
60
-		$this->statusMessage = $statusMessage;
61
-		$this->itemsCount = $itemsCount;
62
-		$this->itemsPerPage = $itemsPerPage;
45
+    /**
46
+     * BaseResponse constructor.
47
+     *
48
+     * @param DataResponse|null $dataResponse
49
+     * @param string $format
50
+     * @param string|null $statusMessage
51
+     * @param int|null $itemsCount
52
+     * @param int|null $itemsPerPage
53
+     */
54
+    public function __construct(DataResponse $dataResponse,
55
+                                $format = 'xml',
56
+                                $statusMessage = null,
57
+                                $itemsCount = null,
58
+                                $itemsPerPage = null) {
59
+        $this->format = $format;
60
+        $this->statusMessage = $statusMessage;
61
+        $this->itemsCount = $itemsCount;
62
+        $this->itemsPerPage = $itemsPerPage;
63 63
 
64
-		$this->data = $dataResponse->getData();
64
+        $this->data = $dataResponse->getData();
65 65
 
66
-		$this->setHeaders($dataResponse->getHeaders());
67
-		$this->setStatus($dataResponse->getStatus());
68
-		$this->setETag($dataResponse->getETag());
69
-		$this->setLastModified($dataResponse->getLastModified());
70
-		$this->setCookies($dataResponse->getCookies());
71
-		$this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
66
+        $this->setHeaders($dataResponse->getHeaders());
67
+        $this->setStatus($dataResponse->getStatus());
68
+        $this->setETag($dataResponse->getETag());
69
+        $this->setLastModified($dataResponse->getLastModified());
70
+        $this->setCookies($dataResponse->getCookies());
71
+        $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy());
72 72
 
73
-		if ($format === 'json') {
74
-			$this->addHeader(
75
-				'Content-Type', 'application/json; charset=utf-8'
76
-			);
77
-		} else {
78
-			$this->addHeader(
79
-				'Content-Type', 'application/xml; charset=utf-8'
80
-			);
81
-		}
82
-	}
73
+        if ($format === 'json') {
74
+            $this->addHeader(
75
+                'Content-Type', 'application/json; charset=utf-8'
76
+            );
77
+        } else {
78
+            $this->addHeader(
79
+                'Content-Type', 'application/xml; charset=utf-8'
80
+            );
81
+        }
82
+    }
83 83
 
84
-	/**
85
-	 * @param string[] $meta
86
-	 * @return string
87
-	 */
88
-	protected function renderResult($meta) {
89
-		// TODO rewrite functions
90
-		return \OC_API::renderResult($this->format, $meta, $this->data);
91
-	}
84
+    /**
85
+     * @param string[] $meta
86
+     * @return string
87
+     */
88
+    protected function renderResult($meta) {
89
+        // TODO rewrite functions
90
+        return \OC_API::renderResult($this->format, $meta, $this->data);
91
+    }
92 92
 
93
-	public function getOCSStatus() {
94
-		return parent::getStatus();
95
-	}
93
+    public function getOCSStatus() {
94
+        return parent::getStatus();
95
+    }
96 96
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@
 block discarded – undo
26 26
 use OCP\AppFramework\Http\EmptyContentSecurityPolicy;
27 27
 use OCP\AppFramework\Http\Response;
28 28
 
29
-abstract class BaseResponse extends Response   {
29
+abstract class BaseResponse extends Response {
30 30
 	/** @var array */
31 31
 	protected $data;
32 32
 
Please login to merge, or discard this patch.
lib/private/Server.php 4 patches
Doc Comments   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1143,7 +1143,7 @@  discard block
 block discarded – undo
1143 1143
 	 * Get the certificate manager for the user
1144 1144
 	 *
1145 1145
 	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1146
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1146
+	 * @return null|CertificateManager | null if $uid is null and no user is logged in
1147 1147
 	 */
1148 1148
 	public function getCertificateManager($userId = '') {
1149 1149
 		if ($userId === '') {
@@ -1464,6 +1464,7 @@  discard block
 block discarded – undo
1464 1464
 	}
1465 1465
 
1466 1466
 	/**
1467
+	 * @param string $app
1467 1468
 	 * @return \OCP\Files\IAppData
1468 1469
 	 */
1469 1470
 	public function getAppDataDir($app) {
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -103,7 +103,6 @@
 block discarded – undo
103 103
 use OC\Tagging\TagMapper;
104 104
 use OC\Template\SCSSCacher;
105 105
 use OCA\Theming\ThemingDefaults;
106
-
107 106
 use OCP\App\IAppManager;
108 107
 use OCP\AppFramework\Utility\ITimeFactory;
109 108
 use OCP\Collaboration\AutoComplete\IManager;
Please login to merge, or discard this patch.
Spacing   +114 added lines, -114 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 		parent::__construct();
158 158
 		$this->webRoot = $webRoot;
159 159
 
160
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
160
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
161 161
 			return $c;
162 162
 		});
163 163
 
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
171 171
 
172 172
 
173
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
173
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
174 174
 			return new PreviewManager(
175 175
 				$c->getConfig(),
176 176
 				$c->getRootFolder(),
@@ -181,13 +181,13 @@  discard block
 block discarded – undo
181 181
 		});
182 182
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
183 183
 
184
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
184
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
185 185
 			return new \OC\Preview\Watcher(
186 186
 				$c->getAppDataDir('preview')
187 187
 			);
188 188
 		});
189 189
 
190
-		$this->registerService('EncryptionManager', function (Server $c) {
190
+		$this->registerService('EncryptionManager', function(Server $c) {
191 191
 			$view = new View();
192 192
 			$util = new Encryption\Util(
193 193
 				$view,
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 			);
206 206
 		});
207 207
 
208
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
208
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
209 209
 			$util = new Encryption\Util(
210 210
 				new View(),
211 211
 				$c->getUserManager(),
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 			);
220 220
 		});
221 221
 
222
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
222
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
223 223
 			$view = new View();
224 224
 			$util = new Encryption\Util(
225 225
 				$view,
@@ -230,30 +230,30 @@  discard block
 block discarded – undo
230 230
 
231 231
 			return new Encryption\Keys\Storage($view, $util);
232 232
 		});
233
-		$this->registerService('TagMapper', function (Server $c) {
233
+		$this->registerService('TagMapper', function(Server $c) {
234 234
 			return new TagMapper($c->getDatabaseConnection());
235 235
 		});
236 236
 
237
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
237
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
238 238
 			$tagMapper = $c->query('TagMapper');
239 239
 			return new TagManager($tagMapper, $c->getUserSession());
240 240
 		});
241 241
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
242 242
 
243
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
243
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
244 244
 			$config = $c->getConfig();
245 245
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246 246
 			return new $factoryClass($this);
247 247
 		});
248
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
248
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
249 249
 			return $c->query('SystemTagManagerFactory')->getManager();
250 250
 		});
251 251
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252 252
 
253
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
253
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
254 254
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
255 255
 		});
256
-		$this->registerService('RootFolder', function (Server $c) {
256
+		$this->registerService('RootFolder', function(Server $c) {
257 257
 			$manager = \OC\Files\Filesystem::getMountManager(null);
258 258
 			$view = new View();
259 259
 			$root = new Root(
@@ -274,38 +274,38 @@  discard block
 block discarded – undo
274 274
 		});
275 275
 		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276 276
 
277
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
-			return new LazyRoot(function () use ($c) {
277
+		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
278
+			return new LazyRoot(function() use ($c) {
279 279
 				return $c->query('RootFolder');
280 280
 			});
281 281
 		});
282 282
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283 283
 
284
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
284
+		$this->registerService(\OC\User\Manager::class, function(Server $c) {
285 285
 			$config = $c->getConfig();
286 286
 			return new \OC\User\Manager($config);
287 287
 		});
288 288
 		$this->registerAlias('UserManager', \OC\User\Manager::class);
289 289
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290 290
 
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
291
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
292 292
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
293
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
294 294
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295 295
 			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
296
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
297 297
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298 298
 			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
299
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
300 300
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301 301
 			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
302
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304 304
 			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
305
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
306 306
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307 307
 			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
308
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
309 309
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310 310
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311 311
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		});
315 315
 		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316 316
 
317
-		$this->registerService(Store::class, function (Server $c) {
317
+		$this->registerService(Store::class, function(Server $c) {
318 318
 			$session = $c->getSession();
319 319
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320 320
 				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
@@ -325,11 +325,11 @@  discard block
 block discarded – undo
325 325
 			return new Store($session, $logger, $tokenProvider);
326 326
 		});
327 327
 		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
328
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
329 329
 			$dbConnection = $c->getDatabaseConnection();
330 330
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331 331
 		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
332
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
333 333
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334 334
 			$crypto = $c->getCrypto();
335 335
 			$config = $c->getConfig();
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		});
340 340
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341 341
 
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
342
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
343 343
 			$manager = $c->getUserManager();
344 344
 			$session = new \OC\Session\Memory('');
345 345
 			$timeFactory = new TimeFactory();
@@ -363,45 +363,45 @@  discard block
 block discarded – undo
363 363
 				$c->getLockdownManager(),
364 364
 				$c->getLogger()
365 365
 			);
366
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
366
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
367 367
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368 368
 			});
369
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
369
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
370 370
 				/** @var $user \OC\User\User */
371 371
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372 372
 			});
373
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
373
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($dispatcher) {
374 374
 				/** @var $user \OC\User\User */
375 375
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376 376
 				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377 377
 			});
378
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
378
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
379 379
 				/** @var $user \OC\User\User */
380 380
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381 381
 			});
382
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
382
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
383 383
 				/** @var $user \OC\User\User */
384 384
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385 385
 			});
386
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
386
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
387 387
 				/** @var $user \OC\User\User */
388 388
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389 389
 			});
390
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
390
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
391 391
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392 392
 			});
393
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
393
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
394 394
 				/** @var $user \OC\User\User */
395 395
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396 396
 			});
397
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
397
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
398 398
 				/** @var $user \OC\User\User */
399 399
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400 400
 			});
401
-			$userSession->listen('\OC\User', 'logout', function () {
401
+			$userSession->listen('\OC\User', 'logout', function() {
402 402
 				\OC_Hook::emit('OC_User', 'logout', array());
403 403
 			});
404
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
404
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) use ($dispatcher) {
405 405
 				/** @var $user \OC\User\User */
406 406
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407 407
 				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		});
411 411
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
412 412
 
413
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
413
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
414 414
 			return new \OC\Authentication\TwoFactorAuth\Manager(
415 415
 				$c->getAppManager(),
416 416
 				$c->getSession(),
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427 427
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428 428
 
429
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
429
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
430 430
 			return new \OC\AllConfig(
431 431
 				$c->getSystemConfig()
432 432
 			);
@@ -434,17 +434,17 @@  discard block
 block discarded – undo
434 434
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
435 435
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436 436
 
437
-		$this->registerService('SystemConfig', function ($c) use ($config) {
437
+		$this->registerService('SystemConfig', function($c) use ($config) {
438 438
 			return new \OC\SystemConfig($config);
439 439
 		});
440 440
 
441
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
441
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
442 442
 			return new \OC\AppConfig($c->getDatabaseConnection());
443 443
 		});
444 444
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
445 445
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446 446
 
447
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
447
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
448 448
 			return new \OC\L10N\Factory(
449 449
 				$c->getConfig(),
450 450
 				$c->getRequest(),
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 		});
455 455
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456 456
 
457
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
457
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
458 458
 			$config = $c->getConfig();
459 459
 			$cacheFactory = $c->getMemCacheFactory();
460 460
 			$request = $c->getRequest();
@@ -466,18 +466,18 @@  discard block
 block discarded – undo
466 466
 		});
467 467
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468 468
 
469
-		$this->registerService('AppHelper', function ($c) {
469
+		$this->registerService('AppHelper', function($c) {
470 470
 			return new \OC\AppHelper();
471 471
 		});
472 472
 		$this->registerAlias('AppFetcher', AppFetcher::class);
473 473
 		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474 474
 
475
-		$this->registerService(\OCP\ICache::class, function ($c) {
475
+		$this->registerService(\OCP\ICache::class, function($c) {
476 476
 			return new Cache\File();
477 477
 		});
478 478
 		$this->registerAlias('UserCache', \OCP\ICache::class);
479 479
 
480
-		$this->registerService(Factory::class, function (Server $c) {
480
+		$this->registerService(Factory::class, function(Server $c) {
481 481
 
482 482
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483 483
 				'\\OC\\Memcache\\ArrayCache',
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 				$version = implode(',', $v);
495 495
 				$instanceId = \OC_Util::getInstanceId();
496 496
 				$path = \OC::$SERVERROOT;
497
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
497
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.$urlGenerator->getBaseUrl());
498 498
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499 499
 					$config->getSystemValue('memcache.local', null),
500 500
 					$config->getSystemValue('memcache.distributed', null),
@@ -507,12 +507,12 @@  discard block
 block discarded – undo
507 507
 		$this->registerAlias('MemCacheFactory', Factory::class);
508 508
 		$this->registerAlias(ICacheFactory::class, Factory::class);
509 509
 
510
-		$this->registerService('RedisFactory', function (Server $c) {
510
+		$this->registerService('RedisFactory', function(Server $c) {
511 511
 			$systemConfig = $c->getSystemConfig();
512 512
 			return new RedisFactory($systemConfig);
513 513
 		});
514 514
 
515
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
515
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
516 516
 			return new \OC\Activity\Manager(
517 517
 				$c->getRequest(),
518 518
 				$c->getUserSession(),
@@ -522,14 +522,14 @@  discard block
 block discarded – undo
522 522
 		});
523 523
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524 524
 
525
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
525
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
526 526
 			return new \OC\Activity\EventMerger(
527 527
 				$c->getL10N('lib')
528 528
 			);
529 529
 		});
530 530
 		$this->registerAlias(IValidator::class, Validator::class);
531 531
 
532
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
532
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
533 533
 			return new AvatarManager(
534 534
 				$c->query(\OC\User\Manager::class),
535 535
 				$c->getAppDataDir('avatar'),
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 
543 543
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544 544
 
545
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
545
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
546 546
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547 547
 			$logger = Log::getLogClass($logType);
548 548
 			call_user_func(array($logger, 'init'));
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 		});
554 554
 		$this->registerAlias('Logger', \OCP\ILogger::class);
555 555
 
556
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
556
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
557 557
 			$config = $c->getConfig();
558 558
 			return new \OC\BackgroundJob\JobList(
559 559
 				$c->getDatabaseConnection(),
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 		});
564 564
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565 565
 
566
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
566
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
567 567
 			$cacheFactory = $c->getMemCacheFactory();
568 568
 			$logger = $c->getLogger();
569 569
 			if ($cacheFactory->isAvailableLowLatency()) {
@@ -575,12 +575,12 @@  discard block
 block discarded – undo
575 575
 		});
576 576
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
577 577
 
578
-		$this->registerService(\OCP\ISearch::class, function ($c) {
578
+		$this->registerService(\OCP\ISearch::class, function($c) {
579 579
 			return new Search();
580 580
 		});
581 581
 		$this->registerAlias('Search', \OCP\ISearch::class);
582 582
 
583
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
583
+		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function($c) {
584 584
 			return new \OC\Security\RateLimiting\Limiter(
585 585
 				$this->getUserSession(),
586 586
 				$this->getRequest(),
@@ -588,34 +588,34 @@  discard block
 block discarded – undo
588 588
 				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589 589
 			);
590 590
 		});
591
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
591
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
592 592
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
593 593
 				$this->getMemCacheFactory(),
594 594
 				new \OC\AppFramework\Utility\TimeFactory()
595 595
 			);
596 596
 		});
597 597
 
598
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
598
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
599 599
 			return new SecureRandom();
600 600
 		});
601 601
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602 602
 
603
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
603
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
604 604
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
605 605
 		});
606 606
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607 607
 
608
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
608
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
609 609
 			return new Hasher($c->getConfig());
610 610
 		});
611 611
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612 612
 
613
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
613
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
614 614
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615 615
 		});
616 616
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617 617
 
618
-		$this->registerService(IDBConnection::class, function (Server $c) {
618
+		$this->registerService(IDBConnection::class, function(Server $c) {
619 619
 			$systemConfig = $c->getSystemConfig();
620 620
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
621 621
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -629,7 +629,7 @@  discard block
 block discarded – undo
629 629
 		});
630 630
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
631 631
 
632
-		$this->registerService('HTTPHelper', function (Server $c) {
632
+		$this->registerService('HTTPHelper', function(Server $c) {
633 633
 			$config = $c->getConfig();
634 634
 			return new HTTPHelper(
635 635
 				$config,
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 			);
638 638
 		});
639 639
 
640
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
640
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
641 641
 			$user = \OC_User::getUser();
642 642
 			$uid = $user ? $user : null;
643 643
 			return new ClientService(
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 			);
653 653
 		});
654 654
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
655
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
656 656
 			$eventLogger = new EventLogger();
657 657
 			if ($c->getSystemConfig()->getValue('debug', false)) {
658 658
 				// In debug mode, module is being activated by default
@@ -662,7 +662,7 @@  discard block
 block discarded – undo
662 662
 		});
663 663
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664 664
 
665
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
665
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
666 666
 			$queryLogger = new QueryLogger();
667 667
 			if ($c->getSystemConfig()->getValue('debug', false)) {
668 668
 				// In debug mode, module is being activated by default
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
 		});
673 673
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674 674
 
675
-		$this->registerService(TempManager::class, function (Server $c) {
675
+		$this->registerService(TempManager::class, function(Server $c) {
676 676
 			return new TempManager(
677 677
 				$c->getLogger(),
678 678
 				$c->getConfig()
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
 		$this->registerAlias('TempManager', TempManager::class);
682 682
 		$this->registerAlias(ITempManager::class, TempManager::class);
683 683
 
684
-		$this->registerService(AppManager::class, function (Server $c) {
684
+		$this->registerService(AppManager::class, function(Server $c) {
685 685
 			return new \OC\App\AppManager(
686 686
 				$c->getUserSession(),
687 687
 				$c->query(\OC\AppConfig::class),
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 		$this->registerAlias('AppManager', AppManager::class);
694 694
 		$this->registerAlias(IAppManager::class, AppManager::class);
695 695
 
696
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
696
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
697 697
 			return new DateTimeZone(
698 698
 				$c->getConfig(),
699 699
 				$c->getSession()
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
 		});
702 702
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703 703
 
704
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
704
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
705 705
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706 706
 
707 707
 			return new DateTimeFormatter(
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 		});
712 712
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713 713
 
714
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
714
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
715 715
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716 716
 			$listener = new UserMountCacheListener($mountCache);
717 717
 			$listener->listen($c->getUserManager());
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 		});
720 720
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721 721
 
722
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
722
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
723 723
 			$loader = \OC\Files\Filesystem::getLoader();
724 724
 			$mountCache = $c->query('UserMountCache');
725 725
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -735,10 +735,10 @@  discard block
 block discarded – undo
735 735
 		});
736 736
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737 737
 
738
-		$this->registerService('IniWrapper', function ($c) {
738
+		$this->registerService('IniWrapper', function($c) {
739 739
 			return new IniGetWrapper();
740 740
 		});
741
-		$this->registerService('AsyncCommandBus', function (Server $c) {
741
+		$this->registerService('AsyncCommandBus', function(Server $c) {
742 742
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
743 743
 			if ($busClass) {
744 744
 				list($app, $class) = explode('::', $busClass, 2);
@@ -753,10 +753,10 @@  discard block
 block discarded – undo
753 753
 				return new CronBus($jobList);
754 754
 			}
755 755
 		});
756
-		$this->registerService('TrustedDomainHelper', function ($c) {
756
+		$this->registerService('TrustedDomainHelper', function($c) {
757 757
 			return new TrustedDomainHelper($this->getConfig());
758 758
 		});
759
-		$this->registerService('Throttler', function (Server $c) {
759
+		$this->registerService('Throttler', function(Server $c) {
760 760
 			return new Throttler(
761 761
 				$c->getDatabaseConnection(),
762 762
 				new TimeFactory(),
@@ -764,7 +764,7 @@  discard block
 block discarded – undo
764 764
 				$c->getConfig()
765 765
 			);
766 766
 		});
767
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
767
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
768 768
 			// IConfig and IAppManager requires a working database. This code
769 769
 			// might however be called when ownCloud is not yet setup.
770 770
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
 				$c->getTempManager()
786 786
 			);
787 787
 		});
788
-		$this->registerService(\OCP\IRequest::class, function ($c) {
788
+		$this->registerService(\OCP\IRequest::class, function($c) {
789 789
 			if (isset($this['urlParams'])) {
790 790
 				$urlParams = $this['urlParams'];
791 791
 			} else {
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
 		});
822 822
 		$this->registerAlias('Request', \OCP\IRequest::class);
823 823
 
824
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
824
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
825 825
 			return new Mailer(
826 826
 				$c->getConfig(),
827 827
 				$c->getLogger(),
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 		});
833 833
 		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834 834
 
835
-		$this->registerService('LDAPProvider', function (Server $c) {
835
+		$this->registerService('LDAPProvider', function(Server $c) {
836 836
 			$config = $c->getConfig();
837 837
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838 838
 			if (is_null($factoryClass)) {
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
 			$factory = new $factoryClass($this);
843 843
 			return $factory->getLDAPProvider();
844 844
 		});
845
-		$this->registerService(ILockingProvider::class, function (Server $c) {
845
+		$this->registerService(ILockingProvider::class, function(Server $c) {
846 846
 			$ini = $c->getIniWrapper();
847 847
 			$config = $c->getConfig();
848 848
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -859,49 +859,49 @@  discard block
 block discarded – undo
859 859
 		});
860 860
 		$this->registerAlias('LockingProvider', ILockingProvider::class);
861 861
 
862
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
862
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
863 863
 			return new \OC\Files\Mount\Manager();
864 864
 		});
865 865
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866 866
 
867
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
867
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
868 868
 			return new \OC\Files\Type\Detection(
869 869
 				$c->getURLGenerator(),
870 870
 				\OC::$configDir,
871
-				\OC::$SERVERROOT . '/resources/config/'
871
+				\OC::$SERVERROOT.'/resources/config/'
872 872
 			);
873 873
 		});
874 874
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875 875
 
876
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
876
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
877 877
 			return new \OC\Files\Type\Loader(
878 878
 				$c->getDatabaseConnection()
879 879
 			);
880 880
 		});
881 881
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
-		$this->registerService(BundleFetcher::class, function () {
882
+		$this->registerService(BundleFetcher::class, function() {
883 883
 			return new BundleFetcher($this->getL10N('lib'));
884 884
 		});
885
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
885
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
886 886
 			return new Manager(
887 887
 				$c->query(IValidator::class)
888 888
 			);
889 889
 		});
890 890
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891 891
 
892
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
892
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
893 893
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
894
-			$manager->registerCapability(function () use ($c) {
894
+			$manager->registerCapability(function() use ($c) {
895 895
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
896 896
 			});
897
-			$manager->registerCapability(function () use ($c) {
897
+			$manager->registerCapability(function() use ($c) {
898 898
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899 899
 			});
900 900
 			return $manager;
901 901
 		});
902 902
 		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903 903
 
904
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
904
+		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
905 905
 			$config = $c->getConfig();
906 906
 			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907 907
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
912 912
 				$manager = $c->getUserManager();
913 913
 				$user = $manager->get($id);
914
-				if(is_null($user)) {
914
+				if (is_null($user)) {
915 915
 					$l = $c->getL10N('core');
916 916
 					$displayName = $l->t('Unknown user');
917 917
 				} else {
@@ -924,7 +924,7 @@  discard block
 block discarded – undo
924 924
 		});
925 925
 		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926 926
 
927
-		$this->registerService('ThemingDefaults', function (Server $c) {
927
+		$this->registerService('ThemingDefaults', function(Server $c) {
928 928
 			/*
929 929
 			 * Dark magic for autoloader.
930 930
 			 * If we do a class_exists it will try to load the class which will
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
 			}
952 952
 			return new \OC_Defaults();
953 953
 		});
954
-		$this->registerService(SCSSCacher::class, function (Server $c) {
954
+		$this->registerService(SCSSCacher::class, function(Server $c) {
955 955
 			/** @var Factory $cacheFactory */
956 956
 			$cacheFactory = $c->query(Factory::class);
957 957
 			return new SCSSCacher(
@@ -964,13 +964,13 @@  discard block
 block discarded – undo
964 964
 				$cacheFactory->createDistributed('SCSS')
965 965
 			);
966 966
 		});
967
-		$this->registerService(EventDispatcher::class, function () {
967
+		$this->registerService(EventDispatcher::class, function() {
968 968
 			return new EventDispatcher();
969 969
 		});
970 970
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
971 971
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972 972
 
973
-		$this->registerService('CryptoWrapper', function (Server $c) {
973
+		$this->registerService('CryptoWrapper', function(Server $c) {
974 974
 			// FIXME: Instantiiated here due to cyclic dependency
975 975
 			$request = new Request(
976 976
 				[
@@ -995,7 +995,7 @@  discard block
 block discarded – undo
995 995
 				$request
996 996
 			);
997 997
 		});
998
-		$this->registerService('CsrfTokenManager', function (Server $c) {
998
+		$this->registerService('CsrfTokenManager', function(Server $c) {
999 999
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000 1000
 
1001 1001
 			return new CsrfTokenManager(
@@ -1003,22 +1003,22 @@  discard block
 block discarded – undo
1003 1003
 				$c->query(SessionStorage::class)
1004 1004
 			);
1005 1005
 		});
1006
-		$this->registerService(SessionStorage::class, function (Server $c) {
1006
+		$this->registerService(SessionStorage::class, function(Server $c) {
1007 1007
 			return new SessionStorage($c->getSession());
1008 1008
 		});
1009
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1009
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
1010 1010
 			return new ContentSecurityPolicyManager();
1011 1011
 		});
1012 1012
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013 1013
 
1014
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1014
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1015 1015
 			return new ContentSecurityPolicyNonceManager(
1016 1016
 				$c->getCsrfTokenManager(),
1017 1017
 				$c->getRequest()
1018 1018
 			);
1019 1019
 		});
1020 1020
 
1021
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1021
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1022 1022
 			$config = $c->getConfig();
1023 1023
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024 1024
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
 
1062 1062
 		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063 1063
 
1064
-		$this->registerService('SettingsManager', function (Server $c) {
1064
+		$this->registerService('SettingsManager', function(Server $c) {
1065 1065
 			$manager = new \OC\Settings\Manager(
1066 1066
 				$c->getLogger(),
1067 1067
 				$c->getDatabaseConnection(),
@@ -1081,24 +1081,24 @@  discard block
 block discarded – undo
1081 1081
 			);
1082 1082
 			return $manager;
1083 1083
 		});
1084
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1084
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1085 1085
 			return new \OC\Files\AppData\Factory(
1086 1086
 				$c->getRootFolder(),
1087 1087
 				$c->getSystemConfig()
1088 1088
 			);
1089 1089
 		});
1090 1090
 
1091
-		$this->registerService('LockdownManager', function (Server $c) {
1092
-			return new LockdownManager(function () use ($c) {
1091
+		$this->registerService('LockdownManager', function(Server $c) {
1092
+			return new LockdownManager(function() use ($c) {
1093 1093
 				return $c->getSession();
1094 1094
 			});
1095 1095
 		});
1096 1096
 
1097
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1097
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1098 1098
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1099 1099
 		});
1100 1100
 
1101
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1101
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1102 1102
 			return new CloudIdManager();
1103 1103
 		});
1104 1104
 
@@ -1108,18 +1108,18 @@  discard block
 block discarded – undo
1108 1108
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1109 1109
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1110 1110
 
1111
-		$this->registerService(Defaults::class, function (Server $c) {
1111
+		$this->registerService(Defaults::class, function(Server $c) {
1112 1112
 			return new Defaults(
1113 1113
 				$c->getThemingDefaults()
1114 1114
 			);
1115 1115
 		});
1116 1116
 		$this->registerAlias('Defaults', \OCP\Defaults::class);
1117 1117
 
1118
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1118
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1119 1119
 			return $c->query(\OCP\IUserSession::class)->getSession();
1120 1120
 		});
1121 1121
 
1122
-		$this->registerService(IShareHelper::class, function (Server $c) {
1122
+		$this->registerService(IShareHelper::class, function(Server $c) {
1123 1123
 			return new ShareHelper(
1124 1124
 				$c->query(\OCP\Share\IManager::class)
1125 1125
 			);
@@ -1181,11 +1181,11 @@  discard block
 block discarded – undo
1181 1181
 				// no avatar to remove
1182 1182
 			} catch (\Exception $e) {
1183 1183
 				// Ignore exceptions
1184
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1184
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1185 1185
 			}
1186 1186
 		});
1187 1187
 
1188
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1188
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1189 1189
 			$manager = $this->getAvatarManager();
1190 1190
 			/** @var IUser $user */
1191 1191
 			$user = $e->getSubject();
@@ -1336,7 +1336,7 @@  discard block
 block discarded – undo
1336 1336
 	 * @deprecated since 9.2.0 use IAppData
1337 1337
 	 */
1338 1338
 	public function getAppFolder() {
1339
-		$dir = '/' . \OC_App::getCurrentApp();
1339
+		$dir = '/'.\OC_App::getCurrentApp();
1340 1340
 		$root = $this->getRootFolder();
1341 1341
 		if (!$root->nodeExists($dir)) {
1342 1342
 			$folder = $root->newFolder($dir);
@@ -1920,7 +1920,7 @@  discard block
 block discarded – undo
1920 1920
 	/**
1921 1921
 	 * @return \OCP\Collaboration\AutoComplete\IManager
1922 1922
 	 */
1923
-	public function getAutoCompleteManager(){
1923
+	public function getAutoCompleteManager() {
1924 1924
 		return $this->query(IManager::class);
1925 1925
 	}
1926 1926
 
Please login to merge, or discard this patch.
Indentation   +1823 added lines, -1823 removed lines patch added patch discarded remove patch
@@ -146,1832 +146,1832 @@
 block discarded – undo
146 146
  * TODO: hookup all manager classes
147 147
  */
148 148
 class Server extends ServerContainer implements IServerContainer {
149
-	/** @var string */
150
-	private $webRoot;
151
-
152
-	/**
153
-	 * @param string $webRoot
154
-	 * @param \OC\Config $config
155
-	 */
156
-	public function __construct($webRoot, \OC\Config $config) {
157
-		parent::__construct();
158
-		$this->webRoot = $webRoot;
159
-
160
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
-			return $c;
162
-		});
163
-
164
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
165
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
166
-
167
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
168
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
169
-
170
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
171
-
172
-
173
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
174
-			return new PreviewManager(
175
-				$c->getConfig(),
176
-				$c->getRootFolder(),
177
-				$c->getAppDataDir('preview'),
178
-				$c->getEventDispatcher(),
179
-				$c->getSession()->get('user_id')
180
-			);
181
-		});
182
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
183
-
184
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
-			return new \OC\Preview\Watcher(
186
-				$c->getAppDataDir('preview')
187
-			);
188
-		});
189
-
190
-		$this->registerService('EncryptionManager', function (Server $c) {
191
-			$view = new View();
192
-			$util = new Encryption\Util(
193
-				$view,
194
-				$c->getUserManager(),
195
-				$c->getGroupManager(),
196
-				$c->getConfig()
197
-			);
198
-			return new Encryption\Manager(
199
-				$c->getConfig(),
200
-				$c->getLogger(),
201
-				$c->getL10N('core'),
202
-				new View(),
203
-				$util,
204
-				new ArrayCache()
205
-			);
206
-		});
207
-
208
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
209
-			$util = new Encryption\Util(
210
-				new View(),
211
-				$c->getUserManager(),
212
-				$c->getGroupManager(),
213
-				$c->getConfig()
214
-			);
215
-			return new Encryption\File(
216
-				$util,
217
-				$c->getRootFolder(),
218
-				$c->getShareManager()
219
-			);
220
-		});
221
-
222
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
223
-			$view = new View();
224
-			$util = new Encryption\Util(
225
-				$view,
226
-				$c->getUserManager(),
227
-				$c->getGroupManager(),
228
-				$c->getConfig()
229
-			);
230
-
231
-			return new Encryption\Keys\Storage($view, $util);
232
-		});
233
-		$this->registerService('TagMapper', function (Server $c) {
234
-			return new TagMapper($c->getDatabaseConnection());
235
-		});
236
-
237
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
-			$tagMapper = $c->query('TagMapper');
239
-			return new TagManager($tagMapper, $c->getUserSession());
240
-		});
241
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
242
-
243
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
244
-			$config = $c->getConfig();
245
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246
-			return new $factoryClass($this);
247
-		});
248
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
-			return $c->query('SystemTagManagerFactory')->getManager();
250
-		});
251
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252
-
253
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
255
-		});
256
-		$this->registerService('RootFolder', function (Server $c) {
257
-			$manager = \OC\Files\Filesystem::getMountManager(null);
258
-			$view = new View();
259
-			$root = new Root(
260
-				$manager,
261
-				$view,
262
-				null,
263
-				$c->getUserMountCache(),
264
-				$this->getLogger(),
265
-				$this->getUserManager()
266
-			);
267
-			$connector = new HookConnector($root, $view);
268
-			$connector->viewToNode();
269
-
270
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
271
-			$previewConnector->connectWatcher();
272
-
273
-			return $root;
274
-		});
275
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276
-
277
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
-			return new LazyRoot(function () use ($c) {
279
-				return $c->query('RootFolder');
280
-			});
281
-		});
282
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283
-
284
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
285
-			$config = $c->getConfig();
286
-			return new \OC\User\Manager($config);
287
-		});
288
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
289
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290
-
291
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
-			});
296
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
-			});
313
-			return $groupManager;
314
-		});
315
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
-
317
-		$this->registerService(Store::class, function (Server $c) {
318
-			$session = $c->getSession();
319
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
-			} else {
322
-				$tokenProvider = null;
323
-			}
324
-			$logger = $c->getLogger();
325
-			return new Store($session, $logger, $tokenProvider);
326
-		});
327
-		$this->registerAlias(IStore::class, Store::class);
328
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
-			$dbConnection = $c->getDatabaseConnection();
330
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
-		});
332
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
-			$crypto = $c->getCrypto();
335
-			$config = $c->getConfig();
336
-			$logger = $c->getLogger();
337
-			$timeFactory = new TimeFactory();
338
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
-		});
340
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
-
342
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
-			$manager = $c->getUserManager();
344
-			$session = new \OC\Session\Memory('');
345
-			$timeFactory = new TimeFactory();
346
-			// Token providers might require a working database. This code
347
-			// might however be called when ownCloud is not yet setup.
348
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
-			} else {
351
-				$defaultTokenProvider = null;
352
-			}
353
-
354
-			$dispatcher = $c->getEventDispatcher();
355
-
356
-			$userSession = new \OC\User\Session(
357
-				$manager,
358
-				$session,
359
-				$timeFactory,
360
-				$defaultTokenProvider,
361
-				$c->getConfig(),
362
-				$c->getSecureRandom(),
363
-				$c->getLockdownManager(),
364
-				$c->getLogger()
365
-			);
366
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
367
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368
-			});
369
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
370
-				/** @var $user \OC\User\User */
371
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377
-			});
378
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
379
-				/** @var $user \OC\User\User */
380
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381
-			});
382
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385
-			});
386
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
-			});
390
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
391
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392
-			});
393
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
394
-				/** @var $user \OC\User\User */
395
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396
-			});
397
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
-			});
401
-			$userSession->listen('\OC\User', 'logout', function () {
402
-				\OC_Hook::emit('OC_User', 'logout', array());
403
-			});
404
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
405
-				/** @var $user \OC\User\User */
406
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
408
-			});
409
-			return $userSession;
410
-		});
411
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
412
-
413
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
414
-			return new \OC\Authentication\TwoFactorAuth\Manager(
415
-				$c->getAppManager(),
416
-				$c->getSession(),
417
-				$c->getConfig(),
418
-				$c->getActivityManager(),
419
-				$c->getLogger(),
420
-				$c->query(\OC\Authentication\Token\IProvider::class),
421
-				$c->query(ITimeFactory::class),
422
-				$c->query(EventDispatcherInterface::class)
423
-			);
424
-		});
425
-
426
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428
-
429
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
430
-			return new \OC\AllConfig(
431
-				$c->getSystemConfig()
432
-			);
433
-		});
434
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
435
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436
-
437
-		$this->registerService('SystemConfig', function ($c) use ($config) {
438
-			return new \OC\SystemConfig($config);
439
-		});
440
-
441
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
442
-			return new \OC\AppConfig($c->getDatabaseConnection());
443
-		});
444
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
445
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446
-
447
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
448
-			return new \OC\L10N\Factory(
449
-				$c->getConfig(),
450
-				$c->getRequest(),
451
-				$c->getUserSession(),
452
-				\OC::$SERVERROOT
453
-			);
454
-		});
455
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456
-
457
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
458
-			$config = $c->getConfig();
459
-			$cacheFactory = $c->getMemCacheFactory();
460
-			$request = $c->getRequest();
461
-			return new \OC\URLGenerator(
462
-				$config,
463
-				$cacheFactory,
464
-				$request
465
-			);
466
-		});
467
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468
-
469
-		$this->registerService('AppHelper', function ($c) {
470
-			return new \OC\AppHelper();
471
-		});
472
-		$this->registerAlias('AppFetcher', AppFetcher::class);
473
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
-
475
-		$this->registerService(\OCP\ICache::class, function ($c) {
476
-			return new Cache\File();
477
-		});
478
-		$this->registerAlias('UserCache', \OCP\ICache::class);
479
-
480
-		$this->registerService(Factory::class, function (Server $c) {
481
-
482
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
-				'\\OC\\Memcache\\ArrayCache',
484
-				'\\OC\\Memcache\\ArrayCache',
485
-				'\\OC\\Memcache\\ArrayCache'
486
-			);
487
-			$config = $c->getConfig();
488
-			$request = $c->getRequest();
489
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
-
491
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
-				$v = \OC_App::getAppVersions();
493
-				$v['core'] = implode(',', \OC_Util::getVersion());
494
-				$version = implode(',', $v);
495
-				$instanceId = \OC_Util::getInstanceId();
496
-				$path = \OC::$SERVERROOT;
497
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
498
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
-					$config->getSystemValue('memcache.local', null),
500
-					$config->getSystemValue('memcache.distributed', null),
501
-					$config->getSystemValue('memcache.locking', null)
502
-				);
503
-			}
504
-			return $arrayCacheFactory;
505
-
506
-		});
507
-		$this->registerAlias('MemCacheFactory', Factory::class);
508
-		$this->registerAlias(ICacheFactory::class, Factory::class);
509
-
510
-		$this->registerService('RedisFactory', function (Server $c) {
511
-			$systemConfig = $c->getSystemConfig();
512
-			return new RedisFactory($systemConfig);
513
-		});
514
-
515
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
-			return new \OC\Activity\Manager(
517
-				$c->getRequest(),
518
-				$c->getUserSession(),
519
-				$c->getConfig(),
520
-				$c->query(IValidator::class)
521
-			);
522
-		});
523
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
-
525
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
-			return new \OC\Activity\EventMerger(
527
-				$c->getL10N('lib')
528
-			);
529
-		});
530
-		$this->registerAlias(IValidator::class, Validator::class);
531
-
532
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
-			return new AvatarManager(
534
-				$c->query(\OC\User\Manager::class),
535
-				$c->getAppDataDir('avatar'),
536
-				$c->getL10N('lib'),
537
-				$c->getLogger(),
538
-				$c->getConfig()
539
-			);
540
-		});
541
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
-
543
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
-
545
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
546
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
-			$logger = Log::getLogClass($logType);
548
-			call_user_func(array($logger, 'init'));
549
-			$config = $this->getSystemConfig();
550
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
551
-
552
-			return new Log($logger, $config, null, $registry);
553
-		});
554
-		$this->registerAlias('Logger', \OCP\ILogger::class);
555
-
556
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
557
-			$config = $c->getConfig();
558
-			return new \OC\BackgroundJob\JobList(
559
-				$c->getDatabaseConnection(),
560
-				$config,
561
-				new TimeFactory()
562
-			);
563
-		});
564
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565
-
566
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
567
-			$cacheFactory = $c->getMemCacheFactory();
568
-			$logger = $c->getLogger();
569
-			if ($cacheFactory->isAvailableLowLatency()) {
570
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
571
-			} else {
572
-				$router = new \OC\Route\Router($logger);
573
-			}
574
-			return $router;
575
-		});
576
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
577
-
578
-		$this->registerService(\OCP\ISearch::class, function ($c) {
579
-			return new Search();
580
-		});
581
-		$this->registerAlias('Search', \OCP\ISearch::class);
582
-
583
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
584
-			return new \OC\Security\RateLimiting\Limiter(
585
-				$this->getUserSession(),
586
-				$this->getRequest(),
587
-				new \OC\AppFramework\Utility\TimeFactory(),
588
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589
-			);
590
-		});
591
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
592
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
593
-				$this->getMemCacheFactory(),
594
-				new \OC\AppFramework\Utility\TimeFactory()
595
-			);
596
-		});
597
-
598
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
599
-			return new SecureRandom();
600
-		});
601
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602
-
603
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
604
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
605
-		});
606
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607
-
608
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
609
-			return new Hasher($c->getConfig());
610
-		});
611
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612
-
613
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
614
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615
-		});
616
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617
-
618
-		$this->registerService(IDBConnection::class, function (Server $c) {
619
-			$systemConfig = $c->getSystemConfig();
620
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
621
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
622
-			if (!$factory->isValidType($type)) {
623
-				throw new \OC\DatabaseException('Invalid database type');
624
-			}
625
-			$connectionParams = $factory->createConnectionParams();
626
-			$connection = $factory->getConnection($type, $connectionParams);
627
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
628
-			return $connection;
629
-		});
630
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
631
-
632
-		$this->registerService('HTTPHelper', function (Server $c) {
633
-			$config = $c->getConfig();
634
-			return new HTTPHelper(
635
-				$config,
636
-				$c->getHTTPClientService()
637
-			);
638
-		});
639
-
640
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
641
-			$user = \OC_User::getUser();
642
-			$uid = $user ? $user : null;
643
-			return new ClientService(
644
-				$c->getConfig(),
645
-				new \OC\Security\CertificateManager(
646
-					$uid,
647
-					new View(),
648
-					$c->getConfig(),
649
-					$c->getLogger(),
650
-					$c->getSecureRandom()
651
-				)
652
-			);
653
-		});
654
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
656
-			$eventLogger = new EventLogger();
657
-			if ($c->getSystemConfig()->getValue('debug', false)) {
658
-				// In debug mode, module is being activated by default
659
-				$eventLogger->activate();
660
-			}
661
-			return $eventLogger;
662
-		});
663
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664
-
665
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
666
-			$queryLogger = new QueryLogger();
667
-			if ($c->getSystemConfig()->getValue('debug', false)) {
668
-				// In debug mode, module is being activated by default
669
-				$queryLogger->activate();
670
-			}
671
-			return $queryLogger;
672
-		});
673
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674
-
675
-		$this->registerService(TempManager::class, function (Server $c) {
676
-			return new TempManager(
677
-				$c->getLogger(),
678
-				$c->getConfig()
679
-			);
680
-		});
681
-		$this->registerAlias('TempManager', TempManager::class);
682
-		$this->registerAlias(ITempManager::class, TempManager::class);
683
-
684
-		$this->registerService(AppManager::class, function (Server $c) {
685
-			return new \OC\App\AppManager(
686
-				$c->getUserSession(),
687
-				$c->query(\OC\AppConfig::class),
688
-				$c->getGroupManager(),
689
-				$c->getMemCacheFactory(),
690
-				$c->getEventDispatcher()
691
-			);
692
-		});
693
-		$this->registerAlias('AppManager', AppManager::class);
694
-		$this->registerAlias(IAppManager::class, AppManager::class);
695
-
696
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
697
-			return new DateTimeZone(
698
-				$c->getConfig(),
699
-				$c->getSession()
700
-			);
701
-		});
702
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703
-
704
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
705
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706
-
707
-			return new DateTimeFormatter(
708
-				$c->getDateTimeZone()->getTimeZone(),
709
-				$c->getL10N('lib', $language)
710
-			);
711
-		});
712
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713
-
714
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
715
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716
-			$listener = new UserMountCacheListener($mountCache);
717
-			$listener->listen($c->getUserManager());
718
-			return $mountCache;
719
-		});
720
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721
-
722
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
723
-			$loader = \OC\Files\Filesystem::getLoader();
724
-			$mountCache = $c->query('UserMountCache');
725
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
726
-
727
-			// builtin providers
728
-
729
-			$config = $c->getConfig();
730
-			$manager->registerProvider(new CacheMountProvider($config));
731
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
732
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
733
-
734
-			return $manager;
735
-		});
736
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737
-
738
-		$this->registerService('IniWrapper', function ($c) {
739
-			return new IniGetWrapper();
740
-		});
741
-		$this->registerService('AsyncCommandBus', function (Server $c) {
742
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
743
-			if ($busClass) {
744
-				list($app, $class) = explode('::', $busClass, 2);
745
-				if ($c->getAppManager()->isInstalled($app)) {
746
-					\OC_App::loadApp($app);
747
-					return $c->query($class);
748
-				} else {
749
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
750
-				}
751
-			} else {
752
-				$jobList = $c->getJobList();
753
-				return new CronBus($jobList);
754
-			}
755
-		});
756
-		$this->registerService('TrustedDomainHelper', function ($c) {
757
-			return new TrustedDomainHelper($this->getConfig());
758
-		});
759
-		$this->registerService('Throttler', function (Server $c) {
760
-			return new Throttler(
761
-				$c->getDatabaseConnection(),
762
-				new TimeFactory(),
763
-				$c->getLogger(),
764
-				$c->getConfig()
765
-			);
766
-		});
767
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
768
-			// IConfig and IAppManager requires a working database. This code
769
-			// might however be called when ownCloud is not yet setup.
770
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
771
-				$config = $c->getConfig();
772
-				$appManager = $c->getAppManager();
773
-			} else {
774
-				$config = null;
775
-				$appManager = null;
776
-			}
777
-
778
-			return new Checker(
779
-				new EnvironmentHelper(),
780
-				new FileAccessHelper(),
781
-				new AppLocator(),
782
-				$config,
783
-				$c->getMemCacheFactory(),
784
-				$appManager,
785
-				$c->getTempManager()
786
-			);
787
-		});
788
-		$this->registerService(\OCP\IRequest::class, function ($c) {
789
-			if (isset($this['urlParams'])) {
790
-				$urlParams = $this['urlParams'];
791
-			} else {
792
-				$urlParams = [];
793
-			}
794
-
795
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
796
-				&& in_array('fakeinput', stream_get_wrappers())
797
-			) {
798
-				$stream = 'fakeinput://data';
799
-			} else {
800
-				$stream = 'php://input';
801
-			}
802
-
803
-			return new Request(
804
-				[
805
-					'get' => $_GET,
806
-					'post' => $_POST,
807
-					'files' => $_FILES,
808
-					'server' => $_SERVER,
809
-					'env' => $_ENV,
810
-					'cookies' => $_COOKIE,
811
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
812
-						? $_SERVER['REQUEST_METHOD']
813
-						: null,
814
-					'urlParams' => $urlParams,
815
-				],
816
-				$this->getSecureRandom(),
817
-				$this->getConfig(),
818
-				$this->getCsrfTokenManager(),
819
-				$stream
820
-			);
821
-		});
822
-		$this->registerAlias('Request', \OCP\IRequest::class);
823
-
824
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
825
-			return new Mailer(
826
-				$c->getConfig(),
827
-				$c->getLogger(),
828
-				$c->query(Defaults::class),
829
-				$c->getURLGenerator(),
830
-				$c->getL10N('lib')
831
-			);
832
-		});
833
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834
-
835
-		$this->registerService('LDAPProvider', function (Server $c) {
836
-			$config = $c->getConfig();
837
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838
-			if (is_null($factoryClass)) {
839
-				throw new \Exception('ldapProviderFactory not set');
840
-			}
841
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
842
-			$factory = new $factoryClass($this);
843
-			return $factory->getLDAPProvider();
844
-		});
845
-		$this->registerService(ILockingProvider::class, function (Server $c) {
846
-			$ini = $c->getIniWrapper();
847
-			$config = $c->getConfig();
848
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
849
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
850
-				/** @var \OC\Memcache\Factory $memcacheFactory */
851
-				$memcacheFactory = $c->getMemCacheFactory();
852
-				$memcache = $memcacheFactory->createLocking('lock');
853
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
854
-					return new MemcacheLockingProvider($memcache, $ttl);
855
-				}
856
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
857
-			}
858
-			return new NoopLockingProvider();
859
-		});
860
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
861
-
862
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
-			return new \OC\Files\Mount\Manager();
864
-		});
865
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
-
867
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
-			return new \OC\Files\Type\Detection(
869
-				$c->getURLGenerator(),
870
-				\OC::$configDir,
871
-				\OC::$SERVERROOT . '/resources/config/'
872
-			);
873
-		});
874
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
-
876
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
-			return new \OC\Files\Type\Loader(
878
-				$c->getDatabaseConnection()
879
-			);
880
-		});
881
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
-		$this->registerService(BundleFetcher::class, function () {
883
-			return new BundleFetcher($this->getL10N('lib'));
884
-		});
885
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
-			return new Manager(
887
-				$c->query(IValidator::class)
888
-			);
889
-		});
890
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
-
892
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
894
-			$manager->registerCapability(function () use ($c) {
895
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
896
-			});
897
-			$manager->registerCapability(function () use ($c) {
898
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
-			});
900
-			return $manager;
901
-		});
902
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
-
904
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
-			$config = $c->getConfig();
906
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
-			$factory = new $factoryClass($this);
909
-			$manager = $factory->getManager();
910
-
911
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
-				$manager = $c->getUserManager();
913
-				$user = $manager->get($id);
914
-				if(is_null($user)) {
915
-					$l = $c->getL10N('core');
916
-					$displayName = $l->t('Unknown user');
917
-				} else {
918
-					$displayName = $user->getDisplayName();
919
-				}
920
-				return $displayName;
921
-			});
922
-
923
-			return $manager;
924
-		});
925
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
-
927
-		$this->registerService('ThemingDefaults', function (Server $c) {
928
-			/*
149
+    /** @var string */
150
+    private $webRoot;
151
+
152
+    /**
153
+     * @param string $webRoot
154
+     * @param \OC\Config $config
155
+     */
156
+    public function __construct($webRoot, \OC\Config $config) {
157
+        parent::__construct();
158
+        $this->webRoot = $webRoot;
159
+
160
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
161
+            return $c;
162
+        });
163
+
164
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
165
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
166
+
167
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
168
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
169
+
170
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
171
+
172
+
173
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
174
+            return new PreviewManager(
175
+                $c->getConfig(),
176
+                $c->getRootFolder(),
177
+                $c->getAppDataDir('preview'),
178
+                $c->getEventDispatcher(),
179
+                $c->getSession()->get('user_id')
180
+            );
181
+        });
182
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
183
+
184
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
185
+            return new \OC\Preview\Watcher(
186
+                $c->getAppDataDir('preview')
187
+            );
188
+        });
189
+
190
+        $this->registerService('EncryptionManager', function (Server $c) {
191
+            $view = new View();
192
+            $util = new Encryption\Util(
193
+                $view,
194
+                $c->getUserManager(),
195
+                $c->getGroupManager(),
196
+                $c->getConfig()
197
+            );
198
+            return new Encryption\Manager(
199
+                $c->getConfig(),
200
+                $c->getLogger(),
201
+                $c->getL10N('core'),
202
+                new View(),
203
+                $util,
204
+                new ArrayCache()
205
+            );
206
+        });
207
+
208
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
209
+            $util = new Encryption\Util(
210
+                new View(),
211
+                $c->getUserManager(),
212
+                $c->getGroupManager(),
213
+                $c->getConfig()
214
+            );
215
+            return new Encryption\File(
216
+                $util,
217
+                $c->getRootFolder(),
218
+                $c->getShareManager()
219
+            );
220
+        });
221
+
222
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
223
+            $view = new View();
224
+            $util = new Encryption\Util(
225
+                $view,
226
+                $c->getUserManager(),
227
+                $c->getGroupManager(),
228
+                $c->getConfig()
229
+            );
230
+
231
+            return new Encryption\Keys\Storage($view, $util);
232
+        });
233
+        $this->registerService('TagMapper', function (Server $c) {
234
+            return new TagMapper($c->getDatabaseConnection());
235
+        });
236
+
237
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
238
+            $tagMapper = $c->query('TagMapper');
239
+            return new TagManager($tagMapper, $c->getUserSession());
240
+        });
241
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
242
+
243
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
244
+            $config = $c->getConfig();
245
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
246
+            return new $factoryClass($this);
247
+        });
248
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
249
+            return $c->query('SystemTagManagerFactory')->getManager();
250
+        });
251
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
252
+
253
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
254
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
255
+        });
256
+        $this->registerService('RootFolder', function (Server $c) {
257
+            $manager = \OC\Files\Filesystem::getMountManager(null);
258
+            $view = new View();
259
+            $root = new Root(
260
+                $manager,
261
+                $view,
262
+                null,
263
+                $c->getUserMountCache(),
264
+                $this->getLogger(),
265
+                $this->getUserManager()
266
+            );
267
+            $connector = new HookConnector($root, $view);
268
+            $connector->viewToNode();
269
+
270
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
271
+            $previewConnector->connectWatcher();
272
+
273
+            return $root;
274
+        });
275
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
276
+
277
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
278
+            return new LazyRoot(function () use ($c) {
279
+                return $c->query('RootFolder');
280
+            });
281
+        });
282
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
283
+
284
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
285
+            $config = $c->getConfig();
286
+            return new \OC\User\Manager($config);
287
+        });
288
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
289
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
290
+
291
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
292
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
293
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
294
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
295
+            });
296
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
297
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
300
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
306
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
311
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
312
+            });
313
+            return $groupManager;
314
+        });
315
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
316
+
317
+        $this->registerService(Store::class, function (Server $c) {
318
+            $session = $c->getSession();
319
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
320
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
321
+            } else {
322
+                $tokenProvider = null;
323
+            }
324
+            $logger = $c->getLogger();
325
+            return new Store($session, $logger, $tokenProvider);
326
+        });
327
+        $this->registerAlias(IStore::class, Store::class);
328
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
329
+            $dbConnection = $c->getDatabaseConnection();
330
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
331
+        });
332
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
333
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
334
+            $crypto = $c->getCrypto();
335
+            $config = $c->getConfig();
336
+            $logger = $c->getLogger();
337
+            $timeFactory = new TimeFactory();
338
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
339
+        });
340
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
341
+
342
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
343
+            $manager = $c->getUserManager();
344
+            $session = new \OC\Session\Memory('');
345
+            $timeFactory = new TimeFactory();
346
+            // Token providers might require a working database. This code
347
+            // might however be called when ownCloud is not yet setup.
348
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
349
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
350
+            } else {
351
+                $defaultTokenProvider = null;
352
+            }
353
+
354
+            $dispatcher = $c->getEventDispatcher();
355
+
356
+            $userSession = new \OC\User\Session(
357
+                $manager,
358
+                $session,
359
+                $timeFactory,
360
+                $defaultTokenProvider,
361
+                $c->getConfig(),
362
+                $c->getSecureRandom(),
363
+                $c->getLockdownManager(),
364
+                $c->getLogger()
365
+            );
366
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
367
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
368
+            });
369
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
370
+                /** @var $user \OC\User\User */
371
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
376
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
377
+            });
378
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
379
+                /** @var $user \OC\User\User */
380
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
381
+            });
382
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
385
+            });
386
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
+            });
390
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
391
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
392
+            });
393
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
394
+                /** @var $user \OC\User\User */
395
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
396
+            });
397
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
+            });
401
+            $userSession->listen('\OC\User', 'logout', function () {
402
+                \OC_Hook::emit('OC_User', 'logout', array());
403
+            });
404
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
405
+                /** @var $user \OC\User\User */
406
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
407
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
408
+            });
409
+            return $userSession;
410
+        });
411
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
412
+
413
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
414
+            return new \OC\Authentication\TwoFactorAuth\Manager(
415
+                $c->getAppManager(),
416
+                $c->getSession(),
417
+                $c->getConfig(),
418
+                $c->getActivityManager(),
419
+                $c->getLogger(),
420
+                $c->query(\OC\Authentication\Token\IProvider::class),
421
+                $c->query(ITimeFactory::class),
422
+                $c->query(EventDispatcherInterface::class)
423
+            );
424
+        });
425
+
426
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
427
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
428
+
429
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
430
+            return new \OC\AllConfig(
431
+                $c->getSystemConfig()
432
+            );
433
+        });
434
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
435
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
436
+
437
+        $this->registerService('SystemConfig', function ($c) use ($config) {
438
+            return new \OC\SystemConfig($config);
439
+        });
440
+
441
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
442
+            return new \OC\AppConfig($c->getDatabaseConnection());
443
+        });
444
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
445
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
446
+
447
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
448
+            return new \OC\L10N\Factory(
449
+                $c->getConfig(),
450
+                $c->getRequest(),
451
+                $c->getUserSession(),
452
+                \OC::$SERVERROOT
453
+            );
454
+        });
455
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
456
+
457
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
458
+            $config = $c->getConfig();
459
+            $cacheFactory = $c->getMemCacheFactory();
460
+            $request = $c->getRequest();
461
+            return new \OC\URLGenerator(
462
+                $config,
463
+                $cacheFactory,
464
+                $request
465
+            );
466
+        });
467
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
468
+
469
+        $this->registerService('AppHelper', function ($c) {
470
+            return new \OC\AppHelper();
471
+        });
472
+        $this->registerAlias('AppFetcher', AppFetcher::class);
473
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
+
475
+        $this->registerService(\OCP\ICache::class, function ($c) {
476
+            return new Cache\File();
477
+        });
478
+        $this->registerAlias('UserCache', \OCP\ICache::class);
479
+
480
+        $this->registerService(Factory::class, function (Server $c) {
481
+
482
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
+                '\\OC\\Memcache\\ArrayCache',
484
+                '\\OC\\Memcache\\ArrayCache',
485
+                '\\OC\\Memcache\\ArrayCache'
486
+            );
487
+            $config = $c->getConfig();
488
+            $request = $c->getRequest();
489
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
+
491
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
+                $v = \OC_App::getAppVersions();
493
+                $v['core'] = implode(',', \OC_Util::getVersion());
494
+                $version = implode(',', $v);
495
+                $instanceId = \OC_Util::getInstanceId();
496
+                $path = \OC::$SERVERROOT;
497
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
498
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
+                    $config->getSystemValue('memcache.local', null),
500
+                    $config->getSystemValue('memcache.distributed', null),
501
+                    $config->getSystemValue('memcache.locking', null)
502
+                );
503
+            }
504
+            return $arrayCacheFactory;
505
+
506
+        });
507
+        $this->registerAlias('MemCacheFactory', Factory::class);
508
+        $this->registerAlias(ICacheFactory::class, Factory::class);
509
+
510
+        $this->registerService('RedisFactory', function (Server $c) {
511
+            $systemConfig = $c->getSystemConfig();
512
+            return new RedisFactory($systemConfig);
513
+        });
514
+
515
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
+            return new \OC\Activity\Manager(
517
+                $c->getRequest(),
518
+                $c->getUserSession(),
519
+                $c->getConfig(),
520
+                $c->query(IValidator::class)
521
+            );
522
+        });
523
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
+
525
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
+            return new \OC\Activity\EventMerger(
527
+                $c->getL10N('lib')
528
+            );
529
+        });
530
+        $this->registerAlias(IValidator::class, Validator::class);
531
+
532
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
+            return new AvatarManager(
534
+                $c->query(\OC\User\Manager::class),
535
+                $c->getAppDataDir('avatar'),
536
+                $c->getL10N('lib'),
537
+                $c->getLogger(),
538
+                $c->getConfig()
539
+            );
540
+        });
541
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
+
543
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
+
545
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
546
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
+            $logger = Log::getLogClass($logType);
548
+            call_user_func(array($logger, 'init'));
549
+            $config = $this->getSystemConfig();
550
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
551
+
552
+            return new Log($logger, $config, null, $registry);
553
+        });
554
+        $this->registerAlias('Logger', \OCP\ILogger::class);
555
+
556
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
557
+            $config = $c->getConfig();
558
+            return new \OC\BackgroundJob\JobList(
559
+                $c->getDatabaseConnection(),
560
+                $config,
561
+                new TimeFactory()
562
+            );
563
+        });
564
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
565
+
566
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
567
+            $cacheFactory = $c->getMemCacheFactory();
568
+            $logger = $c->getLogger();
569
+            if ($cacheFactory->isAvailableLowLatency()) {
570
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
571
+            } else {
572
+                $router = new \OC\Route\Router($logger);
573
+            }
574
+            return $router;
575
+        });
576
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
577
+
578
+        $this->registerService(\OCP\ISearch::class, function ($c) {
579
+            return new Search();
580
+        });
581
+        $this->registerAlias('Search', \OCP\ISearch::class);
582
+
583
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
584
+            return new \OC\Security\RateLimiting\Limiter(
585
+                $this->getUserSession(),
586
+                $this->getRequest(),
587
+                new \OC\AppFramework\Utility\TimeFactory(),
588
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
589
+            );
590
+        });
591
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
592
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
593
+                $this->getMemCacheFactory(),
594
+                new \OC\AppFramework\Utility\TimeFactory()
595
+            );
596
+        });
597
+
598
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
599
+            return new SecureRandom();
600
+        });
601
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
602
+
603
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
604
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
605
+        });
606
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
607
+
608
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
609
+            return new Hasher($c->getConfig());
610
+        });
611
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
612
+
613
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
614
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
615
+        });
616
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
617
+
618
+        $this->registerService(IDBConnection::class, function (Server $c) {
619
+            $systemConfig = $c->getSystemConfig();
620
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
621
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
622
+            if (!$factory->isValidType($type)) {
623
+                throw new \OC\DatabaseException('Invalid database type');
624
+            }
625
+            $connectionParams = $factory->createConnectionParams();
626
+            $connection = $factory->getConnection($type, $connectionParams);
627
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
628
+            return $connection;
629
+        });
630
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
631
+
632
+        $this->registerService('HTTPHelper', function (Server $c) {
633
+            $config = $c->getConfig();
634
+            return new HTTPHelper(
635
+                $config,
636
+                $c->getHTTPClientService()
637
+            );
638
+        });
639
+
640
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
641
+            $user = \OC_User::getUser();
642
+            $uid = $user ? $user : null;
643
+            return new ClientService(
644
+                $c->getConfig(),
645
+                new \OC\Security\CertificateManager(
646
+                    $uid,
647
+                    new View(),
648
+                    $c->getConfig(),
649
+                    $c->getLogger(),
650
+                    $c->getSecureRandom()
651
+                )
652
+            );
653
+        });
654
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
655
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
656
+            $eventLogger = new EventLogger();
657
+            if ($c->getSystemConfig()->getValue('debug', false)) {
658
+                // In debug mode, module is being activated by default
659
+                $eventLogger->activate();
660
+            }
661
+            return $eventLogger;
662
+        });
663
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
664
+
665
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
666
+            $queryLogger = new QueryLogger();
667
+            if ($c->getSystemConfig()->getValue('debug', false)) {
668
+                // In debug mode, module is being activated by default
669
+                $queryLogger->activate();
670
+            }
671
+            return $queryLogger;
672
+        });
673
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
674
+
675
+        $this->registerService(TempManager::class, function (Server $c) {
676
+            return new TempManager(
677
+                $c->getLogger(),
678
+                $c->getConfig()
679
+            );
680
+        });
681
+        $this->registerAlias('TempManager', TempManager::class);
682
+        $this->registerAlias(ITempManager::class, TempManager::class);
683
+
684
+        $this->registerService(AppManager::class, function (Server $c) {
685
+            return new \OC\App\AppManager(
686
+                $c->getUserSession(),
687
+                $c->query(\OC\AppConfig::class),
688
+                $c->getGroupManager(),
689
+                $c->getMemCacheFactory(),
690
+                $c->getEventDispatcher()
691
+            );
692
+        });
693
+        $this->registerAlias('AppManager', AppManager::class);
694
+        $this->registerAlias(IAppManager::class, AppManager::class);
695
+
696
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
697
+            return new DateTimeZone(
698
+                $c->getConfig(),
699
+                $c->getSession()
700
+            );
701
+        });
702
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
703
+
704
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
705
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
706
+
707
+            return new DateTimeFormatter(
708
+                $c->getDateTimeZone()->getTimeZone(),
709
+                $c->getL10N('lib', $language)
710
+            );
711
+        });
712
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
713
+
714
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
715
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
716
+            $listener = new UserMountCacheListener($mountCache);
717
+            $listener->listen($c->getUserManager());
718
+            return $mountCache;
719
+        });
720
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
721
+
722
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
723
+            $loader = \OC\Files\Filesystem::getLoader();
724
+            $mountCache = $c->query('UserMountCache');
725
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
726
+
727
+            // builtin providers
728
+
729
+            $config = $c->getConfig();
730
+            $manager->registerProvider(new CacheMountProvider($config));
731
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
732
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
733
+
734
+            return $manager;
735
+        });
736
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
737
+
738
+        $this->registerService('IniWrapper', function ($c) {
739
+            return new IniGetWrapper();
740
+        });
741
+        $this->registerService('AsyncCommandBus', function (Server $c) {
742
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
743
+            if ($busClass) {
744
+                list($app, $class) = explode('::', $busClass, 2);
745
+                if ($c->getAppManager()->isInstalled($app)) {
746
+                    \OC_App::loadApp($app);
747
+                    return $c->query($class);
748
+                } else {
749
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
750
+                }
751
+            } else {
752
+                $jobList = $c->getJobList();
753
+                return new CronBus($jobList);
754
+            }
755
+        });
756
+        $this->registerService('TrustedDomainHelper', function ($c) {
757
+            return new TrustedDomainHelper($this->getConfig());
758
+        });
759
+        $this->registerService('Throttler', function (Server $c) {
760
+            return new Throttler(
761
+                $c->getDatabaseConnection(),
762
+                new TimeFactory(),
763
+                $c->getLogger(),
764
+                $c->getConfig()
765
+            );
766
+        });
767
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
768
+            // IConfig and IAppManager requires a working database. This code
769
+            // might however be called when ownCloud is not yet setup.
770
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
771
+                $config = $c->getConfig();
772
+                $appManager = $c->getAppManager();
773
+            } else {
774
+                $config = null;
775
+                $appManager = null;
776
+            }
777
+
778
+            return new Checker(
779
+                new EnvironmentHelper(),
780
+                new FileAccessHelper(),
781
+                new AppLocator(),
782
+                $config,
783
+                $c->getMemCacheFactory(),
784
+                $appManager,
785
+                $c->getTempManager()
786
+            );
787
+        });
788
+        $this->registerService(\OCP\IRequest::class, function ($c) {
789
+            if (isset($this['urlParams'])) {
790
+                $urlParams = $this['urlParams'];
791
+            } else {
792
+                $urlParams = [];
793
+            }
794
+
795
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
796
+                && in_array('fakeinput', stream_get_wrappers())
797
+            ) {
798
+                $stream = 'fakeinput://data';
799
+            } else {
800
+                $stream = 'php://input';
801
+            }
802
+
803
+            return new Request(
804
+                [
805
+                    'get' => $_GET,
806
+                    'post' => $_POST,
807
+                    'files' => $_FILES,
808
+                    'server' => $_SERVER,
809
+                    'env' => $_ENV,
810
+                    'cookies' => $_COOKIE,
811
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
812
+                        ? $_SERVER['REQUEST_METHOD']
813
+                        : null,
814
+                    'urlParams' => $urlParams,
815
+                ],
816
+                $this->getSecureRandom(),
817
+                $this->getConfig(),
818
+                $this->getCsrfTokenManager(),
819
+                $stream
820
+            );
821
+        });
822
+        $this->registerAlias('Request', \OCP\IRequest::class);
823
+
824
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
825
+            return new Mailer(
826
+                $c->getConfig(),
827
+                $c->getLogger(),
828
+                $c->query(Defaults::class),
829
+                $c->getURLGenerator(),
830
+                $c->getL10N('lib')
831
+            );
832
+        });
833
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
834
+
835
+        $this->registerService('LDAPProvider', function (Server $c) {
836
+            $config = $c->getConfig();
837
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
838
+            if (is_null($factoryClass)) {
839
+                throw new \Exception('ldapProviderFactory not set');
840
+            }
841
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
842
+            $factory = new $factoryClass($this);
843
+            return $factory->getLDAPProvider();
844
+        });
845
+        $this->registerService(ILockingProvider::class, function (Server $c) {
846
+            $ini = $c->getIniWrapper();
847
+            $config = $c->getConfig();
848
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
849
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
850
+                /** @var \OC\Memcache\Factory $memcacheFactory */
851
+                $memcacheFactory = $c->getMemCacheFactory();
852
+                $memcache = $memcacheFactory->createLocking('lock');
853
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
854
+                    return new MemcacheLockingProvider($memcache, $ttl);
855
+                }
856
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
857
+            }
858
+            return new NoopLockingProvider();
859
+        });
860
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
861
+
862
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
863
+            return new \OC\Files\Mount\Manager();
864
+        });
865
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
866
+
867
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
868
+            return new \OC\Files\Type\Detection(
869
+                $c->getURLGenerator(),
870
+                \OC::$configDir,
871
+                \OC::$SERVERROOT . '/resources/config/'
872
+            );
873
+        });
874
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
875
+
876
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
877
+            return new \OC\Files\Type\Loader(
878
+                $c->getDatabaseConnection()
879
+            );
880
+        });
881
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
882
+        $this->registerService(BundleFetcher::class, function () {
883
+            return new BundleFetcher($this->getL10N('lib'));
884
+        });
885
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
886
+            return new Manager(
887
+                $c->query(IValidator::class)
888
+            );
889
+        });
890
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
891
+
892
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
893
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
894
+            $manager->registerCapability(function () use ($c) {
895
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
896
+            });
897
+            $manager->registerCapability(function () use ($c) {
898
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
899
+            });
900
+            return $manager;
901
+        });
902
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
903
+
904
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
905
+            $config = $c->getConfig();
906
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
907
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
908
+            $factory = new $factoryClass($this);
909
+            $manager = $factory->getManager();
910
+
911
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
912
+                $manager = $c->getUserManager();
913
+                $user = $manager->get($id);
914
+                if(is_null($user)) {
915
+                    $l = $c->getL10N('core');
916
+                    $displayName = $l->t('Unknown user');
917
+                } else {
918
+                    $displayName = $user->getDisplayName();
919
+                }
920
+                return $displayName;
921
+            });
922
+
923
+            return $manager;
924
+        });
925
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
926
+
927
+        $this->registerService('ThemingDefaults', function (Server $c) {
928
+            /*
929 929
 			 * Dark magic for autoloader.
930 930
 			 * If we do a class_exists it will try to load the class which will
931 931
 			 * make composer cache the result. Resulting in errors when enabling
932 932
 			 * the theming app.
933 933
 			 */
934
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
-			if (isset($prefixes['OCA\\Theming\\'])) {
936
-				$classExists = true;
937
-			} else {
938
-				$classExists = false;
939
-			}
940
-
941
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
-				return new ThemingDefaults(
943
-					$c->getConfig(),
944
-					$c->getL10N('theming'),
945
-					$c->getURLGenerator(),
946
-					$c->getAppDataDir('theming'),
947
-					$c->getMemCacheFactory(),
948
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
-					$this->getAppManager()
950
-				);
951
-			}
952
-			return new \OC_Defaults();
953
-		});
954
-		$this->registerService(SCSSCacher::class, function (Server $c) {
955
-			/** @var Factory $cacheFactory */
956
-			$cacheFactory = $c->query(Factory::class);
957
-			return new SCSSCacher(
958
-				$c->getLogger(),
959
-				$c->query(\OC\Files\AppData\Factory::class),
960
-				$c->getURLGenerator(),
961
-				$c->getConfig(),
962
-				$c->getThemingDefaults(),
963
-				\OC::$SERVERROOT,
964
-				$cacheFactory->createDistributed('SCSS')
965
-			);
966
-		});
967
-		$this->registerService(EventDispatcher::class, function () {
968
-			return new EventDispatcher();
969
-		});
970
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
971
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972
-
973
-		$this->registerService('CryptoWrapper', function (Server $c) {
974
-			// FIXME: Instantiiated here due to cyclic dependency
975
-			$request = new Request(
976
-				[
977
-					'get' => $_GET,
978
-					'post' => $_POST,
979
-					'files' => $_FILES,
980
-					'server' => $_SERVER,
981
-					'env' => $_ENV,
982
-					'cookies' => $_COOKIE,
983
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
984
-						? $_SERVER['REQUEST_METHOD']
985
-						: null,
986
-				],
987
-				$c->getSecureRandom(),
988
-				$c->getConfig()
989
-			);
990
-
991
-			return new CryptoWrapper(
992
-				$c->getConfig(),
993
-				$c->getCrypto(),
994
-				$c->getSecureRandom(),
995
-				$request
996
-			);
997
-		});
998
-		$this->registerService('CsrfTokenManager', function (Server $c) {
999
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000
-
1001
-			return new CsrfTokenManager(
1002
-				$tokenGenerator,
1003
-				$c->query(SessionStorage::class)
1004
-			);
1005
-		});
1006
-		$this->registerService(SessionStorage::class, function (Server $c) {
1007
-			return new SessionStorage($c->getSession());
1008
-		});
1009
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1010
-			return new ContentSecurityPolicyManager();
1011
-		});
1012
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013
-
1014
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1015
-			return new ContentSecurityPolicyNonceManager(
1016
-				$c->getCsrfTokenManager(),
1017
-				$c->getRequest()
1018
-			);
1019
-		});
1020
-
1021
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1022
-			$config = $c->getConfig();
1023
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024
-			/** @var \OCP\Share\IProviderFactory $factory */
1025
-			$factory = new $factoryClass($this);
1026
-
1027
-			$manager = new \OC\Share20\Manager(
1028
-				$c->getLogger(),
1029
-				$c->getConfig(),
1030
-				$c->getSecureRandom(),
1031
-				$c->getHasher(),
1032
-				$c->getMountManager(),
1033
-				$c->getGroupManager(),
1034
-				$c->getL10N('lib'),
1035
-				$c->getL10NFactory(),
1036
-				$factory,
1037
-				$c->getUserManager(),
1038
-				$c->getLazyRootFolder(),
1039
-				$c->getEventDispatcher(),
1040
-				$c->getMailer(),
1041
-				$c->getURLGenerator(),
1042
-				$c->getThemingDefaults()
1043
-			);
1044
-
1045
-			return $manager;
1046
-		});
1047
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1048
-
1049
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1050
-			$instance = new Collaboration\Collaborators\Search($c);
1051
-
1052
-			// register default plugins
1053
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1054
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1055
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1056
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1057
-
1058
-			return $instance;
1059
-		});
1060
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1061
-
1062
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063
-
1064
-		$this->registerService('SettingsManager', function (Server $c) {
1065
-			$manager = new \OC\Settings\Manager(
1066
-				$c->getLogger(),
1067
-				$c->getDatabaseConnection(),
1068
-				$c->getL10N('lib'),
1069
-				$c->getConfig(),
1070
-				$c->getEncryptionManager(),
1071
-				$c->getUserManager(),
1072
-				$c->getLockingProvider(),
1073
-				$c->getRequest(),
1074
-				$c->getURLGenerator(),
1075
-				$c->query(AccountManager::class),
1076
-				$c->getGroupManager(),
1077
-				$c->getL10NFactory(),
1078
-				$c->getAppManager()
1079
-			);
1080
-			return $manager;
1081
-		});
1082
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1083
-			return new \OC\Files\AppData\Factory(
1084
-				$c->getRootFolder(),
1085
-				$c->getSystemConfig()
1086
-			);
1087
-		});
1088
-
1089
-		$this->registerService('LockdownManager', function (Server $c) {
1090
-			return new LockdownManager(function () use ($c) {
1091
-				return $c->getSession();
1092
-			});
1093
-		});
1094
-
1095
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1096
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1097
-		});
1098
-
1099
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1100
-			return new CloudIdManager();
1101
-		});
1102
-
1103
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1104
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1105
-
1106
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1107
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1108
-
1109
-		$this->registerService(Defaults::class, function (Server $c) {
1110
-			return new Defaults(
1111
-				$c->getThemingDefaults()
1112
-			);
1113
-		});
1114
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1115
-
1116
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1117
-			return $c->query(\OCP\IUserSession::class)->getSession();
1118
-		});
1119
-
1120
-		$this->registerService(IShareHelper::class, function (Server $c) {
1121
-			return new ShareHelper(
1122
-				$c->query(\OCP\Share\IManager::class)
1123
-			);
1124
-		});
1125
-
1126
-		$this->registerService(Installer::class, function(Server $c) {
1127
-			return new Installer(
1128
-				$c->getAppFetcher(),
1129
-				$c->getHTTPClientService(),
1130
-				$c->getTempManager(),
1131
-				$c->getLogger(),
1132
-				$c->getConfig()
1133
-			);
1134
-		});
1135
-
1136
-		$this->registerService(IApiFactory::class, function(Server $c) {
1137
-			return new ApiFactory($c->getHTTPClientService());
1138
-		});
1139
-
1140
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1141
-			$memcacheFactory = $c->getMemCacheFactory();
1142
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1143
-		});
1144
-
1145
-		$this->registerService(IContactsStore::class, function(Server $c) {
1146
-			return new ContactsStore(
1147
-				$c->getContactsManager(),
1148
-				$c->getConfig(),
1149
-				$c->getUserManager(),
1150
-				$c->getGroupManager()
1151
-			);
1152
-		});
1153
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1154
-
1155
-		$this->connectDispatcher();
1156
-	}
1157
-
1158
-	/**
1159
-	 * @return \OCP\Calendar\IManager
1160
-	 */
1161
-	public function getCalendarManager() {
1162
-		return $this->query('CalendarManager');
1163
-	}
1164
-
1165
-	private function connectDispatcher() {
1166
-		$dispatcher = $this->getEventDispatcher();
1167
-
1168
-		// Delete avatar on user deletion
1169
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1170
-			$logger = $this->getLogger();
1171
-			$manager = $this->getAvatarManager();
1172
-			/** @var IUser $user */
1173
-			$user = $e->getSubject();
1174
-
1175
-			try {
1176
-				$avatar = $manager->getAvatar($user->getUID());
1177
-				$avatar->remove();
1178
-			} catch (NotFoundException $e) {
1179
-				// no avatar to remove
1180
-			} catch (\Exception $e) {
1181
-				// Ignore exceptions
1182
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1183
-			}
1184
-		});
1185
-
1186
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1187
-			$manager = $this->getAvatarManager();
1188
-			/** @var IUser $user */
1189
-			$user = $e->getSubject();
1190
-			$feature = $e->getArgument('feature');
1191
-			$oldValue = $e->getArgument('oldValue');
1192
-			$value = $e->getArgument('value');
1193
-
1194
-			try {
1195
-				$avatar = $manager->getAvatar($user->getUID());
1196
-				$avatar->userChanged($feature, $oldValue, $value);
1197
-			} catch (NotFoundException $e) {
1198
-				// no avatar to remove
1199
-			}
1200
-		});
1201
-	}
1202
-
1203
-	/**
1204
-	 * @return \OCP\Contacts\IManager
1205
-	 */
1206
-	public function getContactsManager() {
1207
-		return $this->query('ContactsManager');
1208
-	}
1209
-
1210
-	/**
1211
-	 * @return \OC\Encryption\Manager
1212
-	 */
1213
-	public function getEncryptionManager() {
1214
-		return $this->query('EncryptionManager');
1215
-	}
1216
-
1217
-	/**
1218
-	 * @return \OC\Encryption\File
1219
-	 */
1220
-	public function getEncryptionFilesHelper() {
1221
-		return $this->query('EncryptionFileHelper');
1222
-	}
1223
-
1224
-	/**
1225
-	 * @return \OCP\Encryption\Keys\IStorage
1226
-	 */
1227
-	public function getEncryptionKeyStorage() {
1228
-		return $this->query('EncryptionKeyStorage');
1229
-	}
1230
-
1231
-	/**
1232
-	 * The current request object holding all information about the request
1233
-	 * currently being processed is returned from this method.
1234
-	 * In case the current execution was not initiated by a web request null is returned
1235
-	 *
1236
-	 * @return \OCP\IRequest
1237
-	 */
1238
-	public function getRequest() {
1239
-		return $this->query('Request');
1240
-	}
1241
-
1242
-	/**
1243
-	 * Returns the preview manager which can create preview images for a given file
1244
-	 *
1245
-	 * @return \OCP\IPreview
1246
-	 */
1247
-	public function getPreviewManager() {
1248
-		return $this->query('PreviewManager');
1249
-	}
1250
-
1251
-	/**
1252
-	 * Returns the tag manager which can get and set tags for different object types
1253
-	 *
1254
-	 * @see \OCP\ITagManager::load()
1255
-	 * @return \OCP\ITagManager
1256
-	 */
1257
-	public function getTagManager() {
1258
-		return $this->query('TagManager');
1259
-	}
1260
-
1261
-	/**
1262
-	 * Returns the system-tag manager
1263
-	 *
1264
-	 * @return \OCP\SystemTag\ISystemTagManager
1265
-	 *
1266
-	 * @since 9.0.0
1267
-	 */
1268
-	public function getSystemTagManager() {
1269
-		return $this->query('SystemTagManager');
1270
-	}
1271
-
1272
-	/**
1273
-	 * Returns the system-tag object mapper
1274
-	 *
1275
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1276
-	 *
1277
-	 * @since 9.0.0
1278
-	 */
1279
-	public function getSystemTagObjectMapper() {
1280
-		return $this->query('SystemTagObjectMapper');
1281
-	}
1282
-
1283
-	/**
1284
-	 * Returns the avatar manager, used for avatar functionality
1285
-	 *
1286
-	 * @return \OCP\IAvatarManager
1287
-	 */
1288
-	public function getAvatarManager() {
1289
-		return $this->query('AvatarManager');
1290
-	}
1291
-
1292
-	/**
1293
-	 * Returns the root folder of ownCloud's data directory
1294
-	 *
1295
-	 * @return \OCP\Files\IRootFolder
1296
-	 */
1297
-	public function getRootFolder() {
1298
-		return $this->query('LazyRootFolder');
1299
-	}
1300
-
1301
-	/**
1302
-	 * Returns the root folder of ownCloud's data directory
1303
-	 * This is the lazy variant so this gets only initialized once it
1304
-	 * is actually used.
1305
-	 *
1306
-	 * @return \OCP\Files\IRootFolder
1307
-	 */
1308
-	public function getLazyRootFolder() {
1309
-		return $this->query('LazyRootFolder');
1310
-	}
1311
-
1312
-	/**
1313
-	 * Returns a view to ownCloud's files folder
1314
-	 *
1315
-	 * @param string $userId user ID
1316
-	 * @return \OCP\Files\Folder|null
1317
-	 */
1318
-	public function getUserFolder($userId = null) {
1319
-		if ($userId === null) {
1320
-			$user = $this->getUserSession()->getUser();
1321
-			if (!$user) {
1322
-				return null;
1323
-			}
1324
-			$userId = $user->getUID();
1325
-		}
1326
-		$root = $this->getRootFolder();
1327
-		return $root->getUserFolder($userId);
1328
-	}
1329
-
1330
-	/**
1331
-	 * Returns an app-specific view in ownClouds data directory
1332
-	 *
1333
-	 * @return \OCP\Files\Folder
1334
-	 * @deprecated since 9.2.0 use IAppData
1335
-	 */
1336
-	public function getAppFolder() {
1337
-		$dir = '/' . \OC_App::getCurrentApp();
1338
-		$root = $this->getRootFolder();
1339
-		if (!$root->nodeExists($dir)) {
1340
-			$folder = $root->newFolder($dir);
1341
-		} else {
1342
-			$folder = $root->get($dir);
1343
-		}
1344
-		return $folder;
1345
-	}
1346
-
1347
-	/**
1348
-	 * @return \OC\User\Manager
1349
-	 */
1350
-	public function getUserManager() {
1351
-		return $this->query('UserManager');
1352
-	}
1353
-
1354
-	/**
1355
-	 * @return \OC\Group\Manager
1356
-	 */
1357
-	public function getGroupManager() {
1358
-		return $this->query('GroupManager');
1359
-	}
1360
-
1361
-	/**
1362
-	 * @return \OC\User\Session
1363
-	 */
1364
-	public function getUserSession() {
1365
-		return $this->query('UserSession');
1366
-	}
1367
-
1368
-	/**
1369
-	 * @return \OCP\ISession
1370
-	 */
1371
-	public function getSession() {
1372
-		return $this->query('UserSession')->getSession();
1373
-	}
1374
-
1375
-	/**
1376
-	 * @param \OCP\ISession $session
1377
-	 */
1378
-	public function setSession(\OCP\ISession $session) {
1379
-		$this->query(SessionStorage::class)->setSession($session);
1380
-		$this->query('UserSession')->setSession($session);
1381
-		$this->query(Store::class)->setSession($session);
1382
-	}
1383
-
1384
-	/**
1385
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1386
-	 */
1387
-	public function getTwoFactorAuthManager() {
1388
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1389
-	}
1390
-
1391
-	/**
1392
-	 * @return \OC\NavigationManager
1393
-	 */
1394
-	public function getNavigationManager() {
1395
-		return $this->query('NavigationManager');
1396
-	}
1397
-
1398
-	/**
1399
-	 * @return \OCP\IConfig
1400
-	 */
1401
-	public function getConfig() {
1402
-		return $this->query('AllConfig');
1403
-	}
1404
-
1405
-	/**
1406
-	 * @return \OC\SystemConfig
1407
-	 */
1408
-	public function getSystemConfig() {
1409
-		return $this->query('SystemConfig');
1410
-	}
1411
-
1412
-	/**
1413
-	 * Returns the app config manager
1414
-	 *
1415
-	 * @return \OCP\IAppConfig
1416
-	 */
1417
-	public function getAppConfig() {
1418
-		return $this->query('AppConfig');
1419
-	}
1420
-
1421
-	/**
1422
-	 * @return \OCP\L10N\IFactory
1423
-	 */
1424
-	public function getL10NFactory() {
1425
-		return $this->query('L10NFactory');
1426
-	}
1427
-
1428
-	/**
1429
-	 * get an L10N instance
1430
-	 *
1431
-	 * @param string $app appid
1432
-	 * @param string $lang
1433
-	 * @return IL10N
1434
-	 */
1435
-	public function getL10N($app, $lang = null) {
1436
-		return $this->getL10NFactory()->get($app, $lang);
1437
-	}
1438
-
1439
-	/**
1440
-	 * @return \OCP\IURLGenerator
1441
-	 */
1442
-	public function getURLGenerator() {
1443
-		return $this->query('URLGenerator');
1444
-	}
1445
-
1446
-	/**
1447
-	 * @return \OCP\IHelper
1448
-	 */
1449
-	public function getHelper() {
1450
-		return $this->query('AppHelper');
1451
-	}
1452
-
1453
-	/**
1454
-	 * @return AppFetcher
1455
-	 */
1456
-	public function getAppFetcher() {
1457
-		return $this->query(AppFetcher::class);
1458
-	}
1459
-
1460
-	/**
1461
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1462
-	 * getMemCacheFactory() instead.
1463
-	 *
1464
-	 * @return \OCP\ICache
1465
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1466
-	 */
1467
-	public function getCache() {
1468
-		return $this->query('UserCache');
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns an \OCP\CacheFactory instance
1473
-	 *
1474
-	 * @return \OCP\ICacheFactory
1475
-	 */
1476
-	public function getMemCacheFactory() {
1477
-		return $this->query('MemCacheFactory');
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns an \OC\RedisFactory instance
1482
-	 *
1483
-	 * @return \OC\RedisFactory
1484
-	 */
1485
-	public function getGetRedisFactory() {
1486
-		return $this->query('RedisFactory');
1487
-	}
1488
-
1489
-
1490
-	/**
1491
-	 * Returns the current session
1492
-	 *
1493
-	 * @return \OCP\IDBConnection
1494
-	 */
1495
-	public function getDatabaseConnection() {
1496
-		return $this->query('DatabaseConnection');
1497
-	}
1498
-
1499
-	/**
1500
-	 * Returns the activity manager
1501
-	 *
1502
-	 * @return \OCP\Activity\IManager
1503
-	 */
1504
-	public function getActivityManager() {
1505
-		return $this->query('ActivityManager');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns an job list for controlling background jobs
1510
-	 *
1511
-	 * @return \OCP\BackgroundJob\IJobList
1512
-	 */
1513
-	public function getJobList() {
1514
-		return $this->query('JobList');
1515
-	}
1516
-
1517
-	/**
1518
-	 * Returns a logger instance
1519
-	 *
1520
-	 * @return \OCP\ILogger
1521
-	 */
1522
-	public function getLogger() {
1523
-		return $this->query('Logger');
1524
-	}
1525
-
1526
-	/**
1527
-	 * Returns a router for generating and matching urls
1528
-	 *
1529
-	 * @return \OCP\Route\IRouter
1530
-	 */
1531
-	public function getRouter() {
1532
-		return $this->query('Router');
1533
-	}
1534
-
1535
-	/**
1536
-	 * Returns a search instance
1537
-	 *
1538
-	 * @return \OCP\ISearch
1539
-	 */
1540
-	public function getSearch() {
1541
-		return $this->query('Search');
1542
-	}
1543
-
1544
-	/**
1545
-	 * Returns a SecureRandom instance
1546
-	 *
1547
-	 * @return \OCP\Security\ISecureRandom
1548
-	 */
1549
-	public function getSecureRandom() {
1550
-		return $this->query('SecureRandom');
1551
-	}
1552
-
1553
-	/**
1554
-	 * Returns a Crypto instance
1555
-	 *
1556
-	 * @return \OCP\Security\ICrypto
1557
-	 */
1558
-	public function getCrypto() {
1559
-		return $this->query('Crypto');
1560
-	}
1561
-
1562
-	/**
1563
-	 * Returns a Hasher instance
1564
-	 *
1565
-	 * @return \OCP\Security\IHasher
1566
-	 */
1567
-	public function getHasher() {
1568
-		return $this->query('Hasher');
1569
-	}
1570
-
1571
-	/**
1572
-	 * Returns a CredentialsManager instance
1573
-	 *
1574
-	 * @return \OCP\Security\ICredentialsManager
1575
-	 */
1576
-	public function getCredentialsManager() {
1577
-		return $this->query('CredentialsManager');
1578
-	}
1579
-
1580
-	/**
1581
-	 * Returns an instance of the HTTP helper class
1582
-	 *
1583
-	 * @deprecated Use getHTTPClientService()
1584
-	 * @return \OC\HTTPHelper
1585
-	 */
1586
-	public function getHTTPHelper() {
1587
-		return $this->query('HTTPHelper');
1588
-	}
1589
-
1590
-	/**
1591
-	 * Get the certificate manager for the user
1592
-	 *
1593
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1594
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1595
-	 */
1596
-	public function getCertificateManager($userId = '') {
1597
-		if ($userId === '') {
1598
-			$userSession = $this->getUserSession();
1599
-			$user = $userSession->getUser();
1600
-			if (is_null($user)) {
1601
-				return null;
1602
-			}
1603
-			$userId = $user->getUID();
1604
-		}
1605
-		return new CertificateManager(
1606
-			$userId,
1607
-			new View(),
1608
-			$this->getConfig(),
1609
-			$this->getLogger(),
1610
-			$this->getSecureRandom()
1611
-		);
1612
-	}
1613
-
1614
-	/**
1615
-	 * Returns an instance of the HTTP client service
1616
-	 *
1617
-	 * @return \OCP\Http\Client\IClientService
1618
-	 */
1619
-	public function getHTTPClientService() {
1620
-		return $this->query('HttpClientService');
1621
-	}
1622
-
1623
-	/**
1624
-	 * Create a new event source
1625
-	 *
1626
-	 * @return \OCP\IEventSource
1627
-	 */
1628
-	public function createEventSource() {
1629
-		return new \OC_EventSource();
1630
-	}
1631
-
1632
-	/**
1633
-	 * Get the active event logger
1634
-	 *
1635
-	 * The returned logger only logs data when debug mode is enabled
1636
-	 *
1637
-	 * @return \OCP\Diagnostics\IEventLogger
1638
-	 */
1639
-	public function getEventLogger() {
1640
-		return $this->query('EventLogger');
1641
-	}
1642
-
1643
-	/**
1644
-	 * Get the active query logger
1645
-	 *
1646
-	 * The returned logger only logs data when debug mode is enabled
1647
-	 *
1648
-	 * @return \OCP\Diagnostics\IQueryLogger
1649
-	 */
1650
-	public function getQueryLogger() {
1651
-		return $this->query('QueryLogger');
1652
-	}
1653
-
1654
-	/**
1655
-	 * Get the manager for temporary files and folders
1656
-	 *
1657
-	 * @return \OCP\ITempManager
1658
-	 */
1659
-	public function getTempManager() {
1660
-		return $this->query('TempManager');
1661
-	}
1662
-
1663
-	/**
1664
-	 * Get the app manager
1665
-	 *
1666
-	 * @return \OCP\App\IAppManager
1667
-	 */
1668
-	public function getAppManager() {
1669
-		return $this->query('AppManager');
1670
-	}
1671
-
1672
-	/**
1673
-	 * Creates a new mailer
1674
-	 *
1675
-	 * @return \OCP\Mail\IMailer
1676
-	 */
1677
-	public function getMailer() {
1678
-		return $this->query('Mailer');
1679
-	}
1680
-
1681
-	/**
1682
-	 * Get the webroot
1683
-	 *
1684
-	 * @return string
1685
-	 */
1686
-	public function getWebRoot() {
1687
-		return $this->webRoot;
1688
-	}
1689
-
1690
-	/**
1691
-	 * @return \OC\OCSClient
1692
-	 */
1693
-	public function getOcsClient() {
1694
-		return $this->query('OcsClient');
1695
-	}
1696
-
1697
-	/**
1698
-	 * @return \OCP\IDateTimeZone
1699
-	 */
1700
-	public function getDateTimeZone() {
1701
-		return $this->query('DateTimeZone');
1702
-	}
1703
-
1704
-	/**
1705
-	 * @return \OCP\IDateTimeFormatter
1706
-	 */
1707
-	public function getDateTimeFormatter() {
1708
-		return $this->query('DateTimeFormatter');
1709
-	}
1710
-
1711
-	/**
1712
-	 * @return \OCP\Files\Config\IMountProviderCollection
1713
-	 */
1714
-	public function getMountProviderCollection() {
1715
-		return $this->query('MountConfigManager');
1716
-	}
1717
-
1718
-	/**
1719
-	 * Get the IniWrapper
1720
-	 *
1721
-	 * @return IniGetWrapper
1722
-	 */
1723
-	public function getIniWrapper() {
1724
-		return $this->query('IniWrapper');
1725
-	}
1726
-
1727
-	/**
1728
-	 * @return \OCP\Command\IBus
1729
-	 */
1730
-	public function getCommandBus() {
1731
-		return $this->query('AsyncCommandBus');
1732
-	}
1733
-
1734
-	/**
1735
-	 * Get the trusted domain helper
1736
-	 *
1737
-	 * @return TrustedDomainHelper
1738
-	 */
1739
-	public function getTrustedDomainHelper() {
1740
-		return $this->query('TrustedDomainHelper');
1741
-	}
1742
-
1743
-	/**
1744
-	 * Get the locking provider
1745
-	 *
1746
-	 * @return \OCP\Lock\ILockingProvider
1747
-	 * @since 8.1.0
1748
-	 */
1749
-	public function getLockingProvider() {
1750
-		return $this->query('LockingProvider');
1751
-	}
1752
-
1753
-	/**
1754
-	 * @return \OCP\Files\Mount\IMountManager
1755
-	 **/
1756
-	function getMountManager() {
1757
-		return $this->query('MountManager');
1758
-	}
1759
-
1760
-	/** @return \OCP\Files\Config\IUserMountCache */
1761
-	function getUserMountCache() {
1762
-		return $this->query('UserMountCache');
1763
-	}
1764
-
1765
-	/**
1766
-	 * Get the MimeTypeDetector
1767
-	 *
1768
-	 * @return \OCP\Files\IMimeTypeDetector
1769
-	 */
1770
-	public function getMimeTypeDetector() {
1771
-		return $this->query('MimeTypeDetector');
1772
-	}
1773
-
1774
-	/**
1775
-	 * Get the MimeTypeLoader
1776
-	 *
1777
-	 * @return \OCP\Files\IMimeTypeLoader
1778
-	 */
1779
-	public function getMimeTypeLoader() {
1780
-		return $this->query('MimeTypeLoader');
1781
-	}
1782
-
1783
-	/**
1784
-	 * Get the manager of all the capabilities
1785
-	 *
1786
-	 * @return \OC\CapabilitiesManager
1787
-	 */
1788
-	public function getCapabilitiesManager() {
1789
-		return $this->query('CapabilitiesManager');
1790
-	}
1791
-
1792
-	/**
1793
-	 * Get the EventDispatcher
1794
-	 *
1795
-	 * @return EventDispatcherInterface
1796
-	 * @since 8.2.0
1797
-	 */
1798
-	public function getEventDispatcher() {
1799
-		return $this->query('EventDispatcher');
1800
-	}
1801
-
1802
-	/**
1803
-	 * Get the Notification Manager
1804
-	 *
1805
-	 * @return \OCP\Notification\IManager
1806
-	 * @since 8.2.0
1807
-	 */
1808
-	public function getNotificationManager() {
1809
-		return $this->query('NotificationManager');
1810
-	}
1811
-
1812
-	/**
1813
-	 * @return \OCP\Comments\ICommentsManager
1814
-	 */
1815
-	public function getCommentsManager() {
1816
-		return $this->query('CommentsManager');
1817
-	}
1818
-
1819
-	/**
1820
-	 * @return \OCA\Theming\ThemingDefaults
1821
-	 */
1822
-	public function getThemingDefaults() {
1823
-		return $this->query('ThemingDefaults');
1824
-	}
1825
-
1826
-	/**
1827
-	 * @return \OC\IntegrityCheck\Checker
1828
-	 */
1829
-	public function getIntegrityCodeChecker() {
1830
-		return $this->query('IntegrityCodeChecker');
1831
-	}
1832
-
1833
-	/**
1834
-	 * @return \OC\Session\CryptoWrapper
1835
-	 */
1836
-	public function getSessionCryptoWrapper() {
1837
-		return $this->query('CryptoWrapper');
1838
-	}
1839
-
1840
-	/**
1841
-	 * @return CsrfTokenManager
1842
-	 */
1843
-	public function getCsrfTokenManager() {
1844
-		return $this->query('CsrfTokenManager');
1845
-	}
1846
-
1847
-	/**
1848
-	 * @return Throttler
1849
-	 */
1850
-	public function getBruteForceThrottler() {
1851
-		return $this->query('Throttler');
1852
-	}
1853
-
1854
-	/**
1855
-	 * @return IContentSecurityPolicyManager
1856
-	 */
1857
-	public function getContentSecurityPolicyManager() {
1858
-		return $this->query('ContentSecurityPolicyManager');
1859
-	}
1860
-
1861
-	/**
1862
-	 * @return ContentSecurityPolicyNonceManager
1863
-	 */
1864
-	public function getContentSecurityPolicyNonceManager() {
1865
-		return $this->query('ContentSecurityPolicyNonceManager');
1866
-	}
1867
-
1868
-	/**
1869
-	 * Not a public API as of 8.2, wait for 9.0
1870
-	 *
1871
-	 * @return \OCA\Files_External\Service\BackendService
1872
-	 */
1873
-	public function getStoragesBackendService() {
1874
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1875
-	}
1876
-
1877
-	/**
1878
-	 * Not a public API as of 8.2, wait for 9.0
1879
-	 *
1880
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1881
-	 */
1882
-	public function getGlobalStoragesService() {
1883
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1884
-	}
1885
-
1886
-	/**
1887
-	 * Not a public API as of 8.2, wait for 9.0
1888
-	 *
1889
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1890
-	 */
1891
-	public function getUserGlobalStoragesService() {
1892
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1893
-	}
1894
-
1895
-	/**
1896
-	 * Not a public API as of 8.2, wait for 9.0
1897
-	 *
1898
-	 * @return \OCA\Files_External\Service\UserStoragesService
1899
-	 */
1900
-	public function getUserStoragesService() {
1901
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1902
-	}
1903
-
1904
-	/**
1905
-	 * @return \OCP\Share\IManager
1906
-	 */
1907
-	public function getShareManager() {
1908
-		return $this->query('ShareManager');
1909
-	}
1910
-
1911
-	/**
1912
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1913
-	 */
1914
-	public function getCollaboratorSearch() {
1915
-		return $this->query('CollaboratorSearch');
1916
-	}
1917
-
1918
-	/**
1919
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1920
-	 */
1921
-	public function getAutoCompleteManager(){
1922
-		return $this->query(IManager::class);
1923
-	}
1924
-
1925
-	/**
1926
-	 * Returns the LDAP Provider
1927
-	 *
1928
-	 * @return \OCP\LDAP\ILDAPProvider
1929
-	 */
1930
-	public function getLDAPProvider() {
1931
-		return $this->query('LDAPProvider');
1932
-	}
1933
-
1934
-	/**
1935
-	 * @return \OCP\Settings\IManager
1936
-	 */
1937
-	public function getSettingsManager() {
1938
-		return $this->query('SettingsManager');
1939
-	}
1940
-
1941
-	/**
1942
-	 * @return \OCP\Files\IAppData
1943
-	 */
1944
-	public function getAppDataDir($app) {
1945
-		/** @var \OC\Files\AppData\Factory $factory */
1946
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1947
-		return $factory->get($app);
1948
-	}
1949
-
1950
-	/**
1951
-	 * @return \OCP\Lockdown\ILockdownManager
1952
-	 */
1953
-	public function getLockdownManager() {
1954
-		return $this->query('LockdownManager');
1955
-	}
1956
-
1957
-	/**
1958
-	 * @return \OCP\Federation\ICloudIdManager
1959
-	 */
1960
-	public function getCloudIdManager() {
1961
-		return $this->query(ICloudIdManager::class);
1962
-	}
1963
-
1964
-	/**
1965
-	 * @return \OCP\Remote\Api\IApiFactory
1966
-	 */
1967
-	public function getRemoteApiFactory() {
1968
-		return $this->query(IApiFactory::class);
1969
-	}
1970
-
1971
-	/**
1972
-	 * @return \OCP\Remote\IInstanceFactory
1973
-	 */
1974
-	public function getRemoteInstanceFactory() {
1975
-		return $this->query(IInstanceFactory::class);
1976
-	}
934
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
935
+            if (isset($prefixes['OCA\\Theming\\'])) {
936
+                $classExists = true;
937
+            } else {
938
+                $classExists = false;
939
+            }
940
+
941
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
942
+                return new ThemingDefaults(
943
+                    $c->getConfig(),
944
+                    $c->getL10N('theming'),
945
+                    $c->getURLGenerator(),
946
+                    $c->getAppDataDir('theming'),
947
+                    $c->getMemCacheFactory(),
948
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
949
+                    $this->getAppManager()
950
+                );
951
+            }
952
+            return new \OC_Defaults();
953
+        });
954
+        $this->registerService(SCSSCacher::class, function (Server $c) {
955
+            /** @var Factory $cacheFactory */
956
+            $cacheFactory = $c->query(Factory::class);
957
+            return new SCSSCacher(
958
+                $c->getLogger(),
959
+                $c->query(\OC\Files\AppData\Factory::class),
960
+                $c->getURLGenerator(),
961
+                $c->getConfig(),
962
+                $c->getThemingDefaults(),
963
+                \OC::$SERVERROOT,
964
+                $cacheFactory->createDistributed('SCSS')
965
+            );
966
+        });
967
+        $this->registerService(EventDispatcher::class, function () {
968
+            return new EventDispatcher();
969
+        });
970
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
971
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
972
+
973
+        $this->registerService('CryptoWrapper', function (Server $c) {
974
+            // FIXME: Instantiiated here due to cyclic dependency
975
+            $request = new Request(
976
+                [
977
+                    'get' => $_GET,
978
+                    'post' => $_POST,
979
+                    'files' => $_FILES,
980
+                    'server' => $_SERVER,
981
+                    'env' => $_ENV,
982
+                    'cookies' => $_COOKIE,
983
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
984
+                        ? $_SERVER['REQUEST_METHOD']
985
+                        : null,
986
+                ],
987
+                $c->getSecureRandom(),
988
+                $c->getConfig()
989
+            );
990
+
991
+            return new CryptoWrapper(
992
+                $c->getConfig(),
993
+                $c->getCrypto(),
994
+                $c->getSecureRandom(),
995
+                $request
996
+            );
997
+        });
998
+        $this->registerService('CsrfTokenManager', function (Server $c) {
999
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1000
+
1001
+            return new CsrfTokenManager(
1002
+                $tokenGenerator,
1003
+                $c->query(SessionStorage::class)
1004
+            );
1005
+        });
1006
+        $this->registerService(SessionStorage::class, function (Server $c) {
1007
+            return new SessionStorage($c->getSession());
1008
+        });
1009
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1010
+            return new ContentSecurityPolicyManager();
1011
+        });
1012
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1013
+
1014
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1015
+            return new ContentSecurityPolicyNonceManager(
1016
+                $c->getCsrfTokenManager(),
1017
+                $c->getRequest()
1018
+            );
1019
+        });
1020
+
1021
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1022
+            $config = $c->getConfig();
1023
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
1024
+            /** @var \OCP\Share\IProviderFactory $factory */
1025
+            $factory = new $factoryClass($this);
1026
+
1027
+            $manager = new \OC\Share20\Manager(
1028
+                $c->getLogger(),
1029
+                $c->getConfig(),
1030
+                $c->getSecureRandom(),
1031
+                $c->getHasher(),
1032
+                $c->getMountManager(),
1033
+                $c->getGroupManager(),
1034
+                $c->getL10N('lib'),
1035
+                $c->getL10NFactory(),
1036
+                $factory,
1037
+                $c->getUserManager(),
1038
+                $c->getLazyRootFolder(),
1039
+                $c->getEventDispatcher(),
1040
+                $c->getMailer(),
1041
+                $c->getURLGenerator(),
1042
+                $c->getThemingDefaults()
1043
+            );
1044
+
1045
+            return $manager;
1046
+        });
1047
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1048
+
1049
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1050
+            $instance = new Collaboration\Collaborators\Search($c);
1051
+
1052
+            // register default plugins
1053
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1054
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1055
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1056
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1057
+
1058
+            return $instance;
1059
+        });
1060
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1061
+
1062
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1063
+
1064
+        $this->registerService('SettingsManager', function (Server $c) {
1065
+            $manager = new \OC\Settings\Manager(
1066
+                $c->getLogger(),
1067
+                $c->getDatabaseConnection(),
1068
+                $c->getL10N('lib'),
1069
+                $c->getConfig(),
1070
+                $c->getEncryptionManager(),
1071
+                $c->getUserManager(),
1072
+                $c->getLockingProvider(),
1073
+                $c->getRequest(),
1074
+                $c->getURLGenerator(),
1075
+                $c->query(AccountManager::class),
1076
+                $c->getGroupManager(),
1077
+                $c->getL10NFactory(),
1078
+                $c->getAppManager()
1079
+            );
1080
+            return $manager;
1081
+        });
1082
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1083
+            return new \OC\Files\AppData\Factory(
1084
+                $c->getRootFolder(),
1085
+                $c->getSystemConfig()
1086
+            );
1087
+        });
1088
+
1089
+        $this->registerService('LockdownManager', function (Server $c) {
1090
+            return new LockdownManager(function () use ($c) {
1091
+                return $c->getSession();
1092
+            });
1093
+        });
1094
+
1095
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1096
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1097
+        });
1098
+
1099
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1100
+            return new CloudIdManager();
1101
+        });
1102
+
1103
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1104
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1105
+
1106
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1107
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1108
+
1109
+        $this->registerService(Defaults::class, function (Server $c) {
1110
+            return new Defaults(
1111
+                $c->getThemingDefaults()
1112
+            );
1113
+        });
1114
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1115
+
1116
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1117
+            return $c->query(\OCP\IUserSession::class)->getSession();
1118
+        });
1119
+
1120
+        $this->registerService(IShareHelper::class, function (Server $c) {
1121
+            return new ShareHelper(
1122
+                $c->query(\OCP\Share\IManager::class)
1123
+            );
1124
+        });
1125
+
1126
+        $this->registerService(Installer::class, function(Server $c) {
1127
+            return new Installer(
1128
+                $c->getAppFetcher(),
1129
+                $c->getHTTPClientService(),
1130
+                $c->getTempManager(),
1131
+                $c->getLogger(),
1132
+                $c->getConfig()
1133
+            );
1134
+        });
1135
+
1136
+        $this->registerService(IApiFactory::class, function(Server $c) {
1137
+            return new ApiFactory($c->getHTTPClientService());
1138
+        });
1139
+
1140
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1141
+            $memcacheFactory = $c->getMemCacheFactory();
1142
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1143
+        });
1144
+
1145
+        $this->registerService(IContactsStore::class, function(Server $c) {
1146
+            return new ContactsStore(
1147
+                $c->getContactsManager(),
1148
+                $c->getConfig(),
1149
+                $c->getUserManager(),
1150
+                $c->getGroupManager()
1151
+            );
1152
+        });
1153
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1154
+
1155
+        $this->connectDispatcher();
1156
+    }
1157
+
1158
+    /**
1159
+     * @return \OCP\Calendar\IManager
1160
+     */
1161
+    public function getCalendarManager() {
1162
+        return $this->query('CalendarManager');
1163
+    }
1164
+
1165
+    private function connectDispatcher() {
1166
+        $dispatcher = $this->getEventDispatcher();
1167
+
1168
+        // Delete avatar on user deletion
1169
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1170
+            $logger = $this->getLogger();
1171
+            $manager = $this->getAvatarManager();
1172
+            /** @var IUser $user */
1173
+            $user = $e->getSubject();
1174
+
1175
+            try {
1176
+                $avatar = $manager->getAvatar($user->getUID());
1177
+                $avatar->remove();
1178
+            } catch (NotFoundException $e) {
1179
+                // no avatar to remove
1180
+            } catch (\Exception $e) {
1181
+                // Ignore exceptions
1182
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1183
+            }
1184
+        });
1185
+
1186
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1187
+            $manager = $this->getAvatarManager();
1188
+            /** @var IUser $user */
1189
+            $user = $e->getSubject();
1190
+            $feature = $e->getArgument('feature');
1191
+            $oldValue = $e->getArgument('oldValue');
1192
+            $value = $e->getArgument('value');
1193
+
1194
+            try {
1195
+                $avatar = $manager->getAvatar($user->getUID());
1196
+                $avatar->userChanged($feature, $oldValue, $value);
1197
+            } catch (NotFoundException $e) {
1198
+                // no avatar to remove
1199
+            }
1200
+        });
1201
+    }
1202
+
1203
+    /**
1204
+     * @return \OCP\Contacts\IManager
1205
+     */
1206
+    public function getContactsManager() {
1207
+        return $this->query('ContactsManager');
1208
+    }
1209
+
1210
+    /**
1211
+     * @return \OC\Encryption\Manager
1212
+     */
1213
+    public function getEncryptionManager() {
1214
+        return $this->query('EncryptionManager');
1215
+    }
1216
+
1217
+    /**
1218
+     * @return \OC\Encryption\File
1219
+     */
1220
+    public function getEncryptionFilesHelper() {
1221
+        return $this->query('EncryptionFileHelper');
1222
+    }
1223
+
1224
+    /**
1225
+     * @return \OCP\Encryption\Keys\IStorage
1226
+     */
1227
+    public function getEncryptionKeyStorage() {
1228
+        return $this->query('EncryptionKeyStorage');
1229
+    }
1230
+
1231
+    /**
1232
+     * The current request object holding all information about the request
1233
+     * currently being processed is returned from this method.
1234
+     * In case the current execution was not initiated by a web request null is returned
1235
+     *
1236
+     * @return \OCP\IRequest
1237
+     */
1238
+    public function getRequest() {
1239
+        return $this->query('Request');
1240
+    }
1241
+
1242
+    /**
1243
+     * Returns the preview manager which can create preview images for a given file
1244
+     *
1245
+     * @return \OCP\IPreview
1246
+     */
1247
+    public function getPreviewManager() {
1248
+        return $this->query('PreviewManager');
1249
+    }
1250
+
1251
+    /**
1252
+     * Returns the tag manager which can get and set tags for different object types
1253
+     *
1254
+     * @see \OCP\ITagManager::load()
1255
+     * @return \OCP\ITagManager
1256
+     */
1257
+    public function getTagManager() {
1258
+        return $this->query('TagManager');
1259
+    }
1260
+
1261
+    /**
1262
+     * Returns the system-tag manager
1263
+     *
1264
+     * @return \OCP\SystemTag\ISystemTagManager
1265
+     *
1266
+     * @since 9.0.0
1267
+     */
1268
+    public function getSystemTagManager() {
1269
+        return $this->query('SystemTagManager');
1270
+    }
1271
+
1272
+    /**
1273
+     * Returns the system-tag object mapper
1274
+     *
1275
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1276
+     *
1277
+     * @since 9.0.0
1278
+     */
1279
+    public function getSystemTagObjectMapper() {
1280
+        return $this->query('SystemTagObjectMapper');
1281
+    }
1282
+
1283
+    /**
1284
+     * Returns the avatar manager, used for avatar functionality
1285
+     *
1286
+     * @return \OCP\IAvatarManager
1287
+     */
1288
+    public function getAvatarManager() {
1289
+        return $this->query('AvatarManager');
1290
+    }
1291
+
1292
+    /**
1293
+     * Returns the root folder of ownCloud's data directory
1294
+     *
1295
+     * @return \OCP\Files\IRootFolder
1296
+     */
1297
+    public function getRootFolder() {
1298
+        return $this->query('LazyRootFolder');
1299
+    }
1300
+
1301
+    /**
1302
+     * Returns the root folder of ownCloud's data directory
1303
+     * This is the lazy variant so this gets only initialized once it
1304
+     * is actually used.
1305
+     *
1306
+     * @return \OCP\Files\IRootFolder
1307
+     */
1308
+    public function getLazyRootFolder() {
1309
+        return $this->query('LazyRootFolder');
1310
+    }
1311
+
1312
+    /**
1313
+     * Returns a view to ownCloud's files folder
1314
+     *
1315
+     * @param string $userId user ID
1316
+     * @return \OCP\Files\Folder|null
1317
+     */
1318
+    public function getUserFolder($userId = null) {
1319
+        if ($userId === null) {
1320
+            $user = $this->getUserSession()->getUser();
1321
+            if (!$user) {
1322
+                return null;
1323
+            }
1324
+            $userId = $user->getUID();
1325
+        }
1326
+        $root = $this->getRootFolder();
1327
+        return $root->getUserFolder($userId);
1328
+    }
1329
+
1330
+    /**
1331
+     * Returns an app-specific view in ownClouds data directory
1332
+     *
1333
+     * @return \OCP\Files\Folder
1334
+     * @deprecated since 9.2.0 use IAppData
1335
+     */
1336
+    public function getAppFolder() {
1337
+        $dir = '/' . \OC_App::getCurrentApp();
1338
+        $root = $this->getRootFolder();
1339
+        if (!$root->nodeExists($dir)) {
1340
+            $folder = $root->newFolder($dir);
1341
+        } else {
1342
+            $folder = $root->get($dir);
1343
+        }
1344
+        return $folder;
1345
+    }
1346
+
1347
+    /**
1348
+     * @return \OC\User\Manager
1349
+     */
1350
+    public function getUserManager() {
1351
+        return $this->query('UserManager');
1352
+    }
1353
+
1354
+    /**
1355
+     * @return \OC\Group\Manager
1356
+     */
1357
+    public function getGroupManager() {
1358
+        return $this->query('GroupManager');
1359
+    }
1360
+
1361
+    /**
1362
+     * @return \OC\User\Session
1363
+     */
1364
+    public function getUserSession() {
1365
+        return $this->query('UserSession');
1366
+    }
1367
+
1368
+    /**
1369
+     * @return \OCP\ISession
1370
+     */
1371
+    public function getSession() {
1372
+        return $this->query('UserSession')->getSession();
1373
+    }
1374
+
1375
+    /**
1376
+     * @param \OCP\ISession $session
1377
+     */
1378
+    public function setSession(\OCP\ISession $session) {
1379
+        $this->query(SessionStorage::class)->setSession($session);
1380
+        $this->query('UserSession')->setSession($session);
1381
+        $this->query(Store::class)->setSession($session);
1382
+    }
1383
+
1384
+    /**
1385
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1386
+     */
1387
+    public function getTwoFactorAuthManager() {
1388
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1389
+    }
1390
+
1391
+    /**
1392
+     * @return \OC\NavigationManager
1393
+     */
1394
+    public function getNavigationManager() {
1395
+        return $this->query('NavigationManager');
1396
+    }
1397
+
1398
+    /**
1399
+     * @return \OCP\IConfig
1400
+     */
1401
+    public function getConfig() {
1402
+        return $this->query('AllConfig');
1403
+    }
1404
+
1405
+    /**
1406
+     * @return \OC\SystemConfig
1407
+     */
1408
+    public function getSystemConfig() {
1409
+        return $this->query('SystemConfig');
1410
+    }
1411
+
1412
+    /**
1413
+     * Returns the app config manager
1414
+     *
1415
+     * @return \OCP\IAppConfig
1416
+     */
1417
+    public function getAppConfig() {
1418
+        return $this->query('AppConfig');
1419
+    }
1420
+
1421
+    /**
1422
+     * @return \OCP\L10N\IFactory
1423
+     */
1424
+    public function getL10NFactory() {
1425
+        return $this->query('L10NFactory');
1426
+    }
1427
+
1428
+    /**
1429
+     * get an L10N instance
1430
+     *
1431
+     * @param string $app appid
1432
+     * @param string $lang
1433
+     * @return IL10N
1434
+     */
1435
+    public function getL10N($app, $lang = null) {
1436
+        return $this->getL10NFactory()->get($app, $lang);
1437
+    }
1438
+
1439
+    /**
1440
+     * @return \OCP\IURLGenerator
1441
+     */
1442
+    public function getURLGenerator() {
1443
+        return $this->query('URLGenerator');
1444
+    }
1445
+
1446
+    /**
1447
+     * @return \OCP\IHelper
1448
+     */
1449
+    public function getHelper() {
1450
+        return $this->query('AppHelper');
1451
+    }
1452
+
1453
+    /**
1454
+     * @return AppFetcher
1455
+     */
1456
+    public function getAppFetcher() {
1457
+        return $this->query(AppFetcher::class);
1458
+    }
1459
+
1460
+    /**
1461
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1462
+     * getMemCacheFactory() instead.
1463
+     *
1464
+     * @return \OCP\ICache
1465
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1466
+     */
1467
+    public function getCache() {
1468
+        return $this->query('UserCache');
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns an \OCP\CacheFactory instance
1473
+     *
1474
+     * @return \OCP\ICacheFactory
1475
+     */
1476
+    public function getMemCacheFactory() {
1477
+        return $this->query('MemCacheFactory');
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns an \OC\RedisFactory instance
1482
+     *
1483
+     * @return \OC\RedisFactory
1484
+     */
1485
+    public function getGetRedisFactory() {
1486
+        return $this->query('RedisFactory');
1487
+    }
1488
+
1489
+
1490
+    /**
1491
+     * Returns the current session
1492
+     *
1493
+     * @return \OCP\IDBConnection
1494
+     */
1495
+    public function getDatabaseConnection() {
1496
+        return $this->query('DatabaseConnection');
1497
+    }
1498
+
1499
+    /**
1500
+     * Returns the activity manager
1501
+     *
1502
+     * @return \OCP\Activity\IManager
1503
+     */
1504
+    public function getActivityManager() {
1505
+        return $this->query('ActivityManager');
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns an job list for controlling background jobs
1510
+     *
1511
+     * @return \OCP\BackgroundJob\IJobList
1512
+     */
1513
+    public function getJobList() {
1514
+        return $this->query('JobList');
1515
+    }
1516
+
1517
+    /**
1518
+     * Returns a logger instance
1519
+     *
1520
+     * @return \OCP\ILogger
1521
+     */
1522
+    public function getLogger() {
1523
+        return $this->query('Logger');
1524
+    }
1525
+
1526
+    /**
1527
+     * Returns a router for generating and matching urls
1528
+     *
1529
+     * @return \OCP\Route\IRouter
1530
+     */
1531
+    public function getRouter() {
1532
+        return $this->query('Router');
1533
+    }
1534
+
1535
+    /**
1536
+     * Returns a search instance
1537
+     *
1538
+     * @return \OCP\ISearch
1539
+     */
1540
+    public function getSearch() {
1541
+        return $this->query('Search');
1542
+    }
1543
+
1544
+    /**
1545
+     * Returns a SecureRandom instance
1546
+     *
1547
+     * @return \OCP\Security\ISecureRandom
1548
+     */
1549
+    public function getSecureRandom() {
1550
+        return $this->query('SecureRandom');
1551
+    }
1552
+
1553
+    /**
1554
+     * Returns a Crypto instance
1555
+     *
1556
+     * @return \OCP\Security\ICrypto
1557
+     */
1558
+    public function getCrypto() {
1559
+        return $this->query('Crypto');
1560
+    }
1561
+
1562
+    /**
1563
+     * Returns a Hasher instance
1564
+     *
1565
+     * @return \OCP\Security\IHasher
1566
+     */
1567
+    public function getHasher() {
1568
+        return $this->query('Hasher');
1569
+    }
1570
+
1571
+    /**
1572
+     * Returns a CredentialsManager instance
1573
+     *
1574
+     * @return \OCP\Security\ICredentialsManager
1575
+     */
1576
+    public function getCredentialsManager() {
1577
+        return $this->query('CredentialsManager');
1578
+    }
1579
+
1580
+    /**
1581
+     * Returns an instance of the HTTP helper class
1582
+     *
1583
+     * @deprecated Use getHTTPClientService()
1584
+     * @return \OC\HTTPHelper
1585
+     */
1586
+    public function getHTTPHelper() {
1587
+        return $this->query('HTTPHelper');
1588
+    }
1589
+
1590
+    /**
1591
+     * Get the certificate manager for the user
1592
+     *
1593
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1594
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1595
+     */
1596
+    public function getCertificateManager($userId = '') {
1597
+        if ($userId === '') {
1598
+            $userSession = $this->getUserSession();
1599
+            $user = $userSession->getUser();
1600
+            if (is_null($user)) {
1601
+                return null;
1602
+            }
1603
+            $userId = $user->getUID();
1604
+        }
1605
+        return new CertificateManager(
1606
+            $userId,
1607
+            new View(),
1608
+            $this->getConfig(),
1609
+            $this->getLogger(),
1610
+            $this->getSecureRandom()
1611
+        );
1612
+    }
1613
+
1614
+    /**
1615
+     * Returns an instance of the HTTP client service
1616
+     *
1617
+     * @return \OCP\Http\Client\IClientService
1618
+     */
1619
+    public function getHTTPClientService() {
1620
+        return $this->query('HttpClientService');
1621
+    }
1622
+
1623
+    /**
1624
+     * Create a new event source
1625
+     *
1626
+     * @return \OCP\IEventSource
1627
+     */
1628
+    public function createEventSource() {
1629
+        return new \OC_EventSource();
1630
+    }
1631
+
1632
+    /**
1633
+     * Get the active event logger
1634
+     *
1635
+     * The returned logger only logs data when debug mode is enabled
1636
+     *
1637
+     * @return \OCP\Diagnostics\IEventLogger
1638
+     */
1639
+    public function getEventLogger() {
1640
+        return $this->query('EventLogger');
1641
+    }
1642
+
1643
+    /**
1644
+     * Get the active query logger
1645
+     *
1646
+     * The returned logger only logs data when debug mode is enabled
1647
+     *
1648
+     * @return \OCP\Diagnostics\IQueryLogger
1649
+     */
1650
+    public function getQueryLogger() {
1651
+        return $this->query('QueryLogger');
1652
+    }
1653
+
1654
+    /**
1655
+     * Get the manager for temporary files and folders
1656
+     *
1657
+     * @return \OCP\ITempManager
1658
+     */
1659
+    public function getTempManager() {
1660
+        return $this->query('TempManager');
1661
+    }
1662
+
1663
+    /**
1664
+     * Get the app manager
1665
+     *
1666
+     * @return \OCP\App\IAppManager
1667
+     */
1668
+    public function getAppManager() {
1669
+        return $this->query('AppManager');
1670
+    }
1671
+
1672
+    /**
1673
+     * Creates a new mailer
1674
+     *
1675
+     * @return \OCP\Mail\IMailer
1676
+     */
1677
+    public function getMailer() {
1678
+        return $this->query('Mailer');
1679
+    }
1680
+
1681
+    /**
1682
+     * Get the webroot
1683
+     *
1684
+     * @return string
1685
+     */
1686
+    public function getWebRoot() {
1687
+        return $this->webRoot;
1688
+    }
1689
+
1690
+    /**
1691
+     * @return \OC\OCSClient
1692
+     */
1693
+    public function getOcsClient() {
1694
+        return $this->query('OcsClient');
1695
+    }
1696
+
1697
+    /**
1698
+     * @return \OCP\IDateTimeZone
1699
+     */
1700
+    public function getDateTimeZone() {
1701
+        return $this->query('DateTimeZone');
1702
+    }
1703
+
1704
+    /**
1705
+     * @return \OCP\IDateTimeFormatter
1706
+     */
1707
+    public function getDateTimeFormatter() {
1708
+        return $this->query('DateTimeFormatter');
1709
+    }
1710
+
1711
+    /**
1712
+     * @return \OCP\Files\Config\IMountProviderCollection
1713
+     */
1714
+    public function getMountProviderCollection() {
1715
+        return $this->query('MountConfigManager');
1716
+    }
1717
+
1718
+    /**
1719
+     * Get the IniWrapper
1720
+     *
1721
+     * @return IniGetWrapper
1722
+     */
1723
+    public function getIniWrapper() {
1724
+        return $this->query('IniWrapper');
1725
+    }
1726
+
1727
+    /**
1728
+     * @return \OCP\Command\IBus
1729
+     */
1730
+    public function getCommandBus() {
1731
+        return $this->query('AsyncCommandBus');
1732
+    }
1733
+
1734
+    /**
1735
+     * Get the trusted domain helper
1736
+     *
1737
+     * @return TrustedDomainHelper
1738
+     */
1739
+    public function getTrustedDomainHelper() {
1740
+        return $this->query('TrustedDomainHelper');
1741
+    }
1742
+
1743
+    /**
1744
+     * Get the locking provider
1745
+     *
1746
+     * @return \OCP\Lock\ILockingProvider
1747
+     * @since 8.1.0
1748
+     */
1749
+    public function getLockingProvider() {
1750
+        return $this->query('LockingProvider');
1751
+    }
1752
+
1753
+    /**
1754
+     * @return \OCP\Files\Mount\IMountManager
1755
+     **/
1756
+    function getMountManager() {
1757
+        return $this->query('MountManager');
1758
+    }
1759
+
1760
+    /** @return \OCP\Files\Config\IUserMountCache */
1761
+    function getUserMountCache() {
1762
+        return $this->query('UserMountCache');
1763
+    }
1764
+
1765
+    /**
1766
+     * Get the MimeTypeDetector
1767
+     *
1768
+     * @return \OCP\Files\IMimeTypeDetector
1769
+     */
1770
+    public function getMimeTypeDetector() {
1771
+        return $this->query('MimeTypeDetector');
1772
+    }
1773
+
1774
+    /**
1775
+     * Get the MimeTypeLoader
1776
+     *
1777
+     * @return \OCP\Files\IMimeTypeLoader
1778
+     */
1779
+    public function getMimeTypeLoader() {
1780
+        return $this->query('MimeTypeLoader');
1781
+    }
1782
+
1783
+    /**
1784
+     * Get the manager of all the capabilities
1785
+     *
1786
+     * @return \OC\CapabilitiesManager
1787
+     */
1788
+    public function getCapabilitiesManager() {
1789
+        return $this->query('CapabilitiesManager');
1790
+    }
1791
+
1792
+    /**
1793
+     * Get the EventDispatcher
1794
+     *
1795
+     * @return EventDispatcherInterface
1796
+     * @since 8.2.0
1797
+     */
1798
+    public function getEventDispatcher() {
1799
+        return $this->query('EventDispatcher');
1800
+    }
1801
+
1802
+    /**
1803
+     * Get the Notification Manager
1804
+     *
1805
+     * @return \OCP\Notification\IManager
1806
+     * @since 8.2.0
1807
+     */
1808
+    public function getNotificationManager() {
1809
+        return $this->query('NotificationManager');
1810
+    }
1811
+
1812
+    /**
1813
+     * @return \OCP\Comments\ICommentsManager
1814
+     */
1815
+    public function getCommentsManager() {
1816
+        return $this->query('CommentsManager');
1817
+    }
1818
+
1819
+    /**
1820
+     * @return \OCA\Theming\ThemingDefaults
1821
+     */
1822
+    public function getThemingDefaults() {
1823
+        return $this->query('ThemingDefaults');
1824
+    }
1825
+
1826
+    /**
1827
+     * @return \OC\IntegrityCheck\Checker
1828
+     */
1829
+    public function getIntegrityCodeChecker() {
1830
+        return $this->query('IntegrityCodeChecker');
1831
+    }
1832
+
1833
+    /**
1834
+     * @return \OC\Session\CryptoWrapper
1835
+     */
1836
+    public function getSessionCryptoWrapper() {
1837
+        return $this->query('CryptoWrapper');
1838
+    }
1839
+
1840
+    /**
1841
+     * @return CsrfTokenManager
1842
+     */
1843
+    public function getCsrfTokenManager() {
1844
+        return $this->query('CsrfTokenManager');
1845
+    }
1846
+
1847
+    /**
1848
+     * @return Throttler
1849
+     */
1850
+    public function getBruteForceThrottler() {
1851
+        return $this->query('Throttler');
1852
+    }
1853
+
1854
+    /**
1855
+     * @return IContentSecurityPolicyManager
1856
+     */
1857
+    public function getContentSecurityPolicyManager() {
1858
+        return $this->query('ContentSecurityPolicyManager');
1859
+    }
1860
+
1861
+    /**
1862
+     * @return ContentSecurityPolicyNonceManager
1863
+     */
1864
+    public function getContentSecurityPolicyNonceManager() {
1865
+        return $this->query('ContentSecurityPolicyNonceManager');
1866
+    }
1867
+
1868
+    /**
1869
+     * Not a public API as of 8.2, wait for 9.0
1870
+     *
1871
+     * @return \OCA\Files_External\Service\BackendService
1872
+     */
1873
+    public function getStoragesBackendService() {
1874
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1875
+    }
1876
+
1877
+    /**
1878
+     * Not a public API as of 8.2, wait for 9.0
1879
+     *
1880
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1881
+     */
1882
+    public function getGlobalStoragesService() {
1883
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1884
+    }
1885
+
1886
+    /**
1887
+     * Not a public API as of 8.2, wait for 9.0
1888
+     *
1889
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1890
+     */
1891
+    public function getUserGlobalStoragesService() {
1892
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1893
+    }
1894
+
1895
+    /**
1896
+     * Not a public API as of 8.2, wait for 9.0
1897
+     *
1898
+     * @return \OCA\Files_External\Service\UserStoragesService
1899
+     */
1900
+    public function getUserStoragesService() {
1901
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1902
+    }
1903
+
1904
+    /**
1905
+     * @return \OCP\Share\IManager
1906
+     */
1907
+    public function getShareManager() {
1908
+        return $this->query('ShareManager');
1909
+    }
1910
+
1911
+    /**
1912
+     * @return \OCP\Collaboration\Collaborators\ISearch
1913
+     */
1914
+    public function getCollaboratorSearch() {
1915
+        return $this->query('CollaboratorSearch');
1916
+    }
1917
+
1918
+    /**
1919
+     * @return \OCP\Collaboration\AutoComplete\IManager
1920
+     */
1921
+    public function getAutoCompleteManager(){
1922
+        return $this->query(IManager::class);
1923
+    }
1924
+
1925
+    /**
1926
+     * Returns the LDAP Provider
1927
+     *
1928
+     * @return \OCP\LDAP\ILDAPProvider
1929
+     */
1930
+    public function getLDAPProvider() {
1931
+        return $this->query('LDAPProvider');
1932
+    }
1933
+
1934
+    /**
1935
+     * @return \OCP\Settings\IManager
1936
+     */
1937
+    public function getSettingsManager() {
1938
+        return $this->query('SettingsManager');
1939
+    }
1940
+
1941
+    /**
1942
+     * @return \OCP\Files\IAppData
1943
+     */
1944
+    public function getAppDataDir($app) {
1945
+        /** @var \OC\Files\AppData\Factory $factory */
1946
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1947
+        return $factory->get($app);
1948
+    }
1949
+
1950
+    /**
1951
+     * @return \OCP\Lockdown\ILockdownManager
1952
+     */
1953
+    public function getLockdownManager() {
1954
+        return $this->query('LockdownManager');
1955
+    }
1956
+
1957
+    /**
1958
+     * @return \OCP\Federation\ICloudIdManager
1959
+     */
1960
+    public function getCloudIdManager() {
1961
+        return $this->query(ICloudIdManager::class);
1962
+    }
1963
+
1964
+    /**
1965
+     * @return \OCP\Remote\Api\IApiFactory
1966
+     */
1967
+    public function getRemoteApiFactory() {
1968
+        return $this->query(IApiFactory::class);
1969
+    }
1970
+
1971
+    /**
1972
+     * @return \OCP\Remote\IInstanceFactory
1973
+     */
1974
+    public function getRemoteInstanceFactory() {
1975
+        return $this->query(IInstanceFactory::class);
1976
+    }
1977 1977
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@
 block discarded – undo
134 134
 	 * @param RequestInterface $request
135 135
 	 * @param ResponseInterface $response
136 136
 	 *
137
-	 * @return void|bool
137
+	 * @return null|false
138 138
 	 */
139 139
 	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140 140
 		$path = $request->getPath();
Please login to merge, or discard this patch.
Indentation   +189 added lines, -189 removed lines patch added patch discarded remove patch
@@ -34,194 +34,194 @@
 block discarded – undo
34 34
 use OCP\IConfig;
35 35
 
36 36
 class PublishPlugin extends ServerPlugin {
37
-	const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
-
39
-	/**
40
-	 * Reference to SabreDAV server object.
41
-	 *
42
-	 * @var \Sabre\DAV\Server
43
-	 */
44
-	protected $server;
45
-
46
-	/**
47
-	 * Config instance to get instance secret.
48
-	 *
49
-	 * @var IConfig
50
-	 */
51
-	protected $config;
52
-
53
-	/**
54
-	 * URL Generator for absolute URLs.
55
-	 *
56
-	 * @var IURLGenerator
57
-	 */
58
-	protected $urlGenerator;
59
-
60
-	/**
61
-	 * PublishPlugin constructor.
62
-	 *
63
-	 * @param IConfig $config
64
-	 * @param IURLGenerator $urlGenerator
65
-	 */
66
-	public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
-		$this->config = $config;
68
-		$this->urlGenerator = $urlGenerator;
69
-	}
70
-
71
-	/**
72
-	 * This method should return a list of server-features.
73
-	 *
74
-	 * This is for example 'versioning' and is added to the DAV: header
75
-	 * in an OPTIONS response.
76
-	 *
77
-	 * @return string[]
78
-	 */
79
-	public function getFeatures() {
80
-		// May have to be changed to be detected
81
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
-	}
83
-
84
-	/**
85
-	 * Returns a plugin name.
86
-	 *
87
-	 * Using this name other plugins will be able to access other plugins
88
-	 * using Sabre\DAV\Server::getPlugin
89
-	 *
90
-	 * @return string
91
-	 */
92
-	public function getPluginName()	{
93
-		return 'oc-calendar-publishing';
94
-	}
95
-
96
-	/**
97
-	 * This initializes the plugin.
98
-	 *
99
-	 * This function is called by Sabre\DAV\Server, after
100
-	 * addPlugin is called.
101
-	 *
102
-	 * This method should set up the required event subscriptions.
103
-	 *
104
-	 * @param Server $server
105
-	 */
106
-	public function initialize(Server $server) {
107
-		$this->server = $server;
108
-
109
-		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
111
-	}
112
-
113
-	public function propFind(PropFind $propFind, INode $node) {
114
-		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
-				if ($node->getPublishStatus()) {
117
-					// We return the publish-url only if the calendar is published.
118
-					$token = $node->getPublishStatus();
119
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
-
121
-					return new Publisher($publishUrl, true);
122
-				}
123
-			});
124
-
125
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
-				return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
-			});
128
-		}
129
-	}
130
-
131
-	/**
132
-	 * We intercept this to handle POST requests on calendars.
133
-	 *
134
-	 * @param RequestInterface $request
135
-	 * @param ResponseInterface $response
136
-	 *
137
-	 * @return void|bool
138
-	 */
139
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
-		$path = $request->getPath();
141
-
142
-		// Only handling xml
143
-		$contentType = $request->getHeader('Content-Type');
144
-		if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
-			return;
146
-		}
147
-
148
-		// Making sure the node exists
149
-		try {
150
-			$node = $this->server->tree->getNodeForPath($path);
151
-		} catch (NotFound $e) {
152
-			return;
153
-		}
154
-
155
-		$requestBody = $request->getBodyAsString();
156
-
157
-		// If this request handler could not deal with this POST request, it
158
-		// will return 'null' and other plugins get a chance to handle the
159
-		// request.
160
-		//
161
-		// However, we already requested the full body. This is a problem,
162
-		// because a body can only be read once. This is why we preemptively
163
-		// re-populated the request body with the existing data.
164
-		$request->setBody($requestBody);
165
-
166
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
-
168
-		switch ($documentType) {
169
-
170
-			case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
-
172
-			// We can only deal with IShareableCalendar objects
173
-			if (!$node instanceof Calendar) {
174
-				return;
175
-			}
176
-			$this->server->transactionType = 'post-publish-calendar';
177
-
178
-			// Getting ACL info
179
-			$acl = $this->server->getPlugin('acl');
180
-
181
-			// If there's no ACL support, we allow everything
182
-			if ($acl) {
183
-				$acl->checkPrivileges($path, '{DAV:}write');
184
-			}
185
-
186
-			$node->setPublishStatus(true);
187
-
188
-			// iCloud sends back the 202, so we will too.
189
-			$response->setStatus(202);
190
-
191
-			// Adding this because sending a response body may cause issues,
192
-			// and I wanted some type of indicator the response was handled.
193
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
194
-
195
-			// Breaking the event chain
196
-			return false;
197
-
198
-			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
-
200
-			// We can only deal with IShareableCalendar objects
201
-			if (!$node instanceof Calendar) {
202
-				return;
203
-			}
204
-			$this->server->transactionType = 'post-unpublish-calendar';
205
-
206
-			// Getting ACL info
207
-			$acl = $this->server->getPlugin('acl');
208
-
209
-			// If there's no ACL support, we allow everything
210
-			if ($acl) {
211
-				$acl->checkPrivileges($path, '{DAV:}write');
212
-			}
213
-
214
-			$node->setPublishStatus(false);
215
-
216
-			$response->setStatus(200);
217
-
218
-			// Adding this because sending a response body may cause issues,
219
-			// and I wanted some type of indicator the response was handled.
220
-			$response->setHeader('X-Sabre-Status', 'everything-went-well');
221
-
222
-			// Breaking the event chain
223
-			return false;
37
+    const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
38
+
39
+    /**
40
+     * Reference to SabreDAV server object.
41
+     *
42
+     * @var \Sabre\DAV\Server
43
+     */
44
+    protected $server;
45
+
46
+    /**
47
+     * Config instance to get instance secret.
48
+     *
49
+     * @var IConfig
50
+     */
51
+    protected $config;
52
+
53
+    /**
54
+     * URL Generator for absolute URLs.
55
+     *
56
+     * @var IURLGenerator
57
+     */
58
+    protected $urlGenerator;
59
+
60
+    /**
61
+     * PublishPlugin constructor.
62
+     *
63
+     * @param IConfig $config
64
+     * @param IURLGenerator $urlGenerator
65
+     */
66
+    public function __construct(IConfig $config, IURLGenerator $urlGenerator) {
67
+        $this->config = $config;
68
+        $this->urlGenerator = $urlGenerator;
69
+    }
70
+
71
+    /**
72
+     * This method should return a list of server-features.
73
+     *
74
+     * This is for example 'versioning' and is added to the DAV: header
75
+     * in an OPTIONS response.
76
+     *
77
+     * @return string[]
78
+     */
79
+    public function getFeatures() {
80
+        // May have to be changed to be detected
81
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
82
+    }
83
+
84
+    /**
85
+     * Returns a plugin name.
86
+     *
87
+     * Using this name other plugins will be able to access other plugins
88
+     * using Sabre\DAV\Server::getPlugin
89
+     *
90
+     * @return string
91
+     */
92
+    public function getPluginName()	{
93
+        return 'oc-calendar-publishing';
94
+    }
95
+
96
+    /**
97
+     * This initializes the plugin.
98
+     *
99
+     * This function is called by Sabre\DAV\Server, after
100
+     * addPlugin is called.
101
+     *
102
+     * This method should set up the required event subscriptions.
103
+     *
104
+     * @param Server $server
105
+     */
106
+    public function initialize(Server $server) {
107
+        $this->server = $server;
108
+
109
+        $this->server->on('method:POST', [$this, 'httpPost']);
110
+        $this->server->on('propFind',    [$this, 'propFind']);
111
+    }
112
+
113
+    public function propFind(PropFind $propFind, INode $node) {
114
+        if ($node instanceof Calendar) {
115
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
116
+                if ($node->getPublishStatus()) {
117
+                    // We return the publish-url only if the calendar is published.
118
+                    $token = $node->getPublishStatus();
119
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
120
+
121
+                    return new Publisher($publishUrl, true);
122
+                }
123
+            });
124
+
125
+            $propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
126
+                return new AllowedSharingModes(!$node->isSubscription(), !$node->isSubscription());
127
+            });
128
+        }
129
+    }
130
+
131
+    /**
132
+     * We intercept this to handle POST requests on calendars.
133
+     *
134
+     * @param RequestInterface $request
135
+     * @param ResponseInterface $response
136
+     *
137
+     * @return void|bool
138
+     */
139
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
140
+        $path = $request->getPath();
141
+
142
+        // Only handling xml
143
+        $contentType = $request->getHeader('Content-Type');
144
+        if (strpos($contentType, 'application/xml') === false && strpos($contentType, 'text/xml') === false) {
145
+            return;
146
+        }
147
+
148
+        // Making sure the node exists
149
+        try {
150
+            $node = $this->server->tree->getNodeForPath($path);
151
+        } catch (NotFound $e) {
152
+            return;
153
+        }
154
+
155
+        $requestBody = $request->getBodyAsString();
156
+
157
+        // If this request handler could not deal with this POST request, it
158
+        // will return 'null' and other plugins get a chance to handle the
159
+        // request.
160
+        //
161
+        // However, we already requested the full body. This is a problem,
162
+        // because a body can only be read once. This is why we preemptively
163
+        // re-populated the request body with the existing data.
164
+        $request->setBody($requestBody);
165
+
166
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
167
+
168
+        switch ($documentType) {
169
+
170
+            case '{'.self::NS_CALENDARSERVER.'}publish-calendar' :
171
+
172
+            // We can only deal with IShareableCalendar objects
173
+            if (!$node instanceof Calendar) {
174
+                return;
175
+            }
176
+            $this->server->transactionType = 'post-publish-calendar';
177
+
178
+            // Getting ACL info
179
+            $acl = $this->server->getPlugin('acl');
180
+
181
+            // If there's no ACL support, we allow everything
182
+            if ($acl) {
183
+                $acl->checkPrivileges($path, '{DAV:}write');
184
+            }
185
+
186
+            $node->setPublishStatus(true);
187
+
188
+            // iCloud sends back the 202, so we will too.
189
+            $response->setStatus(202);
190
+
191
+            // Adding this because sending a response body may cause issues,
192
+            // and I wanted some type of indicator the response was handled.
193
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
194
+
195
+            // Breaking the event chain
196
+            return false;
197
+
198
+            case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar' :
199
+
200
+            // We can only deal with IShareableCalendar objects
201
+            if (!$node instanceof Calendar) {
202
+                return;
203
+            }
204
+            $this->server->transactionType = 'post-unpublish-calendar';
205
+
206
+            // Getting ACL info
207
+            $acl = $this->server->getPlugin('acl');
208
+
209
+            // If there's no ACL support, we allow everything
210
+            if ($acl) {
211
+                $acl->checkPrivileges($path, '{DAV:}write');
212
+            }
213
+
214
+            $node->setPublishStatus(false);
215
+
216
+            $response->setStatus(200);
217
+
218
+            // Adding this because sending a response body may cause issues,
219
+            // and I wanted some type of indicator the response was handled.
220
+            $response->setHeader('X-Sabre-Status', 'everything-went-well');
221
+
222
+            // Breaking the event chain
223
+            return false;
224 224
 
225
-		}
226
-	}
225
+        }
226
+    }
227 227
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 *
90 90
 	 * @return string
91 91
 	 */
92
-	public function getPluginName()	{
92
+	public function getPluginName() {
93 93
 		return 'oc-calendar-publishing';
94 94
 	}
95 95
 
@@ -107,12 +107,12 @@  discard block
 block discarded – undo
107 107
 		$this->server = $server;
108 108
 
109 109
 		$this->server->on('method:POST', [$this, 'httpPost']);
110
-		$this->server->on('propFind',    [$this, 'propFind']);
110
+		$this->server->on('propFind', [$this, 'propFind']);
111 111
 	}
112 112
 
113 113
 	public function propFind(PropFind $propFind, INode $node) {
114 114
 		if ($node instanceof Calendar) {
115
-			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function () use ($node) {
115
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
116 116
 				if ($node->getPublishStatus()) {
117 117
 					// We return the publish-url only if the calendar is published.
118 118
 					$token = $node->getPublishStatus();
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/AddressBookRoot.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
 
31 31
 	/**
32 32
 	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
33
+	 * @param CardDavBackend $carddavBackend
34 34
 	 * @param string $principalPrefix
35 35
 	 */
36 36
 	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,46 +25,46 @@
 block discarded – undo
25 25
 
26 26
 class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot {
27 27
 
28
-	/** @var IL10N */
29
-	protected $l10n;
28
+    /** @var IL10N */
29
+    protected $l10n;
30 30
 
31
-	/**
32
-	 * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
-	 * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
-	 * @param string $principalPrefix
35
-	 */
36
-	public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
-		parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
-		$this->l10n = \OC::$server->getL10N('dav');
39
-	}
31
+    /**
32
+     * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend
33
+     * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend
34
+     * @param string $principalPrefix
35
+     */
36
+    public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, $principalPrefix = 'principals') {
37
+        parent::__construct($principalBackend, $carddavBackend, $principalPrefix);
38
+        $this->l10n = \OC::$server->getL10N('dav');
39
+    }
40 40
 
41
-	/**
42
-	 * This method returns a node for a principal.
43
-	 *
44
-	 * The passed array contains principal information, and is guaranteed to
45
-	 * at least contain a uri item. Other properties may or may not be
46
-	 * supplied by the authentication backend.
47
-	 *
48
-	 * @param array $principal
49
-	 * @return \Sabre\DAV\INode
50
-	 */
51
-	function getChildForPrincipal(array $principal) {
41
+    /**
42
+     * This method returns a node for a principal.
43
+     *
44
+     * The passed array contains principal information, and is guaranteed to
45
+     * at least contain a uri item. Other properties may or may not be
46
+     * supplied by the authentication backend.
47
+     *
48
+     * @param array $principal
49
+     * @return \Sabre\DAV\INode
50
+     */
51
+    function getChildForPrincipal(array $principal) {
52 52
 
53
-		return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
53
+        return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->l10n);
54 54
 
55
-	}
55
+    }
56 56
 
57
-	function getName() {
57
+    function getName() {
58 58
 
59
-		if ($this->principalPrefix === 'principals') {
60
-			return parent::getName();
61
-		}
62
-		// Grabbing all the components of the principal path.
63
-		$parts = explode('/', $this->principalPrefix);
59
+        if ($this->principalPrefix === 'principals') {
60
+            return parent::getName();
61
+        }
62
+        // Grabbing all the components of the principal path.
63
+        $parts = explode('/', $this->principalPrefix);
64 64
 
65
-		// We are only interested in the second part.
66
-		return $parts[1];
65
+        // We are only interested in the second part.
66
+        return $parts[1];
67 67
 
68
-	}
68
+    }
69 69
 
70 70
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -770,7 +770,7 @@
 block discarded – undo
770 770
 
771 771
 	/**
772 772
 	 * @param Share[] $shares
773
-	 * @param $userId
773
+	 * @param string $userId
774 774
 	 * @return Share[] The updates shares if no update is found for a share return the original
775 775
 	 */
776 776
 	private function resolveGroupShares($shares, $userId) {
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -287,7 +287,7 @@  discard block
 block discarded – undo
287 287
 			->orderBy('id');
288 288
 
289 289
 		$cursor = $qb->execute();
290
-		while($data = $cursor->fetch()) {
290
+		while ($data = $cursor->fetch()) {
291 291
 			$children[] = $this->createShare($data);
292 292
 		}
293 293
 		$cursor->closeCursor();
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
 			$user = $this->userManager->get($recipient);
333 333
 
334 334
 			if (is_null($group)) {
335
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
335
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
336 336
 			}
337 337
 
338 338
 			if (!$group->inGroup($user)) {
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 			);
493 493
 		}
494 494
 
495
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
495
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496 496
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
497 497
 
498 498
 		$qb->orderBy('id');
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
 
549 549
 		$cursor = $qb->execute();
550 550
 		$shares = [];
551
-		while($data = $cursor->fetch()) {
551
+		while ($data = $cursor->fetch()) {
552 552
 			$shares[] = $this->createShare($data);
553 553
 		}
554 554
 		$cursor->closeCursor();
@@ -627,7 +627,7 @@  discard block
 block discarded – undo
627 627
 			->execute();
628 628
 
629 629
 		$shares = [];
630
-		while($data = $cursor->fetch()) {
630
+		while ($data = $cursor->fetch()) {
631 631
 			$shares[] = $this->createShare($data);
632 632
 		}
633 633
 		$cursor->closeCursor();
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 
699 699
 			$cursor = $qb->execute();
700 700
 
701
-			while($data = $cursor->fetch()) {
701
+			while ($data = $cursor->fetch()) {
702 702
 				if ($this->isAccessibleResult($data)) {
703 703
 					$shares[] = $this->createShare($data);
704 704
 				}
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
 			$shares2 = [];
714 714
 
715 715
 			$start = 0;
716
-			while(true) {
716
+			while (true) {
717 717
 				$groups = array_slice($allGroups, $start, 100);
718 718
 				$start += 100;
719 719
 
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 					));
759 759
 
760 760
 				$cursor = $qb->execute();
761
-				while($data = $cursor->fetch()) {
761
+				while ($data = $cursor->fetch()) {
762 762
 					if ($offset > 0) {
763 763
 						$offset--;
764 764
 						continue;
@@ -827,14 +827,14 @@  discard block
 block discarded – undo
827 827
 	 */
828 828
 	private function createShare($data) {
829 829
 		$share = new Share($this->rootFolder, $this->userManager);
830
-		$share->setId((int)$data['id'])
831
-			->setShareType((int)$data['share_type'])
832
-			->setPermissions((int)$data['permissions'])
830
+		$share->setId((int) $data['id'])
831
+			->setShareType((int) $data['share_type'])
832
+			->setPermissions((int) $data['permissions'])
833 833
 			->setTarget($data['file_target'])
834
-			->setMailSend((bool)$data['mail_send']);
834
+			->setMailSend((bool) $data['mail_send']);
835 835
 
836 836
 		$shareTime = new \DateTime();
837
-		$shareTime->setTimestamp((int)$data['stime']);
837
+		$shareTime->setTimestamp((int) $data['stime']);
838 838
 		$share->setShareTime($shareTime);
839 839
 
840 840
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
 		$share->setSharedBy($data['uid_initiator']);
850 850
 		$share->setShareOwner($data['uid_owner']);
851 851
 
852
-		$share->setNodeId((int)$data['file_source']);
852
+		$share->setNodeId((int) $data['file_source']);
853 853
 		$share->setNodeType($data['item_type']);
854 854
 
855 855
 		if ($data['expiration'] !== null) {
@@ -879,7 +879,7 @@  discard block
 block discarded – undo
879 879
 		$result = [];
880 880
 
881 881
 		$start = 0;
882
-		while(true) {
882
+		while (true) {
883 883
 			/** @var Share[] $shareSlice */
884 884
 			$shareSlice = array_slice($shares, $start, 100);
885 885
 			$start += 100;
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 			$shareMap = [];
895 895
 
896 896
 			foreach ($shareSlice as $share) {
897
-				$ids[] = (int)$share->getId();
897
+				$ids[] = (int) $share->getId();
898 898
 				$shareMap[$share->getId()] = $share;
899 899
 			}
900 900
 
@@ -911,8 +911,8 @@  discard block
 block discarded – undo
911 911
 
912 912
 			$stmt = $query->execute();
913 913
 
914
-			while($data = $stmt->fetch()) {
915
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
914
+			while ($data = $stmt->fetch()) {
915
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
916 916
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
917 917
 			}
918 918
 
@@ -1009,8 +1009,8 @@  discard block
 block discarded – undo
1009 1009
 
1010 1010
 		$cursor = $qb->execute();
1011 1011
 		$ids = [];
1012
-		while($row = $cursor->fetch()) {
1013
-			$ids[] = (int)$row['id'];
1012
+		while ($row = $cursor->fetch()) {
1013
+			$ids[] = (int) $row['id'];
1014 1014
 		}
1015 1015
 		$cursor->closeCursor();
1016 1016
 
@@ -1052,8 +1052,8 @@  discard block
 block discarded – undo
1052 1052
 
1053 1053
 		$cursor = $qb->execute();
1054 1054
 		$ids = [];
1055
-		while($row = $cursor->fetch()) {
1056
-			$ids[] = (int)$row['id'];
1055
+		while ($row = $cursor->fetch()) {
1056
+			$ids[] = (int) $row['id'];
1057 1057
 		}
1058 1058
 		$cursor->closeCursor();
1059 1059
 
@@ -1107,8 +1107,8 @@  discard block
 block discarded – undo
1107 1107
 
1108 1108
 		$users = [];
1109 1109
 		$link = false;
1110
-		while($row = $cursor->fetch()) {
1111
-			$type = (int)$row['share_type'];
1110
+		while ($row = $cursor->fetch()) {
1111
+			$type = (int) $row['share_type'];
1112 1112
 			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1113 1113
 				$uid = $row['share_with'];
1114 1114
 				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
Please login to merge, or discard this patch.
Indentation   +1106 added lines, -1106 removed lines patch added patch discarded remove patch
@@ -52,1143 +52,1143 @@
 block discarded – undo
52 52
  */
53 53
 class DefaultShareProvider implements IShareProvider {
54 54
 
55
-	// Special share type for user modified group shares
56
-	const SHARE_TYPE_USERGROUP = 2;
57
-
58
-	/** @var IDBConnection */
59
-	private $dbConn;
60
-
61
-	/** @var IUserManager */
62
-	private $userManager;
63
-
64
-	/** @var IGroupManager */
65
-	private $groupManager;
66
-
67
-	/** @var IRootFolder */
68
-	private $rootFolder;
69
-
70
-	/**
71
-	 * DefaultShareProvider constructor.
72
-	 *
73
-	 * @param IDBConnection $connection
74
-	 * @param IUserManager $userManager
75
-	 * @param IGroupManager $groupManager
76
-	 * @param IRootFolder $rootFolder
77
-	 */
78
-	public function __construct(
79
-			IDBConnection $connection,
80
-			IUserManager $userManager,
81
-			IGroupManager $groupManager,
82
-			IRootFolder $rootFolder) {
83
-		$this->dbConn = $connection;
84
-		$this->userManager = $userManager;
85
-		$this->groupManager = $groupManager;
86
-		$this->rootFolder = $rootFolder;
87
-	}
88
-
89
-	/**
90
-	 * Return the identifier of this provider.
91
-	 *
92
-	 * @return string Containing only [a-zA-Z0-9]
93
-	 */
94
-	public function identifier() {
95
-		return 'ocinternal';
96
-	}
97
-
98
-	/**
99
-	 * Share a path
100
-	 *
101
-	 * @param \OCP\Share\IShare $share
102
-	 * @return \OCP\Share\IShare The share object
103
-	 * @throws ShareNotFound
104
-	 * @throws \Exception
105
-	 */
106
-	public function create(\OCP\Share\IShare $share) {
107
-		$qb = $this->dbConn->getQueryBuilder();
108
-
109
-		$qb->insert('share');
110
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
-
112
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
-			//Set the UID of the user we share with
114
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
-			//Set the GID of the group we share with
117
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
-			//Set the token of the share
120
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
-
122
-			//If a password is set store it
123
-			if ($share->getPassword() !== null) {
124
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
-			}
126
-
127
-			//If an expiration date is set store it
128
-			if ($share->getExpirationDate() !== null) {
129
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
-			}
131
-
132
-			if (method_exists($share, 'getParent')) {
133
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
-			}
135
-		} else {
136
-			throw new \Exception('invalid share type!');
137
-		}
138
-
139
-		// Set what is shares
140
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
141
-		if ($share->getNode() instanceof \OCP\Files\File) {
142
-			$qb->setParameter('itemType', 'file');
143
-		} else {
144
-			$qb->setParameter('itemType', 'folder');
145
-		}
146
-
147
-		// Set the file id
148
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
-
151
-		// set the permissions
152
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
-
154
-		// Set who created this share
155
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
-
157
-		// Set who is the owner of this file/folder (and this the owner of the share)
158
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
-
160
-		// Set the file target
161
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
-
163
-		// Set the time this share was created
164
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
165
-
166
-		// insert the data and fetch the id of the share
167
-		$this->dbConn->beginTransaction();
168
-		$qb->execute();
169
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
170
-
171
-		// Now fetch the inserted share and create a complete share object
172
-		$qb = $this->dbConn->getQueryBuilder();
173
-		$qb->select('*')
174
-			->from('share')
175
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
-
177
-		$cursor = $qb->execute();
178
-		$data = $cursor->fetch();
179
-		$this->dbConn->commit();
180
-		$cursor->closeCursor();
181
-
182
-		if ($data === false) {
183
-			throw new ShareNotFound();
184
-		}
185
-
186
-		$mailSendValue = $share->getMailSend();
187
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
-
189
-		$share = $this->createShare($data);
190
-		return $share;
191
-	}
192
-
193
-	/**
194
-	 * Update a share
195
-	 *
196
-	 * @param \OCP\Share\IShare $share
197
-	 * @return \OCP\Share\IShare The share object
198
-	 */
199
-	public function update(\OCP\Share\IShare $share) {
200
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
-			/*
55
+    // Special share type for user modified group shares
56
+    const SHARE_TYPE_USERGROUP = 2;
57
+
58
+    /** @var IDBConnection */
59
+    private $dbConn;
60
+
61
+    /** @var IUserManager */
62
+    private $userManager;
63
+
64
+    /** @var IGroupManager */
65
+    private $groupManager;
66
+
67
+    /** @var IRootFolder */
68
+    private $rootFolder;
69
+
70
+    /**
71
+     * DefaultShareProvider constructor.
72
+     *
73
+     * @param IDBConnection $connection
74
+     * @param IUserManager $userManager
75
+     * @param IGroupManager $groupManager
76
+     * @param IRootFolder $rootFolder
77
+     */
78
+    public function __construct(
79
+            IDBConnection $connection,
80
+            IUserManager $userManager,
81
+            IGroupManager $groupManager,
82
+            IRootFolder $rootFolder) {
83
+        $this->dbConn = $connection;
84
+        $this->userManager = $userManager;
85
+        $this->groupManager = $groupManager;
86
+        $this->rootFolder = $rootFolder;
87
+    }
88
+
89
+    /**
90
+     * Return the identifier of this provider.
91
+     *
92
+     * @return string Containing only [a-zA-Z0-9]
93
+     */
94
+    public function identifier() {
95
+        return 'ocinternal';
96
+    }
97
+
98
+    /**
99
+     * Share a path
100
+     *
101
+     * @param \OCP\Share\IShare $share
102
+     * @return \OCP\Share\IShare The share object
103
+     * @throws ShareNotFound
104
+     * @throws \Exception
105
+     */
106
+    public function create(\OCP\Share\IShare $share) {
107
+        $qb = $this->dbConn->getQueryBuilder();
108
+
109
+        $qb->insert('share');
110
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
111
+
112
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
113
+            //Set the UID of the user we share with
114
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
115
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
116
+            //Set the GID of the group we share with
117
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
118
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
119
+            //Set the token of the share
120
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
121
+
122
+            //If a password is set store it
123
+            if ($share->getPassword() !== null) {
124
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
125
+            }
126
+
127
+            //If an expiration date is set store it
128
+            if ($share->getExpirationDate() !== null) {
129
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
130
+            }
131
+
132
+            if (method_exists($share, 'getParent')) {
133
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
134
+            }
135
+        } else {
136
+            throw new \Exception('invalid share type!');
137
+        }
138
+
139
+        // Set what is shares
140
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
141
+        if ($share->getNode() instanceof \OCP\Files\File) {
142
+            $qb->setParameter('itemType', 'file');
143
+        } else {
144
+            $qb->setParameter('itemType', 'folder');
145
+        }
146
+
147
+        // Set the file id
148
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
149
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
150
+
151
+        // set the permissions
152
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
153
+
154
+        // Set who created this share
155
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
156
+
157
+        // Set who is the owner of this file/folder (and this the owner of the share)
158
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
159
+
160
+        // Set the file target
161
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
162
+
163
+        // Set the time this share was created
164
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
165
+
166
+        // insert the data and fetch the id of the share
167
+        $this->dbConn->beginTransaction();
168
+        $qb->execute();
169
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
170
+
171
+        // Now fetch the inserted share and create a complete share object
172
+        $qb = $this->dbConn->getQueryBuilder();
173
+        $qb->select('*')
174
+            ->from('share')
175
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
176
+
177
+        $cursor = $qb->execute();
178
+        $data = $cursor->fetch();
179
+        $this->dbConn->commit();
180
+        $cursor->closeCursor();
181
+
182
+        if ($data === false) {
183
+            throw new ShareNotFound();
184
+        }
185
+
186
+        $mailSendValue = $share->getMailSend();
187
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
188
+
189
+        $share = $this->createShare($data);
190
+        return $share;
191
+    }
192
+
193
+    /**
194
+     * Update a share
195
+     *
196
+     * @param \OCP\Share\IShare $share
197
+     * @return \OCP\Share\IShare The share object
198
+     */
199
+    public function update(\OCP\Share\IShare $share) {
200
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
201
+            /*
202 202
 			 * We allow updating the recipient on user shares.
203 203
 			 */
204
-			$qb = $this->dbConn->getQueryBuilder();
205
-			$qb->update('share')
206
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
-				->execute();
215
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
-			$qb = $this->dbConn->getQueryBuilder();
217
-			$qb->update('share')
218
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
-				->execute();
226
-
227
-			/*
204
+            $qb = $this->dbConn->getQueryBuilder();
205
+            $qb->update('share')
206
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
207
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
208
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
209
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
210
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
211
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
212
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
213
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
214
+                ->execute();
215
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
216
+            $qb = $this->dbConn->getQueryBuilder();
217
+            $qb->update('share')
218
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
219
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
220
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
221
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
222
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
223
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
224
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
225
+                ->execute();
226
+
227
+            /*
228 228
 			 * Update all user defined group shares
229 229
 			 */
230
-			$qb = $this->dbConn->getQueryBuilder();
231
-			$qb->update('share')
232
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
234
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
235
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
236
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
237
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
238
-				->execute();
239
-
240
-			/*
230
+            $qb = $this->dbConn->getQueryBuilder();
231
+            $qb->update('share')
232
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
233
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
234
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
235
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
236
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
237
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
238
+                ->execute();
239
+
240
+            /*
241 241
 			 * Now update the permissions for all children that have not set it to 0
242 242
 			 */
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
246
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
247
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
248
-				->execute();
249
-
250
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
251
-			$qb = $this->dbConn->getQueryBuilder();
252
-			$qb->update('share')
253
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
254
-				->set('password', $qb->createNamedParameter($share->getPassword()))
255
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
256
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
257
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
258
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
259
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
260
-				->set('token', $qb->createNamedParameter($share->getToken()))
261
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
262
-				->execute();
263
-		}
264
-
265
-		return $share;
266
-	}
267
-
268
-	/**
269
-	 * Get all children of this share
270
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
271
-	 *
272
-	 * @param \OCP\Share\IShare $parent
273
-	 * @return \OCP\Share\IShare[]
274
-	 */
275
-	public function getChildren(\OCP\Share\IShare $parent) {
276
-		$children = [];
277
-
278
-		$qb = $this->dbConn->getQueryBuilder();
279
-		$qb->select('*')
280
-			->from('share')
281
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
282
-			->andWhere(
283
-				$qb->expr()->in(
284
-					'share_type',
285
-					$qb->createNamedParameter([
286
-						\OCP\Share::SHARE_TYPE_USER,
287
-						\OCP\Share::SHARE_TYPE_GROUP,
288
-						\OCP\Share::SHARE_TYPE_LINK,
289
-					], IQueryBuilder::PARAM_INT_ARRAY)
290
-				)
291
-			)
292
-			->andWhere($qb->expr()->orX(
293
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
294
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
295
-			))
296
-			->orderBy('id');
297
-
298
-		$cursor = $qb->execute();
299
-		while($data = $cursor->fetch()) {
300
-			$children[] = $this->createShare($data);
301
-		}
302
-		$cursor->closeCursor();
303
-
304
-		return $children;
305
-	}
306
-
307
-	/**
308
-	 * Delete a share
309
-	 *
310
-	 * @param \OCP\Share\IShare $share
311
-	 */
312
-	public function delete(\OCP\Share\IShare $share) {
313
-		$qb = $this->dbConn->getQueryBuilder();
314
-		$qb->delete('share')
315
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
316
-
317
-		/*
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
246
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
247
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
248
+                ->execute();
249
+
250
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
251
+            $qb = $this->dbConn->getQueryBuilder();
252
+            $qb->update('share')
253
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
254
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
255
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
256
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
257
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
258
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
259
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
260
+                ->set('token', $qb->createNamedParameter($share->getToken()))
261
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
262
+                ->execute();
263
+        }
264
+
265
+        return $share;
266
+    }
267
+
268
+    /**
269
+     * Get all children of this share
270
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
271
+     *
272
+     * @param \OCP\Share\IShare $parent
273
+     * @return \OCP\Share\IShare[]
274
+     */
275
+    public function getChildren(\OCP\Share\IShare $parent) {
276
+        $children = [];
277
+
278
+        $qb = $this->dbConn->getQueryBuilder();
279
+        $qb->select('*')
280
+            ->from('share')
281
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
282
+            ->andWhere(
283
+                $qb->expr()->in(
284
+                    'share_type',
285
+                    $qb->createNamedParameter([
286
+                        \OCP\Share::SHARE_TYPE_USER,
287
+                        \OCP\Share::SHARE_TYPE_GROUP,
288
+                        \OCP\Share::SHARE_TYPE_LINK,
289
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
290
+                )
291
+            )
292
+            ->andWhere($qb->expr()->orX(
293
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
294
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
295
+            ))
296
+            ->orderBy('id');
297
+
298
+        $cursor = $qb->execute();
299
+        while($data = $cursor->fetch()) {
300
+            $children[] = $this->createShare($data);
301
+        }
302
+        $cursor->closeCursor();
303
+
304
+        return $children;
305
+    }
306
+
307
+    /**
308
+     * Delete a share
309
+     *
310
+     * @param \OCP\Share\IShare $share
311
+     */
312
+    public function delete(\OCP\Share\IShare $share) {
313
+        $qb = $this->dbConn->getQueryBuilder();
314
+        $qb->delete('share')
315
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
316
+
317
+        /*
318 318
 		 * If the share is a group share delete all possible
319 319
 		 * user defined groups shares.
320 320
 		 */
321
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
322
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
323
-		}
324
-
325
-		$qb->execute();
326
-	}
327
-
328
-	/**
329
-	 * Unshare a share from the recipient. If this is a group share
330
-	 * this means we need a special entry in the share db.
331
-	 *
332
-	 * @param \OCP\Share\IShare $share
333
-	 * @param string $recipient UserId of recipient
334
-	 * @throws BackendError
335
-	 * @throws ProviderException
336
-	 */
337
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
338
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
339
-
340
-			$group = $this->groupManager->get($share->getSharedWith());
341
-			$user = $this->userManager->get($recipient);
342
-
343
-			if (is_null($group)) {
344
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
345
-			}
346
-
347
-			if (!$group->inGroup($user)) {
348
-				throw new ProviderException('Recipient not in receiving group');
349
-			}
350
-
351
-			// Try to fetch user specific share
352
-			$qb = $this->dbConn->getQueryBuilder();
353
-			$stmt = $qb->select('*')
354
-				->from('share')
355
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
356
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
357
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
358
-				->andWhere($qb->expr()->orX(
359
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
360
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
361
-				))
362
-				->execute();
363
-
364
-			$data = $stmt->fetch();
365
-
366
-			/*
321
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
322
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
323
+        }
324
+
325
+        $qb->execute();
326
+    }
327
+
328
+    /**
329
+     * Unshare a share from the recipient. If this is a group share
330
+     * this means we need a special entry in the share db.
331
+     *
332
+     * @param \OCP\Share\IShare $share
333
+     * @param string $recipient UserId of recipient
334
+     * @throws BackendError
335
+     * @throws ProviderException
336
+     */
337
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
338
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
339
+
340
+            $group = $this->groupManager->get($share->getSharedWith());
341
+            $user = $this->userManager->get($recipient);
342
+
343
+            if (is_null($group)) {
344
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
345
+            }
346
+
347
+            if (!$group->inGroup($user)) {
348
+                throw new ProviderException('Recipient not in receiving group');
349
+            }
350
+
351
+            // Try to fetch user specific share
352
+            $qb = $this->dbConn->getQueryBuilder();
353
+            $stmt = $qb->select('*')
354
+                ->from('share')
355
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
356
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
357
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
358
+                ->andWhere($qb->expr()->orX(
359
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
360
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
361
+                ))
362
+                ->execute();
363
+
364
+            $data = $stmt->fetch();
365
+
366
+            /*
367 367
 			 * Check if there already is a user specific group share.
368 368
 			 * If there is update it (if required).
369 369
 			 */
370
-			if ($data === false) {
371
-				$qb = $this->dbConn->getQueryBuilder();
372
-
373
-				$type = $share->getNodeType();
374
-
375
-				//Insert new share
376
-				$qb->insert('share')
377
-					->values([
378
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
379
-						'share_with' => $qb->createNamedParameter($recipient),
380
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
381
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
382
-						'parent' => $qb->createNamedParameter($share->getId()),
383
-						'item_type' => $qb->createNamedParameter($type),
384
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
385
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
386
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
387
-						'permissions' => $qb->createNamedParameter(0),
388
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
389
-					])->execute();
390
-
391
-			} else if ($data['permissions'] !== 0) {
392
-
393
-				// Update existing usergroup share
394
-				$qb = $this->dbConn->getQueryBuilder();
395
-				$qb->update('share')
396
-					->set('permissions', $qb->createNamedParameter(0))
397
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
398
-					->execute();
399
-			}
400
-
401
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
402
-
403
-			if ($share->getSharedWith() !== $recipient) {
404
-				throw new ProviderException('Recipient does not match');
405
-			}
406
-
407
-			// We can just delete user and link shares
408
-			$this->delete($share);
409
-		} else {
410
-			throw new ProviderException('Invalid shareType');
411
-		}
412
-	}
413
-
414
-	/**
415
-	 * @inheritdoc
416
-	 */
417
-	public function move(\OCP\Share\IShare $share, $recipient) {
418
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
419
-			// Just update the target
420
-			$qb = $this->dbConn->getQueryBuilder();
421
-			$qb->update('share')
422
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
423
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
424
-				->execute();
425
-
426
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
427
-
428
-			// Check if there is a usergroup share
429
-			$qb = $this->dbConn->getQueryBuilder();
430
-			$stmt = $qb->select('id')
431
-				->from('share')
432
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
433
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
434
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
435
-				->andWhere($qb->expr()->orX(
436
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
437
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
438
-				))
439
-				->setMaxResults(1)
440
-				->execute();
441
-
442
-			$data = $stmt->fetch();
443
-			$stmt->closeCursor();
444
-
445
-			if ($data === false) {
446
-				// No usergroup share yet. Create one.
447
-				$qb = $this->dbConn->getQueryBuilder();
448
-				$qb->insert('share')
449
-					->values([
450
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
451
-						'share_with' => $qb->createNamedParameter($recipient),
452
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
453
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
454
-						'parent' => $qb->createNamedParameter($share->getId()),
455
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
456
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
457
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
458
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
459
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
460
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
461
-					])->execute();
462
-			} else {
463
-				// Already a usergroup share. Update it.
464
-				$qb = $this->dbConn->getQueryBuilder();
465
-				$qb->update('share')
466
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
467
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
468
-					->execute();
469
-			}
470
-		}
471
-
472
-		return $share;
473
-	}
474
-
475
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
476
-		$qb = $this->dbConn->getQueryBuilder();
477
-		$qb->select('*')
478
-			->from('share', 's')
479
-			->andWhere($qb->expr()->orX(
480
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
481
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
482
-			));
483
-
484
-		$qb->andWhere($qb->expr()->orX(
485
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
486
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
487
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
488
-		));
489
-
490
-		/**
491
-		 * Reshares for this user are shares where they are the owner.
492
-		 */
493
-		if ($reshares === false) {
494
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
495
-		} else {
496
-			$qb->andWhere(
497
-				$qb->expr()->orX(
498
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
-				)
501
-			);
502
-		}
503
-
504
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
505
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
506
-
507
-		$qb->orderBy('id');
508
-
509
-		$cursor = $qb->execute();
510
-		$shares = [];
511
-		while ($data = $cursor->fetch()) {
512
-			$shares[$data['fileid']][] = $this->createShare($data);
513
-		}
514
-		$cursor->closeCursor();
515
-
516
-		return $shares;
517
-	}
518
-
519
-	/**
520
-	 * @inheritdoc
521
-	 */
522
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
523
-		$qb = $this->dbConn->getQueryBuilder();
524
-		$qb->select('*')
525
-			->from('share')
526
-			->andWhere($qb->expr()->orX(
527
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
528
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
529
-			));
530
-
531
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
532
-
533
-		/**
534
-		 * Reshares for this user are shares where they are the owner.
535
-		 */
536
-		if ($reshares === false) {
537
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
538
-		} else {
539
-			$qb->andWhere(
540
-				$qb->expr()->orX(
541
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
542
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
543
-				)
544
-			);
545
-		}
546
-
547
-		if ($node !== null) {
548
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
549
-		}
550
-
551
-		if ($limit !== -1) {
552
-			$qb->setMaxResults($limit);
553
-		}
554
-
555
-		$qb->setFirstResult($offset);
556
-		$qb->orderBy('id');
557
-
558
-		$cursor = $qb->execute();
559
-		$shares = [];
560
-		while($data = $cursor->fetch()) {
561
-			$shares[] = $this->createShare($data);
562
-		}
563
-		$cursor->closeCursor();
564
-
565
-		return $shares;
566
-	}
567
-
568
-	/**
569
-	 * @inheritdoc
570
-	 */
571
-	public function getShareById($id, $recipientId = null) {
572
-		$qb = $this->dbConn->getQueryBuilder();
573
-
574
-		$qb->select('*')
575
-			->from('share')
576
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
577
-			->andWhere(
578
-				$qb->expr()->in(
579
-					'share_type',
580
-					$qb->createNamedParameter([
581
-						\OCP\Share::SHARE_TYPE_USER,
582
-						\OCP\Share::SHARE_TYPE_GROUP,
583
-						\OCP\Share::SHARE_TYPE_LINK,
584
-					], IQueryBuilder::PARAM_INT_ARRAY)
585
-				)
586
-			)
587
-			->andWhere($qb->expr()->orX(
588
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
589
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
590
-			));
591
-
592
-		$cursor = $qb->execute();
593
-		$data = $cursor->fetch();
594
-		$cursor->closeCursor();
595
-
596
-		if ($data === false) {
597
-			throw new ShareNotFound();
598
-		}
599
-
600
-		try {
601
-			$share = $this->createShare($data);
602
-		} catch (InvalidShare $e) {
603
-			throw new ShareNotFound();
604
-		}
605
-
606
-		// If the recipient is set for a group share resolve to that user
607
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
608
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
609
-		}
610
-
611
-		return $share;
612
-	}
613
-
614
-	/**
615
-	 * Get shares for a given path
616
-	 *
617
-	 * @param \OCP\Files\Node $path
618
-	 * @return \OCP\Share\IShare[]
619
-	 */
620
-	public function getSharesByPath(Node $path) {
621
-		$qb = $this->dbConn->getQueryBuilder();
622
-
623
-		$cursor = $qb->select('*')
624
-			->from('share')
625
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
626
-			->andWhere(
627
-				$qb->expr()->orX(
628
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
629
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
630
-				)
631
-			)
632
-			->andWhere($qb->expr()->orX(
633
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
634
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
635
-			))
636
-			->execute();
637
-
638
-		$shares = [];
639
-		while($data = $cursor->fetch()) {
640
-			$shares[] = $this->createShare($data);
641
-		}
642
-		$cursor->closeCursor();
643
-
644
-		return $shares;
645
-	}
646
-
647
-	/**
648
-	 * Returns whether the given database result can be interpreted as
649
-	 * a share with accessible file (not trashed, not deleted)
650
-	 */
651
-	private function isAccessibleResult($data) {
652
-		// exclude shares leading to deleted file entries
653
-		if ($data['fileid'] === null) {
654
-			return false;
655
-		}
656
-
657
-		// exclude shares leading to trashbin on home storages
658
-		$pathSections = explode('/', $data['path'], 2);
659
-		// FIXME: would not detect rare md5'd home storage case properly
660
-		if ($pathSections[0] !== 'files'
661
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
662
-			return false;
663
-		}
664
-		return true;
665
-	}
666
-
667
-	/**
668
-	 * @inheritdoc
669
-	 */
670
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
671
-		/** @var Share[] $shares */
672
-		$shares = [];
673
-
674
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
675
-			//Get shares directly with this user
676
-			$qb = $this->dbConn->getQueryBuilder();
677
-			$qb->select('s.*',
678
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
679
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
680
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
681
-			)
682
-				->selectAlias('st.id', 'storage_string_id')
683
-				->from('share', 's')
684
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
685
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
686
-
687
-			// Order by id
688
-			$qb->orderBy('s.id');
689
-
690
-			// Set limit and offset
691
-			if ($limit !== -1) {
692
-				$qb->setMaxResults($limit);
693
-			}
694
-			$qb->setFirstResult($offset);
695
-
696
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
697
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
698
-				->andWhere($qb->expr()->orX(
699
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
700
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
701
-				));
702
-
703
-			// Filter by node if provided
704
-			if ($node !== null) {
705
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
706
-			}
707
-
708
-			$cursor = $qb->execute();
709
-
710
-			while($data = $cursor->fetch()) {
711
-				if ($this->isAccessibleResult($data)) {
712
-					$shares[] = $this->createShare($data);
713
-				}
714
-			}
715
-			$cursor->closeCursor();
716
-
717
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
718
-			$user = $this->userManager->get($userId);
719
-			$allGroups = $this->groupManager->getUserGroups($user);
720
-
721
-			/** @var Share[] $shares2 */
722
-			$shares2 = [];
723
-
724
-			$start = 0;
725
-			while(true) {
726
-				$groups = array_slice($allGroups, $start, 100);
727
-				$start += 100;
728
-
729
-				if ($groups === []) {
730
-					break;
731
-				}
732
-
733
-				$qb = $this->dbConn->getQueryBuilder();
734
-				$qb->select('s.*',
735
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
736
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
737
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
738
-				)
739
-					->selectAlias('st.id', 'storage_string_id')
740
-					->from('share', 's')
741
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
742
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
743
-					->orderBy('s.id')
744
-					->setFirstResult(0);
745
-
746
-				if ($limit !== -1) {
747
-					$qb->setMaxResults($limit - count($shares));
748
-				}
749
-
750
-				// Filter by node if provided
751
-				if ($node !== null) {
752
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
753
-				}
754
-
755
-
756
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
757
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
758
-
759
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
760
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
761
-						$groups,
762
-						IQueryBuilder::PARAM_STR_ARRAY
763
-					)))
764
-					->andWhere($qb->expr()->orX(
765
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
766
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
767
-					));
768
-
769
-				$cursor = $qb->execute();
770
-				while($data = $cursor->fetch()) {
771
-					if ($offset > 0) {
772
-						$offset--;
773
-						continue;
774
-					}
775
-
776
-					if ($this->isAccessibleResult($data)) {
777
-						$shares2[] = $this->createShare($data);
778
-					}
779
-				}
780
-				$cursor->closeCursor();
781
-			}
782
-
783
-			/*
370
+            if ($data === false) {
371
+                $qb = $this->dbConn->getQueryBuilder();
372
+
373
+                $type = $share->getNodeType();
374
+
375
+                //Insert new share
376
+                $qb->insert('share')
377
+                    ->values([
378
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
379
+                        'share_with' => $qb->createNamedParameter($recipient),
380
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
381
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
382
+                        'parent' => $qb->createNamedParameter($share->getId()),
383
+                        'item_type' => $qb->createNamedParameter($type),
384
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
385
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
386
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
387
+                        'permissions' => $qb->createNamedParameter(0),
388
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
389
+                    ])->execute();
390
+
391
+            } else if ($data['permissions'] !== 0) {
392
+
393
+                // Update existing usergroup share
394
+                $qb = $this->dbConn->getQueryBuilder();
395
+                $qb->update('share')
396
+                    ->set('permissions', $qb->createNamedParameter(0))
397
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
398
+                    ->execute();
399
+            }
400
+
401
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
402
+
403
+            if ($share->getSharedWith() !== $recipient) {
404
+                throw new ProviderException('Recipient does not match');
405
+            }
406
+
407
+            // We can just delete user and link shares
408
+            $this->delete($share);
409
+        } else {
410
+            throw new ProviderException('Invalid shareType');
411
+        }
412
+    }
413
+
414
+    /**
415
+     * @inheritdoc
416
+     */
417
+    public function move(\OCP\Share\IShare $share, $recipient) {
418
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
419
+            // Just update the target
420
+            $qb = $this->dbConn->getQueryBuilder();
421
+            $qb->update('share')
422
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
423
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
424
+                ->execute();
425
+
426
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
427
+
428
+            // Check if there is a usergroup share
429
+            $qb = $this->dbConn->getQueryBuilder();
430
+            $stmt = $qb->select('id')
431
+                ->from('share')
432
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
433
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
434
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
435
+                ->andWhere($qb->expr()->orX(
436
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
437
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
438
+                ))
439
+                ->setMaxResults(1)
440
+                ->execute();
441
+
442
+            $data = $stmt->fetch();
443
+            $stmt->closeCursor();
444
+
445
+            if ($data === false) {
446
+                // No usergroup share yet. Create one.
447
+                $qb = $this->dbConn->getQueryBuilder();
448
+                $qb->insert('share')
449
+                    ->values([
450
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
451
+                        'share_with' => $qb->createNamedParameter($recipient),
452
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
453
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
454
+                        'parent' => $qb->createNamedParameter($share->getId()),
455
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
456
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
457
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
458
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
459
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
460
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
461
+                    ])->execute();
462
+            } else {
463
+                // Already a usergroup share. Update it.
464
+                $qb = $this->dbConn->getQueryBuilder();
465
+                $qb->update('share')
466
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
467
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
468
+                    ->execute();
469
+            }
470
+        }
471
+
472
+        return $share;
473
+    }
474
+
475
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
476
+        $qb = $this->dbConn->getQueryBuilder();
477
+        $qb->select('*')
478
+            ->from('share', 's')
479
+            ->andWhere($qb->expr()->orX(
480
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
481
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
482
+            ));
483
+
484
+        $qb->andWhere($qb->expr()->orX(
485
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
486
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
487
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
488
+        ));
489
+
490
+        /**
491
+         * Reshares for this user are shares where they are the owner.
492
+         */
493
+        if ($reshares === false) {
494
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
495
+        } else {
496
+            $qb->andWhere(
497
+                $qb->expr()->orX(
498
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
499
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
500
+                )
501
+            );
502
+        }
503
+
504
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
505
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
506
+
507
+        $qb->orderBy('id');
508
+
509
+        $cursor = $qb->execute();
510
+        $shares = [];
511
+        while ($data = $cursor->fetch()) {
512
+            $shares[$data['fileid']][] = $this->createShare($data);
513
+        }
514
+        $cursor->closeCursor();
515
+
516
+        return $shares;
517
+    }
518
+
519
+    /**
520
+     * @inheritdoc
521
+     */
522
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
523
+        $qb = $this->dbConn->getQueryBuilder();
524
+        $qb->select('*')
525
+            ->from('share')
526
+            ->andWhere($qb->expr()->orX(
527
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
528
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
529
+            ));
530
+
531
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
532
+
533
+        /**
534
+         * Reshares for this user are shares where they are the owner.
535
+         */
536
+        if ($reshares === false) {
537
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
538
+        } else {
539
+            $qb->andWhere(
540
+                $qb->expr()->orX(
541
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
542
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
543
+                )
544
+            );
545
+        }
546
+
547
+        if ($node !== null) {
548
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
549
+        }
550
+
551
+        if ($limit !== -1) {
552
+            $qb->setMaxResults($limit);
553
+        }
554
+
555
+        $qb->setFirstResult($offset);
556
+        $qb->orderBy('id');
557
+
558
+        $cursor = $qb->execute();
559
+        $shares = [];
560
+        while($data = $cursor->fetch()) {
561
+            $shares[] = $this->createShare($data);
562
+        }
563
+        $cursor->closeCursor();
564
+
565
+        return $shares;
566
+    }
567
+
568
+    /**
569
+     * @inheritdoc
570
+     */
571
+    public function getShareById($id, $recipientId = null) {
572
+        $qb = $this->dbConn->getQueryBuilder();
573
+
574
+        $qb->select('*')
575
+            ->from('share')
576
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
577
+            ->andWhere(
578
+                $qb->expr()->in(
579
+                    'share_type',
580
+                    $qb->createNamedParameter([
581
+                        \OCP\Share::SHARE_TYPE_USER,
582
+                        \OCP\Share::SHARE_TYPE_GROUP,
583
+                        \OCP\Share::SHARE_TYPE_LINK,
584
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
585
+                )
586
+            )
587
+            ->andWhere($qb->expr()->orX(
588
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
589
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
590
+            ));
591
+
592
+        $cursor = $qb->execute();
593
+        $data = $cursor->fetch();
594
+        $cursor->closeCursor();
595
+
596
+        if ($data === false) {
597
+            throw new ShareNotFound();
598
+        }
599
+
600
+        try {
601
+            $share = $this->createShare($data);
602
+        } catch (InvalidShare $e) {
603
+            throw new ShareNotFound();
604
+        }
605
+
606
+        // If the recipient is set for a group share resolve to that user
607
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
608
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
609
+        }
610
+
611
+        return $share;
612
+    }
613
+
614
+    /**
615
+     * Get shares for a given path
616
+     *
617
+     * @param \OCP\Files\Node $path
618
+     * @return \OCP\Share\IShare[]
619
+     */
620
+    public function getSharesByPath(Node $path) {
621
+        $qb = $this->dbConn->getQueryBuilder();
622
+
623
+        $cursor = $qb->select('*')
624
+            ->from('share')
625
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
626
+            ->andWhere(
627
+                $qb->expr()->orX(
628
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
629
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
630
+                )
631
+            )
632
+            ->andWhere($qb->expr()->orX(
633
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
634
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
635
+            ))
636
+            ->execute();
637
+
638
+        $shares = [];
639
+        while($data = $cursor->fetch()) {
640
+            $shares[] = $this->createShare($data);
641
+        }
642
+        $cursor->closeCursor();
643
+
644
+        return $shares;
645
+    }
646
+
647
+    /**
648
+     * Returns whether the given database result can be interpreted as
649
+     * a share with accessible file (not trashed, not deleted)
650
+     */
651
+    private function isAccessibleResult($data) {
652
+        // exclude shares leading to deleted file entries
653
+        if ($data['fileid'] === null) {
654
+            return false;
655
+        }
656
+
657
+        // exclude shares leading to trashbin on home storages
658
+        $pathSections = explode('/', $data['path'], 2);
659
+        // FIXME: would not detect rare md5'd home storage case properly
660
+        if ($pathSections[0] !== 'files'
661
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
662
+            return false;
663
+        }
664
+        return true;
665
+    }
666
+
667
+    /**
668
+     * @inheritdoc
669
+     */
670
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
671
+        /** @var Share[] $shares */
672
+        $shares = [];
673
+
674
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
675
+            //Get shares directly with this user
676
+            $qb = $this->dbConn->getQueryBuilder();
677
+            $qb->select('s.*',
678
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
679
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
680
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
681
+            )
682
+                ->selectAlias('st.id', 'storage_string_id')
683
+                ->from('share', 's')
684
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
685
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
686
+
687
+            // Order by id
688
+            $qb->orderBy('s.id');
689
+
690
+            // Set limit and offset
691
+            if ($limit !== -1) {
692
+                $qb->setMaxResults($limit);
693
+            }
694
+            $qb->setFirstResult($offset);
695
+
696
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
697
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
698
+                ->andWhere($qb->expr()->orX(
699
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
700
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
701
+                ));
702
+
703
+            // Filter by node if provided
704
+            if ($node !== null) {
705
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
706
+            }
707
+
708
+            $cursor = $qb->execute();
709
+
710
+            while($data = $cursor->fetch()) {
711
+                if ($this->isAccessibleResult($data)) {
712
+                    $shares[] = $this->createShare($data);
713
+                }
714
+            }
715
+            $cursor->closeCursor();
716
+
717
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
718
+            $user = $this->userManager->get($userId);
719
+            $allGroups = $this->groupManager->getUserGroups($user);
720
+
721
+            /** @var Share[] $shares2 */
722
+            $shares2 = [];
723
+
724
+            $start = 0;
725
+            while(true) {
726
+                $groups = array_slice($allGroups, $start, 100);
727
+                $start += 100;
728
+
729
+                if ($groups === []) {
730
+                    break;
731
+                }
732
+
733
+                $qb = $this->dbConn->getQueryBuilder();
734
+                $qb->select('s.*',
735
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
736
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
737
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
738
+                )
739
+                    ->selectAlias('st.id', 'storage_string_id')
740
+                    ->from('share', 's')
741
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
742
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
743
+                    ->orderBy('s.id')
744
+                    ->setFirstResult(0);
745
+
746
+                if ($limit !== -1) {
747
+                    $qb->setMaxResults($limit - count($shares));
748
+                }
749
+
750
+                // Filter by node if provided
751
+                if ($node !== null) {
752
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
753
+                }
754
+
755
+
756
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
757
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
758
+
759
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
760
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
761
+                        $groups,
762
+                        IQueryBuilder::PARAM_STR_ARRAY
763
+                    )))
764
+                    ->andWhere($qb->expr()->orX(
765
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
766
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
767
+                    ));
768
+
769
+                $cursor = $qb->execute();
770
+                while($data = $cursor->fetch()) {
771
+                    if ($offset > 0) {
772
+                        $offset--;
773
+                        continue;
774
+                    }
775
+
776
+                    if ($this->isAccessibleResult($data)) {
777
+                        $shares2[] = $this->createShare($data);
778
+                    }
779
+                }
780
+                $cursor->closeCursor();
781
+            }
782
+
783
+            /*
784 784
  			 * Resolve all group shares to user specific shares
785 785
  			 */
786
-			$shares = $this->resolveGroupShares($shares2, $userId);
787
-		} else {
788
-			throw new BackendError('Invalid backend');
789
-		}
790
-
791
-
792
-		return $shares;
793
-	}
794
-
795
-	/**
796
-	 * Get a share by token
797
-	 *
798
-	 * @param string $token
799
-	 * @return \OCP\Share\IShare
800
-	 * @throws ShareNotFound
801
-	 */
802
-	public function getShareByToken($token) {
803
-		$qb = $this->dbConn->getQueryBuilder();
804
-
805
-		$cursor = $qb->select('*')
806
-			->from('share')
807
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
808
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
809
-			->andWhere($qb->expr()->orX(
810
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
811
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
812
-			))
813
-			->execute();
814
-
815
-		$data = $cursor->fetch();
816
-
817
-		if ($data === false) {
818
-			throw new ShareNotFound();
819
-		}
820
-
821
-		try {
822
-			$share = $this->createShare($data);
823
-		} catch (InvalidShare $e) {
824
-			throw new ShareNotFound();
825
-		}
826
-
827
-		return $share;
828
-	}
829
-
830
-	/**
831
-	 * Create a share object from an database row
832
-	 *
833
-	 * @param mixed[] $data
834
-	 * @return \OCP\Share\IShare
835
-	 * @throws InvalidShare
836
-	 */
837
-	private function createShare($data) {
838
-		$share = new Share($this->rootFolder, $this->userManager);
839
-		$share->setId((int)$data['id'])
840
-			->setShareType((int)$data['share_type'])
841
-			->setPermissions((int)$data['permissions'])
842
-			->setTarget($data['file_target'])
843
-			->setMailSend((bool)$data['mail_send']);
844
-
845
-		$shareTime = new \DateTime();
846
-		$shareTime->setTimestamp((int)$data['stime']);
847
-		$share->setShareTime($shareTime);
848
-
849
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
850
-			$share->setSharedWith($data['share_with']);
851
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
852
-			$share->setSharedWith($data['share_with']);
853
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
854
-			$share->setPassword($data['password']);
855
-			$share->setToken($data['token']);
856
-		}
857
-
858
-		$share->setSharedBy($data['uid_initiator']);
859
-		$share->setShareOwner($data['uid_owner']);
860
-
861
-		$share->setNodeId((int)$data['file_source']);
862
-		$share->setNodeType($data['item_type']);
863
-
864
-		if ($data['expiration'] !== null) {
865
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
866
-			$share->setExpirationDate($expiration);
867
-		}
868
-
869
-		if (isset($data['f_permissions'])) {
870
-			$entryData = $data;
871
-			$entryData['permissions'] = $entryData['f_permissions'];
872
-			$entryData['parent'] = $entryData['f_parent'];
873
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
874
-				\OC::$server->getMimeTypeLoader()));
875
-		}
876
-
877
-		$share->setProviderId($this->identifier());
878
-
879
-		return $share;
880
-	}
881
-
882
-	/**
883
-	 * @param Share[] $shares
884
-	 * @param $userId
885
-	 * @return Share[] The updates shares if no update is found for a share return the original
886
-	 */
887
-	private function resolveGroupShares($shares, $userId) {
888
-		$result = [];
889
-
890
-		$start = 0;
891
-		while(true) {
892
-			/** @var Share[] $shareSlice */
893
-			$shareSlice = array_slice($shares, $start, 100);
894
-			$start += 100;
895
-
896
-			if ($shareSlice === []) {
897
-				break;
898
-			}
899
-
900
-			/** @var int[] $ids */
901
-			$ids = [];
902
-			/** @var Share[] $shareMap */
903
-			$shareMap = [];
904
-
905
-			foreach ($shareSlice as $share) {
906
-				$ids[] = (int)$share->getId();
907
-				$shareMap[$share->getId()] = $share;
908
-			}
909
-
910
-			$qb = $this->dbConn->getQueryBuilder();
911
-
912
-			$query = $qb->select('*')
913
-				->from('share')
914
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
915
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
916
-				->andWhere($qb->expr()->orX(
917
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
918
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
919
-				));
920
-
921
-			$stmt = $query->execute();
922
-
923
-			while($data = $stmt->fetch()) {
924
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
925
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
926
-			}
927
-
928
-			$stmt->closeCursor();
929
-
930
-			foreach ($shareMap as $share) {
931
-				$result[] = $share;
932
-			}
933
-		}
934
-
935
-		return $result;
936
-	}
937
-
938
-	/**
939
-	 * A user is deleted from the system
940
-	 * So clean up the relevant shares.
941
-	 *
942
-	 * @param string $uid
943
-	 * @param int $shareType
944
-	 */
945
-	public function userDeleted($uid, $shareType) {
946
-		$qb = $this->dbConn->getQueryBuilder();
947
-
948
-		$qb->delete('share');
949
-
950
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
951
-			/*
786
+            $shares = $this->resolveGroupShares($shares2, $userId);
787
+        } else {
788
+            throw new BackendError('Invalid backend');
789
+        }
790
+
791
+
792
+        return $shares;
793
+    }
794
+
795
+    /**
796
+     * Get a share by token
797
+     *
798
+     * @param string $token
799
+     * @return \OCP\Share\IShare
800
+     * @throws ShareNotFound
801
+     */
802
+    public function getShareByToken($token) {
803
+        $qb = $this->dbConn->getQueryBuilder();
804
+
805
+        $cursor = $qb->select('*')
806
+            ->from('share')
807
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
808
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
809
+            ->andWhere($qb->expr()->orX(
810
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
811
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
812
+            ))
813
+            ->execute();
814
+
815
+        $data = $cursor->fetch();
816
+
817
+        if ($data === false) {
818
+            throw new ShareNotFound();
819
+        }
820
+
821
+        try {
822
+            $share = $this->createShare($data);
823
+        } catch (InvalidShare $e) {
824
+            throw new ShareNotFound();
825
+        }
826
+
827
+        return $share;
828
+    }
829
+
830
+    /**
831
+     * Create a share object from an database row
832
+     *
833
+     * @param mixed[] $data
834
+     * @return \OCP\Share\IShare
835
+     * @throws InvalidShare
836
+     */
837
+    private function createShare($data) {
838
+        $share = new Share($this->rootFolder, $this->userManager);
839
+        $share->setId((int)$data['id'])
840
+            ->setShareType((int)$data['share_type'])
841
+            ->setPermissions((int)$data['permissions'])
842
+            ->setTarget($data['file_target'])
843
+            ->setMailSend((bool)$data['mail_send']);
844
+
845
+        $shareTime = new \DateTime();
846
+        $shareTime->setTimestamp((int)$data['stime']);
847
+        $share->setShareTime($shareTime);
848
+
849
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
850
+            $share->setSharedWith($data['share_with']);
851
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
852
+            $share->setSharedWith($data['share_with']);
853
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
854
+            $share->setPassword($data['password']);
855
+            $share->setToken($data['token']);
856
+        }
857
+
858
+        $share->setSharedBy($data['uid_initiator']);
859
+        $share->setShareOwner($data['uid_owner']);
860
+
861
+        $share->setNodeId((int)$data['file_source']);
862
+        $share->setNodeType($data['item_type']);
863
+
864
+        if ($data['expiration'] !== null) {
865
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
866
+            $share->setExpirationDate($expiration);
867
+        }
868
+
869
+        if (isset($data['f_permissions'])) {
870
+            $entryData = $data;
871
+            $entryData['permissions'] = $entryData['f_permissions'];
872
+            $entryData['parent'] = $entryData['f_parent'];
873
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
874
+                \OC::$server->getMimeTypeLoader()));
875
+        }
876
+
877
+        $share->setProviderId($this->identifier());
878
+
879
+        return $share;
880
+    }
881
+
882
+    /**
883
+     * @param Share[] $shares
884
+     * @param $userId
885
+     * @return Share[] The updates shares if no update is found for a share return the original
886
+     */
887
+    private function resolveGroupShares($shares, $userId) {
888
+        $result = [];
889
+
890
+        $start = 0;
891
+        while(true) {
892
+            /** @var Share[] $shareSlice */
893
+            $shareSlice = array_slice($shares, $start, 100);
894
+            $start += 100;
895
+
896
+            if ($shareSlice === []) {
897
+                break;
898
+            }
899
+
900
+            /** @var int[] $ids */
901
+            $ids = [];
902
+            /** @var Share[] $shareMap */
903
+            $shareMap = [];
904
+
905
+            foreach ($shareSlice as $share) {
906
+                $ids[] = (int)$share->getId();
907
+                $shareMap[$share->getId()] = $share;
908
+            }
909
+
910
+            $qb = $this->dbConn->getQueryBuilder();
911
+
912
+            $query = $qb->select('*')
913
+                ->from('share')
914
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
915
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
916
+                ->andWhere($qb->expr()->orX(
917
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
918
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
919
+                ));
920
+
921
+            $stmt = $query->execute();
922
+
923
+            while($data = $stmt->fetch()) {
924
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
925
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
926
+            }
927
+
928
+            $stmt->closeCursor();
929
+
930
+            foreach ($shareMap as $share) {
931
+                $result[] = $share;
932
+            }
933
+        }
934
+
935
+        return $result;
936
+    }
937
+
938
+    /**
939
+     * A user is deleted from the system
940
+     * So clean up the relevant shares.
941
+     *
942
+     * @param string $uid
943
+     * @param int $shareType
944
+     */
945
+    public function userDeleted($uid, $shareType) {
946
+        $qb = $this->dbConn->getQueryBuilder();
947
+
948
+        $qb->delete('share');
949
+
950
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
951
+            /*
952 952
 			 * Delete all user shares that are owned by this user
953 953
 			 * or that are received by this user
954 954
 			 */
955 955
 
956
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
956
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
957 957
 
958
-			$qb->andWhere(
959
-				$qb->expr()->orX(
960
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
961
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
962
-				)
963
-			);
964
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
965
-			/*
958
+            $qb->andWhere(
959
+                $qb->expr()->orX(
960
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
961
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
962
+                )
963
+            );
964
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
965
+            /*
966 966
 			 * Delete all group shares that are owned by this user
967 967
 			 * Or special user group shares that are received by this user
968 968
 			 */
969
-			$qb->where(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->orX(
972
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
973
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
974
-					),
975
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
976
-				)
977
-			);
978
-
979
-			$qb->orWhere(
980
-				$qb->expr()->andX(
981
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
982
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
983
-				)
984
-			);
985
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
986
-			/*
969
+            $qb->where(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->orX(
972
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
973
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
974
+                    ),
975
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
976
+                )
977
+            );
978
+
979
+            $qb->orWhere(
980
+                $qb->expr()->andX(
981
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
982
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
983
+                )
984
+            );
985
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
986
+            /*
987 987
 			 * Delete all link shares owned by this user.
988 988
 			 * And all link shares initiated by this user (until #22327 is in)
989 989
 			 */
990
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
991
-
992
-			$qb->andWhere(
993
-				$qb->expr()->orX(
994
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
995
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
996
-				)
997
-			);
998
-		}
999
-
1000
-		$qb->execute();
1001
-	}
1002
-
1003
-	/**
1004
-	 * Delete all shares received by this group. As well as any custom group
1005
-	 * shares for group members.
1006
-	 *
1007
-	 * @param string $gid
1008
-	 */
1009
-	public function groupDeleted($gid) {
1010
-		/*
990
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
991
+
992
+            $qb->andWhere(
993
+                $qb->expr()->orX(
994
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
995
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
996
+                )
997
+            );
998
+        }
999
+
1000
+        $qb->execute();
1001
+    }
1002
+
1003
+    /**
1004
+     * Delete all shares received by this group. As well as any custom group
1005
+     * shares for group members.
1006
+     *
1007
+     * @param string $gid
1008
+     */
1009
+    public function groupDeleted($gid) {
1010
+        /*
1011 1011
 		 * First delete all custom group shares for group members
1012 1012
 		 */
1013
-		$qb = $this->dbConn->getQueryBuilder();
1014
-		$qb->select('id')
1015
-			->from('share')
1016
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1017
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1018
-
1019
-		$cursor = $qb->execute();
1020
-		$ids = [];
1021
-		while($row = $cursor->fetch()) {
1022
-			$ids[] = (int)$row['id'];
1023
-		}
1024
-		$cursor->closeCursor();
1025
-
1026
-		if (!empty($ids)) {
1027
-			$chunks = array_chunk($ids, 100);
1028
-			foreach ($chunks as $chunk) {
1029
-				$qb->delete('share')
1030
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1031
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1032
-				$qb->execute();
1033
-			}
1034
-		}
1035
-
1036
-		/*
1013
+        $qb = $this->dbConn->getQueryBuilder();
1014
+        $qb->select('id')
1015
+            ->from('share')
1016
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1017
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1018
+
1019
+        $cursor = $qb->execute();
1020
+        $ids = [];
1021
+        while($row = $cursor->fetch()) {
1022
+            $ids[] = (int)$row['id'];
1023
+        }
1024
+        $cursor->closeCursor();
1025
+
1026
+        if (!empty($ids)) {
1027
+            $chunks = array_chunk($ids, 100);
1028
+            foreach ($chunks as $chunk) {
1029
+                $qb->delete('share')
1030
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1031
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1032
+                $qb->execute();
1033
+            }
1034
+        }
1035
+
1036
+        /*
1037 1037
 		 * Now delete all the group shares
1038 1038
 		 */
1039
-		$qb = $this->dbConn->getQueryBuilder();
1040
-		$qb->delete('share')
1041
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1042
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1043
-		$qb->execute();
1044
-	}
1045
-
1046
-	/**
1047
-	 * Delete custom group shares to this group for this user
1048
-	 *
1049
-	 * @param string $uid
1050
-	 * @param string $gid
1051
-	 */
1052
-	public function userDeletedFromGroup($uid, $gid) {
1053
-		/*
1039
+        $qb = $this->dbConn->getQueryBuilder();
1040
+        $qb->delete('share')
1041
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1042
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1043
+        $qb->execute();
1044
+    }
1045
+
1046
+    /**
1047
+     * Delete custom group shares to this group for this user
1048
+     *
1049
+     * @param string $uid
1050
+     * @param string $gid
1051
+     */
1052
+    public function userDeletedFromGroup($uid, $gid) {
1053
+        /*
1054 1054
 		 * Get all group shares
1055 1055
 		 */
1056
-		$qb = $this->dbConn->getQueryBuilder();
1057
-		$qb->select('id')
1058
-			->from('share')
1059
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1060
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1061
-
1062
-		$cursor = $qb->execute();
1063
-		$ids = [];
1064
-		while($row = $cursor->fetch()) {
1065
-			$ids[] = (int)$row['id'];
1066
-		}
1067
-		$cursor->closeCursor();
1068
-
1069
-		if (!empty($ids)) {
1070
-			$chunks = array_chunk($ids, 100);
1071
-			foreach ($chunks as $chunk) {
1072
-				/*
1056
+        $qb = $this->dbConn->getQueryBuilder();
1057
+        $qb->select('id')
1058
+            ->from('share')
1059
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1060
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1061
+
1062
+        $cursor = $qb->execute();
1063
+        $ids = [];
1064
+        while($row = $cursor->fetch()) {
1065
+            $ids[] = (int)$row['id'];
1066
+        }
1067
+        $cursor->closeCursor();
1068
+
1069
+        if (!empty($ids)) {
1070
+            $chunks = array_chunk($ids, 100);
1071
+            foreach ($chunks as $chunk) {
1072
+                /*
1073 1073
 				 * Delete all special shares wit this users for the found group shares
1074 1074
 				 */
1075
-				$qb->delete('share')
1076
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1077
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1078
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1079
-				$qb->execute();
1080
-			}
1081
-		}
1082
-	}
1083
-
1084
-	/**
1085
-	 * @inheritdoc
1086
-	 */
1087
-	public function getAccessList($nodes, $currentAccess) {
1088
-		$ids = [];
1089
-		foreach ($nodes as $node) {
1090
-			$ids[] = $node->getId();
1091
-		}
1092
-
1093
-		$qb = $this->dbConn->getQueryBuilder();
1094
-
1095
-		$or = $qb->expr()->orX(
1096
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1097
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1098
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1099
-		);
1100
-
1101
-		if ($currentAccess) {
1102
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1103
-		}
1104
-
1105
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1106
-			->from('share')
1107
-			->where(
1108
-				$or
1109
-			)
1110
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1111
-			->andWhere($qb->expr()->orX(
1112
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1113
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1114
-			));
1115
-		$cursor = $qb->execute();
1116
-
1117
-		$users = [];
1118
-		$link = false;
1119
-		while($row = $cursor->fetch()) {
1120
-			$type = (int)$row['share_type'];
1121
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1122
-				$uid = $row['share_with'];
1123
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1124
-				$users[$uid][$row['id']] = $row;
1125
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1126
-				$gid = $row['share_with'];
1127
-				$group = $this->groupManager->get($gid);
1128
-
1129
-				if ($group === null) {
1130
-					continue;
1131
-				}
1132
-
1133
-				$userList = $group->getUsers();
1134
-				foreach ($userList as $user) {
1135
-					$uid = $user->getUID();
1136
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1137
-					$users[$uid][$row['id']] = $row;
1138
-				}
1139
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1140
-				$link = true;
1141
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1142
-				$uid = $row['share_with'];
1143
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1144
-				$users[$uid][$row['id']] = $row;
1145
-			}
1146
-		}
1147
-		$cursor->closeCursor();
1148
-
1149
-		if ($currentAccess === true) {
1150
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1151
-			$users = array_filter($users);
1152
-		} else {
1153
-			$users = array_keys($users);
1154
-		}
1155
-
1156
-		return ['users' => $users, 'public' => $link];
1157
-	}
1158
-
1159
-	/**
1160
-	 * For each user the path with the fewest slashes is returned
1161
-	 * @param array $shares
1162
-	 * @return array
1163
-	 */
1164
-	protected function filterSharesOfUser(array $shares) {
1165
-		// Group shares when the user has a share exception
1166
-		foreach ($shares as $id => $share) {
1167
-			$type = (int) $share['share_type'];
1168
-			$permissions = (int) $share['permissions'];
1169
-
1170
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1171
-				unset($shares[$share['parent']]);
1172
-
1173
-				if ($permissions === 0) {
1174
-					unset($shares[$id]);
1175
-				}
1176
-			}
1177
-		}
1178
-
1179
-		$best = [];
1180
-		$bestDepth = 0;
1181
-		foreach ($shares as $id => $share) {
1182
-			$depth = substr_count($share['file_target'], '/');
1183
-			if (empty($best) || $depth < $bestDepth) {
1184
-				$bestDepth = $depth;
1185
-				$best = [
1186
-					'node_id' => $share['file_source'],
1187
-					'node_path' => $share['file_target'],
1188
-				];
1189
-			}
1190
-		}
1191
-
1192
-		return $best;
1193
-	}
1075
+                $qb->delete('share')
1076
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1077
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1078
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1079
+                $qb->execute();
1080
+            }
1081
+        }
1082
+    }
1083
+
1084
+    /**
1085
+     * @inheritdoc
1086
+     */
1087
+    public function getAccessList($nodes, $currentAccess) {
1088
+        $ids = [];
1089
+        foreach ($nodes as $node) {
1090
+            $ids[] = $node->getId();
1091
+        }
1092
+
1093
+        $qb = $this->dbConn->getQueryBuilder();
1094
+
1095
+        $or = $qb->expr()->orX(
1096
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1097
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1098
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1099
+        );
1100
+
1101
+        if ($currentAccess) {
1102
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1103
+        }
1104
+
1105
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1106
+            ->from('share')
1107
+            ->where(
1108
+                $or
1109
+            )
1110
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1111
+            ->andWhere($qb->expr()->orX(
1112
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1113
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1114
+            ));
1115
+        $cursor = $qb->execute();
1116
+
1117
+        $users = [];
1118
+        $link = false;
1119
+        while($row = $cursor->fetch()) {
1120
+            $type = (int)$row['share_type'];
1121
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1122
+                $uid = $row['share_with'];
1123
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1124
+                $users[$uid][$row['id']] = $row;
1125
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1126
+                $gid = $row['share_with'];
1127
+                $group = $this->groupManager->get($gid);
1128
+
1129
+                if ($group === null) {
1130
+                    continue;
1131
+                }
1132
+
1133
+                $userList = $group->getUsers();
1134
+                foreach ($userList as $user) {
1135
+                    $uid = $user->getUID();
1136
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1137
+                    $users[$uid][$row['id']] = $row;
1138
+                }
1139
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1140
+                $link = true;
1141
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1142
+                $uid = $row['share_with'];
1143
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1144
+                $users[$uid][$row['id']] = $row;
1145
+            }
1146
+        }
1147
+        $cursor->closeCursor();
1148
+
1149
+        if ($currentAccess === true) {
1150
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1151
+            $users = array_filter($users);
1152
+        } else {
1153
+            $users = array_keys($users);
1154
+        }
1155
+
1156
+        return ['users' => $users, 'public' => $link];
1157
+    }
1158
+
1159
+    /**
1160
+     * For each user the path with the fewest slashes is returned
1161
+     * @param array $shares
1162
+     * @return array
1163
+     */
1164
+    protected function filterSharesOfUser(array $shares) {
1165
+        // Group shares when the user has a share exception
1166
+        foreach ($shares as $id => $share) {
1167
+            $type = (int) $share['share_type'];
1168
+            $permissions = (int) $share['permissions'];
1169
+
1170
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1171
+                unset($shares[$share['parent']]);
1172
+
1173
+                if ($permissions === 0) {
1174
+                    unset($shares[$id]);
1175
+                }
1176
+            }
1177
+        }
1178
+
1179
+        $best = [];
1180
+        $bestDepth = 0;
1181
+        foreach ($shares as $id => $share) {
1182
+            $depth = substr_count($share['file_target'], '/');
1183
+            if (empty($best) || $depth < $bestDepth) {
1184
+                $bestDepth = $depth;
1185
+                $best = [
1186
+                    'node_id' => $share['file_source'],
1187
+                    'node_path' => $share['file_target'],
1188
+                ];
1189
+            }
1190
+        }
1191
+
1192
+        return $best;
1193
+    }
1194 1194
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/ShareTypeList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@
 block discarded – undo
61 61
 	 * The deserialize method is called during xml parsing.
62 62
 	 *
63 63
 	 * @param Reader $reader
64
-	 * @return mixed
64
+	 * @return null|ShareTypeList
65 65
 	 */
66 66
 	static function xmlDeserialize(Reader $reader) {
67 67
 		$shareTypes = [];
Please login to merge, or discard this patch.
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -32,61 +32,61 @@
 block discarded – undo
32 32
  * This property contains multiple "share-type" elements, each containing a share type.
33 33
  */
34 34
 class ShareTypeList implements Element {
35
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
35
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
36 36
 
37
-	/**
38
-	 * Share types
39
-	 *
40
-	 * @var int[]
41
-	 */
42
-	private $shareTypes;
37
+    /**
38
+     * Share types
39
+     *
40
+     * @var int[]
41
+     */
42
+    private $shareTypes;
43 43
 
44
-	/**
45
-	 * @param int[] $shareTypes
46
-	 */
47
-	public function __construct($shareTypes) {
48
-		$this->shareTypes = $shareTypes;
49
-	}
44
+    /**
45
+     * @param int[] $shareTypes
46
+     */
47
+    public function __construct($shareTypes) {
48
+        $this->shareTypes = $shareTypes;
49
+    }
50 50
 
51
-	/**
52
-	 * Returns the share types
53
-	 *
54
-	 * @return int[]
55
-	 */
56
-	public function getShareTypes() {
57
-		return $this->shareTypes;
58
-	}
51
+    /**
52
+     * Returns the share types
53
+     *
54
+     * @return int[]
55
+     */
56
+    public function getShareTypes() {
57
+        return $this->shareTypes;
58
+    }
59 59
 
60
-	/**
61
-	 * The deserialize method is called during xml parsing.
62
-	 *
63
-	 * @param Reader $reader
64
-	 * @return mixed
65
-	 */
66
-	static function xmlDeserialize(Reader $reader) {
67
-		$shareTypes = [];
60
+    /**
61
+     * The deserialize method is called during xml parsing.
62
+     *
63
+     * @param Reader $reader
64
+     * @return mixed
65
+     */
66
+    static function xmlDeserialize(Reader $reader) {
67
+        $shareTypes = [];
68 68
 
69
-		$tree = $reader->parseInnerTree();
70
-		if ($tree === null) {
71
-			return null;
72
-		}
73
-		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
76
-			}
77
-		}
78
-		return new self($shareTypes);
79
-	}
69
+        $tree = $reader->parseInnerTree();
70
+        if ($tree === null) {
71
+            return null;
72
+        }
73
+        foreach ($tree as $elem) {
74
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
+                $shareTypes[] = (int)$elem['value'];
76
+            }
77
+        }
78
+        return new self($shareTypes);
79
+    }
80 80
 
81
-	/**
82
-	 * The xmlSerialize metod is called during xml writing.
83
-	 *
84
-	 * @param Writer $writer
85
-	 * @return void
86
-	 */
87
-	function xmlSerialize(Writer $writer) {
88
-		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
-		}
91
-	}
81
+    /**
82
+     * The xmlSerialize metod is called during xml writing.
83
+     *
84
+     * @param Writer $writer
85
+     * @return void
86
+     */
87
+    function xmlSerialize(Writer $writer) {
88
+        foreach ($this->shareTypes as $shareType) {
89
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
90
+        }
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
 			return null;
72 72
 		}
73 73
 		foreach ($tree as $elem) {
74
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}share-type') {
75
-				$shareTypes[] = (int)$elem['value'];
74
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}share-type') {
75
+				$shareTypes[] = (int) $elem['value'];
76 76
 			}
77 77
 		}
78 78
 		return new self($shareTypes);
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 */
87 87
 	function xmlSerialize(Writer $writer) {
88 88
 		foreach ($this->shareTypes as $shareType) {
89
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}share-type', $shareType);
89
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}share-type', $shareType);
90 90
 		}
91 91
 	}
92 92
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/TagList.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@
 block discarded – undo
80 80
 	 * the next element.
81 81
 	 *
82 82
 	 * @param Reader $reader
83
-	 * @return mixed
83
+	 * @return null|TagList
84 84
 	 */
85 85
 	static function xmlDeserialize(Reader $reader) {
86 86
 		$tags = [];
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -34,92 +34,92 @@
 block discarded – undo
34 34
  * This property contains multiple "tag" elements, each containing a tag name.
35 35
  */
36 36
 class TagList implements Element {
37
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
37
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
38 38
 
39
-	/**
40
-	 * tags
41
-	 *
42
-	 * @var array
43
-	 */
44
-	private $tags;
39
+    /**
40
+     * tags
41
+     *
42
+     * @var array
43
+     */
44
+    private $tags;
45 45
 
46
-	/**
47
-	 * @param array $tags
48
-	 */
49
-	public function __construct(array $tags) {
50
-		$this->tags = $tags;
51
-	}
46
+    /**
47
+     * @param array $tags
48
+     */
49
+    public function __construct(array $tags) {
50
+        $this->tags = $tags;
51
+    }
52 52
 
53
-	/**
54
-	 * Returns the tags
55
-	 *
56
-	 * @return array
57
-	 */
58
-	public function getTags() {
53
+    /**
54
+     * Returns the tags
55
+     *
56
+     * @return array
57
+     */
58
+    public function getTags() {
59 59
 
60
-		return $this->tags;
60
+        return $this->tags;
61 61
 
62
-	}
62
+    }
63 63
 
64
-	/**
65
-	 * The deserialize method is called during xml parsing.
66
-	 *
67
-	 * This method is called statictly, this is because in theory this method
68
-	 * may be used as a type of constructor, or factory method.
69
-	 *
70
-	 * Often you want to return an instance of the current class, but you are
71
-	 * free to return other data as well.
72
-	 *
73
-	 * You are responsible for advancing the reader to the next element. Not
74
-	 * doing anything will result in a never-ending loop.
75
-	 *
76
-	 * If you just want to skip parsing for this element altogether, you can
77
-	 * just call $reader->next();
78
-	 *
79
-	 * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
-	 * the next element.
81
-	 *
82
-	 * @param Reader $reader
83
-	 * @return mixed
84
-	 */
85
-	static function xmlDeserialize(Reader $reader) {
86
-		$tags = [];
64
+    /**
65
+     * The deserialize method is called during xml parsing.
66
+     *
67
+     * This method is called statictly, this is because in theory this method
68
+     * may be used as a type of constructor, or factory method.
69
+     *
70
+     * Often you want to return an instance of the current class, but you are
71
+     * free to return other data as well.
72
+     *
73
+     * You are responsible for advancing the reader to the next element. Not
74
+     * doing anything will result in a never-ending loop.
75
+     *
76
+     * If you just want to skip parsing for this element altogether, you can
77
+     * just call $reader->next();
78
+     *
79
+     * $reader->parseInnerTree() will parse the entire sub-tree, and advance to
80
+     * the next element.
81
+     *
82
+     * @param Reader $reader
83
+     * @return mixed
84
+     */
85
+    static function xmlDeserialize(Reader $reader) {
86
+        $tags = [];
87 87
 
88
-		$tree = $reader->parseInnerTree();
89
-		if ($tree === null) {
90
-			return null;
91
-		}
92
-		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
-				$tags[] = $elem['value'];
95
-			}
96
-		}
97
-		return new self($tags);
98
-	}
88
+        $tree = $reader->parseInnerTree();
89
+        if ($tree === null) {
90
+            return null;
91
+        }
92
+        foreach ($tree as $elem) {
93
+            if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
94
+                $tags[] = $elem['value'];
95
+            }
96
+        }
97
+        return new self($tags);
98
+    }
99 99
 
100
-	/**
101
-	 * The xmlSerialize metod is called during xml writing.
102
-	 *
103
-	 * Use the $writer argument to write its own xml serialization.
104
-	 *
105
-	 * An important note: do _not_ create a parent element. Any element
106
-	 * implementing XmlSerializble should only ever write what's considered
107
-	 * its 'inner xml'.
108
-	 *
109
-	 * The parent of the current element is responsible for writing a
110
-	 * containing element.
111
-	 *
112
-	 * This allows serializers to be re-used for different element names.
113
-	 *
114
-	 * If you are opening new elements, you must also close them again.
115
-	 *
116
-	 * @param Writer $writer
117
-	 * @return void
118
-	 */
119
-	function xmlSerialize(Writer $writer) {
100
+    /**
101
+     * The xmlSerialize metod is called during xml writing.
102
+     *
103
+     * Use the $writer argument to write its own xml serialization.
104
+     *
105
+     * An important note: do _not_ create a parent element. Any element
106
+     * implementing XmlSerializble should only ever write what's considered
107
+     * its 'inner xml'.
108
+     *
109
+     * The parent of the current element is responsible for writing a
110
+     * containing element.
111
+     *
112
+     * This allows serializers to be re-used for different element names.
113
+     *
114
+     * If you are opening new elements, you must also close them again.
115
+     *
116
+     * @param Writer $writer
117
+     * @return void
118
+     */
119
+    function xmlSerialize(Writer $writer) {
120 120
 
121
-		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
-		}
124
-	}
121
+        foreach ($this->tags as $tag) {
122
+            $writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
123
+        }
124
+    }
125 125
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 			return null;
91 91
 		}
92 92
 		foreach ($tree as $elem) {
93
-			if ($elem['name'] === '{' . self::NS_OWNCLOUD . '}tag') {
93
+			if ($elem['name'] === '{'.self::NS_OWNCLOUD.'}tag') {
94 94
 				$tags[] = $elem['value'];
95 95
 			}
96 96
 		}
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	function xmlSerialize(Writer $writer) {
120 120
 
121 121
 		foreach ($this->tags as $tag) {
122
-			$writer->writeElement('{' . self::NS_OWNCLOUD . '}tag', $tag);
122
+			$writer->writeElement('{'.self::NS_OWNCLOUD.'}tag', $tag);
123 123
 		}
124 124
 	}
125 125
 }
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +5 added lines patch added patch discarded remove patch
@@ -318,6 +318,11 @@
 block discarded – undo
318 318
 	 */
319 319
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
320 320
 	// FIXME This is also the reason, why it is not in the public interface
321
+
322
+	/**
323
+	 * @param string $app
324
+	 * @param string $lang
325
+	 */
321 326
 	public function getL10nFilesForApp($app, $lang) {
322 327
 		$languageFiles = [];
323 328
 
Please login to merge, or discard this patch.
Indentation   +401 added lines, -401 removed lines patch added patch discarded remove patch
@@ -40,405 +40,405 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-
103
-		$forceLang = $this->config->getSystemValue('force_language', false);
104
-		if (is_string($forceLang)) {
105
-			$lang = $forceLang;
106
-		}
107
-
108
-		if ($lang === null || !$this->languageExists($app, $lang)) {
109
-			$lang = $this->findLanguage($app);
110
-		}
111
-
112
-		if (!isset($this->instances[$lang][$app])) {
113
-			$this->instances[$lang][$app] = new L10N(
114
-				$this, $app, $lang,
115
-				$this->getL10nFilesForApp($app, $lang)
116
-			);
117
-		}
118
-
119
-		return $this->instances[$lang][$app];
120
-	}
121
-
122
-	/**
123
-	 * Find the best language
124
-	 *
125
-	 * @param string|null $app App id or null for core
126
-	 * @return string language If nothing works it returns 'en'
127
-	 */
128
-	public function findLanguage($app = null) {
129
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
-			return $this->requestLanguage;
131
-		}
132
-
133
-		/**
134
-		 * At this point Nextcloud might not yet be installed and thus the lookup
135
-		 * in the preferences table might fail. For this reason we need to check
136
-		 * whether the instance has already been installed
137
-		 *
138
-		 * @link https://github.com/owncloud/core/issues/21955
139
-		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
143
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
-			} else {
145
-				$userLang = null;
146
-			}
147
-		} else {
148
-			$userId = null;
149
-			$userLang = null;
150
-		}
151
-
152
-		if ($userLang) {
153
-			$this->requestLanguage = $userLang;
154
-			if ($this->languageExists($app, $userLang)) {
155
-				return $userLang;
156
-			}
157
-		}
158
-
159
-		try {
160
-			// Try to get the language from the Request
161
-			$lang = $this->getLanguageFromRequest($app);
162
-			if ($userId !== null && $app === null && !$userLang) {
163
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
164
-			}
165
-			return $lang;
166
-		} catch (LanguageNotFoundException $e) {
167
-			// Finding language from request failed fall back to default language
168
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
169
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
-				return $defaultLanguage;
171
-			}
172
-		}
173
-
174
-		// We could not find any language so fall back to english
175
-		return 'en';
176
-	}
177
-
178
-	/**
179
-	 * Find all available languages for an app
180
-	 *
181
-	 * @param string|null $app App id or null for core
182
-	 * @return array an array of available languages
183
-	 */
184
-	public function findAvailableLanguages($app = null) {
185
-		$key = $app;
186
-		if ($key === null) {
187
-			$key = 'null';
188
-		}
189
-
190
-		// also works with null as key
191
-		if (!empty($this->availableLanguages[$key])) {
192
-			return $this->availableLanguages[$key];
193
-		}
194
-
195
-		$available = ['en']; //english is always available
196
-		$dir = $this->findL10nDir($app);
197
-		if (is_dir($dir)) {
198
-			$files = scandir($dir);
199
-			if ($files !== false) {
200
-				foreach ($files as $file) {
201
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
-						$available[] = substr($file, 0, -5);
203
-					}
204
-				}
205
-			}
206
-		}
207
-
208
-		// merge with translations from theme
209
-		$theme = $this->config->getSystemValue('theme');
210
-		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
-
213
-			if (is_dir($themeDir)) {
214
-				$files = scandir($themeDir);
215
-				if ($files !== false) {
216
-					foreach ($files as $file) {
217
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
-							$available[] = substr($file, 0, -5);
219
-						}
220
-					}
221
-				}
222
-			}
223
-		}
224
-
225
-		$this->availableLanguages[$key] = $available;
226
-		return $available;
227
-	}
228
-
229
-	/**
230
-	 * @param string|null $app App id or null for core
231
-	 * @param string $lang
232
-	 * @return bool
233
-	 */
234
-	public function languageExists($app, $lang) {
235
-		if ($lang === 'en') {//english is always available
236
-			return true;
237
-		}
238
-
239
-		$languages = $this->findAvailableLanguages($app);
240
-		return array_search($lang, $languages) !== false;
241
-	}
242
-
243
-	/**
244
-	 * @param string|null $app
245
-	 * @return string
246
-	 * @throws LanguageNotFoundException
247
-	 */
248
-	private function getLanguageFromRequest($app) {
249
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
-		if ($header !== '') {
251
-			$available = $this->findAvailableLanguages($app);
252
-
253
-			// E.g. make sure that 'de' is before 'de_DE'.
254
-			sort($available);
255
-
256
-			$preferences = preg_split('/,\s*/', strtolower($header));
257
-			foreach ($preferences as $preference) {
258
-				list($preferred_language) = explode(';', $preference);
259
-				$preferred_language = str_replace('-', '_', $preferred_language);
260
-
261
-				foreach ($available as $available_language) {
262
-					if ($preferred_language === strtolower($available_language)) {
263
-						return $this->respectDefaultLanguage($app, $available_language);
264
-					}
265
-				}
266
-
267
-				// Fallback from de_De to de
268
-				foreach ($available as $available_language) {
269
-					if (substr($preferred_language, 0, 2) === $available_language) {
270
-						return $available_language;
271
-					}
272
-				}
273
-			}
274
-		}
275
-
276
-		throw new LanguageNotFoundException();
277
-	}
278
-
279
-	/**
280
-	 * if default language is set to de_DE (formal German) this should be
281
-	 * preferred to 'de' (non-formal German) if possible
282
-	 *
283
-	 * @param string|null $app
284
-	 * @param string $lang
285
-	 * @return string
286
-	 */
287
-	protected function respectDefaultLanguage($app, $lang) {
288
-		$result = $lang;
289
-		$defaultLanguage = $this->config->getSystemValue('default_language', false);
290
-
291
-		// use formal version of german ("Sie" instead of "Du") if the default
292
-		// language is set to 'de_DE' if possible
293
-		if (is_string($defaultLanguage) &&
294
-			strtolower($lang) === 'de' &&
295
-			strtolower($defaultLanguage) === 'de_de' &&
296
-			$this->languageExists($app, 'de_DE')
297
-		) {
298
-			$result = 'de_DE';
299
-		}
300
-
301
-		return $result;
302
-	}
303
-
304
-	/**
305
-	 * Checks if $sub is a subdirectory of $parent
306
-	 *
307
-	 * @param string $sub
308
-	 * @param string $parent
309
-	 * @return bool
310
-	 */
311
-	private function isSubDirectory($sub, $parent) {
312
-		// Check whether $sub contains no ".."
313
-		if(strpos($sub, '..') !== false) {
314
-			return false;
315
-		}
316
-
317
-		// Check whether $sub is a subdirectory of $parent
318
-		if (strpos($sub, $parent) === 0) {
319
-			return true;
320
-		}
321
-
322
-		return false;
323
-	}
324
-
325
-	/**
326
-	 * Get a list of language files that should be loaded
327
-	 *
328
-	 * @param string $app
329
-	 * @param string $lang
330
-	 * @return string[]
331
-	 */
332
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
333
-	// FIXME This is also the reason, why it is not in the public interface
334
-	public function getL10nFilesForApp($app, $lang) {
335
-		$languageFiles = [];
336
-
337
-		$i18nDir = $this->findL10nDir($app);
338
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
-
340
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
-			)
345
-			&& file_exists($transFile)) {
346
-			// load the translations file
347
-			$languageFiles[] = $transFile;
348
-		}
349
-
350
-		// merge with translations from theme
351
-		$theme = $this->config->getSystemValue('theme');
352
-		if (!empty($theme)) {
353
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
-			if (file_exists($transFile)) {
355
-				$languageFiles[] = $transFile;
356
-			}
357
-		}
358
-
359
-		return $languageFiles;
360
-	}
361
-
362
-	/**
363
-	 * find the l10n directory
364
-	 *
365
-	 * @param string $app App id or empty string for core
366
-	 * @return string directory
367
-	 */
368
-	protected function findL10nDir($app = null) {
369
-		if (in_array($app, ['core', 'lib', 'settings'])) {
370
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
-				return $this->serverRoot . '/' . $app . '/l10n/';
372
-			}
373
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
374
-			// Check if the app is in the app folder
375
-			return \OC_App::getAppPath($app) . '/l10n/';
376
-		}
377
-		return $this->serverRoot . '/core/l10n/';
378
-	}
379
-
380
-
381
-	/**
382
-	 * Creates a function from the plural string
383
-	 *
384
-	 * Parts of the code is copied from Habari:
385
-	 * https://github.com/habari/system/blob/master/classes/locale.php
386
-	 * @param string $string
387
-	 * @return string
388
-	 */
389
-	public function createPluralFunction($string) {
390
-		if (isset($this->pluralFunctions[$string])) {
391
-			return $this->pluralFunctions[$string];
392
-		}
393
-
394
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
-			// sanitize
396
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
-
399
-			$body = str_replace(
400
-				array( 'plural', 'n', '$n$plurals', ),
401
-				array( '$plural', '$n', '$nplurals', ),
402
-				'nplurals='. $nplurals . '; plural=' . $plural
403
-			);
404
-
405
-			// add parents
406
-			// important since PHP's ternary evaluates from left to right
407
-			$body .= ';';
408
-			$res = '';
409
-			$p = 0;
410
-			$length = strlen($body);
411
-			for($i = 0; $i < $length; $i++) {
412
-				$ch = $body[$i];
413
-				switch ( $ch ) {
414
-					case '?':
415
-						$res .= ' ? (';
416
-						$p++;
417
-						break;
418
-					case ':':
419
-						$res .= ') : (';
420
-						break;
421
-					case ';':
422
-						$res .= str_repeat( ')', $p ) . ';';
423
-						$p = 0;
424
-						break;
425
-					default:
426
-						$res .= $ch;
427
-				}
428
-			}
429
-
430
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
431
-			$function = create_function('$n', $body);
432
-			$this->pluralFunctions[$string] = $function;
433
-			return $function;
434
-		} else {
435
-			// default: one plural form for all cases but n==1 (english)
436
-			$function = create_function(
437
-				'$n',
438
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
439
-			);
440
-			$this->pluralFunctions[$string] = $function;
441
-			return $function;
442
-		}
443
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+
103
+        $forceLang = $this->config->getSystemValue('force_language', false);
104
+        if (is_string($forceLang)) {
105
+            $lang = $forceLang;
106
+        }
107
+
108
+        if ($lang === null || !$this->languageExists($app, $lang)) {
109
+            $lang = $this->findLanguage($app);
110
+        }
111
+
112
+        if (!isset($this->instances[$lang][$app])) {
113
+            $this->instances[$lang][$app] = new L10N(
114
+                $this, $app, $lang,
115
+                $this->getL10nFilesForApp($app, $lang)
116
+            );
117
+        }
118
+
119
+        return $this->instances[$lang][$app];
120
+    }
121
+
122
+    /**
123
+     * Find the best language
124
+     *
125
+     * @param string|null $app App id or null for core
126
+     * @return string language If nothing works it returns 'en'
127
+     */
128
+    public function findLanguage($app = null) {
129
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
+            return $this->requestLanguage;
131
+        }
132
+
133
+        /**
134
+         * At this point Nextcloud might not yet be installed and thus the lookup
135
+         * in the preferences table might fail. For this reason we need to check
136
+         * whether the instance has already been installed
137
+         *
138
+         * @link https://github.com/owncloud/core/issues/21955
139
+         */
140
+        if($this->config->getSystemValue('installed', false)) {
141
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
+            if(!is_null($userId)) {
143
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
+            } else {
145
+                $userLang = null;
146
+            }
147
+        } else {
148
+            $userId = null;
149
+            $userLang = null;
150
+        }
151
+
152
+        if ($userLang) {
153
+            $this->requestLanguage = $userLang;
154
+            if ($this->languageExists($app, $userLang)) {
155
+                return $userLang;
156
+            }
157
+        }
158
+
159
+        try {
160
+            // Try to get the language from the Request
161
+            $lang = $this->getLanguageFromRequest($app);
162
+            if ($userId !== null && $app === null && !$userLang) {
163
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
164
+            }
165
+            return $lang;
166
+        } catch (LanguageNotFoundException $e) {
167
+            // Finding language from request failed fall back to default language
168
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
169
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
+                return $defaultLanguage;
171
+            }
172
+        }
173
+
174
+        // We could not find any language so fall back to english
175
+        return 'en';
176
+    }
177
+
178
+    /**
179
+     * Find all available languages for an app
180
+     *
181
+     * @param string|null $app App id or null for core
182
+     * @return array an array of available languages
183
+     */
184
+    public function findAvailableLanguages($app = null) {
185
+        $key = $app;
186
+        if ($key === null) {
187
+            $key = 'null';
188
+        }
189
+
190
+        // also works with null as key
191
+        if (!empty($this->availableLanguages[$key])) {
192
+            return $this->availableLanguages[$key];
193
+        }
194
+
195
+        $available = ['en']; //english is always available
196
+        $dir = $this->findL10nDir($app);
197
+        if (is_dir($dir)) {
198
+            $files = scandir($dir);
199
+            if ($files !== false) {
200
+                foreach ($files as $file) {
201
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
+                        $available[] = substr($file, 0, -5);
203
+                    }
204
+                }
205
+            }
206
+        }
207
+
208
+        // merge with translations from theme
209
+        $theme = $this->config->getSystemValue('theme');
210
+        if (!empty($theme)) {
211
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
+
213
+            if (is_dir($themeDir)) {
214
+                $files = scandir($themeDir);
215
+                if ($files !== false) {
216
+                    foreach ($files as $file) {
217
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
+                            $available[] = substr($file, 0, -5);
219
+                        }
220
+                    }
221
+                }
222
+            }
223
+        }
224
+
225
+        $this->availableLanguages[$key] = $available;
226
+        return $available;
227
+    }
228
+
229
+    /**
230
+     * @param string|null $app App id or null for core
231
+     * @param string $lang
232
+     * @return bool
233
+     */
234
+    public function languageExists($app, $lang) {
235
+        if ($lang === 'en') {//english is always available
236
+            return true;
237
+        }
238
+
239
+        $languages = $this->findAvailableLanguages($app);
240
+        return array_search($lang, $languages) !== false;
241
+    }
242
+
243
+    /**
244
+     * @param string|null $app
245
+     * @return string
246
+     * @throws LanguageNotFoundException
247
+     */
248
+    private function getLanguageFromRequest($app) {
249
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
+        if ($header !== '') {
251
+            $available = $this->findAvailableLanguages($app);
252
+
253
+            // E.g. make sure that 'de' is before 'de_DE'.
254
+            sort($available);
255
+
256
+            $preferences = preg_split('/,\s*/', strtolower($header));
257
+            foreach ($preferences as $preference) {
258
+                list($preferred_language) = explode(';', $preference);
259
+                $preferred_language = str_replace('-', '_', $preferred_language);
260
+
261
+                foreach ($available as $available_language) {
262
+                    if ($preferred_language === strtolower($available_language)) {
263
+                        return $this->respectDefaultLanguage($app, $available_language);
264
+                    }
265
+                }
266
+
267
+                // Fallback from de_De to de
268
+                foreach ($available as $available_language) {
269
+                    if (substr($preferred_language, 0, 2) === $available_language) {
270
+                        return $available_language;
271
+                    }
272
+                }
273
+            }
274
+        }
275
+
276
+        throw new LanguageNotFoundException();
277
+    }
278
+
279
+    /**
280
+     * if default language is set to de_DE (formal German) this should be
281
+     * preferred to 'de' (non-formal German) if possible
282
+     *
283
+     * @param string|null $app
284
+     * @param string $lang
285
+     * @return string
286
+     */
287
+    protected function respectDefaultLanguage($app, $lang) {
288
+        $result = $lang;
289
+        $defaultLanguage = $this->config->getSystemValue('default_language', false);
290
+
291
+        // use formal version of german ("Sie" instead of "Du") if the default
292
+        // language is set to 'de_DE' if possible
293
+        if (is_string($defaultLanguage) &&
294
+            strtolower($lang) === 'de' &&
295
+            strtolower($defaultLanguage) === 'de_de' &&
296
+            $this->languageExists($app, 'de_DE')
297
+        ) {
298
+            $result = 'de_DE';
299
+        }
300
+
301
+        return $result;
302
+    }
303
+
304
+    /**
305
+     * Checks if $sub is a subdirectory of $parent
306
+     *
307
+     * @param string $sub
308
+     * @param string $parent
309
+     * @return bool
310
+     */
311
+    private function isSubDirectory($sub, $parent) {
312
+        // Check whether $sub contains no ".."
313
+        if(strpos($sub, '..') !== false) {
314
+            return false;
315
+        }
316
+
317
+        // Check whether $sub is a subdirectory of $parent
318
+        if (strpos($sub, $parent) === 0) {
319
+            return true;
320
+        }
321
+
322
+        return false;
323
+    }
324
+
325
+    /**
326
+     * Get a list of language files that should be loaded
327
+     *
328
+     * @param string $app
329
+     * @param string $lang
330
+     * @return string[]
331
+     */
332
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
333
+    // FIXME This is also the reason, why it is not in the public interface
334
+    public function getL10nFilesForApp($app, $lang) {
335
+        $languageFiles = [];
336
+
337
+        $i18nDir = $this->findL10nDir($app);
338
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
339
+
340
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
344
+            )
345
+            && file_exists($transFile)) {
346
+            // load the translations file
347
+            $languageFiles[] = $transFile;
348
+        }
349
+
350
+        // merge with translations from theme
351
+        $theme = $this->config->getSystemValue('theme');
352
+        if (!empty($theme)) {
353
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
354
+            if (file_exists($transFile)) {
355
+                $languageFiles[] = $transFile;
356
+            }
357
+        }
358
+
359
+        return $languageFiles;
360
+    }
361
+
362
+    /**
363
+     * find the l10n directory
364
+     *
365
+     * @param string $app App id or empty string for core
366
+     * @return string directory
367
+     */
368
+    protected function findL10nDir($app = null) {
369
+        if (in_array($app, ['core', 'lib', 'settings'])) {
370
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
+                return $this->serverRoot . '/' . $app . '/l10n/';
372
+            }
373
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
374
+            // Check if the app is in the app folder
375
+            return \OC_App::getAppPath($app) . '/l10n/';
376
+        }
377
+        return $this->serverRoot . '/core/l10n/';
378
+    }
379
+
380
+
381
+    /**
382
+     * Creates a function from the plural string
383
+     *
384
+     * Parts of the code is copied from Habari:
385
+     * https://github.com/habari/system/blob/master/classes/locale.php
386
+     * @param string $string
387
+     * @return string
388
+     */
389
+    public function createPluralFunction($string) {
390
+        if (isset($this->pluralFunctions[$string])) {
391
+            return $this->pluralFunctions[$string];
392
+        }
393
+
394
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395
+            // sanitize
396
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
398
+
399
+            $body = str_replace(
400
+                array( 'plural', 'n', '$n$plurals', ),
401
+                array( '$plural', '$n', '$nplurals', ),
402
+                'nplurals='. $nplurals . '; plural=' . $plural
403
+            );
404
+
405
+            // add parents
406
+            // important since PHP's ternary evaluates from left to right
407
+            $body .= ';';
408
+            $res = '';
409
+            $p = 0;
410
+            $length = strlen($body);
411
+            for($i = 0; $i < $length; $i++) {
412
+                $ch = $body[$i];
413
+                switch ( $ch ) {
414
+                    case '?':
415
+                        $res .= ' ? (';
416
+                        $p++;
417
+                        break;
418
+                    case ':':
419
+                        $res .= ') : (';
420
+                        break;
421
+                    case ';':
422
+                        $res .= str_repeat( ')', $p ) . ';';
423
+                        $p = 0;
424
+                        break;
425
+                    default:
426
+                        $res .= $ch;
427
+                }
428
+            }
429
+
430
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
431
+            $function = create_function('$n', $body);
432
+            $this->pluralFunctions[$string] = $function;
433
+            return $function;
434
+        } else {
435
+            // default: one plural form for all cases but n==1 (english)
436
+            $function = create_function(
437
+                '$n',
438
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
439
+            );
440
+            $this->pluralFunctions[$string] = $function;
441
+            return $function;
442
+        }
443
+    }
444 444
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -137,9 +137,9 @@  discard block
 block discarded – undo
137 137
 		 *
138 138
 		 * @link https://github.com/owncloud/core/issues/21955
139 139
 		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
140
+		if ($this->config->getSystemValue('installed', false)) {
141
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
142
+			if (!is_null($userId)) {
143 143
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144 144
 			} else {
145 145
 				$userLang = null;
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 		// merge with translations from theme
209 209
 		$theme = $this->config->getSystemValue('theme');
210 210
 		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
211
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
212 212
 
213 213
 			if (is_dir($themeDir)) {
214 214
 				$files = scandir($themeDir);
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 	 */
311 311
 	private function isSubDirectory($sub, $parent) {
312 312
 		// Check whether $sub contains no ".."
313
-		if(strpos($sub, '..') !== false) {
313
+		if (strpos($sub, '..') !== false) {
314 314
 			return false;
315 315
 		}
316 316
 
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 		$languageFiles = [];
336 336
 
337 337
 		$i18nDir = $this->findL10nDir($app);
338
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
338
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
339 339
 
340
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
341
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
342
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
343
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
340
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
341
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
342
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
343
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
344 344
 			)
345 345
 			&& file_exists($transFile)) {
346 346
 			// load the translations file
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 		// merge with translations from theme
351 351
 		$theme = $this->config->getSystemValue('theme');
352 352
 		if (!empty($theme)) {
353
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
353
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
354 354
 			if (file_exists($transFile)) {
355 355
 				$languageFiles[] = $transFile;
356 356
 			}
@@ -367,14 +367,14 @@  discard block
 block discarded – undo
367 367
 	 */
368 368
 	protected function findL10nDir($app = null) {
369 369
 		if (in_array($app, ['core', 'lib', 'settings'])) {
370
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
371
-				return $this->serverRoot . '/' . $app . '/l10n/';
370
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
371
+				return $this->serverRoot.'/'.$app.'/l10n/';
372 372
 			}
373 373
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
374 374
 			// Check if the app is in the app folder
375
-			return \OC_App::getAppPath($app) . '/l10n/';
375
+			return \OC_App::getAppPath($app).'/l10n/';
376 376
 		}
377
-		return $this->serverRoot . '/core/l10n/';
377
+		return $this->serverRoot.'/core/l10n/';
378 378
 	}
379 379
 
380 380
 
@@ -391,15 +391,15 @@  discard block
 block discarded – undo
391 391
 			return $this->pluralFunctions[$string];
392 392
 		}
393 393
 
394
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
394
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
395 395
 			// sanitize
396
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
397
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
396
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
397
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
398 398
 
399 399
 			$body = str_replace(
400
-				array( 'plural', 'n', '$n$plurals', ),
401
-				array( '$plural', '$n', '$nplurals', ),
402
-				'nplurals='. $nplurals . '; plural=' . $plural
400
+				array('plural', 'n', '$n$plurals',),
401
+				array('$plural', '$n', '$nplurals',),
402
+				'nplurals='.$nplurals.'; plural='.$plural
403 403
 			);
404 404
 
405 405
 			// add parents
@@ -408,9 +408,9 @@  discard block
 block discarded – undo
408 408
 			$res = '';
409 409
 			$p = 0;
410 410
 			$length = strlen($body);
411
-			for($i = 0; $i < $length; $i++) {
411
+			for ($i = 0; $i < $length; $i++) {
412 412
 				$ch = $body[$i];
413
-				switch ( $ch ) {
413
+				switch ($ch) {
414 414
 					case '?':
415 415
 						$res .= ' ? (';
416 416
 						$p++;
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 						$res .= ') : (';
420 420
 						break;
421 421
 					case ';':
422
-						$res .= str_repeat( ')', $p ) . ';';
422
+						$res .= str_repeat(')', $p).';';
423 423
 						$p = 0;
424 424
 						break;
425 425
 					default:
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 				}
428 428
 			}
429 429
 
430
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
430
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
431 431
 			$function = create_function('$n', $body);
432 432
 			$this->pluralFunctions[$string] = $function;
433 433
 			return $function;
Please login to merge, or discard this patch.