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