Completed
Pull Request — master (#3531)
by Julius
41:42 queued 16:38
created
apps/dav/lib/CalDAV/PublicCalendarRoot.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -21,7 +21,6 @@
 block discarded – undo
21 21
 namespace OCA\DAV\CalDAV;
22 22
 
23 23
 use Sabre\DAV\Collection;
24
-use Sabre\DAV\Exception\NotFound;
25 24
 
26 25
 class PublicCalendarRoot extends Collection {
27 26
 
Please login to merge, or discard this patch.
Indentation   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -25,43 +25,43 @@
 block discarded – undo
25 25
 
26 26
 class PublicCalendarRoot extends Collection {
27 27
 
28
-	/** @var CalDavBackend */
29
-	protected $caldavBackend;
28
+    /** @var CalDavBackend */
29
+    protected $caldavBackend;
30 30
 
31
-	/** @var \OCP\IL10N */
32
-	protected $l10n;
31
+    /** @var \OCP\IL10N */
32
+    protected $l10n;
33 33
 
34
-	function __construct(CalDavBackend $caldavBackend) {
35
-		$this->caldavBackend = $caldavBackend;
36
-		$this->l10n = \OC::$server->getL10N('dav');
37
-	}
34
+    function __construct(CalDavBackend $caldavBackend) {
35
+        $this->caldavBackend = $caldavBackend;
36
+        $this->l10n = \OC::$server->getL10N('dav');
37
+    }
38 38
 
39
-	/**
40
-	 * @inheritdoc
41
-	 */
42
-	function getName() {
43
-		return 'public-calendars';
44
-	}
39
+    /**
40
+     * @inheritdoc
41
+     */
42
+    function getName() {
43
+        return 'public-calendars';
44
+    }
45 45
 
46
-	/**
47
-	 * @inheritdoc
48
-	 */
49
-	function getChild($name) {
50
-		$calendar = $this->caldavBackend->getPublicCalendar($name);
51
-		return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
-	}
46
+    /**
47
+     * @inheritdoc
48
+     */
49
+    function getChild($name) {
50
+        $calendar = $this->caldavBackend->getPublicCalendar($name);
51
+        return new Calendar($this->caldavBackend, $calendar, $this->l10n);
52
+    }
53 53
 
54
-	/**
55
-	 * @inheritdoc
56
-	 */
57
-	function getChildren() {
58
-		$calendars = $this->caldavBackend->getPublicCalendars();
59
-		$children = [];
60
-		foreach ($calendars as $calendar) {
61
-			// TODO: maybe implement a new class PublicCalendar ???
62
-			$children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
-		}
54
+    /**
55
+     * @inheritdoc
56
+     */
57
+    function getChildren() {
58
+        $calendars = $this->caldavBackend->getPublicCalendars();
59
+        $children = [];
60
+        foreach ($calendars as $calendar) {
61
+            // TODO: maybe implement a new class PublicCalendar ???
62
+            $children[] = new Calendar($this->caldavBackend, $calendar, $this->l10n);
63
+        }
64 64
 
65
-		return $children;
66
-	}
65
+        return $children;
66
+    }
67 67
 }
Please login to merge, or discard this patch.
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.
Indentation   +452 added lines, -452 removed lines patch added patch discarded remove patch
@@ -32,456 +32,456 @@
 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_INT_ARRAY))
109
-				)
110
-			));
111
-
112
-		return $this->getMountsFromQuery($query);
113
-	}
114
-
115
-	/**
116
-	 * Get admin defined mounts
117
-	 *
118
-	 * @return array
119
-	 */
120
-	public function getAdminMounts() {
121
-		$builder = $this->connection->getQueryBuilder();
122
-		$query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
-			->from('external_mounts')
124
-			->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
-		return $this->getMountsFromQuery($query);
126
-	}
127
-
128
-	protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
-			->from('external_mounts', 'm')
131
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
-
134
-		if (is_null($value)) {
135
-			$query = $query->andWhere($builder->expr()->isNull('a.value'));
136
-		} else {
137
-			$query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
-		}
139
-
140
-		return $query;
141
-	}
142
-
143
-	/**
144
-	 * Get mounts by applicable
145
-	 *
146
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
-	 * @param string|null $value user_id, group_id or null for global mounts
148
-	 * @return array
149
-	 */
150
-	public function getMountsFor($type, $value) {
151
-		$builder = $this->connection->getQueryBuilder();
152
-		$query = $this->getForQuery($builder, $type, $value);
153
-
154
-		return $this->getMountsFromQuery($query);
155
-	}
156
-
157
-	/**
158
-	 * Get admin defined mounts by applicable
159
-	 *
160
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
-	 * @param string|null $value user_id, group_id or null for global mounts
162
-	 * @return array
163
-	 */
164
-	public function getAdminMountsFor($type, $value) {
165
-		$builder = $this->connection->getQueryBuilder();
166
-		$query = $this->getForQuery($builder, $type, $value);
167
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
-
169
-		return $this->getMountsFromQuery($query);
170
-	}
171
-
172
-	/**
173
-	 * Get admin defined mounts for multiple applicable
174
-	 *
175
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
-	 * @param string[] $values user_ids or group_ids
177
-	 * @return array
178
-	 */
179
-	public function getAdminMountsForMultiple($type, array $values) {
180
-		$builder = $this->connection->getQueryBuilder();
181
-		$params = array_map(function ($value) use ($builder) {
182
-			return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
-		}, $values);
184
-
185
-		$query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
-			->from('external_mounts', 'm')
187
-			->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
-			->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
-			->andWhere($builder->expr()->in('a.value', $params));
190
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
-
192
-		return $this->getMountsFromQuery($query);
193
-	}
194
-
195
-	/**
196
-	 * Get user defined mounts by applicable
197
-	 *
198
-	 * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
-	 * @param string|null $value user_id, group_id or null for global mounts
200
-	 * @return array
201
-	 */
202
-	public function getUserMountsFor($type, $value) {
203
-		$builder = $this->connection->getQueryBuilder();
204
-		$query = $this->getForQuery($builder, $type, $value);
205
-		$query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
-
207
-		return $this->getMountsFromQuery($query);
208
-	}
209
-
210
-	/**
211
-	 * Add a mount to the database
212
-	 *
213
-	 * @param string $mountPoint
214
-	 * @param string $storageBackend
215
-	 * @param string $authBackend
216
-	 * @param int $priority
217
-	 * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
-	 * @return int the id of the new mount
219
-	 */
220
-	public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
-		if (!$priority) {
222
-			$priority = 100;
223
-		}
224
-		$builder = $this->connection->getQueryBuilder();
225
-		$query = $builder->insert('external_mounts')
226
-			->values([
227
-				'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
-				'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
-				'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
-				'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
-				'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
-			]);
233
-		$query->execute();
234
-		return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
-	}
236
-
237
-	/**
238
-	 * Remove a mount from the database
239
-	 *
240
-	 * @param int $mountId
241
-	 */
242
-	public function removeMount($mountId) {
243
-		$builder = $this->connection->getQueryBuilder();
244
-		$query = $builder->delete('external_mounts')
245
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
-		$query->execute();
247
-
248
-		$query = $builder->delete('external_applicable')
249
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
-		$query->execute();
251
-
252
-		$query = $builder->delete('external_config')
253
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
-		$query->execute();
255
-
256
-		$query = $builder->delete('external_options')
257
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
-		$query->execute();
259
-	}
260
-
261
-	/**
262
-	 * @param int $mountId
263
-	 * @param string $newMountPoint
264
-	 */
265
-	public function setMountPoint($mountId, $newMountPoint) {
266
-		$builder = $this->connection->getQueryBuilder();
267
-
268
-		$query = $builder->update('external_mounts')
269
-			->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
-
272
-		$query->execute();
273
-	}
274
-
275
-	/**
276
-	 * @param int $mountId
277
-	 * @param string $newAuthBackend
278
-	 */
279
-	public function setAuthBackend($mountId, $newAuthBackend) {
280
-		$builder = $this->connection->getQueryBuilder();
281
-
282
-		$query = $builder->update('external_mounts')
283
-			->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
-
286
-		$query->execute();
287
-	}
288
-
289
-	/**
290
-	 * @param int $mountId
291
-	 * @param string $key
292
-	 * @param string $value
293
-	 */
294
-	public function setConfig($mountId, $key, $value) {
295
-		if ($key === 'password') {
296
-			$value = $this->encryptValue($value);
297
-		}
298
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
-			'mount_id' => $mountId,
300
-			'key' => $key,
301
-			'value' => $value
302
-		], ['mount_id', 'key']);
303
-		if ($count === 0) {
304
-			$builder = $this->connection->getQueryBuilder();
305
-			$query = $builder->update('external_config')
306
-				->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
-			$query->execute();
310
-		}
311
-	}
312
-
313
-	/**
314
-	 * @param int $mountId
315
-	 * @param string $key
316
-	 * @param string $value
317
-	 */
318
-	public function setOption($mountId, $key, $value) {
319
-
320
-		$count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
-			'mount_id' => $mountId,
322
-			'key' => $key,
323
-			'value' => json_encode($value)
324
-		], ['mount_id', 'key']);
325
-		if ($count === 0) {
326
-			$builder = $this->connection->getQueryBuilder();
327
-			$query = $builder->update('external_options')
328
-				->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
-				->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
-				->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
-			$query->execute();
332
-		}
333
-	}
334
-
335
-	public function addApplicable($mountId, $type, $value) {
336
-		$this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
-			'mount_id' => $mountId,
338
-			'type' => $type,
339
-			'value' => $value
340
-		], ['mount_id', 'type', 'value']);
341
-	}
342
-
343
-	public function removeApplicable($mountId, $type, $value) {
344
-		$builder = $this->connection->getQueryBuilder();
345
-		$query = $builder->delete('external_applicable')
346
-			->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
-			->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
-
349
-		if (is_null($value)) {
350
-			$query = $query->andWhere($builder->expr()->isNull('value'));
351
-		} else {
352
-			$query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
-		}
354
-
355
-		$query->execute();
356
-	}
357
-
358
-	private function getMountsFromQuery(IQueryBuilder $query) {
359
-		$result = $query->execute();
360
-		$mounts = $result->fetchAll();
361
-		$uniqueMounts = [];
362
-		foreach ($mounts as $mount) {
363
-			$id = $mount['mount_id'];
364
-			if (!isset($uniqueMounts[$id])) {
365
-				$uniqueMounts[$id] = $mount;
366
-			}
367
-		}
368
-		$uniqueMounts = array_values($uniqueMounts);
369
-
370
-		$mountIds = array_map(function ($mount) {
371
-			return $mount['mount_id'];
372
-		}, $uniqueMounts);
373
-		$mountIds = array_values(array_unique($mountIds));
374
-
375
-		$applicable = $this->getApplicableForMounts($mountIds);
376
-		$config = $this->getConfigForMounts($mountIds);
377
-		$options = $this->getOptionsForMounts($mountIds);
378
-
379
-		return array_map(function ($mount, $applicable, $config, $options) {
380
-			$mount['type'] = (int)$mount['type'];
381
-			$mount['priority'] = (int)$mount['priority'];
382
-			$mount['applicable'] = $applicable;
383
-			$mount['config'] = $config;
384
-			$mount['options'] = $options;
385
-			return $mount;
386
-		}, $uniqueMounts, $applicable, $config, $options);
387
-	}
388
-
389
-	/**
390
-	 * Get mount options from a table grouped by mount id
391
-	 *
392
-	 * @param string $table
393
-	 * @param string[] $fields
394
-	 * @param int[] $mountIds
395
-	 * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
-	 */
397
-	private function selectForMounts($table, array $fields, array $mountIds) {
398
-		if (count($mountIds) === 0) {
399
-			return [];
400
-		}
401
-		$builder = $this->connection->getQueryBuilder();
402
-		$fields[] = 'mount_id';
403
-		$placeHolders = array_map(function ($id) use ($builder) {
404
-			return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
-		}, $mountIds);
406
-		$query = $builder->select($fields)
407
-			->from($table)
408
-			->where($builder->expr()->in('mount_id', $placeHolders));
409
-		$rows = $query->execute()->fetchAll();
410
-
411
-		$result = [];
412
-		foreach ($mountIds as $mountId) {
413
-			$result[$mountId] = [];
414
-		}
415
-		foreach ($rows as $row) {
416
-			if (isset($row['type'])) {
417
-				$row['type'] = (int)$row['type'];
418
-			}
419
-			$result[$row['mount_id']][] = $row;
420
-		}
421
-		return $result;
422
-	}
423
-
424
-	/**
425
-	 * @param int[] $mountIds
426
-	 * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
-	 */
428
-	public function getApplicableForMounts($mountIds) {
429
-		return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
-	}
431
-
432
-	/**
433
-	 * @param int[] $mountIds
434
-	 * @return array [$id => ['key1' => $value1, ...], ...]
435
-	 */
436
-	public function getConfigForMounts($mountIds) {
437
-		$mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
-		return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
-	}
440
-
441
-	/**
442
-	 * @param int[] $mountIds
443
-	 * @return array [$id => ['key1' => $value1, ...], ...]
444
-	 */
445
-	public function getOptionsForMounts($mountIds) {
446
-		$mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
-		$optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
-		return array_map(function (array $options) {
449
-			return array_map(function ($option) {
450
-				return json_decode($option);
451
-			}, $options);
452
-		}, $optionsMap);
453
-	}
454
-
455
-	/**
456
-	 * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
-	 * @return array ['key1' => $value1, ...]
458
-	 */
459
-	private function createKeyValueMap(array $keyValuePairs) {
460
-		$decryptedPairts = array_map(function ($pair) {
461
-			if ($pair['key'] === 'password') {
462
-				$pair['value'] = $this->decryptValue($pair['value']);
463
-			}
464
-			return $pair;
465
-		}, $keyValuePairs);
466
-		$keys = array_map(function ($pair) {
467
-			return $pair['key'];
468
-		}, $decryptedPairts);
469
-		$values = array_map(function ($pair) {
470
-			return $pair['value'];
471
-		}, $decryptedPairts);
472
-
473
-		return array_combine($keys, $values);
474
-	}
475
-
476
-	private function encryptValue($value) {
477
-		return $this->crypto->encrypt($value);
478
-	}
479
-
480
-	private function decryptValue($value) {
481
-		try {
482
-			return $this->crypto->decrypt($value);
483
-		} catch (\Exception $e) {
484
-			return $value;
485
-		}
486
-	}
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_INT_ARRAY))
109
+                )
110
+            ));
111
+
112
+        return $this->getMountsFromQuery($query);
113
+    }
114
+
115
+    /**
116
+     * Get admin defined mounts
117
+     *
118
+     * @return array
119
+     */
120
+    public function getAdminMounts() {
121
+        $builder = $this->connection->getQueryBuilder();
122
+        $query = $builder->select(['mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'type'])
123
+            ->from('external_mounts')
124
+            ->where($builder->expr()->eq('type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
125
+        return $this->getMountsFromQuery($query);
126
+    }
127
+
128
+    protected function getForQuery(IQueryBuilder $builder, $type, $value) {
129
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
130
+            ->from('external_mounts', 'm')
131
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
132
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
133
+
134
+        if (is_null($value)) {
135
+            $query = $query->andWhere($builder->expr()->isNull('a.value'));
136
+        } else {
137
+            $query = $query->andWhere($builder->expr()->eq('a.value', $builder->createNamedParameter($value)));
138
+        }
139
+
140
+        return $query;
141
+    }
142
+
143
+    /**
144
+     * Get mounts by applicable
145
+     *
146
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
147
+     * @param string|null $value user_id, group_id or null for global mounts
148
+     * @return array
149
+     */
150
+    public function getMountsFor($type, $value) {
151
+        $builder = $this->connection->getQueryBuilder();
152
+        $query = $this->getForQuery($builder, $type, $value);
153
+
154
+        return $this->getMountsFromQuery($query);
155
+    }
156
+
157
+    /**
158
+     * Get admin defined mounts by applicable
159
+     *
160
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
161
+     * @param string|null $value user_id, group_id or null for global mounts
162
+     * @return array
163
+     */
164
+    public function getAdminMountsFor($type, $value) {
165
+        $builder = $this->connection->getQueryBuilder();
166
+        $query = $this->getForQuery($builder, $type, $value);
167
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
168
+
169
+        return $this->getMountsFromQuery($query);
170
+    }
171
+
172
+    /**
173
+     * Get admin defined mounts for multiple applicable
174
+     *
175
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
176
+     * @param string[] $values user_ids or group_ids
177
+     * @return array
178
+     */
179
+    public function getAdminMountsForMultiple($type, array $values) {
180
+        $builder = $this->connection->getQueryBuilder();
181
+        $params = array_map(function ($value) use ($builder) {
182
+            return $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR);
183
+        }, $values);
184
+
185
+        $query = $builder->select(['m.mount_id', 'mount_point', 'storage_backend', 'auth_backend', 'priority', 'm.type'])
186
+            ->from('external_mounts', 'm')
187
+            ->innerJoin('m', 'external_applicable', 'a', $builder->expr()->eq('m.mount_id', 'a.mount_id'))
188
+            ->where($builder->expr()->eq('a.type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)))
189
+            ->andWhere($builder->expr()->in('a.value', $params));
190
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_ADMIN, IQueryBuilder::PARAM_INT)));
191
+
192
+        return $this->getMountsFromQuery($query);
193
+    }
194
+
195
+    /**
196
+     * Get user defined mounts by applicable
197
+     *
198
+     * @param int $type any of the self::APPLICABLE_TYPE_ constants
199
+     * @param string|null $value user_id, group_id or null for global mounts
200
+     * @return array
201
+     */
202
+    public function getUserMountsFor($type, $value) {
203
+        $builder = $this->connection->getQueryBuilder();
204
+        $query = $this->getForQuery($builder, $type, $value);
205
+        $query->andWhere($builder->expr()->eq('m.type', $builder->expr()->literal(self::MOUNT_TYPE_PERSONAl, IQueryBuilder::PARAM_INT)));
206
+
207
+        return $this->getMountsFromQuery($query);
208
+    }
209
+
210
+    /**
211
+     * Add a mount to the database
212
+     *
213
+     * @param string $mountPoint
214
+     * @param string $storageBackend
215
+     * @param string $authBackend
216
+     * @param int $priority
217
+     * @param int $type self::MOUNT_TYPE_ADMIN or self::MOUNT_TYPE_PERSONAL
218
+     * @return int the id of the new mount
219
+     */
220
+    public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
221
+        if (!$priority) {
222
+            $priority = 100;
223
+        }
224
+        $builder = $this->connection->getQueryBuilder();
225
+        $query = $builder->insert('external_mounts')
226
+            ->values([
227
+                'mount_point' => $builder->createNamedParameter($mountPoint, IQueryBuilder::PARAM_STR),
228
+                'storage_backend' => $builder->createNamedParameter($storageBackend, IQueryBuilder::PARAM_STR),
229
+                'auth_backend' => $builder->createNamedParameter($authBackend, IQueryBuilder::PARAM_STR),
230
+                'priority' => $builder->createNamedParameter($priority, IQueryBuilder::PARAM_INT),
231
+                'type' => $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)
232
+            ]);
233
+        $query->execute();
234
+        return (int)$this->connection->lastInsertId('*PREFIX*external_mounts');
235
+    }
236
+
237
+    /**
238
+     * Remove a mount from the database
239
+     *
240
+     * @param int $mountId
241
+     */
242
+    public function removeMount($mountId) {
243
+        $builder = $this->connection->getQueryBuilder();
244
+        $query = $builder->delete('external_mounts')
245
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
246
+        $query->execute();
247
+
248
+        $query = $builder->delete('external_applicable')
249
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
250
+        $query->execute();
251
+
252
+        $query = $builder->delete('external_config')
253
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
254
+        $query->execute();
255
+
256
+        $query = $builder->delete('external_options')
257
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
258
+        $query->execute();
259
+    }
260
+
261
+    /**
262
+     * @param int $mountId
263
+     * @param string $newMountPoint
264
+     */
265
+    public function setMountPoint($mountId, $newMountPoint) {
266
+        $builder = $this->connection->getQueryBuilder();
267
+
268
+        $query = $builder->update('external_mounts')
269
+            ->set('mount_point', $builder->createNamedParameter($newMountPoint))
270
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
271
+
272
+        $query->execute();
273
+    }
274
+
275
+    /**
276
+     * @param int $mountId
277
+     * @param string $newAuthBackend
278
+     */
279
+    public function setAuthBackend($mountId, $newAuthBackend) {
280
+        $builder = $this->connection->getQueryBuilder();
281
+
282
+        $query = $builder->update('external_mounts')
283
+            ->set('auth_backend', $builder->createNamedParameter($newAuthBackend))
284
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)));
285
+
286
+        $query->execute();
287
+    }
288
+
289
+    /**
290
+     * @param int $mountId
291
+     * @param string $key
292
+     * @param string $value
293
+     */
294
+    public function setConfig($mountId, $key, $value) {
295
+        if ($key === 'password') {
296
+            $value = $this->encryptValue($value);
297
+        }
298
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_config', [
299
+            'mount_id' => $mountId,
300
+            'key' => $key,
301
+            'value' => $value
302
+        ], ['mount_id', 'key']);
303
+        if ($count === 0) {
304
+            $builder = $this->connection->getQueryBuilder();
305
+            $query = $builder->update('external_config')
306
+                ->set('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR))
307
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
308
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
309
+            $query->execute();
310
+        }
311
+    }
312
+
313
+    /**
314
+     * @param int $mountId
315
+     * @param string $key
316
+     * @param string $value
317
+     */
318
+    public function setOption($mountId, $key, $value) {
319
+
320
+        $count = $this->connection->insertIfNotExist('*PREFIX*external_options', [
321
+            'mount_id' => $mountId,
322
+            'key' => $key,
323
+            'value' => json_encode($value)
324
+        ], ['mount_id', 'key']);
325
+        if ($count === 0) {
326
+            $builder = $this->connection->getQueryBuilder();
327
+            $query = $builder->update('external_options')
328
+                ->set('value', $builder->createNamedParameter(json_encode($value), IQueryBuilder::PARAM_STR))
329
+                ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
330
+                ->andWhere($builder->expr()->eq('key', $builder->createNamedParameter($key, IQueryBuilder::PARAM_STR)));
331
+            $query->execute();
332
+        }
333
+    }
334
+
335
+    public function addApplicable($mountId, $type, $value) {
336
+        $this->connection->insertIfNotExist('*PREFIX*external_applicable', [
337
+            'mount_id' => $mountId,
338
+            'type' => $type,
339
+            'value' => $value
340
+        ], ['mount_id', 'type', 'value']);
341
+    }
342
+
343
+    public function removeApplicable($mountId, $type, $value) {
344
+        $builder = $this->connection->getQueryBuilder();
345
+        $query = $builder->delete('external_applicable')
346
+            ->where($builder->expr()->eq('mount_id', $builder->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
347
+            ->andWhere($builder->expr()->eq('type', $builder->createNamedParameter($type, IQueryBuilder::PARAM_INT)));
348
+
349
+        if (is_null($value)) {
350
+            $query = $query->andWhere($builder->expr()->isNull('value'));
351
+        } else {
352
+            $query = $query->andWhere($builder->expr()->eq('value', $builder->createNamedParameter($value, IQueryBuilder::PARAM_STR)));
353
+        }
354
+
355
+        $query->execute();
356
+    }
357
+
358
+    private function getMountsFromQuery(IQueryBuilder $query) {
359
+        $result = $query->execute();
360
+        $mounts = $result->fetchAll();
361
+        $uniqueMounts = [];
362
+        foreach ($mounts as $mount) {
363
+            $id = $mount['mount_id'];
364
+            if (!isset($uniqueMounts[$id])) {
365
+                $uniqueMounts[$id] = $mount;
366
+            }
367
+        }
368
+        $uniqueMounts = array_values($uniqueMounts);
369
+
370
+        $mountIds = array_map(function ($mount) {
371
+            return $mount['mount_id'];
372
+        }, $uniqueMounts);
373
+        $mountIds = array_values(array_unique($mountIds));
374
+
375
+        $applicable = $this->getApplicableForMounts($mountIds);
376
+        $config = $this->getConfigForMounts($mountIds);
377
+        $options = $this->getOptionsForMounts($mountIds);
378
+
379
+        return array_map(function ($mount, $applicable, $config, $options) {
380
+            $mount['type'] = (int)$mount['type'];
381
+            $mount['priority'] = (int)$mount['priority'];
382
+            $mount['applicable'] = $applicable;
383
+            $mount['config'] = $config;
384
+            $mount['options'] = $options;
385
+            return $mount;
386
+        }, $uniqueMounts, $applicable, $config, $options);
387
+    }
388
+
389
+    /**
390
+     * Get mount options from a table grouped by mount id
391
+     *
392
+     * @param string $table
393
+     * @param string[] $fields
394
+     * @param int[] $mountIds
395
+     * @return array [$mountId => [['field1' => $value1, ...], ...], ...]
396
+     */
397
+    private function selectForMounts($table, array $fields, array $mountIds) {
398
+        if (count($mountIds) === 0) {
399
+            return [];
400
+        }
401
+        $builder = $this->connection->getQueryBuilder();
402
+        $fields[] = 'mount_id';
403
+        $placeHolders = array_map(function ($id) use ($builder) {
404
+            return $builder->createPositionalParameter($id, IQueryBuilder::PARAM_INT);
405
+        }, $mountIds);
406
+        $query = $builder->select($fields)
407
+            ->from($table)
408
+            ->where($builder->expr()->in('mount_id', $placeHolders));
409
+        $rows = $query->execute()->fetchAll();
410
+
411
+        $result = [];
412
+        foreach ($mountIds as $mountId) {
413
+            $result[$mountId] = [];
414
+        }
415
+        foreach ($rows as $row) {
416
+            if (isset($row['type'])) {
417
+                $row['type'] = (int)$row['type'];
418
+            }
419
+            $result[$row['mount_id']][] = $row;
420
+        }
421
+        return $result;
422
+    }
423
+
424
+    /**
425
+     * @param int[] $mountIds
426
+     * @return array [$id => [['type' => $type, 'value' => $value], ...], ...]
427
+     */
428
+    public function getApplicableForMounts($mountIds) {
429
+        return $this->selectForMounts('external_applicable', ['type', 'value'], $mountIds);
430
+    }
431
+
432
+    /**
433
+     * @param int[] $mountIds
434
+     * @return array [$id => ['key1' => $value1, ...], ...]
435
+     */
436
+    public function getConfigForMounts($mountIds) {
437
+        $mountConfigs = $this->selectForMounts('external_config', ['key', 'value'], $mountIds);
438
+        return array_map([$this, 'createKeyValueMap'], $mountConfigs);
439
+    }
440
+
441
+    /**
442
+     * @param int[] $mountIds
443
+     * @return array [$id => ['key1' => $value1, ...], ...]
444
+     */
445
+    public function getOptionsForMounts($mountIds) {
446
+        $mountOptions = $this->selectForMounts('external_options', ['key', 'value'], $mountIds);
447
+        $optionsMap = array_map([$this, 'createKeyValueMap'], $mountOptions);
448
+        return array_map(function (array $options) {
449
+            return array_map(function ($option) {
450
+                return json_decode($option);
451
+            }, $options);
452
+        }, $optionsMap);
453
+    }
454
+
455
+    /**
456
+     * @param array $keyValuePairs [['key'=>$key, 'value=>$value], ...]
457
+     * @return array ['key1' => $value1, ...]
458
+     */
459
+    private function createKeyValueMap(array $keyValuePairs) {
460
+        $decryptedPairts = array_map(function ($pair) {
461
+            if ($pair['key'] === 'password') {
462
+                $pair['value'] = $this->decryptValue($pair['value']);
463
+            }
464
+            return $pair;
465
+        }, $keyValuePairs);
466
+        $keys = array_map(function ($pair) {
467
+            return $pair['key'];
468
+        }, $decryptedPairts);
469
+        $values = array_map(function ($pair) {
470
+            return $pair['value'];
471
+        }, $decryptedPairts);
472
+
473
+        return array_combine($keys, $values);
474
+    }
475
+
476
+    private function encryptValue($value) {
477
+        return $this->crypto->encrypt($value);
478
+    }
479
+
480
+    private function decryptValue($value) {
481
+        try {
482
+            return $this->crypto->decrypt($value);
483
+        } catch (\Exception $e) {
484
+            return $value;
485
+        }
486
+    }
487 487
 }
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.
apps/federation/lib/AppInfo/Application.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -24,16 +24,13 @@
 block discarded – undo
24 24
 
25 25
 namespace OCA\Federation\AppInfo;
26 26
 
27
-use OCA\Federation\API\OCSAuthAPI;
28 27
 use OCA\Federation\Controller\SettingsController;
29 28
 use OCA\Federation\DAV\FedAuth;
30 29
 use OCA\Federation\DbHandler;
31 30
 use OCA\Federation\Hooks;
32 31
 use OCA\Federation\Middleware\AddServerMiddleware;
33 32
 use OCA\Federation\SyncFederationAddressBooks;
34
-use OCA\Federation\SyncJob;
35 33
 use OCA\Federation\TrustedServers;
36
-use OCP\API;
37 34
 use OCP\App;
38 35
 use OCP\AppFramework\IAppContainer;
39 36
 use OCP\SabrePluginEvent;
Please login to merge, or discard this patch.
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -42,100 +42,100 @@
 block discarded – undo
42 42
 
43 43
 class Application extends \OCP\AppFramework\App {
44 44
 
45
-	/**
46
-	 * @param array $urlParams
47
-	 */
48
-	public function __construct($urlParams = array()) {
49
-		parent::__construct('federation', $urlParams);
50
-		$this->registerService();
51
-		$this->registerMiddleware();
52
-	}
53
-
54
-	private function registerService() {
55
-		$container = $this->getContainer();
56
-
57
-		$container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
-			return new AddServerMiddleware(
59
-				$c->getAppName(),
60
-				\OC::$server->getL10N($c->getAppName()),
61
-				\OC::$server->getLogger()
62
-			);
63
-		});
64
-
65
-		$container->registerService('DbHandler', function(IAppContainer $c) {
66
-			return new DbHandler(
67
-				\OC::$server->getDatabaseConnection(),
68
-				\OC::$server->getL10N($c->getAppName())
69
-			);
70
-		});
71
-
72
-		$container->registerService('TrustedServers', function(IAppContainer $c) {
73
-			$server = $c->getServer();
74
-			return new TrustedServers(
75
-				$c->query('DbHandler'),
76
-				$server->getHTTPClientService(),
77
-				$server->getLogger(),
78
-				$server->getJobList(),
79
-				$server->getSecureRandom(),
80
-				$server->getConfig(),
81
-				$server->getEventDispatcher()
82
-			);
83
-		});
84
-
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
86
-			$server = $c->getServer();
87
-			return new SettingsController(
88
-				$c->getAppName(),
89
-				$server->getRequest(),
90
-				$server->getL10N($c->getAppName()),
91
-				$c->query('TrustedServers')
92
-			);
93
-		});
94
-
95
-	}
96
-
97
-	private function registerMiddleware() {
98
-		$container = $this->getContainer();
99
-		$container->registerMiddleware('addServerMiddleware');
100
-	}
101
-
102
-	/**
103
-	 * listen to federated_share_added hooks to auto-add new servers to the
104
-	 * list of trusted servers.
105
-	 */
106
-	public function registerHooks() {
107
-
108
-		$container = $this->getContainer();
109
-		$hooksManager = new Hooks($container->query('TrustedServers'));
110
-
111
-		Util::connectHook(
112
-				'OCP\Share',
113
-				'federated_share_added',
114
-				$hooksManager,
115
-				'addServerHook'
116
-		);
117
-
118
-		$dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
-		$dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
-			if ($event instanceof SabrePluginEvent) {
121
-				$authPlugin = $event->getServer()->getPlugin('auth');
122
-				if ($authPlugin instanceof Plugin) {
123
-					$h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
-							$container->getServer()->getL10N('federation')
125
-					);
126
-					$authPlugin->addBackend(new FedAuth($h));
127
-				}
128
-			}
129
-		});
130
-	}
131
-
132
-	/**
133
-	 * @return SyncFederationAddressBooks
134
-	 */
135
-	public function getSyncService() {
136
-		$syncService = \OC::$server->query('CardDAVSyncService');
137
-		$dbHandler = $this->getContainer()->query('DbHandler');
138
-		return new SyncFederationAddressBooks($dbHandler, $syncService);
139
-	}
45
+    /**
46
+     * @param array $urlParams
47
+     */
48
+    public function __construct($urlParams = array()) {
49
+        parent::__construct('federation', $urlParams);
50
+        $this->registerService();
51
+        $this->registerMiddleware();
52
+    }
53
+
54
+    private function registerService() {
55
+        $container = $this->getContainer();
56
+
57
+        $container->registerService('addServerMiddleware', function(IAppContainer $c) {
58
+            return new AddServerMiddleware(
59
+                $c->getAppName(),
60
+                \OC::$server->getL10N($c->getAppName()),
61
+                \OC::$server->getLogger()
62
+            );
63
+        });
64
+
65
+        $container->registerService('DbHandler', function(IAppContainer $c) {
66
+            return new DbHandler(
67
+                \OC::$server->getDatabaseConnection(),
68
+                \OC::$server->getL10N($c->getAppName())
69
+            );
70
+        });
71
+
72
+        $container->registerService('TrustedServers', function(IAppContainer $c) {
73
+            $server = $c->getServer();
74
+            return new TrustedServers(
75
+                $c->query('DbHandler'),
76
+                $server->getHTTPClientService(),
77
+                $server->getLogger(),
78
+                $server->getJobList(),
79
+                $server->getSecureRandom(),
80
+                $server->getConfig(),
81
+                $server->getEventDispatcher()
82
+            );
83
+        });
84
+
85
+        $container->registerService('SettingsController', function (IAppContainer $c) {
86
+            $server = $c->getServer();
87
+            return new SettingsController(
88
+                $c->getAppName(),
89
+                $server->getRequest(),
90
+                $server->getL10N($c->getAppName()),
91
+                $c->query('TrustedServers')
92
+            );
93
+        });
94
+
95
+    }
96
+
97
+    private function registerMiddleware() {
98
+        $container = $this->getContainer();
99
+        $container->registerMiddleware('addServerMiddleware');
100
+    }
101
+
102
+    /**
103
+     * listen to federated_share_added hooks to auto-add new servers to the
104
+     * list of trusted servers.
105
+     */
106
+    public function registerHooks() {
107
+
108
+        $container = $this->getContainer();
109
+        $hooksManager = new Hooks($container->query('TrustedServers'));
110
+
111
+        Util::connectHook(
112
+                'OCP\Share',
113
+                'federated_share_added',
114
+                $hooksManager,
115
+                'addServerHook'
116
+        );
117
+
118
+        $dispatcher = $this->getContainer()->getServer()->getEventDispatcher();
119
+        $dispatcher->addListener('OCA\DAV\Connector\Sabre::authInit', function($event) use($container) {
120
+            if ($event instanceof SabrePluginEvent) {
121
+                $authPlugin = $event->getServer()->getPlugin('auth');
122
+                if ($authPlugin instanceof Plugin) {
123
+                    $h = new DbHandler($container->getServer()->getDatabaseConnection(),
124
+                            $container->getServer()->getL10N('federation')
125
+                    );
126
+                    $authPlugin->addBackend(new FedAuth($h));
127
+                }
128
+            }
129
+        });
130
+    }
131
+
132
+    /**
133
+     * @return SyncFederationAddressBooks
134
+     */
135
+    public function getSyncService() {
136
+        $syncService = \OC::$server->query('CardDAVSyncService');
137
+        $dbHandler = $this->getContainer()->query('DbHandler');
138
+        return new SyncFederationAddressBooks($dbHandler, $syncService);
139
+    }
140 140
 
141 141
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@
 block discarded – undo
82 82
 			);
83 83
 		});
84 84
 
85
-		$container->registerService('SettingsController', function (IAppContainer $c) {
85
+		$container->registerService('SettingsController', function(IAppContainer $c) {
86 86
 			$server = $c->getServer();
87 87
 			return new SettingsController(
88 88
 				$c->getAppName(),
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
@@ -95,7 +95,6 @@
 block discarded – undo
95 95
 use OC\Tagging\TagMapper;
96 96
 use OC\Template\SCSSCacher;
97 97
 use OCA\Theming\ThemingDefaults;
98
-
99 98
 use OCP\App\IAppManager;
100 99
 use OCA\Theming\Util;
101 100
 use OCP\Federation\ICloudIdManager;
Please login to merge, or discard this patch.
Indentation   +1600 added lines, -1600 removed lines patch added patch discarded remove patch
@@ -119,1609 +119,1609 @@
 block discarded – undo
119 119
  * TODO: hookup all manager classes
120 120
  */
121 121
 class Server extends ServerContainer implements IServerContainer {
122
-	/** @var string */
123
-	private $webRoot;
124
-
125
-	/**
126
-	 * @param string $webRoot
127
-	 * @param \OC\Config $config
128
-	 */
129
-	public function __construct($webRoot, \OC\Config $config) {
130
-		parent::__construct();
131
-		$this->webRoot = $webRoot;
132
-
133
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135
-
136
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
137
-			return new PreviewManager(
138
-				$c->getConfig(),
139
-				$c->getRootFolder(),
140
-				$c->getAppDataDir('preview'),
141
-				$c->getEventDispatcher(),
142
-				$c->getSession()->get('user_id')
143
-			);
144
-		});
145
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
146
-
147
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
148
-			return new \OC\Preview\Watcher(
149
-				$c->getAppDataDir('preview')
150
-			);
151
-		});
152
-
153
-		$this->registerService('EncryptionManager', function (Server $c) {
154
-			$view = new View();
155
-			$util = new Encryption\Util(
156
-				$view,
157
-				$c->getUserManager(),
158
-				$c->getGroupManager(),
159
-				$c->getConfig()
160
-			);
161
-			return new Encryption\Manager(
162
-				$c->getConfig(),
163
-				$c->getLogger(),
164
-				$c->getL10N('core'),
165
-				new View(),
166
-				$util,
167
-				new ArrayCache()
168
-			);
169
-		});
170
-
171
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
172
-			$util = new Encryption\Util(
173
-				new View(),
174
-				$c->getUserManager(),
175
-				$c->getGroupManager(),
176
-				$c->getConfig()
177
-			);
178
-			return new Encryption\File($util);
179
-		});
180
-
181
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
182
-			$view = new View();
183
-			$util = new Encryption\Util(
184
-				$view,
185
-				$c->getUserManager(),
186
-				$c->getGroupManager(),
187
-				$c->getConfig()
188
-			);
189
-
190
-			return new Encryption\Keys\Storage($view, $util);
191
-		});
192
-		$this->registerService('TagMapper', function (Server $c) {
193
-			return new TagMapper($c->getDatabaseConnection());
194
-		});
195
-
196
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
197
-			$tagMapper = $c->query('TagMapper');
198
-			return new TagManager($tagMapper, $c->getUserSession());
199
-		});
200
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
201
-
202
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
203
-			$config = $c->getConfig();
204
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
205
-			/** @var \OC\SystemTag\ManagerFactory $factory */
206
-			$factory = new $factoryClass($this);
207
-			return $factory;
208
-		});
209
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
210
-			return $c->query('SystemTagManagerFactory')->getManager();
211
-		});
212
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
213
-
214
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
215
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
216
-		});
217
-		$this->registerService('RootFolder', function (Server $c) {
218
-			$manager = \OC\Files\Filesystem::getMountManager(null);
219
-			$view = new View();
220
-			$root = new Root(
221
-				$manager,
222
-				$view,
223
-				null,
224
-				$c->getUserMountCache(),
225
-				$this->getLogger(),
226
-				$this->getUserManager()
227
-			);
228
-			$connector = new HookConnector($root, $view);
229
-			$connector->viewToNode();
230
-
231
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
232
-			$previewConnector->connectWatcher();
233
-
234
-			return $root;
235
-		});
236
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
237
-
238
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
239
-			return new LazyRoot(function() use ($c) {
240
-				return $c->query('RootFolder');
241
-			});
242
-		});
243
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
244
-
245
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
246
-			$config = $c->getConfig();
247
-			return new \OC\User\Manager($config);
248
-		});
249
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
250
-
251
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
252
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
253
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
254
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
255
-			});
256
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
257
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
258
-			});
259
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
260
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
261
-			});
262
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
263
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
264
-			});
265
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
267
-			});
268
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
269
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
270
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
271
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
272
-			});
273
-			return $groupManager;
274
-		});
275
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
276
-
277
-		$this->registerService(Store::class, function(Server $c) {
278
-			$session = $c->getSession();
279
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
280
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
281
-			} else {
282
-				$tokenProvider = null;
283
-			}
284
-			$logger = $c->getLogger();
285
-			return new Store($session, $logger, $tokenProvider);
286
-		});
287
-		$this->registerAlias(IStore::class, Store::class);
288
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
289
-			$dbConnection = $c->getDatabaseConnection();
290
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
291
-		});
292
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
293
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
294
-			$crypto = $c->getCrypto();
295
-			$config = $c->getConfig();
296
-			$logger = $c->getLogger();
297
-			$timeFactory = new TimeFactory();
298
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
299
-		});
300
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
301
-
302
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
303
-			$manager = $c->getUserManager();
304
-			$session = new \OC\Session\Memory('');
305
-			$timeFactory = new TimeFactory();
306
-			// Token providers might require a working database. This code
307
-			// might however be called when ownCloud is not yet setup.
308
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
309
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
310
-			} else {
311
-				$defaultTokenProvider = null;
312
-			}
313
-
314
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
315
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
316
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
317
-			});
318
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
319
-				/** @var $user \OC\User\User */
320
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
321
-			});
322
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
323
-				/** @var $user \OC\User\User */
324
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
325
-			});
326
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
327
-				/** @var $user \OC\User\User */
328
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
329
-			});
330
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
331
-				/** @var $user \OC\User\User */
332
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
333
-			});
334
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
335
-				/** @var $user \OC\User\User */
336
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337
-			});
338
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
339
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
340
-			});
341
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
342
-				/** @var $user \OC\User\User */
343
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
344
-			});
345
-			$userSession->listen('\OC\User', 'logout', function () {
346
-				\OC_Hook::emit('OC_User', 'logout', array());
347
-			});
348
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
349
-				/** @var $user \OC\User\User */
350
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
351
-			});
352
-			return $userSession;
353
-		});
354
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
355
-
356
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
357
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
358
-		});
359
-
360
-		$this->registerService(\OCP\INavigationManager::class, function (Server $c) {
361
-			return new \OC\NavigationManager($c->getAppManager(),
362
-				$c->getURLGenerator(),
363
-				$c->getL10NFactory(),
364
-				$c->getUserSession(),
365
-				$c->getGroupManager());
366
-		});
367
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
368
-
369
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
370
-			return new \OC\AllConfig(
371
-				$c->getSystemConfig()
372
-			);
373
-		});
374
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
375
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
376
-
377
-		$this->registerService('SystemConfig', function ($c) use ($config) {
378
-			return new \OC\SystemConfig($config);
379
-		});
380
-
381
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
382
-			return new \OC\AppConfig($c->getDatabaseConnection());
383
-		});
384
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
385
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
386
-
387
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
388
-			return new \OC\L10N\Factory(
389
-				$c->getConfig(),
390
-				$c->getRequest(),
391
-				$c->getUserSession(),
392
-				\OC::$SERVERROOT
393
-			);
394
-		});
395
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
396
-
397
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
398
-			$config = $c->getConfig();
399
-			$cacheFactory = $c->getMemCacheFactory();
400
-			return new \OC\URLGenerator(
401
-				$config,
402
-				$cacheFactory
403
-			);
404
-		});
405
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
406
-
407
-		$this->registerService('AppHelper', function ($c) {
408
-			return new \OC\AppHelper();
409
-		});
410
-		$this->registerService('AppFetcher', function ($c) {
411
-			return new AppFetcher(
412
-				$this->getAppDataDir('appstore'),
413
-				$this->getHTTPClientService(),
414
-				$this->query(TimeFactory::class),
415
-				$this->getConfig()
416
-			);
417
-		});
418
-		$this->registerService('CategoryFetcher', function ($c) {
419
-			return new CategoryFetcher(
420
-				$this->getAppDataDir('appstore'),
421
-				$this->getHTTPClientService(),
422
-				$this->query(TimeFactory::class),
423
-				$this->getConfig()
424
-			);
425
-		});
426
-
427
-		$this->registerService(\OCP\ICache::class, function ($c) {
428
-			return new Cache\File();
429
-		});
430
-		$this->registerAlias('UserCache', \OCP\ICache::class);
431
-
432
-		$this->registerService(Factory::class, function (Server $c) {
433
-			$config = $c->getConfig();
434
-
435
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
436
-				$v = \OC_App::getAppVersions();
437
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
438
-				$version = implode(',', $v);
439
-				$instanceId = \OC_Util::getInstanceId();
440
-				$path = \OC::$SERVERROOT;
441
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
442
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
443
-					$config->getSystemValue('memcache.local', null),
444
-					$config->getSystemValue('memcache.distributed', null),
445
-					$config->getSystemValue('memcache.locking', null)
446
-				);
447
-			}
448
-
449
-			return new \OC\Memcache\Factory('', $c->getLogger(),
450
-				'\\OC\\Memcache\\ArrayCache',
451
-				'\\OC\\Memcache\\ArrayCache',
452
-				'\\OC\\Memcache\\ArrayCache'
453
-			);
454
-		});
455
-		$this->registerAlias('MemCacheFactory', Factory::class);
456
-		$this->registerAlias(ICacheFactory::class, Factory::class);
457
-
458
-		$this->registerService('RedisFactory', function (Server $c) {
459
-			$systemConfig = $c->getSystemConfig();
460
-			return new RedisFactory($systemConfig);
461
-		});
462
-
463
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
464
-			return new \OC\Activity\Manager(
465
-				$c->getRequest(),
466
-				$c->getUserSession(),
467
-				$c->getConfig(),
468
-				$c->query(IValidator::class)
469
-			);
470
-		});
471
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
472
-
473
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
474
-			return new \OC\Activity\EventMerger(
475
-				$c->getL10N('lib')
476
-			);
477
-		});
478
-		$this->registerAlias(IValidator::class, Validator::class);
479
-
480
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
481
-			return new AvatarManager(
482
-				$c->getUserManager(),
483
-				$c->getAppDataDir('avatar'),
484
-				$c->getL10N('lib'),
485
-				$c->getLogger(),
486
-				$c->getConfig()
487
-			);
488
-		});
489
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
490
-
491
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
492
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
493
-			$logger = Log::getLogClass($logType);
494
-			call_user_func(array($logger, 'init'));
495
-
496
-			return new Log($logger);
497
-		});
498
-		$this->registerAlias('Logger', \OCP\ILogger::class);
499
-
500
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
501
-			$config = $c->getConfig();
502
-			return new \OC\BackgroundJob\JobList(
503
-				$c->getDatabaseConnection(),
504
-				$config,
505
-				new TimeFactory()
506
-			);
507
-		});
508
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
509
-
510
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
511
-			$cacheFactory = $c->getMemCacheFactory();
512
-			$logger = $c->getLogger();
513
-			if ($cacheFactory->isAvailable()) {
514
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
515
-			} else {
516
-				$router = new \OC\Route\Router($logger);
517
-			}
518
-			return $router;
519
-		});
520
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
521
-
522
-		$this->registerService(\OCP\ISearch::class, function ($c) {
523
-			return new Search();
524
-		});
525
-		$this->registerAlias('Search', \OCP\ISearch::class);
526
-
527
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
528
-			return new SecureRandom();
529
-		});
530
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
531
-
532
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
533
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
534
-		});
535
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
536
-
537
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
538
-			return new Hasher($c->getConfig());
539
-		});
540
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
541
-
542
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
543
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
544
-		});
545
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
546
-
547
-		$this->registerService(IDBConnection::class, function (Server $c) {
548
-			$systemConfig = $c->getSystemConfig();
549
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
550
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
551
-			if (!$factory->isValidType($type)) {
552
-				throw new \OC\DatabaseException('Invalid database type');
553
-			}
554
-			$connectionParams = $factory->createConnectionParams();
555
-			$connection = $factory->getConnection($type, $connectionParams);
556
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
557
-			return $connection;
558
-		});
559
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
560
-
561
-		$this->registerService('HTTPHelper', function (Server $c) {
562
-			$config = $c->getConfig();
563
-			return new HTTPHelper(
564
-				$config,
565
-				$c->getHTTPClientService()
566
-			);
567
-		});
568
-
569
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
570
-			$user = \OC_User::getUser();
571
-			$uid = $user ? $user : null;
572
-			return new ClientService(
573
-				$c->getConfig(),
574
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
575
-			);
576
-		});
577
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
578
-
579
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
580
-			if ($c->getSystemConfig()->getValue('debug', false)) {
581
-				return new EventLogger();
582
-			} else {
583
-				return new NullEventLogger();
584
-			}
585
-		});
586
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
587
-
588
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
589
-			if ($c->getSystemConfig()->getValue('debug', false)) {
590
-				return new QueryLogger();
591
-			} else {
592
-				return new NullQueryLogger();
593
-			}
594
-		});
595
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
596
-
597
-		$this->registerService(TempManager::class, function (Server $c) {
598
-			return new TempManager(
599
-				$c->getLogger(),
600
-				$c->getConfig()
601
-			);
602
-		});
603
-		$this->registerAlias('TempManager', TempManager::class);
604
-		$this->registerAlias(ITempManager::class, TempManager::class);
605
-
606
-		$this->registerService(AppManager::class, function (Server $c) {
607
-			return new \OC\App\AppManager(
608
-				$c->getUserSession(),
609
-				$c->getAppConfig(),
610
-				$c->getGroupManager(),
611
-				$c->getMemCacheFactory(),
612
-				$c->getEventDispatcher()
613
-			);
614
-		});
615
-		$this->registerAlias('AppManager', AppManager::class);
616
-		$this->registerAlias(IAppManager::class, AppManager::class);
617
-
618
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
619
-			return new DateTimeZone(
620
-				$c->getConfig(),
621
-				$c->getSession()
622
-			);
623
-		});
624
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
625
-
626
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
627
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
628
-
629
-			return new DateTimeFormatter(
630
-				$c->getDateTimeZone()->getTimeZone(),
631
-				$c->getL10N('lib', $language)
632
-			);
633
-		});
634
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
635
-
636
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
637
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
638
-			$listener = new UserMountCacheListener($mountCache);
639
-			$listener->listen($c->getUserManager());
640
-			return $mountCache;
641
-		});
642
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
643
-
644
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
645
-			$loader = \OC\Files\Filesystem::getLoader();
646
-			$mountCache = $c->query('UserMountCache');
647
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
648
-
649
-			// builtin providers
650
-
651
-			$config = $c->getConfig();
652
-			$manager->registerProvider(new CacheMountProvider($config));
653
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
654
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
655
-
656
-			return $manager;
657
-		});
658
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
659
-
660
-		$this->registerService('IniWrapper', function ($c) {
661
-			return new IniGetWrapper();
662
-		});
663
-		$this->registerService('AsyncCommandBus', function (Server $c) {
664
-			$jobList = $c->getJobList();
665
-			return new AsyncBus($jobList);
666
-		});
667
-		$this->registerService('TrustedDomainHelper', function ($c) {
668
-			return new TrustedDomainHelper($this->getConfig());
669
-		});
670
-		$this->registerService('Throttler', function(Server $c) {
671
-			return new Throttler(
672
-				$c->getDatabaseConnection(),
673
-				new TimeFactory(),
674
-				$c->getLogger(),
675
-				$c->getConfig()
676
-			);
677
-		});
678
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
679
-			// IConfig and IAppManager requires a working database. This code
680
-			// might however be called when ownCloud is not yet setup.
681
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
682
-				$config = $c->getConfig();
683
-				$appManager = $c->getAppManager();
684
-			} else {
685
-				$config = null;
686
-				$appManager = null;
687
-			}
688
-
689
-			return new Checker(
690
-					new EnvironmentHelper(),
691
-					new FileAccessHelper(),
692
-					new AppLocator(),
693
-					$config,
694
-					$c->getMemCacheFactory(),
695
-					$appManager,
696
-					$c->getTempManager()
697
-			);
698
-		});
699
-		$this->registerService(\OCP\IRequest::class, function ($c) {
700
-			if (isset($this['urlParams'])) {
701
-				$urlParams = $this['urlParams'];
702
-			} else {
703
-				$urlParams = [];
704
-			}
705
-
706
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
707
-				&& in_array('fakeinput', stream_get_wrappers())
708
-			) {
709
-				$stream = 'fakeinput://data';
710
-			} else {
711
-				$stream = 'php://input';
712
-			}
713
-
714
-			return new Request(
715
-				[
716
-					'get' => $_GET,
717
-					'post' => $_POST,
718
-					'files' => $_FILES,
719
-					'server' => $_SERVER,
720
-					'env' => $_ENV,
721
-					'cookies' => $_COOKIE,
722
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
723
-						? $_SERVER['REQUEST_METHOD']
724
-						: null,
725
-					'urlParams' => $urlParams,
726
-				],
727
-				$this->getSecureRandom(),
728
-				$this->getConfig(),
729
-				$this->getCsrfTokenManager(),
730
-				$stream
731
-			);
732
-		});
733
-		$this->registerAlias('Request', \OCP\IRequest::class);
734
-
735
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
736
-			return new Mailer(
737
-				$c->getConfig(),
738
-				$c->getLogger(),
739
-				$c->getThemingDefaults()
740
-			);
741
-		});
742
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
743
-
744
-		$this->registerService('LDAPProvider', function(Server $c) {
745
-			$config = $c->getConfig();
746
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
747
-			if(is_null($factoryClass)) {
748
-				throw new \Exception('ldapProviderFactory not set');
749
-			}
750
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
751
-			$factory = new $factoryClass($this);
752
-			return $factory->getLDAPProvider();
753
-		});
754
-		$this->registerService('LockingProvider', function (Server $c) {
755
-			$ini = $c->getIniWrapper();
756
-			$config = $c->getConfig();
757
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
758
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
759
-				/** @var \OC\Memcache\Factory $memcacheFactory */
760
-				$memcacheFactory = $c->getMemCacheFactory();
761
-				$memcache = $memcacheFactory->createLocking('lock');
762
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
763
-					return new MemcacheLockingProvider($memcache, $ttl);
764
-				}
765
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
766
-			}
767
-			return new NoopLockingProvider();
768
-		});
769
-
770
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
771
-			return new \OC\Files\Mount\Manager();
772
-		});
773
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
774
-
775
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
776
-			return new \OC\Files\Type\Detection(
777
-				$c->getURLGenerator(),
778
-				\OC::$configDir,
779
-				\OC::$SERVERROOT . '/resources/config/'
780
-			);
781
-		});
782
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
783
-
784
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
785
-			return new \OC\Files\Type\Loader(
786
-				$c->getDatabaseConnection()
787
-			);
788
-		});
789
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
790
-
791
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
792
-			return new Manager(
793
-				$c->query(IValidator::class)
794
-			);
795
-		});
796
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
797
-
798
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
799
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
800
-			$manager->registerCapability(function () use ($c) {
801
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
802
-			});
803
-			return $manager;
804
-		});
805
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
806
-
807
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
808
-			$config = $c->getConfig();
809
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
810
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
811
-			$factory = new $factoryClass($this);
812
-			return $factory->getManager();
813
-		});
814
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
815
-
816
-		$this->registerService('ThemingDefaults', function(Server $c) {
817
-			/*
122
+    /** @var string */
123
+    private $webRoot;
124
+
125
+    /**
126
+     * @param string $webRoot
127
+     * @param \OC\Config $config
128
+     */
129
+    public function __construct($webRoot, \OC\Config $config) {
130
+        parent::__construct();
131
+        $this->webRoot = $webRoot;
132
+
133
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135
+
136
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
137
+            return new PreviewManager(
138
+                $c->getConfig(),
139
+                $c->getRootFolder(),
140
+                $c->getAppDataDir('preview'),
141
+                $c->getEventDispatcher(),
142
+                $c->getSession()->get('user_id')
143
+            );
144
+        });
145
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
146
+
147
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
148
+            return new \OC\Preview\Watcher(
149
+                $c->getAppDataDir('preview')
150
+            );
151
+        });
152
+
153
+        $this->registerService('EncryptionManager', function (Server $c) {
154
+            $view = new View();
155
+            $util = new Encryption\Util(
156
+                $view,
157
+                $c->getUserManager(),
158
+                $c->getGroupManager(),
159
+                $c->getConfig()
160
+            );
161
+            return new Encryption\Manager(
162
+                $c->getConfig(),
163
+                $c->getLogger(),
164
+                $c->getL10N('core'),
165
+                new View(),
166
+                $util,
167
+                new ArrayCache()
168
+            );
169
+        });
170
+
171
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
172
+            $util = new Encryption\Util(
173
+                new View(),
174
+                $c->getUserManager(),
175
+                $c->getGroupManager(),
176
+                $c->getConfig()
177
+            );
178
+            return new Encryption\File($util);
179
+        });
180
+
181
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
182
+            $view = new View();
183
+            $util = new Encryption\Util(
184
+                $view,
185
+                $c->getUserManager(),
186
+                $c->getGroupManager(),
187
+                $c->getConfig()
188
+            );
189
+
190
+            return new Encryption\Keys\Storage($view, $util);
191
+        });
192
+        $this->registerService('TagMapper', function (Server $c) {
193
+            return new TagMapper($c->getDatabaseConnection());
194
+        });
195
+
196
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
197
+            $tagMapper = $c->query('TagMapper');
198
+            return new TagManager($tagMapper, $c->getUserSession());
199
+        });
200
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
201
+
202
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
203
+            $config = $c->getConfig();
204
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
205
+            /** @var \OC\SystemTag\ManagerFactory $factory */
206
+            $factory = new $factoryClass($this);
207
+            return $factory;
208
+        });
209
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
210
+            return $c->query('SystemTagManagerFactory')->getManager();
211
+        });
212
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
213
+
214
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
215
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
216
+        });
217
+        $this->registerService('RootFolder', function (Server $c) {
218
+            $manager = \OC\Files\Filesystem::getMountManager(null);
219
+            $view = new View();
220
+            $root = new Root(
221
+                $manager,
222
+                $view,
223
+                null,
224
+                $c->getUserMountCache(),
225
+                $this->getLogger(),
226
+                $this->getUserManager()
227
+            );
228
+            $connector = new HookConnector($root, $view);
229
+            $connector->viewToNode();
230
+
231
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
232
+            $previewConnector->connectWatcher();
233
+
234
+            return $root;
235
+        });
236
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
237
+
238
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
239
+            return new LazyRoot(function() use ($c) {
240
+                return $c->query('RootFolder');
241
+            });
242
+        });
243
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
244
+
245
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
246
+            $config = $c->getConfig();
247
+            return new \OC\User\Manager($config);
248
+        });
249
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
250
+
251
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
252
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
253
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
254
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
255
+            });
256
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
257
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
258
+            });
259
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
260
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
261
+            });
262
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
263
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
264
+            });
265
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
267
+            });
268
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
269
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
270
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
271
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
272
+            });
273
+            return $groupManager;
274
+        });
275
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
276
+
277
+        $this->registerService(Store::class, function(Server $c) {
278
+            $session = $c->getSession();
279
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
280
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
281
+            } else {
282
+                $tokenProvider = null;
283
+            }
284
+            $logger = $c->getLogger();
285
+            return new Store($session, $logger, $tokenProvider);
286
+        });
287
+        $this->registerAlias(IStore::class, Store::class);
288
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
289
+            $dbConnection = $c->getDatabaseConnection();
290
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
291
+        });
292
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
293
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
294
+            $crypto = $c->getCrypto();
295
+            $config = $c->getConfig();
296
+            $logger = $c->getLogger();
297
+            $timeFactory = new TimeFactory();
298
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
299
+        });
300
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
301
+
302
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
303
+            $manager = $c->getUserManager();
304
+            $session = new \OC\Session\Memory('');
305
+            $timeFactory = new TimeFactory();
306
+            // Token providers might require a working database. This code
307
+            // might however be called when ownCloud is not yet setup.
308
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
309
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
310
+            } else {
311
+                $defaultTokenProvider = null;
312
+            }
313
+
314
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
315
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
316
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
317
+            });
318
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
319
+                /** @var $user \OC\User\User */
320
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
321
+            });
322
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
323
+                /** @var $user \OC\User\User */
324
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
325
+            });
326
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
327
+                /** @var $user \OC\User\User */
328
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
329
+            });
330
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
331
+                /** @var $user \OC\User\User */
332
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
333
+            });
334
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
335
+                /** @var $user \OC\User\User */
336
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337
+            });
338
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
339
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
340
+            });
341
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
342
+                /** @var $user \OC\User\User */
343
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
344
+            });
345
+            $userSession->listen('\OC\User', 'logout', function () {
346
+                \OC_Hook::emit('OC_User', 'logout', array());
347
+            });
348
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
349
+                /** @var $user \OC\User\User */
350
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
351
+            });
352
+            return $userSession;
353
+        });
354
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
355
+
356
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
357
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
358
+        });
359
+
360
+        $this->registerService(\OCP\INavigationManager::class, function (Server $c) {
361
+            return new \OC\NavigationManager($c->getAppManager(),
362
+                $c->getURLGenerator(),
363
+                $c->getL10NFactory(),
364
+                $c->getUserSession(),
365
+                $c->getGroupManager());
366
+        });
367
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
368
+
369
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
370
+            return new \OC\AllConfig(
371
+                $c->getSystemConfig()
372
+            );
373
+        });
374
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
375
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
376
+
377
+        $this->registerService('SystemConfig', function ($c) use ($config) {
378
+            return new \OC\SystemConfig($config);
379
+        });
380
+
381
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
382
+            return new \OC\AppConfig($c->getDatabaseConnection());
383
+        });
384
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
385
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
386
+
387
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
388
+            return new \OC\L10N\Factory(
389
+                $c->getConfig(),
390
+                $c->getRequest(),
391
+                $c->getUserSession(),
392
+                \OC::$SERVERROOT
393
+            );
394
+        });
395
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
396
+
397
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
398
+            $config = $c->getConfig();
399
+            $cacheFactory = $c->getMemCacheFactory();
400
+            return new \OC\URLGenerator(
401
+                $config,
402
+                $cacheFactory
403
+            );
404
+        });
405
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
406
+
407
+        $this->registerService('AppHelper', function ($c) {
408
+            return new \OC\AppHelper();
409
+        });
410
+        $this->registerService('AppFetcher', function ($c) {
411
+            return new AppFetcher(
412
+                $this->getAppDataDir('appstore'),
413
+                $this->getHTTPClientService(),
414
+                $this->query(TimeFactory::class),
415
+                $this->getConfig()
416
+            );
417
+        });
418
+        $this->registerService('CategoryFetcher', function ($c) {
419
+            return new CategoryFetcher(
420
+                $this->getAppDataDir('appstore'),
421
+                $this->getHTTPClientService(),
422
+                $this->query(TimeFactory::class),
423
+                $this->getConfig()
424
+            );
425
+        });
426
+
427
+        $this->registerService(\OCP\ICache::class, function ($c) {
428
+            return new Cache\File();
429
+        });
430
+        $this->registerAlias('UserCache', \OCP\ICache::class);
431
+
432
+        $this->registerService(Factory::class, function (Server $c) {
433
+            $config = $c->getConfig();
434
+
435
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
436
+                $v = \OC_App::getAppVersions();
437
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
438
+                $version = implode(',', $v);
439
+                $instanceId = \OC_Util::getInstanceId();
440
+                $path = \OC::$SERVERROOT;
441
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
442
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
443
+                    $config->getSystemValue('memcache.local', null),
444
+                    $config->getSystemValue('memcache.distributed', null),
445
+                    $config->getSystemValue('memcache.locking', null)
446
+                );
447
+            }
448
+
449
+            return new \OC\Memcache\Factory('', $c->getLogger(),
450
+                '\\OC\\Memcache\\ArrayCache',
451
+                '\\OC\\Memcache\\ArrayCache',
452
+                '\\OC\\Memcache\\ArrayCache'
453
+            );
454
+        });
455
+        $this->registerAlias('MemCacheFactory', Factory::class);
456
+        $this->registerAlias(ICacheFactory::class, Factory::class);
457
+
458
+        $this->registerService('RedisFactory', function (Server $c) {
459
+            $systemConfig = $c->getSystemConfig();
460
+            return new RedisFactory($systemConfig);
461
+        });
462
+
463
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
464
+            return new \OC\Activity\Manager(
465
+                $c->getRequest(),
466
+                $c->getUserSession(),
467
+                $c->getConfig(),
468
+                $c->query(IValidator::class)
469
+            );
470
+        });
471
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
472
+
473
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
474
+            return new \OC\Activity\EventMerger(
475
+                $c->getL10N('lib')
476
+            );
477
+        });
478
+        $this->registerAlias(IValidator::class, Validator::class);
479
+
480
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
481
+            return new AvatarManager(
482
+                $c->getUserManager(),
483
+                $c->getAppDataDir('avatar'),
484
+                $c->getL10N('lib'),
485
+                $c->getLogger(),
486
+                $c->getConfig()
487
+            );
488
+        });
489
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
490
+
491
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
492
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
493
+            $logger = Log::getLogClass($logType);
494
+            call_user_func(array($logger, 'init'));
495
+
496
+            return new Log($logger);
497
+        });
498
+        $this->registerAlias('Logger', \OCP\ILogger::class);
499
+
500
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
501
+            $config = $c->getConfig();
502
+            return new \OC\BackgroundJob\JobList(
503
+                $c->getDatabaseConnection(),
504
+                $config,
505
+                new TimeFactory()
506
+            );
507
+        });
508
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
509
+
510
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
511
+            $cacheFactory = $c->getMemCacheFactory();
512
+            $logger = $c->getLogger();
513
+            if ($cacheFactory->isAvailable()) {
514
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
515
+            } else {
516
+                $router = new \OC\Route\Router($logger);
517
+            }
518
+            return $router;
519
+        });
520
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
521
+
522
+        $this->registerService(\OCP\ISearch::class, function ($c) {
523
+            return new Search();
524
+        });
525
+        $this->registerAlias('Search', \OCP\ISearch::class);
526
+
527
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
528
+            return new SecureRandom();
529
+        });
530
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
531
+
532
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
533
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
534
+        });
535
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
536
+
537
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
538
+            return new Hasher($c->getConfig());
539
+        });
540
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
541
+
542
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
543
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
544
+        });
545
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
546
+
547
+        $this->registerService(IDBConnection::class, function (Server $c) {
548
+            $systemConfig = $c->getSystemConfig();
549
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
550
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
551
+            if (!$factory->isValidType($type)) {
552
+                throw new \OC\DatabaseException('Invalid database type');
553
+            }
554
+            $connectionParams = $factory->createConnectionParams();
555
+            $connection = $factory->getConnection($type, $connectionParams);
556
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
557
+            return $connection;
558
+        });
559
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
560
+
561
+        $this->registerService('HTTPHelper', function (Server $c) {
562
+            $config = $c->getConfig();
563
+            return new HTTPHelper(
564
+                $config,
565
+                $c->getHTTPClientService()
566
+            );
567
+        });
568
+
569
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
570
+            $user = \OC_User::getUser();
571
+            $uid = $user ? $user : null;
572
+            return new ClientService(
573
+                $c->getConfig(),
574
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
575
+            );
576
+        });
577
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
578
+
579
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
580
+            if ($c->getSystemConfig()->getValue('debug', false)) {
581
+                return new EventLogger();
582
+            } else {
583
+                return new NullEventLogger();
584
+            }
585
+        });
586
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
587
+
588
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
589
+            if ($c->getSystemConfig()->getValue('debug', false)) {
590
+                return new QueryLogger();
591
+            } else {
592
+                return new NullQueryLogger();
593
+            }
594
+        });
595
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
596
+
597
+        $this->registerService(TempManager::class, function (Server $c) {
598
+            return new TempManager(
599
+                $c->getLogger(),
600
+                $c->getConfig()
601
+            );
602
+        });
603
+        $this->registerAlias('TempManager', TempManager::class);
604
+        $this->registerAlias(ITempManager::class, TempManager::class);
605
+
606
+        $this->registerService(AppManager::class, function (Server $c) {
607
+            return new \OC\App\AppManager(
608
+                $c->getUserSession(),
609
+                $c->getAppConfig(),
610
+                $c->getGroupManager(),
611
+                $c->getMemCacheFactory(),
612
+                $c->getEventDispatcher()
613
+            );
614
+        });
615
+        $this->registerAlias('AppManager', AppManager::class);
616
+        $this->registerAlias(IAppManager::class, AppManager::class);
617
+
618
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
619
+            return new DateTimeZone(
620
+                $c->getConfig(),
621
+                $c->getSession()
622
+            );
623
+        });
624
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
625
+
626
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
627
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
628
+
629
+            return new DateTimeFormatter(
630
+                $c->getDateTimeZone()->getTimeZone(),
631
+                $c->getL10N('lib', $language)
632
+            );
633
+        });
634
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
635
+
636
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
637
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
638
+            $listener = new UserMountCacheListener($mountCache);
639
+            $listener->listen($c->getUserManager());
640
+            return $mountCache;
641
+        });
642
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
643
+
644
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
645
+            $loader = \OC\Files\Filesystem::getLoader();
646
+            $mountCache = $c->query('UserMountCache');
647
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
648
+
649
+            // builtin providers
650
+
651
+            $config = $c->getConfig();
652
+            $manager->registerProvider(new CacheMountProvider($config));
653
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
654
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
655
+
656
+            return $manager;
657
+        });
658
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
659
+
660
+        $this->registerService('IniWrapper', function ($c) {
661
+            return new IniGetWrapper();
662
+        });
663
+        $this->registerService('AsyncCommandBus', function (Server $c) {
664
+            $jobList = $c->getJobList();
665
+            return new AsyncBus($jobList);
666
+        });
667
+        $this->registerService('TrustedDomainHelper', function ($c) {
668
+            return new TrustedDomainHelper($this->getConfig());
669
+        });
670
+        $this->registerService('Throttler', function(Server $c) {
671
+            return new Throttler(
672
+                $c->getDatabaseConnection(),
673
+                new TimeFactory(),
674
+                $c->getLogger(),
675
+                $c->getConfig()
676
+            );
677
+        });
678
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
679
+            // IConfig and IAppManager requires a working database. This code
680
+            // might however be called when ownCloud is not yet setup.
681
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
682
+                $config = $c->getConfig();
683
+                $appManager = $c->getAppManager();
684
+            } else {
685
+                $config = null;
686
+                $appManager = null;
687
+            }
688
+
689
+            return new Checker(
690
+                    new EnvironmentHelper(),
691
+                    new FileAccessHelper(),
692
+                    new AppLocator(),
693
+                    $config,
694
+                    $c->getMemCacheFactory(),
695
+                    $appManager,
696
+                    $c->getTempManager()
697
+            );
698
+        });
699
+        $this->registerService(\OCP\IRequest::class, function ($c) {
700
+            if (isset($this['urlParams'])) {
701
+                $urlParams = $this['urlParams'];
702
+            } else {
703
+                $urlParams = [];
704
+            }
705
+
706
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
707
+                && in_array('fakeinput', stream_get_wrappers())
708
+            ) {
709
+                $stream = 'fakeinput://data';
710
+            } else {
711
+                $stream = 'php://input';
712
+            }
713
+
714
+            return new Request(
715
+                [
716
+                    'get' => $_GET,
717
+                    'post' => $_POST,
718
+                    'files' => $_FILES,
719
+                    'server' => $_SERVER,
720
+                    'env' => $_ENV,
721
+                    'cookies' => $_COOKIE,
722
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
723
+                        ? $_SERVER['REQUEST_METHOD']
724
+                        : null,
725
+                    'urlParams' => $urlParams,
726
+                ],
727
+                $this->getSecureRandom(),
728
+                $this->getConfig(),
729
+                $this->getCsrfTokenManager(),
730
+                $stream
731
+            );
732
+        });
733
+        $this->registerAlias('Request', \OCP\IRequest::class);
734
+
735
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
736
+            return new Mailer(
737
+                $c->getConfig(),
738
+                $c->getLogger(),
739
+                $c->getThemingDefaults()
740
+            );
741
+        });
742
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
743
+
744
+        $this->registerService('LDAPProvider', function(Server $c) {
745
+            $config = $c->getConfig();
746
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
747
+            if(is_null($factoryClass)) {
748
+                throw new \Exception('ldapProviderFactory not set');
749
+            }
750
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
751
+            $factory = new $factoryClass($this);
752
+            return $factory->getLDAPProvider();
753
+        });
754
+        $this->registerService('LockingProvider', function (Server $c) {
755
+            $ini = $c->getIniWrapper();
756
+            $config = $c->getConfig();
757
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
758
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
759
+                /** @var \OC\Memcache\Factory $memcacheFactory */
760
+                $memcacheFactory = $c->getMemCacheFactory();
761
+                $memcache = $memcacheFactory->createLocking('lock');
762
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
763
+                    return new MemcacheLockingProvider($memcache, $ttl);
764
+                }
765
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
766
+            }
767
+            return new NoopLockingProvider();
768
+        });
769
+
770
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
771
+            return new \OC\Files\Mount\Manager();
772
+        });
773
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
774
+
775
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
776
+            return new \OC\Files\Type\Detection(
777
+                $c->getURLGenerator(),
778
+                \OC::$configDir,
779
+                \OC::$SERVERROOT . '/resources/config/'
780
+            );
781
+        });
782
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
783
+
784
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
785
+            return new \OC\Files\Type\Loader(
786
+                $c->getDatabaseConnection()
787
+            );
788
+        });
789
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
790
+
791
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
792
+            return new Manager(
793
+                $c->query(IValidator::class)
794
+            );
795
+        });
796
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
797
+
798
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
799
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
800
+            $manager->registerCapability(function () use ($c) {
801
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
802
+            });
803
+            return $manager;
804
+        });
805
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
806
+
807
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
808
+            $config = $c->getConfig();
809
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
810
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
811
+            $factory = new $factoryClass($this);
812
+            return $factory->getManager();
813
+        });
814
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
815
+
816
+        $this->registerService('ThemingDefaults', function(Server $c) {
817
+            /*
818 818
 			 * Dark magic for autoloader.
819 819
 			 * If we do a class_exists it will try to load the class which will
820 820
 			 * make composer cache the result. Resulting in errors when enabling
821 821
 			 * the theming app.
822 822
 			 */
823
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
824
-			if (isset($prefixes['OCA\\Theming\\'])) {
825
-				$classExists = true;
826
-			} else {
827
-				$classExists = false;
828
-			}
829
-
830
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
831
-				return new ThemingDefaults(
832
-					$c->getConfig(),
833
-					$c->getL10N('theming'),
834
-					$c->getURLGenerator(),
835
-					new \OC_Defaults(),
836
-					$c->getAppDataDir('theming'),
837
-					$c->getMemCacheFactory(),
838
-					new Util($c->getConfig(), $this->getRootFolder(), $this->getAppManager())
839
-				);
840
-			}
841
-			return new \OC_Defaults();
842
-		});
843
-		$this->registerService(SCSSCacher::class, function(Server $c) {
844
-			/** @var Factory $cacheFactory */
845
-			$cacheFactory = $c->query(Factory::class);
846
-			return new SCSSCacher(
847
-				$c->getLogger(),
848
-				$c->query(\OC\Files\AppData\Factory::class),
849
-				$c->getURLGenerator(),
850
-				$c->getConfig(),
851
-				$c->getThemingDefaults(),
852
-				\OC::$SERVERROOT,
853
-				$cacheFactory->createLocal('SCSS')
854
-
855
-			);
856
-		});
857
-		$this->registerService(EventDispatcher::class, function () {
858
-			return new EventDispatcher();
859
-		});
860
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
861
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862
-
863
-		$this->registerService('CryptoWrapper', function (Server $c) {
864
-			// FIXME: Instantiiated here due to cyclic dependency
865
-			$request = new Request(
866
-				[
867
-					'get' => $_GET,
868
-					'post' => $_POST,
869
-					'files' => $_FILES,
870
-					'server' => $_SERVER,
871
-					'env' => $_ENV,
872
-					'cookies' => $_COOKIE,
873
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
-						? $_SERVER['REQUEST_METHOD']
875
-						: null,
876
-				],
877
-				$c->getSecureRandom(),
878
-				$c->getConfig()
879
-			);
880
-
881
-			return new CryptoWrapper(
882
-				$c->getConfig(),
883
-				$c->getCrypto(),
884
-				$c->getSecureRandom(),
885
-				$request
886
-			);
887
-		});
888
-		$this->registerService('CsrfTokenManager', function (Server $c) {
889
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890
-
891
-			return new CsrfTokenManager(
892
-				$tokenGenerator,
893
-				$c->query(SessionStorage::class)
894
-			);
895
-		});
896
-		$this->registerService(SessionStorage::class, function (Server $c) {
897
-			return new SessionStorage($c->getSession());
898
-		});
899
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
900
-			return new ContentSecurityPolicyManager();
901
-		});
902
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
903
-
904
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
905
-			return new ContentSecurityPolicyNonceManager(
906
-				$c->getCsrfTokenManager(),
907
-				$c->getRequest()
908
-			);
909
-		});
910
-
911
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
912
-			$config = $c->getConfig();
913
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
914
-			/** @var \OCP\Share\IProviderFactory $factory */
915
-			$factory = new $factoryClass($this);
916
-
917
-			$manager = new \OC\Share20\Manager(
918
-				$c->getLogger(),
919
-				$c->getConfig(),
920
-				$c->getSecureRandom(),
921
-				$c->getHasher(),
922
-				$c->getMountManager(),
923
-				$c->getGroupManager(),
924
-				$c->getL10N('core'),
925
-				$factory,
926
-				$c->getUserManager(),
927
-				$c->getLazyRootFolder(),
928
-				$c->getEventDispatcher()
929
-			);
930
-
931
-			return $manager;
932
-		});
933
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
934
-
935
-		$this->registerService('SettingsManager', function(Server $c) {
936
-			$manager = new \OC\Settings\Manager(
937
-				$c->getLogger(),
938
-				$c->getDatabaseConnection(),
939
-				$c->getL10N('lib'),
940
-				$c->getConfig(),
941
-				$c->getEncryptionManager(),
942
-				$c->getUserManager(),
943
-				$c->getLockingProvider(),
944
-				$c->getRequest(),
945
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
946
-				$c->getURLGenerator()
947
-			);
948
-			return $manager;
949
-		});
950
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
951
-			return new \OC\Files\AppData\Factory(
952
-				$c->getRootFolder(),
953
-				$c->getSystemConfig()
954
-			);
955
-		});
956
-
957
-		$this->registerService('LockdownManager', function (Server $c) {
958
-			return new LockdownManager();
959
-		});
960
-
961
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
962
-			return new CloudIdManager();
963
-		});
964
-
965
-		/* To trick DI since we don't extend the DIContainer here */
966
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
967
-			return new CleanPreviewsBackgroundJob(
968
-				$c->getRootFolder(),
969
-				$c->getLogger(),
970
-				$c->getJobList(),
971
-				new TimeFactory()
972
-			);
973
-		});
974
-
975
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
976
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
977
-
978
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
979
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
980
-
981
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
982
-			return $c->query(\OCP\IUserSession::class)->getSession();
983
-		});
984
-	}
985
-
986
-	/**
987
-	 * @return \OCP\Contacts\IManager
988
-	 */
989
-	public function getContactsManager() {
990
-		return $this->query('ContactsManager');
991
-	}
992
-
993
-	/**
994
-	 * @return \OC\Encryption\Manager
995
-	 */
996
-	public function getEncryptionManager() {
997
-		return $this->query('EncryptionManager');
998
-	}
999
-
1000
-	/**
1001
-	 * @return \OC\Encryption\File
1002
-	 */
1003
-	public function getEncryptionFilesHelper() {
1004
-		return $this->query('EncryptionFileHelper');
1005
-	}
1006
-
1007
-	/**
1008
-	 * @return \OCP\Encryption\Keys\IStorage
1009
-	 */
1010
-	public function getEncryptionKeyStorage() {
1011
-		return $this->query('EncryptionKeyStorage');
1012
-	}
1013
-
1014
-	/**
1015
-	 * The current request object holding all information about the request
1016
-	 * currently being processed is returned from this method.
1017
-	 * In case the current execution was not initiated by a web request null is returned
1018
-	 *
1019
-	 * @return \OCP\IRequest
1020
-	 */
1021
-	public function getRequest() {
1022
-		return $this->query('Request');
1023
-	}
1024
-
1025
-	/**
1026
-	 * Returns the preview manager which can create preview images for a given file
1027
-	 *
1028
-	 * @return \OCP\IPreview
1029
-	 */
1030
-	public function getPreviewManager() {
1031
-		return $this->query('PreviewManager');
1032
-	}
1033
-
1034
-	/**
1035
-	 * Returns the tag manager which can get and set tags for different object types
1036
-	 *
1037
-	 * @see \OCP\ITagManager::load()
1038
-	 * @return \OCP\ITagManager
1039
-	 */
1040
-	public function getTagManager() {
1041
-		return $this->query('TagManager');
1042
-	}
1043
-
1044
-	/**
1045
-	 * Returns the system-tag manager
1046
-	 *
1047
-	 * @return \OCP\SystemTag\ISystemTagManager
1048
-	 *
1049
-	 * @since 9.0.0
1050
-	 */
1051
-	public function getSystemTagManager() {
1052
-		return $this->query('SystemTagManager');
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns the system-tag object mapper
1057
-	 *
1058
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1059
-	 *
1060
-	 * @since 9.0.0
1061
-	 */
1062
-	public function getSystemTagObjectMapper() {
1063
-		return $this->query('SystemTagObjectMapper');
1064
-	}
1065
-
1066
-	/**
1067
-	 * Returns the avatar manager, used for avatar functionality
1068
-	 *
1069
-	 * @return \OCP\IAvatarManager
1070
-	 */
1071
-	public function getAvatarManager() {
1072
-		return $this->query('AvatarManager');
1073
-	}
1074
-
1075
-	/**
1076
-	 * Returns the root folder of ownCloud's data directory
1077
-	 *
1078
-	 * @return \OCP\Files\IRootFolder
1079
-	 */
1080
-	public function getRootFolder() {
1081
-		return $this->query('LazyRootFolder');
1082
-	}
1083
-
1084
-	/**
1085
-	 * Returns the root folder of ownCloud's data directory
1086
-	 * This is the lazy variant so this gets only initialized once it
1087
-	 * is actually used.
1088
-	 *
1089
-	 * @return \OCP\Files\IRootFolder
1090
-	 */
1091
-	public function getLazyRootFolder() {
1092
-		return $this->query('LazyRootFolder');
1093
-	}
1094
-
1095
-	/**
1096
-	 * Returns a view to ownCloud's files folder
1097
-	 *
1098
-	 * @param string $userId user ID
1099
-	 * @return \OCP\Files\Folder|null
1100
-	 */
1101
-	public function getUserFolder($userId = null) {
1102
-		if ($userId === null) {
1103
-			$user = $this->getUserSession()->getUser();
1104
-			if (!$user) {
1105
-				return null;
1106
-			}
1107
-			$userId = $user->getUID();
1108
-		}
1109
-		$root = $this->getRootFolder();
1110
-		return $root->getUserFolder($userId);
1111
-	}
1112
-
1113
-	/**
1114
-	 * Returns an app-specific view in ownClouds data directory
1115
-	 *
1116
-	 * @return \OCP\Files\Folder
1117
-	 * @deprecated since 9.2.0 use IAppData
1118
-	 */
1119
-	public function getAppFolder() {
1120
-		$dir = '/' . \OC_App::getCurrentApp();
1121
-		$root = $this->getRootFolder();
1122
-		if (!$root->nodeExists($dir)) {
1123
-			$folder = $root->newFolder($dir);
1124
-		} else {
1125
-			$folder = $root->get($dir);
1126
-		}
1127
-		return $folder;
1128
-	}
1129
-
1130
-	/**
1131
-	 * @return \OC\User\Manager
1132
-	 */
1133
-	public function getUserManager() {
1134
-		return $this->query('UserManager');
1135
-	}
1136
-
1137
-	/**
1138
-	 * @return \OC\Group\Manager
1139
-	 */
1140
-	public function getGroupManager() {
1141
-		return $this->query('GroupManager');
1142
-	}
1143
-
1144
-	/**
1145
-	 * @return \OC\User\Session
1146
-	 */
1147
-	public function getUserSession() {
1148
-		return $this->query('UserSession');
1149
-	}
1150
-
1151
-	/**
1152
-	 * @return \OCP\ISession
1153
-	 */
1154
-	public function getSession() {
1155
-		return $this->query('UserSession')->getSession();
1156
-	}
1157
-
1158
-	/**
1159
-	 * @param \OCP\ISession $session
1160
-	 */
1161
-	public function setSession(\OCP\ISession $session) {
1162
-		$this->query(SessionStorage::class)->setSession($session);
1163
-		$this->query('UserSession')->setSession($session);
1164
-		$this->query(Store::class)->setSession($session);
1165
-	}
1166
-
1167
-	/**
1168
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1169
-	 */
1170
-	public function getTwoFactorAuthManager() {
1171
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1172
-	}
1173
-
1174
-	/**
1175
-	 * @return \OC\NavigationManager
1176
-	 */
1177
-	public function getNavigationManager() {
1178
-		return $this->query('NavigationManager');
1179
-	}
1180
-
1181
-	/**
1182
-	 * @return \OCP\IConfig
1183
-	 */
1184
-	public function getConfig() {
1185
-		return $this->query('AllConfig');
1186
-	}
1187
-
1188
-	/**
1189
-	 * @internal For internal use only
1190
-	 * @return \OC\SystemConfig
1191
-	 */
1192
-	public function getSystemConfig() {
1193
-		return $this->query('SystemConfig');
1194
-	}
1195
-
1196
-	/**
1197
-	 * Returns the app config manager
1198
-	 *
1199
-	 * @return \OCP\IAppConfig
1200
-	 */
1201
-	public function getAppConfig() {
1202
-		return $this->query('AppConfig');
1203
-	}
1204
-
1205
-	/**
1206
-	 * @return \OCP\L10N\IFactory
1207
-	 */
1208
-	public function getL10NFactory() {
1209
-		return $this->query('L10NFactory');
1210
-	}
1211
-
1212
-	/**
1213
-	 * get an L10N instance
1214
-	 *
1215
-	 * @param string $app appid
1216
-	 * @param string $lang
1217
-	 * @return IL10N
1218
-	 */
1219
-	public function getL10N($app, $lang = null) {
1220
-		return $this->getL10NFactory()->get($app, $lang);
1221
-	}
1222
-
1223
-	/**
1224
-	 * @return \OCP\IURLGenerator
1225
-	 */
1226
-	public function getURLGenerator() {
1227
-		return $this->query('URLGenerator');
1228
-	}
1229
-
1230
-	/**
1231
-	 * @return \OCP\IHelper
1232
-	 */
1233
-	public function getHelper() {
1234
-		return $this->query('AppHelper');
1235
-	}
1236
-
1237
-	/**
1238
-	 * @return AppFetcher
1239
-	 */
1240
-	public function getAppFetcher() {
1241
-		return $this->query('AppFetcher');
1242
-	}
1243
-
1244
-	/**
1245
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1246
-	 * getMemCacheFactory() instead.
1247
-	 *
1248
-	 * @return \OCP\ICache
1249
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1250
-	 */
1251
-	public function getCache() {
1252
-		return $this->query('UserCache');
1253
-	}
1254
-
1255
-	/**
1256
-	 * Returns an \OCP\CacheFactory instance
1257
-	 *
1258
-	 * @return \OCP\ICacheFactory
1259
-	 */
1260
-	public function getMemCacheFactory() {
1261
-		return $this->query('MemCacheFactory');
1262
-	}
1263
-
1264
-	/**
1265
-	 * Returns an \OC\RedisFactory instance
1266
-	 *
1267
-	 * @return \OC\RedisFactory
1268
-	 */
1269
-	public function getGetRedisFactory() {
1270
-		return $this->query('RedisFactory');
1271
-	}
1272
-
1273
-
1274
-	/**
1275
-	 * Returns the current session
1276
-	 *
1277
-	 * @return \OCP\IDBConnection
1278
-	 */
1279
-	public function getDatabaseConnection() {
1280
-		return $this->query('DatabaseConnection');
1281
-	}
1282
-
1283
-	/**
1284
-	 * Returns the activity manager
1285
-	 *
1286
-	 * @return \OCP\Activity\IManager
1287
-	 */
1288
-	public function getActivityManager() {
1289
-		return $this->query('ActivityManager');
1290
-	}
1291
-
1292
-	/**
1293
-	 * Returns an job list for controlling background jobs
1294
-	 *
1295
-	 * @return \OCP\BackgroundJob\IJobList
1296
-	 */
1297
-	public function getJobList() {
1298
-		return $this->query('JobList');
1299
-	}
1300
-
1301
-	/**
1302
-	 * Returns a logger instance
1303
-	 *
1304
-	 * @return \OCP\ILogger
1305
-	 */
1306
-	public function getLogger() {
1307
-		return $this->query('Logger');
1308
-	}
1309
-
1310
-	/**
1311
-	 * Returns a router for generating and matching urls
1312
-	 *
1313
-	 * @return \OCP\Route\IRouter
1314
-	 */
1315
-	public function getRouter() {
1316
-		return $this->query('Router');
1317
-	}
1318
-
1319
-	/**
1320
-	 * Returns a search instance
1321
-	 *
1322
-	 * @return \OCP\ISearch
1323
-	 */
1324
-	public function getSearch() {
1325
-		return $this->query('Search');
1326
-	}
1327
-
1328
-	/**
1329
-	 * Returns a SecureRandom instance
1330
-	 *
1331
-	 * @return \OCP\Security\ISecureRandom
1332
-	 */
1333
-	public function getSecureRandom() {
1334
-		return $this->query('SecureRandom');
1335
-	}
1336
-
1337
-	/**
1338
-	 * Returns a Crypto instance
1339
-	 *
1340
-	 * @return \OCP\Security\ICrypto
1341
-	 */
1342
-	public function getCrypto() {
1343
-		return $this->query('Crypto');
1344
-	}
1345
-
1346
-	/**
1347
-	 * Returns a Hasher instance
1348
-	 *
1349
-	 * @return \OCP\Security\IHasher
1350
-	 */
1351
-	public function getHasher() {
1352
-		return $this->query('Hasher');
1353
-	}
1354
-
1355
-	/**
1356
-	 * Returns a CredentialsManager instance
1357
-	 *
1358
-	 * @return \OCP\Security\ICredentialsManager
1359
-	 */
1360
-	public function getCredentialsManager() {
1361
-		return $this->query('CredentialsManager');
1362
-	}
1363
-
1364
-	/**
1365
-	 * Returns an instance of the HTTP helper class
1366
-	 *
1367
-	 * @deprecated Use getHTTPClientService()
1368
-	 * @return \OC\HTTPHelper
1369
-	 */
1370
-	public function getHTTPHelper() {
1371
-		return $this->query('HTTPHelper');
1372
-	}
1373
-
1374
-	/**
1375
-	 * Get the certificate manager for the user
1376
-	 *
1377
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1378
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1379
-	 */
1380
-	public function getCertificateManager($userId = '') {
1381
-		if ($userId === '') {
1382
-			$userSession = $this->getUserSession();
1383
-			$user = $userSession->getUser();
1384
-			if (is_null($user)) {
1385
-				return null;
1386
-			}
1387
-			$userId = $user->getUID();
1388
-		}
1389
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1390
-	}
1391
-
1392
-	/**
1393
-	 * Returns an instance of the HTTP client service
1394
-	 *
1395
-	 * @return \OCP\Http\Client\IClientService
1396
-	 */
1397
-	public function getHTTPClientService() {
1398
-		return $this->query('HttpClientService');
1399
-	}
1400
-
1401
-	/**
1402
-	 * Create a new event source
1403
-	 *
1404
-	 * @return \OCP\IEventSource
1405
-	 */
1406
-	public function createEventSource() {
1407
-		return new \OC_EventSource();
1408
-	}
1409
-
1410
-	/**
1411
-	 * Get the active event logger
1412
-	 *
1413
-	 * The returned logger only logs data when debug mode is enabled
1414
-	 *
1415
-	 * @return \OCP\Diagnostics\IEventLogger
1416
-	 */
1417
-	public function getEventLogger() {
1418
-		return $this->query('EventLogger');
1419
-	}
1420
-
1421
-	/**
1422
-	 * Get the active query logger
1423
-	 *
1424
-	 * The returned logger only logs data when debug mode is enabled
1425
-	 *
1426
-	 * @return \OCP\Diagnostics\IQueryLogger
1427
-	 */
1428
-	public function getQueryLogger() {
1429
-		return $this->query('QueryLogger');
1430
-	}
1431
-
1432
-	/**
1433
-	 * Get the manager for temporary files and folders
1434
-	 *
1435
-	 * @return \OCP\ITempManager
1436
-	 */
1437
-	public function getTempManager() {
1438
-		return $this->query('TempManager');
1439
-	}
1440
-
1441
-	/**
1442
-	 * Get the app manager
1443
-	 *
1444
-	 * @return \OCP\App\IAppManager
1445
-	 */
1446
-	public function getAppManager() {
1447
-		return $this->query('AppManager');
1448
-	}
1449
-
1450
-	/**
1451
-	 * Creates a new mailer
1452
-	 *
1453
-	 * @return \OCP\Mail\IMailer
1454
-	 */
1455
-	public function getMailer() {
1456
-		return $this->query('Mailer');
1457
-	}
1458
-
1459
-	/**
1460
-	 * Get the webroot
1461
-	 *
1462
-	 * @return string
1463
-	 */
1464
-	public function getWebRoot() {
1465
-		return $this->webRoot;
1466
-	}
1467
-
1468
-	/**
1469
-	 * @return \OC\OCSClient
1470
-	 */
1471
-	public function getOcsClient() {
1472
-		return $this->query('OcsClient');
1473
-	}
1474
-
1475
-	/**
1476
-	 * @return \OCP\IDateTimeZone
1477
-	 */
1478
-	public function getDateTimeZone() {
1479
-		return $this->query('DateTimeZone');
1480
-	}
1481
-
1482
-	/**
1483
-	 * @return \OCP\IDateTimeFormatter
1484
-	 */
1485
-	public function getDateTimeFormatter() {
1486
-		return $this->query('DateTimeFormatter');
1487
-	}
1488
-
1489
-	/**
1490
-	 * @return \OCP\Files\Config\IMountProviderCollection
1491
-	 */
1492
-	public function getMountProviderCollection() {
1493
-		return $this->query('MountConfigManager');
1494
-	}
1495
-
1496
-	/**
1497
-	 * Get the IniWrapper
1498
-	 *
1499
-	 * @return IniGetWrapper
1500
-	 */
1501
-	public function getIniWrapper() {
1502
-		return $this->query('IniWrapper');
1503
-	}
1504
-
1505
-	/**
1506
-	 * @return \OCP\Command\IBus
1507
-	 */
1508
-	public function getCommandBus() {
1509
-		return $this->query('AsyncCommandBus');
1510
-	}
1511
-
1512
-	/**
1513
-	 * Get the trusted domain helper
1514
-	 *
1515
-	 * @return TrustedDomainHelper
1516
-	 */
1517
-	public function getTrustedDomainHelper() {
1518
-		return $this->query('TrustedDomainHelper');
1519
-	}
1520
-
1521
-	/**
1522
-	 * Get the locking provider
1523
-	 *
1524
-	 * @return \OCP\Lock\ILockingProvider
1525
-	 * @since 8.1.0
1526
-	 */
1527
-	public function getLockingProvider() {
1528
-		return $this->query('LockingProvider');
1529
-	}
1530
-
1531
-	/**
1532
-	 * @return \OCP\Files\Mount\IMountManager
1533
-	 **/
1534
-	function getMountManager() {
1535
-		return $this->query('MountManager');
1536
-	}
1537
-
1538
-	/** @return \OCP\Files\Config\IUserMountCache */
1539
-	function getUserMountCache() {
1540
-		return $this->query('UserMountCache');
1541
-	}
1542
-
1543
-	/**
1544
-	 * Get the MimeTypeDetector
1545
-	 *
1546
-	 * @return \OCP\Files\IMimeTypeDetector
1547
-	 */
1548
-	public function getMimeTypeDetector() {
1549
-		return $this->query('MimeTypeDetector');
1550
-	}
1551
-
1552
-	/**
1553
-	 * Get the MimeTypeLoader
1554
-	 *
1555
-	 * @return \OCP\Files\IMimeTypeLoader
1556
-	 */
1557
-	public function getMimeTypeLoader() {
1558
-		return $this->query('MimeTypeLoader');
1559
-	}
1560
-
1561
-	/**
1562
-	 * Get the manager of all the capabilities
1563
-	 *
1564
-	 * @return \OC\CapabilitiesManager
1565
-	 */
1566
-	public function getCapabilitiesManager() {
1567
-		return $this->query('CapabilitiesManager');
1568
-	}
1569
-
1570
-	/**
1571
-	 * Get the EventDispatcher
1572
-	 *
1573
-	 * @return EventDispatcherInterface
1574
-	 * @since 8.2.0
1575
-	 */
1576
-	public function getEventDispatcher() {
1577
-		return $this->query('EventDispatcher');
1578
-	}
1579
-
1580
-	/**
1581
-	 * Get the Notification Manager
1582
-	 *
1583
-	 * @return \OCP\Notification\IManager
1584
-	 * @since 8.2.0
1585
-	 */
1586
-	public function getNotificationManager() {
1587
-		return $this->query('NotificationManager');
1588
-	}
1589
-
1590
-	/**
1591
-	 * @return \OCP\Comments\ICommentsManager
1592
-	 */
1593
-	public function getCommentsManager() {
1594
-		return $this->query('CommentsManager');
1595
-	}
1596
-
1597
-	/**
1598
-	 * @return \OC_Defaults
1599
-	 */
1600
-	public function getThemingDefaults() {
1601
-		return $this->query('ThemingDefaults');
1602
-	}
1603
-
1604
-	/**
1605
-	 * @return \OC\IntegrityCheck\Checker
1606
-	 */
1607
-	public function getIntegrityCodeChecker() {
1608
-		return $this->query('IntegrityCodeChecker');
1609
-	}
1610
-
1611
-	/**
1612
-	 * @return \OC\Session\CryptoWrapper
1613
-	 */
1614
-	public function getSessionCryptoWrapper() {
1615
-		return $this->query('CryptoWrapper');
1616
-	}
1617
-
1618
-	/**
1619
-	 * @return CsrfTokenManager
1620
-	 */
1621
-	public function getCsrfTokenManager() {
1622
-		return $this->query('CsrfTokenManager');
1623
-	}
1624
-
1625
-	/**
1626
-	 * @return Throttler
1627
-	 */
1628
-	public function getBruteForceThrottler() {
1629
-		return $this->query('Throttler');
1630
-	}
1631
-
1632
-	/**
1633
-	 * @return IContentSecurityPolicyManager
1634
-	 */
1635
-	public function getContentSecurityPolicyManager() {
1636
-		return $this->query('ContentSecurityPolicyManager');
1637
-	}
1638
-
1639
-	/**
1640
-	 * @return ContentSecurityPolicyNonceManager
1641
-	 */
1642
-	public function getContentSecurityPolicyNonceManager() {
1643
-		return $this->query('ContentSecurityPolicyNonceManager');
1644
-	}
1645
-
1646
-	/**
1647
-	 * Not a public API as of 8.2, wait for 9.0
1648
-	 *
1649
-	 * @return \OCA\Files_External\Service\BackendService
1650
-	 */
1651
-	public function getStoragesBackendService() {
1652
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1653
-	}
1654
-
1655
-	/**
1656
-	 * Not a public API as of 8.2, wait for 9.0
1657
-	 *
1658
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1659
-	 */
1660
-	public function getGlobalStoragesService() {
1661
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1662
-	}
1663
-
1664
-	/**
1665
-	 * Not a public API as of 8.2, wait for 9.0
1666
-	 *
1667
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1668
-	 */
1669
-	public function getUserGlobalStoragesService() {
1670
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1671
-	}
1672
-
1673
-	/**
1674
-	 * Not a public API as of 8.2, wait for 9.0
1675
-	 *
1676
-	 * @return \OCA\Files_External\Service\UserStoragesService
1677
-	 */
1678
-	public function getUserStoragesService() {
1679
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1680
-	}
1681
-
1682
-	/**
1683
-	 * @return \OCP\Share\IManager
1684
-	 */
1685
-	public function getShareManager() {
1686
-		return $this->query('ShareManager');
1687
-	}
1688
-
1689
-	/**
1690
-	 * Returns the LDAP Provider
1691
-	 *
1692
-	 * @return \OCP\LDAP\ILDAPProvider
1693
-	 */
1694
-	public function getLDAPProvider() {
1695
-		return $this->query('LDAPProvider');
1696
-	}
1697
-
1698
-	/**
1699
-	 * @return \OCP\Settings\IManager
1700
-	 */
1701
-	public function getSettingsManager() {
1702
-		return $this->query('SettingsManager');
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OCP\Files\IAppData
1707
-	 */
1708
-	public function getAppDataDir($app) {
1709
-		/** @var \OC\Files\AppData\Factory $factory */
1710
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1711
-		return $factory->get($app);
1712
-	}
1713
-
1714
-	/**
1715
-	 * @return \OCP\Lockdown\ILockdownManager
1716
-	 */
1717
-	public function getLockdownManager() {
1718
-		return $this->query('LockdownManager');
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return \OCP\Federation\ICloudIdManager
1723
-	 */
1724
-	public function getCloudIdManager() {
1725
-		return $this->query(ICloudIdManager::class);
1726
-	}
823
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
824
+            if (isset($prefixes['OCA\\Theming\\'])) {
825
+                $classExists = true;
826
+            } else {
827
+                $classExists = false;
828
+            }
829
+
830
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
831
+                return new ThemingDefaults(
832
+                    $c->getConfig(),
833
+                    $c->getL10N('theming'),
834
+                    $c->getURLGenerator(),
835
+                    new \OC_Defaults(),
836
+                    $c->getAppDataDir('theming'),
837
+                    $c->getMemCacheFactory(),
838
+                    new Util($c->getConfig(), $this->getRootFolder(), $this->getAppManager())
839
+                );
840
+            }
841
+            return new \OC_Defaults();
842
+        });
843
+        $this->registerService(SCSSCacher::class, function(Server $c) {
844
+            /** @var Factory $cacheFactory */
845
+            $cacheFactory = $c->query(Factory::class);
846
+            return new SCSSCacher(
847
+                $c->getLogger(),
848
+                $c->query(\OC\Files\AppData\Factory::class),
849
+                $c->getURLGenerator(),
850
+                $c->getConfig(),
851
+                $c->getThemingDefaults(),
852
+                \OC::$SERVERROOT,
853
+                $cacheFactory->createLocal('SCSS')
854
+
855
+            );
856
+        });
857
+        $this->registerService(EventDispatcher::class, function () {
858
+            return new EventDispatcher();
859
+        });
860
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
861
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862
+
863
+        $this->registerService('CryptoWrapper', function (Server $c) {
864
+            // FIXME: Instantiiated here due to cyclic dependency
865
+            $request = new Request(
866
+                [
867
+                    'get' => $_GET,
868
+                    'post' => $_POST,
869
+                    'files' => $_FILES,
870
+                    'server' => $_SERVER,
871
+                    'env' => $_ENV,
872
+                    'cookies' => $_COOKIE,
873
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
874
+                        ? $_SERVER['REQUEST_METHOD']
875
+                        : null,
876
+                ],
877
+                $c->getSecureRandom(),
878
+                $c->getConfig()
879
+            );
880
+
881
+            return new CryptoWrapper(
882
+                $c->getConfig(),
883
+                $c->getCrypto(),
884
+                $c->getSecureRandom(),
885
+                $request
886
+            );
887
+        });
888
+        $this->registerService('CsrfTokenManager', function (Server $c) {
889
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890
+
891
+            return new CsrfTokenManager(
892
+                $tokenGenerator,
893
+                $c->query(SessionStorage::class)
894
+            );
895
+        });
896
+        $this->registerService(SessionStorage::class, function (Server $c) {
897
+            return new SessionStorage($c->getSession());
898
+        });
899
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
900
+            return new ContentSecurityPolicyManager();
901
+        });
902
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
903
+
904
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
905
+            return new ContentSecurityPolicyNonceManager(
906
+                $c->getCsrfTokenManager(),
907
+                $c->getRequest()
908
+            );
909
+        });
910
+
911
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
912
+            $config = $c->getConfig();
913
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
914
+            /** @var \OCP\Share\IProviderFactory $factory */
915
+            $factory = new $factoryClass($this);
916
+
917
+            $manager = new \OC\Share20\Manager(
918
+                $c->getLogger(),
919
+                $c->getConfig(),
920
+                $c->getSecureRandom(),
921
+                $c->getHasher(),
922
+                $c->getMountManager(),
923
+                $c->getGroupManager(),
924
+                $c->getL10N('core'),
925
+                $factory,
926
+                $c->getUserManager(),
927
+                $c->getLazyRootFolder(),
928
+                $c->getEventDispatcher()
929
+            );
930
+
931
+            return $manager;
932
+        });
933
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
934
+
935
+        $this->registerService('SettingsManager', function(Server $c) {
936
+            $manager = new \OC\Settings\Manager(
937
+                $c->getLogger(),
938
+                $c->getDatabaseConnection(),
939
+                $c->getL10N('lib'),
940
+                $c->getConfig(),
941
+                $c->getEncryptionManager(),
942
+                $c->getUserManager(),
943
+                $c->getLockingProvider(),
944
+                $c->getRequest(),
945
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
946
+                $c->getURLGenerator()
947
+            );
948
+            return $manager;
949
+        });
950
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
951
+            return new \OC\Files\AppData\Factory(
952
+                $c->getRootFolder(),
953
+                $c->getSystemConfig()
954
+            );
955
+        });
956
+
957
+        $this->registerService('LockdownManager', function (Server $c) {
958
+            return new LockdownManager();
959
+        });
960
+
961
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
962
+            return new CloudIdManager();
963
+        });
964
+
965
+        /* To trick DI since we don't extend the DIContainer here */
966
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
967
+            return new CleanPreviewsBackgroundJob(
968
+                $c->getRootFolder(),
969
+                $c->getLogger(),
970
+                $c->getJobList(),
971
+                new TimeFactory()
972
+            );
973
+        });
974
+
975
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
976
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
977
+
978
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
979
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
980
+
981
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
982
+            return $c->query(\OCP\IUserSession::class)->getSession();
983
+        });
984
+    }
985
+
986
+    /**
987
+     * @return \OCP\Contacts\IManager
988
+     */
989
+    public function getContactsManager() {
990
+        return $this->query('ContactsManager');
991
+    }
992
+
993
+    /**
994
+     * @return \OC\Encryption\Manager
995
+     */
996
+    public function getEncryptionManager() {
997
+        return $this->query('EncryptionManager');
998
+    }
999
+
1000
+    /**
1001
+     * @return \OC\Encryption\File
1002
+     */
1003
+    public function getEncryptionFilesHelper() {
1004
+        return $this->query('EncryptionFileHelper');
1005
+    }
1006
+
1007
+    /**
1008
+     * @return \OCP\Encryption\Keys\IStorage
1009
+     */
1010
+    public function getEncryptionKeyStorage() {
1011
+        return $this->query('EncryptionKeyStorage');
1012
+    }
1013
+
1014
+    /**
1015
+     * The current request object holding all information about the request
1016
+     * currently being processed is returned from this method.
1017
+     * In case the current execution was not initiated by a web request null is returned
1018
+     *
1019
+     * @return \OCP\IRequest
1020
+     */
1021
+    public function getRequest() {
1022
+        return $this->query('Request');
1023
+    }
1024
+
1025
+    /**
1026
+     * Returns the preview manager which can create preview images for a given file
1027
+     *
1028
+     * @return \OCP\IPreview
1029
+     */
1030
+    public function getPreviewManager() {
1031
+        return $this->query('PreviewManager');
1032
+    }
1033
+
1034
+    /**
1035
+     * Returns the tag manager which can get and set tags for different object types
1036
+     *
1037
+     * @see \OCP\ITagManager::load()
1038
+     * @return \OCP\ITagManager
1039
+     */
1040
+    public function getTagManager() {
1041
+        return $this->query('TagManager');
1042
+    }
1043
+
1044
+    /**
1045
+     * Returns the system-tag manager
1046
+     *
1047
+     * @return \OCP\SystemTag\ISystemTagManager
1048
+     *
1049
+     * @since 9.0.0
1050
+     */
1051
+    public function getSystemTagManager() {
1052
+        return $this->query('SystemTagManager');
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns the system-tag object mapper
1057
+     *
1058
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1059
+     *
1060
+     * @since 9.0.0
1061
+     */
1062
+    public function getSystemTagObjectMapper() {
1063
+        return $this->query('SystemTagObjectMapper');
1064
+    }
1065
+
1066
+    /**
1067
+     * Returns the avatar manager, used for avatar functionality
1068
+     *
1069
+     * @return \OCP\IAvatarManager
1070
+     */
1071
+    public function getAvatarManager() {
1072
+        return $this->query('AvatarManager');
1073
+    }
1074
+
1075
+    /**
1076
+     * Returns the root folder of ownCloud's data directory
1077
+     *
1078
+     * @return \OCP\Files\IRootFolder
1079
+     */
1080
+    public function getRootFolder() {
1081
+        return $this->query('LazyRootFolder');
1082
+    }
1083
+
1084
+    /**
1085
+     * Returns the root folder of ownCloud's data directory
1086
+     * This is the lazy variant so this gets only initialized once it
1087
+     * is actually used.
1088
+     *
1089
+     * @return \OCP\Files\IRootFolder
1090
+     */
1091
+    public function getLazyRootFolder() {
1092
+        return $this->query('LazyRootFolder');
1093
+    }
1094
+
1095
+    /**
1096
+     * Returns a view to ownCloud's files folder
1097
+     *
1098
+     * @param string $userId user ID
1099
+     * @return \OCP\Files\Folder|null
1100
+     */
1101
+    public function getUserFolder($userId = null) {
1102
+        if ($userId === null) {
1103
+            $user = $this->getUserSession()->getUser();
1104
+            if (!$user) {
1105
+                return null;
1106
+            }
1107
+            $userId = $user->getUID();
1108
+        }
1109
+        $root = $this->getRootFolder();
1110
+        return $root->getUserFolder($userId);
1111
+    }
1112
+
1113
+    /**
1114
+     * Returns an app-specific view in ownClouds data directory
1115
+     *
1116
+     * @return \OCP\Files\Folder
1117
+     * @deprecated since 9.2.0 use IAppData
1118
+     */
1119
+    public function getAppFolder() {
1120
+        $dir = '/' . \OC_App::getCurrentApp();
1121
+        $root = $this->getRootFolder();
1122
+        if (!$root->nodeExists($dir)) {
1123
+            $folder = $root->newFolder($dir);
1124
+        } else {
1125
+            $folder = $root->get($dir);
1126
+        }
1127
+        return $folder;
1128
+    }
1129
+
1130
+    /**
1131
+     * @return \OC\User\Manager
1132
+     */
1133
+    public function getUserManager() {
1134
+        return $this->query('UserManager');
1135
+    }
1136
+
1137
+    /**
1138
+     * @return \OC\Group\Manager
1139
+     */
1140
+    public function getGroupManager() {
1141
+        return $this->query('GroupManager');
1142
+    }
1143
+
1144
+    /**
1145
+     * @return \OC\User\Session
1146
+     */
1147
+    public function getUserSession() {
1148
+        return $this->query('UserSession');
1149
+    }
1150
+
1151
+    /**
1152
+     * @return \OCP\ISession
1153
+     */
1154
+    public function getSession() {
1155
+        return $this->query('UserSession')->getSession();
1156
+    }
1157
+
1158
+    /**
1159
+     * @param \OCP\ISession $session
1160
+     */
1161
+    public function setSession(\OCP\ISession $session) {
1162
+        $this->query(SessionStorage::class)->setSession($session);
1163
+        $this->query('UserSession')->setSession($session);
1164
+        $this->query(Store::class)->setSession($session);
1165
+    }
1166
+
1167
+    /**
1168
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1169
+     */
1170
+    public function getTwoFactorAuthManager() {
1171
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1172
+    }
1173
+
1174
+    /**
1175
+     * @return \OC\NavigationManager
1176
+     */
1177
+    public function getNavigationManager() {
1178
+        return $this->query('NavigationManager');
1179
+    }
1180
+
1181
+    /**
1182
+     * @return \OCP\IConfig
1183
+     */
1184
+    public function getConfig() {
1185
+        return $this->query('AllConfig');
1186
+    }
1187
+
1188
+    /**
1189
+     * @internal For internal use only
1190
+     * @return \OC\SystemConfig
1191
+     */
1192
+    public function getSystemConfig() {
1193
+        return $this->query('SystemConfig');
1194
+    }
1195
+
1196
+    /**
1197
+     * Returns the app config manager
1198
+     *
1199
+     * @return \OCP\IAppConfig
1200
+     */
1201
+    public function getAppConfig() {
1202
+        return $this->query('AppConfig');
1203
+    }
1204
+
1205
+    /**
1206
+     * @return \OCP\L10N\IFactory
1207
+     */
1208
+    public function getL10NFactory() {
1209
+        return $this->query('L10NFactory');
1210
+    }
1211
+
1212
+    /**
1213
+     * get an L10N instance
1214
+     *
1215
+     * @param string $app appid
1216
+     * @param string $lang
1217
+     * @return IL10N
1218
+     */
1219
+    public function getL10N($app, $lang = null) {
1220
+        return $this->getL10NFactory()->get($app, $lang);
1221
+    }
1222
+
1223
+    /**
1224
+     * @return \OCP\IURLGenerator
1225
+     */
1226
+    public function getURLGenerator() {
1227
+        return $this->query('URLGenerator');
1228
+    }
1229
+
1230
+    /**
1231
+     * @return \OCP\IHelper
1232
+     */
1233
+    public function getHelper() {
1234
+        return $this->query('AppHelper');
1235
+    }
1236
+
1237
+    /**
1238
+     * @return AppFetcher
1239
+     */
1240
+    public function getAppFetcher() {
1241
+        return $this->query('AppFetcher');
1242
+    }
1243
+
1244
+    /**
1245
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1246
+     * getMemCacheFactory() instead.
1247
+     *
1248
+     * @return \OCP\ICache
1249
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1250
+     */
1251
+    public function getCache() {
1252
+        return $this->query('UserCache');
1253
+    }
1254
+
1255
+    /**
1256
+     * Returns an \OCP\CacheFactory instance
1257
+     *
1258
+     * @return \OCP\ICacheFactory
1259
+     */
1260
+    public function getMemCacheFactory() {
1261
+        return $this->query('MemCacheFactory');
1262
+    }
1263
+
1264
+    /**
1265
+     * Returns an \OC\RedisFactory instance
1266
+     *
1267
+     * @return \OC\RedisFactory
1268
+     */
1269
+    public function getGetRedisFactory() {
1270
+        return $this->query('RedisFactory');
1271
+    }
1272
+
1273
+
1274
+    /**
1275
+     * Returns the current session
1276
+     *
1277
+     * @return \OCP\IDBConnection
1278
+     */
1279
+    public function getDatabaseConnection() {
1280
+        return $this->query('DatabaseConnection');
1281
+    }
1282
+
1283
+    /**
1284
+     * Returns the activity manager
1285
+     *
1286
+     * @return \OCP\Activity\IManager
1287
+     */
1288
+    public function getActivityManager() {
1289
+        return $this->query('ActivityManager');
1290
+    }
1291
+
1292
+    /**
1293
+     * Returns an job list for controlling background jobs
1294
+     *
1295
+     * @return \OCP\BackgroundJob\IJobList
1296
+     */
1297
+    public function getJobList() {
1298
+        return $this->query('JobList');
1299
+    }
1300
+
1301
+    /**
1302
+     * Returns a logger instance
1303
+     *
1304
+     * @return \OCP\ILogger
1305
+     */
1306
+    public function getLogger() {
1307
+        return $this->query('Logger');
1308
+    }
1309
+
1310
+    /**
1311
+     * Returns a router for generating and matching urls
1312
+     *
1313
+     * @return \OCP\Route\IRouter
1314
+     */
1315
+    public function getRouter() {
1316
+        return $this->query('Router');
1317
+    }
1318
+
1319
+    /**
1320
+     * Returns a search instance
1321
+     *
1322
+     * @return \OCP\ISearch
1323
+     */
1324
+    public function getSearch() {
1325
+        return $this->query('Search');
1326
+    }
1327
+
1328
+    /**
1329
+     * Returns a SecureRandom instance
1330
+     *
1331
+     * @return \OCP\Security\ISecureRandom
1332
+     */
1333
+    public function getSecureRandom() {
1334
+        return $this->query('SecureRandom');
1335
+    }
1336
+
1337
+    /**
1338
+     * Returns a Crypto instance
1339
+     *
1340
+     * @return \OCP\Security\ICrypto
1341
+     */
1342
+    public function getCrypto() {
1343
+        return $this->query('Crypto');
1344
+    }
1345
+
1346
+    /**
1347
+     * Returns a Hasher instance
1348
+     *
1349
+     * @return \OCP\Security\IHasher
1350
+     */
1351
+    public function getHasher() {
1352
+        return $this->query('Hasher');
1353
+    }
1354
+
1355
+    /**
1356
+     * Returns a CredentialsManager instance
1357
+     *
1358
+     * @return \OCP\Security\ICredentialsManager
1359
+     */
1360
+    public function getCredentialsManager() {
1361
+        return $this->query('CredentialsManager');
1362
+    }
1363
+
1364
+    /**
1365
+     * Returns an instance of the HTTP helper class
1366
+     *
1367
+     * @deprecated Use getHTTPClientService()
1368
+     * @return \OC\HTTPHelper
1369
+     */
1370
+    public function getHTTPHelper() {
1371
+        return $this->query('HTTPHelper');
1372
+    }
1373
+
1374
+    /**
1375
+     * Get the certificate manager for the user
1376
+     *
1377
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1378
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1379
+     */
1380
+    public function getCertificateManager($userId = '') {
1381
+        if ($userId === '') {
1382
+            $userSession = $this->getUserSession();
1383
+            $user = $userSession->getUser();
1384
+            if (is_null($user)) {
1385
+                return null;
1386
+            }
1387
+            $userId = $user->getUID();
1388
+        }
1389
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1390
+    }
1391
+
1392
+    /**
1393
+     * Returns an instance of the HTTP client service
1394
+     *
1395
+     * @return \OCP\Http\Client\IClientService
1396
+     */
1397
+    public function getHTTPClientService() {
1398
+        return $this->query('HttpClientService');
1399
+    }
1400
+
1401
+    /**
1402
+     * Create a new event source
1403
+     *
1404
+     * @return \OCP\IEventSource
1405
+     */
1406
+    public function createEventSource() {
1407
+        return new \OC_EventSource();
1408
+    }
1409
+
1410
+    /**
1411
+     * Get the active event logger
1412
+     *
1413
+     * The returned logger only logs data when debug mode is enabled
1414
+     *
1415
+     * @return \OCP\Diagnostics\IEventLogger
1416
+     */
1417
+    public function getEventLogger() {
1418
+        return $this->query('EventLogger');
1419
+    }
1420
+
1421
+    /**
1422
+     * Get the active query logger
1423
+     *
1424
+     * The returned logger only logs data when debug mode is enabled
1425
+     *
1426
+     * @return \OCP\Diagnostics\IQueryLogger
1427
+     */
1428
+    public function getQueryLogger() {
1429
+        return $this->query('QueryLogger');
1430
+    }
1431
+
1432
+    /**
1433
+     * Get the manager for temporary files and folders
1434
+     *
1435
+     * @return \OCP\ITempManager
1436
+     */
1437
+    public function getTempManager() {
1438
+        return $this->query('TempManager');
1439
+    }
1440
+
1441
+    /**
1442
+     * Get the app manager
1443
+     *
1444
+     * @return \OCP\App\IAppManager
1445
+     */
1446
+    public function getAppManager() {
1447
+        return $this->query('AppManager');
1448
+    }
1449
+
1450
+    /**
1451
+     * Creates a new mailer
1452
+     *
1453
+     * @return \OCP\Mail\IMailer
1454
+     */
1455
+    public function getMailer() {
1456
+        return $this->query('Mailer');
1457
+    }
1458
+
1459
+    /**
1460
+     * Get the webroot
1461
+     *
1462
+     * @return string
1463
+     */
1464
+    public function getWebRoot() {
1465
+        return $this->webRoot;
1466
+    }
1467
+
1468
+    /**
1469
+     * @return \OC\OCSClient
1470
+     */
1471
+    public function getOcsClient() {
1472
+        return $this->query('OcsClient');
1473
+    }
1474
+
1475
+    /**
1476
+     * @return \OCP\IDateTimeZone
1477
+     */
1478
+    public function getDateTimeZone() {
1479
+        return $this->query('DateTimeZone');
1480
+    }
1481
+
1482
+    /**
1483
+     * @return \OCP\IDateTimeFormatter
1484
+     */
1485
+    public function getDateTimeFormatter() {
1486
+        return $this->query('DateTimeFormatter');
1487
+    }
1488
+
1489
+    /**
1490
+     * @return \OCP\Files\Config\IMountProviderCollection
1491
+     */
1492
+    public function getMountProviderCollection() {
1493
+        return $this->query('MountConfigManager');
1494
+    }
1495
+
1496
+    /**
1497
+     * Get the IniWrapper
1498
+     *
1499
+     * @return IniGetWrapper
1500
+     */
1501
+    public function getIniWrapper() {
1502
+        return $this->query('IniWrapper');
1503
+    }
1504
+
1505
+    /**
1506
+     * @return \OCP\Command\IBus
1507
+     */
1508
+    public function getCommandBus() {
1509
+        return $this->query('AsyncCommandBus');
1510
+    }
1511
+
1512
+    /**
1513
+     * Get the trusted domain helper
1514
+     *
1515
+     * @return TrustedDomainHelper
1516
+     */
1517
+    public function getTrustedDomainHelper() {
1518
+        return $this->query('TrustedDomainHelper');
1519
+    }
1520
+
1521
+    /**
1522
+     * Get the locking provider
1523
+     *
1524
+     * @return \OCP\Lock\ILockingProvider
1525
+     * @since 8.1.0
1526
+     */
1527
+    public function getLockingProvider() {
1528
+        return $this->query('LockingProvider');
1529
+    }
1530
+
1531
+    /**
1532
+     * @return \OCP\Files\Mount\IMountManager
1533
+     **/
1534
+    function getMountManager() {
1535
+        return $this->query('MountManager');
1536
+    }
1537
+
1538
+    /** @return \OCP\Files\Config\IUserMountCache */
1539
+    function getUserMountCache() {
1540
+        return $this->query('UserMountCache');
1541
+    }
1542
+
1543
+    /**
1544
+     * Get the MimeTypeDetector
1545
+     *
1546
+     * @return \OCP\Files\IMimeTypeDetector
1547
+     */
1548
+    public function getMimeTypeDetector() {
1549
+        return $this->query('MimeTypeDetector');
1550
+    }
1551
+
1552
+    /**
1553
+     * Get the MimeTypeLoader
1554
+     *
1555
+     * @return \OCP\Files\IMimeTypeLoader
1556
+     */
1557
+    public function getMimeTypeLoader() {
1558
+        return $this->query('MimeTypeLoader');
1559
+    }
1560
+
1561
+    /**
1562
+     * Get the manager of all the capabilities
1563
+     *
1564
+     * @return \OC\CapabilitiesManager
1565
+     */
1566
+    public function getCapabilitiesManager() {
1567
+        return $this->query('CapabilitiesManager');
1568
+    }
1569
+
1570
+    /**
1571
+     * Get the EventDispatcher
1572
+     *
1573
+     * @return EventDispatcherInterface
1574
+     * @since 8.2.0
1575
+     */
1576
+    public function getEventDispatcher() {
1577
+        return $this->query('EventDispatcher');
1578
+    }
1579
+
1580
+    /**
1581
+     * Get the Notification Manager
1582
+     *
1583
+     * @return \OCP\Notification\IManager
1584
+     * @since 8.2.0
1585
+     */
1586
+    public function getNotificationManager() {
1587
+        return $this->query('NotificationManager');
1588
+    }
1589
+
1590
+    /**
1591
+     * @return \OCP\Comments\ICommentsManager
1592
+     */
1593
+    public function getCommentsManager() {
1594
+        return $this->query('CommentsManager');
1595
+    }
1596
+
1597
+    /**
1598
+     * @return \OC_Defaults
1599
+     */
1600
+    public function getThemingDefaults() {
1601
+        return $this->query('ThemingDefaults');
1602
+    }
1603
+
1604
+    /**
1605
+     * @return \OC\IntegrityCheck\Checker
1606
+     */
1607
+    public function getIntegrityCodeChecker() {
1608
+        return $this->query('IntegrityCodeChecker');
1609
+    }
1610
+
1611
+    /**
1612
+     * @return \OC\Session\CryptoWrapper
1613
+     */
1614
+    public function getSessionCryptoWrapper() {
1615
+        return $this->query('CryptoWrapper');
1616
+    }
1617
+
1618
+    /**
1619
+     * @return CsrfTokenManager
1620
+     */
1621
+    public function getCsrfTokenManager() {
1622
+        return $this->query('CsrfTokenManager');
1623
+    }
1624
+
1625
+    /**
1626
+     * @return Throttler
1627
+     */
1628
+    public function getBruteForceThrottler() {
1629
+        return $this->query('Throttler');
1630
+    }
1631
+
1632
+    /**
1633
+     * @return IContentSecurityPolicyManager
1634
+     */
1635
+    public function getContentSecurityPolicyManager() {
1636
+        return $this->query('ContentSecurityPolicyManager');
1637
+    }
1638
+
1639
+    /**
1640
+     * @return ContentSecurityPolicyNonceManager
1641
+     */
1642
+    public function getContentSecurityPolicyNonceManager() {
1643
+        return $this->query('ContentSecurityPolicyNonceManager');
1644
+    }
1645
+
1646
+    /**
1647
+     * Not a public API as of 8.2, wait for 9.0
1648
+     *
1649
+     * @return \OCA\Files_External\Service\BackendService
1650
+     */
1651
+    public function getStoragesBackendService() {
1652
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1653
+    }
1654
+
1655
+    /**
1656
+     * Not a public API as of 8.2, wait for 9.0
1657
+     *
1658
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1659
+     */
1660
+    public function getGlobalStoragesService() {
1661
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1662
+    }
1663
+
1664
+    /**
1665
+     * Not a public API as of 8.2, wait for 9.0
1666
+     *
1667
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1668
+     */
1669
+    public function getUserGlobalStoragesService() {
1670
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1671
+    }
1672
+
1673
+    /**
1674
+     * Not a public API as of 8.2, wait for 9.0
1675
+     *
1676
+     * @return \OCA\Files_External\Service\UserStoragesService
1677
+     */
1678
+    public function getUserStoragesService() {
1679
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1680
+    }
1681
+
1682
+    /**
1683
+     * @return \OCP\Share\IManager
1684
+     */
1685
+    public function getShareManager() {
1686
+        return $this->query('ShareManager');
1687
+    }
1688
+
1689
+    /**
1690
+     * Returns the LDAP Provider
1691
+     *
1692
+     * @return \OCP\LDAP\ILDAPProvider
1693
+     */
1694
+    public function getLDAPProvider() {
1695
+        return $this->query('LDAPProvider');
1696
+    }
1697
+
1698
+    /**
1699
+     * @return \OCP\Settings\IManager
1700
+     */
1701
+    public function getSettingsManager() {
1702
+        return $this->query('SettingsManager');
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OCP\Files\IAppData
1707
+     */
1708
+    public function getAppDataDir($app) {
1709
+        /** @var \OC\Files\AppData\Factory $factory */
1710
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1711
+        return $factory->get($app);
1712
+    }
1713
+
1714
+    /**
1715
+     * @return \OCP\Lockdown\ILockdownManager
1716
+     */
1717
+    public function getLockdownManager() {
1718
+        return $this->query('LockdownManager');
1719
+    }
1720
+
1721
+    /**
1722
+     * @return \OCP\Federation\ICloudIdManager
1723
+     */
1724
+    public function getCloudIdManager() {
1725
+        return $this->query(ICloudIdManager::class);
1726
+    }
1727 1727
 }
Please login to merge, or discard this patch.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
134 134
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
135 135
 
136
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
136
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
137 137
 			return new PreviewManager(
138 138
 				$c->getConfig(),
139 139
 				$c->getRootFolder(),
@@ -144,13 +144,13 @@  discard block
 block discarded – undo
144 144
 		});
145 145
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
146 146
 
147
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
147
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
148 148
 			return new \OC\Preview\Watcher(
149 149
 				$c->getAppDataDir('preview')
150 150
 			);
151 151
 		});
152 152
 
153
-		$this->registerService('EncryptionManager', function (Server $c) {
153
+		$this->registerService('EncryptionManager', function(Server $c) {
154 154
 			$view = new View();
155 155
 			$util = new Encryption\Util(
156 156
 				$view,
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			);
169 169
 		});
170 170
 
171
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
171
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
172 172
 			$util = new Encryption\Util(
173 173
 				new View(),
174 174
 				$c->getUserManager(),
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 			return new Encryption\File($util);
179 179
 		});
180 180
 
181
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
181
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
182 182
 			$view = new View();
183 183
 			$util = new Encryption\Util(
184 184
 				$view,
@@ -189,32 +189,32 @@  discard block
 block discarded – undo
189 189
 
190 190
 			return new Encryption\Keys\Storage($view, $util);
191 191
 		});
192
-		$this->registerService('TagMapper', function (Server $c) {
192
+		$this->registerService('TagMapper', function(Server $c) {
193 193
 			return new TagMapper($c->getDatabaseConnection());
194 194
 		});
195 195
 
196
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
196
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
197 197
 			$tagMapper = $c->query('TagMapper');
198 198
 			return new TagManager($tagMapper, $c->getUserSession());
199 199
 		});
200 200
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
201 201
 
202
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
202
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
203 203
 			$config = $c->getConfig();
204 204
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
205 205
 			/** @var \OC\SystemTag\ManagerFactory $factory */
206 206
 			$factory = new $factoryClass($this);
207 207
 			return $factory;
208 208
 		});
209
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
209
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
210 210
 			return $c->query('SystemTagManagerFactory')->getManager();
211 211
 		});
212 212
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
213 213
 
214
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
214
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
215 215
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
216 216
 		});
217
-		$this->registerService('RootFolder', function (Server $c) {
217
+		$this->registerService('RootFolder', function(Server $c) {
218 218
 			$manager = \OC\Files\Filesystem::getMountManager(null);
219 219
 			$view = new View();
220 220
 			$root = new Root(
@@ -242,30 +242,30 @@  discard block
 block discarded – undo
242 242
 		});
243 243
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
244 244
 
245
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
245
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
246 246
 			$config = $c->getConfig();
247 247
 			return new \OC\User\Manager($config);
248 248
 		});
249 249
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
250 250
 
251
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
251
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
252 252
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
253
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
253
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
254 254
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
255 255
 			});
256
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
256
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
257 257
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
258 258
 			});
259
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
259
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
260 260
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
261 261
 			});
262
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
262
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
263 263
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
264 264
 			});
265
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
265
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
266 266
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
267 267
 			});
268
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
268
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
269 269
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
270 270
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
271 271
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -285,11 +285,11 @@  discard block
 block discarded – undo
285 285
 			return new Store($session, $logger, $tokenProvider);
286 286
 		});
287 287
 		$this->registerAlias(IStore::class, Store::class);
288
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
288
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
289 289
 			$dbConnection = $c->getDatabaseConnection();
290 290
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
291 291
 		});
292
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
292
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
293 293
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
294 294
 			$crypto = $c->getCrypto();
295 295
 			$config = $c->getConfig();
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 		});
300 300
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
301 301
 
302
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
302
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
303 303
 			$manager = $c->getUserManager();
304 304
 			$session = new \OC\Session\Memory('');
305 305
 			$timeFactory = new TimeFactory();
@@ -312,40 +312,40 @@  discard block
 block discarded – undo
312 312
 			}
313 313
 
314 314
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
315
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
315
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
316 316
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
317 317
 			});
318
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
318
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
319 319
 				/** @var $user \OC\User\User */
320 320
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
321 321
 			});
322
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
322
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
323 323
 				/** @var $user \OC\User\User */
324 324
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
325 325
 			});
326
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
326
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
327 327
 				/** @var $user \OC\User\User */
328 328
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
329 329
 			});
330
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
330
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
331 331
 				/** @var $user \OC\User\User */
332 332
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
333 333
 			});
334
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
334
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
335 335
 				/** @var $user \OC\User\User */
336 336
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
337 337
 			});
338
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
338
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
339 339
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
340 340
 			});
341
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
341
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
342 342
 				/** @var $user \OC\User\User */
343 343
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
344 344
 			});
345
-			$userSession->listen('\OC\User', 'logout', function () {
345
+			$userSession->listen('\OC\User', 'logout', function() {
346 346
 				\OC_Hook::emit('OC_User', 'logout', array());
347 347
 			});
348
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
348
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
349 349
 				/** @var $user \OC\User\User */
350 350
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
351 351
 			});
@@ -353,11 +353,11 @@  discard block
 block discarded – undo
353 353
 		});
354 354
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
355 355
 
356
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
356
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
357 357
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
358 358
 		});
359 359
 
360
-		$this->registerService(\OCP\INavigationManager::class, function (Server $c) {
360
+		$this->registerService(\OCP\INavigationManager::class, function(Server $c) {
361 361
 			return new \OC\NavigationManager($c->getAppManager(),
362 362
 				$c->getURLGenerator(),
363 363
 				$c->getL10NFactory(),
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
 		});
367 367
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
368 368
 
369
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
369
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
370 370
 			return new \OC\AllConfig(
371 371
 				$c->getSystemConfig()
372 372
 			);
@@ -374,17 +374,17 @@  discard block
 block discarded – undo
374 374
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
375 375
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
376 376
 
377
-		$this->registerService('SystemConfig', function ($c) use ($config) {
377
+		$this->registerService('SystemConfig', function($c) use ($config) {
378 378
 			return new \OC\SystemConfig($config);
379 379
 		});
380 380
 
381
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
381
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
382 382
 			return new \OC\AppConfig($c->getDatabaseConnection());
383 383
 		});
384 384
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
385 385
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
386 386
 
387
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
387
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
388 388
 			return new \OC\L10N\Factory(
389 389
 				$c->getConfig(),
390 390
 				$c->getRequest(),
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 		});
395 395
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
396 396
 
397
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
397
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
398 398
 			$config = $c->getConfig();
399 399
 			$cacheFactory = $c->getMemCacheFactory();
400 400
 			return new \OC\URLGenerator(
@@ -404,10 +404,10 @@  discard block
 block discarded – undo
404 404
 		});
405 405
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
406 406
 
407
-		$this->registerService('AppHelper', function ($c) {
407
+		$this->registerService('AppHelper', function($c) {
408 408
 			return new \OC\AppHelper();
409 409
 		});
410
-		$this->registerService('AppFetcher', function ($c) {
410
+		$this->registerService('AppFetcher', function($c) {
411 411
 			return new AppFetcher(
412 412
 				$this->getAppDataDir('appstore'),
413 413
 				$this->getHTTPClientService(),
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 				$this->getConfig()
416 416
 			);
417 417
 		});
418
-		$this->registerService('CategoryFetcher', function ($c) {
418
+		$this->registerService('CategoryFetcher', function($c) {
419 419
 			return new CategoryFetcher(
420 420
 				$this->getAppDataDir('appstore'),
421 421
 				$this->getHTTPClientService(),
@@ -424,21 +424,21 @@  discard block
 block discarded – undo
424 424
 			);
425 425
 		});
426 426
 
427
-		$this->registerService(\OCP\ICache::class, function ($c) {
427
+		$this->registerService(\OCP\ICache::class, function($c) {
428 428
 			return new Cache\File();
429 429
 		});
430 430
 		$this->registerAlias('UserCache', \OCP\ICache::class);
431 431
 
432
-		$this->registerService(Factory::class, function (Server $c) {
432
+		$this->registerService(Factory::class, function(Server $c) {
433 433
 			$config = $c->getConfig();
434 434
 
435 435
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
436 436
 				$v = \OC_App::getAppVersions();
437
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
437
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
438 438
 				$version = implode(',', $v);
439 439
 				$instanceId = \OC_Util::getInstanceId();
440 440
 				$path = \OC::$SERVERROOT;
441
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
441
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
442 442
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
443 443
 					$config->getSystemValue('memcache.local', null),
444 444
 					$config->getSystemValue('memcache.distributed', null),
@@ -455,12 +455,12 @@  discard block
 block discarded – undo
455 455
 		$this->registerAlias('MemCacheFactory', Factory::class);
456 456
 		$this->registerAlias(ICacheFactory::class, Factory::class);
457 457
 
458
-		$this->registerService('RedisFactory', function (Server $c) {
458
+		$this->registerService('RedisFactory', function(Server $c) {
459 459
 			$systemConfig = $c->getSystemConfig();
460 460
 			return new RedisFactory($systemConfig);
461 461
 		});
462 462
 
463
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
463
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
464 464
 			return new \OC\Activity\Manager(
465 465
 				$c->getRequest(),
466 466
 				$c->getUserSession(),
@@ -470,14 +470,14 @@  discard block
 block discarded – undo
470 470
 		});
471 471
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
472 472
 
473
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
473
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
474 474
 			return new \OC\Activity\EventMerger(
475 475
 				$c->getL10N('lib')
476 476
 			);
477 477
 		});
478 478
 		$this->registerAlias(IValidator::class, Validator::class);
479 479
 
480
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
480
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
481 481
 			return new AvatarManager(
482 482
 				$c->getUserManager(),
483 483
 				$c->getAppDataDir('avatar'),
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 		});
489 489
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
490 490
 
491
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
491
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
492 492
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
493 493
 			$logger = Log::getLogClass($logType);
494 494
 			call_user_func(array($logger, 'init'));
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 		});
498 498
 		$this->registerAlias('Logger', \OCP\ILogger::class);
499 499
 
500
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
500
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
501 501
 			$config = $c->getConfig();
502 502
 			return new \OC\BackgroundJob\JobList(
503 503
 				$c->getDatabaseConnection(),
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
 		});
508 508
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
509 509
 
510
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
510
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
511 511
 			$cacheFactory = $c->getMemCacheFactory();
512 512
 			$logger = $c->getLogger();
513 513
 			if ($cacheFactory->isAvailable()) {
@@ -519,32 +519,32 @@  discard block
 block discarded – undo
519 519
 		});
520 520
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
521 521
 
522
-		$this->registerService(\OCP\ISearch::class, function ($c) {
522
+		$this->registerService(\OCP\ISearch::class, function($c) {
523 523
 			return new Search();
524 524
 		});
525 525
 		$this->registerAlias('Search', \OCP\ISearch::class);
526 526
 
527
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
527
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
528 528
 			return new SecureRandom();
529 529
 		});
530 530
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
531 531
 
532
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
532
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
533 533
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
534 534
 		});
535 535
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
536 536
 
537
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
537
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
538 538
 			return new Hasher($c->getConfig());
539 539
 		});
540 540
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
541 541
 
542
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
542
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
543 543
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
544 544
 		});
545 545
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
546 546
 
547
-		$this->registerService(IDBConnection::class, function (Server $c) {
547
+		$this->registerService(IDBConnection::class, function(Server $c) {
548 548
 			$systemConfig = $c->getSystemConfig();
549 549
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
550 550
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 		});
559 559
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
560 560
 
561
-		$this->registerService('HTTPHelper', function (Server $c) {
561
+		$this->registerService('HTTPHelper', function(Server $c) {
562 562
 			$config = $c->getConfig();
563 563
 			return new HTTPHelper(
564 564
 				$config,
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 			);
567 567
 		});
568 568
 
569
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
569
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
570 570
 			$user = \OC_User::getUser();
571 571
 			$uid = $user ? $user : null;
572 572
 			return new ClientService(
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 		});
577 577
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
578 578
 
579
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
579
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
580 580
 			if ($c->getSystemConfig()->getValue('debug', false)) {
581 581
 				return new EventLogger();
582 582
 			} else {
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 		});
586 586
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
587 587
 
588
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
588
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
589 589
 			if ($c->getSystemConfig()->getValue('debug', false)) {
590 590
 				return new QueryLogger();
591 591
 			} else {
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 		});
595 595
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
596 596
 
597
-		$this->registerService(TempManager::class, function (Server $c) {
597
+		$this->registerService(TempManager::class, function(Server $c) {
598 598
 			return new TempManager(
599 599
 				$c->getLogger(),
600 600
 				$c->getConfig()
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
 		$this->registerAlias('TempManager', TempManager::class);
604 604
 		$this->registerAlias(ITempManager::class, TempManager::class);
605 605
 
606
-		$this->registerService(AppManager::class, function (Server $c) {
606
+		$this->registerService(AppManager::class, function(Server $c) {
607 607
 			return new \OC\App\AppManager(
608 608
 				$c->getUserSession(),
609 609
 				$c->getAppConfig(),
@@ -615,7 +615,7 @@  discard block
 block discarded – undo
615 615
 		$this->registerAlias('AppManager', AppManager::class);
616 616
 		$this->registerAlias(IAppManager::class, AppManager::class);
617 617
 
618
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
618
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
619 619
 			return new DateTimeZone(
620 620
 				$c->getConfig(),
621 621
 				$c->getSession()
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 		});
624 624
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
625 625
 
626
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
626
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
627 627
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
628 628
 
629 629
 			return new DateTimeFormatter(
@@ -633,7 +633,7 @@  discard block
 block discarded – undo
633 633
 		});
634 634
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
635 635
 
636
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
636
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
637 637
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
638 638
 			$listener = new UserMountCacheListener($mountCache);
639 639
 			$listener->listen($c->getUserManager());
@@ -641,10 +641,10 @@  discard block
 block discarded – undo
641 641
 		});
642 642
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
643 643
 
644
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
644
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
645 645
 			$loader = \OC\Files\Filesystem::getLoader();
646 646
 			$mountCache = $c->query('UserMountCache');
647
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
647
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
648 648
 
649 649
 			// builtin providers
650 650
 
@@ -657,14 +657,14 @@  discard block
 block discarded – undo
657 657
 		});
658 658
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
659 659
 
660
-		$this->registerService('IniWrapper', function ($c) {
660
+		$this->registerService('IniWrapper', function($c) {
661 661
 			return new IniGetWrapper();
662 662
 		});
663
-		$this->registerService('AsyncCommandBus', function (Server $c) {
663
+		$this->registerService('AsyncCommandBus', function(Server $c) {
664 664
 			$jobList = $c->getJobList();
665 665
 			return new AsyncBus($jobList);
666 666
 		});
667
-		$this->registerService('TrustedDomainHelper', function ($c) {
667
+		$this->registerService('TrustedDomainHelper', function($c) {
668 668
 			return new TrustedDomainHelper($this->getConfig());
669 669
 		});
670 670
 		$this->registerService('Throttler', function(Server $c) {
@@ -675,10 +675,10 @@  discard block
 block discarded – undo
675 675
 				$c->getConfig()
676 676
 			);
677 677
 		});
678
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
678
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
679 679
 			// IConfig and IAppManager requires a working database. This code
680 680
 			// might however be called when ownCloud is not yet setup.
681
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
681
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
682 682
 				$config = $c->getConfig();
683 683
 				$appManager = $c->getAppManager();
684 684
 			} else {
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 					$c->getTempManager()
697 697
 			);
698 698
 		});
699
-		$this->registerService(\OCP\IRequest::class, function ($c) {
699
+		$this->registerService(\OCP\IRequest::class, function($c) {
700 700
 			if (isset($this['urlParams'])) {
701 701
 				$urlParams = $this['urlParams'];
702 702
 			} else {
@@ -732,7 +732,7 @@  discard block
 block discarded – undo
732 732
 		});
733 733
 		$this->registerAlias('Request', \OCP\IRequest::class);
734 734
 
735
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
735
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
736 736
 			return new Mailer(
737 737
 				$c->getConfig(),
738 738
 				$c->getLogger(),
@@ -744,14 +744,14 @@  discard block
 block discarded – undo
744 744
 		$this->registerService('LDAPProvider', function(Server $c) {
745 745
 			$config = $c->getConfig();
746 746
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
747
-			if(is_null($factoryClass)) {
747
+			if (is_null($factoryClass)) {
748 748
 				throw new \Exception('ldapProviderFactory not set');
749 749
 			}
750 750
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
751 751
 			$factory = new $factoryClass($this);
752 752
 			return $factory->getLDAPProvider();
753 753
 		});
754
-		$this->registerService('LockingProvider', function (Server $c) {
754
+		$this->registerService('LockingProvider', function(Server $c) {
755 755
 			$ini = $c->getIniWrapper();
756 756
 			$config = $c->getConfig();
757 757
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -767,37 +767,37 @@  discard block
 block discarded – undo
767 767
 			return new NoopLockingProvider();
768 768
 		});
769 769
 
770
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
770
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
771 771
 			return new \OC\Files\Mount\Manager();
772 772
 		});
773 773
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
774 774
 
775
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
775
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
776 776
 			return new \OC\Files\Type\Detection(
777 777
 				$c->getURLGenerator(),
778 778
 				\OC::$configDir,
779
-				\OC::$SERVERROOT . '/resources/config/'
779
+				\OC::$SERVERROOT.'/resources/config/'
780 780
 			);
781 781
 		});
782 782
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
783 783
 
784
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
784
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
785 785
 			return new \OC\Files\Type\Loader(
786 786
 				$c->getDatabaseConnection()
787 787
 			);
788 788
 		});
789 789
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
790 790
 
791
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
791
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
792 792
 			return new Manager(
793 793
 				$c->query(IValidator::class)
794 794
 			);
795 795
 		});
796 796
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
797 797
 
798
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
798
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
799 799
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
800
-			$manager->registerCapability(function () use ($c) {
800
+			$manager->registerCapability(function() use ($c) {
801 801
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
802 802
 			});
803 803
 			return $manager;
@@ -854,13 +854,13 @@  discard block
 block discarded – undo
854 854
 
855 855
 			);
856 856
 		});
857
-		$this->registerService(EventDispatcher::class, function () {
857
+		$this->registerService(EventDispatcher::class, function() {
858 858
 			return new EventDispatcher();
859 859
 		});
860 860
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
861 861
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
862 862
 
863
-		$this->registerService('CryptoWrapper', function (Server $c) {
863
+		$this->registerService('CryptoWrapper', function(Server $c) {
864 864
 			// FIXME: Instantiiated here due to cyclic dependency
865 865
 			$request = new Request(
866 866
 				[
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 				$request
886 886
 			);
887 887
 		});
888
-		$this->registerService('CsrfTokenManager', function (Server $c) {
888
+		$this->registerService('CsrfTokenManager', function(Server $c) {
889 889
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
890 890
 
891 891
 			return new CsrfTokenManager(
@@ -893,10 +893,10 @@  discard block
 block discarded – undo
893 893
 				$c->query(SessionStorage::class)
894 894
 			);
895 895
 		});
896
-		$this->registerService(SessionStorage::class, function (Server $c) {
896
+		$this->registerService(SessionStorage::class, function(Server $c) {
897 897
 			return new SessionStorage($c->getSession());
898 898
 		});
899
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
899
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
900 900
 			return new ContentSecurityPolicyManager();
901 901
 		});
902 902
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -947,23 +947,23 @@  discard block
 block discarded – undo
947 947
 			);
948 948
 			return $manager;
949 949
 		});
950
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
950
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
951 951
 			return new \OC\Files\AppData\Factory(
952 952
 				$c->getRootFolder(),
953 953
 				$c->getSystemConfig()
954 954
 			);
955 955
 		});
956 956
 
957
-		$this->registerService('LockdownManager', function (Server $c) {
957
+		$this->registerService('LockdownManager', function(Server $c) {
958 958
 			return new LockdownManager();
959 959
 		});
960 960
 
961
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
961
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
962 962
 			return new CloudIdManager();
963 963
 		});
964 964
 
965 965
 		/* To trick DI since we don't extend the DIContainer here */
966
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
966
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
967 967
 			return new CleanPreviewsBackgroundJob(
968 968
 				$c->getRootFolder(),
969 969
 				$c->getLogger(),
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
 	 * @deprecated since 9.2.0 use IAppData
1118 1118
 	 */
1119 1119
 	public function getAppFolder() {
1120
-		$dir = '/' . \OC_App::getCurrentApp();
1120
+		$dir = '/'.\OC_App::getCurrentApp();
1121 1121
 		$root = $this->getRootFolder();
1122 1122
 		if (!$root->nodeExists($dir)) {
1123 1123
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/Response.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 
227 227
 	/**
228 228
 	 * By default renders no output
229
-	 * @return null
229
+	 * @return string
230 230
 	 * @since 6.0.0
231 231
 	 */
232 232
 	public function render() {
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 
260 260
 	/**
261 261
 	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
262
+	 * @return ContentSecurityPolicy|null Used Content-Security-Policy or null if
263 263
 	 *                                    none specified.
264 264
 	 * @since 8.1.0
265 265
 	 */
Please login to merge, or discard this patch.
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -42,285 +42,285 @@
 block discarded – undo
42 42
  */
43 43
 class Response {
44 44
 
45
-	/**
46
-	 * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
-	 * @var array
48
-	 */
49
-	private $headers = array(
50
-		'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
-	);
52
-
53
-
54
-	/**
55
-	 * Cookies that will be need to be constructed as header
56
-	 * @var array
57
-	 */
58
-	private $cookies = array();
59
-
60
-
61
-	/**
62
-	 * HTTP status code - defaults to STATUS OK
63
-	 * @var int
64
-	 */
65
-	private $status = Http::STATUS_OK;
66
-
67
-
68
-	/**
69
-	 * Last modified date
70
-	 * @var \DateTime
71
-	 */
72
-	private $lastModified;
73
-
74
-
75
-	/**
76
-	 * ETag
77
-	 * @var string
78
-	 */
79
-	private $ETag;
80
-
81
-	/** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
-	private $contentSecurityPolicy = null;
83
-
84
-
85
-	/**
86
-	 * Caches the response
87
-	 * @param int $cacheSeconds the amount of seconds that should be cached
88
-	 * if 0 then caching will be disabled
89
-	 * @return $this
90
-	 * @since 6.0.0 - return value was added in 7.0.0
91
-	 */
92
-	public function cacheFor($cacheSeconds) {
93
-
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
-		} else {
97
-			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
-		}
99
-
100
-		return $this;
101
-	}
102
-
103
-	/**
104
-	 * Adds a new cookie to the response
105
-	 * @param string $name The name of the cookie
106
-	 * @param string $value The value of the cookie
107
-	 * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
-	 * 									to null cookie will be considered as session
109
-	 * 									cookie.
110
-	 * @return $this
111
-	 * @since 8.0.0
112
-	 */
113
-	public function addCookie($name, $value, \DateTime $expireDate = null) {
114
-		$this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
-		return $this;
116
-	}
117
-
118
-
119
-	/**
120
-	 * Set the specified cookies
121
-	 * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
-	 * @return $this
123
-	 * @since 8.0.0
124
-	 */
125
-	public function setCookies(array $cookies) {
126
-		$this->cookies = $cookies;
127
-		return $this;
128
-	}
129
-
130
-
131
-	/**
132
-	 * Invalidates the specified cookie
133
-	 * @param string $name
134
-	 * @return $this
135
-	 * @since 8.0.0
136
-	 */
137
-	public function invalidateCookie($name) {
138
-		$this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
-		return $this;
140
-	}
141
-
142
-	/**
143
-	 * Invalidates the specified cookies
144
-	 * @param array $cookieNames array('foo', 'bar')
145
-	 * @return $this
146
-	 * @since 8.0.0
147
-	 */
148
-	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
150
-			$this->invalidateCookie($cookieName);
151
-		}
152
-		return $this;
153
-	}
154
-
155
-	/**
156
-	 * Returns the cookies
157
-	 * @return array
158
-	 * @since 8.0.0
159
-	 */
160
-	public function getCookies() {
161
-		return $this->cookies;
162
-	}
163
-
164
-	/**
165
-	 * Adds a new header to the response that will be called before the render
166
-	 * function
167
-	 * @param string $name The name of the HTTP header
168
-	 * @param string $value The value, null will delete it
169
-	 * @return $this
170
-	 * @since 6.0.0 - return value was added in 7.0.0
171
-	 */
172
-	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
174
-		                      // to be able to reliably check for security
175
-		                      // headers
176
-
177
-		if(is_null($value)) {
178
-			unset($this->headers[$name]);
179
-		} else {
180
-			$this->headers[$name] = $value;
181
-		}
182
-
183
-		return $this;
184
-	}
185
-
186
-
187
-	/**
188
-	 * Set the headers
189
-	 * @param array $headers value header pairs
190
-	 * @return $this
191
-	 * @since 8.0.0
192
-	 */
193
-	public function setHeaders(array $headers) {
194
-		$this->headers = $headers;
195
-
196
-		return $this;
197
-	}
198
-
199
-
200
-	/**
201
-	 * Returns the set headers
202
-	 * @return array the headers
203
-	 * @since 6.0.0
204
-	 */
205
-	public function getHeaders() {
206
-		$mergeWith = [];
207
-
208
-		if($this->lastModified) {
209
-			$mergeWith['Last-Modified'] =
210
-				$this->lastModified->format(\DateTime::RFC2822);
211
-		}
212
-
213
-		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
215
-			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
-		}
217
-		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
-
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
221
-		}
222
-
223
-		return array_merge($mergeWith, $this->headers);
224
-	}
225
-
226
-
227
-	/**
228
-	 * By default renders no output
229
-	 * @return null
230
-	 * @since 6.0.0
231
-	 */
232
-	public function render() {
233
-		return null;
234
-	}
235
-
236
-
237
-	/**
238
-	 * Set response status
239
-	 * @param int $status a HTTP status code, see also the STATUS constants
240
-	 * @return Response Reference to this object
241
-	 * @since 6.0.0 - return value was added in 7.0.0
242
-	 */
243
-	public function setStatus($status) {
244
-		$this->status = $status;
245
-
246
-		return $this;
247
-	}
248
-
249
-	/**
250
-	 * Set a Content-Security-Policy
251
-	 * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
-	 * @return $this
253
-	 * @since 8.1.0
254
-	 */
255
-	public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
-		$this->contentSecurityPolicy = $csp;
257
-		return $this;
258
-	}
259
-
260
-	/**
261
-	 * Get the currently used Content-Security-Policy
262
-	 * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
-	 *                                    none specified.
264
-	 * @since 8.1.0
265
-	 */
266
-	public function getContentSecurityPolicy() {
267
-		return $this->contentSecurityPolicy;
268
-	}
269
-
270
-
271
-	/**
272
-	 * Get response status
273
-	 * @since 6.0.0
274
-	 */
275
-	public function getStatus() {
276
-		return $this->status;
277
-	}
278
-
279
-
280
-	/**
281
-	 * Get the ETag
282
-	 * @return string the etag
283
-	 * @since 6.0.0
284
-	 */
285
-	public function getETag() {
286
-		return $this->ETag;
287
-	}
288
-
289
-
290
-	/**
291
-	 * Get "last modified" date
292
-	 * @return \DateTime RFC2822 formatted last modified date
293
-	 * @since 6.0.0
294
-	 */
295
-	public function getLastModified() {
296
-		return $this->lastModified;
297
-	}
298
-
299
-
300
-	/**
301
-	 * Set the ETag
302
-	 * @param string $ETag
303
-	 * @return Response Reference to this object
304
-	 * @since 6.0.0 - return value was added in 7.0.0
305
-	 */
306
-	public function setETag($ETag) {
307
-		$this->ETag = $ETag;
308
-
309
-		return $this;
310
-	}
311
-
312
-
313
-	/**
314
-	 * Set "last modified" date
315
-	 * @param \DateTime $lastModified
316
-	 * @return Response Reference to this object
317
-	 * @since 6.0.0 - return value was added in 7.0.0
318
-	 */
319
-	public function setLastModified($lastModified) {
320
-		$this->lastModified = $lastModified;
321
-
322
-		return $this;
323
-	}
45
+    /**
46
+     * Headers - defaults to ['Cache-Control' => 'no-cache, no-store, must-revalidate']
47
+     * @var array
48
+     */
49
+    private $headers = array(
50
+        'Cache-Control' => 'no-cache, no-store, must-revalidate'
51
+    );
52
+
53
+
54
+    /**
55
+     * Cookies that will be need to be constructed as header
56
+     * @var array
57
+     */
58
+    private $cookies = array();
59
+
60
+
61
+    /**
62
+     * HTTP status code - defaults to STATUS OK
63
+     * @var int
64
+     */
65
+    private $status = Http::STATUS_OK;
66
+
67
+
68
+    /**
69
+     * Last modified date
70
+     * @var \DateTime
71
+     */
72
+    private $lastModified;
73
+
74
+
75
+    /**
76
+     * ETag
77
+     * @var string
78
+     */
79
+    private $ETag;
80
+
81
+    /** @var ContentSecurityPolicy|null Used Content-Security-Policy */
82
+    private $contentSecurityPolicy = null;
83
+
84
+
85
+    /**
86
+     * Caches the response
87
+     * @param int $cacheSeconds the amount of seconds that should be cached
88
+     * if 0 then caching will be disabled
89
+     * @return $this
90
+     * @since 6.0.0 - return value was added in 7.0.0
91
+     */
92
+    public function cacheFor($cacheSeconds) {
93
+
94
+        if($cacheSeconds > 0) {
95
+            $this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
96
+        } else {
97
+            $this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98
+        }
99
+
100
+        return $this;
101
+    }
102
+
103
+    /**
104
+     * Adds a new cookie to the response
105
+     * @param string $name The name of the cookie
106
+     * @param string $value The value of the cookie
107
+     * @param \DateTime|null $expireDate Date on that the cookie should expire, if set
108
+     * 									to null cookie will be considered as session
109
+     * 									cookie.
110
+     * @return $this
111
+     * @since 8.0.0
112
+     */
113
+    public function addCookie($name, $value, \DateTime $expireDate = null) {
114
+        $this->cookies[$name] = array('value' => $value, 'expireDate' => $expireDate);
115
+        return $this;
116
+    }
117
+
118
+
119
+    /**
120
+     * Set the specified cookies
121
+     * @param array $cookies array('foo' => array('value' => 'bar', 'expire' => null))
122
+     * @return $this
123
+     * @since 8.0.0
124
+     */
125
+    public function setCookies(array $cookies) {
126
+        $this->cookies = $cookies;
127
+        return $this;
128
+    }
129
+
130
+
131
+    /**
132
+     * Invalidates the specified cookie
133
+     * @param string $name
134
+     * @return $this
135
+     * @since 8.0.0
136
+     */
137
+    public function invalidateCookie($name) {
138
+        $this->addCookie($name, 'expired', new \DateTime('1971-01-01 00:00'));
139
+        return $this;
140
+    }
141
+
142
+    /**
143
+     * Invalidates the specified cookies
144
+     * @param array $cookieNames array('foo', 'bar')
145
+     * @return $this
146
+     * @since 8.0.0
147
+     */
148
+    public function invalidateCookies(array $cookieNames) {
149
+        foreach($cookieNames as $cookieName) {
150
+            $this->invalidateCookie($cookieName);
151
+        }
152
+        return $this;
153
+    }
154
+
155
+    /**
156
+     * Returns the cookies
157
+     * @return array
158
+     * @since 8.0.0
159
+     */
160
+    public function getCookies() {
161
+        return $this->cookies;
162
+    }
163
+
164
+    /**
165
+     * Adds a new header to the response that will be called before the render
166
+     * function
167
+     * @param string $name The name of the HTTP header
168
+     * @param string $value The value, null will delete it
169
+     * @return $this
170
+     * @since 6.0.0 - return value was added in 7.0.0
171
+     */
172
+    public function addHeader($name, $value) {
173
+        $name = trim($name);  // always remove leading and trailing whitespace
174
+                                // to be able to reliably check for security
175
+                                // headers
176
+
177
+        if(is_null($value)) {
178
+            unset($this->headers[$name]);
179
+        } else {
180
+            $this->headers[$name] = $value;
181
+        }
182
+
183
+        return $this;
184
+    }
185
+
186
+
187
+    /**
188
+     * Set the headers
189
+     * @param array $headers value header pairs
190
+     * @return $this
191
+     * @since 8.0.0
192
+     */
193
+    public function setHeaders(array $headers) {
194
+        $this->headers = $headers;
195
+
196
+        return $this;
197
+    }
198
+
199
+
200
+    /**
201
+     * Returns the set headers
202
+     * @return array the headers
203
+     * @since 6.0.0
204
+     */
205
+    public function getHeaders() {
206
+        $mergeWith = [];
207
+
208
+        if($this->lastModified) {
209
+            $mergeWith['Last-Modified'] =
210
+                $this->lastModified->format(\DateTime::RFC2822);
211
+        }
212
+
213
+        // Build Content-Security-Policy and use default if none has been specified
214
+        if(is_null($this->contentSecurityPolicy)) {
215
+            $this->setContentSecurityPolicy(new ContentSecurityPolicy());
216
+        }
217
+        $this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218
+
219
+        if($this->ETag) {
220
+            $mergeWith['ETag'] = '"' . $this->ETag . '"';
221
+        }
222
+
223
+        return array_merge($mergeWith, $this->headers);
224
+    }
225
+
226
+
227
+    /**
228
+     * By default renders no output
229
+     * @return null
230
+     * @since 6.0.0
231
+     */
232
+    public function render() {
233
+        return null;
234
+    }
235
+
236
+
237
+    /**
238
+     * Set response status
239
+     * @param int $status a HTTP status code, see also the STATUS constants
240
+     * @return Response Reference to this object
241
+     * @since 6.0.0 - return value was added in 7.0.0
242
+     */
243
+    public function setStatus($status) {
244
+        $this->status = $status;
245
+
246
+        return $this;
247
+    }
248
+
249
+    /**
250
+     * Set a Content-Security-Policy
251
+     * @param EmptyContentSecurityPolicy $csp Policy to set for the response object
252
+     * @return $this
253
+     * @since 8.1.0
254
+     */
255
+    public function setContentSecurityPolicy(EmptyContentSecurityPolicy $csp) {
256
+        $this->contentSecurityPolicy = $csp;
257
+        return $this;
258
+    }
259
+
260
+    /**
261
+     * Get the currently used Content-Security-Policy
262
+     * @return EmptyContentSecurityPolicy|null Used Content-Security-Policy or null if
263
+     *                                    none specified.
264
+     * @since 8.1.0
265
+     */
266
+    public function getContentSecurityPolicy() {
267
+        return $this->contentSecurityPolicy;
268
+    }
269
+
270
+
271
+    /**
272
+     * Get response status
273
+     * @since 6.0.0
274
+     */
275
+    public function getStatus() {
276
+        return $this->status;
277
+    }
278
+
279
+
280
+    /**
281
+     * Get the ETag
282
+     * @return string the etag
283
+     * @since 6.0.0
284
+     */
285
+    public function getETag() {
286
+        return $this->ETag;
287
+    }
288
+
289
+
290
+    /**
291
+     * Get "last modified" date
292
+     * @return \DateTime RFC2822 formatted last modified date
293
+     * @since 6.0.0
294
+     */
295
+    public function getLastModified() {
296
+        return $this->lastModified;
297
+    }
298
+
299
+
300
+    /**
301
+     * Set the ETag
302
+     * @param string $ETag
303
+     * @return Response Reference to this object
304
+     * @since 6.0.0 - return value was added in 7.0.0
305
+     */
306
+    public function setETag($ETag) {
307
+        $this->ETag = $ETag;
308
+
309
+        return $this;
310
+    }
311
+
312
+
313
+    /**
314
+     * Set "last modified" date
315
+     * @param \DateTime $lastModified
316
+     * @return Response Reference to this object
317
+     * @since 6.0.0 - return value was added in 7.0.0
318
+     */
319
+    public function setLastModified($lastModified) {
320
+        $this->lastModified = $lastModified;
321
+
322
+        return $this;
323
+    }
324 324
 
325 325
 
326 326
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function cacheFor($cacheSeconds) {
93 93
 
94
-		if($cacheSeconds > 0) {
95
-			$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
94
+		if ($cacheSeconds > 0) {
95
+			$this->addHeader('Cache-Control', 'max-age='.$cacheSeconds.', must-revalidate');
96 96
 		} else {
97 97
 			$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
98 98
 		}
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
 	 * @since 8.0.0
147 147
 	 */
148 148
 	public function invalidateCookies(array $cookieNames) {
149
-		foreach($cookieNames as $cookieName) {
149
+		foreach ($cookieNames as $cookieName) {
150 150
 			$this->invalidateCookie($cookieName);
151 151
 		}
152 152
 		return $this;
@@ -170,11 +170,11 @@  discard block
 block discarded – undo
170 170
 	 * @since 6.0.0 - return value was added in 7.0.0
171 171
 	 */
172 172
 	public function addHeader($name, $value) {
173
-		$name = trim($name);  // always remove leading and trailing whitespace
173
+		$name = trim($name); // always remove leading and trailing whitespace
174 174
 		                      // to be able to reliably check for security
175 175
 		                      // headers
176 176
 
177
-		if(is_null($value)) {
177
+		if (is_null($value)) {
178 178
 			unset($this->headers[$name]);
179 179
 		} else {
180 180
 			$this->headers[$name] = $value;
@@ -205,19 +205,19 @@  discard block
 block discarded – undo
205 205
 	public function getHeaders() {
206 206
 		$mergeWith = [];
207 207
 
208
-		if($this->lastModified) {
208
+		if ($this->lastModified) {
209 209
 			$mergeWith['Last-Modified'] =
210 210
 				$this->lastModified->format(\DateTime::RFC2822);
211 211
 		}
212 212
 
213 213
 		// Build Content-Security-Policy and use default if none has been specified
214
-		if(is_null($this->contentSecurityPolicy)) {
214
+		if (is_null($this->contentSecurityPolicy)) {
215 215
 			$this->setContentSecurityPolicy(new ContentSecurityPolicy());
216 216
 		}
217 217
 		$this->headers['Content-Security-Policy'] = $this->contentSecurityPolicy->buildPolicy();
218 218
 
219
-		if($this->ETag) {
220
-			$mergeWith['ETag'] = '"' . $this->ETag . '"';
219
+		if ($this->ETag) {
220
+			$mergeWith['ETag'] = '"'.$this->ETag.'"';
221 221
 		}
222 222
 
223 223
 		return array_merge($mergeWith, $this->headers);
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 4 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.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 namespace OC\Share20;
25 25
 
26 26
 use OC\Files\Cache\Cache;
27
-use OC\Files\Cache\CacheEntry;
28 27
 use OCP\Files\File;
29 28
 use OCP\Files\Folder;
30 29
 use OCP\Share\IShareProvider;
Please login to merge, or discard this patch.
Indentation   +987 added lines, -987 removed lines patch added patch discarded remove patch
@@ -47,1024 +47,1024 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->execute();
206
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
-			$qb = $this->dbConn->getQueryBuilder();
208
-			$qb->update('share')
209
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->execute();
216
-
217
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->execute();
206
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
+            $qb = $this->dbConn->getQueryBuilder();
208
+            $qb->update('share')
209
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->execute();
216
+
217
+            /*
218 218
 			 * Update all user defined group shares
219 219
 			 */
220
-			$qb = $this->dbConn->getQueryBuilder();
221
-			$qb->update('share')
222
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
-				->execute();
228
-
229
-			/*
220
+            $qb = $this->dbConn->getQueryBuilder();
221
+            $qb->update('share')
222
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
+                ->execute();
228
+
229
+            /*
230 230
 			 * Now update the permissions for all children that have not set it to 0
231 231
 			 */
232
-			$qb = $this->dbConn->getQueryBuilder();
233
-			$qb->update('share')
234
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
-				->execute();
238
-
239
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
-			$qb = $this->dbConn->getQueryBuilder();
241
-			$qb->update('share')
242
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
-				->set('share_with', $qb->createNamedParameter($share->getPassword()))
244
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
-				->set('token', $qb->createNamedParameter($share->getToken()))
250
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
-				->execute();
252
-		}
253
-
254
-		return $share;
255
-	}
256
-
257
-	/**
258
-	 * Get all children of this share
259
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
-	 *
261
-	 * @param \OCP\Share\IShare $parent
262
-	 * @return \OCP\Share\IShare[]
263
-	 */
264
-	public function getChildren(\OCP\Share\IShare $parent) {
265
-		$children = [];
266
-
267
-		$qb = $this->dbConn->getQueryBuilder();
268
-		$qb->select('*')
269
-			->from('share')
270
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
-			->andWhere(
272
-				$qb->expr()->in(
273
-					'share_type',
274
-					$qb->createNamedParameter([
275
-						\OCP\Share::SHARE_TYPE_USER,
276
-						\OCP\Share::SHARE_TYPE_GROUP,
277
-						\OCP\Share::SHARE_TYPE_LINK,
278
-					], IQueryBuilder::PARAM_INT_ARRAY)
279
-				)
280
-			)
281
-			->andWhere($qb->expr()->orX(
282
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
-			))
285
-			->orderBy('id');
286
-
287
-		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
289
-			$children[] = $this->createShare($data);
290
-		}
291
-		$cursor->closeCursor();
292
-
293
-		return $children;
294
-	}
295
-
296
-	/**
297
-	 * Delete a share
298
-	 *
299
-	 * @param \OCP\Share\IShare $share
300
-	 */
301
-	public function delete(\OCP\Share\IShare $share) {
302
-		$qb = $this->dbConn->getQueryBuilder();
303
-		$qb->delete('share')
304
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
-
306
-		/*
232
+            $qb = $this->dbConn->getQueryBuilder();
233
+            $qb->update('share')
234
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
+                ->execute();
238
+
239
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
+            $qb = $this->dbConn->getQueryBuilder();
241
+            $qb->update('share')
242
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
+                ->set('share_with', $qb->createNamedParameter($share->getPassword()))
244
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
+                ->set('token', $qb->createNamedParameter($share->getToken()))
250
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
+                ->execute();
252
+        }
253
+
254
+        return $share;
255
+    }
256
+
257
+    /**
258
+     * Get all children of this share
259
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
+     *
261
+     * @param \OCP\Share\IShare $parent
262
+     * @return \OCP\Share\IShare[]
263
+     */
264
+    public function getChildren(\OCP\Share\IShare $parent) {
265
+        $children = [];
266
+
267
+        $qb = $this->dbConn->getQueryBuilder();
268
+        $qb->select('*')
269
+            ->from('share')
270
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
+            ->andWhere(
272
+                $qb->expr()->in(
273
+                    'share_type',
274
+                    $qb->createNamedParameter([
275
+                        \OCP\Share::SHARE_TYPE_USER,
276
+                        \OCP\Share::SHARE_TYPE_GROUP,
277
+                        \OCP\Share::SHARE_TYPE_LINK,
278
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
279
+                )
280
+            )
281
+            ->andWhere($qb->expr()->orX(
282
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
+            ))
285
+            ->orderBy('id');
286
+
287
+        $cursor = $qb->execute();
288
+        while($data = $cursor->fetch()) {
289
+            $children[] = $this->createShare($data);
290
+        }
291
+        $cursor->closeCursor();
292
+
293
+        return $children;
294
+    }
295
+
296
+    /**
297
+     * Delete a share
298
+     *
299
+     * @param \OCP\Share\IShare $share
300
+     */
301
+    public function delete(\OCP\Share\IShare $share) {
302
+        $qb = $this->dbConn->getQueryBuilder();
303
+        $qb->delete('share')
304
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
+
306
+        /*
307 307
 		 * If the share is a group share delete all possible
308 308
 		 * user defined groups shares.
309 309
 		 */
310
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
-		}
313
-
314
-		$qb->execute();
315
-	}
316
-
317
-	/**
318
-	 * Unshare a share from the recipient. If this is a group share
319
-	 * this means we need a special entry in the share db.
320
-	 *
321
-	 * @param \OCP\Share\IShare $share
322
-	 * @param string $recipient UserId of recipient
323
-	 * @throws BackendError
324
-	 * @throws ProviderException
325
-	 */
326
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
-
329
-			$group = $this->groupManager->get($share->getSharedWith());
330
-			$user = $this->userManager->get($recipient);
331
-
332
-			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
-			}
335
-
336
-			if (!$group->inGroup($user)) {
337
-				throw new ProviderException('Recipient not in receiving group');
338
-			}
339
-
340
-			// Try to fetch user specific share
341
-			$qb = $this->dbConn->getQueryBuilder();
342
-			$stmt = $qb->select('*')
343
-				->from('share')
344
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
-				->andWhere($qb->expr()->orX(
348
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
-				))
351
-				->execute();
352
-
353
-			$data = $stmt->fetch();
354
-
355
-			/*
310
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
+        }
313
+
314
+        $qb->execute();
315
+    }
316
+
317
+    /**
318
+     * Unshare a share from the recipient. If this is a group share
319
+     * this means we need a special entry in the share db.
320
+     *
321
+     * @param \OCP\Share\IShare $share
322
+     * @param string $recipient UserId of recipient
323
+     * @throws BackendError
324
+     * @throws ProviderException
325
+     */
326
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
+
329
+            $group = $this->groupManager->get($share->getSharedWith());
330
+            $user = $this->userManager->get($recipient);
331
+
332
+            if (is_null($group)) {
333
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
+            }
335
+
336
+            if (!$group->inGroup($user)) {
337
+                throw new ProviderException('Recipient not in receiving group');
338
+            }
339
+
340
+            // Try to fetch user specific share
341
+            $qb = $this->dbConn->getQueryBuilder();
342
+            $stmt = $qb->select('*')
343
+                ->from('share')
344
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
+                ->andWhere($qb->expr()->orX(
348
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
+                ))
351
+                ->execute();
352
+
353
+            $data = $stmt->fetch();
354
+
355
+            /*
356 356
 			 * Check if there already is a user specific group share.
357 357
 			 * If there is update it (if required).
358 358
 			 */
359
-			if ($data === false) {
360
-				$qb = $this->dbConn->getQueryBuilder();
361
-
362
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
-
364
-				//Insert new share
365
-				$qb->insert('share')
366
-					->values([
367
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
-						'share_with' => $qb->createNamedParameter($recipient),
369
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
-						'parent' => $qb->createNamedParameter($share->getId()),
372
-						'item_type' => $qb->createNamedParameter($type),
373
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
376
-						'permissions' => $qb->createNamedParameter(0),
377
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
-					])->execute();
379
-
380
-			} else if ($data['permissions'] !== 0) {
381
-
382
-				// Update existing usergroup share
383
-				$qb = $this->dbConn->getQueryBuilder();
384
-				$qb->update('share')
385
-					->set('permissions', $qb->createNamedParameter(0))
386
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
-					->execute();
388
-			}
389
-
390
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
-
392
-			if ($share->getSharedWith() !== $recipient) {
393
-				throw new ProviderException('Recipient does not match');
394
-			}
395
-
396
-			// We can just delete user and link shares
397
-			$this->delete($share);
398
-		} else {
399
-			throw new ProviderException('Invalid shareType');
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @inheritdoc
405
-	 */
406
-	public function move(\OCP\Share\IShare $share, $recipient) {
407
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
-			// Just update the target
409
-			$qb = $this->dbConn->getQueryBuilder();
410
-			$qb->update('share')
411
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
-				->execute();
414
-
415
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
-
417
-			// Check if there is a usergroup share
418
-			$qb = $this->dbConn->getQueryBuilder();
419
-			$stmt = $qb->select('id')
420
-				->from('share')
421
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
-				->andWhere($qb->expr()->orX(
425
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
-				))
428
-				->setMaxResults(1)
429
-				->execute();
430
-
431
-			$data = $stmt->fetch();
432
-			$stmt->closeCursor();
433
-
434
-			if ($data === false) {
435
-				// No usergroup share yet. Create one.
436
-				$qb = $this->dbConn->getQueryBuilder();
437
-				$qb->insert('share')
438
-					->values([
439
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
-						'share_with' => $qb->createNamedParameter($recipient),
441
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
-						'parent' => $qb->createNamedParameter($share->getId()),
444
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
448
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
-					])->execute();
451
-			} else {
452
-				// Already a usergroup share. Update it.
453
-				$qb = $this->dbConn->getQueryBuilder();
454
-				$qb->update('share')
455
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
-					->execute();
458
-			}
459
-		}
460
-
461
-		return $share;
462
-	}
463
-
464
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
465
-		$qb = $this->dbConn->getQueryBuilder();
466
-		$qb->select('*')
467
-			->from('share', 's')
468
-			->andWhere($qb->expr()->orX(
469
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
-			));
472
-
473
-		$qb->andWhere($qb->expr()->orX(
474
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
-		));
478
-
479
-		/**
480
-		 * Reshares for this user are shares where they are the owner.
481
-		 */
482
-		if ($reshares === false) {
483
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
-		} else {
485
-			$qb->andWhere(
486
-				$qb->expr()->orX(
487
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
-				)
490
-			);
491
-		}
492
-
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
-
496
-		$qb->orderBy('id');
497
-
498
-		$cursor = $qb->execute();
499
-		$shares = [];
500
-		while ($data = $cursor->fetch()) {
501
-			$shares[$data['fileid']][] = $this->createShare($data);
502
-		}
503
-		$cursor->closeCursor();
504
-
505
-		return $shares;
506
-	}
507
-
508
-	/**
509
-	 * @inheritdoc
510
-	 */
511
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
-		$qb = $this->dbConn->getQueryBuilder();
513
-		$qb->select('*')
514
-			->from('share')
515
-			->andWhere($qb->expr()->orX(
516
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
-			));
519
-
520
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
-
522
-		/**
523
-		 * Reshares for this user are shares where they are the owner.
524
-		 */
525
-		if ($reshares === false) {
526
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
-		} else {
528
-			$qb->andWhere(
529
-				$qb->expr()->orX(
530
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
-				)
533
-			);
534
-		}
535
-
536
-		if ($node !== null) {
537
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
-		}
539
-
540
-		if ($limit !== -1) {
541
-			$qb->setMaxResults($limit);
542
-		}
543
-
544
-		$qb->setFirstResult($offset);
545
-		$qb->orderBy('id');
546
-
547
-		$cursor = $qb->execute();
548
-		$shares = [];
549
-		while($data = $cursor->fetch()) {
550
-			$shares[] = $this->createShare($data);
551
-		}
552
-		$cursor->closeCursor();
553
-
554
-		return $shares;
555
-	}
556
-
557
-	/**
558
-	 * @inheritdoc
559
-	 */
560
-	public function getShareById($id, $recipientId = null) {
561
-		$qb = $this->dbConn->getQueryBuilder();
562
-
563
-		$qb->select('*')
564
-			->from('share')
565
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
-			->andWhere(
567
-				$qb->expr()->in(
568
-					'share_type',
569
-					$qb->createNamedParameter([
570
-						\OCP\Share::SHARE_TYPE_USER,
571
-						\OCP\Share::SHARE_TYPE_GROUP,
572
-						\OCP\Share::SHARE_TYPE_LINK,
573
-					], IQueryBuilder::PARAM_INT_ARRAY)
574
-				)
575
-			)
576
-			->andWhere($qb->expr()->orX(
577
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
-			));
580
-
581
-		$cursor = $qb->execute();
582
-		$data = $cursor->fetch();
583
-		$cursor->closeCursor();
584
-
585
-		if ($data === false) {
586
-			throw new ShareNotFound();
587
-		}
588
-
589
-		try {
590
-			$share = $this->createShare($data);
591
-		} catch (InvalidShare $e) {
592
-			throw new ShareNotFound();
593
-		}
594
-
595
-		// If the recipient is set for a group share resolve to that user
596
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
598
-		}
599
-
600
-		return $share;
601
-	}
602
-
603
-	/**
604
-	 * Get shares for a given path
605
-	 *
606
-	 * @param \OCP\Files\Node $path
607
-	 * @return \OCP\Share\IShare[]
608
-	 */
609
-	public function getSharesByPath(Node $path) {
610
-		$qb = $this->dbConn->getQueryBuilder();
611
-
612
-		$cursor = $qb->select('*')
613
-			->from('share')
614
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
-			->andWhere(
616
-				$qb->expr()->orX(
617
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
-				)
620
-			)
621
-			->andWhere($qb->expr()->orX(
622
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
-			))
625
-			->execute();
626
-
627
-		$shares = [];
628
-		while($data = $cursor->fetch()) {
629
-			$shares[] = $this->createShare($data);
630
-		}
631
-		$cursor->closeCursor();
632
-
633
-		return $shares;
634
-	}
635
-
636
-	/**
637
-	 * Returns whether the given database result can be interpreted as
638
-	 * a share with accessible file (not trashed, not deleted)
639
-	 */
640
-	private function isAccessibleResult($data) {
641
-		// exclude shares leading to deleted file entries
642
-		if ($data['fileid'] === null) {
643
-			return false;
644
-		}
645
-
646
-		// exclude shares leading to trashbin on home storages
647
-		$pathSections = explode('/', $data['path'], 2);
648
-		// FIXME: would not detect rare md5'd home storage case properly
649
-		if ($pathSections[0] !== 'files' 
650
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
-			return false;
652
-		}
653
-		return true;
654
-	}
655
-
656
-	/**
657
-	 * @inheritdoc
658
-	 */
659
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
-		/** @var Share[] $shares */
661
-		$shares = [];
662
-
663
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
-			//Get shares directly with this user
665
-			$qb = $this->dbConn->getQueryBuilder();
666
-			$qb->select('s.*',
667
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
-			)
671
-				->selectAlias('st.id', 'storage_string_id')
672
-				->from('share', 's')
673
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
-
676
-			// Order by id
677
-			$qb->orderBy('s.id');
678
-
679
-			// Set limit and offset
680
-			if ($limit !== -1) {
681
-				$qb->setMaxResults($limit);
682
-			}
683
-			$qb->setFirstResult($offset);
684
-
685
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
-				->andWhere($qb->expr()->orX(
688
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
-				));
691
-
692
-			// Filter by node if provided
693
-			if ($node !== null) {
694
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
-			}
696
-
697
-			$cursor = $qb->execute();
698
-
699
-			while($data = $cursor->fetch()) {
700
-				if ($this->isAccessibleResult($data)) {
701
-					$shares[] = $this->createShare($data);
702
-				}
703
-			}
704
-			$cursor->closeCursor();
705
-
706
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
-			$user = $this->userManager->get($userId);
708
-			$allGroups = $this->groupManager->getUserGroups($user);
709
-
710
-			/** @var Share[] $shares2 */
711
-			$shares2 = [];
712
-
713
-			$start = 0;
714
-			while(true) {
715
-				$groups = array_slice($allGroups, $start, 100);
716
-				$start += 100;
717
-
718
-				if ($groups === []) {
719
-					break;
720
-				}
721
-
722
-				$qb = $this->dbConn->getQueryBuilder();
723
-				$qb->select('s.*',
724
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
-				)
728
-					->selectAlias('st.id', 'storage_string_id')
729
-					->from('share', 's')
730
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
-					->orderBy('s.id')
733
-					->setFirstResult(0);
734
-
735
-				if ($limit !== -1) {
736
-					$qb->setMaxResults($limit - count($shares));
737
-				}
738
-
739
-				// Filter by node if provided
740
-				if ($node !== null) {
741
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
-				}
743
-
744
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
-
746
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
-						$groups,
749
-						IQueryBuilder::PARAM_STR_ARRAY
750
-					)))
751
-					->andWhere($qb->expr()->orX(
752
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
-					));
755
-
756
-				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
758
-					if ($offset > 0) {
759
-						$offset--;
760
-						continue;
761
-					}
762
-
763
-					if ($this->isAccessibleResult($data)) {
764
-						$shares2[] = $this->createShare($data);
765
-					}
766
-				}
767
-				$cursor->closeCursor();
768
-			}
769
-
770
-			/*
359
+            if ($data === false) {
360
+                $qb = $this->dbConn->getQueryBuilder();
361
+
362
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
+
364
+                //Insert new share
365
+                $qb->insert('share')
366
+                    ->values([
367
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
+                        'share_with' => $qb->createNamedParameter($recipient),
369
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
+                        'parent' => $qb->createNamedParameter($share->getId()),
372
+                        'item_type' => $qb->createNamedParameter($type),
373
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
376
+                        'permissions' => $qb->createNamedParameter(0),
377
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
+                    ])->execute();
379
+
380
+            } else if ($data['permissions'] !== 0) {
381
+
382
+                // Update existing usergroup share
383
+                $qb = $this->dbConn->getQueryBuilder();
384
+                $qb->update('share')
385
+                    ->set('permissions', $qb->createNamedParameter(0))
386
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
+                    ->execute();
388
+            }
389
+
390
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
+
392
+            if ($share->getSharedWith() !== $recipient) {
393
+                throw new ProviderException('Recipient does not match');
394
+            }
395
+
396
+            // We can just delete user and link shares
397
+            $this->delete($share);
398
+        } else {
399
+            throw new ProviderException('Invalid shareType');
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @inheritdoc
405
+     */
406
+    public function move(\OCP\Share\IShare $share, $recipient) {
407
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
+            // Just update the target
409
+            $qb = $this->dbConn->getQueryBuilder();
410
+            $qb->update('share')
411
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
+                ->execute();
414
+
415
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
+
417
+            // Check if there is a usergroup share
418
+            $qb = $this->dbConn->getQueryBuilder();
419
+            $stmt = $qb->select('id')
420
+                ->from('share')
421
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
+                ->andWhere($qb->expr()->orX(
425
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
+                ))
428
+                ->setMaxResults(1)
429
+                ->execute();
430
+
431
+            $data = $stmt->fetch();
432
+            $stmt->closeCursor();
433
+
434
+            if ($data === false) {
435
+                // No usergroup share yet. Create one.
436
+                $qb = $this->dbConn->getQueryBuilder();
437
+                $qb->insert('share')
438
+                    ->values([
439
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
+                        'share_with' => $qb->createNamedParameter($recipient),
441
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
+                        'parent' => $qb->createNamedParameter($share->getId()),
444
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
448
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
+                    ])->execute();
451
+            } else {
452
+                // Already a usergroup share. Update it.
453
+                $qb = $this->dbConn->getQueryBuilder();
454
+                $qb->update('share')
455
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
+                    ->execute();
458
+            }
459
+        }
460
+
461
+        return $share;
462
+    }
463
+
464
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
465
+        $qb = $this->dbConn->getQueryBuilder();
466
+        $qb->select('*')
467
+            ->from('share', 's')
468
+            ->andWhere($qb->expr()->orX(
469
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
+            ));
472
+
473
+        $qb->andWhere($qb->expr()->orX(
474
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
+        ));
478
+
479
+        /**
480
+         * Reshares for this user are shares where they are the owner.
481
+         */
482
+        if ($reshares === false) {
483
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
+        } else {
485
+            $qb->andWhere(
486
+                $qb->expr()->orX(
487
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
+                )
490
+            );
491
+        }
492
+
493
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
+
496
+        $qb->orderBy('id');
497
+
498
+        $cursor = $qb->execute();
499
+        $shares = [];
500
+        while ($data = $cursor->fetch()) {
501
+            $shares[$data['fileid']][] = $this->createShare($data);
502
+        }
503
+        $cursor->closeCursor();
504
+
505
+        return $shares;
506
+    }
507
+
508
+    /**
509
+     * @inheritdoc
510
+     */
511
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
+        $qb = $this->dbConn->getQueryBuilder();
513
+        $qb->select('*')
514
+            ->from('share')
515
+            ->andWhere($qb->expr()->orX(
516
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
+            ));
519
+
520
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
+
522
+        /**
523
+         * Reshares for this user are shares where they are the owner.
524
+         */
525
+        if ($reshares === false) {
526
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
+        } else {
528
+            $qb->andWhere(
529
+                $qb->expr()->orX(
530
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
+                )
533
+            );
534
+        }
535
+
536
+        if ($node !== null) {
537
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
+        }
539
+
540
+        if ($limit !== -1) {
541
+            $qb->setMaxResults($limit);
542
+        }
543
+
544
+        $qb->setFirstResult($offset);
545
+        $qb->orderBy('id');
546
+
547
+        $cursor = $qb->execute();
548
+        $shares = [];
549
+        while($data = $cursor->fetch()) {
550
+            $shares[] = $this->createShare($data);
551
+        }
552
+        $cursor->closeCursor();
553
+
554
+        return $shares;
555
+    }
556
+
557
+    /**
558
+     * @inheritdoc
559
+     */
560
+    public function getShareById($id, $recipientId = null) {
561
+        $qb = $this->dbConn->getQueryBuilder();
562
+
563
+        $qb->select('*')
564
+            ->from('share')
565
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
+            ->andWhere(
567
+                $qb->expr()->in(
568
+                    'share_type',
569
+                    $qb->createNamedParameter([
570
+                        \OCP\Share::SHARE_TYPE_USER,
571
+                        \OCP\Share::SHARE_TYPE_GROUP,
572
+                        \OCP\Share::SHARE_TYPE_LINK,
573
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
574
+                )
575
+            )
576
+            ->andWhere($qb->expr()->orX(
577
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
+            ));
580
+
581
+        $cursor = $qb->execute();
582
+        $data = $cursor->fetch();
583
+        $cursor->closeCursor();
584
+
585
+        if ($data === false) {
586
+            throw new ShareNotFound();
587
+        }
588
+
589
+        try {
590
+            $share = $this->createShare($data);
591
+        } catch (InvalidShare $e) {
592
+            throw new ShareNotFound();
593
+        }
594
+
595
+        // If the recipient is set for a group share resolve to that user
596
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
598
+        }
599
+
600
+        return $share;
601
+    }
602
+
603
+    /**
604
+     * Get shares for a given path
605
+     *
606
+     * @param \OCP\Files\Node $path
607
+     * @return \OCP\Share\IShare[]
608
+     */
609
+    public function getSharesByPath(Node $path) {
610
+        $qb = $this->dbConn->getQueryBuilder();
611
+
612
+        $cursor = $qb->select('*')
613
+            ->from('share')
614
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
+            ->andWhere(
616
+                $qb->expr()->orX(
617
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
+                )
620
+            )
621
+            ->andWhere($qb->expr()->orX(
622
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
+            ))
625
+            ->execute();
626
+
627
+        $shares = [];
628
+        while($data = $cursor->fetch()) {
629
+            $shares[] = $this->createShare($data);
630
+        }
631
+        $cursor->closeCursor();
632
+
633
+        return $shares;
634
+    }
635
+
636
+    /**
637
+     * Returns whether the given database result can be interpreted as
638
+     * a share with accessible file (not trashed, not deleted)
639
+     */
640
+    private function isAccessibleResult($data) {
641
+        // exclude shares leading to deleted file entries
642
+        if ($data['fileid'] === null) {
643
+            return false;
644
+        }
645
+
646
+        // exclude shares leading to trashbin on home storages
647
+        $pathSections = explode('/', $data['path'], 2);
648
+        // FIXME: would not detect rare md5'd home storage case properly
649
+        if ($pathSections[0] !== 'files' 
650
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
+            return false;
652
+        }
653
+        return true;
654
+    }
655
+
656
+    /**
657
+     * @inheritdoc
658
+     */
659
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
+        /** @var Share[] $shares */
661
+        $shares = [];
662
+
663
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
+            //Get shares directly with this user
665
+            $qb = $this->dbConn->getQueryBuilder();
666
+            $qb->select('s.*',
667
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
+            )
671
+                ->selectAlias('st.id', 'storage_string_id')
672
+                ->from('share', 's')
673
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
+
676
+            // Order by id
677
+            $qb->orderBy('s.id');
678
+
679
+            // Set limit and offset
680
+            if ($limit !== -1) {
681
+                $qb->setMaxResults($limit);
682
+            }
683
+            $qb->setFirstResult($offset);
684
+
685
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
+                ->andWhere($qb->expr()->orX(
688
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
+                ));
691
+
692
+            // Filter by node if provided
693
+            if ($node !== null) {
694
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
+            }
696
+
697
+            $cursor = $qb->execute();
698
+
699
+            while($data = $cursor->fetch()) {
700
+                if ($this->isAccessibleResult($data)) {
701
+                    $shares[] = $this->createShare($data);
702
+                }
703
+            }
704
+            $cursor->closeCursor();
705
+
706
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
+            $user = $this->userManager->get($userId);
708
+            $allGroups = $this->groupManager->getUserGroups($user);
709
+
710
+            /** @var Share[] $shares2 */
711
+            $shares2 = [];
712
+
713
+            $start = 0;
714
+            while(true) {
715
+                $groups = array_slice($allGroups, $start, 100);
716
+                $start += 100;
717
+
718
+                if ($groups === []) {
719
+                    break;
720
+                }
721
+
722
+                $qb = $this->dbConn->getQueryBuilder();
723
+                $qb->select('s.*',
724
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
+                )
728
+                    ->selectAlias('st.id', 'storage_string_id')
729
+                    ->from('share', 's')
730
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
+                    ->orderBy('s.id')
733
+                    ->setFirstResult(0);
734
+
735
+                if ($limit !== -1) {
736
+                    $qb->setMaxResults($limit - count($shares));
737
+                }
738
+
739
+                // Filter by node if provided
740
+                if ($node !== null) {
741
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
+                }
743
+
744
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
+
746
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
+                        $groups,
749
+                        IQueryBuilder::PARAM_STR_ARRAY
750
+                    )))
751
+                    ->andWhere($qb->expr()->orX(
752
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
+                    ));
755
+
756
+                $cursor = $qb->execute();
757
+                while($data = $cursor->fetch()) {
758
+                    if ($offset > 0) {
759
+                        $offset--;
760
+                        continue;
761
+                    }
762
+
763
+                    if ($this->isAccessibleResult($data)) {
764
+                        $shares2[] = $this->createShare($data);
765
+                    }
766
+                }
767
+                $cursor->closeCursor();
768
+            }
769
+
770
+            /*
771 771
  			 * Resolve all group shares to user specific shares
772 772
  			 */
773
-			$shares = $this->resolveGroupShares($shares2, $userId);
774
-		} else {
775
-			throw new BackendError('Invalid backend');
776
-		}
777
-
778
-
779
-		return $shares;
780
-	}
781
-
782
-	/**
783
-	 * Get a share by token
784
-	 *
785
-	 * @param string $token
786
-	 * @return \OCP\Share\IShare
787
-	 * @throws ShareNotFound
788
-	 */
789
-	public function getShareByToken($token) {
790
-		$qb = $this->dbConn->getQueryBuilder();
791
-
792
-		$cursor = $qb->select('*')
793
-			->from('share')
794
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
-			->andWhere($qb->expr()->orX(
797
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
-			))
800
-			->execute();
801
-
802
-		$data = $cursor->fetch();
803
-
804
-		if ($data === false) {
805
-			throw new ShareNotFound();
806
-		}
807
-
808
-		try {
809
-			$share = $this->createShare($data);
810
-		} catch (InvalidShare $e) {
811
-			throw new ShareNotFound();
812
-		}
813
-
814
-		return $share;
815
-	}
816
-
817
-	/**
818
-	 * Create a share object from an database row
819
-	 *
820
-	 * @param mixed[] $data
821
-	 * @return \OCP\Share\IShare
822
-	 * @throws InvalidShare
823
-	 */
824
-	private function createShare($data) {
825
-		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
829
-			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
831
-
832
-		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
834
-		$share->setShareTime($shareTime);
835
-
836
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
-			$share->setSharedWith($data['share_with']);
838
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
-			$share->setSharedWith($data['share_with']);
840
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
-			$share->setPassword($data['share_with']);
842
-			$share->setToken($data['token']);
843
-		}
844
-
845
-		$share->setSharedBy($data['uid_initiator']);
846
-		$share->setShareOwner($data['uid_owner']);
847
-
848
-		$share->setNodeId((int)$data['file_source']);
849
-		$share->setNodeType($data['item_type']);
850
-
851
-		if ($data['expiration'] !== null) {
852
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
-			$share->setExpirationDate($expiration);
854
-		}
855
-
856
-		if (isset($data['f_permissions'])) {
857
-			$entryData = $data;
858
-			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
860
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
-				\OC::$server->getMimeTypeLoader()));
862
-		}
863
-
864
-		$share->setProviderId($this->identifier());
865
-
866
-		return $share;
867
-	}
868
-
869
-	/**
870
-	 * @param Share[] $shares
871
-	 * @param $userId
872
-	 * @return Share[] The updates shares if no update is found for a share return the original
873
-	 */
874
-	private function resolveGroupShares($shares, $userId) {
875
-		$result = [];
876
-
877
-		$start = 0;
878
-		while(true) {
879
-			/** @var Share[] $shareSlice */
880
-			$shareSlice = array_slice($shares, $start, 100);
881
-			$start += 100;
882
-
883
-			if ($shareSlice === []) {
884
-				break;
885
-			}
886
-
887
-			/** @var int[] $ids */
888
-			$ids = [];
889
-			/** @var Share[] $shareMap */
890
-			$shareMap = [];
891
-
892
-			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
894
-				$shareMap[$share->getId()] = $share;
895
-			}
896
-
897
-			$qb = $this->dbConn->getQueryBuilder();
898
-
899
-			$query = $qb->select('*')
900
-				->from('share')
901
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
-				->andWhere($qb->expr()->orX(
904
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
-				));
907
-
908
-			$stmt = $query->execute();
909
-
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
913
-			}
914
-
915
-			$stmt->closeCursor();
916
-
917
-			foreach ($shareMap as $share) {
918
-				$result[] = $share;
919
-			}
920
-		}
921
-
922
-		return $result;
923
-	}
924
-
925
-	/**
926
-	 * A user is deleted from the system
927
-	 * So clean up the relevant shares.
928
-	 *
929
-	 * @param string $uid
930
-	 * @param int $shareType
931
-	 */
932
-	public function userDeleted($uid, $shareType) {
933
-		$qb = $this->dbConn->getQueryBuilder();
934
-
935
-		$qb->delete('share');
936
-
937
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
-			/*
773
+            $shares = $this->resolveGroupShares($shares2, $userId);
774
+        } else {
775
+            throw new BackendError('Invalid backend');
776
+        }
777
+
778
+
779
+        return $shares;
780
+    }
781
+
782
+    /**
783
+     * Get a share by token
784
+     *
785
+     * @param string $token
786
+     * @return \OCP\Share\IShare
787
+     * @throws ShareNotFound
788
+     */
789
+    public function getShareByToken($token) {
790
+        $qb = $this->dbConn->getQueryBuilder();
791
+
792
+        $cursor = $qb->select('*')
793
+            ->from('share')
794
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
+            ->andWhere($qb->expr()->orX(
797
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
+            ))
800
+            ->execute();
801
+
802
+        $data = $cursor->fetch();
803
+
804
+        if ($data === false) {
805
+            throw new ShareNotFound();
806
+        }
807
+
808
+        try {
809
+            $share = $this->createShare($data);
810
+        } catch (InvalidShare $e) {
811
+            throw new ShareNotFound();
812
+        }
813
+
814
+        return $share;
815
+    }
816
+
817
+    /**
818
+     * Create a share object from an database row
819
+     *
820
+     * @param mixed[] $data
821
+     * @return \OCP\Share\IShare
822
+     * @throws InvalidShare
823
+     */
824
+    private function createShare($data) {
825
+        $share = new Share($this->rootFolder, $this->userManager);
826
+        $share->setId((int)$data['id'])
827
+            ->setShareType((int)$data['share_type'])
828
+            ->setPermissions((int)$data['permissions'])
829
+            ->setTarget($data['file_target'])
830
+            ->setMailSend((bool)$data['mail_send']);
831
+
832
+        $shareTime = new \DateTime();
833
+        $shareTime->setTimestamp((int)$data['stime']);
834
+        $share->setShareTime($shareTime);
835
+
836
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
+            $share->setSharedWith($data['share_with']);
838
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
+            $share->setSharedWith($data['share_with']);
840
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
+            $share->setPassword($data['share_with']);
842
+            $share->setToken($data['token']);
843
+        }
844
+
845
+        $share->setSharedBy($data['uid_initiator']);
846
+        $share->setShareOwner($data['uid_owner']);
847
+
848
+        $share->setNodeId((int)$data['file_source']);
849
+        $share->setNodeType($data['item_type']);
850
+
851
+        if ($data['expiration'] !== null) {
852
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
+            $share->setExpirationDate($expiration);
854
+        }
855
+
856
+        if (isset($data['f_permissions'])) {
857
+            $entryData = $data;
858
+            $entryData['permissions'] = $entryData['f_permissions'];
859
+            $entryData['parent'] = $entryData['f_parent'];;
860
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
+                \OC::$server->getMimeTypeLoader()));
862
+        }
863
+
864
+        $share->setProviderId($this->identifier());
865
+
866
+        return $share;
867
+    }
868
+
869
+    /**
870
+     * @param Share[] $shares
871
+     * @param $userId
872
+     * @return Share[] The updates shares if no update is found for a share return the original
873
+     */
874
+    private function resolveGroupShares($shares, $userId) {
875
+        $result = [];
876
+
877
+        $start = 0;
878
+        while(true) {
879
+            /** @var Share[] $shareSlice */
880
+            $shareSlice = array_slice($shares, $start, 100);
881
+            $start += 100;
882
+
883
+            if ($shareSlice === []) {
884
+                break;
885
+            }
886
+
887
+            /** @var int[] $ids */
888
+            $ids = [];
889
+            /** @var Share[] $shareMap */
890
+            $shareMap = [];
891
+
892
+            foreach ($shareSlice as $share) {
893
+                $ids[] = (int)$share->getId();
894
+                $shareMap[$share->getId()] = $share;
895
+            }
896
+
897
+            $qb = $this->dbConn->getQueryBuilder();
898
+
899
+            $query = $qb->select('*')
900
+                ->from('share')
901
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
+                ->andWhere($qb->expr()->orX(
904
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
+                ));
907
+
908
+            $stmt = $query->execute();
909
+
910
+            while($data = $stmt->fetch()) {
911
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
913
+            }
914
+
915
+            $stmt->closeCursor();
916
+
917
+            foreach ($shareMap as $share) {
918
+                $result[] = $share;
919
+            }
920
+        }
921
+
922
+        return $result;
923
+    }
924
+
925
+    /**
926
+     * A user is deleted from the system
927
+     * So clean up the relevant shares.
928
+     *
929
+     * @param string $uid
930
+     * @param int $shareType
931
+     */
932
+    public function userDeleted($uid, $shareType) {
933
+        $qb = $this->dbConn->getQueryBuilder();
934
+
935
+        $qb->delete('share');
936
+
937
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
+            /*
939 939
 			 * Delete all user shares that are owned by this user
940 940
 			 * or that are received by this user
941 941
 			 */
942 942
 
943
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
943
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
944 944
 
945
-			$qb->andWhere(
946
-				$qb->expr()->orX(
947
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
-				)
950
-			);
951
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
-			/*
945
+            $qb->andWhere(
946
+                $qb->expr()->orX(
947
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
+                )
950
+            );
951
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
+            /*
953 953
 			 * Delete all group shares that are owned by this user
954 954
 			 * Or special user group shares that are received by this user
955 955
 			 */
956
-			$qb->where(
957
-				$qb->expr()->andX(
958
-					$qb->expr()->orX(
959
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
-					),
962
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
-				)
964
-			);
965
-
966
-			$qb->orWhere(
967
-				$qb->expr()->andX(
968
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
-				)
971
-			);
972
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
-			/*
956
+            $qb->where(
957
+                $qb->expr()->andX(
958
+                    $qb->expr()->orX(
959
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
+                    ),
962
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
+                )
964
+            );
965
+
966
+            $qb->orWhere(
967
+                $qb->expr()->andX(
968
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
+                )
971
+            );
972
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
+            /*
974 974
 			 * Delete all link shares owned by this user.
975 975
 			 * And all link shares initiated by this user (until #22327 is in)
976 976
 			 */
977
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
-
979
-			$qb->andWhere(
980
-				$qb->expr()->orX(
981
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
-				)
984
-			);
985
-		}
986
-
987
-		$qb->execute();
988
-	}
989
-
990
-	/**
991
-	 * Delete all shares received by this group. As well as any custom group
992
-	 * shares for group members.
993
-	 *
994
-	 * @param string $gid
995
-	 */
996
-	public function groupDeleted($gid) {
997
-		/*
977
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
+
979
+            $qb->andWhere(
980
+                $qb->expr()->orX(
981
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
+                )
984
+            );
985
+        }
986
+
987
+        $qb->execute();
988
+    }
989
+
990
+    /**
991
+     * Delete all shares received by this group. As well as any custom group
992
+     * shares for group members.
993
+     *
994
+     * @param string $gid
995
+     */
996
+    public function groupDeleted($gid) {
997
+        /*
998 998
 		 * First delete all custom group shares for group members
999 999
 		 */
1000
-		$qb = $this->dbConn->getQueryBuilder();
1001
-		$qb->select('id')
1002
-			->from('share')
1003
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
-
1006
-		$cursor = $qb->execute();
1007
-		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1010
-		}
1011
-		$cursor->closeCursor();
1012
-
1013
-		if (!empty($ids)) {
1014
-			$chunks = array_chunk($ids, 100);
1015
-			foreach ($chunks as $chunk) {
1016
-				$qb->delete('share')
1017
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
-				$qb->execute();
1020
-			}
1021
-		}
1022
-
1023
-		/*
1000
+        $qb = $this->dbConn->getQueryBuilder();
1001
+        $qb->select('id')
1002
+            ->from('share')
1003
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
+
1006
+        $cursor = $qb->execute();
1007
+        $ids = [];
1008
+        while($row = $cursor->fetch()) {
1009
+            $ids[] = (int)$row['id'];
1010
+        }
1011
+        $cursor->closeCursor();
1012
+
1013
+        if (!empty($ids)) {
1014
+            $chunks = array_chunk($ids, 100);
1015
+            foreach ($chunks as $chunk) {
1016
+                $qb->delete('share')
1017
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
+                $qb->execute();
1020
+            }
1021
+        }
1022
+
1023
+        /*
1024 1024
 		 * Now delete all the group shares
1025 1025
 		 */
1026
-		$qb = $this->dbConn->getQueryBuilder();
1027
-		$qb->delete('share')
1028
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
-		$qb->execute();
1031
-	}
1032
-
1033
-	/**
1034
-	 * Delete custom group shares to this group for this user
1035
-	 *
1036
-	 * @param string $uid
1037
-	 * @param string $gid
1038
-	 */
1039
-	public function userDeletedFromGroup($uid, $gid) {
1040
-		/*
1026
+        $qb = $this->dbConn->getQueryBuilder();
1027
+        $qb->delete('share')
1028
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
+        $qb->execute();
1031
+    }
1032
+
1033
+    /**
1034
+     * Delete custom group shares to this group for this user
1035
+     *
1036
+     * @param string $uid
1037
+     * @param string $gid
1038
+     */
1039
+    public function userDeletedFromGroup($uid, $gid) {
1040
+        /*
1041 1041
 		 * Get all group shares
1042 1042
 		 */
1043
-		$qb = $this->dbConn->getQueryBuilder();
1044
-		$qb->select('id')
1045
-			->from('share')
1046
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
-
1049
-		$cursor = $qb->execute();
1050
-		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1053
-		}
1054
-		$cursor->closeCursor();
1055
-
1056
-		if (!empty($ids)) {
1057
-			$chunks = array_chunk($ids, 100);
1058
-			foreach ($chunks as $chunk) {
1059
-				/*
1043
+        $qb = $this->dbConn->getQueryBuilder();
1044
+        $qb->select('id')
1045
+            ->from('share')
1046
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
+
1049
+        $cursor = $qb->execute();
1050
+        $ids = [];
1051
+        while($row = $cursor->fetch()) {
1052
+            $ids[] = (int)$row['id'];
1053
+        }
1054
+        $cursor->closeCursor();
1055
+
1056
+        if (!empty($ids)) {
1057
+            $chunks = array_chunk($ids, 100);
1058
+            foreach ($chunks as $chunk) {
1059
+                /*
1060 1060
 				 * Delete all special shares wit this users for the found group shares
1061 1061
 				 */
1062
-				$qb->delete('share')
1063
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
-				$qb->execute();
1067
-			}
1068
-		}
1069
-	}
1062
+                $qb->delete('share')
1063
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
+                $qb->execute();
1067
+            }
1068
+        }
1069
+    }
1070 1070
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 			->orderBy('id');
286 286
 
287 287
 		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
288
+		while ($data = $cursor->fetch()) {
289 289
 			$children[] = $this->createShare($data);
290 290
 		}
291 291
 		$cursor->closeCursor();
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 			$user = $this->userManager->get($recipient);
331 331
 
332 332
 			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
333
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
334 334
 			}
335 335
 
336 336
 			if (!$group->inGroup($user)) {
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 			);
491 491
 		}
492 492
 
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
493
+		$qb->innerJoin('s', 'filecache', 'f', 's.file_source = f.fileid');
494 494
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495 495
 
496 496
 		$qb->orderBy('id');
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 
547 547
 		$cursor = $qb->execute();
548 548
 		$shares = [];
549
-		while($data = $cursor->fetch()) {
549
+		while ($data = $cursor->fetch()) {
550 550
 			$shares[] = $this->createShare($data);
551 551
 		}
552 552
 		$cursor->closeCursor();
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 			->execute();
626 626
 
627 627
 		$shares = [];
628
-		while($data = $cursor->fetch()) {
628
+		while ($data = $cursor->fetch()) {
629 629
 			$shares[] = $this->createShare($data);
630 630
 		}
631 631
 		$cursor->closeCursor();
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 
697 697
 			$cursor = $qb->execute();
698 698
 
699
-			while($data = $cursor->fetch()) {
699
+			while ($data = $cursor->fetch()) {
700 700
 				if ($this->isAccessibleResult($data)) {
701 701
 					$shares[] = $this->createShare($data);
702 702
 				}
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 			$shares2 = [];
712 712
 
713 713
 			$start = 0;
714
-			while(true) {
714
+			while (true) {
715 715
 				$groups = array_slice($allGroups, $start, 100);
716 716
 				$start += 100;
717 717
 
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 					));
755 755
 
756 756
 				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
757
+				while ($data = $cursor->fetch()) {
758 758
 					if ($offset > 0) {
759 759
 						$offset--;
760 760
 						continue;
@@ -823,14 +823,14 @@  discard block
 block discarded – undo
823 823
 	 */
824 824
 	private function createShare($data) {
825 825
 		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
826
+		$share->setId((int) $data['id'])
827
+			->setShareType((int) $data['share_type'])
828
+			->setPermissions((int) $data['permissions'])
829 829
 			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
830
+			->setMailSend((bool) $data['mail_send']);
831 831
 
832 832
 		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
833
+		$shareTime->setTimestamp((int) $data['stime']);
834 834
 		$share->setShareTime($shareTime);
835 835
 
836 836
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 		$share->setSharedBy($data['uid_initiator']);
846 846
 		$share->setShareOwner($data['uid_owner']);
847 847
 
848
-		$share->setNodeId((int)$data['file_source']);
848
+		$share->setNodeId((int) $data['file_source']);
849 849
 		$share->setNodeType($data['item_type']);
850 850
 
851 851
 		if ($data['expiration'] !== null) {
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 		if (isset($data['f_permissions'])) {
857 857
 			$entryData = $data;
858 858
 			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
859
+			$entryData['parent'] = $entryData['f_parent']; ;
860 860
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861 861
 				\OC::$server->getMimeTypeLoader()));
862 862
 		}
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 		$result = [];
876 876
 
877 877
 		$start = 0;
878
-		while(true) {
878
+		while (true) {
879 879
 			/** @var Share[] $shareSlice */
880 880
 			$shareSlice = array_slice($shares, $start, 100);
881 881
 			$start += 100;
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 			$shareMap = [];
891 891
 
892 892
 			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
893
+				$ids[] = (int) $share->getId();
894 894
 				$shareMap[$share->getId()] = $share;
895 895
 			}
896 896
 
@@ -907,8 +907,8 @@  discard block
 block discarded – undo
907 907
 
908 908
 			$stmt = $query->execute();
909 909
 
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
910
+			while ($data = $stmt->fetch()) {
911
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
912 912
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
913 913
 			}
914 914
 
@@ -1005,8 +1005,8 @@  discard block
 block discarded – undo
1005 1005
 
1006 1006
 		$cursor = $qb->execute();
1007 1007
 		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1008
+		while ($row = $cursor->fetch()) {
1009
+			$ids[] = (int) $row['id'];
1010 1010
 		}
1011 1011
 		$cursor->closeCursor();
1012 1012
 
@@ -1048,8 +1048,8 @@  discard block
 block discarded – undo
1048 1048
 
1049 1049
 		$cursor = $qb->execute();
1050 1050
 		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1051
+		while ($row = $cursor->fetch()) {
1052
+			$ids[] = (int) $row['id'];
1053 1053
 		}
1054 1054
 		$cursor->closeCursor();
1055 1055
 
Please login to merge, or discard this patch.