Completed
Pull Request — master (#4303)
by Björn
23:11 queued 10:06
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.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131 131
 		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132 132
 
133
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
133
+		$this->registerService(\OCP\IPreview::class, function(Server $c) {
134 134
 			return new PreviewManager(
135 135
 				$c->getConfig(),
136 136
 				$c->getRootFolder(),
@@ -141,13 +141,13 @@  discard block
 block discarded – undo
141 141
 		});
142 142
 		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
143 143
 
144
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
144
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
145 145
 			return new \OC\Preview\Watcher(
146 146
 				$c->getAppDataDir('preview')
147 147
 			);
148 148
 		});
149 149
 
150
-		$this->registerService('EncryptionManager', function (Server $c) {
150
+		$this->registerService('EncryptionManager', function(Server $c) {
151 151
 			$view = new View();
152 152
 			$util = new Encryption\Util(
153 153
 				$view,
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 			);
166 166
 		});
167 167
 
168
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
168
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
169 169
 			$util = new Encryption\Util(
170 170
 				new View(),
171 171
 				$c->getUserManager(),
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 			return new Encryption\File($util);
176 176
 		});
177 177
 
178
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
178
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
179 179
 			$view = new View();
180 180
 			$util = new Encryption\Util(
181 181
 				$view,
@@ -186,32 +186,32 @@  discard block
 block discarded – undo
186 186
 
187 187
 			return new Encryption\Keys\Storage($view, $util);
188 188
 		});
189
-		$this->registerService('TagMapper', function (Server $c) {
189
+		$this->registerService('TagMapper', function(Server $c) {
190 190
 			return new TagMapper($c->getDatabaseConnection());
191 191
 		});
192 192
 
193
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
193
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
194 194
 			$tagMapper = $c->query('TagMapper');
195 195
 			return new TagManager($tagMapper, $c->getUserSession());
196 196
 		});
197 197
 		$this->registerAlias('TagManager', \OCP\ITagManager::class);
198 198
 
199
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
199
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
200 200
 			$config = $c->getConfig();
201 201
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202 202
 			/** @var \OC\SystemTag\ManagerFactory $factory */
203 203
 			$factory = new $factoryClass($this);
204 204
 			return $factory;
205 205
 		});
206
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
206
+		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function(Server $c) {
207 207
 			return $c->query('SystemTagManagerFactory')->getManager();
208 208
 		});
209 209
 		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210 210
 
211
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
211
+		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function(Server $c) {
212 212
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
213 213
 		});
214
-		$this->registerService('RootFolder', function (Server $c) {
214
+		$this->registerService('RootFolder', function(Server $c) {
215 215
 			$manager = \OC\Files\Filesystem::getMountManager(null);
216 216
 			$view = new View();
217 217
 			$root = new Root(
@@ -239,30 +239,30 @@  discard block
 block discarded – undo
239 239
 		});
240 240
 		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241 241
 
242
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
242
+		$this->registerService(\OCP\IUserManager::class, function(Server $c) {
243 243
 			$config = $c->getConfig();
244 244
 			return new \OC\User\Manager($config);
245 245
 		});
246 246
 		$this->registerAlias('UserManager', \OCP\IUserManager::class);
247 247
 
248
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
248
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
249 249
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
250
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
251 251
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252 252
 			});
253
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
253
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
254 254
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255 255
 			});
256
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
256
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
257 257
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258 258
 			});
259
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
259
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
260 260
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261 261
 			});
262
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
262
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
263 263
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264 264
 			});
265
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
265
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
266 266
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267 267
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268 268
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -282,11 +282,11 @@  discard block
 block discarded – undo
282 282
 			return new Store($session, $logger, $tokenProvider);
283 283
 		});
284 284
 		$this->registerAlias(IStore::class, Store::class);
285
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
285
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
286 286
 			$dbConnection = $c->getDatabaseConnection();
287 287
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
288 288
 		});
289
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
289
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
290 290
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291 291
 			$crypto = $c->getCrypto();
292 292
 			$config = $c->getConfig();
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 		});
297 297
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298 298
 
299
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
299
+		$this->registerService(\OCP\IUserSession::class, function(Server $c) {
300 300
 			$manager = $c->getUserManager();
301 301
 			$session = new \OC\Session\Memory('');
302 302
 			$timeFactory = new TimeFactory();
@@ -309,40 +309,40 @@  discard block
 block discarded – undo
309 309
 			}
310 310
 
311 311
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
312
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
313 313
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314 314
 			});
315
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
315
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
316 316
 				/** @var $user \OC\User\User */
317 317
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318 318
 			});
319
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
319
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
320 320
 				/** @var $user \OC\User\User */
321 321
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322 322
 			});
323
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
323
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
324 324
 				/** @var $user \OC\User\User */
325 325
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326 326
 			});
327
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
327
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
328 328
 				/** @var $user \OC\User\User */
329 329
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330 330
 			});
331
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
331
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
332 332
 				/** @var $user \OC\User\User */
333 333
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334 334
 			});
335
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
335
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
336 336
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337 337
 			});
338
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
338
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
339 339
 				/** @var $user \OC\User\User */
340 340
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341 341
 			});
342
-			$userSession->listen('\OC\User', 'logout', function () {
342
+			$userSession->listen('\OC\User', 'logout', function() {
343 343
 				\OC_Hook::emit('OC_User', 'logout', array());
344 344
 			});
345
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
345
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
346 346
 				/** @var $user \OC\User\User */
347 347
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348 348
 			});
@@ -350,14 +350,14 @@  discard block
 block discarded – undo
350 350
 		});
351 351
 		$this->registerAlias('UserSession', \OCP\IUserSession::class);
352 352
 
353
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
353
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
354 354
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355 355
 		});
356 356
 
357 357
 		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358 358
 		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359 359
 
360
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
360
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
361 361
 			return new \OC\AllConfig(
362 362
 				$c->getSystemConfig()
363 363
 			);
@@ -365,17 +365,17 @@  discard block
 block discarded – undo
365 365
 		$this->registerAlias('AllConfig', \OC\AllConfig::class);
366 366
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367 367
 
368
-		$this->registerService('SystemConfig', function ($c) use ($config) {
368
+		$this->registerService('SystemConfig', function($c) use ($config) {
369 369
 			return new \OC\SystemConfig($config);
370 370
 		});
371 371
 
372
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
372
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
373 373
 			return new \OC\AppConfig($c->getDatabaseConnection());
374 374
 		});
375 375
 		$this->registerAlias('AppConfig', \OC\AppConfig::class);
376 376
 		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377 377
 
378
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
378
+		$this->registerService(\OCP\L10N\IFactory::class, function(Server $c) {
379 379
 			return new \OC\L10N\Factory(
380 380
 				$c->getConfig(),
381 381
 				$c->getRequest(),
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 		});
386 386
 		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387 387
 
388
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
388
+		$this->registerService(\OCP\IURLGenerator::class, function(Server $c) {
389 389
 			$config = $c->getConfig();
390 390
 			$cacheFactory = $c->getMemCacheFactory();
391 391
 			return new \OC\URLGenerator(
@@ -395,10 +395,10 @@  discard block
 block discarded – undo
395 395
 		});
396 396
 		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397 397
 
398
-		$this->registerService('AppHelper', function ($c) {
398
+		$this->registerService('AppHelper', function($c) {
399 399
 			return new \OC\AppHelper();
400 400
 		});
401
-		$this->registerService('AppFetcher', function ($c) {
401
+		$this->registerService('AppFetcher', function($c) {
402 402
 			return new AppFetcher(
403 403
 				$this->getAppDataDir('appstore'),
404 404
 				$this->getHTTPClientService(),
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 				$this->getConfig()
407 407
 			);
408 408
 		});
409
-		$this->registerService('CategoryFetcher', function ($c) {
409
+		$this->registerService('CategoryFetcher', function($c) {
410 410
 			return new CategoryFetcher(
411 411
 				$this->getAppDataDir('appstore'),
412 412
 				$this->getHTTPClientService(),
@@ -415,21 +415,21 @@  discard block
 block discarded – undo
415 415
 			);
416 416
 		});
417 417
 
418
-		$this->registerService(\OCP\ICache::class, function ($c) {
418
+		$this->registerService(\OCP\ICache::class, function($c) {
419 419
 			return new Cache\File();
420 420
 		});
421 421
 		$this->registerAlias('UserCache', \OCP\ICache::class);
422 422
 
423
-		$this->registerService(Factory::class, function (Server $c) {
423
+		$this->registerService(Factory::class, function(Server $c) {
424 424
 			$config = $c->getConfig();
425 425
 
426 426
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427 427
 				$v = \OC_App::getAppVersions();
428
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
428
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
429 429
 				$version = implode(',', $v);
430 430
 				$instanceId = \OC_Util::getInstanceId();
431 431
 				$path = \OC::$SERVERROOT;
432
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
432
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
433 433
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434 434
 					$config->getSystemValue('memcache.local', null),
435 435
 					$config->getSystemValue('memcache.distributed', null),
@@ -446,12 +446,12 @@  discard block
 block discarded – undo
446 446
 		$this->registerAlias('MemCacheFactory', Factory::class);
447 447
 		$this->registerAlias(ICacheFactory::class, Factory::class);
448 448
 
449
-		$this->registerService('RedisFactory', function (Server $c) {
449
+		$this->registerService('RedisFactory', function(Server $c) {
450 450
 			$systemConfig = $c->getSystemConfig();
451 451
 			return new RedisFactory($systemConfig);
452 452
 		});
453 453
 
454
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
454
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
455 455
 			return new \OC\Activity\Manager(
456 456
 				$c->getRequest(),
457 457
 				$c->getUserSession(),
@@ -461,14 +461,14 @@  discard block
 block discarded – undo
461 461
 		});
462 462
 		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463 463
 
464
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
464
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
465 465
 			return new \OC\Activity\EventMerger(
466 466
 				$c->getL10N('lib')
467 467
 			);
468 468
 		});
469 469
 		$this->registerAlias(IValidator::class, Validator::class);
470 470
 
471
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
471
+		$this->registerService(\OCP\IAvatarManager::class, function(Server $c) {
472 472
 			return new AvatarManager(
473 473
 				$c->getUserManager(),
474 474
 				$c->getAppDataDir('avatar'),
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 		});
480 480
 		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481 481
 
482
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
482
+		$this->registerService(\OCP\ILogger::class, function(Server $c) {
483 483
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484 484
 			$logger = Log::getLogClass($logType);
485 485
 			call_user_func(array($logger, 'init'));
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 		});
489 489
 		$this->registerAlias('Logger', \OCP\ILogger::class);
490 490
 
491
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
491
+		$this->registerService(\OCP\BackgroundJob\IJobList::class, function(Server $c) {
492 492
 			$config = $c->getConfig();
493 493
 			return new \OC\BackgroundJob\JobList(
494 494
 				$c->getDatabaseConnection(),
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 		});
499 499
 		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500 500
 
501
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
501
+		$this->registerService(\OCP\Route\IRouter::class, function(Server $c) {
502 502
 			$cacheFactory = $c->getMemCacheFactory();
503 503
 			$logger = $c->getLogger();
504 504
 			if ($cacheFactory->isAvailable()) {
@@ -510,32 +510,32 @@  discard block
 block discarded – undo
510 510
 		});
511 511
 		$this->registerAlias('Router', \OCP\Route\IRouter::class);
512 512
 
513
-		$this->registerService(\OCP\ISearch::class, function ($c) {
513
+		$this->registerService(\OCP\ISearch::class, function($c) {
514 514
 			return new Search();
515 515
 		});
516 516
 		$this->registerAlias('Search', \OCP\ISearch::class);
517 517
 
518
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
518
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
519 519
 			return new SecureRandom();
520 520
 		});
521 521
 		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522 522
 
523
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
523
+		$this->registerService(\OCP\Security\ICrypto::class, function(Server $c) {
524 524
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
525 525
 		});
526 526
 		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527 527
 
528
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
528
+		$this->registerService(\OCP\Security\IHasher::class, function(Server $c) {
529 529
 			return new Hasher($c->getConfig());
530 530
 		});
531 531
 		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532 532
 
533
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
533
+		$this->registerService(\OCP\Security\ICredentialsManager::class, function(Server $c) {
534 534
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535 535
 		});
536 536
 		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537 537
 
538
-		$this->registerService(IDBConnection::class, function (Server $c) {
538
+		$this->registerService(IDBConnection::class, function(Server $c) {
539 539
 			$systemConfig = $c->getSystemConfig();
540 540
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
541 541
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 		});
550 550
 		$this->registerAlias('DatabaseConnection', IDBConnection::class);
551 551
 
552
-		$this->registerService('HTTPHelper', function (Server $c) {
552
+		$this->registerService('HTTPHelper', function(Server $c) {
553 553
 			$config = $c->getConfig();
554 554
 			return new HTTPHelper(
555 555
 				$config,
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 			);
558 558
 		});
559 559
 
560
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
560
+		$this->registerService(\OCP\Http\Client\IClientService::class, function(Server $c) {
561 561
 			$user = \OC_User::getUser();
562 562
 			$uid = $user ? $user : null;
563 563
 			return new ClientService(
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 		});
568 568
 		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569 569
 
570
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
570
+		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function(Server $c) {
571 571
 			if ($c->getSystemConfig()->getValue('debug', false)) {
572 572
 				return new EventLogger();
573 573
 			} else {
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
 		});
577 577
 		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578 578
 
579
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
579
+		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function(Server $c) {
580 580
 			if ($c->getSystemConfig()->getValue('debug', false)) {
581 581
 				return new QueryLogger();
582 582
 			} else {
@@ -585,7 +585,7 @@  discard block
 block discarded – undo
585 585
 		});
586 586
 		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587 587
 
588
-		$this->registerService(TempManager::class, function (Server $c) {
588
+		$this->registerService(TempManager::class, function(Server $c) {
589 589
 			return new TempManager(
590 590
 				$c->getLogger(),
591 591
 				$c->getConfig()
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 		$this->registerAlias('TempManager', TempManager::class);
595 595
 		$this->registerAlias(ITempManager::class, TempManager::class);
596 596
 
597
-		$this->registerService(AppManager::class, function (Server $c) {
597
+		$this->registerService(AppManager::class, function(Server $c) {
598 598
 			return new \OC\App\AppManager(
599 599
 				$c->getUserSession(),
600 600
 				$c->getAppConfig(),
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 		$this->registerAlias('AppManager', AppManager::class);
607 607
 		$this->registerAlias(IAppManager::class, AppManager::class);
608 608
 
609
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
609
+		$this->registerService(\OCP\IDateTimeZone::class, function(Server $c) {
610 610
 			return new DateTimeZone(
611 611
 				$c->getConfig(),
612 612
 				$c->getSession()
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 		});
615 615
 		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616 616
 
617
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
617
+		$this->registerService(\OCP\IDateTimeFormatter::class, function(Server $c) {
618 618
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619 619
 
620 620
 			return new DateTimeFormatter(
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
 		});
625 625
 		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626 626
 
627
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
627
+		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function(Server $c) {
628 628
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629 629
 			$listener = new UserMountCacheListener($mountCache);
630 630
 			$listener->listen($c->getUserManager());
@@ -632,10 +632,10 @@  discard block
 block discarded – undo
632 632
 		});
633 633
 		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634 634
 
635
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
635
+		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function(Server $c) {
636 636
 			$loader = \OC\Files\Filesystem::getLoader();
637 637
 			$mountCache = $c->query('UserMountCache');
638
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
638
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639 639
 
640 640
 			// builtin providers
641 641
 
@@ -648,14 +648,14 @@  discard block
 block discarded – undo
648 648
 		});
649 649
 		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650 650
 
651
-		$this->registerService('IniWrapper', function ($c) {
651
+		$this->registerService('IniWrapper', function($c) {
652 652
 			return new IniGetWrapper();
653 653
 		});
654
-		$this->registerService('AsyncCommandBus', function (Server $c) {
654
+		$this->registerService('AsyncCommandBus', function(Server $c) {
655 655
 			$jobList = $c->getJobList();
656 656
 			return new AsyncBus($jobList);
657 657
 		});
658
-		$this->registerService('TrustedDomainHelper', function ($c) {
658
+		$this->registerService('TrustedDomainHelper', function($c) {
659 659
 			return new TrustedDomainHelper($this->getConfig());
660 660
 		});
661 661
 		$this->registerService('Throttler', function(Server $c) {
@@ -666,10 +666,10 @@  discard block
 block discarded – undo
666 666
 				$c->getConfig()
667 667
 			);
668 668
 		});
669
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
669
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
670 670
 			// IConfig and IAppManager requires a working database. This code
671 671
 			// might however be called when ownCloud is not yet setup.
672
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
672
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
673 673
 				$config = $c->getConfig();
674 674
 				$appManager = $c->getAppManager();
675 675
 			} else {
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 					$c->getTempManager()
688 688
 			);
689 689
 		});
690
-		$this->registerService(\OCP\IRequest::class, function ($c) {
690
+		$this->registerService(\OCP\IRequest::class, function($c) {
691 691
 			if (isset($this['urlParams'])) {
692 692
 				$urlParams = $this['urlParams'];
693 693
 			} else {
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 		});
724 724
 		$this->registerAlias('Request', \OCP\IRequest::class);
725 725
 
726
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
726
+		$this->registerService(\OCP\Mail\IMailer::class, function(Server $c) {
727 727
 			return new Mailer(
728 728
 				$c->getConfig(),
729 729
 				$c->getLogger(),
@@ -735,14 +735,14 @@  discard block
 block discarded – undo
735 735
 		$this->registerService('LDAPProvider', function(Server $c) {
736 736
 			$config = $c->getConfig();
737 737
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
738
-			if(is_null($factoryClass)) {
738
+			if (is_null($factoryClass)) {
739 739
 				throw new \Exception('ldapProviderFactory not set');
740 740
 			}
741 741
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
742 742
 			$factory = new $factoryClass($this);
743 743
 			return $factory->getLDAPProvider();
744 744
 		});
745
-		$this->registerService('LockingProvider', function (Server $c) {
745
+		$this->registerService('LockingProvider', function(Server $c) {
746 746
 			$ini = $c->getIniWrapper();
747 747
 			$config = $c->getConfig();
748 748
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -758,37 +758,37 @@  discard block
 block discarded – undo
758 758
 			return new NoopLockingProvider();
759 759
 		});
760 760
 
761
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
761
+		$this->registerService(\OCP\Files\Mount\IMountManager::class, function() {
762 762
 			return new \OC\Files\Mount\Manager();
763 763
 		});
764 764
 		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
765 765
 
766
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
766
+		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function(Server $c) {
767 767
 			return new \OC\Files\Type\Detection(
768 768
 				$c->getURLGenerator(),
769 769
 				\OC::$configDir,
770
-				\OC::$SERVERROOT . '/resources/config/'
770
+				\OC::$SERVERROOT.'/resources/config/'
771 771
 			);
772 772
 		});
773 773
 		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
774 774
 
775
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
775
+		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function(Server $c) {
776 776
 			return new \OC\Files\Type\Loader(
777 777
 				$c->getDatabaseConnection()
778 778
 			);
779 779
 		});
780 780
 		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
781 781
 
782
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
782
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
783 783
 			return new Manager(
784 784
 				$c->query(IValidator::class)
785 785
 			);
786 786
 		});
787 787
 		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
788 788
 
789
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
789
+		$this->registerService(\OC\CapabilitiesManager::class, function(Server $c) {
790 790
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
791
-			$manager->registerCapability(function () use ($c) {
791
+			$manager->registerCapability(function() use ($c) {
792 792
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
793 793
 			});
794 794
 			return $manager;
@@ -830,13 +830,13 @@  discard block
 block discarded – undo
830 830
 			}
831 831
 			return new \OC_Defaults();
832 832
 		});
833
-		$this->registerService(EventDispatcher::class, function () {
833
+		$this->registerService(EventDispatcher::class, function() {
834 834
 			return new EventDispatcher();
835 835
 		});
836 836
 		$this->registerAlias('EventDispatcher', EventDispatcher::class);
837 837
 		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
838 838
 
839
-		$this->registerService('CryptoWrapper', function (Server $c) {
839
+		$this->registerService('CryptoWrapper', function(Server $c) {
840 840
 			// FIXME: Instantiiated here due to cyclic dependency
841 841
 			$request = new Request(
842 842
 				[
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 				$request
862 862
 			);
863 863
 		});
864
-		$this->registerService('CsrfTokenManager', function (Server $c) {
864
+		$this->registerService('CsrfTokenManager', function(Server $c) {
865 865
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
866 866
 
867 867
 			return new CsrfTokenManager(
@@ -869,10 +869,10 @@  discard block
 block discarded – undo
869 869
 				$c->query(SessionStorage::class)
870 870
 			);
871 871
 		});
872
-		$this->registerService(SessionStorage::class, function (Server $c) {
872
+		$this->registerService(SessionStorage::class, function(Server $c) {
873 873
 			return new SessionStorage($c->getSession());
874 874
 		});
875
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
875
+		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function(Server $c) {
876 876
 			return new ContentSecurityPolicyManager();
877 877
 		});
878 878
 		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
@@ -923,25 +923,25 @@  discard block
 block discarded – undo
923 923
 			);
924 924
 			return $manager;
925 925
 		});
926
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
926
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
927 927
 			return new \OC\Files\AppData\Factory(
928 928
 				$c->getRootFolder(),
929 929
 				$c->getSystemConfig()
930 930
 			);
931 931
 		});
932 932
 
933
-		$this->registerService('LockdownManager', function (Server $c) {
933
+		$this->registerService('LockdownManager', function(Server $c) {
934 934
 			return new LockdownManager(function() use ($c) {
935 935
 				return $c->getSession();
936 936
 			});
937 937
 		});
938 938
 
939
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
939
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
940 940
 			return new CloudIdManager();
941 941
 		});
942 942
 
943 943
 		/* To trick DI since we don't extend the DIContainer here */
944
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
944
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
945 945
 			return new CleanPreviewsBackgroundJob(
946 946
 				$c->getRootFolder(),
947 947
 				$c->getLogger(),
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
957 957
 		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
958 958
 
959
-		$this->registerService(Defaults::class, function (Server $c) {
959
+		$this->registerService(Defaults::class, function(Server $c) {
960 960
 			return new Defaults(
961 961
 				$c->getThemingDefaults()
962 962
 			);
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
 	 * @deprecated since 9.2.0 use IAppData
1103 1103
 	 */
1104 1104
 	public function getAppFolder() {
1105
-		$dir = '/' . \OC_App::getCurrentApp();
1105
+		$dir = '/'.\OC_App::getCurrentApp();
1106 1106
 		$root = $this->getRootFolder();
1107 1107
 		if (!$root->nodeExists($dir)) {
1108 1108
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.
Indentation   +1590 added lines, -1590 removed lines patch added patch discarded remove patch
@@ -116,1599 +116,1599 @@
 block discarded – undo
116 116
  * TODO: hookup all manager classes
117 117
  */
118 118
 class Server extends ServerContainer implements IServerContainer {
119
-	/** @var string */
120
-	private $webRoot;
121
-
122
-	/**
123
-	 * @param string $webRoot
124
-	 * @param \OC\Config $config
125
-	 */
126
-	public function __construct($webRoot, \OC\Config $config) {
127
-		parent::__construct();
128
-		$this->webRoot = $webRoot;
129
-
130
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132
-
133
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
134
-			return new PreviewManager(
135
-				$c->getConfig(),
136
-				$c->getRootFolder(),
137
-				$c->getAppDataDir('preview'),
138
-				$c->getEventDispatcher(),
139
-				$c->getSession()->get('user_id')
140
-			);
141
-		});
142
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
143
-
144
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
-			return new \OC\Preview\Watcher(
146
-				$c->getAppDataDir('preview')
147
-			);
148
-		});
149
-
150
-		$this->registerService('EncryptionManager', function (Server $c) {
151
-			$view = new View();
152
-			$util = new Encryption\Util(
153
-				$view,
154
-				$c->getUserManager(),
155
-				$c->getGroupManager(),
156
-				$c->getConfig()
157
-			);
158
-			return new Encryption\Manager(
159
-				$c->getConfig(),
160
-				$c->getLogger(),
161
-				$c->getL10N('core'),
162
-				new View(),
163
-				$util,
164
-				new ArrayCache()
165
-			);
166
-		});
167
-
168
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
169
-			$util = new Encryption\Util(
170
-				new View(),
171
-				$c->getUserManager(),
172
-				$c->getGroupManager(),
173
-				$c->getConfig()
174
-			);
175
-			return new Encryption\File($util);
176
-		});
177
-
178
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
179
-			$view = new View();
180
-			$util = new Encryption\Util(
181
-				$view,
182
-				$c->getUserManager(),
183
-				$c->getGroupManager(),
184
-				$c->getConfig()
185
-			);
186
-
187
-			return new Encryption\Keys\Storage($view, $util);
188
-		});
189
-		$this->registerService('TagMapper', function (Server $c) {
190
-			return new TagMapper($c->getDatabaseConnection());
191
-		});
192
-
193
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
194
-			$tagMapper = $c->query('TagMapper');
195
-			return new TagManager($tagMapper, $c->getUserSession());
196
-		});
197
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
198
-
199
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
200
-			$config = $c->getConfig();
201
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202
-			/** @var \OC\SystemTag\ManagerFactory $factory */
203
-			$factory = new $factoryClass($this);
204
-			return $factory;
205
-		});
206
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
207
-			return $c->query('SystemTagManagerFactory')->getManager();
208
-		});
209
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210
-
211
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
212
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
213
-		});
214
-		$this->registerService('RootFolder', function (Server $c) {
215
-			$manager = \OC\Files\Filesystem::getMountManager(null);
216
-			$view = new View();
217
-			$root = new Root(
218
-				$manager,
219
-				$view,
220
-				null,
221
-				$c->getUserMountCache(),
222
-				$this->getLogger(),
223
-				$this->getUserManager()
224
-			);
225
-			$connector = new HookConnector($root, $view);
226
-			$connector->viewToNode();
227
-
228
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
229
-			$previewConnector->connectWatcher();
230
-
231
-			return $root;
232
-		});
233
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
234
-
235
-		$this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
236
-			return new LazyRoot(function() use ($c) {
237
-				return $c->query('RootFolder');
238
-			});
239
-		});
240
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241
-
242
-		$this->registerService(\OCP\IUserManager::class, function (Server $c) {
243
-			$config = $c->getConfig();
244
-			return new \OC\User\Manager($config);
245
-		});
246
-		$this->registerAlias('UserManager', \OCP\IUserManager::class);
247
-
248
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
249
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
251
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252
-			});
253
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
254
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255
-			});
256
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
257
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258
-			});
259
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
260
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261
-			});
262
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
263
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264
-			});
265
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
269
-			});
270
-			return $groupManager;
271
-		});
272
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
273
-
274
-		$this->registerService(Store::class, function(Server $c) {
275
-			$session = $c->getSession();
276
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
277
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
278
-			} else {
279
-				$tokenProvider = null;
280
-			}
281
-			$logger = $c->getLogger();
282
-			return new Store($session, $logger, $tokenProvider);
283
-		});
284
-		$this->registerAlias(IStore::class, Store::class);
285
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
286
-			$dbConnection = $c->getDatabaseConnection();
287
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
288
-		});
289
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
290
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291
-			$crypto = $c->getCrypto();
292
-			$config = $c->getConfig();
293
-			$logger = $c->getLogger();
294
-			$timeFactory = new TimeFactory();
295
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
296
-		});
297
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298
-
299
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
300
-			$manager = $c->getUserManager();
301
-			$session = new \OC\Session\Memory('');
302
-			$timeFactory = new TimeFactory();
303
-			// Token providers might require a working database. This code
304
-			// might however be called when ownCloud is not yet setup.
305
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
306
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
307
-			} else {
308
-				$defaultTokenProvider = null;
309
-			}
310
-
311
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
313
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314
-			});
315
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
316
-				/** @var $user \OC\User\User */
317
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318
-			});
319
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
320
-				/** @var $user \OC\User\User */
321
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322
-			});
323
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
324
-				/** @var $user \OC\User\User */
325
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326
-			});
327
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
328
-				/** @var $user \OC\User\User */
329
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330
-			});
331
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
332
-				/** @var $user \OC\User\User */
333
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334
-			});
335
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
336
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337
-			});
338
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
339
-				/** @var $user \OC\User\User */
340
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341
-			});
342
-			$userSession->listen('\OC\User', 'logout', function () {
343
-				\OC_Hook::emit('OC_User', 'logout', array());
344
-			});
345
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
346
-				/** @var $user \OC\User\User */
347
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348
-			});
349
-			return $userSession;
350
-		});
351
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
352
-
353
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
354
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355
-		});
356
-
357
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359
-
360
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
361
-			return new \OC\AllConfig(
362
-				$c->getSystemConfig()
363
-			);
364
-		});
365
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
366
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367
-
368
-		$this->registerService('SystemConfig', function ($c) use ($config) {
369
-			return new \OC\SystemConfig($config);
370
-		});
371
-
372
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
373
-			return new \OC\AppConfig($c->getDatabaseConnection());
374
-		});
375
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
376
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377
-
378
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
379
-			return new \OC\L10N\Factory(
380
-				$c->getConfig(),
381
-				$c->getRequest(),
382
-				$c->getUserSession(),
383
-				\OC::$SERVERROOT
384
-			);
385
-		});
386
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387
-
388
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
389
-			$config = $c->getConfig();
390
-			$cacheFactory = $c->getMemCacheFactory();
391
-			return new \OC\URLGenerator(
392
-				$config,
393
-				$cacheFactory
394
-			);
395
-		});
396
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397
-
398
-		$this->registerService('AppHelper', function ($c) {
399
-			return new \OC\AppHelper();
400
-		});
401
-		$this->registerService('AppFetcher', function ($c) {
402
-			return new AppFetcher(
403
-				$this->getAppDataDir('appstore'),
404
-				$this->getHTTPClientService(),
405
-				$this->query(TimeFactory::class),
406
-				$this->getConfig()
407
-			);
408
-		});
409
-		$this->registerService('CategoryFetcher', function ($c) {
410
-			return new CategoryFetcher(
411
-				$this->getAppDataDir('appstore'),
412
-				$this->getHTTPClientService(),
413
-				$this->query(TimeFactory::class),
414
-				$this->getConfig()
415
-			);
416
-		});
417
-
418
-		$this->registerService(\OCP\ICache::class, function ($c) {
419
-			return new Cache\File();
420
-		});
421
-		$this->registerAlias('UserCache', \OCP\ICache::class);
422
-
423
-		$this->registerService(Factory::class, function (Server $c) {
424
-			$config = $c->getConfig();
425
-
426
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427
-				$v = \OC_App::getAppVersions();
428
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
429
-				$version = implode(',', $v);
430
-				$instanceId = \OC_Util::getInstanceId();
431
-				$path = \OC::$SERVERROOT;
432
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
433
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434
-					$config->getSystemValue('memcache.local', null),
435
-					$config->getSystemValue('memcache.distributed', null),
436
-					$config->getSystemValue('memcache.locking', null)
437
-				);
438
-			}
439
-
440
-			return new \OC\Memcache\Factory('', $c->getLogger(),
441
-				'\\OC\\Memcache\\ArrayCache',
442
-				'\\OC\\Memcache\\ArrayCache',
443
-				'\\OC\\Memcache\\ArrayCache'
444
-			);
445
-		});
446
-		$this->registerAlias('MemCacheFactory', Factory::class);
447
-		$this->registerAlias(ICacheFactory::class, Factory::class);
448
-
449
-		$this->registerService('RedisFactory', function (Server $c) {
450
-			$systemConfig = $c->getSystemConfig();
451
-			return new RedisFactory($systemConfig);
452
-		});
453
-
454
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
455
-			return new \OC\Activity\Manager(
456
-				$c->getRequest(),
457
-				$c->getUserSession(),
458
-				$c->getConfig(),
459
-				$c->query(IValidator::class)
460
-			);
461
-		});
462
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463
-
464
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
465
-			return new \OC\Activity\EventMerger(
466
-				$c->getL10N('lib')
467
-			);
468
-		});
469
-		$this->registerAlias(IValidator::class, Validator::class);
470
-
471
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
472
-			return new AvatarManager(
473
-				$c->getUserManager(),
474
-				$c->getAppDataDir('avatar'),
475
-				$c->getL10N('lib'),
476
-				$c->getLogger(),
477
-				$c->getConfig()
478
-			);
479
-		});
480
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481
-
482
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
483
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484
-			$logger = Log::getLogClass($logType);
485
-			call_user_func(array($logger, 'init'));
486
-
487
-			return new Log($logger);
488
-		});
489
-		$this->registerAlias('Logger', \OCP\ILogger::class);
490
-
491
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
492
-			$config = $c->getConfig();
493
-			return new \OC\BackgroundJob\JobList(
494
-				$c->getDatabaseConnection(),
495
-				$config,
496
-				new TimeFactory()
497
-			);
498
-		});
499
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500
-
501
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
502
-			$cacheFactory = $c->getMemCacheFactory();
503
-			$logger = $c->getLogger();
504
-			if ($cacheFactory->isAvailable()) {
505
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
506
-			} else {
507
-				$router = new \OC\Route\Router($logger);
508
-			}
509
-			return $router;
510
-		});
511
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
512
-
513
-		$this->registerService(\OCP\ISearch::class, function ($c) {
514
-			return new Search();
515
-		});
516
-		$this->registerAlias('Search', \OCP\ISearch::class);
517
-
518
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
519
-			return new SecureRandom();
520
-		});
521
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522
-
523
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
524
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
525
-		});
526
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527
-
528
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
529
-			return new Hasher($c->getConfig());
530
-		});
531
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532
-
533
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
534
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535
-		});
536
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537
-
538
-		$this->registerService(IDBConnection::class, function (Server $c) {
539
-			$systemConfig = $c->getSystemConfig();
540
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
541
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
542
-			if (!$factory->isValidType($type)) {
543
-				throw new \OC\DatabaseException('Invalid database type');
544
-			}
545
-			$connectionParams = $factory->createConnectionParams();
546
-			$connection = $factory->getConnection($type, $connectionParams);
547
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
548
-			return $connection;
549
-		});
550
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
551
-
552
-		$this->registerService('HTTPHelper', function (Server $c) {
553
-			$config = $c->getConfig();
554
-			return new HTTPHelper(
555
-				$config,
556
-				$c->getHTTPClientService()
557
-			);
558
-		});
559
-
560
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
561
-			$user = \OC_User::getUser();
562
-			$uid = $user ? $user : null;
563
-			return new ClientService(
564
-				$c->getConfig(),
565
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
566
-			);
567
-		});
568
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569
-
570
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
571
-			if ($c->getSystemConfig()->getValue('debug', false)) {
572
-				return new EventLogger();
573
-			} else {
574
-				return new NullEventLogger();
575
-			}
576
-		});
577
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578
-
579
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
580
-			if ($c->getSystemConfig()->getValue('debug', false)) {
581
-				return new QueryLogger();
582
-			} else {
583
-				return new NullQueryLogger();
584
-			}
585
-		});
586
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587
-
588
-		$this->registerService(TempManager::class, function (Server $c) {
589
-			return new TempManager(
590
-				$c->getLogger(),
591
-				$c->getConfig()
592
-			);
593
-		});
594
-		$this->registerAlias('TempManager', TempManager::class);
595
-		$this->registerAlias(ITempManager::class, TempManager::class);
596
-
597
-		$this->registerService(AppManager::class, function (Server $c) {
598
-			return new \OC\App\AppManager(
599
-				$c->getUserSession(),
600
-				$c->getAppConfig(),
601
-				$c->getGroupManager(),
602
-				$c->getMemCacheFactory(),
603
-				$c->getEventDispatcher()
604
-			);
605
-		});
606
-		$this->registerAlias('AppManager', AppManager::class);
607
-		$this->registerAlias(IAppManager::class, AppManager::class);
608
-
609
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
610
-			return new DateTimeZone(
611
-				$c->getConfig(),
612
-				$c->getSession()
613
-			);
614
-		});
615
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616
-
617
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
618
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619
-
620
-			return new DateTimeFormatter(
621
-				$c->getDateTimeZone()->getTimeZone(),
622
-				$c->getL10N('lib', $language)
623
-			);
624
-		});
625
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626
-
627
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
628
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629
-			$listener = new UserMountCacheListener($mountCache);
630
-			$listener->listen($c->getUserManager());
631
-			return $mountCache;
632
-		});
633
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634
-
635
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
636
-			$loader = \OC\Files\Filesystem::getLoader();
637
-			$mountCache = $c->query('UserMountCache');
638
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639
-
640
-			// builtin providers
641
-
642
-			$config = $c->getConfig();
643
-			$manager->registerProvider(new CacheMountProvider($config));
644
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
645
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
646
-
647
-			return $manager;
648
-		});
649
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650
-
651
-		$this->registerService('IniWrapper', function ($c) {
652
-			return new IniGetWrapper();
653
-		});
654
-		$this->registerService('AsyncCommandBus', function (Server $c) {
655
-			$jobList = $c->getJobList();
656
-			return new AsyncBus($jobList);
657
-		});
658
-		$this->registerService('TrustedDomainHelper', function ($c) {
659
-			return new TrustedDomainHelper($this->getConfig());
660
-		});
661
-		$this->registerService('Throttler', function(Server $c) {
662
-			return new Throttler(
663
-				$c->getDatabaseConnection(),
664
-				new TimeFactory(),
665
-				$c->getLogger(),
666
-				$c->getConfig()
667
-			);
668
-		});
669
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
670
-			// IConfig and IAppManager requires a working database. This code
671
-			// might however be called when ownCloud is not yet setup.
672
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
673
-				$config = $c->getConfig();
674
-				$appManager = $c->getAppManager();
675
-			} else {
676
-				$config = null;
677
-				$appManager = null;
678
-			}
679
-
680
-			return new Checker(
681
-					new EnvironmentHelper(),
682
-					new FileAccessHelper(),
683
-					new AppLocator(),
684
-					$config,
685
-					$c->getMemCacheFactory(),
686
-					$appManager,
687
-					$c->getTempManager()
688
-			);
689
-		});
690
-		$this->registerService(\OCP\IRequest::class, function ($c) {
691
-			if (isset($this['urlParams'])) {
692
-				$urlParams = $this['urlParams'];
693
-			} else {
694
-				$urlParams = [];
695
-			}
696
-
697
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
698
-				&& in_array('fakeinput', stream_get_wrappers())
699
-			) {
700
-				$stream = 'fakeinput://data';
701
-			} else {
702
-				$stream = 'php://input';
703
-			}
704
-
705
-			return new Request(
706
-				[
707
-					'get' => $_GET,
708
-					'post' => $_POST,
709
-					'files' => $_FILES,
710
-					'server' => $_SERVER,
711
-					'env' => $_ENV,
712
-					'cookies' => $_COOKIE,
713
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
714
-						? $_SERVER['REQUEST_METHOD']
715
-						: null,
716
-					'urlParams' => $urlParams,
717
-				],
718
-				$this->getSecureRandom(),
719
-				$this->getConfig(),
720
-				$this->getCsrfTokenManager(),
721
-				$stream
722
-			);
723
-		});
724
-		$this->registerAlias('Request', \OCP\IRequest::class);
725
-
726
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
727
-			return new Mailer(
728
-				$c->getConfig(),
729
-				$c->getLogger(),
730
-				$c->query(Defaults::class),
731
-				$c->getURLGenerator(),
732
-				$c->getL10N('lib')
733
-			);
734
-		});
735
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
736
-
737
-		$this->registerService('LDAPProvider', function(Server $c) {
738
-			$config = $c->getConfig();
739
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
740
-			if(is_null($factoryClass)) {
741
-				throw new \Exception('ldapProviderFactory not set');
742
-			}
743
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
744
-			$factory = new $factoryClass($this);
745
-			return $factory->getLDAPProvider();
746
-		});
747
-		$this->registerService('LockingProvider', function (Server $c) {
748
-			$ini = $c->getIniWrapper();
749
-			$config = $c->getConfig();
750
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
751
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
752
-				/** @var \OC\Memcache\Factory $memcacheFactory */
753
-				$memcacheFactory = $c->getMemCacheFactory();
754
-				$memcache = $memcacheFactory->createLocking('lock');
755
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
756
-					return new MemcacheLockingProvider($memcache, $ttl);
757
-				}
758
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
759
-			}
760
-			return new NoopLockingProvider();
761
-		});
762
-
763
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
764
-			return new \OC\Files\Mount\Manager();
765
-		});
766
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
767
-
768
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
769
-			return new \OC\Files\Type\Detection(
770
-				$c->getURLGenerator(),
771
-				\OC::$configDir,
772
-				\OC::$SERVERROOT . '/resources/config/'
773
-			);
774
-		});
775
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
776
-
777
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
778
-			return new \OC\Files\Type\Loader(
779
-				$c->getDatabaseConnection()
780
-			);
781
-		});
782
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
783
-
784
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
785
-			return new Manager(
786
-				$c->query(IValidator::class)
787
-			);
788
-		});
789
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
790
-
791
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
792
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
793
-			$manager->registerCapability(function () use ($c) {
794
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
795
-			});
796
-			return $manager;
797
-		});
798
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
799
-
800
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
801
-			$config = $c->getConfig();
802
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
803
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
804
-			$factory = new $factoryClass($this);
805
-			return $factory->getManager();
806
-		});
807
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
808
-
809
-		$this->registerService('ThemingDefaults', function(Server $c) {
810
-			/*
119
+    /** @var string */
120
+    private $webRoot;
121
+
122
+    /**
123
+     * @param string $webRoot
124
+     * @param \OC\Config $config
125
+     */
126
+    public function __construct($webRoot, \OC\Config $config) {
127
+        parent::__construct();
128
+        $this->webRoot = $webRoot;
129
+
130
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
131
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
132
+
133
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
134
+            return new PreviewManager(
135
+                $c->getConfig(),
136
+                $c->getRootFolder(),
137
+                $c->getAppDataDir('preview'),
138
+                $c->getEventDispatcher(),
139
+                $c->getSession()->get('user_id')
140
+            );
141
+        });
142
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
143
+
144
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
145
+            return new \OC\Preview\Watcher(
146
+                $c->getAppDataDir('preview')
147
+            );
148
+        });
149
+
150
+        $this->registerService('EncryptionManager', function (Server $c) {
151
+            $view = new View();
152
+            $util = new Encryption\Util(
153
+                $view,
154
+                $c->getUserManager(),
155
+                $c->getGroupManager(),
156
+                $c->getConfig()
157
+            );
158
+            return new Encryption\Manager(
159
+                $c->getConfig(),
160
+                $c->getLogger(),
161
+                $c->getL10N('core'),
162
+                new View(),
163
+                $util,
164
+                new ArrayCache()
165
+            );
166
+        });
167
+
168
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
169
+            $util = new Encryption\Util(
170
+                new View(),
171
+                $c->getUserManager(),
172
+                $c->getGroupManager(),
173
+                $c->getConfig()
174
+            );
175
+            return new Encryption\File($util);
176
+        });
177
+
178
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
179
+            $view = new View();
180
+            $util = new Encryption\Util(
181
+                $view,
182
+                $c->getUserManager(),
183
+                $c->getGroupManager(),
184
+                $c->getConfig()
185
+            );
186
+
187
+            return new Encryption\Keys\Storage($view, $util);
188
+        });
189
+        $this->registerService('TagMapper', function (Server $c) {
190
+            return new TagMapper($c->getDatabaseConnection());
191
+        });
192
+
193
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
194
+            $tagMapper = $c->query('TagMapper');
195
+            return new TagManager($tagMapper, $c->getUserSession());
196
+        });
197
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
198
+
199
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
200
+            $config = $c->getConfig();
201
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
202
+            /** @var \OC\SystemTag\ManagerFactory $factory */
203
+            $factory = new $factoryClass($this);
204
+            return $factory;
205
+        });
206
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
207
+            return $c->query('SystemTagManagerFactory')->getManager();
208
+        });
209
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
210
+
211
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
212
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
213
+        });
214
+        $this->registerService('RootFolder', function (Server $c) {
215
+            $manager = \OC\Files\Filesystem::getMountManager(null);
216
+            $view = new View();
217
+            $root = new Root(
218
+                $manager,
219
+                $view,
220
+                null,
221
+                $c->getUserMountCache(),
222
+                $this->getLogger(),
223
+                $this->getUserManager()
224
+            );
225
+            $connector = new HookConnector($root, $view);
226
+            $connector->viewToNode();
227
+
228
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
229
+            $previewConnector->connectWatcher();
230
+
231
+            return $root;
232
+        });
233
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
234
+
235
+        $this->registerService(\OCP\Files\IRootFolder::class, function(Server $c) {
236
+            return new LazyRoot(function() use ($c) {
237
+                return $c->query('RootFolder');
238
+            });
239
+        });
240
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
241
+
242
+        $this->registerService(\OCP\IUserManager::class, function (Server $c) {
243
+            $config = $c->getConfig();
244
+            return new \OC\User\Manager($config);
245
+        });
246
+        $this->registerAlias('UserManager', \OCP\IUserManager::class);
247
+
248
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
249
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
250
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
251
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
252
+            });
253
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
254
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
255
+            });
256
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
257
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
258
+            });
259
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
260
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
261
+            });
262
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
263
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
264
+            });
265
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
266
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
267
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
268
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
269
+            });
270
+            return $groupManager;
271
+        });
272
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
273
+
274
+        $this->registerService(Store::class, function(Server $c) {
275
+            $session = $c->getSession();
276
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
277
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
278
+            } else {
279
+                $tokenProvider = null;
280
+            }
281
+            $logger = $c->getLogger();
282
+            return new Store($session, $logger, $tokenProvider);
283
+        });
284
+        $this->registerAlias(IStore::class, Store::class);
285
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
286
+            $dbConnection = $c->getDatabaseConnection();
287
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
288
+        });
289
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
290
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
291
+            $crypto = $c->getCrypto();
292
+            $config = $c->getConfig();
293
+            $logger = $c->getLogger();
294
+            $timeFactory = new TimeFactory();
295
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
296
+        });
297
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
298
+
299
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
300
+            $manager = $c->getUserManager();
301
+            $session = new \OC\Session\Memory('');
302
+            $timeFactory = new TimeFactory();
303
+            // Token providers might require a working database. This code
304
+            // might however be called when ownCloud is not yet setup.
305
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
306
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
307
+            } else {
308
+                $defaultTokenProvider = null;
309
+            }
310
+
311
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom(), $c->getLockdownManager());
312
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
313
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
314
+            });
315
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
316
+                /** @var $user \OC\User\User */
317
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
318
+            });
319
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
320
+                /** @var $user \OC\User\User */
321
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
322
+            });
323
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
324
+                /** @var $user \OC\User\User */
325
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
326
+            });
327
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
328
+                /** @var $user \OC\User\User */
329
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
330
+            });
331
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
332
+                /** @var $user \OC\User\User */
333
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
334
+            });
335
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
336
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
337
+            });
338
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
339
+                /** @var $user \OC\User\User */
340
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
341
+            });
342
+            $userSession->listen('\OC\User', 'logout', function () {
343
+                \OC_Hook::emit('OC_User', 'logout', array());
344
+            });
345
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
346
+                /** @var $user \OC\User\User */
347
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
348
+            });
349
+            return $userSession;
350
+        });
351
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
352
+
353
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
354
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
355
+        });
356
+
357
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
358
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
359
+
360
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
361
+            return new \OC\AllConfig(
362
+                $c->getSystemConfig()
363
+            );
364
+        });
365
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
366
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
367
+
368
+        $this->registerService('SystemConfig', function ($c) use ($config) {
369
+            return new \OC\SystemConfig($config);
370
+        });
371
+
372
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
373
+            return new \OC\AppConfig($c->getDatabaseConnection());
374
+        });
375
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
376
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
377
+
378
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
379
+            return new \OC\L10N\Factory(
380
+                $c->getConfig(),
381
+                $c->getRequest(),
382
+                $c->getUserSession(),
383
+                \OC::$SERVERROOT
384
+            );
385
+        });
386
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
387
+
388
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
389
+            $config = $c->getConfig();
390
+            $cacheFactory = $c->getMemCacheFactory();
391
+            return new \OC\URLGenerator(
392
+                $config,
393
+                $cacheFactory
394
+            );
395
+        });
396
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
397
+
398
+        $this->registerService('AppHelper', function ($c) {
399
+            return new \OC\AppHelper();
400
+        });
401
+        $this->registerService('AppFetcher', function ($c) {
402
+            return new AppFetcher(
403
+                $this->getAppDataDir('appstore'),
404
+                $this->getHTTPClientService(),
405
+                $this->query(TimeFactory::class),
406
+                $this->getConfig()
407
+            );
408
+        });
409
+        $this->registerService('CategoryFetcher', function ($c) {
410
+            return new CategoryFetcher(
411
+                $this->getAppDataDir('appstore'),
412
+                $this->getHTTPClientService(),
413
+                $this->query(TimeFactory::class),
414
+                $this->getConfig()
415
+            );
416
+        });
417
+
418
+        $this->registerService(\OCP\ICache::class, function ($c) {
419
+            return new Cache\File();
420
+        });
421
+        $this->registerAlias('UserCache', \OCP\ICache::class);
422
+
423
+        $this->registerService(Factory::class, function (Server $c) {
424
+            $config = $c->getConfig();
425
+
426
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
427
+                $v = \OC_App::getAppVersions();
428
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
429
+                $version = implode(',', $v);
430
+                $instanceId = \OC_Util::getInstanceId();
431
+                $path = \OC::$SERVERROOT;
432
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
433
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
434
+                    $config->getSystemValue('memcache.local', null),
435
+                    $config->getSystemValue('memcache.distributed', null),
436
+                    $config->getSystemValue('memcache.locking', null)
437
+                );
438
+            }
439
+
440
+            return new \OC\Memcache\Factory('', $c->getLogger(),
441
+                '\\OC\\Memcache\\ArrayCache',
442
+                '\\OC\\Memcache\\ArrayCache',
443
+                '\\OC\\Memcache\\ArrayCache'
444
+            );
445
+        });
446
+        $this->registerAlias('MemCacheFactory', Factory::class);
447
+        $this->registerAlias(ICacheFactory::class, Factory::class);
448
+
449
+        $this->registerService('RedisFactory', function (Server $c) {
450
+            $systemConfig = $c->getSystemConfig();
451
+            return new RedisFactory($systemConfig);
452
+        });
453
+
454
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
455
+            return new \OC\Activity\Manager(
456
+                $c->getRequest(),
457
+                $c->getUserSession(),
458
+                $c->getConfig(),
459
+                $c->query(IValidator::class)
460
+            );
461
+        });
462
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
463
+
464
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
465
+            return new \OC\Activity\EventMerger(
466
+                $c->getL10N('lib')
467
+            );
468
+        });
469
+        $this->registerAlias(IValidator::class, Validator::class);
470
+
471
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
472
+            return new AvatarManager(
473
+                $c->getUserManager(),
474
+                $c->getAppDataDir('avatar'),
475
+                $c->getL10N('lib'),
476
+                $c->getLogger(),
477
+                $c->getConfig()
478
+            );
479
+        });
480
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
481
+
482
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
483
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
484
+            $logger = Log::getLogClass($logType);
485
+            call_user_func(array($logger, 'init'));
486
+
487
+            return new Log($logger);
488
+        });
489
+        $this->registerAlias('Logger', \OCP\ILogger::class);
490
+
491
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
492
+            $config = $c->getConfig();
493
+            return new \OC\BackgroundJob\JobList(
494
+                $c->getDatabaseConnection(),
495
+                $config,
496
+                new TimeFactory()
497
+            );
498
+        });
499
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
500
+
501
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
502
+            $cacheFactory = $c->getMemCacheFactory();
503
+            $logger = $c->getLogger();
504
+            if ($cacheFactory->isAvailable()) {
505
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
506
+            } else {
507
+                $router = new \OC\Route\Router($logger);
508
+            }
509
+            return $router;
510
+        });
511
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
512
+
513
+        $this->registerService(\OCP\ISearch::class, function ($c) {
514
+            return new Search();
515
+        });
516
+        $this->registerAlias('Search', \OCP\ISearch::class);
517
+
518
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
519
+            return new SecureRandom();
520
+        });
521
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
522
+
523
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
524
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
525
+        });
526
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
527
+
528
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
529
+            return new Hasher($c->getConfig());
530
+        });
531
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
532
+
533
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
534
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
535
+        });
536
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
537
+
538
+        $this->registerService(IDBConnection::class, function (Server $c) {
539
+            $systemConfig = $c->getSystemConfig();
540
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
541
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
542
+            if (!$factory->isValidType($type)) {
543
+                throw new \OC\DatabaseException('Invalid database type');
544
+            }
545
+            $connectionParams = $factory->createConnectionParams();
546
+            $connection = $factory->getConnection($type, $connectionParams);
547
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
548
+            return $connection;
549
+        });
550
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
551
+
552
+        $this->registerService('HTTPHelper', function (Server $c) {
553
+            $config = $c->getConfig();
554
+            return new HTTPHelper(
555
+                $config,
556
+                $c->getHTTPClientService()
557
+            );
558
+        });
559
+
560
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
561
+            $user = \OC_User::getUser();
562
+            $uid = $user ? $user : null;
563
+            return new ClientService(
564
+                $c->getConfig(),
565
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
566
+            );
567
+        });
568
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
569
+
570
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
571
+            if ($c->getSystemConfig()->getValue('debug', false)) {
572
+                return new EventLogger();
573
+            } else {
574
+                return new NullEventLogger();
575
+            }
576
+        });
577
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
578
+
579
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
580
+            if ($c->getSystemConfig()->getValue('debug', false)) {
581
+                return new QueryLogger();
582
+            } else {
583
+                return new NullQueryLogger();
584
+            }
585
+        });
586
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
587
+
588
+        $this->registerService(TempManager::class, function (Server $c) {
589
+            return new TempManager(
590
+                $c->getLogger(),
591
+                $c->getConfig()
592
+            );
593
+        });
594
+        $this->registerAlias('TempManager', TempManager::class);
595
+        $this->registerAlias(ITempManager::class, TempManager::class);
596
+
597
+        $this->registerService(AppManager::class, function (Server $c) {
598
+            return new \OC\App\AppManager(
599
+                $c->getUserSession(),
600
+                $c->getAppConfig(),
601
+                $c->getGroupManager(),
602
+                $c->getMemCacheFactory(),
603
+                $c->getEventDispatcher()
604
+            );
605
+        });
606
+        $this->registerAlias('AppManager', AppManager::class);
607
+        $this->registerAlias(IAppManager::class, AppManager::class);
608
+
609
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
610
+            return new DateTimeZone(
611
+                $c->getConfig(),
612
+                $c->getSession()
613
+            );
614
+        });
615
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
616
+
617
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
618
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
619
+
620
+            return new DateTimeFormatter(
621
+                $c->getDateTimeZone()->getTimeZone(),
622
+                $c->getL10N('lib', $language)
623
+            );
624
+        });
625
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
626
+
627
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
628
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
629
+            $listener = new UserMountCacheListener($mountCache);
630
+            $listener->listen($c->getUserManager());
631
+            return $mountCache;
632
+        });
633
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
634
+
635
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
636
+            $loader = \OC\Files\Filesystem::getLoader();
637
+            $mountCache = $c->query('UserMountCache');
638
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
639
+
640
+            // builtin providers
641
+
642
+            $config = $c->getConfig();
643
+            $manager->registerProvider(new CacheMountProvider($config));
644
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
645
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
646
+
647
+            return $manager;
648
+        });
649
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
650
+
651
+        $this->registerService('IniWrapper', function ($c) {
652
+            return new IniGetWrapper();
653
+        });
654
+        $this->registerService('AsyncCommandBus', function (Server $c) {
655
+            $jobList = $c->getJobList();
656
+            return new AsyncBus($jobList);
657
+        });
658
+        $this->registerService('TrustedDomainHelper', function ($c) {
659
+            return new TrustedDomainHelper($this->getConfig());
660
+        });
661
+        $this->registerService('Throttler', function(Server $c) {
662
+            return new Throttler(
663
+                $c->getDatabaseConnection(),
664
+                new TimeFactory(),
665
+                $c->getLogger(),
666
+                $c->getConfig()
667
+            );
668
+        });
669
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
670
+            // IConfig and IAppManager requires a working database. This code
671
+            // might however be called when ownCloud is not yet setup.
672
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
673
+                $config = $c->getConfig();
674
+                $appManager = $c->getAppManager();
675
+            } else {
676
+                $config = null;
677
+                $appManager = null;
678
+            }
679
+
680
+            return new Checker(
681
+                    new EnvironmentHelper(),
682
+                    new FileAccessHelper(),
683
+                    new AppLocator(),
684
+                    $config,
685
+                    $c->getMemCacheFactory(),
686
+                    $appManager,
687
+                    $c->getTempManager()
688
+            );
689
+        });
690
+        $this->registerService(\OCP\IRequest::class, function ($c) {
691
+            if (isset($this['urlParams'])) {
692
+                $urlParams = $this['urlParams'];
693
+            } else {
694
+                $urlParams = [];
695
+            }
696
+
697
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
698
+                && in_array('fakeinput', stream_get_wrappers())
699
+            ) {
700
+                $stream = 'fakeinput://data';
701
+            } else {
702
+                $stream = 'php://input';
703
+            }
704
+
705
+            return new Request(
706
+                [
707
+                    'get' => $_GET,
708
+                    'post' => $_POST,
709
+                    'files' => $_FILES,
710
+                    'server' => $_SERVER,
711
+                    'env' => $_ENV,
712
+                    'cookies' => $_COOKIE,
713
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
714
+                        ? $_SERVER['REQUEST_METHOD']
715
+                        : null,
716
+                    'urlParams' => $urlParams,
717
+                ],
718
+                $this->getSecureRandom(),
719
+                $this->getConfig(),
720
+                $this->getCsrfTokenManager(),
721
+                $stream
722
+            );
723
+        });
724
+        $this->registerAlias('Request', \OCP\IRequest::class);
725
+
726
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
727
+            return new Mailer(
728
+                $c->getConfig(),
729
+                $c->getLogger(),
730
+                $c->query(Defaults::class),
731
+                $c->getURLGenerator(),
732
+                $c->getL10N('lib')
733
+            );
734
+        });
735
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
736
+
737
+        $this->registerService('LDAPProvider', function(Server $c) {
738
+            $config = $c->getConfig();
739
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
740
+            if(is_null($factoryClass)) {
741
+                throw new \Exception('ldapProviderFactory not set');
742
+            }
743
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
744
+            $factory = new $factoryClass($this);
745
+            return $factory->getLDAPProvider();
746
+        });
747
+        $this->registerService('LockingProvider', function (Server $c) {
748
+            $ini = $c->getIniWrapper();
749
+            $config = $c->getConfig();
750
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
751
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
752
+                /** @var \OC\Memcache\Factory $memcacheFactory */
753
+                $memcacheFactory = $c->getMemCacheFactory();
754
+                $memcache = $memcacheFactory->createLocking('lock');
755
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
756
+                    return new MemcacheLockingProvider($memcache, $ttl);
757
+                }
758
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
759
+            }
760
+            return new NoopLockingProvider();
761
+        });
762
+
763
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
764
+            return new \OC\Files\Mount\Manager();
765
+        });
766
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
767
+
768
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
769
+            return new \OC\Files\Type\Detection(
770
+                $c->getURLGenerator(),
771
+                \OC::$configDir,
772
+                \OC::$SERVERROOT . '/resources/config/'
773
+            );
774
+        });
775
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
776
+
777
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
778
+            return new \OC\Files\Type\Loader(
779
+                $c->getDatabaseConnection()
780
+            );
781
+        });
782
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
783
+
784
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
785
+            return new Manager(
786
+                $c->query(IValidator::class)
787
+            );
788
+        });
789
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
790
+
791
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
792
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
793
+            $manager->registerCapability(function () use ($c) {
794
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
795
+            });
796
+            return $manager;
797
+        });
798
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
799
+
800
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function(Server $c) {
801
+            $config = $c->getConfig();
802
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
803
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
804
+            $factory = new $factoryClass($this);
805
+            return $factory->getManager();
806
+        });
807
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
808
+
809
+        $this->registerService('ThemingDefaults', function(Server $c) {
810
+            /*
811 811
 			 * Dark magic for autoloader.
812 812
 			 * If we do a class_exists it will try to load the class which will
813 813
 			 * make composer cache the result. Resulting in errors when enabling
814 814
 			 * the theming app.
815 815
 			 */
816
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
817
-			if (isset($prefixes['OCA\\Theming\\'])) {
818
-				$classExists = true;
819
-			} else {
820
-				$classExists = false;
821
-			}
822
-
823
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
824
-				return new ThemingDefaults(
825
-					$c->getConfig(),
826
-					$c->getL10N('theming'),
827
-					$c->getURLGenerator(),
828
-					new \OC_Defaults(),
829
-					$c->getAppDataDir('theming'),
830
-					$c->getMemCacheFactory()
831
-				);
832
-			}
833
-			return new \OC_Defaults();
834
-		});
835
-		$this->registerService(EventDispatcher::class, function () {
836
-			return new EventDispatcher();
837
-		});
838
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
839
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
840
-
841
-		$this->registerService('CryptoWrapper', function (Server $c) {
842
-			// FIXME: Instantiiated here due to cyclic dependency
843
-			$request = new Request(
844
-				[
845
-					'get' => $_GET,
846
-					'post' => $_POST,
847
-					'files' => $_FILES,
848
-					'server' => $_SERVER,
849
-					'env' => $_ENV,
850
-					'cookies' => $_COOKIE,
851
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
852
-						? $_SERVER['REQUEST_METHOD']
853
-						: null,
854
-				],
855
-				$c->getSecureRandom(),
856
-				$c->getConfig()
857
-			);
858
-
859
-			return new CryptoWrapper(
860
-				$c->getConfig(),
861
-				$c->getCrypto(),
862
-				$c->getSecureRandom(),
863
-				$request
864
-			);
865
-		});
866
-		$this->registerService('CsrfTokenManager', function (Server $c) {
867
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
868
-
869
-			return new CsrfTokenManager(
870
-				$tokenGenerator,
871
-				$c->query(SessionStorage::class)
872
-			);
873
-		});
874
-		$this->registerService(SessionStorage::class, function (Server $c) {
875
-			return new SessionStorage($c->getSession());
876
-		});
877
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
878
-			return new ContentSecurityPolicyManager();
879
-		});
880
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
881
-
882
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
883
-			return new ContentSecurityPolicyNonceManager(
884
-				$c->getCsrfTokenManager(),
885
-				$c->getRequest()
886
-			);
887
-		});
888
-
889
-		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
890
-			$config = $c->getConfig();
891
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
892
-			/** @var \OCP\Share\IProviderFactory $factory */
893
-			$factory = new $factoryClass($this);
894
-
895
-			$manager = new \OC\Share20\Manager(
896
-				$c->getLogger(),
897
-				$c->getConfig(),
898
-				$c->getSecureRandom(),
899
-				$c->getHasher(),
900
-				$c->getMountManager(),
901
-				$c->getGroupManager(),
902
-				$c->getL10N('core'),
903
-				$factory,
904
-				$c->getUserManager(),
905
-				$c->getLazyRootFolder(),
906
-				$c->getEventDispatcher()
907
-			);
908
-
909
-			return $manager;
910
-		});
911
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
912
-
913
-		$this->registerService('SettingsManager', function(Server $c) {
914
-			$manager = new \OC\Settings\Manager(
915
-				$c->getLogger(),
916
-				$c->getDatabaseConnection(),
917
-				$c->getL10N('lib'),
918
-				$c->getConfig(),
919
-				$c->getEncryptionManager(),
920
-				$c->getUserManager(),
921
-				$c->getLockingProvider(),
922
-				$c->getRequest(),
923
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
924
-				$c->getURLGenerator()
925
-			);
926
-			return $manager;
927
-		});
928
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
929
-			return new \OC\Files\AppData\Factory(
930
-				$c->getRootFolder(),
931
-				$c->getSystemConfig()
932
-			);
933
-		});
934
-
935
-		$this->registerService('LockdownManager', function (Server $c) {
936
-			return new LockdownManager(function() use ($c) {
937
-				return $c->getSession();
938
-			});
939
-		});
940
-
941
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
942
-			return new CloudIdManager();
943
-		});
944
-
945
-		/* To trick DI since we don't extend the DIContainer here */
946
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
947
-			return new CleanPreviewsBackgroundJob(
948
-				$c->getRootFolder(),
949
-				$c->getLogger(),
950
-				$c->getJobList(),
951
-				new TimeFactory()
952
-			);
953
-		});
954
-
955
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
956
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
957
-
958
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
959
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
960
-
961
-		$this->registerService(Defaults::class, function (Server $c) {
962
-			return new Defaults(
963
-				$c->getThemingDefaults()
964
-			);
965
-		});
966
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
967
-
968
-		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
969
-			return $c->query(\OCP\IUserSession::class)->getSession();
970
-		});
971
-	}
972
-
973
-	/**
974
-	 * @return \OCP\Contacts\IManager
975
-	 */
976
-	public function getContactsManager() {
977
-		return $this->query('ContactsManager');
978
-	}
979
-
980
-	/**
981
-	 * @return \OC\Encryption\Manager
982
-	 */
983
-	public function getEncryptionManager() {
984
-		return $this->query('EncryptionManager');
985
-	}
986
-
987
-	/**
988
-	 * @return \OC\Encryption\File
989
-	 */
990
-	public function getEncryptionFilesHelper() {
991
-		return $this->query('EncryptionFileHelper');
992
-	}
993
-
994
-	/**
995
-	 * @return \OCP\Encryption\Keys\IStorage
996
-	 */
997
-	public function getEncryptionKeyStorage() {
998
-		return $this->query('EncryptionKeyStorage');
999
-	}
1000
-
1001
-	/**
1002
-	 * The current request object holding all information about the request
1003
-	 * currently being processed is returned from this method.
1004
-	 * In case the current execution was not initiated by a web request null is returned
1005
-	 *
1006
-	 * @return \OCP\IRequest
1007
-	 */
1008
-	public function getRequest() {
1009
-		return $this->query('Request');
1010
-	}
1011
-
1012
-	/**
1013
-	 * Returns the preview manager which can create preview images for a given file
1014
-	 *
1015
-	 * @return \OCP\IPreview
1016
-	 */
1017
-	public function getPreviewManager() {
1018
-		return $this->query('PreviewManager');
1019
-	}
1020
-
1021
-	/**
1022
-	 * Returns the tag manager which can get and set tags for different object types
1023
-	 *
1024
-	 * @see \OCP\ITagManager::load()
1025
-	 * @return \OCP\ITagManager
1026
-	 */
1027
-	public function getTagManager() {
1028
-		return $this->query('TagManager');
1029
-	}
1030
-
1031
-	/**
1032
-	 * Returns the system-tag manager
1033
-	 *
1034
-	 * @return \OCP\SystemTag\ISystemTagManager
1035
-	 *
1036
-	 * @since 9.0.0
1037
-	 */
1038
-	public function getSystemTagManager() {
1039
-		return $this->query('SystemTagManager');
1040
-	}
1041
-
1042
-	/**
1043
-	 * Returns the system-tag object mapper
1044
-	 *
1045
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1046
-	 *
1047
-	 * @since 9.0.0
1048
-	 */
1049
-	public function getSystemTagObjectMapper() {
1050
-		return $this->query('SystemTagObjectMapper');
1051
-	}
1052
-
1053
-	/**
1054
-	 * Returns the avatar manager, used for avatar functionality
1055
-	 *
1056
-	 * @return \OCP\IAvatarManager
1057
-	 */
1058
-	public function getAvatarManager() {
1059
-		return $this->query('AvatarManager');
1060
-	}
1061
-
1062
-	/**
1063
-	 * Returns the root folder of ownCloud's data directory
1064
-	 *
1065
-	 * @return \OCP\Files\IRootFolder
1066
-	 */
1067
-	public function getRootFolder() {
1068
-		return $this->query('LazyRootFolder');
1069
-	}
1070
-
1071
-	/**
1072
-	 * Returns the root folder of ownCloud's data directory
1073
-	 * This is the lazy variant so this gets only initialized once it
1074
-	 * is actually used.
1075
-	 *
1076
-	 * @return \OCP\Files\IRootFolder
1077
-	 */
1078
-	public function getLazyRootFolder() {
1079
-		return $this->query('LazyRootFolder');
1080
-	}
1081
-
1082
-	/**
1083
-	 * Returns a view to ownCloud's files folder
1084
-	 *
1085
-	 * @param string $userId user ID
1086
-	 * @return \OCP\Files\Folder|null
1087
-	 */
1088
-	public function getUserFolder($userId = null) {
1089
-		if ($userId === null) {
1090
-			$user = $this->getUserSession()->getUser();
1091
-			if (!$user) {
1092
-				return null;
1093
-			}
1094
-			$userId = $user->getUID();
1095
-		}
1096
-		$root = $this->getRootFolder();
1097
-		return $root->getUserFolder($userId);
1098
-	}
1099
-
1100
-	/**
1101
-	 * Returns an app-specific view in ownClouds data directory
1102
-	 *
1103
-	 * @return \OCP\Files\Folder
1104
-	 * @deprecated since 9.2.0 use IAppData
1105
-	 */
1106
-	public function getAppFolder() {
1107
-		$dir = '/' . \OC_App::getCurrentApp();
1108
-		$root = $this->getRootFolder();
1109
-		if (!$root->nodeExists($dir)) {
1110
-			$folder = $root->newFolder($dir);
1111
-		} else {
1112
-			$folder = $root->get($dir);
1113
-		}
1114
-		return $folder;
1115
-	}
1116
-
1117
-	/**
1118
-	 * @return \OC\User\Manager
1119
-	 */
1120
-	public function getUserManager() {
1121
-		return $this->query('UserManager');
1122
-	}
1123
-
1124
-	/**
1125
-	 * @return \OC\Group\Manager
1126
-	 */
1127
-	public function getGroupManager() {
1128
-		return $this->query('GroupManager');
1129
-	}
1130
-
1131
-	/**
1132
-	 * @return \OC\User\Session
1133
-	 */
1134
-	public function getUserSession() {
1135
-		return $this->query('UserSession');
1136
-	}
1137
-
1138
-	/**
1139
-	 * @return \OCP\ISession
1140
-	 */
1141
-	public function getSession() {
1142
-		return $this->query('UserSession')->getSession();
1143
-	}
1144
-
1145
-	/**
1146
-	 * @param \OCP\ISession $session
1147
-	 */
1148
-	public function setSession(\OCP\ISession $session) {
1149
-		$this->query(SessionStorage::class)->setSession($session);
1150
-		$this->query('UserSession')->setSession($session);
1151
-		$this->query(Store::class)->setSession($session);
1152
-	}
1153
-
1154
-	/**
1155
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1156
-	 */
1157
-	public function getTwoFactorAuthManager() {
1158
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1159
-	}
1160
-
1161
-	/**
1162
-	 * @return \OC\NavigationManager
1163
-	 */
1164
-	public function getNavigationManager() {
1165
-		return $this->query('NavigationManager');
1166
-	}
1167
-
1168
-	/**
1169
-	 * @return \OCP\IConfig
1170
-	 */
1171
-	public function getConfig() {
1172
-		return $this->query('AllConfig');
1173
-	}
1174
-
1175
-	/**
1176
-	 * @internal For internal use only
1177
-	 * @return \OC\SystemConfig
1178
-	 */
1179
-	public function getSystemConfig() {
1180
-		return $this->query('SystemConfig');
1181
-	}
1182
-
1183
-	/**
1184
-	 * Returns the app config manager
1185
-	 *
1186
-	 * @return \OCP\IAppConfig
1187
-	 */
1188
-	public function getAppConfig() {
1189
-		return $this->query('AppConfig');
1190
-	}
1191
-
1192
-	/**
1193
-	 * @return \OCP\L10N\IFactory
1194
-	 */
1195
-	public function getL10NFactory() {
1196
-		return $this->query('L10NFactory');
1197
-	}
1198
-
1199
-	/**
1200
-	 * get an L10N instance
1201
-	 *
1202
-	 * @param string $app appid
1203
-	 * @param string $lang
1204
-	 * @return IL10N
1205
-	 */
1206
-	public function getL10N($app, $lang = null) {
1207
-		return $this->getL10NFactory()->get($app, $lang);
1208
-	}
1209
-
1210
-	/**
1211
-	 * @return \OCP\IURLGenerator
1212
-	 */
1213
-	public function getURLGenerator() {
1214
-		return $this->query('URLGenerator');
1215
-	}
1216
-
1217
-	/**
1218
-	 * @return \OCP\IHelper
1219
-	 */
1220
-	public function getHelper() {
1221
-		return $this->query('AppHelper');
1222
-	}
1223
-
1224
-	/**
1225
-	 * @return AppFetcher
1226
-	 */
1227
-	public function getAppFetcher() {
1228
-		return $this->query('AppFetcher');
1229
-	}
1230
-
1231
-	/**
1232
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1233
-	 * getMemCacheFactory() instead.
1234
-	 *
1235
-	 * @return \OCP\ICache
1236
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1237
-	 */
1238
-	public function getCache() {
1239
-		return $this->query('UserCache');
1240
-	}
1241
-
1242
-	/**
1243
-	 * Returns an \OCP\CacheFactory instance
1244
-	 *
1245
-	 * @return \OCP\ICacheFactory
1246
-	 */
1247
-	public function getMemCacheFactory() {
1248
-		return $this->query('MemCacheFactory');
1249
-	}
1250
-
1251
-	/**
1252
-	 * Returns an \OC\RedisFactory instance
1253
-	 *
1254
-	 * @return \OC\RedisFactory
1255
-	 */
1256
-	public function getGetRedisFactory() {
1257
-		return $this->query('RedisFactory');
1258
-	}
1259
-
1260
-
1261
-	/**
1262
-	 * Returns the current session
1263
-	 *
1264
-	 * @return \OCP\IDBConnection
1265
-	 */
1266
-	public function getDatabaseConnection() {
1267
-		return $this->query('DatabaseConnection');
1268
-	}
1269
-
1270
-	/**
1271
-	 * Returns the activity manager
1272
-	 *
1273
-	 * @return \OCP\Activity\IManager
1274
-	 */
1275
-	public function getActivityManager() {
1276
-		return $this->query('ActivityManager');
1277
-	}
1278
-
1279
-	/**
1280
-	 * Returns an job list for controlling background jobs
1281
-	 *
1282
-	 * @return \OCP\BackgroundJob\IJobList
1283
-	 */
1284
-	public function getJobList() {
1285
-		return $this->query('JobList');
1286
-	}
1287
-
1288
-	/**
1289
-	 * Returns a logger instance
1290
-	 *
1291
-	 * @return \OCP\ILogger
1292
-	 */
1293
-	public function getLogger() {
1294
-		return $this->query('Logger');
1295
-	}
1296
-
1297
-	/**
1298
-	 * Returns a router for generating and matching urls
1299
-	 *
1300
-	 * @return \OCP\Route\IRouter
1301
-	 */
1302
-	public function getRouter() {
1303
-		return $this->query('Router');
1304
-	}
1305
-
1306
-	/**
1307
-	 * Returns a search instance
1308
-	 *
1309
-	 * @return \OCP\ISearch
1310
-	 */
1311
-	public function getSearch() {
1312
-		return $this->query('Search');
1313
-	}
1314
-
1315
-	/**
1316
-	 * Returns a SecureRandom instance
1317
-	 *
1318
-	 * @return \OCP\Security\ISecureRandom
1319
-	 */
1320
-	public function getSecureRandom() {
1321
-		return $this->query('SecureRandom');
1322
-	}
1323
-
1324
-	/**
1325
-	 * Returns a Crypto instance
1326
-	 *
1327
-	 * @return \OCP\Security\ICrypto
1328
-	 */
1329
-	public function getCrypto() {
1330
-		return $this->query('Crypto');
1331
-	}
1332
-
1333
-	/**
1334
-	 * Returns a Hasher instance
1335
-	 *
1336
-	 * @return \OCP\Security\IHasher
1337
-	 */
1338
-	public function getHasher() {
1339
-		return $this->query('Hasher');
1340
-	}
1341
-
1342
-	/**
1343
-	 * Returns a CredentialsManager instance
1344
-	 *
1345
-	 * @return \OCP\Security\ICredentialsManager
1346
-	 */
1347
-	public function getCredentialsManager() {
1348
-		return $this->query('CredentialsManager');
1349
-	}
1350
-
1351
-	/**
1352
-	 * Returns an instance of the HTTP helper class
1353
-	 *
1354
-	 * @deprecated Use getHTTPClientService()
1355
-	 * @return \OC\HTTPHelper
1356
-	 */
1357
-	public function getHTTPHelper() {
1358
-		return $this->query('HTTPHelper');
1359
-	}
1360
-
1361
-	/**
1362
-	 * Get the certificate manager for the user
1363
-	 *
1364
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1365
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1366
-	 */
1367
-	public function getCertificateManager($userId = '') {
1368
-		if ($userId === '') {
1369
-			$userSession = $this->getUserSession();
1370
-			$user = $userSession->getUser();
1371
-			if (is_null($user)) {
1372
-				return null;
1373
-			}
1374
-			$userId = $user->getUID();
1375
-		}
1376
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1377
-	}
1378
-
1379
-	/**
1380
-	 * Returns an instance of the HTTP client service
1381
-	 *
1382
-	 * @return \OCP\Http\Client\IClientService
1383
-	 */
1384
-	public function getHTTPClientService() {
1385
-		return $this->query('HttpClientService');
1386
-	}
1387
-
1388
-	/**
1389
-	 * Create a new event source
1390
-	 *
1391
-	 * @return \OCP\IEventSource
1392
-	 */
1393
-	public function createEventSource() {
1394
-		return new \OC_EventSource();
1395
-	}
1396
-
1397
-	/**
1398
-	 * Get the active event logger
1399
-	 *
1400
-	 * The returned logger only logs data when debug mode is enabled
1401
-	 *
1402
-	 * @return \OCP\Diagnostics\IEventLogger
1403
-	 */
1404
-	public function getEventLogger() {
1405
-		return $this->query('EventLogger');
1406
-	}
1407
-
1408
-	/**
1409
-	 * Get the active query logger
1410
-	 *
1411
-	 * The returned logger only logs data when debug mode is enabled
1412
-	 *
1413
-	 * @return \OCP\Diagnostics\IQueryLogger
1414
-	 */
1415
-	public function getQueryLogger() {
1416
-		return $this->query('QueryLogger');
1417
-	}
1418
-
1419
-	/**
1420
-	 * Get the manager for temporary files and folders
1421
-	 *
1422
-	 * @return \OCP\ITempManager
1423
-	 */
1424
-	public function getTempManager() {
1425
-		return $this->query('TempManager');
1426
-	}
1427
-
1428
-	/**
1429
-	 * Get the app manager
1430
-	 *
1431
-	 * @return \OCP\App\IAppManager
1432
-	 */
1433
-	public function getAppManager() {
1434
-		return $this->query('AppManager');
1435
-	}
1436
-
1437
-	/**
1438
-	 * Creates a new mailer
1439
-	 *
1440
-	 * @return \OCP\Mail\IMailer
1441
-	 */
1442
-	public function getMailer() {
1443
-		return $this->query('Mailer');
1444
-	}
1445
-
1446
-	/**
1447
-	 * Get the webroot
1448
-	 *
1449
-	 * @return string
1450
-	 */
1451
-	public function getWebRoot() {
1452
-		return $this->webRoot;
1453
-	}
1454
-
1455
-	/**
1456
-	 * @return \OC\OCSClient
1457
-	 */
1458
-	public function getOcsClient() {
1459
-		return $this->query('OcsClient');
1460
-	}
1461
-
1462
-	/**
1463
-	 * @return \OCP\IDateTimeZone
1464
-	 */
1465
-	public function getDateTimeZone() {
1466
-		return $this->query('DateTimeZone');
1467
-	}
1468
-
1469
-	/**
1470
-	 * @return \OCP\IDateTimeFormatter
1471
-	 */
1472
-	public function getDateTimeFormatter() {
1473
-		return $this->query('DateTimeFormatter');
1474
-	}
1475
-
1476
-	/**
1477
-	 * @return \OCP\Files\Config\IMountProviderCollection
1478
-	 */
1479
-	public function getMountProviderCollection() {
1480
-		return $this->query('MountConfigManager');
1481
-	}
1482
-
1483
-	/**
1484
-	 * Get the IniWrapper
1485
-	 *
1486
-	 * @return IniGetWrapper
1487
-	 */
1488
-	public function getIniWrapper() {
1489
-		return $this->query('IniWrapper');
1490
-	}
1491
-
1492
-	/**
1493
-	 * @return \OCP\Command\IBus
1494
-	 */
1495
-	public function getCommandBus() {
1496
-		return $this->query('AsyncCommandBus');
1497
-	}
1498
-
1499
-	/**
1500
-	 * Get the trusted domain helper
1501
-	 *
1502
-	 * @return TrustedDomainHelper
1503
-	 */
1504
-	public function getTrustedDomainHelper() {
1505
-		return $this->query('TrustedDomainHelper');
1506
-	}
1507
-
1508
-	/**
1509
-	 * Get the locking provider
1510
-	 *
1511
-	 * @return \OCP\Lock\ILockingProvider
1512
-	 * @since 8.1.0
1513
-	 */
1514
-	public function getLockingProvider() {
1515
-		return $this->query('LockingProvider');
1516
-	}
1517
-
1518
-	/**
1519
-	 * @return \OCP\Files\Mount\IMountManager
1520
-	 **/
1521
-	function getMountManager() {
1522
-		return $this->query('MountManager');
1523
-	}
1524
-
1525
-	/** @return \OCP\Files\Config\IUserMountCache */
1526
-	function getUserMountCache() {
1527
-		return $this->query('UserMountCache');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Get the MimeTypeDetector
1532
-	 *
1533
-	 * @return \OCP\Files\IMimeTypeDetector
1534
-	 */
1535
-	public function getMimeTypeDetector() {
1536
-		return $this->query('MimeTypeDetector');
1537
-	}
1538
-
1539
-	/**
1540
-	 * Get the MimeTypeLoader
1541
-	 *
1542
-	 * @return \OCP\Files\IMimeTypeLoader
1543
-	 */
1544
-	public function getMimeTypeLoader() {
1545
-		return $this->query('MimeTypeLoader');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Get the manager of all the capabilities
1550
-	 *
1551
-	 * @return \OC\CapabilitiesManager
1552
-	 */
1553
-	public function getCapabilitiesManager() {
1554
-		return $this->query('CapabilitiesManager');
1555
-	}
1556
-
1557
-	/**
1558
-	 * Get the EventDispatcher
1559
-	 *
1560
-	 * @return EventDispatcherInterface
1561
-	 * @since 8.2.0
1562
-	 */
1563
-	public function getEventDispatcher() {
1564
-		return $this->query('EventDispatcher');
1565
-	}
1566
-
1567
-	/**
1568
-	 * Get the Notification Manager
1569
-	 *
1570
-	 * @return \OCP\Notification\IManager
1571
-	 * @since 8.2.0
1572
-	 */
1573
-	public function getNotificationManager() {
1574
-		return $this->query('NotificationManager');
1575
-	}
1576
-
1577
-	/**
1578
-	 * @return \OCP\Comments\ICommentsManager
1579
-	 */
1580
-	public function getCommentsManager() {
1581
-		return $this->query('CommentsManager');
1582
-	}
1583
-
1584
-	/**
1585
-	 * @return \OCA\Theming\ThemingDefaults
1586
-	 */
1587
-	public function getThemingDefaults() {
1588
-		return $this->query('ThemingDefaults');
1589
-	}
1590
-
1591
-	/**
1592
-	 * @return \OC\IntegrityCheck\Checker
1593
-	 */
1594
-	public function getIntegrityCodeChecker() {
1595
-		return $this->query('IntegrityCodeChecker');
1596
-	}
1597
-
1598
-	/**
1599
-	 * @return \OC\Session\CryptoWrapper
1600
-	 */
1601
-	public function getSessionCryptoWrapper() {
1602
-		return $this->query('CryptoWrapper');
1603
-	}
1604
-
1605
-	/**
1606
-	 * @return CsrfTokenManager
1607
-	 */
1608
-	public function getCsrfTokenManager() {
1609
-		return $this->query('CsrfTokenManager');
1610
-	}
1611
-
1612
-	/**
1613
-	 * @return Throttler
1614
-	 */
1615
-	public function getBruteForceThrottler() {
1616
-		return $this->query('Throttler');
1617
-	}
1618
-
1619
-	/**
1620
-	 * @return IContentSecurityPolicyManager
1621
-	 */
1622
-	public function getContentSecurityPolicyManager() {
1623
-		return $this->query('ContentSecurityPolicyManager');
1624
-	}
1625
-
1626
-	/**
1627
-	 * @return ContentSecurityPolicyNonceManager
1628
-	 */
1629
-	public function getContentSecurityPolicyNonceManager() {
1630
-		return $this->query('ContentSecurityPolicyNonceManager');
1631
-	}
1632
-
1633
-	/**
1634
-	 * Not a public API as of 8.2, wait for 9.0
1635
-	 *
1636
-	 * @return \OCA\Files_External\Service\BackendService
1637
-	 */
1638
-	public function getStoragesBackendService() {
1639
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1640
-	}
1641
-
1642
-	/**
1643
-	 * Not a public API as of 8.2, wait for 9.0
1644
-	 *
1645
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1646
-	 */
1647
-	public function getGlobalStoragesService() {
1648
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1649
-	}
1650
-
1651
-	/**
1652
-	 * Not a public API as of 8.2, wait for 9.0
1653
-	 *
1654
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1655
-	 */
1656
-	public function getUserGlobalStoragesService() {
1657
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1658
-	}
1659
-
1660
-	/**
1661
-	 * Not a public API as of 8.2, wait for 9.0
1662
-	 *
1663
-	 * @return \OCA\Files_External\Service\UserStoragesService
1664
-	 */
1665
-	public function getUserStoragesService() {
1666
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1667
-	}
1668
-
1669
-	/**
1670
-	 * @return \OCP\Share\IManager
1671
-	 */
1672
-	public function getShareManager() {
1673
-		return $this->query('ShareManager');
1674
-	}
1675
-
1676
-	/**
1677
-	 * Returns the LDAP Provider
1678
-	 *
1679
-	 * @return \OCP\LDAP\ILDAPProvider
1680
-	 */
1681
-	public function getLDAPProvider() {
1682
-		return $this->query('LDAPProvider');
1683
-	}
1684
-
1685
-	/**
1686
-	 * @return \OCP\Settings\IManager
1687
-	 */
1688
-	public function getSettingsManager() {
1689
-		return $this->query('SettingsManager');
1690
-	}
1691
-
1692
-	/**
1693
-	 * @return \OCP\Files\IAppData
1694
-	 */
1695
-	public function getAppDataDir($app) {
1696
-		/** @var \OC\Files\AppData\Factory $factory */
1697
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1698
-		return $factory->get($app);
1699
-	}
1700
-
1701
-	/**
1702
-	 * @return \OCP\Lockdown\ILockdownManager
1703
-	 */
1704
-	public function getLockdownManager() {
1705
-		return $this->query('LockdownManager');
1706
-	}
1707
-
1708
-	/**
1709
-	 * @return \OCP\Federation\ICloudIdManager
1710
-	 */
1711
-	public function getCloudIdManager() {
1712
-		return $this->query(ICloudIdManager::class);
1713
-	}
816
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
817
+            if (isset($prefixes['OCA\\Theming\\'])) {
818
+                $classExists = true;
819
+            } else {
820
+                $classExists = false;
821
+            }
822
+
823
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
824
+                return new ThemingDefaults(
825
+                    $c->getConfig(),
826
+                    $c->getL10N('theming'),
827
+                    $c->getURLGenerator(),
828
+                    new \OC_Defaults(),
829
+                    $c->getAppDataDir('theming'),
830
+                    $c->getMemCacheFactory()
831
+                );
832
+            }
833
+            return new \OC_Defaults();
834
+        });
835
+        $this->registerService(EventDispatcher::class, function () {
836
+            return new EventDispatcher();
837
+        });
838
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
839
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
840
+
841
+        $this->registerService('CryptoWrapper', function (Server $c) {
842
+            // FIXME: Instantiiated here due to cyclic dependency
843
+            $request = new Request(
844
+                [
845
+                    'get' => $_GET,
846
+                    'post' => $_POST,
847
+                    'files' => $_FILES,
848
+                    'server' => $_SERVER,
849
+                    'env' => $_ENV,
850
+                    'cookies' => $_COOKIE,
851
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
852
+                        ? $_SERVER['REQUEST_METHOD']
853
+                        : null,
854
+                ],
855
+                $c->getSecureRandom(),
856
+                $c->getConfig()
857
+            );
858
+
859
+            return new CryptoWrapper(
860
+                $c->getConfig(),
861
+                $c->getCrypto(),
862
+                $c->getSecureRandom(),
863
+                $request
864
+            );
865
+        });
866
+        $this->registerService('CsrfTokenManager', function (Server $c) {
867
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
868
+
869
+            return new CsrfTokenManager(
870
+                $tokenGenerator,
871
+                $c->query(SessionStorage::class)
872
+            );
873
+        });
874
+        $this->registerService(SessionStorage::class, function (Server $c) {
875
+            return new SessionStorage($c->getSession());
876
+        });
877
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
878
+            return new ContentSecurityPolicyManager();
879
+        });
880
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
881
+
882
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
883
+            return new ContentSecurityPolicyNonceManager(
884
+                $c->getCsrfTokenManager(),
885
+                $c->getRequest()
886
+            );
887
+        });
888
+
889
+        $this->registerService(\OCP\Share\IManager::class, function(Server $c) {
890
+            $config = $c->getConfig();
891
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
892
+            /** @var \OCP\Share\IProviderFactory $factory */
893
+            $factory = new $factoryClass($this);
894
+
895
+            $manager = new \OC\Share20\Manager(
896
+                $c->getLogger(),
897
+                $c->getConfig(),
898
+                $c->getSecureRandom(),
899
+                $c->getHasher(),
900
+                $c->getMountManager(),
901
+                $c->getGroupManager(),
902
+                $c->getL10N('core'),
903
+                $factory,
904
+                $c->getUserManager(),
905
+                $c->getLazyRootFolder(),
906
+                $c->getEventDispatcher()
907
+            );
908
+
909
+            return $manager;
910
+        });
911
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
912
+
913
+        $this->registerService('SettingsManager', function(Server $c) {
914
+            $manager = new \OC\Settings\Manager(
915
+                $c->getLogger(),
916
+                $c->getDatabaseConnection(),
917
+                $c->getL10N('lib'),
918
+                $c->getConfig(),
919
+                $c->getEncryptionManager(),
920
+                $c->getUserManager(),
921
+                $c->getLockingProvider(),
922
+                $c->getRequest(),
923
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
924
+                $c->getURLGenerator()
925
+            );
926
+            return $manager;
927
+        });
928
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
929
+            return new \OC\Files\AppData\Factory(
930
+                $c->getRootFolder(),
931
+                $c->getSystemConfig()
932
+            );
933
+        });
934
+
935
+        $this->registerService('LockdownManager', function (Server $c) {
936
+            return new LockdownManager(function() use ($c) {
937
+                return $c->getSession();
938
+            });
939
+        });
940
+
941
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
942
+            return new CloudIdManager();
943
+        });
944
+
945
+        /* To trick DI since we don't extend the DIContainer here */
946
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
947
+            return new CleanPreviewsBackgroundJob(
948
+                $c->getRootFolder(),
949
+                $c->getLogger(),
950
+                $c->getJobList(),
951
+                new TimeFactory()
952
+            );
953
+        });
954
+
955
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
956
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
957
+
958
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
959
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
960
+
961
+        $this->registerService(Defaults::class, function (Server $c) {
962
+            return new Defaults(
963
+                $c->getThemingDefaults()
964
+            );
965
+        });
966
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
967
+
968
+        $this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
969
+            return $c->query(\OCP\IUserSession::class)->getSession();
970
+        });
971
+    }
972
+
973
+    /**
974
+     * @return \OCP\Contacts\IManager
975
+     */
976
+    public function getContactsManager() {
977
+        return $this->query('ContactsManager');
978
+    }
979
+
980
+    /**
981
+     * @return \OC\Encryption\Manager
982
+     */
983
+    public function getEncryptionManager() {
984
+        return $this->query('EncryptionManager');
985
+    }
986
+
987
+    /**
988
+     * @return \OC\Encryption\File
989
+     */
990
+    public function getEncryptionFilesHelper() {
991
+        return $this->query('EncryptionFileHelper');
992
+    }
993
+
994
+    /**
995
+     * @return \OCP\Encryption\Keys\IStorage
996
+     */
997
+    public function getEncryptionKeyStorage() {
998
+        return $this->query('EncryptionKeyStorage');
999
+    }
1000
+
1001
+    /**
1002
+     * The current request object holding all information about the request
1003
+     * currently being processed is returned from this method.
1004
+     * In case the current execution was not initiated by a web request null is returned
1005
+     *
1006
+     * @return \OCP\IRequest
1007
+     */
1008
+    public function getRequest() {
1009
+        return $this->query('Request');
1010
+    }
1011
+
1012
+    /**
1013
+     * Returns the preview manager which can create preview images for a given file
1014
+     *
1015
+     * @return \OCP\IPreview
1016
+     */
1017
+    public function getPreviewManager() {
1018
+        return $this->query('PreviewManager');
1019
+    }
1020
+
1021
+    /**
1022
+     * Returns the tag manager which can get and set tags for different object types
1023
+     *
1024
+     * @see \OCP\ITagManager::load()
1025
+     * @return \OCP\ITagManager
1026
+     */
1027
+    public function getTagManager() {
1028
+        return $this->query('TagManager');
1029
+    }
1030
+
1031
+    /**
1032
+     * Returns the system-tag manager
1033
+     *
1034
+     * @return \OCP\SystemTag\ISystemTagManager
1035
+     *
1036
+     * @since 9.0.0
1037
+     */
1038
+    public function getSystemTagManager() {
1039
+        return $this->query('SystemTagManager');
1040
+    }
1041
+
1042
+    /**
1043
+     * Returns the system-tag object mapper
1044
+     *
1045
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1046
+     *
1047
+     * @since 9.0.0
1048
+     */
1049
+    public function getSystemTagObjectMapper() {
1050
+        return $this->query('SystemTagObjectMapper');
1051
+    }
1052
+
1053
+    /**
1054
+     * Returns the avatar manager, used for avatar functionality
1055
+     *
1056
+     * @return \OCP\IAvatarManager
1057
+     */
1058
+    public function getAvatarManager() {
1059
+        return $this->query('AvatarManager');
1060
+    }
1061
+
1062
+    /**
1063
+     * Returns the root folder of ownCloud's data directory
1064
+     *
1065
+     * @return \OCP\Files\IRootFolder
1066
+     */
1067
+    public function getRootFolder() {
1068
+        return $this->query('LazyRootFolder');
1069
+    }
1070
+
1071
+    /**
1072
+     * Returns the root folder of ownCloud's data directory
1073
+     * This is the lazy variant so this gets only initialized once it
1074
+     * is actually used.
1075
+     *
1076
+     * @return \OCP\Files\IRootFolder
1077
+     */
1078
+    public function getLazyRootFolder() {
1079
+        return $this->query('LazyRootFolder');
1080
+    }
1081
+
1082
+    /**
1083
+     * Returns a view to ownCloud's files folder
1084
+     *
1085
+     * @param string $userId user ID
1086
+     * @return \OCP\Files\Folder|null
1087
+     */
1088
+    public function getUserFolder($userId = null) {
1089
+        if ($userId === null) {
1090
+            $user = $this->getUserSession()->getUser();
1091
+            if (!$user) {
1092
+                return null;
1093
+            }
1094
+            $userId = $user->getUID();
1095
+        }
1096
+        $root = $this->getRootFolder();
1097
+        return $root->getUserFolder($userId);
1098
+    }
1099
+
1100
+    /**
1101
+     * Returns an app-specific view in ownClouds data directory
1102
+     *
1103
+     * @return \OCP\Files\Folder
1104
+     * @deprecated since 9.2.0 use IAppData
1105
+     */
1106
+    public function getAppFolder() {
1107
+        $dir = '/' . \OC_App::getCurrentApp();
1108
+        $root = $this->getRootFolder();
1109
+        if (!$root->nodeExists($dir)) {
1110
+            $folder = $root->newFolder($dir);
1111
+        } else {
1112
+            $folder = $root->get($dir);
1113
+        }
1114
+        return $folder;
1115
+    }
1116
+
1117
+    /**
1118
+     * @return \OC\User\Manager
1119
+     */
1120
+    public function getUserManager() {
1121
+        return $this->query('UserManager');
1122
+    }
1123
+
1124
+    /**
1125
+     * @return \OC\Group\Manager
1126
+     */
1127
+    public function getGroupManager() {
1128
+        return $this->query('GroupManager');
1129
+    }
1130
+
1131
+    /**
1132
+     * @return \OC\User\Session
1133
+     */
1134
+    public function getUserSession() {
1135
+        return $this->query('UserSession');
1136
+    }
1137
+
1138
+    /**
1139
+     * @return \OCP\ISession
1140
+     */
1141
+    public function getSession() {
1142
+        return $this->query('UserSession')->getSession();
1143
+    }
1144
+
1145
+    /**
1146
+     * @param \OCP\ISession $session
1147
+     */
1148
+    public function setSession(\OCP\ISession $session) {
1149
+        $this->query(SessionStorage::class)->setSession($session);
1150
+        $this->query('UserSession')->setSession($session);
1151
+        $this->query(Store::class)->setSession($session);
1152
+    }
1153
+
1154
+    /**
1155
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1156
+     */
1157
+    public function getTwoFactorAuthManager() {
1158
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1159
+    }
1160
+
1161
+    /**
1162
+     * @return \OC\NavigationManager
1163
+     */
1164
+    public function getNavigationManager() {
1165
+        return $this->query('NavigationManager');
1166
+    }
1167
+
1168
+    /**
1169
+     * @return \OCP\IConfig
1170
+     */
1171
+    public function getConfig() {
1172
+        return $this->query('AllConfig');
1173
+    }
1174
+
1175
+    /**
1176
+     * @internal For internal use only
1177
+     * @return \OC\SystemConfig
1178
+     */
1179
+    public function getSystemConfig() {
1180
+        return $this->query('SystemConfig');
1181
+    }
1182
+
1183
+    /**
1184
+     * Returns the app config manager
1185
+     *
1186
+     * @return \OCP\IAppConfig
1187
+     */
1188
+    public function getAppConfig() {
1189
+        return $this->query('AppConfig');
1190
+    }
1191
+
1192
+    /**
1193
+     * @return \OCP\L10N\IFactory
1194
+     */
1195
+    public function getL10NFactory() {
1196
+        return $this->query('L10NFactory');
1197
+    }
1198
+
1199
+    /**
1200
+     * get an L10N instance
1201
+     *
1202
+     * @param string $app appid
1203
+     * @param string $lang
1204
+     * @return IL10N
1205
+     */
1206
+    public function getL10N($app, $lang = null) {
1207
+        return $this->getL10NFactory()->get($app, $lang);
1208
+    }
1209
+
1210
+    /**
1211
+     * @return \OCP\IURLGenerator
1212
+     */
1213
+    public function getURLGenerator() {
1214
+        return $this->query('URLGenerator');
1215
+    }
1216
+
1217
+    /**
1218
+     * @return \OCP\IHelper
1219
+     */
1220
+    public function getHelper() {
1221
+        return $this->query('AppHelper');
1222
+    }
1223
+
1224
+    /**
1225
+     * @return AppFetcher
1226
+     */
1227
+    public function getAppFetcher() {
1228
+        return $this->query('AppFetcher');
1229
+    }
1230
+
1231
+    /**
1232
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1233
+     * getMemCacheFactory() instead.
1234
+     *
1235
+     * @return \OCP\ICache
1236
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1237
+     */
1238
+    public function getCache() {
1239
+        return $this->query('UserCache');
1240
+    }
1241
+
1242
+    /**
1243
+     * Returns an \OCP\CacheFactory instance
1244
+     *
1245
+     * @return \OCP\ICacheFactory
1246
+     */
1247
+    public function getMemCacheFactory() {
1248
+        return $this->query('MemCacheFactory');
1249
+    }
1250
+
1251
+    /**
1252
+     * Returns an \OC\RedisFactory instance
1253
+     *
1254
+     * @return \OC\RedisFactory
1255
+     */
1256
+    public function getGetRedisFactory() {
1257
+        return $this->query('RedisFactory');
1258
+    }
1259
+
1260
+
1261
+    /**
1262
+     * Returns the current session
1263
+     *
1264
+     * @return \OCP\IDBConnection
1265
+     */
1266
+    public function getDatabaseConnection() {
1267
+        return $this->query('DatabaseConnection');
1268
+    }
1269
+
1270
+    /**
1271
+     * Returns the activity manager
1272
+     *
1273
+     * @return \OCP\Activity\IManager
1274
+     */
1275
+    public function getActivityManager() {
1276
+        return $this->query('ActivityManager');
1277
+    }
1278
+
1279
+    /**
1280
+     * Returns an job list for controlling background jobs
1281
+     *
1282
+     * @return \OCP\BackgroundJob\IJobList
1283
+     */
1284
+    public function getJobList() {
1285
+        return $this->query('JobList');
1286
+    }
1287
+
1288
+    /**
1289
+     * Returns a logger instance
1290
+     *
1291
+     * @return \OCP\ILogger
1292
+     */
1293
+    public function getLogger() {
1294
+        return $this->query('Logger');
1295
+    }
1296
+
1297
+    /**
1298
+     * Returns a router for generating and matching urls
1299
+     *
1300
+     * @return \OCP\Route\IRouter
1301
+     */
1302
+    public function getRouter() {
1303
+        return $this->query('Router');
1304
+    }
1305
+
1306
+    /**
1307
+     * Returns a search instance
1308
+     *
1309
+     * @return \OCP\ISearch
1310
+     */
1311
+    public function getSearch() {
1312
+        return $this->query('Search');
1313
+    }
1314
+
1315
+    /**
1316
+     * Returns a SecureRandom instance
1317
+     *
1318
+     * @return \OCP\Security\ISecureRandom
1319
+     */
1320
+    public function getSecureRandom() {
1321
+        return $this->query('SecureRandom');
1322
+    }
1323
+
1324
+    /**
1325
+     * Returns a Crypto instance
1326
+     *
1327
+     * @return \OCP\Security\ICrypto
1328
+     */
1329
+    public function getCrypto() {
1330
+        return $this->query('Crypto');
1331
+    }
1332
+
1333
+    /**
1334
+     * Returns a Hasher instance
1335
+     *
1336
+     * @return \OCP\Security\IHasher
1337
+     */
1338
+    public function getHasher() {
1339
+        return $this->query('Hasher');
1340
+    }
1341
+
1342
+    /**
1343
+     * Returns a CredentialsManager instance
1344
+     *
1345
+     * @return \OCP\Security\ICredentialsManager
1346
+     */
1347
+    public function getCredentialsManager() {
1348
+        return $this->query('CredentialsManager');
1349
+    }
1350
+
1351
+    /**
1352
+     * Returns an instance of the HTTP helper class
1353
+     *
1354
+     * @deprecated Use getHTTPClientService()
1355
+     * @return \OC\HTTPHelper
1356
+     */
1357
+    public function getHTTPHelper() {
1358
+        return $this->query('HTTPHelper');
1359
+    }
1360
+
1361
+    /**
1362
+     * Get the certificate manager for the user
1363
+     *
1364
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1365
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1366
+     */
1367
+    public function getCertificateManager($userId = '') {
1368
+        if ($userId === '') {
1369
+            $userSession = $this->getUserSession();
1370
+            $user = $userSession->getUser();
1371
+            if (is_null($user)) {
1372
+                return null;
1373
+            }
1374
+            $userId = $user->getUID();
1375
+        }
1376
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1377
+    }
1378
+
1379
+    /**
1380
+     * Returns an instance of the HTTP client service
1381
+     *
1382
+     * @return \OCP\Http\Client\IClientService
1383
+     */
1384
+    public function getHTTPClientService() {
1385
+        return $this->query('HttpClientService');
1386
+    }
1387
+
1388
+    /**
1389
+     * Create a new event source
1390
+     *
1391
+     * @return \OCP\IEventSource
1392
+     */
1393
+    public function createEventSource() {
1394
+        return new \OC_EventSource();
1395
+    }
1396
+
1397
+    /**
1398
+     * Get the active event logger
1399
+     *
1400
+     * The returned logger only logs data when debug mode is enabled
1401
+     *
1402
+     * @return \OCP\Diagnostics\IEventLogger
1403
+     */
1404
+    public function getEventLogger() {
1405
+        return $this->query('EventLogger');
1406
+    }
1407
+
1408
+    /**
1409
+     * Get the active query logger
1410
+     *
1411
+     * The returned logger only logs data when debug mode is enabled
1412
+     *
1413
+     * @return \OCP\Diagnostics\IQueryLogger
1414
+     */
1415
+    public function getQueryLogger() {
1416
+        return $this->query('QueryLogger');
1417
+    }
1418
+
1419
+    /**
1420
+     * Get the manager for temporary files and folders
1421
+     *
1422
+     * @return \OCP\ITempManager
1423
+     */
1424
+    public function getTempManager() {
1425
+        return $this->query('TempManager');
1426
+    }
1427
+
1428
+    /**
1429
+     * Get the app manager
1430
+     *
1431
+     * @return \OCP\App\IAppManager
1432
+     */
1433
+    public function getAppManager() {
1434
+        return $this->query('AppManager');
1435
+    }
1436
+
1437
+    /**
1438
+     * Creates a new mailer
1439
+     *
1440
+     * @return \OCP\Mail\IMailer
1441
+     */
1442
+    public function getMailer() {
1443
+        return $this->query('Mailer');
1444
+    }
1445
+
1446
+    /**
1447
+     * Get the webroot
1448
+     *
1449
+     * @return string
1450
+     */
1451
+    public function getWebRoot() {
1452
+        return $this->webRoot;
1453
+    }
1454
+
1455
+    /**
1456
+     * @return \OC\OCSClient
1457
+     */
1458
+    public function getOcsClient() {
1459
+        return $this->query('OcsClient');
1460
+    }
1461
+
1462
+    /**
1463
+     * @return \OCP\IDateTimeZone
1464
+     */
1465
+    public function getDateTimeZone() {
1466
+        return $this->query('DateTimeZone');
1467
+    }
1468
+
1469
+    /**
1470
+     * @return \OCP\IDateTimeFormatter
1471
+     */
1472
+    public function getDateTimeFormatter() {
1473
+        return $this->query('DateTimeFormatter');
1474
+    }
1475
+
1476
+    /**
1477
+     * @return \OCP\Files\Config\IMountProviderCollection
1478
+     */
1479
+    public function getMountProviderCollection() {
1480
+        return $this->query('MountConfigManager');
1481
+    }
1482
+
1483
+    /**
1484
+     * Get the IniWrapper
1485
+     *
1486
+     * @return IniGetWrapper
1487
+     */
1488
+    public function getIniWrapper() {
1489
+        return $this->query('IniWrapper');
1490
+    }
1491
+
1492
+    /**
1493
+     * @return \OCP\Command\IBus
1494
+     */
1495
+    public function getCommandBus() {
1496
+        return $this->query('AsyncCommandBus');
1497
+    }
1498
+
1499
+    /**
1500
+     * Get the trusted domain helper
1501
+     *
1502
+     * @return TrustedDomainHelper
1503
+     */
1504
+    public function getTrustedDomainHelper() {
1505
+        return $this->query('TrustedDomainHelper');
1506
+    }
1507
+
1508
+    /**
1509
+     * Get the locking provider
1510
+     *
1511
+     * @return \OCP\Lock\ILockingProvider
1512
+     * @since 8.1.0
1513
+     */
1514
+    public function getLockingProvider() {
1515
+        return $this->query('LockingProvider');
1516
+    }
1517
+
1518
+    /**
1519
+     * @return \OCP\Files\Mount\IMountManager
1520
+     **/
1521
+    function getMountManager() {
1522
+        return $this->query('MountManager');
1523
+    }
1524
+
1525
+    /** @return \OCP\Files\Config\IUserMountCache */
1526
+    function getUserMountCache() {
1527
+        return $this->query('UserMountCache');
1528
+    }
1529
+
1530
+    /**
1531
+     * Get the MimeTypeDetector
1532
+     *
1533
+     * @return \OCP\Files\IMimeTypeDetector
1534
+     */
1535
+    public function getMimeTypeDetector() {
1536
+        return $this->query('MimeTypeDetector');
1537
+    }
1538
+
1539
+    /**
1540
+     * Get the MimeTypeLoader
1541
+     *
1542
+     * @return \OCP\Files\IMimeTypeLoader
1543
+     */
1544
+    public function getMimeTypeLoader() {
1545
+        return $this->query('MimeTypeLoader');
1546
+    }
1547
+
1548
+    /**
1549
+     * Get the manager of all the capabilities
1550
+     *
1551
+     * @return \OC\CapabilitiesManager
1552
+     */
1553
+    public function getCapabilitiesManager() {
1554
+        return $this->query('CapabilitiesManager');
1555
+    }
1556
+
1557
+    /**
1558
+     * Get the EventDispatcher
1559
+     *
1560
+     * @return EventDispatcherInterface
1561
+     * @since 8.2.0
1562
+     */
1563
+    public function getEventDispatcher() {
1564
+        return $this->query('EventDispatcher');
1565
+    }
1566
+
1567
+    /**
1568
+     * Get the Notification Manager
1569
+     *
1570
+     * @return \OCP\Notification\IManager
1571
+     * @since 8.2.0
1572
+     */
1573
+    public function getNotificationManager() {
1574
+        return $this->query('NotificationManager');
1575
+    }
1576
+
1577
+    /**
1578
+     * @return \OCP\Comments\ICommentsManager
1579
+     */
1580
+    public function getCommentsManager() {
1581
+        return $this->query('CommentsManager');
1582
+    }
1583
+
1584
+    /**
1585
+     * @return \OCA\Theming\ThemingDefaults
1586
+     */
1587
+    public function getThemingDefaults() {
1588
+        return $this->query('ThemingDefaults');
1589
+    }
1590
+
1591
+    /**
1592
+     * @return \OC\IntegrityCheck\Checker
1593
+     */
1594
+    public function getIntegrityCodeChecker() {
1595
+        return $this->query('IntegrityCodeChecker');
1596
+    }
1597
+
1598
+    /**
1599
+     * @return \OC\Session\CryptoWrapper
1600
+     */
1601
+    public function getSessionCryptoWrapper() {
1602
+        return $this->query('CryptoWrapper');
1603
+    }
1604
+
1605
+    /**
1606
+     * @return CsrfTokenManager
1607
+     */
1608
+    public function getCsrfTokenManager() {
1609
+        return $this->query('CsrfTokenManager');
1610
+    }
1611
+
1612
+    /**
1613
+     * @return Throttler
1614
+     */
1615
+    public function getBruteForceThrottler() {
1616
+        return $this->query('Throttler');
1617
+    }
1618
+
1619
+    /**
1620
+     * @return IContentSecurityPolicyManager
1621
+     */
1622
+    public function getContentSecurityPolicyManager() {
1623
+        return $this->query('ContentSecurityPolicyManager');
1624
+    }
1625
+
1626
+    /**
1627
+     * @return ContentSecurityPolicyNonceManager
1628
+     */
1629
+    public function getContentSecurityPolicyNonceManager() {
1630
+        return $this->query('ContentSecurityPolicyNonceManager');
1631
+    }
1632
+
1633
+    /**
1634
+     * Not a public API as of 8.2, wait for 9.0
1635
+     *
1636
+     * @return \OCA\Files_External\Service\BackendService
1637
+     */
1638
+    public function getStoragesBackendService() {
1639
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1640
+    }
1641
+
1642
+    /**
1643
+     * Not a public API as of 8.2, wait for 9.0
1644
+     *
1645
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1646
+     */
1647
+    public function getGlobalStoragesService() {
1648
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1649
+    }
1650
+
1651
+    /**
1652
+     * Not a public API as of 8.2, wait for 9.0
1653
+     *
1654
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1655
+     */
1656
+    public function getUserGlobalStoragesService() {
1657
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1658
+    }
1659
+
1660
+    /**
1661
+     * Not a public API as of 8.2, wait for 9.0
1662
+     *
1663
+     * @return \OCA\Files_External\Service\UserStoragesService
1664
+     */
1665
+    public function getUserStoragesService() {
1666
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1667
+    }
1668
+
1669
+    /**
1670
+     * @return \OCP\Share\IManager
1671
+     */
1672
+    public function getShareManager() {
1673
+        return $this->query('ShareManager');
1674
+    }
1675
+
1676
+    /**
1677
+     * Returns the LDAP Provider
1678
+     *
1679
+     * @return \OCP\LDAP\ILDAPProvider
1680
+     */
1681
+    public function getLDAPProvider() {
1682
+        return $this->query('LDAPProvider');
1683
+    }
1684
+
1685
+    /**
1686
+     * @return \OCP\Settings\IManager
1687
+     */
1688
+    public function getSettingsManager() {
1689
+        return $this->query('SettingsManager');
1690
+    }
1691
+
1692
+    /**
1693
+     * @return \OCP\Files\IAppData
1694
+     */
1695
+    public function getAppDataDir($app) {
1696
+        /** @var \OC\Files\AppData\Factory $factory */
1697
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1698
+        return $factory->get($app);
1699
+    }
1700
+
1701
+    /**
1702
+     * @return \OCP\Lockdown\ILockdownManager
1703
+     */
1704
+    public function getLockdownManager() {
1705
+        return $this->query('LockdownManager');
1706
+    }
1707
+
1708
+    /**
1709
+     * @return \OCP\Federation\ICloudIdManager
1710
+     */
1711
+    public function getCloudIdManager() {
1712
+        return $this->query(ICloudIdManager::class);
1713
+    }
1714 1714
 }
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   +990 added lines, -990 removed lines patch added patch discarded remove patch
@@ -47,1027 +47,1027 @@
 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('password', $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('password', $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
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
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
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073 1073
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 4 patches
Doc Comments   +10 added lines, -4 removed lines patch added patch discarded remove patch
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 *
159 159
 	 * By default this excludes the automatically generated birthday calendar
160 160
 	 *
161
-	 * @param $principalUri
161
+	 * @param string $principalUri
162 162
 	 * @param bool $excludeBirthday
163 163
 	 * @return int
164 164
 	 */
@@ -303,6 +303,9 @@  discard block
 block discarded – undo
303 303
 		return array_values($calendars);
304 304
 	}
305 305
 
306
+	/**
307
+	 * @param string $principalUri
308
+	 */
306 309
 	public function getUsersOwnCalendars($principalUri) {
307 310
 		$principalUri = $this->convertPrincipal($principalUri, true);
308 311
 		$fields = array_values($this->propertyMap);
@@ -851,7 +854,7 @@  discard block
 block discarded – undo
851 854
 	 * calendar-data. If the result of a subsequent GET to this object is not
852 855
 	 * the exact same as this request body, you should omit the ETag.
853 856
 	 *
854
-	 * @param mixed $calendarId
857
+	 * @param integer $calendarId
855 858
 	 * @param string $objectUri
856 859
 	 * @param string $calendarData
857 860
 	 * @return string
@@ -894,7 +897,7 @@  discard block
 block discarded – undo
894 897
 	 * calendar-data. If the result of a subsequent GET to this object is not
895 898
 	 * the exact same as this request body, you should omit the ETag.
896 899
 	 *
897
-	 * @param mixed $calendarId
900
+	 * @param integer $calendarId
898 901
 	 * @param string $objectUri
899 902
 	 * @param string $calendarData
900 903
 	 * @return string
@@ -1309,7 +1312,7 @@  discard block
 block discarded – undo
1309 1312
 	 * @param string $principalUri
1310 1313
 	 * @param string $uri
1311 1314
 	 * @param array $properties
1312
-	 * @return mixed
1315
+	 * @return integer
1313 1316
 	 */
1314 1317
 	function createSubscription($principalUri, $uri, array $properties) {
1315 1318
 
@@ -1712,6 +1715,9 @@  discard block
 block discarded – undo
1712 1715
 		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1713 1716
 	}
1714 1717
 
1718
+	/**
1719
+	 * @param boolean $toV2
1720
+	 */
1715 1721
 	private function convertPrincipal($principalUri, $toV2) {
1716 1722
 		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1717 1723
 			list(, $name) = URLUtil::splitPath($principalUri);
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -808,7 +808,9 @@
 block discarded – undo
808 808
 		$stmt = $query->execute();
809 809
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
810 810
 
811
-		if(!$row) return null;
811
+		if(!$row) {
812
+		    return null;
813
+		}
812 814
 
813 815
 		return [
814 816
 				'id'            => $row['id'],
Please login to merge, or discard this patch.
Indentation   +1755 added lines, -1755 removed lines patch added patch discarded remove patch
@@ -59,1760 +59,1760 @@
 block discarded – undo
59 59
  */
60 60
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
61 61
 
62
-	const PERSONAL_CALENDAR_URI = 'personal';
63
-	const PERSONAL_CALENDAR_NAME = 'Personal';
64
-
65
-	/**
66
-	 * We need to specify a max date, because we need to stop *somewhere*
67
-	 *
68
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
69
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
-	 * in 2038-01-19 to avoid problems when the date is converted
71
-	 * to a unix timestamp.
72
-	 */
73
-	const MAX_DATE = '2038-01-01';
74
-
75
-	const ACCESS_PUBLIC = 4;
76
-	const CLASSIFICATION_PUBLIC = 0;
77
-	const CLASSIFICATION_PRIVATE = 1;
78
-	const CLASSIFICATION_CONFIDENTIAL = 2;
79
-
80
-	/**
81
-	 * List of CalDAV properties, and how they map to database field names
82
-	 * Add your own properties by simply adding on to this array.
83
-	 *
84
-	 * Note that only string-based properties are supported here.
85
-	 *
86
-	 * @var array
87
-	 */
88
-	public $propertyMap = [
89
-		'{DAV:}displayname'                          => 'displayname',
90
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
-	];
95
-
96
-	/**
97
-	 * List of subscription properties, and how they map to database field names.
98
-	 *
99
-	 * @var array
100
-	 */
101
-	public $subscriptionPropertyMap = [
102
-		'{DAV:}displayname'                                           => 'displayname',
103
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
-	];
110
-
111
-	/**
112
-	 * @var string[] Map of uid => display name
113
-	 */
114
-	protected $userDisplayNames;
115
-
116
-	/** @var IDBConnection */
117
-	private $db;
118
-
119
-	/** @var Backend */
120
-	private $sharingBackend;
121
-
122
-	/** @var Principal */
123
-	private $principalBackend;
124
-
125
-	/** @var IUserManager */
126
-	private $userManager;
127
-
128
-	/** @var ISecureRandom */
129
-	private $random;
130
-
131
-	/** @var EventDispatcherInterface */
132
-	private $dispatcher;
133
-
134
-	/** @var bool */
135
-	private $legacyEndpoint;
136
-
137
-	/**
138
-	 * CalDavBackend constructor.
139
-	 *
140
-	 * @param IDBConnection $db
141
-	 * @param Principal $principalBackend
142
-	 * @param IUserManager $userManager
143
-	 * @param ISecureRandom $random
144
-	 * @param EventDispatcherInterface $dispatcher
145
-	 * @param bool $legacyEndpoint
146
-	 */
147
-	public function __construct(IDBConnection $db,
148
-								Principal $principalBackend,
149
-								IUserManager $userManager,
150
-								ISecureRandom $random,
151
-								EventDispatcherInterface $dispatcher,
152
-								$legacyEndpoint = false) {
153
-		$this->db = $db;
154
-		$this->principalBackend = $principalBackend;
155
-		$this->userManager = $userManager;
156
-		$this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
-		$this->random = $random;
158
-		$this->dispatcher = $dispatcher;
159
-		$this->legacyEndpoint = $legacyEndpoint;
160
-	}
161
-
162
-	/**
163
-	 * Return the number of calendars for a principal
164
-	 *
165
-	 * By default this excludes the automatically generated birthday calendar
166
-	 *
167
-	 * @param $principalUri
168
-	 * @param bool $excludeBirthday
169
-	 * @return int
170
-	 */
171
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
-		$principalUri = $this->convertPrincipal($principalUri, true);
173
-		$query = $this->db->getQueryBuilder();
174
-		$query->select($query->createFunction('COUNT(*)'))
175
-			->from('calendars')
176
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
-
178
-		if ($excludeBirthday) {
179
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
-		}
181
-
182
-		return (int)$query->execute()->fetchColumn();
183
-	}
184
-
185
-	/**
186
-	 * Returns a list of calendars for a principal.
187
-	 *
188
-	 * Every project is an array with the following keys:
189
-	 *  * id, a unique id that will be used by other functions to modify the
190
-	 *    calendar. This can be the same as the uri or a database key.
191
-	 *  * uri, which the basename of the uri with which the calendar is
192
-	 *    accessed.
193
-	 *  * principaluri. The owner of the calendar. Almost always the same as
194
-	 *    principalUri passed to this method.
195
-	 *
196
-	 * Furthermore it can contain webdav properties in clark notation. A very
197
-	 * common one is '{DAV:}displayname'.
198
-	 *
199
-	 * Many clients also require:
200
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
-	 * For this property, you can just return an instance of
202
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
-	 *
204
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
-	 * ACL will automatically be put in read-only mode.
206
-	 *
207
-	 * @param string $principalUri
208
-	 * @return array
209
-	 */
210
-	function getCalendarsForUser($principalUri) {
211
-		$principalUriOriginal = $principalUri;
212
-		$principalUri = $this->convertPrincipal($principalUri, true);
213
-		$fields = array_values($this->propertyMap);
214
-		$fields[] = 'id';
215
-		$fields[] = 'uri';
216
-		$fields[] = 'synctoken';
217
-		$fields[] = 'components';
218
-		$fields[] = 'principaluri';
219
-		$fields[] = 'transparent';
220
-
221
-		// Making fields a comma-delimited list
222
-		$query = $this->db->getQueryBuilder();
223
-		$query->select($fields)->from('calendars')
224
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
-				->orderBy('calendarorder', 'ASC');
226
-		$stmt = $query->execute();
227
-
228
-		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
-
231
-			$components = [];
232
-			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
234
-			}
235
-
236
-			$calendar = [
237
-				'id' => $row['id'],
238
-				'uri' => $row['uri'],
239
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
-			];
246
-
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
248
-				$calendar[$xmlName] = $row[$dbName];
249
-			}
250
-
251
-			if (!isset($calendars[$calendar['id']])) {
252
-				$calendars[$calendar['id']] = $calendar;
253
-			}
254
-		}
255
-
256
-		$stmt->closeCursor();
257
-
258
-		// query for shared calendars
259
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
261
-
262
-		$fields = array_values($this->propertyMap);
263
-		$fields[] = 'a.id';
264
-		$fields[] = 'a.uri';
265
-		$fields[] = 'a.synctoken';
266
-		$fields[] = 'a.components';
267
-		$fields[] = 'a.principaluri';
268
-		$fields[] = 'a.transparent';
269
-		$fields[] = 's.access';
270
-		$query = $this->db->getQueryBuilder();
271
-		$result = $query->select($fields)
272
-			->from('dav_shares', 's')
273
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
-			->setParameter('type', 'calendar')
277
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
-			->execute();
279
-
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
282
-			if ($row['principaluri'] === $principalUri) {
283
-				continue;
284
-			}
285
-
286
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
287
-			if (isset($calendars[$row['id']])) {
288
-				if ($readOnly) {
289
-					// New share can not have more permissions then the old one.
290
-					continue;
291
-				}
292
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
293
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
294
-					// Old share is already read-write, no more permissions can be gained
295
-					continue;
296
-				}
297
-			}
298
-
299
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
300
-			$uri = $row['uri'] . '_shared_by_' . $name;
301
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
302
-			$components = [];
303
-			if ($row['components']) {
304
-				$components = explode(',',$row['components']);
305
-			}
306
-			$calendar = [
307
-				'id' => $row['id'],
308
-				'uri' => $uri,
309
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315
-				$readOnlyPropertyName => $readOnly,
316
-			];
317
-
318
-			foreach($this->propertyMap as $xmlName=>$dbName) {
319
-				$calendar[$xmlName] = $row[$dbName];
320
-			}
321
-
322
-			$calendars[$calendar['id']] = $calendar;
323
-		}
324
-		$result->closeCursor();
325
-
326
-		return array_values($calendars);
327
-	}
328
-
329
-	public function getUsersOwnCalendars($principalUri) {
330
-		$principalUri = $this->convertPrincipal($principalUri, true);
331
-		$fields = array_values($this->propertyMap);
332
-		$fields[] = 'id';
333
-		$fields[] = 'uri';
334
-		$fields[] = 'synctoken';
335
-		$fields[] = 'components';
336
-		$fields[] = 'principaluri';
337
-		$fields[] = 'transparent';
338
-		// Making fields a comma-delimited list
339
-		$query = $this->db->getQueryBuilder();
340
-		$query->select($fields)->from('calendars')
341
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
342
-			->orderBy('calendarorder', 'ASC');
343
-		$stmt = $query->execute();
344
-		$calendars = [];
345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346
-			$components = [];
347
-			if ($row['components']) {
348
-				$components = explode(',',$row['components']);
349
-			}
350
-			$calendar = [
351
-				'id' => $row['id'],
352
-				'uri' => $row['uri'],
353
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
358
-			];
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
360
-				$calendar[$xmlName] = $row[$dbName];
361
-			}
362
-			if (!isset($calendars[$calendar['id']])) {
363
-				$calendars[$calendar['id']] = $calendar;
364
-			}
365
-		}
366
-		$stmt->closeCursor();
367
-		return array_values($calendars);
368
-	}
369
-
370
-
371
-	private function getUserDisplayName($uid) {
372
-		if (!isset($this->userDisplayNames[$uid])) {
373
-			$user = $this->userManager->get($uid);
374
-
375
-			if ($user instanceof IUser) {
376
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
377
-			} else {
378
-				$this->userDisplayNames[$uid] = $uid;
379
-			}
380
-		}
381
-
382
-		return $this->userDisplayNames[$uid];
383
-	}
62
+    const PERSONAL_CALENDAR_URI = 'personal';
63
+    const PERSONAL_CALENDAR_NAME = 'Personal';
64
+
65
+    /**
66
+     * We need to specify a max date, because we need to stop *somewhere*
67
+     *
68
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
69
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
70
+     * in 2038-01-19 to avoid problems when the date is converted
71
+     * to a unix timestamp.
72
+     */
73
+    const MAX_DATE = '2038-01-01';
74
+
75
+    const ACCESS_PUBLIC = 4;
76
+    const CLASSIFICATION_PUBLIC = 0;
77
+    const CLASSIFICATION_PRIVATE = 1;
78
+    const CLASSIFICATION_CONFIDENTIAL = 2;
79
+
80
+    /**
81
+     * List of CalDAV properties, and how they map to database field names
82
+     * Add your own properties by simply adding on to this array.
83
+     *
84
+     * Note that only string-based properties are supported here.
85
+     *
86
+     * @var array
87
+     */
88
+    public $propertyMap = [
89
+        '{DAV:}displayname'                          => 'displayname',
90
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
91
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
92
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
93
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
94
+    ];
95
+
96
+    /**
97
+     * List of subscription properties, and how they map to database field names.
98
+     *
99
+     * @var array
100
+     */
101
+    public $subscriptionPropertyMap = [
102
+        '{DAV:}displayname'                                           => 'displayname',
103
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
104
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
105
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
106
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
107
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
108
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
109
+    ];
110
+
111
+    /**
112
+     * @var string[] Map of uid => display name
113
+     */
114
+    protected $userDisplayNames;
115
+
116
+    /** @var IDBConnection */
117
+    private $db;
118
+
119
+    /** @var Backend */
120
+    private $sharingBackend;
121
+
122
+    /** @var Principal */
123
+    private $principalBackend;
124
+
125
+    /** @var IUserManager */
126
+    private $userManager;
127
+
128
+    /** @var ISecureRandom */
129
+    private $random;
130
+
131
+    /** @var EventDispatcherInterface */
132
+    private $dispatcher;
133
+
134
+    /** @var bool */
135
+    private $legacyEndpoint;
136
+
137
+    /**
138
+     * CalDavBackend constructor.
139
+     *
140
+     * @param IDBConnection $db
141
+     * @param Principal $principalBackend
142
+     * @param IUserManager $userManager
143
+     * @param ISecureRandom $random
144
+     * @param EventDispatcherInterface $dispatcher
145
+     * @param bool $legacyEndpoint
146
+     */
147
+    public function __construct(IDBConnection $db,
148
+                                Principal $principalBackend,
149
+                                IUserManager $userManager,
150
+                                ISecureRandom $random,
151
+                                EventDispatcherInterface $dispatcher,
152
+                                $legacyEndpoint = false) {
153
+        $this->db = $db;
154
+        $this->principalBackend = $principalBackend;
155
+        $this->userManager = $userManager;
156
+        $this->sharingBackend = new Backend($this->db, $principalBackend, 'calendar');
157
+        $this->random = $random;
158
+        $this->dispatcher = $dispatcher;
159
+        $this->legacyEndpoint = $legacyEndpoint;
160
+    }
161
+
162
+    /**
163
+     * Return the number of calendars for a principal
164
+     *
165
+     * By default this excludes the automatically generated birthday calendar
166
+     *
167
+     * @param $principalUri
168
+     * @param bool $excludeBirthday
169
+     * @return int
170
+     */
171
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
172
+        $principalUri = $this->convertPrincipal($principalUri, true);
173
+        $query = $this->db->getQueryBuilder();
174
+        $query->select($query->createFunction('COUNT(*)'))
175
+            ->from('calendars')
176
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
177
+
178
+        if ($excludeBirthday) {
179
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180
+        }
181
+
182
+        return (int)$query->execute()->fetchColumn();
183
+    }
184
+
185
+    /**
186
+     * Returns a list of calendars for a principal.
187
+     *
188
+     * Every project is an array with the following keys:
189
+     *  * id, a unique id that will be used by other functions to modify the
190
+     *    calendar. This can be the same as the uri or a database key.
191
+     *  * uri, which the basename of the uri with which the calendar is
192
+     *    accessed.
193
+     *  * principaluri. The owner of the calendar. Almost always the same as
194
+     *    principalUri passed to this method.
195
+     *
196
+     * Furthermore it can contain webdav properties in clark notation. A very
197
+     * common one is '{DAV:}displayname'.
198
+     *
199
+     * Many clients also require:
200
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
201
+     * For this property, you can just return an instance of
202
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
203
+     *
204
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
205
+     * ACL will automatically be put in read-only mode.
206
+     *
207
+     * @param string $principalUri
208
+     * @return array
209
+     */
210
+    function getCalendarsForUser($principalUri) {
211
+        $principalUriOriginal = $principalUri;
212
+        $principalUri = $this->convertPrincipal($principalUri, true);
213
+        $fields = array_values($this->propertyMap);
214
+        $fields[] = 'id';
215
+        $fields[] = 'uri';
216
+        $fields[] = 'synctoken';
217
+        $fields[] = 'components';
218
+        $fields[] = 'principaluri';
219
+        $fields[] = 'transparent';
220
+
221
+        // Making fields a comma-delimited list
222
+        $query = $this->db->getQueryBuilder();
223
+        $query->select($fields)->from('calendars')
224
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
225
+                ->orderBy('calendarorder', 'ASC');
226
+        $stmt = $query->execute();
227
+
228
+        $calendars = [];
229
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230
+
231
+            $components = [];
232
+            if ($row['components']) {
233
+                $components = explode(',',$row['components']);
234
+            }
235
+
236
+            $calendar = [
237
+                'id' => $row['id'],
238
+                'uri' => $row['uri'],
239
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245
+            ];
246
+
247
+            foreach($this->propertyMap as $xmlName=>$dbName) {
248
+                $calendar[$xmlName] = $row[$dbName];
249
+            }
250
+
251
+            if (!isset($calendars[$calendar['id']])) {
252
+                $calendars[$calendar['id']] = $calendar;
253
+            }
254
+        }
255
+
256
+        $stmt->closeCursor();
257
+
258
+        // query for shared calendars
259
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
+        $principals[]= $principalUri;
261
+
262
+        $fields = array_values($this->propertyMap);
263
+        $fields[] = 'a.id';
264
+        $fields[] = 'a.uri';
265
+        $fields[] = 'a.synctoken';
266
+        $fields[] = 'a.components';
267
+        $fields[] = 'a.principaluri';
268
+        $fields[] = 'a.transparent';
269
+        $fields[] = 's.access';
270
+        $query = $this->db->getQueryBuilder();
271
+        $result = $query->select($fields)
272
+            ->from('dav_shares', 's')
273
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
274
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
275
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
276
+            ->setParameter('type', 'calendar')
277
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278
+            ->execute();
279
+
280
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
+        while($row = $result->fetch()) {
282
+            if ($row['principaluri'] === $principalUri) {
283
+                continue;
284
+            }
285
+
286
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
287
+            if (isset($calendars[$row['id']])) {
288
+                if ($readOnly) {
289
+                    // New share can not have more permissions then the old one.
290
+                    continue;
291
+                }
292
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
293
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
294
+                    // Old share is already read-write, no more permissions can be gained
295
+                    continue;
296
+                }
297
+            }
298
+
299
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
300
+            $uri = $row['uri'] . '_shared_by_' . $name;
301
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
302
+            $components = [];
303
+            if ($row['components']) {
304
+                $components = explode(',',$row['components']);
305
+            }
306
+            $calendar = [
307
+                'id' => $row['id'],
308
+                'uri' => $uri,
309
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315
+                $readOnlyPropertyName => $readOnly,
316
+            ];
317
+
318
+            foreach($this->propertyMap as $xmlName=>$dbName) {
319
+                $calendar[$xmlName] = $row[$dbName];
320
+            }
321
+
322
+            $calendars[$calendar['id']] = $calendar;
323
+        }
324
+        $result->closeCursor();
325
+
326
+        return array_values($calendars);
327
+    }
328
+
329
+    public function getUsersOwnCalendars($principalUri) {
330
+        $principalUri = $this->convertPrincipal($principalUri, true);
331
+        $fields = array_values($this->propertyMap);
332
+        $fields[] = 'id';
333
+        $fields[] = 'uri';
334
+        $fields[] = 'synctoken';
335
+        $fields[] = 'components';
336
+        $fields[] = 'principaluri';
337
+        $fields[] = 'transparent';
338
+        // Making fields a comma-delimited list
339
+        $query = $this->db->getQueryBuilder();
340
+        $query->select($fields)->from('calendars')
341
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
342
+            ->orderBy('calendarorder', 'ASC');
343
+        $stmt = $query->execute();
344
+        $calendars = [];
345
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346
+            $components = [];
347
+            if ($row['components']) {
348
+                $components = explode(',',$row['components']);
349
+            }
350
+            $calendar = [
351
+                'id' => $row['id'],
352
+                'uri' => $row['uri'],
353
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
358
+            ];
359
+            foreach($this->propertyMap as $xmlName=>$dbName) {
360
+                $calendar[$xmlName] = $row[$dbName];
361
+            }
362
+            if (!isset($calendars[$calendar['id']])) {
363
+                $calendars[$calendar['id']] = $calendar;
364
+            }
365
+        }
366
+        $stmt->closeCursor();
367
+        return array_values($calendars);
368
+    }
369
+
370
+
371
+    private function getUserDisplayName($uid) {
372
+        if (!isset($this->userDisplayNames[$uid])) {
373
+            $user = $this->userManager->get($uid);
374
+
375
+            if ($user instanceof IUser) {
376
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
377
+            } else {
378
+                $this->userDisplayNames[$uid] = $uid;
379
+            }
380
+        }
381
+
382
+        return $this->userDisplayNames[$uid];
383
+    }
384 384
 	
385
-	/**
386
-	 * @return array
387
-	 */
388
-	public function getPublicCalendars() {
389
-		$fields = array_values($this->propertyMap);
390
-		$fields[] = 'a.id';
391
-		$fields[] = 'a.uri';
392
-		$fields[] = 'a.synctoken';
393
-		$fields[] = 'a.components';
394
-		$fields[] = 'a.principaluri';
395
-		$fields[] = 'a.transparent';
396
-		$fields[] = 's.access';
397
-		$fields[] = 's.publicuri';
398
-		$calendars = [];
399
-		$query = $this->db->getQueryBuilder();
400
-		$result = $query->select($fields)
401
-			->from('dav_shares', 's')
402
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
403
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
404
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405
-			->execute();
406
-
407
-		while($row = $result->fetch()) {
408
-			list(, $name) = URLUtil::splitPath($row['principaluri']);
409
-			$row['displayname'] = $row['displayname'] . "($name)";
410
-			$components = [];
411
-			if ($row['components']) {
412
-				$components = explode(',',$row['components']);
413
-			}
414
-			$calendar = [
415
-				'id' => $row['id'],
416
-				'uri' => $row['publicuri'],
417
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
425
-			];
426
-
427
-			foreach($this->propertyMap as $xmlName=>$dbName) {
428
-				$calendar[$xmlName] = $row[$dbName];
429
-			}
430
-
431
-			if (!isset($calendars[$calendar['id']])) {
432
-				$calendars[$calendar['id']] = $calendar;
433
-			}
434
-		}
435
-		$result->closeCursor();
436
-
437
-		return array_values($calendars);
438
-	}
439
-
440
-	/**
441
-	 * @param string $uri
442
-	 * @return array
443
-	 * @throws NotFound
444
-	 */
445
-	public function getPublicCalendar($uri) {
446
-		$fields = array_values($this->propertyMap);
447
-		$fields[] = 'a.id';
448
-		$fields[] = 'a.uri';
449
-		$fields[] = 'a.synctoken';
450
-		$fields[] = 'a.components';
451
-		$fields[] = 'a.principaluri';
452
-		$fields[] = 'a.transparent';
453
-		$fields[] = 's.access';
454
-		$fields[] = 's.publicuri';
455
-		$query = $this->db->getQueryBuilder();
456
-		$result = $query->select($fields)
457
-			->from('dav_shares', 's')
458
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
459
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
460
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
461
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
462
-			->execute();
463
-
464
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
465
-
466
-		$result->closeCursor();
467
-
468
-		if ($row === false) {
469
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
470
-		}
471
-
472
-		list(, $name) = URLUtil::splitPath($row['principaluri']);
473
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
474
-		$components = [];
475
-		if ($row['components']) {
476
-			$components = explode(',',$row['components']);
477
-		}
478
-		$calendar = [
479
-			'id' => $row['id'],
480
-			'uri' => $row['publicuri'],
481
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
-		];
490
-
491
-		foreach($this->propertyMap as $xmlName=>$dbName) {
492
-			$calendar[$xmlName] = $row[$dbName];
493
-		}
494
-
495
-		return $calendar;
496
-
497
-	}
498
-
499
-	/**
500
-	 * @param string $principal
501
-	 * @param string $uri
502
-	 * @return array|null
503
-	 */
504
-	public function getCalendarByUri($principal, $uri) {
505
-		$fields = array_values($this->propertyMap);
506
-		$fields[] = 'id';
507
-		$fields[] = 'uri';
508
-		$fields[] = 'synctoken';
509
-		$fields[] = 'components';
510
-		$fields[] = 'principaluri';
511
-		$fields[] = 'transparent';
512
-
513
-		// Making fields a comma-delimited list
514
-		$query = $this->db->getQueryBuilder();
515
-		$query->select($fields)->from('calendars')
516
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
517
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
518
-			->setMaxResults(1);
519
-		$stmt = $query->execute();
520
-
521
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
522
-		$stmt->closeCursor();
523
-		if ($row === false) {
524
-			return null;
525
-		}
526
-
527
-		$components = [];
528
-		if ($row['components']) {
529
-			$components = explode(',',$row['components']);
530
-		}
531
-
532
-		$calendar = [
533
-			'id' => $row['id'],
534
-			'uri' => $row['uri'],
535
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
540
-		];
541
-
542
-		foreach($this->propertyMap as $xmlName=>$dbName) {
543
-			$calendar[$xmlName] = $row[$dbName];
544
-		}
545
-
546
-		return $calendar;
547
-	}
548
-
549
-	public function getCalendarById($calendarId) {
550
-		$fields = array_values($this->propertyMap);
551
-		$fields[] = 'id';
552
-		$fields[] = 'uri';
553
-		$fields[] = 'synctoken';
554
-		$fields[] = 'components';
555
-		$fields[] = 'principaluri';
556
-		$fields[] = 'transparent';
557
-
558
-		// Making fields a comma-delimited list
559
-		$query = $this->db->getQueryBuilder();
560
-		$query->select($fields)->from('calendars')
561
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
562
-			->setMaxResults(1);
563
-		$stmt = $query->execute();
564
-
565
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
566
-		$stmt->closeCursor();
567
-		if ($row === false) {
568
-			return null;
569
-		}
570
-
571
-		$components = [];
572
-		if ($row['components']) {
573
-			$components = explode(',',$row['components']);
574
-		}
575
-
576
-		$calendar = [
577
-			'id' => $row['id'],
578
-			'uri' => $row['uri'],
579
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
584
-		];
585
-
586
-		foreach($this->propertyMap as $xmlName=>$dbName) {
587
-			$calendar[$xmlName] = $row[$dbName];
588
-		}
589
-
590
-		return $calendar;
591
-	}
592
-
593
-	/**
594
-	 * Creates a new calendar for a principal.
595
-	 *
596
-	 * If the creation was a success, an id must be returned that can be used to reference
597
-	 * this calendar in other methods, such as updateCalendar.
598
-	 *
599
-	 * @param string $principalUri
600
-	 * @param string $calendarUri
601
-	 * @param array $properties
602
-	 * @return int
603
-	 */
604
-	function createCalendar($principalUri, $calendarUri, array $properties) {
605
-		$values = [
606
-			'principaluri' => $this->convertPrincipal($principalUri, true),
607
-			'uri'          => $calendarUri,
608
-			'synctoken'    => 1,
609
-			'transparent'  => 0,
610
-			'components'   => 'VEVENT,VTODO',
611
-			'displayname'  => $calendarUri
612
-		];
613
-
614
-		// Default value
615
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616
-		if (isset($properties[$sccs])) {
617
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619
-			}
620
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
621
-		}
622
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
623
-		if (isset($properties[$transp])) {
624
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625
-		}
626
-
627
-		foreach($this->propertyMap as $xmlName=>$dbName) {
628
-			if (isset($properties[$xmlName])) {
629
-				$values[$dbName] = $properties[$xmlName];
630
-			}
631
-		}
632
-
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->insert('calendars');
635
-		foreach($values as $column => $value) {
636
-			$query->setValue($column, $query->createNamedParameter($value));
637
-		}
638
-		$query->execute();
639
-		$calendarId = $query->getLastInsertId();
640
-
641
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
642
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
643
-			[
644
-				'calendarId' => $calendarId,
645
-				'calendarData' => $this->getCalendarById($calendarId),
646
-		]));
647
-
648
-		return $calendarId;
649
-	}
650
-
651
-	/**
652
-	 * Updates properties for a calendar.
653
-	 *
654
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
655
-	 * To do the actual updates, you must tell this object which properties
656
-	 * you're going to process with the handle() method.
657
-	 *
658
-	 * Calling the handle method is like telling the PropPatch object "I
659
-	 * promise I can handle updating this property".
660
-	 *
661
-	 * Read the PropPatch documentation for more info and examples.
662
-	 *
663
-	 * @param PropPatch $propPatch
664
-	 * @return void
665
-	 */
666
-	function updateCalendar($calendarId, PropPatch $propPatch) {
667
-		$supportedProperties = array_keys($this->propertyMap);
668
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
669
-
670
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671
-			$newValues = [];
672
-			foreach ($mutations as $propertyName => $propertyValue) {
673
-
674
-				switch ($propertyName) {
675
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
676
-						$fieldName = 'transparent';
677
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678
-						break;
679
-					default :
680
-						$fieldName = $this->propertyMap[$propertyName];
681
-						$newValues[$fieldName] = $propertyValue;
682
-						break;
683
-				}
684
-
685
-			}
686
-			$query = $this->db->getQueryBuilder();
687
-			$query->update('calendars');
688
-			foreach ($newValues as $fieldName => $value) {
689
-				$query->set($fieldName, $query->createNamedParameter($value));
690
-			}
691
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
692
-			$query->execute();
693
-
694
-			$this->addChange($calendarId, "", 2);
695
-
696
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
697
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
698
-				[
699
-					'calendarId' => $calendarId,
700
-					'calendarData' => $this->getCalendarById($calendarId),
701
-					'shares' => $this->getShares($calendarId),
702
-					'propertyMutations' => $mutations,
703
-			]));
704
-
705
-			return true;
706
-		});
707
-	}
708
-
709
-	/**
710
-	 * Delete a calendar and all it's objects
711
-	 *
712
-	 * @param mixed $calendarId
713
-	 * @return void
714
-	 */
715
-	function deleteCalendar($calendarId) {
716
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
717
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
718
-			[
719
-				'calendarId' => $calendarId,
720
-				'calendarData' => $this->getCalendarById($calendarId),
721
-				'shares' => $this->getShares($calendarId),
722
-		]));
723
-
724
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
725
-		$stmt->execute([$calendarId]);
726
-
727
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
728
-		$stmt->execute([$calendarId]);
729
-
730
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
731
-		$stmt->execute([$calendarId]);
732
-
733
-		$this->sharingBackend->deleteAllShares($calendarId);
734
-	}
735
-
736
-	/**
737
-	 * Delete all of an user's shares
738
-	 *
739
-	 * @param string $principaluri
740
-	 * @return void
741
-	 */
742
-	function deleteAllSharesByUser($principaluri) {
743
-		$this->sharingBackend->deleteAllSharesByUser($principaluri);
744
-	}
745
-
746
-	/**
747
-	 * Returns all calendar objects within a calendar.
748
-	 *
749
-	 * Every item contains an array with the following keys:
750
-	 *   * calendardata - The iCalendar-compatible calendar data
751
-	 *   * uri - a unique key which will be used to construct the uri. This can
752
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
753
-	 *     good idea. This is only the basename, or filename, not the full
754
-	 *     path.
755
-	 *   * lastmodified - a timestamp of the last modification time
756
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
757
-	 *   '"abcdef"')
758
-	 *   * size - The size of the calendar objects, in bytes.
759
-	 *   * component - optional, a string containing the type of object, such
760
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
761
-	 *     the Content-Type header.
762
-	 *
763
-	 * Note that the etag is optional, but it's highly encouraged to return for
764
-	 * speed reasons.
765
-	 *
766
-	 * The calendardata is also optional. If it's not returned
767
-	 * 'getCalendarObject' will be called later, which *is* expected to return
768
-	 * calendardata.
769
-	 *
770
-	 * If neither etag or size are specified, the calendardata will be
771
-	 * used/fetched to determine these numbers. If both are specified the
772
-	 * amount of times this is needed is reduced by a great degree.
773
-	 *
774
-	 * @param mixed $calendarId
775
-	 * @return array
776
-	 */
777
-	function getCalendarObjects($calendarId) {
778
-		$query = $this->db->getQueryBuilder();
779
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
780
-			->from('calendarobjects')
781
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
782
-		$stmt = $query->execute();
783
-
784
-		$result = [];
785
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786
-			$result[] = [
787
-					'id'           => $row['id'],
788
-					'uri'          => $row['uri'],
789
-					'lastmodified' => $row['lastmodified'],
790
-					'etag'         => '"' . $row['etag'] . '"',
791
-					'calendarid'   => $row['calendarid'],
792
-					'size'         => (int)$row['size'],
793
-					'component'    => strtolower($row['componenttype']),
794
-					'classification'=> (int)$row['classification']
795
-			];
796
-		}
797
-
798
-		return $result;
799
-	}
800
-
801
-	/**
802
-	 * Returns information from a single calendar object, based on it's object
803
-	 * uri.
804
-	 *
805
-	 * The object uri is only the basename, or filename and not a full path.
806
-	 *
807
-	 * The returned array must have the same keys as getCalendarObjects. The
808
-	 * 'calendardata' object is required here though, while it's not required
809
-	 * for getCalendarObjects.
810
-	 *
811
-	 * This method must return null if the object did not exist.
812
-	 *
813
-	 * @param mixed $calendarId
814
-	 * @param string $objectUri
815
-	 * @return array|null
816
-	 */
817
-	function getCalendarObject($calendarId, $objectUri) {
818
-
819
-		$query = $this->db->getQueryBuilder();
820
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
821
-				->from('calendarobjects')
822
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
823
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
824
-		$stmt = $query->execute();
825
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
826
-
827
-		if(!$row) return null;
828
-
829
-		return [
830
-				'id'            => $row['id'],
831
-				'uri'           => $row['uri'],
832
-				'lastmodified'  => $row['lastmodified'],
833
-				'etag'          => '"' . $row['etag'] . '"',
834
-				'calendarid'    => $row['calendarid'],
835
-				'size'          => (int)$row['size'],
836
-				'calendardata'  => $this->readBlob($row['calendardata']),
837
-				'component'     => strtolower($row['componenttype']),
838
-				'classification'=> (int)$row['classification']
839
-		];
840
-	}
841
-
842
-	/**
843
-	 * Returns a list of calendar objects.
844
-	 *
845
-	 * This method should work identical to getCalendarObject, but instead
846
-	 * return all the calendar objects in the list as an array.
847
-	 *
848
-	 * If the backend supports this, it may allow for some speed-ups.
849
-	 *
850
-	 * @param mixed $calendarId
851
-	 * @param string[] $uris
852
-	 * @return array
853
-	 */
854
-	function getMultipleCalendarObjects($calendarId, array $uris) {
855
-		if (empty($uris)) {
856
-			return [];
857
-		}
858
-
859
-		$chunks = array_chunk($uris, 100);
860
-		$objects = [];
861
-
862
-		$query = $this->db->getQueryBuilder();
863
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
864
-			->from('calendarobjects')
865
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
867
-
868
-		foreach ($chunks as $uris) {
869
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
870
-			$result = $query->execute();
871
-
872
-			while ($row = $result->fetch()) {
873
-				$objects[] = [
874
-					'id'           => $row['id'],
875
-					'uri'          => $row['uri'],
876
-					'lastmodified' => $row['lastmodified'],
877
-					'etag'         => '"' . $row['etag'] . '"',
878
-					'calendarid'   => $row['calendarid'],
879
-					'size'         => (int)$row['size'],
880
-					'calendardata' => $this->readBlob($row['calendardata']),
881
-					'component'    => strtolower($row['componenttype']),
882
-					'classification' => (int)$row['classification']
883
-				];
884
-			}
885
-			$result->closeCursor();
886
-		}
887
-		return $objects;
888
-	}
889
-
890
-	/**
891
-	 * Creates a new calendar object.
892
-	 *
893
-	 * The object uri is only the basename, or filename and not a full path.
894
-	 *
895
-	 * It is possible return an etag from this function, which will be used in
896
-	 * the response to this PUT request. Note that the ETag must be surrounded
897
-	 * by double-quotes.
898
-	 *
899
-	 * However, you should only really return this ETag if you don't mangle the
900
-	 * calendar-data. If the result of a subsequent GET to this object is not
901
-	 * the exact same as this request body, you should omit the ETag.
902
-	 *
903
-	 * @param mixed $calendarId
904
-	 * @param string $objectUri
905
-	 * @param string $calendarData
906
-	 * @return string
907
-	 */
908
-	function createCalendarObject($calendarId, $objectUri, $calendarData) {
909
-		$extraData = $this->getDenormalizedData($calendarData);
910
-
911
-		$query = $this->db->getQueryBuilder();
912
-		$query->insert('calendarobjects')
913
-			->values([
914
-				'calendarid' => $query->createNamedParameter($calendarId),
915
-				'uri' => $query->createNamedParameter($objectUri),
916
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
917
-				'lastmodified' => $query->createNamedParameter(time()),
918
-				'etag' => $query->createNamedParameter($extraData['etag']),
919
-				'size' => $query->createNamedParameter($extraData['size']),
920
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
921
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
922
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
923
-				'classification' => $query->createNamedParameter($extraData['classification']),
924
-				'uid' => $query->createNamedParameter($extraData['uid']),
925
-			])
926
-			->execute();
927
-
928
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
929
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
930
-			[
931
-				'calendarId' => $calendarId,
932
-				'calendarData' => $this->getCalendarById($calendarId),
933
-				'shares' => $this->getShares($calendarId),
934
-				'objectData' => $this->getCalendarObject($calendarId, $objectUri),
935
-			]
936
-		));
937
-		$this->addChange($calendarId, $objectUri, 1);
938
-
939
-		return '"' . $extraData['etag'] . '"';
940
-	}
941
-
942
-	/**
943
-	 * Updates an existing calendarobject, based on it's uri.
944
-	 *
945
-	 * The object uri is only the basename, or filename and not a full path.
946
-	 *
947
-	 * It is possible return an etag from this function, which will be used in
948
-	 * the response to this PUT request. Note that the ETag must be surrounded
949
-	 * by double-quotes.
950
-	 *
951
-	 * However, you should only really return this ETag if you don't mangle the
952
-	 * calendar-data. If the result of a subsequent GET to this object is not
953
-	 * the exact same as this request body, you should omit the ETag.
954
-	 *
955
-	 * @param mixed $calendarId
956
-	 * @param string $objectUri
957
-	 * @param string $calendarData
958
-	 * @return string
959
-	 */
960
-	function updateCalendarObject($calendarId, $objectUri, $calendarData) {
961
-		$extraData = $this->getDenormalizedData($calendarData);
962
-
963
-		$query = $this->db->getQueryBuilder();
964
-		$query->update('calendarobjects')
965
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
966
-				->set('lastmodified', $query->createNamedParameter(time()))
967
-				->set('etag', $query->createNamedParameter($extraData['etag']))
968
-				->set('size', $query->createNamedParameter($extraData['size']))
969
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
970
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
971
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
972
-				->set('classification', $query->createNamedParameter($extraData['classification']))
973
-				->set('uid', $query->createNamedParameter($extraData['uid']))
974
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
975
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
976
-			->execute();
977
-
978
-		$data = $this->getCalendarObject($calendarId, $objectUri);
979
-		if (is_array($data)) {
980
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
981
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
982
-				[
983
-					'calendarId' => $calendarId,
984
-					'calendarData' => $this->getCalendarById($calendarId),
985
-					'shares' => $this->getShares($calendarId),
986
-					'objectData' => $data,
987
-				]
988
-			));
989
-		}
990
-		$this->addChange($calendarId, $objectUri, 2);
991
-
992
-		return '"' . $extraData['etag'] . '"';
993
-	}
994
-
995
-	/**
996
-	 * @param int $calendarObjectId
997
-	 * @param int $classification
998
-	 */
999
-	public function setClassification($calendarObjectId, $classification) {
1000
-		if (!in_array($classification, [
1001
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1002
-		])) {
1003
-			throw new \InvalidArgumentException();
1004
-		}
1005
-		$query = $this->db->getQueryBuilder();
1006
-		$query->update('calendarobjects')
1007
-			->set('classification', $query->createNamedParameter($classification))
1008
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1009
-			->execute();
1010
-	}
1011
-
1012
-	/**
1013
-	 * Deletes an existing calendar object.
1014
-	 *
1015
-	 * The object uri is only the basename, or filename and not a full path.
1016
-	 *
1017
-	 * @param mixed $calendarId
1018
-	 * @param string $objectUri
1019
-	 * @return void
1020
-	 */
1021
-	function deleteCalendarObject($calendarId, $objectUri) {
1022
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1023
-		if (is_array($data)) {
1024
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1025
-				'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1026
-				[
1027
-					'calendarId' => $calendarId,
1028
-					'calendarData' => $this->getCalendarById($calendarId),
1029
-					'shares' => $this->getShares($calendarId),
1030
-					'objectData' => $data,
1031
-				]
1032
-			));
1033
-		}
1034
-
1035
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1036
-		$stmt->execute([$calendarId, $objectUri]);
1037
-
1038
-		$this->addChange($calendarId, $objectUri, 3);
1039
-	}
1040
-
1041
-	/**
1042
-	 * Performs a calendar-query on the contents of this calendar.
1043
-	 *
1044
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1045
-	 * calendar-query it is possible for a client to request a specific set of
1046
-	 * object, based on contents of iCalendar properties, date-ranges and
1047
-	 * iCalendar component types (VTODO, VEVENT).
1048
-	 *
1049
-	 * This method should just return a list of (relative) urls that match this
1050
-	 * query.
1051
-	 *
1052
-	 * The list of filters are specified as an array. The exact array is
1053
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1054
-	 *
1055
-	 * Note that it is extremely likely that getCalendarObject for every path
1056
-	 * returned from this method will be called almost immediately after. You
1057
-	 * may want to anticipate this to speed up these requests.
1058
-	 *
1059
-	 * This method provides a default implementation, which parses *all* the
1060
-	 * iCalendar objects in the specified calendar.
1061
-	 *
1062
-	 * This default may well be good enough for personal use, and calendars
1063
-	 * that aren't very large. But if you anticipate high usage, big calendars
1064
-	 * or high loads, you are strongly advised to optimize certain paths.
1065
-	 *
1066
-	 * The best way to do so is override this method and to optimize
1067
-	 * specifically for 'common filters'.
1068
-	 *
1069
-	 * Requests that are extremely common are:
1070
-	 *   * requests for just VEVENTS
1071
-	 *   * requests for just VTODO
1072
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1073
-	 *
1074
-	 * ..and combinations of these requests. It may not be worth it to try to
1075
-	 * handle every possible situation and just rely on the (relatively
1076
-	 * easy to use) CalendarQueryValidator to handle the rest.
1077
-	 *
1078
-	 * Note that especially time-range-filters may be difficult to parse. A
1079
-	 * time-range filter specified on a VEVENT must for instance also handle
1080
-	 * recurrence rules correctly.
1081
-	 * A good example of how to interprete all these filters can also simply
1082
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1083
-	 * as possible, so it gives you a good idea on what type of stuff you need
1084
-	 * to think of.
1085
-	 *
1086
-	 * @param mixed $calendarId
1087
-	 * @param array $filters
1088
-	 * @return array
1089
-	 */
1090
-	function calendarQuery($calendarId, array $filters) {
1091
-		$componentType = null;
1092
-		$requirePostFilter = true;
1093
-		$timeRange = null;
1094
-
1095
-		// if no filters were specified, we don't need to filter after a query
1096
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1097
-			$requirePostFilter = false;
1098
-		}
1099
-
1100
-		// Figuring out if there's a component filter
1101
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1102
-			$componentType = $filters['comp-filters'][0]['name'];
1103
-
1104
-			// Checking if we need post-filters
1105
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1106
-				$requirePostFilter = false;
1107
-			}
1108
-			// There was a time-range filter
1109
-			if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1110
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1111
-
1112
-				// If start time OR the end time is not specified, we can do a
1113
-				// 100% accurate mysql query.
1114
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1115
-					$requirePostFilter = false;
1116
-				}
1117
-			}
1118
-
1119
-		}
1120
-		$columns = ['uri'];
1121
-		if ($requirePostFilter) {
1122
-			$columns = ['uri', 'calendardata'];
1123
-		}
1124
-		$query = $this->db->getQueryBuilder();
1125
-		$query->select($columns)
1126
-			->from('calendarobjects')
1127
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1128
-
1129
-		if ($componentType) {
1130
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1131
-		}
1132
-
1133
-		if ($timeRange && $timeRange['start']) {
1134
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1135
-		}
1136
-		if ($timeRange && $timeRange['end']) {
1137
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1138
-		}
1139
-
1140
-		$stmt = $query->execute();
1141
-
1142
-		$result = [];
1143
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144
-			if ($requirePostFilter) {
1145
-				if (!$this->validateFilterForObject($row, $filters)) {
1146
-					continue;
1147
-				}
1148
-			}
1149
-			$result[] = $row['uri'];
1150
-		}
1151
-
1152
-		return $result;
1153
-	}
1154
-
1155
-	/**
1156
-	 * Searches through all of a users calendars and calendar objects to find
1157
-	 * an object with a specific UID.
1158
-	 *
1159
-	 * This method should return the path to this object, relative to the
1160
-	 * calendar home, so this path usually only contains two parts:
1161
-	 *
1162
-	 * calendarpath/objectpath.ics
1163
-	 *
1164
-	 * If the uid is not found, return null.
1165
-	 *
1166
-	 * This method should only consider * objects that the principal owns, so
1167
-	 * any calendars owned by other principals that also appear in this
1168
-	 * collection should be ignored.
1169
-	 *
1170
-	 * @param string $principalUri
1171
-	 * @param string $uid
1172
-	 * @return string|null
1173
-	 */
1174
-	function getCalendarObjectByUID($principalUri, $uid) {
1175
-
1176
-		$query = $this->db->getQueryBuilder();
1177
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1178
-			->from('calendarobjects', 'co')
1179
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1180
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1181
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1182
-
1183
-		$stmt = $query->execute();
1184
-
1185
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1187
-		}
1188
-
1189
-		return null;
1190
-	}
1191
-
1192
-	/**
1193
-	 * The getChanges method returns all the changes that have happened, since
1194
-	 * the specified syncToken in the specified calendar.
1195
-	 *
1196
-	 * This function should return an array, such as the following:
1197
-	 *
1198
-	 * [
1199
-	 *   'syncToken' => 'The current synctoken',
1200
-	 *   'added'   => [
1201
-	 *      'new.txt',
1202
-	 *   ],
1203
-	 *   'modified'   => [
1204
-	 *      'modified.txt',
1205
-	 *   ],
1206
-	 *   'deleted' => [
1207
-	 *      'foo.php.bak',
1208
-	 *      'old.txt'
1209
-	 *   ]
1210
-	 * );
1211
-	 *
1212
-	 * The returned syncToken property should reflect the *current* syncToken
1213
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1214
-	 * property This is * needed here too, to ensure the operation is atomic.
1215
-	 *
1216
-	 * If the $syncToken argument is specified as null, this is an initial
1217
-	 * sync, and all members should be reported.
1218
-	 *
1219
-	 * The modified property is an array of nodenames that have changed since
1220
-	 * the last token.
1221
-	 *
1222
-	 * The deleted property is an array with nodenames, that have been deleted
1223
-	 * from collection.
1224
-	 *
1225
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1226
-	 * 1, you only have to report changes that happened only directly in
1227
-	 * immediate descendants. If it's 2, it should also include changes from
1228
-	 * the nodes below the child collections. (grandchildren)
1229
-	 *
1230
-	 * The $limit argument allows a client to specify how many results should
1231
-	 * be returned at most. If the limit is not specified, it should be treated
1232
-	 * as infinite.
1233
-	 *
1234
-	 * If the limit (infinite or not) is higher than you're willing to return,
1235
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1236
-	 *
1237
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1238
-	 * return null.
1239
-	 *
1240
-	 * The limit is 'suggestive'. You are free to ignore it.
1241
-	 *
1242
-	 * @param string $calendarId
1243
-	 * @param string $syncToken
1244
-	 * @param int $syncLevel
1245
-	 * @param int $limit
1246
-	 * @return array
1247
-	 */
1248
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249
-		// Current synctoken
1250
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
-		$stmt->execute([ $calendarId ]);
1252
-		$currentToken = $stmt->fetchColumn(0);
1253
-
1254
-		if (is_null($currentToken)) {
1255
-			return null;
1256
-		}
1257
-
1258
-		$result = [
1259
-			'syncToken' => $currentToken,
1260
-			'added'     => [],
1261
-			'modified'  => [],
1262
-			'deleted'   => [],
1263
-		];
1264
-
1265
-		if ($syncToken) {
1266
-
1267
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
-			if ($limit>0) {
1269
-				$query.= " `LIMIT` " . (int)$limit;
1270
-			}
1271
-
1272
-			// Fetching all changes
1273
-			$stmt = $this->db->prepare($query);
1274
-			$stmt->execute([$syncToken, $currentToken, $calendarId]);
1275
-
1276
-			$changes = [];
1277
-
1278
-			// This loop ensures that any duplicates are overwritten, only the
1279
-			// last change on a node is relevant.
1280
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281
-
1282
-				$changes[$row['uri']] = $row['operation'];
1283
-
1284
-			}
1285
-
1286
-			foreach($changes as $uri => $operation) {
1287
-
1288
-				switch($operation) {
1289
-					case 1 :
1290
-						$result['added'][] = $uri;
1291
-						break;
1292
-					case 2 :
1293
-						$result['modified'][] = $uri;
1294
-						break;
1295
-					case 3 :
1296
-						$result['deleted'][] = $uri;
1297
-						break;
1298
-				}
1299
-
1300
-			}
1301
-		} else {
1302
-			// No synctoken supplied, this is the initial sync.
1303
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1304
-			$stmt = $this->db->prepare($query);
1305
-			$stmt->execute([$calendarId]);
1306
-
1307
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1308
-		}
1309
-		return $result;
1310
-
1311
-	}
1312
-
1313
-	/**
1314
-	 * Returns a list of subscriptions for a principal.
1315
-	 *
1316
-	 * Every subscription is an array with the following keys:
1317
-	 *  * id, a unique id that will be used by other functions to modify the
1318
-	 *    subscription. This can be the same as the uri or a database key.
1319
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1320
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1321
-	 *    principalUri passed to this method.
1322
-	 *
1323
-	 * Furthermore, all the subscription info must be returned too:
1324
-	 *
1325
-	 * 1. {DAV:}displayname
1326
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1327
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1328
-	 *    should not be stripped).
1329
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1330
-	 *    should not be stripped).
1331
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1332
-	 *    attachments should not be stripped).
1333
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1334
-	 *     Sabre\DAV\Property\Href).
1335
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1336
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1337
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1338
-	 *    (should just be an instance of
1339
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1340
-	 *    default components).
1341
-	 *
1342
-	 * @param string $principalUri
1343
-	 * @return array
1344
-	 */
1345
-	function getSubscriptionsForUser($principalUri) {
1346
-		$fields = array_values($this->subscriptionPropertyMap);
1347
-		$fields[] = 'id';
1348
-		$fields[] = 'uri';
1349
-		$fields[] = 'source';
1350
-		$fields[] = 'principaluri';
1351
-		$fields[] = 'lastmodified';
1352
-
1353
-		$query = $this->db->getQueryBuilder();
1354
-		$query->select($fields)
1355
-			->from('calendarsubscriptions')
1356
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357
-			->orderBy('calendarorder', 'asc');
1358
-		$stmt =$query->execute();
1359
-
1360
-		$subscriptions = [];
1361
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362
-
1363
-			$subscription = [
1364
-				'id'           => $row['id'],
1365
-				'uri'          => $row['uri'],
1366
-				'principaluri' => $row['principaluri'],
1367
-				'source'       => $row['source'],
1368
-				'lastmodified' => $row['lastmodified'],
1369
-
1370
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371
-			];
1372
-
1373
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374
-				if (!is_null($row[$dbName])) {
1375
-					$subscription[$xmlName] = $row[$dbName];
1376
-				}
1377
-			}
1378
-
1379
-			$subscriptions[] = $subscription;
1380
-
1381
-		}
1382
-
1383
-		return $subscriptions;
1384
-	}
1385
-
1386
-	/**
1387
-	 * Creates a new subscription for a principal.
1388
-	 *
1389
-	 * If the creation was a success, an id must be returned that can be used to reference
1390
-	 * this subscription in other methods, such as updateSubscription.
1391
-	 *
1392
-	 * @param string $principalUri
1393
-	 * @param string $uri
1394
-	 * @param array $properties
1395
-	 * @return mixed
1396
-	 */
1397
-	function createSubscription($principalUri, $uri, array $properties) {
1398
-
1399
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1400
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1401
-		}
1402
-
1403
-		$values = [
1404
-			'principaluri' => $principalUri,
1405
-			'uri'          => $uri,
1406
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1407
-			'lastmodified' => time(),
1408
-		];
1409
-
1410
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411
-
1412
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413
-			if (array_key_exists($xmlName, $properties)) {
1414
-					$values[$dbName] = $properties[$xmlName];
1415
-					if (in_array($dbName, $propertiesBoolean)) {
1416
-						$values[$dbName] = true;
1417
-				}
1418
-			}
1419
-		}
1420
-
1421
-		$valuesToInsert = array();
1422
-
1423
-		$query = $this->db->getQueryBuilder();
1424
-
1425
-		foreach (array_keys($values) as $name) {
1426
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1427
-		}
1428
-
1429
-		$query->insert('calendarsubscriptions')
1430
-			->values($valuesToInsert)
1431
-			->execute();
1432
-
1433
-		return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1434
-	}
1435
-
1436
-	/**
1437
-	 * Updates a subscription
1438
-	 *
1439
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1440
-	 * To do the actual updates, you must tell this object which properties
1441
-	 * you're going to process with the handle() method.
1442
-	 *
1443
-	 * Calling the handle method is like telling the PropPatch object "I
1444
-	 * promise I can handle updating this property".
1445
-	 *
1446
-	 * Read the PropPatch documentation for more info and examples.
1447
-	 *
1448
-	 * @param mixed $subscriptionId
1449
-	 * @param PropPatch $propPatch
1450
-	 * @return void
1451
-	 */
1452
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1453
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1454
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1455
-
1456
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1457
-
1458
-			$newValues = [];
1459
-
1460
-			foreach($mutations as $propertyName=>$propertyValue) {
1461
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462
-					$newValues['source'] = $propertyValue->getHref();
1463
-				} else {
1464
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1465
-					$newValues[$fieldName] = $propertyValue;
1466
-				}
1467
-			}
1468
-
1469
-			$query = $this->db->getQueryBuilder();
1470
-			$query->update('calendarsubscriptions')
1471
-				->set('lastmodified', $query->createNamedParameter(time()));
1472
-			foreach($newValues as $fieldName=>$value) {
1473
-				$query->set($fieldName, $query->createNamedParameter($value));
1474
-			}
1475
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1476
-				->execute();
1477
-
1478
-			return true;
1479
-
1480
-		});
1481
-	}
1482
-
1483
-	/**
1484
-	 * Deletes a subscription.
1485
-	 *
1486
-	 * @param mixed $subscriptionId
1487
-	 * @return void
1488
-	 */
1489
-	function deleteSubscription($subscriptionId) {
1490
-		$query = $this->db->getQueryBuilder();
1491
-		$query->delete('calendarsubscriptions')
1492
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1493
-			->execute();
1494
-	}
1495
-
1496
-	/**
1497
-	 * Returns a single scheduling object for the inbox collection.
1498
-	 *
1499
-	 * The returned array should contain the following elements:
1500
-	 *   * uri - A unique basename for the object. This will be used to
1501
-	 *           construct a full uri.
1502
-	 *   * calendardata - The iCalendar object
1503
-	 *   * lastmodified - The last modification date. Can be an int for a unix
1504
-	 *                    timestamp, or a PHP DateTime object.
1505
-	 *   * etag - A unique token that must change if the object changed.
1506
-	 *   * size - The size of the object, in bytes.
1507
-	 *
1508
-	 * @param string $principalUri
1509
-	 * @param string $objectUri
1510
-	 * @return array
1511
-	 */
1512
-	function getSchedulingObject($principalUri, $objectUri) {
1513
-		$query = $this->db->getQueryBuilder();
1514
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1515
-			->from('schedulingobjects')
1516
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1517
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1518
-			->execute();
1519
-
1520
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521
-
1522
-		if(!$row) {
1523
-			return null;
1524
-		}
1525
-
1526
-		return [
1527
-				'uri'          => $row['uri'],
1528
-				'calendardata' => $row['calendardata'],
1529
-				'lastmodified' => $row['lastmodified'],
1530
-				'etag'         => '"' . $row['etag'] . '"',
1531
-				'size'         => (int)$row['size'],
1532
-		];
1533
-	}
1534
-
1535
-	/**
1536
-	 * Returns all scheduling objects for the inbox collection.
1537
-	 *
1538
-	 * These objects should be returned as an array. Every item in the array
1539
-	 * should follow the same structure as returned from getSchedulingObject.
1540
-	 *
1541
-	 * The main difference is that 'calendardata' is optional.
1542
-	 *
1543
-	 * @param string $principalUri
1544
-	 * @return array
1545
-	 */
1546
-	function getSchedulingObjects($principalUri) {
1547
-		$query = $this->db->getQueryBuilder();
1548
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1549
-				->from('schedulingobjects')
1550
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1551
-				->execute();
1552
-
1553
-		$result = [];
1554
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555
-			$result[] = [
1556
-					'calendardata' => $row['calendardata'],
1557
-					'uri'          => $row['uri'],
1558
-					'lastmodified' => $row['lastmodified'],
1559
-					'etag'         => '"' . $row['etag'] . '"',
1560
-					'size'         => (int)$row['size'],
1561
-			];
1562
-		}
1563
-
1564
-		return $result;
1565
-	}
1566
-
1567
-	/**
1568
-	 * Deletes a scheduling object from the inbox collection.
1569
-	 *
1570
-	 * @param string $principalUri
1571
-	 * @param string $objectUri
1572
-	 * @return void
1573
-	 */
1574
-	function deleteSchedulingObject($principalUri, $objectUri) {
1575
-		$query = $this->db->getQueryBuilder();
1576
-		$query->delete('schedulingobjects')
1577
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1578
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1579
-				->execute();
1580
-	}
1581
-
1582
-	/**
1583
-	 * Creates a new scheduling object. This should land in a users' inbox.
1584
-	 *
1585
-	 * @param string $principalUri
1586
-	 * @param string $objectUri
1587
-	 * @param string $objectData
1588
-	 * @return void
1589
-	 */
1590
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
1591
-		$query = $this->db->getQueryBuilder();
1592
-		$query->insert('schedulingobjects')
1593
-			->values([
1594
-				'principaluri' => $query->createNamedParameter($principalUri),
1595
-				'calendardata' => $query->createNamedParameter($objectData),
1596
-				'uri' => $query->createNamedParameter($objectUri),
1597
-				'lastmodified' => $query->createNamedParameter(time()),
1598
-				'etag' => $query->createNamedParameter(md5($objectData)),
1599
-				'size' => $query->createNamedParameter(strlen($objectData))
1600
-			])
1601
-			->execute();
1602
-	}
1603
-
1604
-	/**
1605
-	 * Adds a change record to the calendarchanges table.
1606
-	 *
1607
-	 * @param mixed $calendarId
1608
-	 * @param string $objectUri
1609
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
1610
-	 * @return void
1611
-	 */
1612
-	protected function addChange($calendarId, $objectUri, $operation) {
1613
-
1614
-		$stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1615
-		$stmt->execute([
1616
-			$objectUri,
1617
-			$calendarId,
1618
-			$operation,
1619
-			$calendarId
1620
-		]);
1621
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1622
-		$stmt->execute([
1623
-			$calendarId
1624
-		]);
1625
-
1626
-	}
1627
-
1628
-	/**
1629
-	 * Parses some information from calendar objects, used for optimized
1630
-	 * calendar-queries.
1631
-	 *
1632
-	 * Returns an array with the following keys:
1633
-	 *   * etag - An md5 checksum of the object without the quotes.
1634
-	 *   * size - Size of the object in bytes
1635
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
1636
-	 *   * firstOccurence
1637
-	 *   * lastOccurence
1638
-	 *   * uid - value of the UID property
1639
-	 *
1640
-	 * @param string $calendarData
1641
-	 * @return array
1642
-	 */
1643
-	public function getDenormalizedData($calendarData) {
1644
-
1645
-		$vObject = Reader::read($calendarData);
1646
-		$componentType = null;
1647
-		$component = null;
1648
-		$firstOccurrence = null;
1649
-		$lastOccurrence = null;
1650
-		$uid = null;
1651
-		$classification = self::CLASSIFICATION_PUBLIC;
1652
-		foreach($vObject->getComponents() as $component) {
1653
-			if ($component->name!=='VTIMEZONE') {
1654
-				$componentType = $component->name;
1655
-				$uid = (string)$component->UID;
1656
-				break;
1657
-			}
1658
-		}
1659
-		if (!$componentType) {
1660
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1661
-		}
1662
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
1663
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1664
-			// Finding the last occurrence is a bit harder
1665
-			if (!isset($component->RRULE)) {
1666
-				if (isset($component->DTEND)) {
1667
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1668
-				} elseif (isset($component->DURATION)) {
1669
-					$endDate = clone $component->DTSTART->getDateTime();
1670
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1671
-					$lastOccurrence = $endDate->getTimeStamp();
1672
-				} elseif (!$component->DTSTART->hasTime()) {
1673
-					$endDate = clone $component->DTSTART->getDateTime();
1674
-					$endDate->modify('+1 day');
1675
-					$lastOccurrence = $endDate->getTimeStamp();
1676
-				} else {
1677
-					$lastOccurrence = $firstOccurrence;
1678
-				}
1679
-			} else {
1680
-				$it = new EventIterator($vObject, (string)$component->UID);
1681
-				$maxDate = new \DateTime(self::MAX_DATE);
1682
-				if ($it->isInfinite()) {
1683
-					$lastOccurrence = $maxDate->getTimestamp();
1684
-				} else {
1685
-					$end = $it->getDtEnd();
1686
-					while($it->valid() && $end < $maxDate) {
1687
-						$end = $it->getDtEnd();
1688
-						$it->next();
1689
-
1690
-					}
1691
-					$lastOccurrence = $end->getTimestamp();
1692
-				}
1693
-
1694
-			}
1695
-		}
1696
-
1697
-		if ($component->CLASS) {
1698
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1699
-			switch ($component->CLASS->getValue()) {
1700
-				case 'PUBLIC':
1701
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1702
-					break;
1703
-				case 'CONFIDENTIAL':
1704
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1705
-					break;
1706
-			}
1707
-		}
1708
-		return [
1709
-			'etag' => md5($calendarData),
1710
-			'size' => strlen($calendarData),
1711
-			'componentType' => $componentType,
1712
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1713
-			'lastOccurence'  => $lastOccurrence,
1714
-			'uid' => $uid,
1715
-			'classification' => $classification
1716
-		];
1717
-
1718
-	}
1719
-
1720
-	private function readBlob($cardData) {
1721
-		if (is_resource($cardData)) {
1722
-			return stream_get_contents($cardData);
1723
-		}
1724
-
1725
-		return $cardData;
1726
-	}
1727
-
1728
-	/**
1729
-	 * @param IShareable $shareable
1730
-	 * @param array $add
1731
-	 * @param array $remove
1732
-	 */
1733
-	public function updateShares($shareable, $add, $remove) {
1734
-		$calendarId = $shareable->getResourceId();
1735
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1736
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1737
-			[
1738
-				'calendarId' => $calendarId,
1739
-				'calendarData' => $this->getCalendarById($calendarId),
1740
-				'shares' => $this->getShares($calendarId),
1741
-				'add' => $add,
1742
-				'remove' => $remove,
1743
-			]));
1744
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
1745
-	}
1746
-
1747
-	/**
1748
-	 * @param int $resourceId
1749
-	 * @return array
1750
-	 */
1751
-	public function getShares($resourceId) {
1752
-		return $this->sharingBackend->getShares($resourceId);
1753
-	}
1754
-
1755
-	/**
1756
-	 * @param boolean $value
1757
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1758
-	 * @return string|null
1759
-	 */
1760
-	public function setPublishStatus($value, $calendar) {
1761
-		$query = $this->db->getQueryBuilder();
1762
-		if ($value) {
1763
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1764
-			$query->insert('dav_shares')
1765
-				->values([
1766
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1767
-					'type' => $query->createNamedParameter('calendar'),
1768
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1769
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1770
-					'publicuri' => $query->createNamedParameter($publicUri)
1771
-				]);
1772
-			$query->execute();
1773
-			return $publicUri;
1774
-		}
1775
-		$query->delete('dav_shares')
1776
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1777
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1778
-		$query->execute();
1779
-		return null;
1780
-	}
1781
-
1782
-	/**
1783
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
1784
-	 * @return mixed
1785
-	 */
1786
-	public function getPublishStatus($calendar) {
1787
-		$query = $this->db->getQueryBuilder();
1788
-		$result = $query->select('publicuri')
1789
-			->from('dav_shares')
1790
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1791
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1792
-			->execute();
1793
-
1794
-		$row = $result->fetch();
1795
-		$result->closeCursor();
1796
-		return $row ? reset($row) : false;
1797
-	}
1798
-
1799
-	/**
1800
-	 * @param int $resourceId
1801
-	 * @param array $acl
1802
-	 * @return array
1803
-	 */
1804
-	public function applyShareAcl($resourceId, $acl) {
1805
-		return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1806
-	}
1807
-
1808
-	private function convertPrincipal($principalUri, $toV2) {
1809
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1810
-			list(, $name) = URLUtil::splitPath($principalUri);
1811
-			if ($toV2 === true) {
1812
-				return "principals/users/$name";
1813
-			}
1814
-			return "principals/$name";
1815
-		}
1816
-		return $principalUri;
1817
-	}
385
+    /**
386
+     * @return array
387
+     */
388
+    public function getPublicCalendars() {
389
+        $fields = array_values($this->propertyMap);
390
+        $fields[] = 'a.id';
391
+        $fields[] = 'a.uri';
392
+        $fields[] = 'a.synctoken';
393
+        $fields[] = 'a.components';
394
+        $fields[] = 'a.principaluri';
395
+        $fields[] = 'a.transparent';
396
+        $fields[] = 's.access';
397
+        $fields[] = 's.publicuri';
398
+        $calendars = [];
399
+        $query = $this->db->getQueryBuilder();
400
+        $result = $query->select($fields)
401
+            ->from('dav_shares', 's')
402
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
403
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
404
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405
+            ->execute();
406
+
407
+        while($row = $result->fetch()) {
408
+            list(, $name) = URLUtil::splitPath($row['principaluri']);
409
+            $row['displayname'] = $row['displayname'] . "($name)";
410
+            $components = [];
411
+            if ($row['components']) {
412
+                $components = explode(',',$row['components']);
413
+            }
414
+            $calendar = [
415
+                'id' => $row['id'],
416
+                'uri' => $row['publicuri'],
417
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
425
+            ];
426
+
427
+            foreach($this->propertyMap as $xmlName=>$dbName) {
428
+                $calendar[$xmlName] = $row[$dbName];
429
+            }
430
+
431
+            if (!isset($calendars[$calendar['id']])) {
432
+                $calendars[$calendar['id']] = $calendar;
433
+            }
434
+        }
435
+        $result->closeCursor();
436
+
437
+        return array_values($calendars);
438
+    }
439
+
440
+    /**
441
+     * @param string $uri
442
+     * @return array
443
+     * @throws NotFound
444
+     */
445
+    public function getPublicCalendar($uri) {
446
+        $fields = array_values($this->propertyMap);
447
+        $fields[] = 'a.id';
448
+        $fields[] = 'a.uri';
449
+        $fields[] = 'a.synctoken';
450
+        $fields[] = 'a.components';
451
+        $fields[] = 'a.principaluri';
452
+        $fields[] = 'a.transparent';
453
+        $fields[] = 's.access';
454
+        $fields[] = 's.publicuri';
455
+        $query = $this->db->getQueryBuilder();
456
+        $result = $query->select($fields)
457
+            ->from('dav_shares', 's')
458
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
459
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
460
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
461
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
462
+            ->execute();
463
+
464
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
465
+
466
+        $result->closeCursor();
467
+
468
+        if ($row === false) {
469
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
470
+        }
471
+
472
+        list(, $name) = URLUtil::splitPath($row['principaluri']);
473
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
474
+        $components = [];
475
+        if ($row['components']) {
476
+            $components = explode(',',$row['components']);
477
+        }
478
+        $calendar = [
479
+            'id' => $row['id'],
480
+            'uri' => $row['publicuri'],
481
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
489
+        ];
490
+
491
+        foreach($this->propertyMap as $xmlName=>$dbName) {
492
+            $calendar[$xmlName] = $row[$dbName];
493
+        }
494
+
495
+        return $calendar;
496
+
497
+    }
498
+
499
+    /**
500
+     * @param string $principal
501
+     * @param string $uri
502
+     * @return array|null
503
+     */
504
+    public function getCalendarByUri($principal, $uri) {
505
+        $fields = array_values($this->propertyMap);
506
+        $fields[] = 'id';
507
+        $fields[] = 'uri';
508
+        $fields[] = 'synctoken';
509
+        $fields[] = 'components';
510
+        $fields[] = 'principaluri';
511
+        $fields[] = 'transparent';
512
+
513
+        // Making fields a comma-delimited list
514
+        $query = $this->db->getQueryBuilder();
515
+        $query->select($fields)->from('calendars')
516
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
517
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
518
+            ->setMaxResults(1);
519
+        $stmt = $query->execute();
520
+
521
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
522
+        $stmt->closeCursor();
523
+        if ($row === false) {
524
+            return null;
525
+        }
526
+
527
+        $components = [];
528
+        if ($row['components']) {
529
+            $components = explode(',',$row['components']);
530
+        }
531
+
532
+        $calendar = [
533
+            'id' => $row['id'],
534
+            'uri' => $row['uri'],
535
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
540
+        ];
541
+
542
+        foreach($this->propertyMap as $xmlName=>$dbName) {
543
+            $calendar[$xmlName] = $row[$dbName];
544
+        }
545
+
546
+        return $calendar;
547
+    }
548
+
549
+    public function getCalendarById($calendarId) {
550
+        $fields = array_values($this->propertyMap);
551
+        $fields[] = 'id';
552
+        $fields[] = 'uri';
553
+        $fields[] = 'synctoken';
554
+        $fields[] = 'components';
555
+        $fields[] = 'principaluri';
556
+        $fields[] = 'transparent';
557
+
558
+        // Making fields a comma-delimited list
559
+        $query = $this->db->getQueryBuilder();
560
+        $query->select($fields)->from('calendars')
561
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
562
+            ->setMaxResults(1);
563
+        $stmt = $query->execute();
564
+
565
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
566
+        $stmt->closeCursor();
567
+        if ($row === false) {
568
+            return null;
569
+        }
570
+
571
+        $components = [];
572
+        if ($row['components']) {
573
+            $components = explode(',',$row['components']);
574
+        }
575
+
576
+        $calendar = [
577
+            'id' => $row['id'],
578
+            'uri' => $row['uri'],
579
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
584
+        ];
585
+
586
+        foreach($this->propertyMap as $xmlName=>$dbName) {
587
+            $calendar[$xmlName] = $row[$dbName];
588
+        }
589
+
590
+        return $calendar;
591
+    }
592
+
593
+    /**
594
+     * Creates a new calendar for a principal.
595
+     *
596
+     * If the creation was a success, an id must be returned that can be used to reference
597
+     * this calendar in other methods, such as updateCalendar.
598
+     *
599
+     * @param string $principalUri
600
+     * @param string $calendarUri
601
+     * @param array $properties
602
+     * @return int
603
+     */
604
+    function createCalendar($principalUri, $calendarUri, array $properties) {
605
+        $values = [
606
+            'principaluri' => $this->convertPrincipal($principalUri, true),
607
+            'uri'          => $calendarUri,
608
+            'synctoken'    => 1,
609
+            'transparent'  => 0,
610
+            'components'   => 'VEVENT,VTODO',
611
+            'displayname'  => $calendarUri
612
+        ];
613
+
614
+        // Default value
615
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616
+        if (isset($properties[$sccs])) {
617
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619
+            }
620
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
621
+        }
622
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
623
+        if (isset($properties[$transp])) {
624
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625
+        }
626
+
627
+        foreach($this->propertyMap as $xmlName=>$dbName) {
628
+            if (isset($properties[$xmlName])) {
629
+                $values[$dbName] = $properties[$xmlName];
630
+            }
631
+        }
632
+
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->insert('calendars');
635
+        foreach($values as $column => $value) {
636
+            $query->setValue($column, $query->createNamedParameter($value));
637
+        }
638
+        $query->execute();
639
+        $calendarId = $query->getLastInsertId();
640
+
641
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
642
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
643
+            [
644
+                'calendarId' => $calendarId,
645
+                'calendarData' => $this->getCalendarById($calendarId),
646
+        ]));
647
+
648
+        return $calendarId;
649
+    }
650
+
651
+    /**
652
+     * Updates properties for a calendar.
653
+     *
654
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
655
+     * To do the actual updates, you must tell this object which properties
656
+     * you're going to process with the handle() method.
657
+     *
658
+     * Calling the handle method is like telling the PropPatch object "I
659
+     * promise I can handle updating this property".
660
+     *
661
+     * Read the PropPatch documentation for more info and examples.
662
+     *
663
+     * @param PropPatch $propPatch
664
+     * @return void
665
+     */
666
+    function updateCalendar($calendarId, PropPatch $propPatch) {
667
+        $supportedProperties = array_keys($this->propertyMap);
668
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
669
+
670
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671
+            $newValues = [];
672
+            foreach ($mutations as $propertyName => $propertyValue) {
673
+
674
+                switch ($propertyName) {
675
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
676
+                        $fieldName = 'transparent';
677
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678
+                        break;
679
+                    default :
680
+                        $fieldName = $this->propertyMap[$propertyName];
681
+                        $newValues[$fieldName] = $propertyValue;
682
+                        break;
683
+                }
684
+
685
+            }
686
+            $query = $this->db->getQueryBuilder();
687
+            $query->update('calendars');
688
+            foreach ($newValues as $fieldName => $value) {
689
+                $query->set($fieldName, $query->createNamedParameter($value));
690
+            }
691
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
692
+            $query->execute();
693
+
694
+            $this->addChange($calendarId, "", 2);
695
+
696
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
697
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
698
+                [
699
+                    'calendarId' => $calendarId,
700
+                    'calendarData' => $this->getCalendarById($calendarId),
701
+                    'shares' => $this->getShares($calendarId),
702
+                    'propertyMutations' => $mutations,
703
+            ]));
704
+
705
+            return true;
706
+        });
707
+    }
708
+
709
+    /**
710
+     * Delete a calendar and all it's objects
711
+     *
712
+     * @param mixed $calendarId
713
+     * @return void
714
+     */
715
+    function deleteCalendar($calendarId) {
716
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
717
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
718
+            [
719
+                'calendarId' => $calendarId,
720
+                'calendarData' => $this->getCalendarById($calendarId),
721
+                'shares' => $this->getShares($calendarId),
722
+        ]));
723
+
724
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?');
725
+        $stmt->execute([$calendarId]);
726
+
727
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
728
+        $stmt->execute([$calendarId]);
729
+
730
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ?');
731
+        $stmt->execute([$calendarId]);
732
+
733
+        $this->sharingBackend->deleteAllShares($calendarId);
734
+    }
735
+
736
+    /**
737
+     * Delete all of an user's shares
738
+     *
739
+     * @param string $principaluri
740
+     * @return void
741
+     */
742
+    function deleteAllSharesByUser($principaluri) {
743
+        $this->sharingBackend->deleteAllSharesByUser($principaluri);
744
+    }
745
+
746
+    /**
747
+     * Returns all calendar objects within a calendar.
748
+     *
749
+     * Every item contains an array with the following keys:
750
+     *   * calendardata - The iCalendar-compatible calendar data
751
+     *   * uri - a unique key which will be used to construct the uri. This can
752
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
753
+     *     good idea. This is only the basename, or filename, not the full
754
+     *     path.
755
+     *   * lastmodified - a timestamp of the last modification time
756
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
757
+     *   '"abcdef"')
758
+     *   * size - The size of the calendar objects, in bytes.
759
+     *   * component - optional, a string containing the type of object, such
760
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
761
+     *     the Content-Type header.
762
+     *
763
+     * Note that the etag is optional, but it's highly encouraged to return for
764
+     * speed reasons.
765
+     *
766
+     * The calendardata is also optional. If it's not returned
767
+     * 'getCalendarObject' will be called later, which *is* expected to return
768
+     * calendardata.
769
+     *
770
+     * If neither etag or size are specified, the calendardata will be
771
+     * used/fetched to determine these numbers. If both are specified the
772
+     * amount of times this is needed is reduced by a great degree.
773
+     *
774
+     * @param mixed $calendarId
775
+     * @return array
776
+     */
777
+    function getCalendarObjects($calendarId) {
778
+        $query = $this->db->getQueryBuilder();
779
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
780
+            ->from('calendarobjects')
781
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
782
+        $stmt = $query->execute();
783
+
784
+        $result = [];
785
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786
+            $result[] = [
787
+                    'id'           => $row['id'],
788
+                    'uri'          => $row['uri'],
789
+                    'lastmodified' => $row['lastmodified'],
790
+                    'etag'         => '"' . $row['etag'] . '"',
791
+                    'calendarid'   => $row['calendarid'],
792
+                    'size'         => (int)$row['size'],
793
+                    'component'    => strtolower($row['componenttype']),
794
+                    'classification'=> (int)$row['classification']
795
+            ];
796
+        }
797
+
798
+        return $result;
799
+    }
800
+
801
+    /**
802
+     * Returns information from a single calendar object, based on it's object
803
+     * uri.
804
+     *
805
+     * The object uri is only the basename, or filename and not a full path.
806
+     *
807
+     * The returned array must have the same keys as getCalendarObjects. The
808
+     * 'calendardata' object is required here though, while it's not required
809
+     * for getCalendarObjects.
810
+     *
811
+     * This method must return null if the object did not exist.
812
+     *
813
+     * @param mixed $calendarId
814
+     * @param string $objectUri
815
+     * @return array|null
816
+     */
817
+    function getCalendarObject($calendarId, $objectUri) {
818
+
819
+        $query = $this->db->getQueryBuilder();
820
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
821
+                ->from('calendarobjects')
822
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
823
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)));
824
+        $stmt = $query->execute();
825
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
826
+
827
+        if(!$row) return null;
828
+
829
+        return [
830
+                'id'            => $row['id'],
831
+                'uri'           => $row['uri'],
832
+                'lastmodified'  => $row['lastmodified'],
833
+                'etag'          => '"' . $row['etag'] . '"',
834
+                'calendarid'    => $row['calendarid'],
835
+                'size'          => (int)$row['size'],
836
+                'calendardata'  => $this->readBlob($row['calendardata']),
837
+                'component'     => strtolower($row['componenttype']),
838
+                'classification'=> (int)$row['classification']
839
+        ];
840
+    }
841
+
842
+    /**
843
+     * Returns a list of calendar objects.
844
+     *
845
+     * This method should work identical to getCalendarObject, but instead
846
+     * return all the calendar objects in the list as an array.
847
+     *
848
+     * If the backend supports this, it may allow for some speed-ups.
849
+     *
850
+     * @param mixed $calendarId
851
+     * @param string[] $uris
852
+     * @return array
853
+     */
854
+    function getMultipleCalendarObjects($calendarId, array $uris) {
855
+        if (empty($uris)) {
856
+            return [];
857
+        }
858
+
859
+        $chunks = array_chunk($uris, 100);
860
+        $objects = [];
861
+
862
+        $query = $this->db->getQueryBuilder();
863
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
864
+            ->from('calendarobjects')
865
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
866
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
867
+
868
+        foreach ($chunks as $uris) {
869
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
870
+            $result = $query->execute();
871
+
872
+            while ($row = $result->fetch()) {
873
+                $objects[] = [
874
+                    'id'           => $row['id'],
875
+                    'uri'          => $row['uri'],
876
+                    'lastmodified' => $row['lastmodified'],
877
+                    'etag'         => '"' . $row['etag'] . '"',
878
+                    'calendarid'   => $row['calendarid'],
879
+                    'size'         => (int)$row['size'],
880
+                    'calendardata' => $this->readBlob($row['calendardata']),
881
+                    'component'    => strtolower($row['componenttype']),
882
+                    'classification' => (int)$row['classification']
883
+                ];
884
+            }
885
+            $result->closeCursor();
886
+        }
887
+        return $objects;
888
+    }
889
+
890
+    /**
891
+     * Creates a new calendar object.
892
+     *
893
+     * The object uri is only the basename, or filename and not a full path.
894
+     *
895
+     * It is possible return an etag from this function, which will be used in
896
+     * the response to this PUT request. Note that the ETag must be surrounded
897
+     * by double-quotes.
898
+     *
899
+     * However, you should only really return this ETag if you don't mangle the
900
+     * calendar-data. If the result of a subsequent GET to this object is not
901
+     * the exact same as this request body, you should omit the ETag.
902
+     *
903
+     * @param mixed $calendarId
904
+     * @param string $objectUri
905
+     * @param string $calendarData
906
+     * @return string
907
+     */
908
+    function createCalendarObject($calendarId, $objectUri, $calendarData) {
909
+        $extraData = $this->getDenormalizedData($calendarData);
910
+
911
+        $query = $this->db->getQueryBuilder();
912
+        $query->insert('calendarobjects')
913
+            ->values([
914
+                'calendarid' => $query->createNamedParameter($calendarId),
915
+                'uri' => $query->createNamedParameter($objectUri),
916
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
917
+                'lastmodified' => $query->createNamedParameter(time()),
918
+                'etag' => $query->createNamedParameter($extraData['etag']),
919
+                'size' => $query->createNamedParameter($extraData['size']),
920
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
921
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
922
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
923
+                'classification' => $query->createNamedParameter($extraData['classification']),
924
+                'uid' => $query->createNamedParameter($extraData['uid']),
925
+            ])
926
+            ->execute();
927
+
928
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
929
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
930
+            [
931
+                'calendarId' => $calendarId,
932
+                'calendarData' => $this->getCalendarById($calendarId),
933
+                'shares' => $this->getShares($calendarId),
934
+                'objectData' => $this->getCalendarObject($calendarId, $objectUri),
935
+            ]
936
+        ));
937
+        $this->addChange($calendarId, $objectUri, 1);
938
+
939
+        return '"' . $extraData['etag'] . '"';
940
+    }
941
+
942
+    /**
943
+     * Updates an existing calendarobject, based on it's uri.
944
+     *
945
+     * The object uri is only the basename, or filename and not a full path.
946
+     *
947
+     * It is possible return an etag from this function, which will be used in
948
+     * the response to this PUT request. Note that the ETag must be surrounded
949
+     * by double-quotes.
950
+     *
951
+     * However, you should only really return this ETag if you don't mangle the
952
+     * calendar-data. If the result of a subsequent GET to this object is not
953
+     * the exact same as this request body, you should omit the ETag.
954
+     *
955
+     * @param mixed $calendarId
956
+     * @param string $objectUri
957
+     * @param string $calendarData
958
+     * @return string
959
+     */
960
+    function updateCalendarObject($calendarId, $objectUri, $calendarData) {
961
+        $extraData = $this->getDenormalizedData($calendarData);
962
+
963
+        $query = $this->db->getQueryBuilder();
964
+        $query->update('calendarobjects')
965
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
966
+                ->set('lastmodified', $query->createNamedParameter(time()))
967
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
968
+                ->set('size', $query->createNamedParameter($extraData['size']))
969
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
970
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
971
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
972
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
973
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
974
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
975
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
976
+            ->execute();
977
+
978
+        $data = $this->getCalendarObject($calendarId, $objectUri);
979
+        if (is_array($data)) {
980
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
981
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
982
+                [
983
+                    'calendarId' => $calendarId,
984
+                    'calendarData' => $this->getCalendarById($calendarId),
985
+                    'shares' => $this->getShares($calendarId),
986
+                    'objectData' => $data,
987
+                ]
988
+            ));
989
+        }
990
+        $this->addChange($calendarId, $objectUri, 2);
991
+
992
+        return '"' . $extraData['etag'] . '"';
993
+    }
994
+
995
+    /**
996
+     * @param int $calendarObjectId
997
+     * @param int $classification
998
+     */
999
+    public function setClassification($calendarObjectId, $classification) {
1000
+        if (!in_array($classification, [
1001
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1002
+        ])) {
1003
+            throw new \InvalidArgumentException();
1004
+        }
1005
+        $query = $this->db->getQueryBuilder();
1006
+        $query->update('calendarobjects')
1007
+            ->set('classification', $query->createNamedParameter($classification))
1008
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1009
+            ->execute();
1010
+    }
1011
+
1012
+    /**
1013
+     * Deletes an existing calendar object.
1014
+     *
1015
+     * The object uri is only the basename, or filename and not a full path.
1016
+     *
1017
+     * @param mixed $calendarId
1018
+     * @param string $objectUri
1019
+     * @return void
1020
+     */
1021
+    function deleteCalendarObject($calendarId, $objectUri) {
1022
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1023
+        if (is_array($data)) {
1024
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1025
+                '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1026
+                [
1027
+                    'calendarId' => $calendarId,
1028
+                    'calendarData' => $this->getCalendarById($calendarId),
1029
+                    'shares' => $this->getShares($calendarId),
1030
+                    'objectData' => $data,
1031
+                ]
1032
+            ));
1033
+        }
1034
+
1035
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ?');
1036
+        $stmt->execute([$calendarId, $objectUri]);
1037
+
1038
+        $this->addChange($calendarId, $objectUri, 3);
1039
+    }
1040
+
1041
+    /**
1042
+     * Performs a calendar-query on the contents of this calendar.
1043
+     *
1044
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1045
+     * calendar-query it is possible for a client to request a specific set of
1046
+     * object, based on contents of iCalendar properties, date-ranges and
1047
+     * iCalendar component types (VTODO, VEVENT).
1048
+     *
1049
+     * This method should just return a list of (relative) urls that match this
1050
+     * query.
1051
+     *
1052
+     * The list of filters are specified as an array. The exact array is
1053
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1054
+     *
1055
+     * Note that it is extremely likely that getCalendarObject for every path
1056
+     * returned from this method will be called almost immediately after. You
1057
+     * may want to anticipate this to speed up these requests.
1058
+     *
1059
+     * This method provides a default implementation, which parses *all* the
1060
+     * iCalendar objects in the specified calendar.
1061
+     *
1062
+     * This default may well be good enough for personal use, and calendars
1063
+     * that aren't very large. But if you anticipate high usage, big calendars
1064
+     * or high loads, you are strongly advised to optimize certain paths.
1065
+     *
1066
+     * The best way to do so is override this method and to optimize
1067
+     * specifically for 'common filters'.
1068
+     *
1069
+     * Requests that are extremely common are:
1070
+     *   * requests for just VEVENTS
1071
+     *   * requests for just VTODO
1072
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1073
+     *
1074
+     * ..and combinations of these requests. It may not be worth it to try to
1075
+     * handle every possible situation and just rely on the (relatively
1076
+     * easy to use) CalendarQueryValidator to handle the rest.
1077
+     *
1078
+     * Note that especially time-range-filters may be difficult to parse. A
1079
+     * time-range filter specified on a VEVENT must for instance also handle
1080
+     * recurrence rules correctly.
1081
+     * A good example of how to interprete all these filters can also simply
1082
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1083
+     * as possible, so it gives you a good idea on what type of stuff you need
1084
+     * to think of.
1085
+     *
1086
+     * @param mixed $calendarId
1087
+     * @param array $filters
1088
+     * @return array
1089
+     */
1090
+    function calendarQuery($calendarId, array $filters) {
1091
+        $componentType = null;
1092
+        $requirePostFilter = true;
1093
+        $timeRange = null;
1094
+
1095
+        // if no filters were specified, we don't need to filter after a query
1096
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1097
+            $requirePostFilter = false;
1098
+        }
1099
+
1100
+        // Figuring out if there's a component filter
1101
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1102
+            $componentType = $filters['comp-filters'][0]['name'];
1103
+
1104
+            // Checking if we need post-filters
1105
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1106
+                $requirePostFilter = false;
1107
+            }
1108
+            // There was a time-range filter
1109
+            if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1110
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1111
+
1112
+                // If start time OR the end time is not specified, we can do a
1113
+                // 100% accurate mysql query.
1114
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1115
+                    $requirePostFilter = false;
1116
+                }
1117
+            }
1118
+
1119
+        }
1120
+        $columns = ['uri'];
1121
+        if ($requirePostFilter) {
1122
+            $columns = ['uri', 'calendardata'];
1123
+        }
1124
+        $query = $this->db->getQueryBuilder();
1125
+        $query->select($columns)
1126
+            ->from('calendarobjects')
1127
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
1128
+
1129
+        if ($componentType) {
1130
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1131
+        }
1132
+
1133
+        if ($timeRange && $timeRange['start']) {
1134
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1135
+        }
1136
+        if ($timeRange && $timeRange['end']) {
1137
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1138
+        }
1139
+
1140
+        $stmt = $query->execute();
1141
+
1142
+        $result = [];
1143
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144
+            if ($requirePostFilter) {
1145
+                if (!$this->validateFilterForObject($row, $filters)) {
1146
+                    continue;
1147
+                }
1148
+            }
1149
+            $result[] = $row['uri'];
1150
+        }
1151
+
1152
+        return $result;
1153
+    }
1154
+
1155
+    /**
1156
+     * Searches through all of a users calendars and calendar objects to find
1157
+     * an object with a specific UID.
1158
+     *
1159
+     * This method should return the path to this object, relative to the
1160
+     * calendar home, so this path usually only contains two parts:
1161
+     *
1162
+     * calendarpath/objectpath.ics
1163
+     *
1164
+     * If the uid is not found, return null.
1165
+     *
1166
+     * This method should only consider * objects that the principal owns, so
1167
+     * any calendars owned by other principals that also appear in this
1168
+     * collection should be ignored.
1169
+     *
1170
+     * @param string $principalUri
1171
+     * @param string $uid
1172
+     * @return string|null
1173
+     */
1174
+    function getCalendarObjectByUID($principalUri, $uid) {
1175
+
1176
+        $query = $this->db->getQueryBuilder();
1177
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1178
+            ->from('calendarobjects', 'co')
1179
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1180
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1181
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1182
+
1183
+        $stmt = $query->execute();
1184
+
1185
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1187
+        }
1188
+
1189
+        return null;
1190
+    }
1191
+
1192
+    /**
1193
+     * The getChanges method returns all the changes that have happened, since
1194
+     * the specified syncToken in the specified calendar.
1195
+     *
1196
+     * This function should return an array, such as the following:
1197
+     *
1198
+     * [
1199
+     *   'syncToken' => 'The current synctoken',
1200
+     *   'added'   => [
1201
+     *      'new.txt',
1202
+     *   ],
1203
+     *   'modified'   => [
1204
+     *      'modified.txt',
1205
+     *   ],
1206
+     *   'deleted' => [
1207
+     *      'foo.php.bak',
1208
+     *      'old.txt'
1209
+     *   ]
1210
+     * );
1211
+     *
1212
+     * The returned syncToken property should reflect the *current* syncToken
1213
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1214
+     * property This is * needed here too, to ensure the operation is atomic.
1215
+     *
1216
+     * If the $syncToken argument is specified as null, this is an initial
1217
+     * sync, and all members should be reported.
1218
+     *
1219
+     * The modified property is an array of nodenames that have changed since
1220
+     * the last token.
1221
+     *
1222
+     * The deleted property is an array with nodenames, that have been deleted
1223
+     * from collection.
1224
+     *
1225
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1226
+     * 1, you only have to report changes that happened only directly in
1227
+     * immediate descendants. If it's 2, it should also include changes from
1228
+     * the nodes below the child collections. (grandchildren)
1229
+     *
1230
+     * The $limit argument allows a client to specify how many results should
1231
+     * be returned at most. If the limit is not specified, it should be treated
1232
+     * as infinite.
1233
+     *
1234
+     * If the limit (infinite or not) is higher than you're willing to return,
1235
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1236
+     *
1237
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1238
+     * return null.
1239
+     *
1240
+     * The limit is 'suggestive'. You are free to ignore it.
1241
+     *
1242
+     * @param string $calendarId
1243
+     * @param string $syncToken
1244
+     * @param int $syncLevel
1245
+     * @param int $limit
1246
+     * @return array
1247
+     */
1248
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249
+        // Current synctoken
1250
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
+        $stmt->execute([ $calendarId ]);
1252
+        $currentToken = $stmt->fetchColumn(0);
1253
+
1254
+        if (is_null($currentToken)) {
1255
+            return null;
1256
+        }
1257
+
1258
+        $result = [
1259
+            'syncToken' => $currentToken,
1260
+            'added'     => [],
1261
+            'modified'  => [],
1262
+            'deleted'   => [],
1263
+        ];
1264
+
1265
+        if ($syncToken) {
1266
+
1267
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
+            if ($limit>0) {
1269
+                $query.= " `LIMIT` " . (int)$limit;
1270
+            }
1271
+
1272
+            // Fetching all changes
1273
+            $stmt = $this->db->prepare($query);
1274
+            $stmt->execute([$syncToken, $currentToken, $calendarId]);
1275
+
1276
+            $changes = [];
1277
+
1278
+            // This loop ensures that any duplicates are overwritten, only the
1279
+            // last change on a node is relevant.
1280
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281
+
1282
+                $changes[$row['uri']] = $row['operation'];
1283
+
1284
+            }
1285
+
1286
+            foreach($changes as $uri => $operation) {
1287
+
1288
+                switch($operation) {
1289
+                    case 1 :
1290
+                        $result['added'][] = $uri;
1291
+                        break;
1292
+                    case 2 :
1293
+                        $result['modified'][] = $uri;
1294
+                        break;
1295
+                    case 3 :
1296
+                        $result['deleted'][] = $uri;
1297
+                        break;
1298
+                }
1299
+
1300
+            }
1301
+        } else {
1302
+            // No synctoken supplied, this is the initial sync.
1303
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ?";
1304
+            $stmt = $this->db->prepare($query);
1305
+            $stmt->execute([$calendarId]);
1306
+
1307
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1308
+        }
1309
+        return $result;
1310
+
1311
+    }
1312
+
1313
+    /**
1314
+     * Returns a list of subscriptions for a principal.
1315
+     *
1316
+     * Every subscription is an array with the following keys:
1317
+     *  * id, a unique id that will be used by other functions to modify the
1318
+     *    subscription. This can be the same as the uri or a database key.
1319
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1320
+     *  * principaluri. The owner of the subscription. Almost always the same as
1321
+     *    principalUri passed to this method.
1322
+     *
1323
+     * Furthermore, all the subscription info must be returned too:
1324
+     *
1325
+     * 1. {DAV:}displayname
1326
+     * 2. {http://apple.com/ns/ical/}refreshrate
1327
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1328
+     *    should not be stripped).
1329
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1330
+     *    should not be stripped).
1331
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1332
+     *    attachments should not be stripped).
1333
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1334
+     *     Sabre\DAV\Property\Href).
1335
+     * 7. {http://apple.com/ns/ical/}calendar-color
1336
+     * 8. {http://apple.com/ns/ical/}calendar-order
1337
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1338
+     *    (should just be an instance of
1339
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1340
+     *    default components).
1341
+     *
1342
+     * @param string $principalUri
1343
+     * @return array
1344
+     */
1345
+    function getSubscriptionsForUser($principalUri) {
1346
+        $fields = array_values($this->subscriptionPropertyMap);
1347
+        $fields[] = 'id';
1348
+        $fields[] = 'uri';
1349
+        $fields[] = 'source';
1350
+        $fields[] = 'principaluri';
1351
+        $fields[] = 'lastmodified';
1352
+
1353
+        $query = $this->db->getQueryBuilder();
1354
+        $query->select($fields)
1355
+            ->from('calendarsubscriptions')
1356
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357
+            ->orderBy('calendarorder', 'asc');
1358
+        $stmt =$query->execute();
1359
+
1360
+        $subscriptions = [];
1361
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362
+
1363
+            $subscription = [
1364
+                'id'           => $row['id'],
1365
+                'uri'          => $row['uri'],
1366
+                'principaluri' => $row['principaluri'],
1367
+                'source'       => $row['source'],
1368
+                'lastmodified' => $row['lastmodified'],
1369
+
1370
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371
+            ];
1372
+
1373
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374
+                if (!is_null($row[$dbName])) {
1375
+                    $subscription[$xmlName] = $row[$dbName];
1376
+                }
1377
+            }
1378
+
1379
+            $subscriptions[] = $subscription;
1380
+
1381
+        }
1382
+
1383
+        return $subscriptions;
1384
+    }
1385
+
1386
+    /**
1387
+     * Creates a new subscription for a principal.
1388
+     *
1389
+     * If the creation was a success, an id must be returned that can be used to reference
1390
+     * this subscription in other methods, such as updateSubscription.
1391
+     *
1392
+     * @param string $principalUri
1393
+     * @param string $uri
1394
+     * @param array $properties
1395
+     * @return mixed
1396
+     */
1397
+    function createSubscription($principalUri, $uri, array $properties) {
1398
+
1399
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1400
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1401
+        }
1402
+
1403
+        $values = [
1404
+            'principaluri' => $principalUri,
1405
+            'uri'          => $uri,
1406
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1407
+            'lastmodified' => time(),
1408
+        ];
1409
+
1410
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411
+
1412
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413
+            if (array_key_exists($xmlName, $properties)) {
1414
+                    $values[$dbName] = $properties[$xmlName];
1415
+                    if (in_array($dbName, $propertiesBoolean)) {
1416
+                        $values[$dbName] = true;
1417
+                }
1418
+            }
1419
+        }
1420
+
1421
+        $valuesToInsert = array();
1422
+
1423
+        $query = $this->db->getQueryBuilder();
1424
+
1425
+        foreach (array_keys($values) as $name) {
1426
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1427
+        }
1428
+
1429
+        $query->insert('calendarsubscriptions')
1430
+            ->values($valuesToInsert)
1431
+            ->execute();
1432
+
1433
+        return $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1434
+    }
1435
+
1436
+    /**
1437
+     * Updates a subscription
1438
+     *
1439
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1440
+     * To do the actual updates, you must tell this object which properties
1441
+     * you're going to process with the handle() method.
1442
+     *
1443
+     * Calling the handle method is like telling the PropPatch object "I
1444
+     * promise I can handle updating this property".
1445
+     *
1446
+     * Read the PropPatch documentation for more info and examples.
1447
+     *
1448
+     * @param mixed $subscriptionId
1449
+     * @param PropPatch $propPatch
1450
+     * @return void
1451
+     */
1452
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1453
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1454
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1455
+
1456
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1457
+
1458
+            $newValues = [];
1459
+
1460
+            foreach($mutations as $propertyName=>$propertyValue) {
1461
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462
+                    $newValues['source'] = $propertyValue->getHref();
1463
+                } else {
1464
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1465
+                    $newValues[$fieldName] = $propertyValue;
1466
+                }
1467
+            }
1468
+
1469
+            $query = $this->db->getQueryBuilder();
1470
+            $query->update('calendarsubscriptions')
1471
+                ->set('lastmodified', $query->createNamedParameter(time()));
1472
+            foreach($newValues as $fieldName=>$value) {
1473
+                $query->set($fieldName, $query->createNamedParameter($value));
1474
+            }
1475
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1476
+                ->execute();
1477
+
1478
+            return true;
1479
+
1480
+        });
1481
+    }
1482
+
1483
+    /**
1484
+     * Deletes a subscription.
1485
+     *
1486
+     * @param mixed $subscriptionId
1487
+     * @return void
1488
+     */
1489
+    function deleteSubscription($subscriptionId) {
1490
+        $query = $this->db->getQueryBuilder();
1491
+        $query->delete('calendarsubscriptions')
1492
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
1493
+            ->execute();
1494
+    }
1495
+
1496
+    /**
1497
+     * Returns a single scheduling object for the inbox collection.
1498
+     *
1499
+     * The returned array should contain the following elements:
1500
+     *   * uri - A unique basename for the object. This will be used to
1501
+     *           construct a full uri.
1502
+     *   * calendardata - The iCalendar object
1503
+     *   * lastmodified - The last modification date. Can be an int for a unix
1504
+     *                    timestamp, or a PHP DateTime object.
1505
+     *   * etag - A unique token that must change if the object changed.
1506
+     *   * size - The size of the object, in bytes.
1507
+     *
1508
+     * @param string $principalUri
1509
+     * @param string $objectUri
1510
+     * @return array
1511
+     */
1512
+    function getSchedulingObject($principalUri, $objectUri) {
1513
+        $query = $this->db->getQueryBuilder();
1514
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1515
+            ->from('schedulingobjects')
1516
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1517
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1518
+            ->execute();
1519
+
1520
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521
+
1522
+        if(!$row) {
1523
+            return null;
1524
+        }
1525
+
1526
+        return [
1527
+                'uri'          => $row['uri'],
1528
+                'calendardata' => $row['calendardata'],
1529
+                'lastmodified' => $row['lastmodified'],
1530
+                'etag'         => '"' . $row['etag'] . '"',
1531
+                'size'         => (int)$row['size'],
1532
+        ];
1533
+    }
1534
+
1535
+    /**
1536
+     * Returns all scheduling objects for the inbox collection.
1537
+     *
1538
+     * These objects should be returned as an array. Every item in the array
1539
+     * should follow the same structure as returned from getSchedulingObject.
1540
+     *
1541
+     * The main difference is that 'calendardata' is optional.
1542
+     *
1543
+     * @param string $principalUri
1544
+     * @return array
1545
+     */
1546
+    function getSchedulingObjects($principalUri) {
1547
+        $query = $this->db->getQueryBuilder();
1548
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
1549
+                ->from('schedulingobjects')
1550
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1551
+                ->execute();
1552
+
1553
+        $result = [];
1554
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555
+            $result[] = [
1556
+                    'calendardata' => $row['calendardata'],
1557
+                    'uri'          => $row['uri'],
1558
+                    'lastmodified' => $row['lastmodified'],
1559
+                    'etag'         => '"' . $row['etag'] . '"',
1560
+                    'size'         => (int)$row['size'],
1561
+            ];
1562
+        }
1563
+
1564
+        return $result;
1565
+    }
1566
+
1567
+    /**
1568
+     * Deletes a scheduling object from the inbox collection.
1569
+     *
1570
+     * @param string $principalUri
1571
+     * @param string $objectUri
1572
+     * @return void
1573
+     */
1574
+    function deleteSchedulingObject($principalUri, $objectUri) {
1575
+        $query = $this->db->getQueryBuilder();
1576
+        $query->delete('schedulingobjects')
1577
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1578
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1579
+                ->execute();
1580
+    }
1581
+
1582
+    /**
1583
+     * Creates a new scheduling object. This should land in a users' inbox.
1584
+     *
1585
+     * @param string $principalUri
1586
+     * @param string $objectUri
1587
+     * @param string $objectData
1588
+     * @return void
1589
+     */
1590
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
1591
+        $query = $this->db->getQueryBuilder();
1592
+        $query->insert('schedulingobjects')
1593
+            ->values([
1594
+                'principaluri' => $query->createNamedParameter($principalUri),
1595
+                'calendardata' => $query->createNamedParameter($objectData),
1596
+                'uri' => $query->createNamedParameter($objectUri),
1597
+                'lastmodified' => $query->createNamedParameter(time()),
1598
+                'etag' => $query->createNamedParameter(md5($objectData)),
1599
+                'size' => $query->createNamedParameter(strlen($objectData))
1600
+            ])
1601
+            ->execute();
1602
+    }
1603
+
1604
+    /**
1605
+     * Adds a change record to the calendarchanges table.
1606
+     *
1607
+     * @param mixed $calendarId
1608
+     * @param string $objectUri
1609
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
1610
+     * @return void
1611
+     */
1612
+    protected function addChange($calendarId, $objectUri, $operation) {
1613
+
1614
+        $stmt = $this->db->prepare('INSERT INTO `*PREFIX*calendarchanges` (`uri`, `synctoken`, `calendarid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*calendars` WHERE `id` = ?');
1615
+        $stmt->execute([
1616
+            $objectUri,
1617
+            $calendarId,
1618
+            $operation,
1619
+            $calendarId
1620
+        ]);
1621
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*calendars` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
1622
+        $stmt->execute([
1623
+            $calendarId
1624
+        ]);
1625
+
1626
+    }
1627
+
1628
+    /**
1629
+     * Parses some information from calendar objects, used for optimized
1630
+     * calendar-queries.
1631
+     *
1632
+     * Returns an array with the following keys:
1633
+     *   * etag - An md5 checksum of the object without the quotes.
1634
+     *   * size - Size of the object in bytes
1635
+     *   * componentType - VEVENT, VTODO or VJOURNAL
1636
+     *   * firstOccurence
1637
+     *   * lastOccurence
1638
+     *   * uid - value of the UID property
1639
+     *
1640
+     * @param string $calendarData
1641
+     * @return array
1642
+     */
1643
+    public function getDenormalizedData($calendarData) {
1644
+
1645
+        $vObject = Reader::read($calendarData);
1646
+        $componentType = null;
1647
+        $component = null;
1648
+        $firstOccurrence = null;
1649
+        $lastOccurrence = null;
1650
+        $uid = null;
1651
+        $classification = self::CLASSIFICATION_PUBLIC;
1652
+        foreach($vObject->getComponents() as $component) {
1653
+            if ($component->name!=='VTIMEZONE') {
1654
+                $componentType = $component->name;
1655
+                $uid = (string)$component->UID;
1656
+                break;
1657
+            }
1658
+        }
1659
+        if (!$componentType) {
1660
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
1661
+        }
1662
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
1663
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
1664
+            // Finding the last occurrence is a bit harder
1665
+            if (!isset($component->RRULE)) {
1666
+                if (isset($component->DTEND)) {
1667
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
1668
+                } elseif (isset($component->DURATION)) {
1669
+                    $endDate = clone $component->DTSTART->getDateTime();
1670
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
1671
+                    $lastOccurrence = $endDate->getTimeStamp();
1672
+                } elseif (!$component->DTSTART->hasTime()) {
1673
+                    $endDate = clone $component->DTSTART->getDateTime();
1674
+                    $endDate->modify('+1 day');
1675
+                    $lastOccurrence = $endDate->getTimeStamp();
1676
+                } else {
1677
+                    $lastOccurrence = $firstOccurrence;
1678
+                }
1679
+            } else {
1680
+                $it = new EventIterator($vObject, (string)$component->UID);
1681
+                $maxDate = new \DateTime(self::MAX_DATE);
1682
+                if ($it->isInfinite()) {
1683
+                    $lastOccurrence = $maxDate->getTimestamp();
1684
+                } else {
1685
+                    $end = $it->getDtEnd();
1686
+                    while($it->valid() && $end < $maxDate) {
1687
+                        $end = $it->getDtEnd();
1688
+                        $it->next();
1689
+
1690
+                    }
1691
+                    $lastOccurrence = $end->getTimestamp();
1692
+                }
1693
+
1694
+            }
1695
+        }
1696
+
1697
+        if ($component->CLASS) {
1698
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
1699
+            switch ($component->CLASS->getValue()) {
1700
+                case 'PUBLIC':
1701
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
1702
+                    break;
1703
+                case 'CONFIDENTIAL':
1704
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
1705
+                    break;
1706
+            }
1707
+        }
1708
+        return [
1709
+            'etag' => md5($calendarData),
1710
+            'size' => strlen($calendarData),
1711
+            'componentType' => $componentType,
1712
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
1713
+            'lastOccurence'  => $lastOccurrence,
1714
+            'uid' => $uid,
1715
+            'classification' => $classification
1716
+        ];
1717
+
1718
+    }
1719
+
1720
+    private function readBlob($cardData) {
1721
+        if (is_resource($cardData)) {
1722
+            return stream_get_contents($cardData);
1723
+        }
1724
+
1725
+        return $cardData;
1726
+    }
1727
+
1728
+    /**
1729
+     * @param IShareable $shareable
1730
+     * @param array $add
1731
+     * @param array $remove
1732
+     */
1733
+    public function updateShares($shareable, $add, $remove) {
1734
+        $calendarId = $shareable->getResourceId();
1735
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
1736
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
1737
+            [
1738
+                'calendarId' => $calendarId,
1739
+                'calendarData' => $this->getCalendarById($calendarId),
1740
+                'shares' => $this->getShares($calendarId),
1741
+                'add' => $add,
1742
+                'remove' => $remove,
1743
+            ]));
1744
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
1745
+    }
1746
+
1747
+    /**
1748
+     * @param int $resourceId
1749
+     * @return array
1750
+     */
1751
+    public function getShares($resourceId) {
1752
+        return $this->sharingBackend->getShares($resourceId);
1753
+    }
1754
+
1755
+    /**
1756
+     * @param boolean $value
1757
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1758
+     * @return string|null
1759
+     */
1760
+    public function setPublishStatus($value, $calendar) {
1761
+        $query = $this->db->getQueryBuilder();
1762
+        if ($value) {
1763
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
1764
+            $query->insert('dav_shares')
1765
+                ->values([
1766
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
1767
+                    'type' => $query->createNamedParameter('calendar'),
1768
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
1769
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
1770
+                    'publicuri' => $query->createNamedParameter($publicUri)
1771
+                ]);
1772
+            $query->execute();
1773
+            return $publicUri;
1774
+        }
1775
+        $query->delete('dav_shares')
1776
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1777
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
1778
+        $query->execute();
1779
+        return null;
1780
+    }
1781
+
1782
+    /**
1783
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
1784
+     * @return mixed
1785
+     */
1786
+    public function getPublishStatus($calendar) {
1787
+        $query = $this->db->getQueryBuilder();
1788
+        $result = $query->select('publicuri')
1789
+            ->from('dav_shares')
1790
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
1791
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
1792
+            ->execute();
1793
+
1794
+        $row = $result->fetch();
1795
+        $result->closeCursor();
1796
+        return $row ? reset($row) : false;
1797
+    }
1798
+
1799
+    /**
1800
+     * @param int $resourceId
1801
+     * @param array $acl
1802
+     * @return array
1803
+     */
1804
+    public function applyShareAcl($resourceId, $acl) {
1805
+        return $this->sharingBackend->applyShareAcl($resourceId, $acl);
1806
+    }
1807
+
1808
+    private function convertPrincipal($principalUri, $toV2) {
1809
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1810
+            list(, $name) = URLUtil::splitPath($principalUri);
1811
+            if ($toV2 === true) {
1812
+                return "principals/users/$name";
1813
+            }
1814
+            return "principals/$name";
1815
+        }
1816
+        return $principalUri;
1817
+    }
1818 1818
 }
Please login to merge, or discard this patch.
Spacing   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
180 180
 		}
181 181
 
182
-		return (int)$query->execute()->fetchColumn();
182
+		return (int) $query->execute()->fetchColumn();
183 183
 	}
184 184
 
185 185
 	/**
@@ -226,25 +226,25 @@  discard block
 block discarded – undo
226 226
 		$stmt = $query->execute();
227 227
 
228 228
 		$calendars = [];
229
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
229
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
230 230
 
231 231
 			$components = [];
232 232
 			if ($row['components']) {
233
-				$components = explode(',',$row['components']);
233
+				$components = explode(',', $row['components']);
234 234
 			}
235 235
 
236 236
 			$calendar = [
237 237
 				'id' => $row['id'],
238 238
 				'uri' => $row['uri'],
239 239
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
240
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
241
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
242
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
244
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
240
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
241
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
242
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
243
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
244
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
245 245
 			];
246 246
 
247
-			foreach($this->propertyMap as $xmlName=>$dbName) {
247
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
248 248
 				$calendar[$xmlName] = $row[$dbName];
249 249
 			}
250 250
 
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
 
258 258
 		// query for shared calendars
259 259
 		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
260
-		$principals[]= $principalUri;
260
+		$principals[] = $principalUri;
261 261
 
262 262
 		$fields = array_values($this->propertyMap);
263 263
 		$fields[] = 'a.id';
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
278 278
 			->execute();
279 279
 
280
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
281
-		while($row = $result->fetch()) {
280
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
281
+		while ($row = $result->fetch()) {
282 282
 			if ($row['principaluri'] === $principalUri) {
283 283
 				continue;
284 284
 			}
@@ -297,25 +297,25 @@  discard block
 block discarded – undo
297 297
 			}
298 298
 
299 299
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
300
-			$uri = $row['uri'] . '_shared_by_' . $name;
301
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
300
+			$uri = $row['uri'].'_shared_by_'.$name;
301
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
302 302
 			$components = [];
303 303
 			if ($row['components']) {
304
-				$components = explode(',',$row['components']);
304
+				$components = explode(',', $row['components']);
305 305
 			}
306 306
 			$calendar = [
307 307
 				'id' => $row['id'],
308 308
 				'uri' => $uri,
309 309
 				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
310
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
311
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
312
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
314
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
310
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
311
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
312
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
313
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
314
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
315 315
 				$readOnlyPropertyName => $readOnly,
316 316
 			];
317 317
 
318
-			foreach($this->propertyMap as $xmlName=>$dbName) {
318
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
319 319
 				$calendar[$xmlName] = $row[$dbName];
320 320
 			}
321 321
 
@@ -342,21 +342,21 @@  discard block
 block discarded – undo
342 342
 			->orderBy('calendarorder', 'ASC');
343 343
 		$stmt = $query->execute();
344 344
 		$calendars = [];
345
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
345
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
346 346
 			$components = [];
347 347
 			if ($row['components']) {
348
-				$components = explode(',',$row['components']);
348
+				$components = explode(',', $row['components']);
349 349
 			}
350 350
 			$calendar = [
351 351
 				'id' => $row['id'],
352 352
 				'uri' => $row['uri'],
353 353
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
354
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
355
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
356
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
355
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
356
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
357
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
358 358
 			];
359
-			foreach($this->propertyMap as $xmlName=>$dbName) {
359
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
360 360
 				$calendar[$xmlName] = $row[$dbName];
361 361
 			}
362 362
 			if (!isset($calendars[$calendar['id']])) {
@@ -404,27 +404,27 @@  discard block
 block discarded – undo
404 404
 			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
405 405
 			->execute();
406 406
 
407
-		while($row = $result->fetch()) {
407
+		while ($row = $result->fetch()) {
408 408
 			list(, $name) = URLUtil::splitPath($row['principaluri']);
409
-			$row['displayname'] = $row['displayname'] . "($name)";
409
+			$row['displayname'] = $row['displayname']."($name)";
410 410
 			$components = [];
411 411
 			if ($row['components']) {
412
-				$components = explode(',',$row['components']);
412
+				$components = explode(',', $row['components']);
413 413
 			}
414 414
 			$calendar = [
415 415
 				'id' => $row['id'],
416 416
 				'uri' => $row['publicuri'],
417 417
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
418
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
419
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
420
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
422
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
424
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
418
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
419
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
420
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
421
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
422
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
423
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
424
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
425 425
 			];
426 426
 
427
-			foreach($this->propertyMap as $xmlName=>$dbName) {
427
+			foreach ($this->propertyMap as $xmlName=>$dbName) {
428 428
 				$calendar[$xmlName] = $row[$dbName];
429 429
 			}
430 430
 
@@ -466,29 +466,29 @@  discard block
 block discarded – undo
466 466
 		$result->closeCursor();
467 467
 
468 468
 		if ($row === false) {
469
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
469
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
470 470
 		}
471 471
 
472 472
 		list(, $name) = URLUtil::splitPath($row['principaluri']);
473
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
473
+		$row['displayname'] = $row['displayname'].' '."($name)";
474 474
 		$components = [];
475 475
 		if ($row['components']) {
476
-			$components = explode(',',$row['components']);
476
+			$components = explode(',', $row['components']);
477 477
 		}
478 478
 		$calendar = [
479 479
 			'id' => $row['id'],
480 480
 			'uri' => $row['publicuri'],
481 481
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
483
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
484
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
488
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
482
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
483
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
484
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
486
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
487
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => (int) $row['access'] === Backend::ACCESS_READ,
488
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
489 489
 		];
490 490
 
491
-		foreach($this->propertyMap as $xmlName=>$dbName) {
491
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
492 492
 			$calendar[$xmlName] = $row[$dbName];
493 493
 		}
494 494
 
@@ -526,20 +526,20 @@  discard block
 block discarded – undo
526 526
 
527 527
 		$components = [];
528 528
 		if ($row['components']) {
529
-			$components = explode(',',$row['components']);
529
+			$components = explode(',', $row['components']);
530 530
 		}
531 531
 
532 532
 		$calendar = [
533 533
 			'id' => $row['id'],
534 534
 			'uri' => $row['uri'],
535 535
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
536
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
537
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
538
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
536
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
537
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
538
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
539
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
540 540
 		];
541 541
 
542
-		foreach($this->propertyMap as $xmlName=>$dbName) {
542
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
543 543
 			$calendar[$xmlName] = $row[$dbName];
544 544
 		}
545 545
 
@@ -570,20 +570,20 @@  discard block
 block discarded – undo
570 570
 
571 571
 		$components = [];
572 572
 		if ($row['components']) {
573
-			$components = explode(',',$row['components']);
573
+			$components = explode(',', $row['components']);
574 574
 		}
575 575
 
576 576
 		$calendar = [
577 577
 			'id' => $row['id'],
578 578
 			'uri' => $row['uri'],
579 579
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
580
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
581
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
582
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
580
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ? $row['synctoken'] : '0'),
581
+			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
582
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
583
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
584 584
 		];
585 585
 
586
-		foreach($this->propertyMap as $xmlName=>$dbName) {
586
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
587 587
 			$calendar[$xmlName] = $row[$dbName];
588 588
 		}
589 589
 
@@ -615,16 +615,16 @@  discard block
 block discarded – undo
615 615
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
616 616
 		if (isset($properties[$sccs])) {
617 617
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
618
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
618
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
619 619
 			}
620
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
620
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
621 621
 		}
622
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
622
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
623 623
 		if (isset($properties[$transp])) {
624 624
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
625 625
 		}
626 626
 
627
-		foreach($this->propertyMap as $xmlName=>$dbName) {
627
+		foreach ($this->propertyMap as $xmlName=>$dbName) {
628 628
 			if (isset($properties[$xmlName])) {
629 629
 				$values[$dbName] = $properties[$xmlName];
630 630
 			}
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 
633 633
 		$query = $this->db->getQueryBuilder();
634 634
 		$query->insert('calendars');
635
-		foreach($values as $column => $value) {
635
+		foreach ($values as $column => $value) {
636 636
 			$query->setValue($column, $query->createNamedParameter($value));
637 637
 		}
638 638
 		$query->execute();
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
 	 */
666 666
 	function updateCalendar($calendarId, PropPatch $propPatch) {
667 667
 		$supportedProperties = array_keys($this->propertyMap);
668
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
668
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
669 669
 
670 670
 		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
671 671
 			$newValues = [];
672 672
 			foreach ($mutations as $propertyName => $propertyValue) {
673 673
 
674 674
 				switch ($propertyName) {
675
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
675
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' :
676 676
 						$fieldName = 'transparent';
677 677
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
678 678
 						break;
@@ -782,16 +782,16 @@  discard block
 block discarded – undo
782 782
 		$stmt = $query->execute();
783 783
 
784 784
 		$result = [];
785
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
785
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
786 786
 			$result[] = [
787 787
 					'id'           => $row['id'],
788 788
 					'uri'          => $row['uri'],
789 789
 					'lastmodified' => $row['lastmodified'],
790
-					'etag'         => '"' . $row['etag'] . '"',
790
+					'etag'         => '"'.$row['etag'].'"',
791 791
 					'calendarid'   => $row['calendarid'],
792
-					'size'         => (int)$row['size'],
792
+					'size'         => (int) $row['size'],
793 793
 					'component'    => strtolower($row['componenttype']),
794
-					'classification'=> (int)$row['classification']
794
+					'classification'=> (int) $row['classification']
795 795
 			];
796 796
 		}
797 797
 
@@ -824,18 +824,18 @@  discard block
 block discarded – undo
824 824
 		$stmt = $query->execute();
825 825
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
826 826
 
827
-		if(!$row) return null;
827
+		if (!$row) return null;
828 828
 
829 829
 		return [
830 830
 				'id'            => $row['id'],
831 831
 				'uri'           => $row['uri'],
832 832
 				'lastmodified'  => $row['lastmodified'],
833
-				'etag'          => '"' . $row['etag'] . '"',
833
+				'etag'          => '"'.$row['etag'].'"',
834 834
 				'calendarid'    => $row['calendarid'],
835
-				'size'          => (int)$row['size'],
835
+				'size'          => (int) $row['size'],
836 836
 				'calendardata'  => $this->readBlob($row['calendardata']),
837 837
 				'component'     => strtolower($row['componenttype']),
838
-				'classification'=> (int)$row['classification']
838
+				'classification'=> (int) $row['classification']
839 839
 		];
840 840
 	}
841 841
 
@@ -874,12 +874,12 @@  discard block
 block discarded – undo
874 874
 					'id'           => $row['id'],
875 875
 					'uri'          => $row['uri'],
876 876
 					'lastmodified' => $row['lastmodified'],
877
-					'etag'         => '"' . $row['etag'] . '"',
877
+					'etag'         => '"'.$row['etag'].'"',
878 878
 					'calendarid'   => $row['calendarid'],
879
-					'size'         => (int)$row['size'],
879
+					'size'         => (int) $row['size'],
880 880
 					'calendardata' => $this->readBlob($row['calendardata']),
881 881
 					'component'    => strtolower($row['componenttype']),
882
-					'classification' => (int)$row['classification']
882
+					'classification' => (int) $row['classification']
883 883
 				];
884 884
 			}
885 885
 			$result->closeCursor();
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
 		));
937 937
 		$this->addChange($calendarId, $objectUri, 1);
938 938
 
939
-		return '"' . $extraData['etag'] . '"';
939
+		return '"'.$extraData['etag'].'"';
940 940
 	}
941 941
 
942 942
 	/**
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
 		}
990 990
 		$this->addChange($calendarId, $objectUri, 2);
991 991
 
992
-		return '"' . $extraData['etag'] . '"';
992
+		return '"'.$extraData['etag'].'"';
993 993
 	}
994 994
 
995 995
 	/**
@@ -1140,7 +1140,7 @@  discard block
 block discarded – undo
1140 1140
 		$stmt = $query->execute();
1141 1141
 
1142 1142
 		$result = [];
1143
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1143
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1144 1144
 			if ($requirePostFilter) {
1145 1145
 				if (!$this->validateFilterForObject($row, $filters)) {
1146 1146
 					continue;
@@ -1183,7 +1183,7 @@  discard block
 block discarded – undo
1183 1183
 		$stmt = $query->execute();
1184 1184
 
1185 1185
 		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1186
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1186
+			return $row['calendaruri'].'/'.$row['objecturi'];
1187 1187
 		}
1188 1188
 
1189 1189
 		return null;
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
 	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) {
1249 1249
 		// Current synctoken
1250 1250
 		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1251
-		$stmt->execute([ $calendarId ]);
1251
+		$stmt->execute([$calendarId]);
1252 1252
 		$currentToken = $stmt->fetchColumn(0);
1253 1253
 
1254 1254
 		if (is_null($currentToken)) {
@@ -1265,8 +1265,8 @@  discard block
 block discarded – undo
1265 1265
 		if ($syncToken) {
1266 1266
 
1267 1267
 			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? ORDER BY `synctoken`";
1268
-			if ($limit>0) {
1269
-				$query.= " `LIMIT` " . (int)$limit;
1268
+			if ($limit > 0) {
1269
+				$query .= " `LIMIT` ".(int) $limit;
1270 1270
 			}
1271 1271
 
1272 1272
 			// Fetching all changes
@@ -1277,15 +1277,15 @@  discard block
 block discarded – undo
1277 1277
 
1278 1278
 			// This loop ensures that any duplicates are overwritten, only the
1279 1279
 			// last change on a node is relevant.
1280
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1280
+			while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1281 1281
 
1282 1282
 				$changes[$row['uri']] = $row['operation'];
1283 1283
 
1284 1284
 			}
1285 1285
 
1286
-			foreach($changes as $uri => $operation) {
1286
+			foreach ($changes as $uri => $operation) {
1287 1287
 
1288
-				switch($operation) {
1288
+				switch ($operation) {
1289 1289
 					case 1 :
1290 1290
 						$result['added'][] = $uri;
1291 1291
 						break;
@@ -1355,10 +1355,10 @@  discard block
 block discarded – undo
1355 1355
 			->from('calendarsubscriptions')
1356 1356
 			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1357 1357
 			->orderBy('calendarorder', 'asc');
1358
-		$stmt =$query->execute();
1358
+		$stmt = $query->execute();
1359 1359
 
1360 1360
 		$subscriptions = [];
1361
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1361
+		while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1362 1362
 
1363 1363
 			$subscription = [
1364 1364
 				'id'           => $row['id'],
@@ -1367,10 +1367,10 @@  discard block
 block discarded – undo
1367 1367
 				'source'       => $row['source'],
1368 1368
 				'lastmodified' => $row['lastmodified'],
1369 1369
 
1370
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1370
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1371 1371
 			];
1372 1372
 
1373
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1373
+			foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1374 1374
 				if (!is_null($row[$dbName])) {
1375 1375
 					$subscription[$xmlName] = $row[$dbName];
1376 1376
 				}
@@ -1409,7 +1409,7 @@  discard block
 block discarded – undo
1409 1409
 
1410 1410
 		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1411 1411
 
1412
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1412
+		foreach ($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1413 1413
 			if (array_key_exists($xmlName, $properties)) {
1414 1414
 					$values[$dbName] = $properties[$xmlName];
1415 1415
 					if (in_array($dbName, $propertiesBoolean)) {
@@ -1457,7 +1457,7 @@  discard block
 block discarded – undo
1457 1457
 
1458 1458
 			$newValues = [];
1459 1459
 
1460
-			foreach($mutations as $propertyName=>$propertyValue) {
1460
+			foreach ($mutations as $propertyName=>$propertyValue) {
1461 1461
 				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1462 1462
 					$newValues['source'] = $propertyValue->getHref();
1463 1463
 				} else {
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
 			$query = $this->db->getQueryBuilder();
1470 1470
 			$query->update('calendarsubscriptions')
1471 1471
 				->set('lastmodified', $query->createNamedParameter(time()));
1472
-			foreach($newValues as $fieldName=>$value) {
1472
+			foreach ($newValues as $fieldName=>$value) {
1473 1473
 				$query->set($fieldName, $query->createNamedParameter($value));
1474 1474
 			}
1475 1475
 			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
@@ -1519,7 +1519,7 @@  discard block
 block discarded – undo
1519 1519
 
1520 1520
 		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
1521 1521
 
1522
-		if(!$row) {
1522
+		if (!$row) {
1523 1523
 			return null;
1524 1524
 		}
1525 1525
 
@@ -1527,8 +1527,8 @@  discard block
 block discarded – undo
1527 1527
 				'uri'          => $row['uri'],
1528 1528
 				'calendardata' => $row['calendardata'],
1529 1529
 				'lastmodified' => $row['lastmodified'],
1530
-				'etag'         => '"' . $row['etag'] . '"',
1531
-				'size'         => (int)$row['size'],
1530
+				'etag'         => '"'.$row['etag'].'"',
1531
+				'size'         => (int) $row['size'],
1532 1532
 		];
1533 1533
 	}
1534 1534
 
@@ -1551,13 +1551,13 @@  discard block
 block discarded – undo
1551 1551
 				->execute();
1552 1552
 
1553 1553
 		$result = [];
1554
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1554
+		foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1555 1555
 			$result[] = [
1556 1556
 					'calendardata' => $row['calendardata'],
1557 1557
 					'uri'          => $row['uri'],
1558 1558
 					'lastmodified' => $row['lastmodified'],
1559
-					'etag'         => '"' . $row['etag'] . '"',
1560
-					'size'         => (int)$row['size'],
1559
+					'etag'         => '"'.$row['etag'].'"',
1560
+					'size'         => (int) $row['size'],
1561 1561
 			];
1562 1562
 		}
1563 1563
 
@@ -1649,10 +1649,10 @@  discard block
 block discarded – undo
1649 1649
 		$lastOccurrence = null;
1650 1650
 		$uid = null;
1651 1651
 		$classification = self::CLASSIFICATION_PUBLIC;
1652
-		foreach($vObject->getComponents() as $component) {
1653
-			if ($component->name!=='VTIMEZONE') {
1652
+		foreach ($vObject->getComponents() as $component) {
1653
+			if ($component->name !== 'VTIMEZONE') {
1654 1654
 				$componentType = $component->name;
1655
-				$uid = (string)$component->UID;
1655
+				$uid = (string) $component->UID;
1656 1656
 				break;
1657 1657
 			}
1658 1658
 		}
@@ -1677,13 +1677,13 @@  discard block
 block discarded – undo
1677 1677
 					$lastOccurrence = $firstOccurrence;
1678 1678
 				}
1679 1679
 			} else {
1680
-				$it = new EventIterator($vObject, (string)$component->UID);
1680
+				$it = new EventIterator($vObject, (string) $component->UID);
1681 1681
 				$maxDate = new \DateTime(self::MAX_DATE);
1682 1682
 				if ($it->isInfinite()) {
1683 1683
 					$lastOccurrence = $maxDate->getTimestamp();
1684 1684
 				} else {
1685 1685
 					$end = $it->getDtEnd();
1686
-					while($it->valid() && $end < $maxDate) {
1686
+					while ($it->valid() && $end < $maxDate) {
1687 1687
 						$end = $it->getDtEnd();
1688 1688
 						$it->next();
1689 1689
 
Please login to merge, or discard this patch.