Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
lib/private/Files/View.php 2 patches
Indentation   +2109 added lines, -2109 removed lines patch added patch discarded remove patch
@@ -83,2113 +83,2113 @@
 block discarded – undo
83 83
  * \OC\Files\Storage\Storage object
84 84
  */
85 85
 class View {
86
-	/** @var string */
87
-	private $fakeRoot = '';
88
-
89
-	/**
90
-	 * @var \OCP\Lock\ILockingProvider
91
-	 */
92
-	protected $lockingProvider;
93
-
94
-	private $lockingEnabled;
95
-
96
-	private $updaterEnabled = true;
97
-
98
-	/** @var \OC\User\Manager */
99
-	private $userManager;
100
-
101
-	/** @var \OCP\ILogger */
102
-	private $logger;
103
-
104
-	/**
105
-	 * @param string $root
106
-	 * @throws \Exception If $root contains an invalid path
107
-	 */
108
-	public function __construct($root = '') {
109
-		if (is_null($root)) {
110
-			throw new \InvalidArgumentException('Root can\'t be null');
111
-		}
112
-		if (!Filesystem::isValidPath($root)) {
113
-			throw new \Exception();
114
-		}
115
-
116
-		$this->fakeRoot = $root;
117
-		$this->lockingProvider = \OC::$server->getLockingProvider();
118
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
-		$this->userManager = \OC::$server->getUserManager();
120
-		$this->logger = \OC::$server->getLogger();
121
-	}
122
-
123
-	public function getAbsolutePath($path = '/') {
124
-		if ($path === null) {
125
-			return null;
126
-		}
127
-		$this->assertPathLength($path);
128
-		if ($path === '') {
129
-			$path = '/';
130
-		}
131
-		if ($path[0] !== '/') {
132
-			$path = '/' . $path;
133
-		}
134
-		return $this->fakeRoot . $path;
135
-	}
136
-
137
-	/**
138
-	 * change the root to a fake root
139
-	 *
140
-	 * @param string $fakeRoot
141
-	 * @return boolean|null
142
-	 */
143
-	public function chroot($fakeRoot) {
144
-		if (!$fakeRoot == '') {
145
-			if ($fakeRoot[0] !== '/') {
146
-				$fakeRoot = '/' . $fakeRoot;
147
-			}
148
-		}
149
-		$this->fakeRoot = $fakeRoot;
150
-	}
151
-
152
-	/**
153
-	 * get the fake root
154
-	 *
155
-	 * @return string
156
-	 */
157
-	public function getRoot() {
158
-		return $this->fakeRoot;
159
-	}
160
-
161
-	/**
162
-	 * get path relative to the root of the view
163
-	 *
164
-	 * @param string $path
165
-	 * @return string
166
-	 */
167
-	public function getRelativePath($path) {
168
-		$this->assertPathLength($path);
169
-		if ($this->fakeRoot == '') {
170
-			return $path;
171
-		}
172
-
173
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
-			return '/';
175
-		}
176
-
177
-		// missing slashes can cause wrong matches!
178
-		$root = rtrim($this->fakeRoot, '/') . '/';
179
-
180
-		if (strpos($path, $root) !== 0) {
181
-			return null;
182
-		} else {
183
-			$path = substr($path, strlen($this->fakeRoot));
184
-			if (strlen($path) === 0) {
185
-				return '/';
186
-			} else {
187
-				return $path;
188
-			}
189
-		}
190
-	}
191
-
192
-	/**
193
-	 * get the mountpoint of the storage object for a path
194
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
195
-	 * returned mountpoint is relative to the absolute root of the filesystem
196
-	 * and does not take the chroot into account )
197
-	 *
198
-	 * @param string $path
199
-	 * @return string
200
-	 */
201
-	public function getMountPoint($path) {
202
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
-	}
204
-
205
-	/**
206
-	 * get the mountpoint of the storage object for a path
207
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
208
-	 * returned mountpoint is relative to the absolute root of the filesystem
209
-	 * and does not take the chroot into account )
210
-	 *
211
-	 * @param string $path
212
-	 * @return \OCP\Files\Mount\IMountPoint
213
-	 */
214
-	public function getMount($path) {
215
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
-	}
217
-
218
-	/**
219
-	 * resolve a path to a storage and internal path
220
-	 *
221
-	 * @param string $path
222
-	 * @return array an array consisting of the storage and the internal path
223
-	 */
224
-	public function resolvePath($path) {
225
-		$a = $this->getAbsolutePath($path);
226
-		$p = Filesystem::normalizePath($a);
227
-		return Filesystem::resolvePath($p);
228
-	}
229
-
230
-	/**
231
-	 * return the path to a local version of the file
232
-	 * we need this because we can't know if a file is stored local or not from
233
-	 * outside the filestorage and for some purposes a local file is needed
234
-	 *
235
-	 * @param string $path
236
-	 * @return string
237
-	 */
238
-	public function getLocalFile($path) {
239
-		$parent = substr($path, 0, strrpos($path, '/'));
240
-		$path = $this->getAbsolutePath($path);
241
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
242
-		if (Filesystem::isValidPath($parent) and $storage) {
243
-			return $storage->getLocalFile($internalPath);
244
-		} else {
245
-			return null;
246
-		}
247
-	}
248
-
249
-	/**
250
-	 * @param string $path
251
-	 * @return string
252
-	 */
253
-	public function getLocalFolder($path) {
254
-		$parent = substr($path, 0, strrpos($path, '/'));
255
-		$path = $this->getAbsolutePath($path);
256
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
257
-		if (Filesystem::isValidPath($parent) and $storage) {
258
-			return $storage->getLocalFolder($internalPath);
259
-		} else {
260
-			return null;
261
-		}
262
-	}
263
-
264
-	/**
265
-	 * the following functions operate with arguments and return values identical
266
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
-	 * for \OC\Files\Storage\Storage via basicOperation().
268
-	 */
269
-	public function mkdir($path) {
270
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
271
-	}
272
-
273
-	/**
274
-	 * remove mount point
275
-	 *
276
-	 * @param \OC\Files\Mount\MoveableMount $mount
277
-	 * @param string $path relative to data/
278
-	 * @return boolean
279
-	 */
280
-	protected function removeMount($mount, $path) {
281
-		if ($mount instanceof MoveableMount) {
282
-			// cut of /user/files to get the relative path to data/user/files
283
-			$pathParts = explode('/', $path, 4);
284
-			$relPath = '/' . $pathParts[3];
285
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
-			\OC_Hook::emit(
287
-				Filesystem::CLASSNAME, "umount",
288
-				[Filesystem::signal_param_path => $relPath]
289
-			);
290
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
-			$result = $mount->removeMount();
292
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
-			if ($result) {
294
-				\OC_Hook::emit(
295
-					Filesystem::CLASSNAME, "post_umount",
296
-					[Filesystem::signal_param_path => $relPath]
297
-				);
298
-			}
299
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
-			return $result;
301
-		} else {
302
-			// do not allow deleting the storage's root / the mount point
303
-			// because for some storages it might delete the whole contents
304
-			// but isn't supposed to work that way
305
-			return false;
306
-		}
307
-	}
308
-
309
-	public function disableCacheUpdate() {
310
-		$this->updaterEnabled = false;
311
-	}
312
-
313
-	public function enableCacheUpdate() {
314
-		$this->updaterEnabled = true;
315
-	}
316
-
317
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
-		if ($this->updaterEnabled) {
319
-			if (is_null($time)) {
320
-				$time = time();
321
-			}
322
-			$storage->getUpdater()->update($internalPath, $time);
323
-		}
324
-	}
325
-
326
-	protected function removeUpdate(Storage $storage, $internalPath) {
327
-		if ($this->updaterEnabled) {
328
-			$storage->getUpdater()->remove($internalPath);
329
-		}
330
-	}
331
-
332
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
-		if ($this->updaterEnabled) {
334
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * @param string $path
340
-	 * @return bool|mixed
341
-	 */
342
-	public function rmdir($path) {
343
-		$absolutePath = $this->getAbsolutePath($path);
344
-		$mount = Filesystem::getMountManager()->find($absolutePath);
345
-		if ($mount->getInternalPath($absolutePath) === '') {
346
-			return $this->removeMount($mount, $absolutePath);
347
-		}
348
-		if ($this->is_dir($path)) {
349
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
350
-		} else {
351
-			$result = false;
352
-		}
353
-
354
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
-			$storage = $mount->getStorage();
356
-			$internalPath = $mount->getInternalPath($absolutePath);
357
-			$storage->getUpdater()->remove($internalPath);
358
-		}
359
-		return $result;
360
-	}
361
-
362
-	/**
363
-	 * @param string $path
364
-	 * @return resource
365
-	 */
366
-	public function opendir($path) {
367
-		return $this->basicOperation('opendir', $path, ['read']);
368
-	}
369
-
370
-	/**
371
-	 * @param string $path
372
-	 * @return bool|mixed
373
-	 */
374
-	public function is_dir($path) {
375
-		if ($path == '/') {
376
-			return true;
377
-		}
378
-		return $this->basicOperation('is_dir', $path);
379
-	}
380
-
381
-	/**
382
-	 * @param string $path
383
-	 * @return bool|mixed
384
-	 */
385
-	public function is_file($path) {
386
-		if ($path == '/') {
387
-			return false;
388
-		}
389
-		return $this->basicOperation('is_file', $path);
390
-	}
391
-
392
-	/**
393
-	 * @param string $path
394
-	 * @return mixed
395
-	 */
396
-	public function stat($path) {
397
-		return $this->basicOperation('stat', $path);
398
-	}
399
-
400
-	/**
401
-	 * @param string $path
402
-	 * @return mixed
403
-	 */
404
-	public function filetype($path) {
405
-		return $this->basicOperation('filetype', $path);
406
-	}
407
-
408
-	/**
409
-	 * @param string $path
410
-	 * @return mixed
411
-	 */
412
-	public function filesize($path) {
413
-		return $this->basicOperation('filesize', $path);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @return bool|mixed
419
-	 * @throws \OCP\Files\InvalidPathException
420
-	 */
421
-	public function readfile($path) {
422
-		$this->assertPathLength($path);
423
-		@ob_end_clean();
424
-		$handle = $this->fopen($path, 'rb');
425
-		if ($handle) {
426
-			$chunkSize = 8192; // 8 kB chunks
427
-			while (!feof($handle)) {
428
-				echo fread($handle, $chunkSize);
429
-				flush();
430
-			}
431
-			fclose($handle);
432
-			return $this->filesize($path);
433
-		}
434
-		return false;
435
-	}
436
-
437
-	/**
438
-	 * @param string $path
439
-	 * @param int $from
440
-	 * @param int $to
441
-	 * @return bool|mixed
442
-	 * @throws \OCP\Files\InvalidPathException
443
-	 * @throws \OCP\Files\UnseekableException
444
-	 */
445
-	public function readfilePart($path, $from, $to) {
446
-		$this->assertPathLength($path);
447
-		@ob_end_clean();
448
-		$handle = $this->fopen($path, 'rb');
449
-		if ($handle) {
450
-			$chunkSize = 8192; // 8 kB chunks
451
-			$startReading = true;
452
-
453
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
-				// forward file handle via chunked fread because fseek seem to have failed
455
-
456
-				$end = $from + 1;
457
-				while (!feof($handle) && ftell($handle) < $end) {
458
-					$len = $from - ftell($handle);
459
-					if ($len > $chunkSize) {
460
-						$len = $chunkSize;
461
-					}
462
-					$result = fread($handle, $len);
463
-
464
-					if ($result === false) {
465
-						$startReading = false;
466
-						break;
467
-					}
468
-				}
469
-			}
470
-
471
-			if ($startReading) {
472
-				$end = $to + 1;
473
-				while (!feof($handle) && ftell($handle) < $end) {
474
-					$len = $end - ftell($handle);
475
-					if ($len > $chunkSize) {
476
-						$len = $chunkSize;
477
-					}
478
-					echo fread($handle, $len);
479
-					flush();
480
-				}
481
-				return ftell($handle) - $from;
482
-			}
483
-
484
-			throw new \OCP\Files\UnseekableException('fseek error');
485
-		}
486
-		return false;
487
-	}
488
-
489
-	/**
490
-	 * @param string $path
491
-	 * @return mixed
492
-	 */
493
-	public function isCreatable($path) {
494
-		return $this->basicOperation('isCreatable', $path);
495
-	}
496
-
497
-	/**
498
-	 * @param string $path
499
-	 * @return mixed
500
-	 */
501
-	public function isReadable($path) {
502
-		return $this->basicOperation('isReadable', $path);
503
-	}
504
-
505
-	/**
506
-	 * @param string $path
507
-	 * @return mixed
508
-	 */
509
-	public function isUpdatable($path) {
510
-		return $this->basicOperation('isUpdatable', $path);
511
-	}
512
-
513
-	/**
514
-	 * @param string $path
515
-	 * @return bool|mixed
516
-	 */
517
-	public function isDeletable($path) {
518
-		$absolutePath = $this->getAbsolutePath($path);
519
-		$mount = Filesystem::getMountManager()->find($absolutePath);
520
-		if ($mount->getInternalPath($absolutePath) === '') {
521
-			return $mount instanceof MoveableMount;
522
-		}
523
-		return $this->basicOperation('isDeletable', $path);
524
-	}
525
-
526
-	/**
527
-	 * @param string $path
528
-	 * @return mixed
529
-	 */
530
-	public function isSharable($path) {
531
-		return $this->basicOperation('isSharable', $path);
532
-	}
533
-
534
-	/**
535
-	 * @param string $path
536
-	 * @return bool|mixed
537
-	 */
538
-	public function file_exists($path) {
539
-		if ($path == '/') {
540
-			return true;
541
-		}
542
-		return $this->basicOperation('file_exists', $path);
543
-	}
544
-
545
-	/**
546
-	 * @param string $path
547
-	 * @return mixed
548
-	 */
549
-	public function filemtime($path) {
550
-		return $this->basicOperation('filemtime', $path);
551
-	}
552
-
553
-	/**
554
-	 * @param string $path
555
-	 * @param int|string $mtime
556
-	 * @return bool
557
-	 */
558
-	public function touch($path, $mtime = null) {
559
-		if (!is_null($mtime) and !is_numeric($mtime)) {
560
-			$mtime = strtotime($mtime);
561
-		}
562
-
563
-		$hooks = ['touch'];
564
-
565
-		if (!$this->file_exists($path)) {
566
-			$hooks[] = 'create';
567
-			$hooks[] = 'write';
568
-		}
569
-		try {
570
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
-		} catch (\Exception $e) {
572
-			$this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
-			$result = false;
574
-		}
575
-		if (!$result) {
576
-			// If create file fails because of permissions on external storage like SMB folders,
577
-			// check file exists and return false if not.
578
-			if (!$this->file_exists($path)) {
579
-				return false;
580
-			}
581
-			if (is_null($mtime)) {
582
-				$mtime = time();
583
-			}
584
-			//if native touch fails, we emulate it by changing the mtime in the cache
585
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
586
-		}
587
-		return true;
588
-	}
589
-
590
-	/**
591
-	 * @param string $path
592
-	 * @return mixed
593
-	 * @throws LockedException
594
-	 */
595
-	public function file_get_contents($path) {
596
-		return $this->basicOperation('file_get_contents', $path, ['read']);
597
-	}
598
-
599
-	/**
600
-	 * @param bool $exists
601
-	 * @param string $path
602
-	 * @param bool $run
603
-	 */
604
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
605
-		if (!$exists) {
606
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
607
-				Filesystem::signal_param_path => $this->getHookPath($path),
608
-				Filesystem::signal_param_run => &$run,
609
-			]);
610
-		} else {
611
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
612
-				Filesystem::signal_param_path => $this->getHookPath($path),
613
-				Filesystem::signal_param_run => &$run,
614
-			]);
615
-		}
616
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
617
-			Filesystem::signal_param_path => $this->getHookPath($path),
618
-			Filesystem::signal_param_run => &$run,
619
-		]);
620
-	}
621
-
622
-	/**
623
-	 * @param bool $exists
624
-	 * @param string $path
625
-	 */
626
-	protected function emit_file_hooks_post($exists, $path) {
627
-		if (!$exists) {
628
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
629
-				Filesystem::signal_param_path => $this->getHookPath($path),
630
-			]);
631
-		} else {
632
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
633
-				Filesystem::signal_param_path => $this->getHookPath($path),
634
-			]);
635
-		}
636
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
637
-			Filesystem::signal_param_path => $this->getHookPath($path),
638
-		]);
639
-	}
640
-
641
-	/**
642
-	 * @param string $path
643
-	 * @param string|resource $data
644
-	 * @return bool|mixed
645
-	 * @throws LockedException
646
-	 */
647
-	public function file_put_contents($path, $data) {
648
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
649
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
650
-			if (Filesystem::isValidPath($path)
651
-				and !Filesystem::isFileBlacklisted($path)
652
-			) {
653
-				$path = $this->getRelativePath($absolutePath);
654
-
655
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
656
-
657
-				$exists = $this->file_exists($path);
658
-				$run = true;
659
-				if ($this->shouldEmitHooks($path)) {
660
-					$this->emit_file_hooks_pre($exists, $path, $run);
661
-				}
662
-				if (!$run) {
663
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
664
-					return false;
665
-				}
666
-
667
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
668
-
669
-				/** @var \OC\Files\Storage\Storage $storage */
670
-				list($storage, $internalPath) = $this->resolvePath($path);
671
-				$target = $storage->fopen($internalPath, 'w');
672
-				if ($target) {
673
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
674
-					fclose($target);
675
-					fclose($data);
676
-
677
-					$this->writeUpdate($storage, $internalPath);
678
-
679
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
680
-
681
-					if ($this->shouldEmitHooks($path) && $result !== false) {
682
-						$this->emit_file_hooks_post($exists, $path);
683
-					}
684
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
685
-					return $result;
686
-				} else {
687
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
688
-					return false;
689
-				}
690
-			} else {
691
-				return false;
692
-			}
693
-		} else {
694
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
695
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
696
-		}
697
-	}
698
-
699
-	/**
700
-	 * @param string $path
701
-	 * @return bool|mixed
702
-	 */
703
-	public function unlink($path) {
704
-		if ($path === '' || $path === '/') {
705
-			// do not allow deleting the root
706
-			return false;
707
-		}
708
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
709
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
710
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
711
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
712
-			return $this->removeMount($mount, $absolutePath);
713
-		}
714
-		if ($this->is_dir($path)) {
715
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
716
-		} else {
717
-			$result = $this->basicOperation('unlink', $path, ['delete']);
718
-		}
719
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
720
-			$storage = $mount->getStorage();
721
-			$internalPath = $mount->getInternalPath($absolutePath);
722
-			$storage->getUpdater()->remove($internalPath);
723
-			return true;
724
-		} else {
725
-			return $result;
726
-		}
727
-	}
728
-
729
-	/**
730
-	 * @param string $directory
731
-	 * @return bool|mixed
732
-	 */
733
-	public function deleteAll($directory) {
734
-		return $this->rmdir($directory);
735
-	}
736
-
737
-	/**
738
-	 * Rename/move a file or folder from the source path to target path.
739
-	 *
740
-	 * @param string $path1 source path
741
-	 * @param string $path2 target path
742
-	 *
743
-	 * @return bool|mixed
744
-	 * @throws LockedException
745
-	 */
746
-	public function rename($path1, $path2) {
747
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
748
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
749
-		$result = false;
750
-		if (
751
-			Filesystem::isValidPath($path2)
752
-			and Filesystem::isValidPath($path1)
753
-			and !Filesystem::isFileBlacklisted($path2)
754
-		) {
755
-			$path1 = $this->getRelativePath($absolutePath1);
756
-			$path2 = $this->getRelativePath($absolutePath2);
757
-			$exists = $this->file_exists($path2);
758
-
759
-			if ($path1 == null or $path2 == null) {
760
-				return false;
761
-			}
762
-
763
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
764
-			try {
765
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
766
-
767
-				$run = true;
768
-				if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
769
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
770
-					$this->emit_file_hooks_pre($exists, $path2, $run);
771
-				} elseif ($this->shouldEmitHooks($path1)) {
772
-					\OC_Hook::emit(
773
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
774
-						[
775
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
776
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
777
-							Filesystem::signal_param_run => &$run
778
-						]
779
-					);
780
-				}
781
-				if ($run) {
782
-					$this->verifyPath(dirname($path2), basename($path2));
783
-
784
-					$manager = Filesystem::getMountManager();
785
-					$mount1 = $this->getMount($path1);
786
-					$mount2 = $this->getMount($path2);
787
-					$storage1 = $mount1->getStorage();
788
-					$storage2 = $mount2->getStorage();
789
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
790
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
791
-
792
-					$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
793
-					try {
794
-						$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
795
-
796
-						if ($internalPath1 === '') {
797
-							if ($mount1 instanceof MoveableMount) {
798
-								$sourceParentMount = $this->getMount(dirname($path1));
799
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
800
-									/**
801
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
802
-									 */
803
-									$sourceMountPoint = $mount1->getMountPoint();
804
-									$result = $mount1->moveMount($absolutePath2);
805
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
806
-								} else {
807
-									$result = false;
808
-								}
809
-							} else {
810
-								$result = false;
811
-							}
812
-							// moving a file/folder within the same mount point
813
-						} elseif ($storage1 === $storage2) {
814
-							if ($storage1) {
815
-								$result = $storage1->rename($internalPath1, $internalPath2);
816
-							} else {
817
-								$result = false;
818
-							}
819
-							// moving a file/folder between storages (from $storage1 to $storage2)
820
-						} else {
821
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
822
-						}
823
-
824
-						if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
825
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
826
-							$this->writeUpdate($storage2, $internalPath2);
827
-						} else if ($result) {
828
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
829
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
830
-							}
831
-						}
832
-					} catch(\Exception $e) {
833
-						throw $e;
834
-					} finally {
835
-						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
836
-						$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
837
-					}
838
-
839
-					if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
840
-						if ($this->shouldEmitHooks()) {
841
-							$this->emit_file_hooks_post($exists, $path2);
842
-						}
843
-					} elseif ($result) {
844
-						if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
845
-							\OC_Hook::emit(
846
-								Filesystem::CLASSNAME,
847
-								Filesystem::signal_post_rename,
848
-								[
849
-									Filesystem::signal_param_oldpath => $this->getHookPath($path1),
850
-									Filesystem::signal_param_newpath => $this->getHookPath($path2)
851
-								]
852
-							);
853
-						}
854
-					}
855
-				}
856
-			} catch(\Exception $e) {
857
-				throw $e;
858
-			} finally {
859
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
860
-				$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
861
-			}
862
-		}
863
-		return $result;
864
-	}
865
-
866
-	/**
867
-	 * Copy a file/folder from the source path to target path
868
-	 *
869
-	 * @param string $path1 source path
870
-	 * @param string $path2 target path
871
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
872
-	 *
873
-	 * @return bool|mixed
874
-	 */
875
-	public function copy($path1, $path2, $preserveMtime = false) {
876
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
877
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
878
-		$result = false;
879
-		if (
880
-			Filesystem::isValidPath($path2)
881
-			and Filesystem::isValidPath($path1)
882
-			and !Filesystem::isFileBlacklisted($path2)
883
-		) {
884
-			$path1 = $this->getRelativePath($absolutePath1);
885
-			$path2 = $this->getRelativePath($absolutePath2);
886
-
887
-			if ($path1 == null or $path2 == null) {
888
-				return false;
889
-			}
890
-			$run = true;
891
-
892
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
893
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
894
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
895
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
896
-
897
-			try {
898
-
899
-				$exists = $this->file_exists($path2);
900
-				if ($this->shouldEmitHooks()) {
901
-					\OC_Hook::emit(
902
-						Filesystem::CLASSNAME,
903
-						Filesystem::signal_copy,
904
-						[
905
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
906
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
907
-							Filesystem::signal_param_run => &$run
908
-						]
909
-					);
910
-					$this->emit_file_hooks_pre($exists, $path2, $run);
911
-				}
912
-				if ($run) {
913
-					$mount1 = $this->getMount($path1);
914
-					$mount2 = $this->getMount($path2);
915
-					$storage1 = $mount1->getStorage();
916
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
917
-					$storage2 = $mount2->getStorage();
918
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
919
-
920
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
921
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
922
-
923
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
924
-						if ($storage1) {
925
-							$result = $storage1->copy($internalPath1, $internalPath2);
926
-						} else {
927
-							$result = false;
928
-						}
929
-					} else {
930
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
931
-					}
932
-
933
-					$this->writeUpdate($storage2, $internalPath2);
934
-
935
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
936
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
-
938
-					if ($this->shouldEmitHooks() && $result !== false) {
939
-						\OC_Hook::emit(
940
-							Filesystem::CLASSNAME,
941
-							Filesystem::signal_post_copy,
942
-							[
943
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
944
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
945
-							]
946
-						);
947
-						$this->emit_file_hooks_post($exists, $path2);
948
-					}
949
-
950
-				}
951
-			} catch (\Exception $e) {
952
-				$this->unlockFile($path2, $lockTypePath2);
953
-				$this->unlockFile($path1, $lockTypePath1);
954
-				throw $e;
955
-			}
956
-
957
-			$this->unlockFile($path2, $lockTypePath2);
958
-			$this->unlockFile($path1, $lockTypePath1);
959
-
960
-		}
961
-		return $result;
962
-	}
963
-
964
-	/**
965
-	 * @param string $path
966
-	 * @param string $mode 'r' or 'w'
967
-	 * @return resource
968
-	 * @throws LockedException
969
-	 */
970
-	public function fopen($path, $mode) {
971
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
972
-		$hooks = [];
973
-		switch ($mode) {
974
-			case 'r':
975
-				$hooks[] = 'read';
976
-				break;
977
-			case 'r+':
978
-			case 'w+':
979
-			case 'x+':
980
-			case 'a+':
981
-				$hooks[] = 'read';
982
-				$hooks[] = 'write';
983
-				break;
984
-			case 'w':
985
-			case 'x':
986
-			case 'a':
987
-				$hooks[] = 'write';
988
-				break;
989
-			default:
990
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
991
-		}
992
-
993
-		if ($mode !== 'r' && $mode !== 'w') {
994
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
995
-		}
996
-
997
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
998
-	}
999
-
1000
-	/**
1001
-	 * @param string $path
1002
-	 * @return bool|string
1003
-	 * @throws \OCP\Files\InvalidPathException
1004
-	 */
1005
-	public function toTmpFile($path) {
1006
-		$this->assertPathLength($path);
1007
-		if (Filesystem::isValidPath($path)) {
1008
-			$source = $this->fopen($path, 'r');
1009
-			if ($source) {
1010
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1011
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1012
-				file_put_contents($tmpFile, $source);
1013
-				return $tmpFile;
1014
-			} else {
1015
-				return false;
1016
-			}
1017
-		} else {
1018
-			return false;
1019
-		}
1020
-	}
1021
-
1022
-	/**
1023
-	 * @param string $tmpFile
1024
-	 * @param string $path
1025
-	 * @return bool|mixed
1026
-	 * @throws \OCP\Files\InvalidPathException
1027
-	 */
1028
-	public function fromTmpFile($tmpFile, $path) {
1029
-		$this->assertPathLength($path);
1030
-		if (Filesystem::isValidPath($path)) {
1031
-
1032
-			// Get directory that the file is going into
1033
-			$filePath = dirname($path);
1034
-
1035
-			// Create the directories if any
1036
-			if (!$this->file_exists($filePath)) {
1037
-				$result = $this->createParentDirectories($filePath);
1038
-				if ($result === false) {
1039
-					return false;
1040
-				}
1041
-			}
1042
-
1043
-			$source = fopen($tmpFile, 'r');
1044
-			if ($source) {
1045
-				$result = $this->file_put_contents($path, $source);
1046
-				// $this->file_put_contents() might have already closed
1047
-				// the resource, so we check it, before trying to close it
1048
-				// to avoid messages in the error log.
1049
-				if (is_resource($source)) {
1050
-					fclose($source);
1051
-				}
1052
-				unlink($tmpFile);
1053
-				return $result;
1054
-			} else {
1055
-				return false;
1056
-			}
1057
-		} else {
1058
-			return false;
1059
-		}
1060
-	}
1061
-
1062
-
1063
-	/**
1064
-	 * @param string $path
1065
-	 * @return mixed
1066
-	 * @throws \OCP\Files\InvalidPathException
1067
-	 */
1068
-	public function getMimeType($path) {
1069
-		$this->assertPathLength($path);
1070
-		return $this->basicOperation('getMimeType', $path);
1071
-	}
1072
-
1073
-	/**
1074
-	 * @param string $type
1075
-	 * @param string $path
1076
-	 * @param bool $raw
1077
-	 * @return bool|null|string
1078
-	 */
1079
-	public function hash($type, $path, $raw = false) {
1080
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1081
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1082
-		if (Filesystem::isValidPath($path)) {
1083
-			$path = $this->getRelativePath($absolutePath);
1084
-			if ($path == null) {
1085
-				return false;
1086
-			}
1087
-			if ($this->shouldEmitHooks($path)) {
1088
-				\OC_Hook::emit(
1089
-					Filesystem::CLASSNAME,
1090
-					Filesystem::signal_read,
1091
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1092
-				);
1093
-			}
1094
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1095
-			if ($storage) {
1096
-				return $storage->hash($type, $internalPath, $raw);
1097
-			}
1098
-		}
1099
-		return null;
1100
-	}
1101
-
1102
-	/**
1103
-	 * @param string $path
1104
-	 * @return mixed
1105
-	 * @throws \OCP\Files\InvalidPathException
1106
-	 */
1107
-	public function free_space($path = '/') {
1108
-		$this->assertPathLength($path);
1109
-		$result = $this->basicOperation('free_space', $path);
1110
-		if ($result === null) {
1111
-			throw new InvalidPathException();
1112
-		}
1113
-		return $result;
1114
-	}
1115
-
1116
-	/**
1117
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1118
-	 *
1119
-	 * @param string $operation
1120
-	 * @param string $path
1121
-	 * @param array $hooks (optional)
1122
-	 * @param mixed $extraParam (optional)
1123
-	 * @return mixed
1124
-	 * @throws LockedException
1125
-	 *
1126
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1127
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1128
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1129
-	 */
1130
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1131
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1132
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
-		if (Filesystem::isValidPath($path)
1134
-			and !Filesystem::isFileBlacklisted($path)
1135
-		) {
1136
-			$path = $this->getRelativePath($absolutePath);
1137
-			if ($path == null) {
1138
-				return false;
1139
-			}
1140
-
1141
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1142
-				// always a shared lock during pre-hooks so the hook can read the file
1143
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1144
-			}
1145
-
1146
-			$run = $this->runHooks($hooks, $path);
1147
-			/** @var \OC\Files\Storage\Storage $storage */
1148
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1149
-			if ($run and $storage) {
1150
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1151
-					try {
1152
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
-					} catch (LockedException $e) {
1154
-						// release the shared lock we acquired before quiting
1155
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
-						throw $e;
1157
-					}
1158
-				}
1159
-				try {
1160
-					if (!is_null($extraParam)) {
1161
-						$result = $storage->$operation($internalPath, $extraParam);
1162
-					} else {
1163
-						$result = $storage->$operation($internalPath);
1164
-					}
1165
-				} catch (\Exception $e) {
1166
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1167
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1168
-					} else if (in_array('read', $hooks)) {
1169
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
-					}
1171
-					throw $e;
1172
-				}
1173
-
1174
-				if ($result && in_array('delete', $hooks) and $result) {
1175
-					$this->removeUpdate($storage, $internalPath);
1176
-				}
1177
-				if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1178
-					$this->writeUpdate($storage, $internalPath);
1179
-				}
1180
-				if ($result && in_array('touch', $hooks)) {
1181
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1182
-				}
1183
-
1184
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1185
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1186
-				}
1187
-
1188
-				$unlockLater = false;
1189
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1190
-					$unlockLater = true;
1191
-					// make sure our unlocking callback will still be called if connection is aborted
1192
-					ignore_user_abort(true);
1193
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1194
-						if (in_array('write', $hooks)) {
1195
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1196
-						} else if (in_array('read', $hooks)) {
1197
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1198
-						}
1199
-					});
1200
-				}
1201
-
1202
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1203
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1204
-						$this->runHooks($hooks, $path, true);
1205
-					}
1206
-				}
1207
-
1208
-				if (!$unlockLater
1209
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1210
-				) {
1211
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1212
-				}
1213
-				return $result;
1214
-			} else {
1215
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1216
-			}
1217
-		}
1218
-		return null;
1219
-	}
1220
-
1221
-	/**
1222
-	 * get the path relative to the default root for hook usage
1223
-	 *
1224
-	 * @param string $path
1225
-	 * @return string
1226
-	 */
1227
-	private function getHookPath($path) {
1228
-		if (!Filesystem::getView()) {
1229
-			return $path;
1230
-		}
1231
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1232
-	}
1233
-
1234
-	private function shouldEmitHooks($path = '') {
1235
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1236
-			return false;
1237
-		}
1238
-		if (!Filesystem::$loaded) {
1239
-			return false;
1240
-		}
1241
-		$defaultRoot = Filesystem::getRoot();
1242
-		if ($defaultRoot === null) {
1243
-			return false;
1244
-		}
1245
-		if ($this->fakeRoot === $defaultRoot) {
1246
-			return true;
1247
-		}
1248
-		$fullPath = $this->getAbsolutePath($path);
1249
-
1250
-		if ($fullPath === $defaultRoot) {
1251
-			return true;
1252
-		}
1253
-
1254
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1255
-	}
1256
-
1257
-	/**
1258
-	 * @param string[] $hooks
1259
-	 * @param string $path
1260
-	 * @param bool $post
1261
-	 * @return bool
1262
-	 */
1263
-	private function runHooks($hooks, $path, $post = false) {
1264
-		$relativePath = $path;
1265
-		$path = $this->getHookPath($path);
1266
-		$prefix = $post ? 'post_' : '';
1267
-		$run = true;
1268
-		if ($this->shouldEmitHooks($relativePath)) {
1269
-			foreach ($hooks as $hook) {
1270
-				if ($hook != 'read') {
1271
-					\OC_Hook::emit(
1272
-						Filesystem::CLASSNAME,
1273
-						$prefix . $hook,
1274
-						[
1275
-							Filesystem::signal_param_run => &$run,
1276
-							Filesystem::signal_param_path => $path
1277
-						]
1278
-					);
1279
-				} elseif (!$post) {
1280
-					\OC_Hook::emit(
1281
-						Filesystem::CLASSNAME,
1282
-						$prefix . $hook,
1283
-						[
1284
-							Filesystem::signal_param_path => $path
1285
-						]
1286
-					);
1287
-				}
1288
-			}
1289
-		}
1290
-		return $run;
1291
-	}
1292
-
1293
-	/**
1294
-	 * check if a file or folder has been updated since $time
1295
-	 *
1296
-	 * @param string $path
1297
-	 * @param int $time
1298
-	 * @return bool
1299
-	 */
1300
-	public function hasUpdated($path, $time) {
1301
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1302
-	}
1303
-
1304
-	/**
1305
-	 * @param string $ownerId
1306
-	 * @return \OC\User\User
1307
-	 */
1308
-	private function getUserObjectForOwner($ownerId) {
1309
-		$owner = $this->userManager->get($ownerId);
1310
-		if ($owner instanceof IUser) {
1311
-			return $owner;
1312
-		} else {
1313
-			return new User($ownerId, null, \OC::$server->getEventDispatcher());
1314
-		}
1315
-	}
1316
-
1317
-	/**
1318
-	 * Get file info from cache
1319
-	 *
1320
-	 * If the file is not in cached it will be scanned
1321
-	 * If the file has changed on storage the cache will be updated
1322
-	 *
1323
-	 * @param \OC\Files\Storage\Storage $storage
1324
-	 * @param string $internalPath
1325
-	 * @param string $relativePath
1326
-	 * @return ICacheEntry|bool
1327
-	 */
1328
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1329
-		$cache = $storage->getCache($internalPath);
1330
-		$data = $cache->get($internalPath);
1331
-		$watcher = $storage->getWatcher($internalPath);
1332
-
1333
-		try {
1334
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1335
-			if (!$data || $data['size'] === -1) {
1336
-				if (!$storage->file_exists($internalPath)) {
1337
-					return false;
1338
-				}
1339
-				// don't need to get a lock here since the scanner does it's own locking
1340
-				$scanner = $storage->getScanner($internalPath);
1341
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1342
-				$data = $cache->get($internalPath);
1343
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1344
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1345
-				$watcher->update($internalPath, $data);
1346
-				$storage->getPropagator()->propagateChange($internalPath, time());
1347
-				$data = $cache->get($internalPath);
1348
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1349
-			}
1350
-		} catch (LockedException $e) {
1351
-			// if the file is locked we just use the old cache info
1352
-		}
1353
-
1354
-		return $data;
1355
-	}
1356
-
1357
-	/**
1358
-	 * get the filesystem info
1359
-	 *
1360
-	 * @param string $path
1361
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1362
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1363
-	 * defaults to true
1364
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1365
-	 */
1366
-	public function getFileInfo($path, $includeMountPoints = true) {
1367
-		$this->assertPathLength($path);
1368
-		if (!Filesystem::isValidPath($path)) {
1369
-			return false;
1370
-		}
1371
-		if (Cache\Scanner::isPartialFile($path)) {
1372
-			return $this->getPartFileInfo($path);
1373
-		}
1374
-		$relativePath = $path;
1375
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1376
-
1377
-		$mount = Filesystem::getMountManager()->find($path);
1378
-		if (!$mount) {
1379
-			\OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1380
-			return false;
1381
-		}
1382
-		$storage = $mount->getStorage();
1383
-		$internalPath = $mount->getInternalPath($path);
1384
-		if ($storage) {
1385
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1386
-
1387
-			if (!$data instanceof ICacheEntry) {
1388
-				return false;
1389
-			}
1390
-
1391
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1392
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1393
-			}
1394
-			$ownerId = $storage->getOwner($internalPath);
1395
-			$owner = null;
1396
-			if ($ownerId !== null && $ownerId !== false) {
1397
-				// ownerId might be null if files are accessed with an access token without file system access
1398
-				$owner = $this->getUserObjectForOwner($ownerId);
1399
-			}
1400
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1401
-
1402
-			if ($data and isset($data['fileid'])) {
1403
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1404
-					//add the sizes of other mount points to the folder
1405
-					$extOnly = ($includeMountPoints === 'ext');
1406
-					$mounts = Filesystem::getMountManager()->findIn($path);
1407
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1408
-						$subStorage = $mount->getStorage();
1409
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1410
-					}));
1411
-				}
1412
-			}
1413
-
1414
-			return $info;
1415
-		} else {
1416
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1417
-		}
1418
-
1419
-		return false;
1420
-	}
1421
-
1422
-	/**
1423
-	 * get the content of a directory
1424
-	 *
1425
-	 * @param string $directory path under datadirectory
1426
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1427
-	 * @return FileInfo[]
1428
-	 */
1429
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1430
-		$this->assertPathLength($directory);
1431
-		if (!Filesystem::isValidPath($directory)) {
1432
-			return [];
1433
-		}
1434
-		$path = $this->getAbsolutePath($directory);
1435
-		$path = Filesystem::normalizePath($path);
1436
-		$mount = $this->getMount($directory);
1437
-		if (!$mount) {
1438
-			return [];
1439
-		}
1440
-		$storage = $mount->getStorage();
1441
-		$internalPath = $mount->getInternalPath($path);
1442
-		if ($storage) {
1443
-			$cache = $storage->getCache($internalPath);
1444
-			$user = \OC_User::getUser();
1445
-
1446
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1447
-
1448
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1449
-				return [];
1450
-			}
1451
-
1452
-			$folderId = $data['fileid'];
1453
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1454
-
1455
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1456
-
1457
-			$fileNames = array_map(function (ICacheEntry $content) {
1458
-				return $content->getName();
1459
-			}, $contents);
1460
-			/**
1461
-			 * @var \OC\Files\FileInfo[] $fileInfos
1462
-			 */
1463
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1464
-				if ($sharingDisabled) {
1465
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1466
-				}
1467
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1468
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1469
-			}, $contents);
1470
-			$files = array_combine($fileNames, $fileInfos);
1471
-
1472
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1473
-			$mounts = Filesystem::getMountManager()->findIn($path);
1474
-			$dirLength = strlen($path);
1475
-			foreach ($mounts as $mount) {
1476
-				$mountPoint = $mount->getMountPoint();
1477
-				$subStorage = $mount->getStorage();
1478
-				if ($subStorage) {
1479
-					$subCache = $subStorage->getCache('');
1480
-
1481
-					$rootEntry = $subCache->get('');
1482
-					if (!$rootEntry) {
1483
-						$subScanner = $subStorage->getScanner('');
1484
-						try {
1485
-							$subScanner->scanFile('');
1486
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1487
-							continue;
1488
-						} catch (\OCP\Files\StorageInvalidException $e) {
1489
-							continue;
1490
-						} catch (\Exception $e) {
1491
-							// sometimes when the storage is not available it can be any exception
1492
-							\OC::$server->getLogger()->logException($e, [
1493
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1494
-								'level' => ILogger::ERROR,
1495
-								'app' => 'lib',
1496
-							]);
1497
-							continue;
1498
-						}
1499
-						$rootEntry = $subCache->get('');
1500
-					}
1501
-
1502
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1503
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1504
-						if ($pos = strpos($relativePath, '/')) {
1505
-							//mountpoint inside subfolder add size to the correct folder
1506
-							$entryName = substr($relativePath, 0, $pos);
1507
-							foreach ($files as &$entry) {
1508
-								if ($entry->getName() === $entryName) {
1509
-									$entry->addSubEntry($rootEntry, $mountPoint);
1510
-								}
1511
-							}
1512
-						} else { //mountpoint in this folder, add an entry for it
1513
-							$rootEntry['name'] = $relativePath;
1514
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1515
-							$permissions = $rootEntry['permissions'];
1516
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1517
-							// for shared files/folders we use the permissions given by the owner
1518
-							if ($mount instanceof MoveableMount) {
1519
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1520
-							} else {
1521
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1522
-							}
1523
-
1524
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1525
-
1526
-							// if sharing was disabled for the user we remove the share permissions
1527
-							if (\OCP\Util::isSharingDisabledForUser()) {
1528
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1529
-							}
1530
-
1531
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1532
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1533
-						}
1534
-					}
1535
-				}
1536
-			}
1537
-
1538
-			if ($mimetype_filter) {
1539
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1540
-					if (strpos($mimetype_filter, '/')) {
1541
-						return $file->getMimetype() === $mimetype_filter;
1542
-					} else {
1543
-						return $file->getMimePart() === $mimetype_filter;
1544
-					}
1545
-				});
1546
-			}
1547
-
1548
-			return array_values($files);
1549
-		} else {
1550
-			return [];
1551
-		}
1552
-	}
1553
-
1554
-	/**
1555
-	 * change file metadata
1556
-	 *
1557
-	 * @param string $path
1558
-	 * @param array|\OCP\Files\FileInfo $data
1559
-	 * @return int
1560
-	 *
1561
-	 * returns the fileid of the updated file
1562
-	 */
1563
-	public function putFileInfo($path, $data) {
1564
-		$this->assertPathLength($path);
1565
-		if ($data instanceof FileInfo) {
1566
-			$data = $data->getData();
1567
-		}
1568
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1569
-		/**
1570
-		 * @var \OC\Files\Storage\Storage $storage
1571
-		 * @var string $internalPath
1572
-		 */
1573
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1574
-		if ($storage) {
1575
-			$cache = $storage->getCache($path);
1576
-
1577
-			if (!$cache->inCache($internalPath)) {
1578
-				$scanner = $storage->getScanner($internalPath);
1579
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1580
-			}
1581
-
1582
-			return $cache->put($internalPath, $data);
1583
-		} else {
1584
-			return -1;
1585
-		}
1586
-	}
1587
-
1588
-	/**
1589
-	 * search for files with the name matching $query
1590
-	 *
1591
-	 * @param string $query
1592
-	 * @return FileInfo[]
1593
-	 */
1594
-	public function search($query) {
1595
-		return $this->searchCommon('search', ['%' . $query . '%']);
1596
-	}
1597
-
1598
-	/**
1599
-	 * search for files with the name matching $query
1600
-	 *
1601
-	 * @param string $query
1602
-	 * @return FileInfo[]
1603
-	 */
1604
-	public function searchRaw($query) {
1605
-		return $this->searchCommon('search', [$query]);
1606
-	}
1607
-
1608
-	/**
1609
-	 * search for files by mimetype
1610
-	 *
1611
-	 * @param string $mimetype
1612
-	 * @return FileInfo[]
1613
-	 */
1614
-	public function searchByMime($mimetype) {
1615
-		return $this->searchCommon('searchByMime', [$mimetype]);
1616
-	}
1617
-
1618
-	/**
1619
-	 * search for files by tag
1620
-	 *
1621
-	 * @param string|int $tag name or tag id
1622
-	 * @param string $userId owner of the tags
1623
-	 * @return FileInfo[]
1624
-	 */
1625
-	public function searchByTag($tag, $userId) {
1626
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1627
-	}
1628
-
1629
-	/**
1630
-	 * @param string $method cache method
1631
-	 * @param array $args
1632
-	 * @return FileInfo[]
1633
-	 */
1634
-	private function searchCommon($method, $args) {
1635
-		$files = [];
1636
-		$rootLength = strlen($this->fakeRoot);
1637
-
1638
-		$mount = $this->getMount('');
1639
-		$mountPoint = $mount->getMountPoint();
1640
-		$storage = $mount->getStorage();
1641
-		if ($storage) {
1642
-			$cache = $storage->getCache('');
1643
-
1644
-			$results = call_user_func_array([$cache, $method], $args);
1645
-			foreach ($results as $result) {
1646
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1647
-					$internalPath = $result['path'];
1648
-					$path = $mountPoint . $result['path'];
1649
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1650
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1651
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
-				}
1653
-			}
1654
-
1655
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1656
-			foreach ($mounts as $mount) {
1657
-				$mountPoint = $mount->getMountPoint();
1658
-				$storage = $mount->getStorage();
1659
-				if ($storage) {
1660
-					$cache = $storage->getCache('');
1661
-
1662
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1663
-					$results = call_user_func_array([$cache, $method], $args);
1664
-					if ($results) {
1665
-						foreach ($results as $result) {
1666
-							$internalPath = $result['path'];
1667
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1668
-							$path = rtrim($mountPoint . $internalPath, '/');
1669
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1670
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
-						}
1672
-					}
1673
-				}
1674
-			}
1675
-		}
1676
-		return $files;
1677
-	}
1678
-
1679
-	/**
1680
-	 * Get the owner for a file or folder
1681
-	 *
1682
-	 * @param string $path
1683
-	 * @return string the user id of the owner
1684
-	 * @throws NotFoundException
1685
-	 */
1686
-	public function getOwner($path) {
1687
-		$info = $this->getFileInfo($path);
1688
-		if (!$info) {
1689
-			throw new NotFoundException($path . ' not found while trying to get owner');
1690
-		}
1691
-
1692
-		if ($info->getOwner() === null) {
1693
-			throw new NotFoundException($path . ' has no owner');
1694
-		}
1695
-
1696
-		return $info->getOwner()->getUID();
1697
-	}
1698
-
1699
-	/**
1700
-	 * get the ETag for a file or folder
1701
-	 *
1702
-	 * @param string $path
1703
-	 * @return string
1704
-	 */
1705
-	public function getETag($path) {
1706
-		/**
1707
-		 * @var Storage\Storage $storage
1708
-		 * @var string $internalPath
1709
-		 */
1710
-		list($storage, $internalPath) = $this->resolvePath($path);
1711
-		if ($storage) {
1712
-			return $storage->getETag($internalPath);
1713
-		} else {
1714
-			return null;
1715
-		}
1716
-	}
1717
-
1718
-	/**
1719
-	 * Get the path of a file by id, relative to the view
1720
-	 *
1721
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1722
-	 *
1723
-	 * @param int $id
1724
-	 * @throws NotFoundException
1725
-	 * @return string
1726
-	 */
1727
-	public function getPath($id) {
1728
-		$id = (int)$id;
1729
-		$manager = Filesystem::getMountManager();
1730
-		$mounts = $manager->findIn($this->fakeRoot);
1731
-		$mounts[] = $manager->find($this->fakeRoot);
1732
-		// reverse the array so we start with the storage this view is in
1733
-		// which is the most likely to contain the file we're looking for
1734
-		$mounts = array_reverse($mounts);
1735
-
1736
-		// put non shared mounts in front of the shared mount
1737
-		// this prevent unneeded recursion into shares
1738
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1739
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1740
-		});
1741
-
1742
-		foreach ($mounts as $mount) {
1743
-			/**
1744
-			 * @var \OC\Files\Mount\MountPoint $mount
1745
-			 */
1746
-			if ($mount->getStorage()) {
1747
-				$cache = $mount->getStorage()->getCache();
1748
-				$internalPath = $cache->getPathById($id);
1749
-				if (is_string($internalPath)) {
1750
-					$fullPath = $mount->getMountPoint() . $internalPath;
1751
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1752
-						return $path;
1753
-					}
1754
-				}
1755
-			}
1756
-		}
1757
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1758
-	}
1759
-
1760
-	/**
1761
-	 * @param string $path
1762
-	 * @throws InvalidPathException
1763
-	 */
1764
-	private function assertPathLength($path) {
1765
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1766
-		// Check for the string length - performed using isset() instead of strlen()
1767
-		// because isset() is about 5x-40x faster.
1768
-		if (isset($path[$maxLen])) {
1769
-			$pathLen = strlen($path);
1770
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1771
-		}
1772
-	}
1773
-
1774
-	/**
1775
-	 * check if it is allowed to move a mount point to a given target.
1776
-	 * It is not allowed to move a mount point into a different mount point or
1777
-	 * into an already shared folder
1778
-	 *
1779
-	 * @param IStorage $targetStorage
1780
-	 * @param string $targetInternalPath
1781
-	 * @return boolean
1782
-	 */
1783
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1784
-
1785
-		// note: cannot use the view because the target is already locked
1786
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1787
-		if ($fileId === -1) {
1788
-			// target might not exist, need to check parent instead
1789
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1790
-		}
1791
-
1792
-		// check if any of the parents were shared by the current owner (include collections)
1793
-		$shares = \OCP\Share::getItemShared(
1794
-			'folder',
1795
-			$fileId,
1796
-			\OCP\Share::FORMAT_NONE,
1797
-			null,
1798
-			true
1799
-		);
1800
-
1801
-		if (count($shares) > 0) {
1802
-			\OCP\Util::writeLog('files',
1803
-				'It is not allowed to move one mount point into a shared folder',
1804
-				ILogger::DEBUG);
1805
-			return false;
1806
-		}
1807
-
1808
-		return true;
1809
-	}
1810
-
1811
-	/**
1812
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1813
-	 *
1814
-	 * @param string $path
1815
-	 * @return \OCP\Files\FileInfo
1816
-	 */
1817
-	private function getPartFileInfo($path) {
1818
-		$mount = $this->getMount($path);
1819
-		$storage = $mount->getStorage();
1820
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1821
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1822
-		return new FileInfo(
1823
-			$this->getAbsolutePath($path),
1824
-			$storage,
1825
-			$internalPath,
1826
-			[
1827
-				'fileid' => null,
1828
-				'mimetype' => $storage->getMimeType($internalPath),
1829
-				'name' => basename($path),
1830
-				'etag' => null,
1831
-				'size' => $storage->filesize($internalPath),
1832
-				'mtime' => $storage->filemtime($internalPath),
1833
-				'encrypted' => false,
1834
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1835
-			],
1836
-			$mount,
1837
-			$owner
1838
-		);
1839
-	}
1840
-
1841
-	/**
1842
-	 * @param string $path
1843
-	 * @param string $fileName
1844
-	 * @throws InvalidPathException
1845
-	 */
1846
-	public function verifyPath($path, $fileName) {
1847
-		try {
1848
-			/** @type \OCP\Files\Storage $storage */
1849
-			list($storage, $internalPath) = $this->resolvePath($path);
1850
-			$storage->verifyPath($internalPath, $fileName);
1851
-		} catch (ReservedWordException $ex) {
1852
-			$l = \OC::$server->getL10N('lib');
1853
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1854
-		} catch (InvalidCharacterInPathException $ex) {
1855
-			$l = \OC::$server->getL10N('lib');
1856
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1857
-		} catch (FileNameTooLongException $ex) {
1858
-			$l = \OC::$server->getL10N('lib');
1859
-			throw new InvalidPathException($l->t('File name is too long'));
1860
-		} catch (InvalidDirectoryException $ex) {
1861
-			$l = \OC::$server->getL10N('lib');
1862
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1863
-		} catch (EmptyFileNameException $ex) {
1864
-			$l = \OC::$server->getL10N('lib');
1865
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1866
-		}
1867
-	}
1868
-
1869
-	/**
1870
-	 * get all parent folders of $path
1871
-	 *
1872
-	 * @param string $path
1873
-	 * @return string[]
1874
-	 */
1875
-	private function getParents($path) {
1876
-		$path = trim($path, '/');
1877
-		if (!$path) {
1878
-			return [];
1879
-		}
1880
-
1881
-		$parts = explode('/', $path);
1882
-
1883
-		// remove the single file
1884
-		array_pop($parts);
1885
-		$result = ['/'];
1886
-		$resultPath = '';
1887
-		foreach ($parts as $part) {
1888
-			if ($part) {
1889
-				$resultPath .= '/' . $part;
1890
-				$result[] = $resultPath;
1891
-			}
1892
-		}
1893
-		return $result;
1894
-	}
1895
-
1896
-	/**
1897
-	 * Returns the mount point for which to lock
1898
-	 *
1899
-	 * @param string $absolutePath absolute path
1900
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1901
-	 * is mounted directly on the given path, false otherwise
1902
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1903
-	 */
1904
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1905
-		$results = [];
1906
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1907
-		if (!$mount) {
1908
-			return $results;
1909
-		}
1910
-
1911
-		if ($useParentMount) {
1912
-			// find out if something is mounted directly on the path
1913
-			$internalPath = $mount->getInternalPath($absolutePath);
1914
-			if ($internalPath === '') {
1915
-				// resolve the parent mount instead
1916
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1917
-			}
1918
-		}
1919
-
1920
-		return $mount;
1921
-	}
1922
-
1923
-	/**
1924
-	 * Lock the given path
1925
-	 *
1926
-	 * @param string $path the path of the file to lock, relative to the view
1927
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1928
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1929
-	 *
1930
-	 * @return bool False if the path is excluded from locking, true otherwise
1931
-	 * @throws LockedException if the path is already locked
1932
-	 */
1933
-	private function lockPath($path, $type, $lockMountPoint = false) {
1934
-		$absolutePath = $this->getAbsolutePath($path);
1935
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1936
-		if (!$this->shouldLockFile($absolutePath)) {
1937
-			return false;
1938
-		}
1939
-
1940
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1941
-		if ($mount) {
1942
-			try {
1943
-				$storage = $mount->getStorage();
1944
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1945
-					$storage->acquireLock(
1946
-						$mount->getInternalPath($absolutePath),
1947
-						$type,
1948
-						$this->lockingProvider
1949
-					);
1950
-				}
1951
-			} catch (LockedException $e) {
1952
-				// rethrow with the a human-readable path
1953
-				throw new LockedException(
1954
-					$this->getPathRelativeToFiles($absolutePath),
1955
-					$e,
1956
-					$e->getExistingLock()
1957
-				);
1958
-			}
1959
-		}
1960
-
1961
-		return true;
1962
-	}
1963
-
1964
-	/**
1965
-	 * Change the lock type
1966
-	 *
1967
-	 * @param string $path the path of the file to lock, relative to the view
1968
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1969
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1970
-	 *
1971
-	 * @return bool False if the path is excluded from locking, true otherwise
1972
-	 * @throws LockedException if the path is already locked
1973
-	 */
1974
-	public function changeLock($path, $type, $lockMountPoint = false) {
1975
-		$path = Filesystem::normalizePath($path);
1976
-		$absolutePath = $this->getAbsolutePath($path);
1977
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1978
-		if (!$this->shouldLockFile($absolutePath)) {
1979
-			return false;
1980
-		}
1981
-
1982
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1983
-		if ($mount) {
1984
-			try {
1985
-				$storage = $mount->getStorage();
1986
-				if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1987
-					$storage->changeLock(
1988
-						$mount->getInternalPath($absolutePath),
1989
-						$type,
1990
-						$this->lockingProvider
1991
-					);
1992
-				}
1993
-			} catch (LockedException $e) {
1994
-				try {
1995
-					// rethrow with the a human-readable path
1996
-					throw new LockedException(
1997
-						$this->getPathRelativeToFiles($absolutePath),
1998
-						$e,
1999
-						$e->getExistingLock()
2000
-					);
2001
-				} catch (\InvalidArgumentException $ex) {
2002
-					throw new LockedException(
2003
-						$absolutePath,
2004
-						$ex,
2005
-						$e->getExistingLock()
2006
-					);
2007
-				}
2008
-			}
2009
-		}
2010
-
2011
-		return true;
2012
-	}
2013
-
2014
-	/**
2015
-	 * Unlock the given path
2016
-	 *
2017
-	 * @param string $path the path of the file to unlock, relative to the view
2018
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2019
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2020
-	 *
2021
-	 * @return bool False if the path is excluded from locking, true otherwise
2022
-	 * @throws LockedException
2023
-	 */
2024
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2025
-		$absolutePath = $this->getAbsolutePath($path);
2026
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2027
-		if (!$this->shouldLockFile($absolutePath)) {
2028
-			return false;
2029
-		}
2030
-
2031
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2032
-		if ($mount) {
2033
-			$storage = $mount->getStorage();
2034
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2035
-				$storage->releaseLock(
2036
-					$mount->getInternalPath($absolutePath),
2037
-					$type,
2038
-					$this->lockingProvider
2039
-				);
2040
-			}
2041
-		}
2042
-
2043
-		return true;
2044
-	}
2045
-
2046
-	/**
2047
-	 * Lock a path and all its parents up to the root of the view
2048
-	 *
2049
-	 * @param string $path the path of the file to lock relative to the view
2050
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
-	 *
2053
-	 * @return bool False if the path is excluded from locking, true otherwise
2054
-	 * @throws LockedException
2055
-	 */
2056
-	public function lockFile($path, $type, $lockMountPoint = false) {
2057
-		$absolutePath = $this->getAbsolutePath($path);
2058
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2059
-		if (!$this->shouldLockFile($absolutePath)) {
2060
-			return false;
2061
-		}
2062
-
2063
-		$this->lockPath($path, $type, $lockMountPoint);
2064
-
2065
-		$parents = $this->getParents($path);
2066
-		foreach ($parents as $parent) {
2067
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2068
-		}
2069
-
2070
-		return true;
2071
-	}
2072
-
2073
-	/**
2074
-	 * Unlock a path and all its parents up to the root of the view
2075
-	 *
2076
-	 * @param string $path the path of the file to lock relative to the view
2077
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2078
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2079
-	 *
2080
-	 * @return bool False if the path is excluded from locking, true otherwise
2081
-	 * @throws LockedException
2082
-	 */
2083
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2084
-		$absolutePath = $this->getAbsolutePath($path);
2085
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2086
-		if (!$this->shouldLockFile($absolutePath)) {
2087
-			return false;
2088
-		}
2089
-
2090
-		$this->unlockPath($path, $type, $lockMountPoint);
2091
-
2092
-		$parents = $this->getParents($path);
2093
-		foreach ($parents as $parent) {
2094
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2095
-		}
2096
-
2097
-		return true;
2098
-	}
2099
-
2100
-	/**
2101
-	 * Only lock files in data/user/files/
2102
-	 *
2103
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2104
-	 * @return bool
2105
-	 */
2106
-	protected function shouldLockFile($path) {
2107
-		$path = Filesystem::normalizePath($path);
2108
-
2109
-		$pathSegments = explode('/', $path);
2110
-		if (isset($pathSegments[2])) {
2111
-			// E.g.: /username/files/path-to-file
2112
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2113
-		}
2114
-
2115
-		return strpos($path, '/appdata_') !== 0;
2116
-	}
2117
-
2118
-	/**
2119
-	 * Shortens the given absolute path to be relative to
2120
-	 * "$user/files".
2121
-	 *
2122
-	 * @param string $absolutePath absolute path which is under "files"
2123
-	 *
2124
-	 * @return string path relative to "files" with trimmed slashes or null
2125
-	 * if the path was NOT relative to files
2126
-	 *
2127
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2128
-	 * @since 8.1.0
2129
-	 */
2130
-	public function getPathRelativeToFiles($absolutePath) {
2131
-		$path = Filesystem::normalizePath($absolutePath);
2132
-		$parts = explode('/', trim($path, '/'), 3);
2133
-		// "$user", "files", "path/to/dir"
2134
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2135
-			$this->logger->error(
2136
-				'$absolutePath must be relative to "files", value is "%s"',
2137
-				[
2138
-					$absolutePath
2139
-				]
2140
-			);
2141
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2142
-		}
2143
-		if (isset($parts[2])) {
2144
-			return $parts[2];
2145
-		}
2146
-		return '';
2147
-	}
2148
-
2149
-	/**
2150
-	 * @param string $filename
2151
-	 * @return array
2152
-	 * @throws \OC\User\NoUserException
2153
-	 * @throws NotFoundException
2154
-	 */
2155
-	public function getUidAndFilename($filename) {
2156
-		$info = $this->getFileInfo($filename);
2157
-		if (!$info instanceof \OCP\Files\FileInfo) {
2158
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2159
-		}
2160
-		$uid = $info->getOwner()->getUID();
2161
-		if ($uid != \OCP\User::getUser()) {
2162
-			Filesystem::initMountPoints($uid);
2163
-			$ownerView = new View('/' . $uid . '/files');
2164
-			try {
2165
-				$filename = $ownerView->getPath($info['fileid']);
2166
-			} catch (NotFoundException $e) {
2167
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2168
-			}
2169
-		}
2170
-		return [$uid, $filename];
2171
-	}
2172
-
2173
-	/**
2174
-	 * Creates parent non-existing folders
2175
-	 *
2176
-	 * @param string $filePath
2177
-	 * @return bool
2178
-	 */
2179
-	private function createParentDirectories($filePath) {
2180
-		$directoryParts = explode('/', $filePath);
2181
-		$directoryParts = array_filter($directoryParts);
2182
-		foreach ($directoryParts as $key => $part) {
2183
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2184
-			$currentPath = '/' . implode('/', $currentPathElements);
2185
-			if ($this->is_file($currentPath)) {
2186
-				return false;
2187
-			}
2188
-			if (!$this->file_exists($currentPath)) {
2189
-				$this->mkdir($currentPath);
2190
-			}
2191
-		}
2192
-
2193
-		return true;
2194
-	}
86
+    /** @var string */
87
+    private $fakeRoot = '';
88
+
89
+    /**
90
+     * @var \OCP\Lock\ILockingProvider
91
+     */
92
+    protected $lockingProvider;
93
+
94
+    private $lockingEnabled;
95
+
96
+    private $updaterEnabled = true;
97
+
98
+    /** @var \OC\User\Manager */
99
+    private $userManager;
100
+
101
+    /** @var \OCP\ILogger */
102
+    private $logger;
103
+
104
+    /**
105
+     * @param string $root
106
+     * @throws \Exception If $root contains an invalid path
107
+     */
108
+    public function __construct($root = '') {
109
+        if (is_null($root)) {
110
+            throw new \InvalidArgumentException('Root can\'t be null');
111
+        }
112
+        if (!Filesystem::isValidPath($root)) {
113
+            throw new \Exception();
114
+        }
115
+
116
+        $this->fakeRoot = $root;
117
+        $this->lockingProvider = \OC::$server->getLockingProvider();
118
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
119
+        $this->userManager = \OC::$server->getUserManager();
120
+        $this->logger = \OC::$server->getLogger();
121
+    }
122
+
123
+    public function getAbsolutePath($path = '/') {
124
+        if ($path === null) {
125
+            return null;
126
+        }
127
+        $this->assertPathLength($path);
128
+        if ($path === '') {
129
+            $path = '/';
130
+        }
131
+        if ($path[0] !== '/') {
132
+            $path = '/' . $path;
133
+        }
134
+        return $this->fakeRoot . $path;
135
+    }
136
+
137
+    /**
138
+     * change the root to a fake root
139
+     *
140
+     * @param string $fakeRoot
141
+     * @return boolean|null
142
+     */
143
+    public function chroot($fakeRoot) {
144
+        if (!$fakeRoot == '') {
145
+            if ($fakeRoot[0] !== '/') {
146
+                $fakeRoot = '/' . $fakeRoot;
147
+            }
148
+        }
149
+        $this->fakeRoot = $fakeRoot;
150
+    }
151
+
152
+    /**
153
+     * get the fake root
154
+     *
155
+     * @return string
156
+     */
157
+    public function getRoot() {
158
+        return $this->fakeRoot;
159
+    }
160
+
161
+    /**
162
+     * get path relative to the root of the view
163
+     *
164
+     * @param string $path
165
+     * @return string
166
+     */
167
+    public function getRelativePath($path) {
168
+        $this->assertPathLength($path);
169
+        if ($this->fakeRoot == '') {
170
+            return $path;
171
+        }
172
+
173
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
174
+            return '/';
175
+        }
176
+
177
+        // missing slashes can cause wrong matches!
178
+        $root = rtrim($this->fakeRoot, '/') . '/';
179
+
180
+        if (strpos($path, $root) !== 0) {
181
+            return null;
182
+        } else {
183
+            $path = substr($path, strlen($this->fakeRoot));
184
+            if (strlen($path) === 0) {
185
+                return '/';
186
+            } else {
187
+                return $path;
188
+            }
189
+        }
190
+    }
191
+
192
+    /**
193
+     * get the mountpoint of the storage object for a path
194
+     * ( note: because a storage is not always mounted inside the fakeroot, the
195
+     * returned mountpoint is relative to the absolute root of the filesystem
196
+     * and does not take the chroot into account )
197
+     *
198
+     * @param string $path
199
+     * @return string
200
+     */
201
+    public function getMountPoint($path) {
202
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
203
+    }
204
+
205
+    /**
206
+     * get the mountpoint of the storage object for a path
207
+     * ( note: because a storage is not always mounted inside the fakeroot, the
208
+     * returned mountpoint is relative to the absolute root of the filesystem
209
+     * and does not take the chroot into account )
210
+     *
211
+     * @param string $path
212
+     * @return \OCP\Files\Mount\IMountPoint
213
+     */
214
+    public function getMount($path) {
215
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
216
+    }
217
+
218
+    /**
219
+     * resolve a path to a storage and internal path
220
+     *
221
+     * @param string $path
222
+     * @return array an array consisting of the storage and the internal path
223
+     */
224
+    public function resolvePath($path) {
225
+        $a = $this->getAbsolutePath($path);
226
+        $p = Filesystem::normalizePath($a);
227
+        return Filesystem::resolvePath($p);
228
+    }
229
+
230
+    /**
231
+     * return the path to a local version of the file
232
+     * we need this because we can't know if a file is stored local or not from
233
+     * outside the filestorage and for some purposes a local file is needed
234
+     *
235
+     * @param string $path
236
+     * @return string
237
+     */
238
+    public function getLocalFile($path) {
239
+        $parent = substr($path, 0, strrpos($path, '/'));
240
+        $path = $this->getAbsolutePath($path);
241
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
242
+        if (Filesystem::isValidPath($parent) and $storage) {
243
+            return $storage->getLocalFile($internalPath);
244
+        } else {
245
+            return null;
246
+        }
247
+    }
248
+
249
+    /**
250
+     * @param string $path
251
+     * @return string
252
+     */
253
+    public function getLocalFolder($path) {
254
+        $parent = substr($path, 0, strrpos($path, '/'));
255
+        $path = $this->getAbsolutePath($path);
256
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
257
+        if (Filesystem::isValidPath($parent) and $storage) {
258
+            return $storage->getLocalFolder($internalPath);
259
+        } else {
260
+            return null;
261
+        }
262
+    }
263
+
264
+    /**
265
+     * the following functions operate with arguments and return values identical
266
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
267
+     * for \OC\Files\Storage\Storage via basicOperation().
268
+     */
269
+    public function mkdir($path) {
270
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
271
+    }
272
+
273
+    /**
274
+     * remove mount point
275
+     *
276
+     * @param \OC\Files\Mount\MoveableMount $mount
277
+     * @param string $path relative to data/
278
+     * @return boolean
279
+     */
280
+    protected function removeMount($mount, $path) {
281
+        if ($mount instanceof MoveableMount) {
282
+            // cut of /user/files to get the relative path to data/user/files
283
+            $pathParts = explode('/', $path, 4);
284
+            $relPath = '/' . $pathParts[3];
285
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286
+            \OC_Hook::emit(
287
+                Filesystem::CLASSNAME, "umount",
288
+                [Filesystem::signal_param_path => $relPath]
289
+            );
290
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
291
+            $result = $mount->removeMount();
292
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
293
+            if ($result) {
294
+                \OC_Hook::emit(
295
+                    Filesystem::CLASSNAME, "post_umount",
296
+                    [Filesystem::signal_param_path => $relPath]
297
+                );
298
+            }
299
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
300
+            return $result;
301
+        } else {
302
+            // do not allow deleting the storage's root / the mount point
303
+            // because for some storages it might delete the whole contents
304
+            // but isn't supposed to work that way
305
+            return false;
306
+        }
307
+    }
308
+
309
+    public function disableCacheUpdate() {
310
+        $this->updaterEnabled = false;
311
+    }
312
+
313
+    public function enableCacheUpdate() {
314
+        $this->updaterEnabled = true;
315
+    }
316
+
317
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
318
+        if ($this->updaterEnabled) {
319
+            if (is_null($time)) {
320
+                $time = time();
321
+            }
322
+            $storage->getUpdater()->update($internalPath, $time);
323
+        }
324
+    }
325
+
326
+    protected function removeUpdate(Storage $storage, $internalPath) {
327
+        if ($this->updaterEnabled) {
328
+            $storage->getUpdater()->remove($internalPath);
329
+        }
330
+    }
331
+
332
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
333
+        if ($this->updaterEnabled) {
334
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
335
+        }
336
+    }
337
+
338
+    /**
339
+     * @param string $path
340
+     * @return bool|mixed
341
+     */
342
+    public function rmdir($path) {
343
+        $absolutePath = $this->getAbsolutePath($path);
344
+        $mount = Filesystem::getMountManager()->find($absolutePath);
345
+        if ($mount->getInternalPath($absolutePath) === '') {
346
+            return $this->removeMount($mount, $absolutePath);
347
+        }
348
+        if ($this->is_dir($path)) {
349
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
350
+        } else {
351
+            $result = false;
352
+        }
353
+
354
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
355
+            $storage = $mount->getStorage();
356
+            $internalPath = $mount->getInternalPath($absolutePath);
357
+            $storage->getUpdater()->remove($internalPath);
358
+        }
359
+        return $result;
360
+    }
361
+
362
+    /**
363
+     * @param string $path
364
+     * @return resource
365
+     */
366
+    public function opendir($path) {
367
+        return $this->basicOperation('opendir', $path, ['read']);
368
+    }
369
+
370
+    /**
371
+     * @param string $path
372
+     * @return bool|mixed
373
+     */
374
+    public function is_dir($path) {
375
+        if ($path == '/') {
376
+            return true;
377
+        }
378
+        return $this->basicOperation('is_dir', $path);
379
+    }
380
+
381
+    /**
382
+     * @param string $path
383
+     * @return bool|mixed
384
+     */
385
+    public function is_file($path) {
386
+        if ($path == '/') {
387
+            return false;
388
+        }
389
+        return $this->basicOperation('is_file', $path);
390
+    }
391
+
392
+    /**
393
+     * @param string $path
394
+     * @return mixed
395
+     */
396
+    public function stat($path) {
397
+        return $this->basicOperation('stat', $path);
398
+    }
399
+
400
+    /**
401
+     * @param string $path
402
+     * @return mixed
403
+     */
404
+    public function filetype($path) {
405
+        return $this->basicOperation('filetype', $path);
406
+    }
407
+
408
+    /**
409
+     * @param string $path
410
+     * @return mixed
411
+     */
412
+    public function filesize($path) {
413
+        return $this->basicOperation('filesize', $path);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @return bool|mixed
419
+     * @throws \OCP\Files\InvalidPathException
420
+     */
421
+    public function readfile($path) {
422
+        $this->assertPathLength($path);
423
+        @ob_end_clean();
424
+        $handle = $this->fopen($path, 'rb');
425
+        if ($handle) {
426
+            $chunkSize = 8192; // 8 kB chunks
427
+            while (!feof($handle)) {
428
+                echo fread($handle, $chunkSize);
429
+                flush();
430
+            }
431
+            fclose($handle);
432
+            return $this->filesize($path);
433
+        }
434
+        return false;
435
+    }
436
+
437
+    /**
438
+     * @param string $path
439
+     * @param int $from
440
+     * @param int $to
441
+     * @return bool|mixed
442
+     * @throws \OCP\Files\InvalidPathException
443
+     * @throws \OCP\Files\UnseekableException
444
+     */
445
+    public function readfilePart($path, $from, $to) {
446
+        $this->assertPathLength($path);
447
+        @ob_end_clean();
448
+        $handle = $this->fopen($path, 'rb');
449
+        if ($handle) {
450
+            $chunkSize = 8192; // 8 kB chunks
451
+            $startReading = true;
452
+
453
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
454
+                // forward file handle via chunked fread because fseek seem to have failed
455
+
456
+                $end = $from + 1;
457
+                while (!feof($handle) && ftell($handle) < $end) {
458
+                    $len = $from - ftell($handle);
459
+                    if ($len > $chunkSize) {
460
+                        $len = $chunkSize;
461
+                    }
462
+                    $result = fread($handle, $len);
463
+
464
+                    if ($result === false) {
465
+                        $startReading = false;
466
+                        break;
467
+                    }
468
+                }
469
+            }
470
+
471
+            if ($startReading) {
472
+                $end = $to + 1;
473
+                while (!feof($handle) && ftell($handle) < $end) {
474
+                    $len = $end - ftell($handle);
475
+                    if ($len > $chunkSize) {
476
+                        $len = $chunkSize;
477
+                    }
478
+                    echo fread($handle, $len);
479
+                    flush();
480
+                }
481
+                return ftell($handle) - $from;
482
+            }
483
+
484
+            throw new \OCP\Files\UnseekableException('fseek error');
485
+        }
486
+        return false;
487
+    }
488
+
489
+    /**
490
+     * @param string $path
491
+     * @return mixed
492
+     */
493
+    public function isCreatable($path) {
494
+        return $this->basicOperation('isCreatable', $path);
495
+    }
496
+
497
+    /**
498
+     * @param string $path
499
+     * @return mixed
500
+     */
501
+    public function isReadable($path) {
502
+        return $this->basicOperation('isReadable', $path);
503
+    }
504
+
505
+    /**
506
+     * @param string $path
507
+     * @return mixed
508
+     */
509
+    public function isUpdatable($path) {
510
+        return $this->basicOperation('isUpdatable', $path);
511
+    }
512
+
513
+    /**
514
+     * @param string $path
515
+     * @return bool|mixed
516
+     */
517
+    public function isDeletable($path) {
518
+        $absolutePath = $this->getAbsolutePath($path);
519
+        $mount = Filesystem::getMountManager()->find($absolutePath);
520
+        if ($mount->getInternalPath($absolutePath) === '') {
521
+            return $mount instanceof MoveableMount;
522
+        }
523
+        return $this->basicOperation('isDeletable', $path);
524
+    }
525
+
526
+    /**
527
+     * @param string $path
528
+     * @return mixed
529
+     */
530
+    public function isSharable($path) {
531
+        return $this->basicOperation('isSharable', $path);
532
+    }
533
+
534
+    /**
535
+     * @param string $path
536
+     * @return bool|mixed
537
+     */
538
+    public function file_exists($path) {
539
+        if ($path == '/') {
540
+            return true;
541
+        }
542
+        return $this->basicOperation('file_exists', $path);
543
+    }
544
+
545
+    /**
546
+     * @param string $path
547
+     * @return mixed
548
+     */
549
+    public function filemtime($path) {
550
+        return $this->basicOperation('filemtime', $path);
551
+    }
552
+
553
+    /**
554
+     * @param string $path
555
+     * @param int|string $mtime
556
+     * @return bool
557
+     */
558
+    public function touch($path, $mtime = null) {
559
+        if (!is_null($mtime) and !is_numeric($mtime)) {
560
+            $mtime = strtotime($mtime);
561
+        }
562
+
563
+        $hooks = ['touch'];
564
+
565
+        if (!$this->file_exists($path)) {
566
+            $hooks[] = 'create';
567
+            $hooks[] = 'write';
568
+        }
569
+        try {
570
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
571
+        } catch (\Exception $e) {
572
+            $this->logger->logException($e, ['level' => ILogger::INFO, 'message' => 'Error while setting modified time']);
573
+            $result = false;
574
+        }
575
+        if (!$result) {
576
+            // If create file fails because of permissions on external storage like SMB folders,
577
+            // check file exists and return false if not.
578
+            if (!$this->file_exists($path)) {
579
+                return false;
580
+            }
581
+            if (is_null($mtime)) {
582
+                $mtime = time();
583
+            }
584
+            //if native touch fails, we emulate it by changing the mtime in the cache
585
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
586
+        }
587
+        return true;
588
+    }
589
+
590
+    /**
591
+     * @param string $path
592
+     * @return mixed
593
+     * @throws LockedException
594
+     */
595
+    public function file_get_contents($path) {
596
+        return $this->basicOperation('file_get_contents', $path, ['read']);
597
+    }
598
+
599
+    /**
600
+     * @param bool $exists
601
+     * @param string $path
602
+     * @param bool $run
603
+     */
604
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
605
+        if (!$exists) {
606
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
607
+                Filesystem::signal_param_path => $this->getHookPath($path),
608
+                Filesystem::signal_param_run => &$run,
609
+            ]);
610
+        } else {
611
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
612
+                Filesystem::signal_param_path => $this->getHookPath($path),
613
+                Filesystem::signal_param_run => &$run,
614
+            ]);
615
+        }
616
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
617
+            Filesystem::signal_param_path => $this->getHookPath($path),
618
+            Filesystem::signal_param_run => &$run,
619
+        ]);
620
+    }
621
+
622
+    /**
623
+     * @param bool $exists
624
+     * @param string $path
625
+     */
626
+    protected function emit_file_hooks_post($exists, $path) {
627
+        if (!$exists) {
628
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
629
+                Filesystem::signal_param_path => $this->getHookPath($path),
630
+            ]);
631
+        } else {
632
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
633
+                Filesystem::signal_param_path => $this->getHookPath($path),
634
+            ]);
635
+        }
636
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
637
+            Filesystem::signal_param_path => $this->getHookPath($path),
638
+        ]);
639
+    }
640
+
641
+    /**
642
+     * @param string $path
643
+     * @param string|resource $data
644
+     * @return bool|mixed
645
+     * @throws LockedException
646
+     */
647
+    public function file_put_contents($path, $data) {
648
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
649
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
650
+            if (Filesystem::isValidPath($path)
651
+                and !Filesystem::isFileBlacklisted($path)
652
+            ) {
653
+                $path = $this->getRelativePath($absolutePath);
654
+
655
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
656
+
657
+                $exists = $this->file_exists($path);
658
+                $run = true;
659
+                if ($this->shouldEmitHooks($path)) {
660
+                    $this->emit_file_hooks_pre($exists, $path, $run);
661
+                }
662
+                if (!$run) {
663
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
664
+                    return false;
665
+                }
666
+
667
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
668
+
669
+                /** @var \OC\Files\Storage\Storage $storage */
670
+                list($storage, $internalPath) = $this->resolvePath($path);
671
+                $target = $storage->fopen($internalPath, 'w');
672
+                if ($target) {
673
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
674
+                    fclose($target);
675
+                    fclose($data);
676
+
677
+                    $this->writeUpdate($storage, $internalPath);
678
+
679
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
680
+
681
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
682
+                        $this->emit_file_hooks_post($exists, $path);
683
+                    }
684
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
685
+                    return $result;
686
+                } else {
687
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
688
+                    return false;
689
+                }
690
+            } else {
691
+                return false;
692
+            }
693
+        } else {
694
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
695
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
696
+        }
697
+    }
698
+
699
+    /**
700
+     * @param string $path
701
+     * @return bool|mixed
702
+     */
703
+    public function unlink($path) {
704
+        if ($path === '' || $path === '/') {
705
+            // do not allow deleting the root
706
+            return false;
707
+        }
708
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
709
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
710
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
711
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
712
+            return $this->removeMount($mount, $absolutePath);
713
+        }
714
+        if ($this->is_dir($path)) {
715
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
716
+        } else {
717
+            $result = $this->basicOperation('unlink', $path, ['delete']);
718
+        }
719
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
720
+            $storage = $mount->getStorage();
721
+            $internalPath = $mount->getInternalPath($absolutePath);
722
+            $storage->getUpdater()->remove($internalPath);
723
+            return true;
724
+        } else {
725
+            return $result;
726
+        }
727
+    }
728
+
729
+    /**
730
+     * @param string $directory
731
+     * @return bool|mixed
732
+     */
733
+    public function deleteAll($directory) {
734
+        return $this->rmdir($directory);
735
+    }
736
+
737
+    /**
738
+     * Rename/move a file or folder from the source path to target path.
739
+     *
740
+     * @param string $path1 source path
741
+     * @param string $path2 target path
742
+     *
743
+     * @return bool|mixed
744
+     * @throws LockedException
745
+     */
746
+    public function rename($path1, $path2) {
747
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
748
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
749
+        $result = false;
750
+        if (
751
+            Filesystem::isValidPath($path2)
752
+            and Filesystem::isValidPath($path1)
753
+            and !Filesystem::isFileBlacklisted($path2)
754
+        ) {
755
+            $path1 = $this->getRelativePath($absolutePath1);
756
+            $path2 = $this->getRelativePath($absolutePath2);
757
+            $exists = $this->file_exists($path2);
758
+
759
+            if ($path1 == null or $path2 == null) {
760
+                return false;
761
+            }
762
+
763
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
764
+            try {
765
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
766
+
767
+                $run = true;
768
+                if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
769
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
770
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
771
+                } elseif ($this->shouldEmitHooks($path1)) {
772
+                    \OC_Hook::emit(
773
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
774
+                        [
775
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
776
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
777
+                            Filesystem::signal_param_run => &$run
778
+                        ]
779
+                    );
780
+                }
781
+                if ($run) {
782
+                    $this->verifyPath(dirname($path2), basename($path2));
783
+
784
+                    $manager = Filesystem::getMountManager();
785
+                    $mount1 = $this->getMount($path1);
786
+                    $mount2 = $this->getMount($path2);
787
+                    $storage1 = $mount1->getStorage();
788
+                    $storage2 = $mount2->getStorage();
789
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
790
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
791
+
792
+                    $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
793
+                    try {
794
+                        $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
795
+
796
+                        if ($internalPath1 === '') {
797
+                            if ($mount1 instanceof MoveableMount) {
798
+                                $sourceParentMount = $this->getMount(dirname($path1));
799
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
800
+                                    /**
801
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
802
+                                     */
803
+                                    $sourceMountPoint = $mount1->getMountPoint();
804
+                                    $result = $mount1->moveMount($absolutePath2);
805
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
806
+                                } else {
807
+                                    $result = false;
808
+                                }
809
+                            } else {
810
+                                $result = false;
811
+                            }
812
+                            // moving a file/folder within the same mount point
813
+                        } elseif ($storage1 === $storage2) {
814
+                            if ($storage1) {
815
+                                $result = $storage1->rename($internalPath1, $internalPath2);
816
+                            } else {
817
+                                $result = false;
818
+                            }
819
+                            // moving a file/folder between storages (from $storage1 to $storage2)
820
+                        } else {
821
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
822
+                        }
823
+
824
+                        if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
825
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
826
+                            $this->writeUpdate($storage2, $internalPath2);
827
+                        } else if ($result) {
828
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
829
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
830
+                            }
831
+                        }
832
+                    } catch(\Exception $e) {
833
+                        throw $e;
834
+                    } finally {
835
+                        $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
836
+                        $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
837
+                    }
838
+
839
+                    if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
840
+                        if ($this->shouldEmitHooks()) {
841
+                            $this->emit_file_hooks_post($exists, $path2);
842
+                        }
843
+                    } elseif ($result) {
844
+                        if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
845
+                            \OC_Hook::emit(
846
+                                Filesystem::CLASSNAME,
847
+                                Filesystem::signal_post_rename,
848
+                                [
849
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($path1),
850
+                                    Filesystem::signal_param_newpath => $this->getHookPath($path2)
851
+                                ]
852
+                            );
853
+                        }
854
+                    }
855
+                }
856
+            } catch(\Exception $e) {
857
+                throw $e;
858
+            } finally {
859
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
860
+                $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
861
+            }
862
+        }
863
+        return $result;
864
+    }
865
+
866
+    /**
867
+     * Copy a file/folder from the source path to target path
868
+     *
869
+     * @param string $path1 source path
870
+     * @param string $path2 target path
871
+     * @param bool $preserveMtime whether to preserve mtime on the copy
872
+     *
873
+     * @return bool|mixed
874
+     */
875
+    public function copy($path1, $path2, $preserveMtime = false) {
876
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
877
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
878
+        $result = false;
879
+        if (
880
+            Filesystem::isValidPath($path2)
881
+            and Filesystem::isValidPath($path1)
882
+            and !Filesystem::isFileBlacklisted($path2)
883
+        ) {
884
+            $path1 = $this->getRelativePath($absolutePath1);
885
+            $path2 = $this->getRelativePath($absolutePath2);
886
+
887
+            if ($path1 == null or $path2 == null) {
888
+                return false;
889
+            }
890
+            $run = true;
891
+
892
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
893
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
894
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
895
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
896
+
897
+            try {
898
+
899
+                $exists = $this->file_exists($path2);
900
+                if ($this->shouldEmitHooks()) {
901
+                    \OC_Hook::emit(
902
+                        Filesystem::CLASSNAME,
903
+                        Filesystem::signal_copy,
904
+                        [
905
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
906
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
907
+                            Filesystem::signal_param_run => &$run
908
+                        ]
909
+                    );
910
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
911
+                }
912
+                if ($run) {
913
+                    $mount1 = $this->getMount($path1);
914
+                    $mount2 = $this->getMount($path2);
915
+                    $storage1 = $mount1->getStorage();
916
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
917
+                    $storage2 = $mount2->getStorage();
918
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
919
+
920
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
921
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
922
+
923
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
924
+                        if ($storage1) {
925
+                            $result = $storage1->copy($internalPath1, $internalPath2);
926
+                        } else {
927
+                            $result = false;
928
+                        }
929
+                    } else {
930
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
931
+                    }
932
+
933
+                    $this->writeUpdate($storage2, $internalPath2);
934
+
935
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
936
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
+
938
+                    if ($this->shouldEmitHooks() && $result !== false) {
939
+                        \OC_Hook::emit(
940
+                            Filesystem::CLASSNAME,
941
+                            Filesystem::signal_post_copy,
942
+                            [
943
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
944
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
945
+                            ]
946
+                        );
947
+                        $this->emit_file_hooks_post($exists, $path2);
948
+                    }
949
+
950
+                }
951
+            } catch (\Exception $e) {
952
+                $this->unlockFile($path2, $lockTypePath2);
953
+                $this->unlockFile($path1, $lockTypePath1);
954
+                throw $e;
955
+            }
956
+
957
+            $this->unlockFile($path2, $lockTypePath2);
958
+            $this->unlockFile($path1, $lockTypePath1);
959
+
960
+        }
961
+        return $result;
962
+    }
963
+
964
+    /**
965
+     * @param string $path
966
+     * @param string $mode 'r' or 'w'
967
+     * @return resource
968
+     * @throws LockedException
969
+     */
970
+    public function fopen($path, $mode) {
971
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
972
+        $hooks = [];
973
+        switch ($mode) {
974
+            case 'r':
975
+                $hooks[] = 'read';
976
+                break;
977
+            case 'r+':
978
+            case 'w+':
979
+            case 'x+':
980
+            case 'a+':
981
+                $hooks[] = 'read';
982
+                $hooks[] = 'write';
983
+                break;
984
+            case 'w':
985
+            case 'x':
986
+            case 'a':
987
+                $hooks[] = 'write';
988
+                break;
989
+            default:
990
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
991
+        }
992
+
993
+        if ($mode !== 'r' && $mode !== 'w') {
994
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
995
+        }
996
+
997
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
998
+    }
999
+
1000
+    /**
1001
+     * @param string $path
1002
+     * @return bool|string
1003
+     * @throws \OCP\Files\InvalidPathException
1004
+     */
1005
+    public function toTmpFile($path) {
1006
+        $this->assertPathLength($path);
1007
+        if (Filesystem::isValidPath($path)) {
1008
+            $source = $this->fopen($path, 'r');
1009
+            if ($source) {
1010
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1011
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1012
+                file_put_contents($tmpFile, $source);
1013
+                return $tmpFile;
1014
+            } else {
1015
+                return false;
1016
+            }
1017
+        } else {
1018
+            return false;
1019
+        }
1020
+    }
1021
+
1022
+    /**
1023
+     * @param string $tmpFile
1024
+     * @param string $path
1025
+     * @return bool|mixed
1026
+     * @throws \OCP\Files\InvalidPathException
1027
+     */
1028
+    public function fromTmpFile($tmpFile, $path) {
1029
+        $this->assertPathLength($path);
1030
+        if (Filesystem::isValidPath($path)) {
1031
+
1032
+            // Get directory that the file is going into
1033
+            $filePath = dirname($path);
1034
+
1035
+            // Create the directories if any
1036
+            if (!$this->file_exists($filePath)) {
1037
+                $result = $this->createParentDirectories($filePath);
1038
+                if ($result === false) {
1039
+                    return false;
1040
+                }
1041
+            }
1042
+
1043
+            $source = fopen($tmpFile, 'r');
1044
+            if ($source) {
1045
+                $result = $this->file_put_contents($path, $source);
1046
+                // $this->file_put_contents() might have already closed
1047
+                // the resource, so we check it, before trying to close it
1048
+                // to avoid messages in the error log.
1049
+                if (is_resource($source)) {
1050
+                    fclose($source);
1051
+                }
1052
+                unlink($tmpFile);
1053
+                return $result;
1054
+            } else {
1055
+                return false;
1056
+            }
1057
+        } else {
1058
+            return false;
1059
+        }
1060
+    }
1061
+
1062
+
1063
+    /**
1064
+     * @param string $path
1065
+     * @return mixed
1066
+     * @throws \OCP\Files\InvalidPathException
1067
+     */
1068
+    public function getMimeType($path) {
1069
+        $this->assertPathLength($path);
1070
+        return $this->basicOperation('getMimeType', $path);
1071
+    }
1072
+
1073
+    /**
1074
+     * @param string $type
1075
+     * @param string $path
1076
+     * @param bool $raw
1077
+     * @return bool|null|string
1078
+     */
1079
+    public function hash($type, $path, $raw = false) {
1080
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1081
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1082
+        if (Filesystem::isValidPath($path)) {
1083
+            $path = $this->getRelativePath($absolutePath);
1084
+            if ($path == null) {
1085
+                return false;
1086
+            }
1087
+            if ($this->shouldEmitHooks($path)) {
1088
+                \OC_Hook::emit(
1089
+                    Filesystem::CLASSNAME,
1090
+                    Filesystem::signal_read,
1091
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1092
+                );
1093
+            }
1094
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1095
+            if ($storage) {
1096
+                return $storage->hash($type, $internalPath, $raw);
1097
+            }
1098
+        }
1099
+        return null;
1100
+    }
1101
+
1102
+    /**
1103
+     * @param string $path
1104
+     * @return mixed
1105
+     * @throws \OCP\Files\InvalidPathException
1106
+     */
1107
+    public function free_space($path = '/') {
1108
+        $this->assertPathLength($path);
1109
+        $result = $this->basicOperation('free_space', $path);
1110
+        if ($result === null) {
1111
+            throw new InvalidPathException();
1112
+        }
1113
+        return $result;
1114
+    }
1115
+
1116
+    /**
1117
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1118
+     *
1119
+     * @param string $operation
1120
+     * @param string $path
1121
+     * @param array $hooks (optional)
1122
+     * @param mixed $extraParam (optional)
1123
+     * @return mixed
1124
+     * @throws LockedException
1125
+     *
1126
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1127
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1128
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1129
+     */
1130
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1131
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1132
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
+        if (Filesystem::isValidPath($path)
1134
+            and !Filesystem::isFileBlacklisted($path)
1135
+        ) {
1136
+            $path = $this->getRelativePath($absolutePath);
1137
+            if ($path == null) {
1138
+                return false;
1139
+            }
1140
+
1141
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1142
+                // always a shared lock during pre-hooks so the hook can read the file
1143
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1144
+            }
1145
+
1146
+            $run = $this->runHooks($hooks, $path);
1147
+            /** @var \OC\Files\Storage\Storage $storage */
1148
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1149
+            if ($run and $storage) {
1150
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1151
+                    try {
1152
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1153
+                    } catch (LockedException $e) {
1154
+                        // release the shared lock we acquired before quiting
1155
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1156
+                        throw $e;
1157
+                    }
1158
+                }
1159
+                try {
1160
+                    if (!is_null($extraParam)) {
1161
+                        $result = $storage->$operation($internalPath, $extraParam);
1162
+                    } else {
1163
+                        $result = $storage->$operation($internalPath);
1164
+                    }
1165
+                } catch (\Exception $e) {
1166
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1167
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1168
+                    } else if (in_array('read', $hooks)) {
1169
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1170
+                    }
1171
+                    throw $e;
1172
+                }
1173
+
1174
+                if ($result && in_array('delete', $hooks) and $result) {
1175
+                    $this->removeUpdate($storage, $internalPath);
1176
+                }
1177
+                if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1178
+                    $this->writeUpdate($storage, $internalPath);
1179
+                }
1180
+                if ($result && in_array('touch', $hooks)) {
1181
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1182
+                }
1183
+
1184
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1185
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1186
+                }
1187
+
1188
+                $unlockLater = false;
1189
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1190
+                    $unlockLater = true;
1191
+                    // make sure our unlocking callback will still be called if connection is aborted
1192
+                    ignore_user_abort(true);
1193
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1194
+                        if (in_array('write', $hooks)) {
1195
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1196
+                        } else if (in_array('read', $hooks)) {
1197
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1198
+                        }
1199
+                    });
1200
+                }
1201
+
1202
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1203
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1204
+                        $this->runHooks($hooks, $path, true);
1205
+                    }
1206
+                }
1207
+
1208
+                if (!$unlockLater
1209
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1210
+                ) {
1211
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1212
+                }
1213
+                return $result;
1214
+            } else {
1215
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1216
+            }
1217
+        }
1218
+        return null;
1219
+    }
1220
+
1221
+    /**
1222
+     * get the path relative to the default root for hook usage
1223
+     *
1224
+     * @param string $path
1225
+     * @return string
1226
+     */
1227
+    private function getHookPath($path) {
1228
+        if (!Filesystem::getView()) {
1229
+            return $path;
1230
+        }
1231
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1232
+    }
1233
+
1234
+    private function shouldEmitHooks($path = '') {
1235
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1236
+            return false;
1237
+        }
1238
+        if (!Filesystem::$loaded) {
1239
+            return false;
1240
+        }
1241
+        $defaultRoot = Filesystem::getRoot();
1242
+        if ($defaultRoot === null) {
1243
+            return false;
1244
+        }
1245
+        if ($this->fakeRoot === $defaultRoot) {
1246
+            return true;
1247
+        }
1248
+        $fullPath = $this->getAbsolutePath($path);
1249
+
1250
+        if ($fullPath === $defaultRoot) {
1251
+            return true;
1252
+        }
1253
+
1254
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1255
+    }
1256
+
1257
+    /**
1258
+     * @param string[] $hooks
1259
+     * @param string $path
1260
+     * @param bool $post
1261
+     * @return bool
1262
+     */
1263
+    private function runHooks($hooks, $path, $post = false) {
1264
+        $relativePath = $path;
1265
+        $path = $this->getHookPath($path);
1266
+        $prefix = $post ? 'post_' : '';
1267
+        $run = true;
1268
+        if ($this->shouldEmitHooks($relativePath)) {
1269
+            foreach ($hooks as $hook) {
1270
+                if ($hook != 'read') {
1271
+                    \OC_Hook::emit(
1272
+                        Filesystem::CLASSNAME,
1273
+                        $prefix . $hook,
1274
+                        [
1275
+                            Filesystem::signal_param_run => &$run,
1276
+                            Filesystem::signal_param_path => $path
1277
+                        ]
1278
+                    );
1279
+                } elseif (!$post) {
1280
+                    \OC_Hook::emit(
1281
+                        Filesystem::CLASSNAME,
1282
+                        $prefix . $hook,
1283
+                        [
1284
+                            Filesystem::signal_param_path => $path
1285
+                        ]
1286
+                    );
1287
+                }
1288
+            }
1289
+        }
1290
+        return $run;
1291
+    }
1292
+
1293
+    /**
1294
+     * check if a file or folder has been updated since $time
1295
+     *
1296
+     * @param string $path
1297
+     * @param int $time
1298
+     * @return bool
1299
+     */
1300
+    public function hasUpdated($path, $time) {
1301
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1302
+    }
1303
+
1304
+    /**
1305
+     * @param string $ownerId
1306
+     * @return \OC\User\User
1307
+     */
1308
+    private function getUserObjectForOwner($ownerId) {
1309
+        $owner = $this->userManager->get($ownerId);
1310
+        if ($owner instanceof IUser) {
1311
+            return $owner;
1312
+        } else {
1313
+            return new User($ownerId, null, \OC::$server->getEventDispatcher());
1314
+        }
1315
+    }
1316
+
1317
+    /**
1318
+     * Get file info from cache
1319
+     *
1320
+     * If the file is not in cached it will be scanned
1321
+     * If the file has changed on storage the cache will be updated
1322
+     *
1323
+     * @param \OC\Files\Storage\Storage $storage
1324
+     * @param string $internalPath
1325
+     * @param string $relativePath
1326
+     * @return ICacheEntry|bool
1327
+     */
1328
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1329
+        $cache = $storage->getCache($internalPath);
1330
+        $data = $cache->get($internalPath);
1331
+        $watcher = $storage->getWatcher($internalPath);
1332
+
1333
+        try {
1334
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1335
+            if (!$data || $data['size'] === -1) {
1336
+                if (!$storage->file_exists($internalPath)) {
1337
+                    return false;
1338
+                }
1339
+                // don't need to get a lock here since the scanner does it's own locking
1340
+                $scanner = $storage->getScanner($internalPath);
1341
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1342
+                $data = $cache->get($internalPath);
1343
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1344
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1345
+                $watcher->update($internalPath, $data);
1346
+                $storage->getPropagator()->propagateChange($internalPath, time());
1347
+                $data = $cache->get($internalPath);
1348
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1349
+            }
1350
+        } catch (LockedException $e) {
1351
+            // if the file is locked we just use the old cache info
1352
+        }
1353
+
1354
+        return $data;
1355
+    }
1356
+
1357
+    /**
1358
+     * get the filesystem info
1359
+     *
1360
+     * @param string $path
1361
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1362
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1363
+     * defaults to true
1364
+     * @return \OC\Files\FileInfo|false False if file does not exist
1365
+     */
1366
+    public function getFileInfo($path, $includeMountPoints = true) {
1367
+        $this->assertPathLength($path);
1368
+        if (!Filesystem::isValidPath($path)) {
1369
+            return false;
1370
+        }
1371
+        if (Cache\Scanner::isPartialFile($path)) {
1372
+            return $this->getPartFileInfo($path);
1373
+        }
1374
+        $relativePath = $path;
1375
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1376
+
1377
+        $mount = Filesystem::getMountManager()->find($path);
1378
+        if (!$mount) {
1379
+            \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1380
+            return false;
1381
+        }
1382
+        $storage = $mount->getStorage();
1383
+        $internalPath = $mount->getInternalPath($path);
1384
+        if ($storage) {
1385
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1386
+
1387
+            if (!$data instanceof ICacheEntry) {
1388
+                return false;
1389
+            }
1390
+
1391
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1392
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1393
+            }
1394
+            $ownerId = $storage->getOwner($internalPath);
1395
+            $owner = null;
1396
+            if ($ownerId !== null && $ownerId !== false) {
1397
+                // ownerId might be null if files are accessed with an access token without file system access
1398
+                $owner = $this->getUserObjectForOwner($ownerId);
1399
+            }
1400
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1401
+
1402
+            if ($data and isset($data['fileid'])) {
1403
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1404
+                    //add the sizes of other mount points to the folder
1405
+                    $extOnly = ($includeMountPoints === 'ext');
1406
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1407
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1408
+                        $subStorage = $mount->getStorage();
1409
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1410
+                    }));
1411
+                }
1412
+            }
1413
+
1414
+            return $info;
1415
+        } else {
1416
+            \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1417
+        }
1418
+
1419
+        return false;
1420
+    }
1421
+
1422
+    /**
1423
+     * get the content of a directory
1424
+     *
1425
+     * @param string $directory path under datadirectory
1426
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1427
+     * @return FileInfo[]
1428
+     */
1429
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1430
+        $this->assertPathLength($directory);
1431
+        if (!Filesystem::isValidPath($directory)) {
1432
+            return [];
1433
+        }
1434
+        $path = $this->getAbsolutePath($directory);
1435
+        $path = Filesystem::normalizePath($path);
1436
+        $mount = $this->getMount($directory);
1437
+        if (!$mount) {
1438
+            return [];
1439
+        }
1440
+        $storage = $mount->getStorage();
1441
+        $internalPath = $mount->getInternalPath($path);
1442
+        if ($storage) {
1443
+            $cache = $storage->getCache($internalPath);
1444
+            $user = \OC_User::getUser();
1445
+
1446
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1447
+
1448
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1449
+                return [];
1450
+            }
1451
+
1452
+            $folderId = $data['fileid'];
1453
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1454
+
1455
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1456
+
1457
+            $fileNames = array_map(function (ICacheEntry $content) {
1458
+                return $content->getName();
1459
+            }, $contents);
1460
+            /**
1461
+             * @var \OC\Files\FileInfo[] $fileInfos
1462
+             */
1463
+            $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1464
+                if ($sharingDisabled) {
1465
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1466
+                }
1467
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1468
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1469
+            }, $contents);
1470
+            $files = array_combine($fileNames, $fileInfos);
1471
+
1472
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1473
+            $mounts = Filesystem::getMountManager()->findIn($path);
1474
+            $dirLength = strlen($path);
1475
+            foreach ($mounts as $mount) {
1476
+                $mountPoint = $mount->getMountPoint();
1477
+                $subStorage = $mount->getStorage();
1478
+                if ($subStorage) {
1479
+                    $subCache = $subStorage->getCache('');
1480
+
1481
+                    $rootEntry = $subCache->get('');
1482
+                    if (!$rootEntry) {
1483
+                        $subScanner = $subStorage->getScanner('');
1484
+                        try {
1485
+                            $subScanner->scanFile('');
1486
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1487
+                            continue;
1488
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1489
+                            continue;
1490
+                        } catch (\Exception $e) {
1491
+                            // sometimes when the storage is not available it can be any exception
1492
+                            \OC::$server->getLogger()->logException($e, [
1493
+                                'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1494
+                                'level' => ILogger::ERROR,
1495
+                                'app' => 'lib',
1496
+                            ]);
1497
+                            continue;
1498
+                        }
1499
+                        $rootEntry = $subCache->get('');
1500
+                    }
1501
+
1502
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1503
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1504
+                        if ($pos = strpos($relativePath, '/')) {
1505
+                            //mountpoint inside subfolder add size to the correct folder
1506
+                            $entryName = substr($relativePath, 0, $pos);
1507
+                            foreach ($files as &$entry) {
1508
+                                if ($entry->getName() === $entryName) {
1509
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1510
+                                }
1511
+                            }
1512
+                        } else { //mountpoint in this folder, add an entry for it
1513
+                            $rootEntry['name'] = $relativePath;
1514
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1515
+                            $permissions = $rootEntry['permissions'];
1516
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1517
+                            // for shared files/folders we use the permissions given by the owner
1518
+                            if ($mount instanceof MoveableMount) {
1519
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1520
+                            } else {
1521
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1522
+                            }
1523
+
1524
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1525
+
1526
+                            // if sharing was disabled for the user we remove the share permissions
1527
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1528
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1529
+                            }
1530
+
1531
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1532
+                            $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1533
+                        }
1534
+                    }
1535
+                }
1536
+            }
1537
+
1538
+            if ($mimetype_filter) {
1539
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1540
+                    if (strpos($mimetype_filter, '/')) {
1541
+                        return $file->getMimetype() === $mimetype_filter;
1542
+                    } else {
1543
+                        return $file->getMimePart() === $mimetype_filter;
1544
+                    }
1545
+                });
1546
+            }
1547
+
1548
+            return array_values($files);
1549
+        } else {
1550
+            return [];
1551
+        }
1552
+    }
1553
+
1554
+    /**
1555
+     * change file metadata
1556
+     *
1557
+     * @param string $path
1558
+     * @param array|\OCP\Files\FileInfo $data
1559
+     * @return int
1560
+     *
1561
+     * returns the fileid of the updated file
1562
+     */
1563
+    public function putFileInfo($path, $data) {
1564
+        $this->assertPathLength($path);
1565
+        if ($data instanceof FileInfo) {
1566
+            $data = $data->getData();
1567
+        }
1568
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1569
+        /**
1570
+         * @var \OC\Files\Storage\Storage $storage
1571
+         * @var string $internalPath
1572
+         */
1573
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1574
+        if ($storage) {
1575
+            $cache = $storage->getCache($path);
1576
+
1577
+            if (!$cache->inCache($internalPath)) {
1578
+                $scanner = $storage->getScanner($internalPath);
1579
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1580
+            }
1581
+
1582
+            return $cache->put($internalPath, $data);
1583
+        } else {
1584
+            return -1;
1585
+        }
1586
+    }
1587
+
1588
+    /**
1589
+     * search for files with the name matching $query
1590
+     *
1591
+     * @param string $query
1592
+     * @return FileInfo[]
1593
+     */
1594
+    public function search($query) {
1595
+        return $this->searchCommon('search', ['%' . $query . '%']);
1596
+    }
1597
+
1598
+    /**
1599
+     * search for files with the name matching $query
1600
+     *
1601
+     * @param string $query
1602
+     * @return FileInfo[]
1603
+     */
1604
+    public function searchRaw($query) {
1605
+        return $this->searchCommon('search', [$query]);
1606
+    }
1607
+
1608
+    /**
1609
+     * search for files by mimetype
1610
+     *
1611
+     * @param string $mimetype
1612
+     * @return FileInfo[]
1613
+     */
1614
+    public function searchByMime($mimetype) {
1615
+        return $this->searchCommon('searchByMime', [$mimetype]);
1616
+    }
1617
+
1618
+    /**
1619
+     * search for files by tag
1620
+     *
1621
+     * @param string|int $tag name or tag id
1622
+     * @param string $userId owner of the tags
1623
+     * @return FileInfo[]
1624
+     */
1625
+    public function searchByTag($tag, $userId) {
1626
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1627
+    }
1628
+
1629
+    /**
1630
+     * @param string $method cache method
1631
+     * @param array $args
1632
+     * @return FileInfo[]
1633
+     */
1634
+    private function searchCommon($method, $args) {
1635
+        $files = [];
1636
+        $rootLength = strlen($this->fakeRoot);
1637
+
1638
+        $mount = $this->getMount('');
1639
+        $mountPoint = $mount->getMountPoint();
1640
+        $storage = $mount->getStorage();
1641
+        if ($storage) {
1642
+            $cache = $storage->getCache('');
1643
+
1644
+            $results = call_user_func_array([$cache, $method], $args);
1645
+            foreach ($results as $result) {
1646
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1647
+                    $internalPath = $result['path'];
1648
+                    $path = $mountPoint . $result['path'];
1649
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1650
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1651
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
+                }
1653
+            }
1654
+
1655
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1656
+            foreach ($mounts as $mount) {
1657
+                $mountPoint = $mount->getMountPoint();
1658
+                $storage = $mount->getStorage();
1659
+                if ($storage) {
1660
+                    $cache = $storage->getCache('');
1661
+
1662
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1663
+                    $results = call_user_func_array([$cache, $method], $args);
1664
+                    if ($results) {
1665
+                        foreach ($results as $result) {
1666
+                            $internalPath = $result['path'];
1667
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1668
+                            $path = rtrim($mountPoint . $internalPath, '/');
1669
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1670
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671
+                        }
1672
+                    }
1673
+                }
1674
+            }
1675
+        }
1676
+        return $files;
1677
+    }
1678
+
1679
+    /**
1680
+     * Get the owner for a file or folder
1681
+     *
1682
+     * @param string $path
1683
+     * @return string the user id of the owner
1684
+     * @throws NotFoundException
1685
+     */
1686
+    public function getOwner($path) {
1687
+        $info = $this->getFileInfo($path);
1688
+        if (!$info) {
1689
+            throw new NotFoundException($path . ' not found while trying to get owner');
1690
+        }
1691
+
1692
+        if ($info->getOwner() === null) {
1693
+            throw new NotFoundException($path . ' has no owner');
1694
+        }
1695
+
1696
+        return $info->getOwner()->getUID();
1697
+    }
1698
+
1699
+    /**
1700
+     * get the ETag for a file or folder
1701
+     *
1702
+     * @param string $path
1703
+     * @return string
1704
+     */
1705
+    public function getETag($path) {
1706
+        /**
1707
+         * @var Storage\Storage $storage
1708
+         * @var string $internalPath
1709
+         */
1710
+        list($storage, $internalPath) = $this->resolvePath($path);
1711
+        if ($storage) {
1712
+            return $storage->getETag($internalPath);
1713
+        } else {
1714
+            return null;
1715
+        }
1716
+    }
1717
+
1718
+    /**
1719
+     * Get the path of a file by id, relative to the view
1720
+     *
1721
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1722
+     *
1723
+     * @param int $id
1724
+     * @throws NotFoundException
1725
+     * @return string
1726
+     */
1727
+    public function getPath($id) {
1728
+        $id = (int)$id;
1729
+        $manager = Filesystem::getMountManager();
1730
+        $mounts = $manager->findIn($this->fakeRoot);
1731
+        $mounts[] = $manager->find($this->fakeRoot);
1732
+        // reverse the array so we start with the storage this view is in
1733
+        // which is the most likely to contain the file we're looking for
1734
+        $mounts = array_reverse($mounts);
1735
+
1736
+        // put non shared mounts in front of the shared mount
1737
+        // this prevent unneeded recursion into shares
1738
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1739
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1740
+        });
1741
+
1742
+        foreach ($mounts as $mount) {
1743
+            /**
1744
+             * @var \OC\Files\Mount\MountPoint $mount
1745
+             */
1746
+            if ($mount->getStorage()) {
1747
+                $cache = $mount->getStorage()->getCache();
1748
+                $internalPath = $cache->getPathById($id);
1749
+                if (is_string($internalPath)) {
1750
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1751
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1752
+                        return $path;
1753
+                    }
1754
+                }
1755
+            }
1756
+        }
1757
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1758
+    }
1759
+
1760
+    /**
1761
+     * @param string $path
1762
+     * @throws InvalidPathException
1763
+     */
1764
+    private function assertPathLength($path) {
1765
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1766
+        // Check for the string length - performed using isset() instead of strlen()
1767
+        // because isset() is about 5x-40x faster.
1768
+        if (isset($path[$maxLen])) {
1769
+            $pathLen = strlen($path);
1770
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1771
+        }
1772
+    }
1773
+
1774
+    /**
1775
+     * check if it is allowed to move a mount point to a given target.
1776
+     * It is not allowed to move a mount point into a different mount point or
1777
+     * into an already shared folder
1778
+     *
1779
+     * @param IStorage $targetStorage
1780
+     * @param string $targetInternalPath
1781
+     * @return boolean
1782
+     */
1783
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1784
+
1785
+        // note: cannot use the view because the target is already locked
1786
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1787
+        if ($fileId === -1) {
1788
+            // target might not exist, need to check parent instead
1789
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1790
+        }
1791
+
1792
+        // check if any of the parents were shared by the current owner (include collections)
1793
+        $shares = \OCP\Share::getItemShared(
1794
+            'folder',
1795
+            $fileId,
1796
+            \OCP\Share::FORMAT_NONE,
1797
+            null,
1798
+            true
1799
+        );
1800
+
1801
+        if (count($shares) > 0) {
1802
+            \OCP\Util::writeLog('files',
1803
+                'It is not allowed to move one mount point into a shared folder',
1804
+                ILogger::DEBUG);
1805
+            return false;
1806
+        }
1807
+
1808
+        return true;
1809
+    }
1810
+
1811
+    /**
1812
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1813
+     *
1814
+     * @param string $path
1815
+     * @return \OCP\Files\FileInfo
1816
+     */
1817
+    private function getPartFileInfo($path) {
1818
+        $mount = $this->getMount($path);
1819
+        $storage = $mount->getStorage();
1820
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1821
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1822
+        return new FileInfo(
1823
+            $this->getAbsolutePath($path),
1824
+            $storage,
1825
+            $internalPath,
1826
+            [
1827
+                'fileid' => null,
1828
+                'mimetype' => $storage->getMimeType($internalPath),
1829
+                'name' => basename($path),
1830
+                'etag' => null,
1831
+                'size' => $storage->filesize($internalPath),
1832
+                'mtime' => $storage->filemtime($internalPath),
1833
+                'encrypted' => false,
1834
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1835
+            ],
1836
+            $mount,
1837
+            $owner
1838
+        );
1839
+    }
1840
+
1841
+    /**
1842
+     * @param string $path
1843
+     * @param string $fileName
1844
+     * @throws InvalidPathException
1845
+     */
1846
+    public function verifyPath($path, $fileName) {
1847
+        try {
1848
+            /** @type \OCP\Files\Storage $storage */
1849
+            list($storage, $internalPath) = $this->resolvePath($path);
1850
+            $storage->verifyPath($internalPath, $fileName);
1851
+        } catch (ReservedWordException $ex) {
1852
+            $l = \OC::$server->getL10N('lib');
1853
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1854
+        } catch (InvalidCharacterInPathException $ex) {
1855
+            $l = \OC::$server->getL10N('lib');
1856
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1857
+        } catch (FileNameTooLongException $ex) {
1858
+            $l = \OC::$server->getL10N('lib');
1859
+            throw new InvalidPathException($l->t('File name is too long'));
1860
+        } catch (InvalidDirectoryException $ex) {
1861
+            $l = \OC::$server->getL10N('lib');
1862
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1863
+        } catch (EmptyFileNameException $ex) {
1864
+            $l = \OC::$server->getL10N('lib');
1865
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1866
+        }
1867
+    }
1868
+
1869
+    /**
1870
+     * get all parent folders of $path
1871
+     *
1872
+     * @param string $path
1873
+     * @return string[]
1874
+     */
1875
+    private function getParents($path) {
1876
+        $path = trim($path, '/');
1877
+        if (!$path) {
1878
+            return [];
1879
+        }
1880
+
1881
+        $parts = explode('/', $path);
1882
+
1883
+        // remove the single file
1884
+        array_pop($parts);
1885
+        $result = ['/'];
1886
+        $resultPath = '';
1887
+        foreach ($parts as $part) {
1888
+            if ($part) {
1889
+                $resultPath .= '/' . $part;
1890
+                $result[] = $resultPath;
1891
+            }
1892
+        }
1893
+        return $result;
1894
+    }
1895
+
1896
+    /**
1897
+     * Returns the mount point for which to lock
1898
+     *
1899
+     * @param string $absolutePath absolute path
1900
+     * @param bool $useParentMount true to return parent mount instead of whatever
1901
+     * is mounted directly on the given path, false otherwise
1902
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1903
+     */
1904
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1905
+        $results = [];
1906
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1907
+        if (!$mount) {
1908
+            return $results;
1909
+        }
1910
+
1911
+        if ($useParentMount) {
1912
+            // find out if something is mounted directly on the path
1913
+            $internalPath = $mount->getInternalPath($absolutePath);
1914
+            if ($internalPath === '') {
1915
+                // resolve the parent mount instead
1916
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1917
+            }
1918
+        }
1919
+
1920
+        return $mount;
1921
+    }
1922
+
1923
+    /**
1924
+     * Lock the given path
1925
+     *
1926
+     * @param string $path the path of the file to lock, relative to the view
1927
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1928
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1929
+     *
1930
+     * @return bool False if the path is excluded from locking, true otherwise
1931
+     * @throws LockedException if the path is already locked
1932
+     */
1933
+    private function lockPath($path, $type, $lockMountPoint = false) {
1934
+        $absolutePath = $this->getAbsolutePath($path);
1935
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1936
+        if (!$this->shouldLockFile($absolutePath)) {
1937
+            return false;
1938
+        }
1939
+
1940
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1941
+        if ($mount) {
1942
+            try {
1943
+                $storage = $mount->getStorage();
1944
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1945
+                    $storage->acquireLock(
1946
+                        $mount->getInternalPath($absolutePath),
1947
+                        $type,
1948
+                        $this->lockingProvider
1949
+                    );
1950
+                }
1951
+            } catch (LockedException $e) {
1952
+                // rethrow with the a human-readable path
1953
+                throw new LockedException(
1954
+                    $this->getPathRelativeToFiles($absolutePath),
1955
+                    $e,
1956
+                    $e->getExistingLock()
1957
+                );
1958
+            }
1959
+        }
1960
+
1961
+        return true;
1962
+    }
1963
+
1964
+    /**
1965
+     * Change the lock type
1966
+     *
1967
+     * @param string $path the path of the file to lock, relative to the view
1968
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1969
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1970
+     *
1971
+     * @return bool False if the path is excluded from locking, true otherwise
1972
+     * @throws LockedException if the path is already locked
1973
+     */
1974
+    public function changeLock($path, $type, $lockMountPoint = false) {
1975
+        $path = Filesystem::normalizePath($path);
1976
+        $absolutePath = $this->getAbsolutePath($path);
1977
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1978
+        if (!$this->shouldLockFile($absolutePath)) {
1979
+            return false;
1980
+        }
1981
+
1982
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1983
+        if ($mount) {
1984
+            try {
1985
+                $storage = $mount->getStorage();
1986
+                if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1987
+                    $storage->changeLock(
1988
+                        $mount->getInternalPath($absolutePath),
1989
+                        $type,
1990
+                        $this->lockingProvider
1991
+                    );
1992
+                }
1993
+            } catch (LockedException $e) {
1994
+                try {
1995
+                    // rethrow with the a human-readable path
1996
+                    throw new LockedException(
1997
+                        $this->getPathRelativeToFiles($absolutePath),
1998
+                        $e,
1999
+                        $e->getExistingLock()
2000
+                    );
2001
+                } catch (\InvalidArgumentException $ex) {
2002
+                    throw new LockedException(
2003
+                        $absolutePath,
2004
+                        $ex,
2005
+                        $e->getExistingLock()
2006
+                    );
2007
+                }
2008
+            }
2009
+        }
2010
+
2011
+        return true;
2012
+    }
2013
+
2014
+    /**
2015
+     * Unlock the given path
2016
+     *
2017
+     * @param string $path the path of the file to unlock, relative to the view
2018
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2019
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2020
+     *
2021
+     * @return bool False if the path is excluded from locking, true otherwise
2022
+     * @throws LockedException
2023
+     */
2024
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2025
+        $absolutePath = $this->getAbsolutePath($path);
2026
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2027
+        if (!$this->shouldLockFile($absolutePath)) {
2028
+            return false;
2029
+        }
2030
+
2031
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2032
+        if ($mount) {
2033
+            $storage = $mount->getStorage();
2034
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2035
+                $storage->releaseLock(
2036
+                    $mount->getInternalPath($absolutePath),
2037
+                    $type,
2038
+                    $this->lockingProvider
2039
+                );
2040
+            }
2041
+        }
2042
+
2043
+        return true;
2044
+    }
2045
+
2046
+    /**
2047
+     * Lock a path and all its parents up to the root of the view
2048
+     *
2049
+     * @param string $path the path of the file to lock relative to the view
2050
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
+     *
2053
+     * @return bool False if the path is excluded from locking, true otherwise
2054
+     * @throws LockedException
2055
+     */
2056
+    public function lockFile($path, $type, $lockMountPoint = false) {
2057
+        $absolutePath = $this->getAbsolutePath($path);
2058
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2059
+        if (!$this->shouldLockFile($absolutePath)) {
2060
+            return false;
2061
+        }
2062
+
2063
+        $this->lockPath($path, $type, $lockMountPoint);
2064
+
2065
+        $parents = $this->getParents($path);
2066
+        foreach ($parents as $parent) {
2067
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2068
+        }
2069
+
2070
+        return true;
2071
+    }
2072
+
2073
+    /**
2074
+     * Unlock a path and all its parents up to the root of the view
2075
+     *
2076
+     * @param string $path the path of the file to lock relative to the view
2077
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2078
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2079
+     *
2080
+     * @return bool False if the path is excluded from locking, true otherwise
2081
+     * @throws LockedException
2082
+     */
2083
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2084
+        $absolutePath = $this->getAbsolutePath($path);
2085
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2086
+        if (!$this->shouldLockFile($absolutePath)) {
2087
+            return false;
2088
+        }
2089
+
2090
+        $this->unlockPath($path, $type, $lockMountPoint);
2091
+
2092
+        $parents = $this->getParents($path);
2093
+        foreach ($parents as $parent) {
2094
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2095
+        }
2096
+
2097
+        return true;
2098
+    }
2099
+
2100
+    /**
2101
+     * Only lock files in data/user/files/
2102
+     *
2103
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2104
+     * @return bool
2105
+     */
2106
+    protected function shouldLockFile($path) {
2107
+        $path = Filesystem::normalizePath($path);
2108
+
2109
+        $pathSegments = explode('/', $path);
2110
+        if (isset($pathSegments[2])) {
2111
+            // E.g.: /username/files/path-to-file
2112
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2113
+        }
2114
+
2115
+        return strpos($path, '/appdata_') !== 0;
2116
+    }
2117
+
2118
+    /**
2119
+     * Shortens the given absolute path to be relative to
2120
+     * "$user/files".
2121
+     *
2122
+     * @param string $absolutePath absolute path which is under "files"
2123
+     *
2124
+     * @return string path relative to "files" with trimmed slashes or null
2125
+     * if the path was NOT relative to files
2126
+     *
2127
+     * @throws \InvalidArgumentException if the given path was not under "files"
2128
+     * @since 8.1.0
2129
+     */
2130
+    public function getPathRelativeToFiles($absolutePath) {
2131
+        $path = Filesystem::normalizePath($absolutePath);
2132
+        $parts = explode('/', trim($path, '/'), 3);
2133
+        // "$user", "files", "path/to/dir"
2134
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2135
+            $this->logger->error(
2136
+                '$absolutePath must be relative to "files", value is "%s"',
2137
+                [
2138
+                    $absolutePath
2139
+                ]
2140
+            );
2141
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2142
+        }
2143
+        if (isset($parts[2])) {
2144
+            return $parts[2];
2145
+        }
2146
+        return '';
2147
+    }
2148
+
2149
+    /**
2150
+     * @param string $filename
2151
+     * @return array
2152
+     * @throws \OC\User\NoUserException
2153
+     * @throws NotFoundException
2154
+     */
2155
+    public function getUidAndFilename($filename) {
2156
+        $info = $this->getFileInfo($filename);
2157
+        if (!$info instanceof \OCP\Files\FileInfo) {
2158
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2159
+        }
2160
+        $uid = $info->getOwner()->getUID();
2161
+        if ($uid != \OCP\User::getUser()) {
2162
+            Filesystem::initMountPoints($uid);
2163
+            $ownerView = new View('/' . $uid . '/files');
2164
+            try {
2165
+                $filename = $ownerView->getPath($info['fileid']);
2166
+            } catch (NotFoundException $e) {
2167
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2168
+            }
2169
+        }
2170
+        return [$uid, $filename];
2171
+    }
2172
+
2173
+    /**
2174
+     * Creates parent non-existing folders
2175
+     *
2176
+     * @param string $filePath
2177
+     * @return bool
2178
+     */
2179
+    private function createParentDirectories($filePath) {
2180
+        $directoryParts = explode('/', $filePath);
2181
+        $directoryParts = array_filter($directoryParts);
2182
+        foreach ($directoryParts as $key => $part) {
2183
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2184
+            $currentPath = '/' . implode('/', $currentPathElements);
2185
+            if ($this->is_file($currentPath)) {
2186
+                return false;
2187
+            }
2188
+            if (!$this->file_exists($currentPath)) {
2189
+                $this->mkdir($currentPath);
2190
+            }
2191
+        }
2192
+
2193
+        return true;
2194
+    }
2195 2195
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -129,9 +129,9 @@  discard block
 block discarded – undo
129 129
 			$path = '/';
130 130
 		}
131 131
 		if ($path[0] !== '/') {
132
-			$path = '/' . $path;
132
+			$path = '/'.$path;
133 133
 		}
134
-		return $this->fakeRoot . $path;
134
+		return $this->fakeRoot.$path;
135 135
 	}
136 136
 
137 137
 	/**
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	public function chroot($fakeRoot) {
144 144
 		if (!$fakeRoot == '') {
145 145
 			if ($fakeRoot[0] !== '/') {
146
-				$fakeRoot = '/' . $fakeRoot;
146
+				$fakeRoot = '/'.$fakeRoot;
147 147
 			}
148 148
 		}
149 149
 		$this->fakeRoot = $fakeRoot;
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 		}
176 176
 
177 177
 		// missing slashes can cause wrong matches!
178
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
+		$root = rtrim($this->fakeRoot, '/').'/';
179 179
 
180 180
 		if (strpos($path, $root) !== 0) {
181 181
 			return null;
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 		if ($mount instanceof MoveableMount) {
282 282
 			// cut of /user/files to get the relative path to data/user/files
283 283
 			$pathParts = explode('/', $path, 4);
284
-			$relPath = '/' . $pathParts[3];
284
+			$relPath = '/'.$pathParts[3];
285 285
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
286 286
 			\OC_Hook::emit(
287 287
 				Filesystem::CLASSNAME, "umount",
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 		}
708 708
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
709 709
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
710
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
710
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
711 711
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
712 712
 			return $this->removeMount($mount, $absolutePath);
713 713
 		}
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
 								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
830 830
 							}
831 831
 						}
832
-					} catch(\Exception $e) {
832
+					} catch (\Exception $e) {
833 833
 						throw $e;
834 834
 					} finally {
835 835
 						$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
@@ -853,7 +853,7 @@  discard block
 block discarded – undo
853 853
 						}
854 854
 					}
855 855
 				}
856
-			} catch(\Exception $e) {
856
+			} catch (\Exception $e) {
857 857
 				throw $e;
858 858
 			} finally {
859 859
 				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 				$hooks[] = 'write';
988 988
 				break;
989 989
 			default:
990
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, ILogger::ERROR);
990
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, ILogger::ERROR);
991 991
 		}
992 992
 
993 993
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
 					[Filesystem::signal_param_path => $this->getHookPath($path)]
1092 1092
 				);
1093 1093
 			}
1094
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1094
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1095 1095
 			if ($storage) {
1096 1096
 				return $storage->hash($type, $internalPath, $raw);
1097 1097
 			}
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 
1146 1146
 			$run = $this->runHooks($hooks, $path);
1147 1147
 			/** @var \OC\Files\Storage\Storage $storage */
1148
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1148
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1149 1149
 			if ($run and $storage) {
1150 1150
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1151 1151
 					try {
@@ -1174,7 +1174,7 @@  discard block
 block discarded – undo
1174 1174
 				if ($result && in_array('delete', $hooks) and $result) {
1175 1175
 					$this->removeUpdate($storage, $internalPath);
1176 1176
 				}
1177
-				if ($result && in_array('write', $hooks,  true) && $operation !== 'fopen' && $operation !== 'touch') {
1177
+				if ($result && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1178 1178
 					$this->writeUpdate($storage, $internalPath);
1179 1179
 				}
1180 1180
 				if ($result && in_array('touch', $hooks)) {
@@ -1190,7 +1190,7 @@  discard block
 block discarded – undo
1190 1190
 					$unlockLater = true;
1191 1191
 					// make sure our unlocking callback will still be called if connection is aborted
1192 1192
 					ignore_user_abort(true);
1193
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1193
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1194 1194
 						if (in_array('write', $hooks)) {
1195 1195
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1196 1196
 						} else if (in_array('read', $hooks)) {
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
 			return true;
1252 1252
 		}
1253 1253
 
1254
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1254
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1255 1255
 	}
1256 1256
 
1257 1257
 	/**
@@ -1270,7 +1270,7 @@  discard block
 block discarded – undo
1270 1270
 				if ($hook != 'read') {
1271 1271
 					\OC_Hook::emit(
1272 1272
 						Filesystem::CLASSNAME,
1273
-						$prefix . $hook,
1273
+						$prefix.$hook,
1274 1274
 						[
1275 1275
 							Filesystem::signal_param_run => &$run,
1276 1276
 							Filesystem::signal_param_path => $path
@@ -1279,7 +1279,7 @@  discard block
 block discarded – undo
1279 1279
 				} elseif (!$post) {
1280 1280
 					\OC_Hook::emit(
1281 1281
 						Filesystem::CLASSNAME,
1282
-						$prefix . $hook,
1282
+						$prefix.$hook,
1283 1283
 						[
1284 1284
 							Filesystem::signal_param_path => $path
1285 1285
 						]
@@ -1372,11 +1372,11 @@  discard block
 block discarded – undo
1372 1372
 			return $this->getPartFileInfo($path);
1373 1373
 		}
1374 1374
 		$relativePath = $path;
1375
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1375
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1376 1376
 
1377 1377
 		$mount = Filesystem::getMountManager()->find($path);
1378 1378
 		if (!$mount) {
1379
-			\OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
1379
+			\OC::$server->getLogger()->warning('Mountpoint not found for path: '.$path);
1380 1380
 			return false;
1381 1381
 		}
1382 1382
 		$storage = $mount->getStorage();
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
 					//add the sizes of other mount points to the folder
1405 1405
 					$extOnly = ($includeMountPoints === 'ext');
1406 1406
 					$mounts = Filesystem::getMountManager()->findIn($path);
1407
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1407
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1408 1408
 						$subStorage = $mount->getStorage();
1409 1409
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1410 1410
 					}));
@@ -1413,7 +1413,7 @@  discard block
 block discarded – undo
1413 1413
 
1414 1414
 			return $info;
1415 1415
 		} else {
1416
-			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
1416
+			\OC::$server->getLogger()->warning('Storage not valid for mountpoint: '.$mount->getMountPoint());
1417 1417
 		}
1418 1418
 
1419 1419
 		return false;
@@ -1454,18 +1454,18 @@  discard block
 block discarded – undo
1454 1454
 
1455 1455
 			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1456 1456
 
1457
-			$fileNames = array_map(function (ICacheEntry $content) {
1457
+			$fileNames = array_map(function(ICacheEntry $content) {
1458 1458
 				return $content->getName();
1459 1459
 			}, $contents);
1460 1460
 			/**
1461 1461
 			 * @var \OC\Files\FileInfo[] $fileInfos
1462 1462
 			 */
1463
-			$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1463
+			$fileInfos = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1464 1464
 				if ($sharingDisabled) {
1465 1465
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1466 1466
 				}
1467 1467
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1468
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1468
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1469 1469
 			}, $contents);
1470 1470
 			$files = array_combine($fileNames, $fileInfos);
1471 1471
 
@@ -1490,7 +1490,7 @@  discard block
 block discarded – undo
1490 1490
 						} catch (\Exception $e) {
1491 1491
 							// sometimes when the storage is not available it can be any exception
1492 1492
 							\OC::$server->getLogger()->logException($e, [
1493
-								'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
1493
+								'message' => 'Exception while scanning storage "'.$subStorage->getId().'"',
1494 1494
 								'level' => ILogger::ERROR,
1495 1495
 								'app' => 'lib',
1496 1496
 							]);
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
 								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1522 1522
 							}
1523 1523
 
1524
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1524
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1525 1525
 
1526 1526
 							// if sharing was disabled for the user we remove the share permissions
1527 1527
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1529,14 +1529,14 @@  discard block
 block discarded – undo
1529 1529
 							}
1530 1530
 
1531 1531
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1532
-							$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1532
+							$files[$rootEntry->getName()] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1533 1533
 						}
1534 1534
 					}
1535 1535
 				}
1536 1536
 			}
1537 1537
 
1538 1538
 			if ($mimetype_filter) {
1539
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1539
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1540 1540
 					if (strpos($mimetype_filter, '/')) {
1541 1541
 						return $file->getMimetype() === $mimetype_filter;
1542 1542
 					} else {
@@ -1565,7 +1565,7 @@  discard block
 block discarded – undo
1565 1565
 		if ($data instanceof FileInfo) {
1566 1566
 			$data = $data->getData();
1567 1567
 		}
1568
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1568
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1569 1569
 		/**
1570 1570
 		 * @var \OC\Files\Storage\Storage $storage
1571 1571
 		 * @var string $internalPath
@@ -1592,7 +1592,7 @@  discard block
 block discarded – undo
1592 1592
 	 * @return FileInfo[]
1593 1593
 	 */
1594 1594
 	public function search($query) {
1595
-		return $this->searchCommon('search', ['%' . $query . '%']);
1595
+		return $this->searchCommon('search', ['%'.$query.'%']);
1596 1596
 	}
1597 1597
 
1598 1598
 	/**
@@ -1643,10 +1643,10 @@  discard block
 block discarded – undo
1643 1643
 
1644 1644
 			$results = call_user_func_array([$cache, $method], $args);
1645 1645
 			foreach ($results as $result) {
1646
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1646
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1647 1647
 					$internalPath = $result['path'];
1648
-					$path = $mountPoint . $result['path'];
1649
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1648
+					$path = $mountPoint.$result['path'];
1649
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1650 1650
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1651 1651
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652 1652
 				}
@@ -1664,8 +1664,8 @@  discard block
 block discarded – undo
1664 1664
 					if ($results) {
1665 1665
 						foreach ($results as $result) {
1666 1666
 							$internalPath = $result['path'];
1667
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1668
-							$path = rtrim($mountPoint . $internalPath, '/');
1667
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1668
+							$path = rtrim($mountPoint.$internalPath, '/');
1669 1669
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1670 1670
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1671 1671
 						}
@@ -1686,11 +1686,11 @@  discard block
 block discarded – undo
1686 1686
 	public function getOwner($path) {
1687 1687
 		$info = $this->getFileInfo($path);
1688 1688
 		if (!$info) {
1689
-			throw new NotFoundException($path . ' not found while trying to get owner');
1689
+			throw new NotFoundException($path.' not found while trying to get owner');
1690 1690
 		}
1691 1691
 
1692 1692
 		if ($info->getOwner() === null) {
1693
-			throw new NotFoundException($path . ' has no owner');
1693
+			throw new NotFoundException($path.' has no owner');
1694 1694
 		}
1695 1695
 
1696 1696
 		return $info->getOwner()->getUID();
@@ -1725,7 +1725,7 @@  discard block
 block discarded – undo
1725 1725
 	 * @return string
1726 1726
 	 */
1727 1727
 	public function getPath($id) {
1728
-		$id = (int)$id;
1728
+		$id = (int) $id;
1729 1729
 		$manager = Filesystem::getMountManager();
1730 1730
 		$mounts = $manager->findIn($this->fakeRoot);
1731 1731
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1735,7 +1735,7 @@  discard block
 block discarded – undo
1735 1735
 
1736 1736
 		// put non shared mounts in front of the shared mount
1737 1737
 		// this prevent unneeded recursion into shares
1738
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1738
+		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1739 1739
 			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1740 1740
 		});
1741 1741
 
@@ -1747,7 +1747,7 @@  discard block
 block discarded – undo
1747 1747
 				$cache = $mount->getStorage()->getCache();
1748 1748
 				$internalPath = $cache->getPathById($id);
1749 1749
 				if (is_string($internalPath)) {
1750
-					$fullPath = $mount->getMountPoint() . $internalPath;
1750
+					$fullPath = $mount->getMountPoint().$internalPath;
1751 1751
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1752 1752
 						return $path;
1753 1753
 					}
@@ -1783,10 +1783,10 @@  discard block
 block discarded – undo
1783 1783
 	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath) {
1784 1784
 
1785 1785
 		// note: cannot use the view because the target is already locked
1786
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
1786
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
1787 1787
 		if ($fileId === -1) {
1788 1788
 			// target might not exist, need to check parent instead
1789
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
1789
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
1790 1790
 		}
1791 1791
 
1792 1792
 		// check if any of the parents were shared by the current owner (include collections)
@@ -1886,7 +1886,7 @@  discard block
 block discarded – undo
1886 1886
 		$resultPath = '';
1887 1887
 		foreach ($parts as $part) {
1888 1888
 			if ($part) {
1889
-				$resultPath .= '/' . $part;
1889
+				$resultPath .= '/'.$part;
1890 1890
 				$result[] = $resultPath;
1891 1891
 			}
1892 1892
 		}
@@ -2155,16 +2155,16 @@  discard block
 block discarded – undo
2155 2155
 	public function getUidAndFilename($filename) {
2156 2156
 		$info = $this->getFileInfo($filename);
2157 2157
 		if (!$info instanceof \OCP\Files\FileInfo) {
2158
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2158
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2159 2159
 		}
2160 2160
 		$uid = $info->getOwner()->getUID();
2161 2161
 		if ($uid != \OCP\User::getUser()) {
2162 2162
 			Filesystem::initMountPoints($uid);
2163
-			$ownerView = new View('/' . $uid . '/files');
2163
+			$ownerView = new View('/'.$uid.'/files');
2164 2164
 			try {
2165 2165
 				$filename = $ownerView->getPath($info['fileid']);
2166 2166
 			} catch (NotFoundException $e) {
2167
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2167
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2168 2168
 			}
2169 2169
 		}
2170 2170
 		return [$uid, $filename];
@@ -2181,7 +2181,7 @@  discard block
 block discarded – undo
2181 2181
 		$directoryParts = array_filter($directoryParts);
2182 2182
 		foreach ($directoryParts as $key => $part) {
2183 2183
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2184
-			$currentPath = '/' . implode('/', $currentPathElements);
2184
+			$currentPath = '/'.implode('/', $currentPathElements);
2185 2185
 			if ($this->is_file($currentPath)) {
2186 2186
 				return false;
2187 2187
 			}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Cache.php 2 patches
Indentation   +932 added lines, -932 removed lines patch added patch discarded remove patch
@@ -61,936 +61,936 @@
 block discarded – undo
61 61
  * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
62 62
  */
63 63
 class Cache implements ICache {
64
-	use MoveFromCacheTrait {
65
-		MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
66
-	}
67
-
68
-	/**
69
-	 * @var array partial data for the cache
70
-	 */
71
-	protected $partial = [];
72
-
73
-	/**
74
-	 * @var string
75
-	 */
76
-	protected $storageId;
77
-
78
-	private $storage;
79
-
80
-	/**
81
-	 * @var Storage $storageCache
82
-	 */
83
-	protected $storageCache;
84
-
85
-	/** @var IMimeTypeLoader */
86
-	protected $mimetypeLoader;
87
-
88
-	/**
89
-	 * @var IDBConnection
90
-	 */
91
-	protected $connection;
92
-
93
-	protected $eventDispatcher;
94
-
95
-	/** @var QuerySearchHelper */
96
-	protected $querySearchHelper;
97
-
98
-	/**
99
-	 * @param IStorage $storage
100
-	 */
101
-	public function __construct(IStorage $storage) {
102
-		$this->storageId = $storage->getId();
103
-		$this->storage = $storage;
104
-		if (strlen($this->storageId) > 64) {
105
-			$this->storageId = md5($this->storageId);
106
-		}
107
-
108
-		$this->storageCache = new Storage($storage);
109
-		$this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
110
-		$this->connection = \OC::$server->getDatabaseConnection();
111
-		$this->eventDispatcher = \OC::$server->getEventDispatcher();
112
-		$this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
113
-	}
114
-
115
-	private function getQueryBuilder() {
116
-		return new CacheQueryBuilder(
117
-			$this->connection,
118
-			\OC::$server->getSystemConfig(),
119
-			\OC::$server->getLogger(),
120
-			$this
121
-		);
122
-	}
123
-
124
-	/**
125
-	 * Get the numeric storage id for this cache's storage
126
-	 *
127
-	 * @return int
128
-	 */
129
-	public function getNumericStorageId() {
130
-		return $this->storageCache->getNumericId();
131
-	}
132
-
133
-	/**
134
-	 * get the stored metadata of a file or folder
135
-	 *
136
-	 * @param string | int $file either the path of a file or folder or the file id for a file or folder
137
-	 * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
138
-	 */
139
-	public function get($file) {
140
-		$query = $this->getQueryBuilder();
141
-		$query->selectFileCache();
142
-
143
-		if (is_string($file) or $file == '') {
144
-			// normalize file
145
-			$file = $this->normalize($file);
146
-
147
-			$query->whereStorageId()
148
-				->wherePath($file);
149
-		} else { //file id
150
-			$query->whereFileId($file);
151
-		}
152
-
153
-		$data = $query->execute()->fetch();
154
-
155
-		//merge partial data
156
-		if (!$data and is_string($file) and isset($this->partial[$file])) {
157
-			return $this->partial[$file];
158
-		} else if (!$data) {
159
-			return $data;
160
-		} else {
161
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * Create a CacheEntry from database row
167
-	 *
168
-	 * @param array $data
169
-	 * @param IMimeTypeLoader $mimetypeLoader
170
-	 * @return CacheEntry
171
-	 */
172
-	public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
173
-		//fix types
174
-		$data['fileid'] = (int)$data['fileid'];
175
-		$data['parent'] = (int)$data['parent'];
176
-		$data['size'] = 0 + $data['size'];
177
-		$data['mtime'] = (int)$data['mtime'];
178
-		$data['storage_mtime'] = (int)$data['storage_mtime'];
179
-		$data['encryptedVersion'] = (int)$data['encrypted'];
180
-		$data['encrypted'] = (bool)$data['encrypted'];
181
-		$data['storage_id'] = $data['storage'];
182
-		$data['storage'] = (int)$data['storage'];
183
-		$data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
184
-		$data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
185
-		if ($data['storage_mtime'] == 0) {
186
-			$data['storage_mtime'] = $data['mtime'];
187
-		}
188
-		$data['permissions'] = (int)$data['permissions'];
189
-		if (isset($data['creation_time'])) {
190
-			$data['creation_time'] = (int) $data['creation_time'];
191
-		}
192
-		if (isset($data['upload_time'])) {
193
-			$data['upload_time'] = (int) $data['upload_time'];
194
-		}
195
-		return new CacheEntry($data);
196
-	}
197
-
198
-	/**
199
-	 * get the metadata of all files stored in $folder
200
-	 *
201
-	 * @param string $folder
202
-	 * @return ICacheEntry[]
203
-	 */
204
-	public function getFolderContents($folder) {
205
-		$fileId = $this->getId($folder);
206
-		return $this->getFolderContentsById($fileId);
207
-	}
208
-
209
-	/**
210
-	 * get the metadata of all files stored in $folder
211
-	 *
212
-	 * @param int $fileId the file id of the folder
213
-	 * @return ICacheEntry[]
214
-	 */
215
-	public function getFolderContentsById($fileId) {
216
-		if ($fileId > -1) {
217
-			$query = $this->getQueryBuilder();
218
-			$query->selectFileCache()
219
-				->whereParent($fileId)
220
-				->orderBy('name', 'ASC');
221
-
222
-			$files = $query->execute()->fetchAll();
223
-			return array_map(function (array $data) {
224
-				return self::cacheEntryFromData($data, $this->mimetypeLoader);
225
-			}, $files);
226
-		}
227
-		return [];
228
-	}
229
-
230
-	/**
231
-	 * insert or update meta data for a file or folder
232
-	 *
233
-	 * @param string $file
234
-	 * @param array $data
235
-	 *
236
-	 * @return int file id
237
-	 * @throws \RuntimeException
238
-	 */
239
-	public function put($file, array $data) {
240
-		if (($id = $this->getId($file)) > -1) {
241
-			$this->update($id, $data);
242
-			return $id;
243
-		} else {
244
-			return $this->insert($file, $data);
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * insert meta data for a new file or folder
250
-	 *
251
-	 * @param string $file
252
-	 * @param array $data
253
-	 *
254
-	 * @return int file id
255
-	 * @throws \RuntimeException
256
-	 *
257
-	 * @suppress SqlInjectionChecker
258
-	 */
259
-	public function insert($file, array $data) {
260
-		// normalize file
261
-		$file = $this->normalize($file);
262
-
263
-		if (isset($this->partial[$file])) { //add any saved partial data
264
-			$data = array_merge($this->partial[$file], $data);
265
-			unset($this->partial[$file]);
266
-		}
267
-
268
-		$requiredFields = ['size', 'mtime', 'mimetype'];
269
-		foreach ($requiredFields as $field) {
270
-			if (!isset($data[$field])) { //data not complete save as partial and return
271
-				$this->partial[$file] = $data;
272
-				return -1;
273
-			}
274
-		}
275
-
276
-		$data['path'] = $file;
277
-		if (!isset($data['parent'])) {
278
-			$data['parent'] = $this->getParentId($file);
279
-		}
280
-		$data['name'] = basename($file);
281
-
282
-		[$values, $extensionValues] = $this->normalizeData($data);
283
-		$values['storage'] = $this->getNumericStorageId();
284
-
285
-		try {
286
-			$builder = $this->connection->getQueryBuilder();
287
-			$builder->insert('filecache');
288
-
289
-			foreach ($values as $column => $value) {
290
-				$builder->setValue($column, $builder->createNamedParameter($value));
291
-			}
292
-
293
-			if ($builder->execute()) {
294
-				$fileId = $builder->getLastInsertId();
295
-
296
-				if (count($extensionValues)) {
297
-					$query = $this->getQueryBuilder();
298
-					$query->insert('filecache_extended');
299
-
300
-					$query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
301
-					foreach ($extensionValues as $column => $value) {
302
-						$query->setValue($column, $query->createNamedParameter($value));
303
-					}
304
-					$query->execute();
305
-				}
306
-
307
-				$this->eventDispatcher->dispatch(CacheInsertEvent::class, new CacheInsertEvent($this->storage, $file, $fileId));
308
-				return $fileId;
309
-			}
310
-		} catch (UniqueConstraintViolationException $e) {
311
-			// entry exists already
312
-			if ($this->connection->inTransaction()) {
313
-				$this->connection->commit();
314
-				$this->connection->beginTransaction();
315
-			}
316
-		}
317
-
318
-		// The file was created in the mean time
319
-		if (($id = $this->getId($file)) > -1) {
320
-			$this->update($id, $data);
321
-			return $id;
322
-		} else {
323
-			throw new \RuntimeException('File entry could not be inserted but could also not be selected with getId() in order to perform an update. Please try again.');
324
-		}
325
-	}
326
-
327
-	/**
328
-	 * update the metadata of an existing file or folder in the cache
329
-	 *
330
-	 * @param int $id the fileid of the existing file or folder
331
-	 * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged
332
-	 */
333
-	public function update($id, array $data) {
334
-
335
-		if (isset($data['path'])) {
336
-			// normalize path
337
-			$data['path'] = $this->normalize($data['path']);
338
-		}
339
-
340
-		if (isset($data['name'])) {
341
-			// normalize path
342
-			$data['name'] = $this->normalize($data['name']);
343
-		}
344
-
345
-		[$values, $extensionValues] = $this->normalizeData($data);
346
-
347
-		if (count($values)) {
348
-			$query = $this->getQueryBuilder();
349
-
350
-			$query->update('filecache')
351
-				->whereFileId($id)
352
-				->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
353
-					return $query->expr()->orX(
354
-						$query->expr()->neq($key, $query->createNamedParameter($value)),
355
-						$query->expr()->isNull($key)
356
-					);
357
-				}, array_keys($values), array_values($values))));
358
-
359
-			foreach ($values as $key => $value) {
360
-				$query->set($key, $query->createNamedParameter($value));
361
-			}
362
-
363
-			$query->execute();
364
-		}
365
-
366
-		if (count($extensionValues)) {
367
-			try {
368
-				$query = $this->getQueryBuilder();
369
-				$query->insert('filecache_extended');
370
-
371
-				$query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
372
-				foreach ($extensionValues as $column => $value) {
373
-					$query->setValue($column, $query->createNamedParameter($value));
374
-				}
375
-
376
-				$query->execute();
377
-			} catch (UniqueConstraintViolationException $e) {
378
-				$query = $this->getQueryBuilder();
379
-				$query->update('filecache_extended')
380
-					->whereFileId($id)
381
-					->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
382
-						return $query->expr()->orX(
383
-							$query->expr()->neq($key, $query->createNamedParameter($value)),
384
-							$query->expr()->isNull($key)
385
-						);
386
-					}, array_keys($extensionValues), array_values($extensionValues))));
387
-
388
-				foreach ($extensionValues as $key => $value) {
389
-					$query->set($key, $query->createNamedParameter($value));
390
-				}
391
-
392
-				$query->execute();
393
-			}
394
-		}
395
-
396
-		$path = $this->getPathById($id);
397
-		// path can still be null if the file doesn't exist
398
-		if ($path !== null) {
399
-			$this->eventDispatcher->dispatch(CacheUpdateEvent::class, new CacheUpdateEvent($this->storage, $path, $id));
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * extract query parts and params array from data array
405
-	 *
406
-	 * @param array $data
407
-	 * @return array
408
-	 */
409
-	protected function normalizeData(array $data): array {
410
-		$fields = [
411
-			'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
412
-			'etag', 'permissions', 'checksum', 'storage'];
413
-		$extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
414
-
415
-		$doNotCopyStorageMTime = false;
416
-		if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
417
-			// this horrific magic tells it to not copy storage_mtime to mtime
418
-			unset($data['mtime']);
419
-			$doNotCopyStorageMTime = true;
420
-		}
421
-
422
-		$params = [];
423
-		$extensionParams = [];
424
-		foreach ($data as $name => $value) {
425
-			if (array_search($name, $fields) !== false) {
426
-				if ($name === 'path') {
427
-					$params['path_hash'] = md5($value);
428
-				} else if ($name === 'mimetype') {
429
-					$params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
430
-					$value = $this->mimetypeLoader->getId($value);
431
-				} else if ($name === 'storage_mtime') {
432
-					if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
433
-						$params['mtime'] = $value;
434
-					}
435
-				} else if ($name === 'encrypted') {
436
-					if (isset($data['encryptedVersion'])) {
437
-						$value = $data['encryptedVersion'];
438
-					} else {
439
-						// Boolean to integer conversion
440
-						$value = $value ? 1 : 0;
441
-					}
442
-				}
443
-				$params[$name] = $value;
444
-			}
445
-			if (array_search($name, $extensionFields) !== false) {
446
-				$extensionParams[$name] = $value;
447
-			}
448
-		}
449
-		return [$params, array_filter($extensionParams)];
450
-	}
451
-
452
-	/**
453
-	 * get the file id for a file
454
-	 *
455
-	 * A file id is a numeric id for a file or folder that's unique within an owncloud instance which stays the same for the lifetime of a file
456
-	 *
457
-	 * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
458
-	 *
459
-	 * @param string $file
460
-	 * @return int
461
-	 */
462
-	public function getId($file) {
463
-		// normalize file
464
-		$file = $this->normalize($file);
465
-
466
-		$query = $this->getQueryBuilder();
467
-		$query->select('fileid')
468
-			->from('filecache')
469
-			->whereStorageId()
470
-			->wherePath($file);
471
-
472
-		$id = $query->execute()->fetchColumn();
473
-		return $id === false ? -1 : (int)$id;
474
-	}
475
-
476
-	/**
477
-	 * get the id of the parent folder of a file
478
-	 *
479
-	 * @param string $file
480
-	 * @return int
481
-	 */
482
-	public function getParentId($file) {
483
-		if ($file === '') {
484
-			return -1;
485
-		} else {
486
-			$parent = $this->getParentPath($file);
487
-			return (int)$this->getId($parent);
488
-		}
489
-	}
490
-
491
-	private function getParentPath($path) {
492
-		$parent = dirname($path);
493
-		if ($parent === '.') {
494
-			$parent = '';
495
-		}
496
-		return $parent;
497
-	}
498
-
499
-	/**
500
-	 * check if a file is available in the cache
501
-	 *
502
-	 * @param string $file
503
-	 * @return bool
504
-	 */
505
-	public function inCache($file) {
506
-		return $this->getId($file) != -1;
507
-	}
508
-
509
-	/**
510
-	 * remove a file or folder from the cache
511
-	 *
512
-	 * when removing a folder from the cache all files and folders inside the folder will be removed as well
513
-	 *
514
-	 * @param string $file
515
-	 */
516
-	public function remove($file) {
517
-		$entry = $this->get($file);
518
-
519
-		if ($entry) {
520
-			$query = $this->getQueryBuilder();
521
-			$query->delete('filecache')
522
-				->whereFileId($entry->getId());
523
-			$query->execute();
524
-
525
-			$query = $this->getQueryBuilder();
526
-			$query->delete('filecache_extended')
527
-				->whereFileId($entry->getId());
528
-			$query->execute();
529
-
530
-			if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
531
-				$this->removeChildren($entry);
532
-			}
533
-		}
534
-	}
535
-
536
-	/**
537
-	 * Get all sub folders of a folder
538
-	 *
539
-	 * @param ICacheEntry $entry the cache entry of the folder to get the subfolders for
540
-	 * @return ICacheEntry[] the cache entries for the subfolders
541
-	 */
542
-	private function getSubFolders(ICacheEntry $entry) {
543
-		$children = $this->getFolderContentsById($entry->getId());
544
-		return array_filter($children, function ($child) {
545
-			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
546
-		});
547
-	}
548
-
549
-	/**
550
-	 * Recursively remove all children of a folder
551
-	 *
552
-	 * @param ICacheEntry $entry the cache entry of the folder to remove the children of
553
-	 * @throws \OC\DatabaseException
554
-	 */
555
-	private function removeChildren(ICacheEntry $entry) {
556
-		$children = $this->getFolderContentsById($entry->getId());
557
-		$childIds = array_map(function (ICacheEntry $cacheEntry) {
558
-			return $cacheEntry->getId();
559
-		}, $children);
560
-		$childFolders = array_filter($children, function ($child) {
561
-			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
562
-		});
563
-		foreach ($childFolders as $folder) {
564
-			$this->removeChildren($folder);
565
-		}
566
-
567
-		$query = $this->getQueryBuilder();
568
-		$query->delete('filecache')
569
-			->whereParent($entry->getId());
570
-		$query->execute();
571
-
572
-		$query = $this->getQueryBuilder();
573
-		$query->delete('filecache_extended')
574
-			->where($query->expr()->in('fileid', $query->createNamedParameter($childIds, IQueryBuilder::PARAM_INT_ARRAY)));
575
-		$query->execute();
576
-	}
577
-
578
-	/**
579
-	 * Move a file or folder in the cache
580
-	 *
581
-	 * @param string $source
582
-	 * @param string $target
583
-	 */
584
-	public function move($source, $target) {
585
-		$this->moveFromCache($this, $source, $target);
586
-	}
587
-
588
-	/**
589
-	 * Get the storage id and path needed for a move
590
-	 *
591
-	 * @param string $path
592
-	 * @return array [$storageId, $internalPath]
593
-	 */
594
-	protected function getMoveInfo($path) {
595
-		return [$this->getNumericStorageId(), $path];
596
-	}
597
-
598
-	/**
599
-	 * Move a file or folder in the cache
600
-	 *
601
-	 * @param \OCP\Files\Cache\ICache $sourceCache
602
-	 * @param string $sourcePath
603
-	 * @param string $targetPath
604
-	 * @throws \OC\DatabaseException
605
-	 * @throws \Exception if the given storages have an invalid id
606
-	 * @suppress SqlInjectionChecker
607
-	 */
608
-	public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
609
-		if ($sourceCache instanceof Cache) {
610
-			// normalize source and target
611
-			$sourcePath = $this->normalize($sourcePath);
612
-			$targetPath = $this->normalize($targetPath);
613
-
614
-			$sourceData = $sourceCache->get($sourcePath);
615
-			$sourceId = $sourceData['fileid'];
616
-			$newParentId = $this->getParentId($targetPath);
617
-
618
-			[$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
619
-			[$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
620
-
621
-			if (is_null($sourceStorageId) || $sourceStorageId === false) {
622
-				throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
623
-			}
624
-			if (is_null($targetStorageId) || $targetStorageId === false) {
625
-				throw new \Exception('Invalid target storage id: ' . $targetStorageId);
626
-			}
627
-
628
-			$this->connection->beginTransaction();
629
-			if ($sourceData['mimetype'] === 'httpd/unix-directory') {
630
-				//update all child entries
631
-				$sourceLength = mb_strlen($sourcePath);
632
-				$query = $this->connection->getQueryBuilder();
633
-
634
-				$fun = $query->func();
635
-				$newPathFunction = $fun->concat(
636
-					$query->createNamedParameter($targetPath),
637
-					$fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
638
-				);
639
-				$query->update('filecache')
640
-					->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
641
-					->set('path_hash', $fun->md5($newPathFunction))
642
-					->set('path', $newPathFunction)
643
-					->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
644
-					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
645
-
646
-				try {
647
-					$query->execute();
648
-				} catch (\OC\DatabaseException $e) {
649
-					$this->connection->rollBack();
650
-					throw $e;
651
-				}
652
-			}
653
-
654
-			$query = $this->getQueryBuilder();
655
-			$query->update('filecache')
656
-				->set('storage', $query->createNamedParameter($targetStorageId))
657
-				->set('path', $query->createNamedParameter($targetPath))
658
-				->set('path_hash', $query->createNamedParameter(md5($targetPath)))
659
-				->set('name', $query->createNamedParameter(basename($targetPath)))
660
-				->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
661
-				->whereFileId($sourceId);
662
-			$query->execute();
663
-
664
-			$this->connection->commit();
665
-		} else {
666
-			$this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
667
-		}
668
-	}
669
-
670
-	/**
671
-	 * remove all entries for files that are stored on the storage from the cache
672
-	 */
673
-	public function clear() {
674
-		$query = $this->getQueryBuilder();
675
-		$query->delete('filecache')
676
-			->whereStorageId();
677
-		$query->execute();
678
-
679
-		$query = $this->connection->getQueryBuilder();
680
-		$query->delete('storages')
681
-			->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
682
-		$query->execute();
683
-	}
684
-
685
-	/**
686
-	 * Get the scan status of a file
687
-	 *
688
-	 * - Cache::NOT_FOUND: File is not in the cache
689
-	 * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
690
-	 * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
691
-	 * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
692
-	 *
693
-	 * @param string $file
694
-	 *
695
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
696
-	 */
697
-	public function getStatus($file) {
698
-		// normalize file
699
-		$file = $this->normalize($file);
700
-
701
-		$query = $this->getQueryBuilder();
702
-		$query->select('size')
703
-			->from('filecache')
704
-			->whereStorageId()
705
-			->wherePath($file);
706
-		$size = $query->execute()->fetchColumn();
707
-		if ($size !== false) {
708
-			if ((int)$size === -1) {
709
-				return self::SHALLOW;
710
-			} else {
711
-				return self::COMPLETE;
712
-			}
713
-		} else {
714
-			if (isset($this->partial[$file])) {
715
-				return self::PARTIAL;
716
-			} else {
717
-				return self::NOT_FOUND;
718
-			}
719
-		}
720
-	}
721
-
722
-	/**
723
-	 * search for files matching $pattern
724
-	 *
725
-	 * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
726
-	 * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
727
-	 */
728
-	public function search($pattern) {
729
-		// normalize pattern
730
-		$pattern = $this->normalize($pattern);
731
-
732
-		if ($pattern === '%%') {
733
-			return [];
734
-		}
735
-
736
-		$query = $this->getQueryBuilder();
737
-		$query->selectFileCache()
738
-			->whereStorageId()
739
-			->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
740
-
741
-		return array_map(function (array $data) {
742
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
743
-		}, $query->execute()->fetchAll());
744
-	}
745
-
746
-	/**
747
-	 * @param Statement $result
748
-	 * @return CacheEntry[]
749
-	 */
750
-	private function searchResultToCacheEntries(Statement $result) {
751
-		$files = $result->fetchAll();
752
-
753
-		return array_map(function (array $data) {
754
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
755
-		}, $files);
756
-	}
757
-
758
-	/**
759
-	 * search for files by mimetype
760
-	 *
761
-	 * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
762
-	 *        where it will search for all mimetypes in the group ('image/*')
763
-	 * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
764
-	 */
765
-	public function searchByMime($mimetype) {
766
-		$mimeId = $this->mimetypeLoader->getId($mimetype);
767
-
768
-		$query = $this->getQueryBuilder();
769
-		$query->selectFileCache()
770
-			->whereStorageId();
771
-
772
-		if (strpos($mimetype, '/')) {
773
-			$query->andWhere($query->expr()->eq('mimetype', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
774
-		} else {
775
-			$query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
776
-		}
777
-
778
-		return array_map(function (array $data) {
779
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
780
-		}, $query->execute()->fetchAll());
781
-	}
782
-
783
-	public function searchQuery(ISearchQuery $searchQuery) {
784
-		$builder = $this->getQueryBuilder();
785
-
786
-		$query = $builder->selectFileCache('file');
787
-
788
-		$query->whereStorageId();
789
-
790
-		if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
791
-			$query
792
-				->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
793
-				->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
794
-					$builder->expr()->eq('tagmap.type', 'tag.type'),
795
-					$builder->expr()->eq('tagmap.categoryid', 'tag.id')
796
-				))
797
-				->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
798
-				->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($searchQuery->getUser()->getUID())));
799
-		}
800
-
801
-		$searchExpr = $this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation());
802
-		if ($searchExpr) {
803
-			$query->andWhere($searchExpr);
804
-		}
805
-
806
-		if ($searchQuery->limitToHome() && ($this instanceof HomeCache)) {
807
-			$query->andWhere($builder->expr()->like('path', $query->expr()->literal('files/%')));
808
-		}
809
-
810
-		$this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
811
-
812
-		if ($searchQuery->getLimit()) {
813
-			$query->setMaxResults($searchQuery->getLimit());
814
-		}
815
-		if ($searchQuery->getOffset()) {
816
-			$query->setFirstResult($searchQuery->getOffset());
817
-		}
818
-
819
-		$result = $query->execute();
820
-		return $this->searchResultToCacheEntries($result);
821
-	}
822
-
823
-	/**
824
-	 * Re-calculate the folder size and the size of all parent folders
825
-	 *
826
-	 * @param string|boolean $path
827
-	 * @param array $data (optional) meta data of the folder
828
-	 */
829
-	public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
830
-		$this->calculateFolderSize($path, $data);
831
-		if ($path !== '') {
832
-			$parent = dirname($path);
833
-			if ($parent === '.' or $parent === '/') {
834
-				$parent = '';
835
-			}
836
-			if ($isBackgroundScan) {
837
-				$parentData = $this->get($parent);
838
-				if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
839
-					$this->correctFolderSize($parent, $parentData, $isBackgroundScan);
840
-				}
841
-			} else {
842
-				$this->correctFolderSize($parent);
843
-			}
844
-		}
845
-	}
846
-
847
-	/**
848
-	 * get the incomplete count that shares parent $folder
849
-	 *
850
-	 * @param int $fileId the file id of the folder
851
-	 * @return int
852
-	 */
853
-	public function getIncompleteChildrenCount($fileId) {
854
-		if ($fileId > -1) {
855
-			$query = $this->getQueryBuilder();
856
-			$query->select($query->func()->count())
857
-				->from('filecache')
858
-				->whereParent($fileId)
859
-				->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
860
-
861
-			return (int)$query->execute()->fetchColumn();
862
-		}
863
-		return -1;
864
-	}
865
-
866
-	/**
867
-	 * calculate the size of a folder and set it in the cache
868
-	 *
869
-	 * @param string $path
870
-	 * @param array $entry (optional) meta data of the folder
871
-	 * @return int
872
-	 */
873
-	public function calculateFolderSize($path, $entry = null) {
874
-		$totalSize = 0;
875
-		if (is_null($entry) or !isset($entry['fileid'])) {
876
-			$entry = $this->get($path);
877
-		}
878
-		if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
879
-			$id = $entry['fileid'];
880
-
881
-			$query = $this->getQueryBuilder();
882
-			$query->selectAlias($query->func()->sum('size'), 'f1')
883
-				->selectAlias($query->func()->min('size'), 'f2')
884
-				->from('filecache')
885
-				->whereStorageId()
886
-				->whereParent($id);
887
-
888
-			if ($row = $query->execute()->fetch()) {
889
-				[$sum, $min] = array_values($row);
890
-				$sum = 0 + $sum;
891
-				$min = 0 + $min;
892
-				if ($min === -1) {
893
-					$totalSize = $min;
894
-				} else {
895
-					$totalSize = $sum;
896
-				}
897
-				if ($entry['size'] !== $totalSize) {
898
-					$this->update($id, ['size' => $totalSize]);
899
-				}
900
-			}
901
-		}
902
-		return $totalSize;
903
-	}
904
-
905
-	/**
906
-	 * get all file ids on the files on the storage
907
-	 *
908
-	 * @return int[]
909
-	 */
910
-	public function getAll() {
911
-		$query = $this->getQueryBuilder();
912
-		$query->select('fileid')
913
-			->from('filecache')
914
-			->whereStorageId();
915
-
916
-		return array_map(function ($id) {
917
-			return (int)$id;
918
-		}, $query->execute()->fetchAll(\PDO::FETCH_COLUMN));
919
-	}
920
-
921
-	/**
922
-	 * find a folder in the cache which has not been fully scanned
923
-	 *
924
-	 * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
925
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
926
-	 * likely the folder where we stopped scanning previously
927
-	 *
928
-	 * @return string|bool the path of the folder or false when no folder matched
929
-	 */
930
-	public function getIncomplete() {
931
-		$query = $this->getQueryBuilder();
932
-		$query->select('path')
933
-			->from('filecache')
934
-			->whereStorageId()
935
-			->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
936
-			->orderBy('fileid', 'DESC');
937
-
938
-		return $query->execute()->fetchColumn();
939
-	}
940
-
941
-	/**
942
-	 * get the path of a file on this storage by it's file id
943
-	 *
944
-	 * @param int $id the file id of the file or folder to search
945
-	 * @return string|null the path of the file (relative to the storage) or null if a file with the given id does not exists within this cache
946
-	 */
947
-	public function getPathById($id) {
948
-		$query = $this->getQueryBuilder();
949
-		$query->select('path')
950
-			->from('filecache')
951
-			->whereStorageId()
952
-			->whereFileId($id);
953
-
954
-		$path = $query->execute()->fetchColumn();
955
-		return $path === false ? null : $path;
956
-	}
957
-
958
-	/**
959
-	 * get the storage id of the storage for a file and the internal path of the file
960
-	 * unlike getPathById this does not limit the search to files on this storage and
961
-	 * instead does a global search in the cache table
962
-	 *
963
-	 * @param int $id
964
-	 * @return array first element holding the storage id, second the path
965
-	 * @deprecated use getPathById() instead
966
-	 */
967
-	static public function getById($id) {
968
-		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
969
-		$query->select('path', 'storage')
970
-			->from('filecache')
971
-			->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
972
-		if ($row = $query->execute()->fetch()) {
973
-			$numericId = $row['storage'];
974
-			$path = $row['path'];
975
-		} else {
976
-			return null;
977
-		}
978
-
979
-		if ($id = Storage::getStorageId($numericId)) {
980
-			return [$id, $path];
981
-		} else {
982
-			return null;
983
-		}
984
-	}
985
-
986
-	/**
987
-	 * normalize the given path
988
-	 *
989
-	 * @param string $path
990
-	 * @return string
991
-	 */
992
-	public function normalize($path) {
993
-
994
-		return trim(\OC_Util::normalizeUnicode($path), '/');
995
-	}
64
+    use MoveFromCacheTrait {
65
+        MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
66
+    }
67
+
68
+    /**
69
+     * @var array partial data for the cache
70
+     */
71
+    protected $partial = [];
72
+
73
+    /**
74
+     * @var string
75
+     */
76
+    protected $storageId;
77
+
78
+    private $storage;
79
+
80
+    /**
81
+     * @var Storage $storageCache
82
+     */
83
+    protected $storageCache;
84
+
85
+    /** @var IMimeTypeLoader */
86
+    protected $mimetypeLoader;
87
+
88
+    /**
89
+     * @var IDBConnection
90
+     */
91
+    protected $connection;
92
+
93
+    protected $eventDispatcher;
94
+
95
+    /** @var QuerySearchHelper */
96
+    protected $querySearchHelper;
97
+
98
+    /**
99
+     * @param IStorage $storage
100
+     */
101
+    public function __construct(IStorage $storage) {
102
+        $this->storageId = $storage->getId();
103
+        $this->storage = $storage;
104
+        if (strlen($this->storageId) > 64) {
105
+            $this->storageId = md5($this->storageId);
106
+        }
107
+
108
+        $this->storageCache = new Storage($storage);
109
+        $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
110
+        $this->connection = \OC::$server->getDatabaseConnection();
111
+        $this->eventDispatcher = \OC::$server->getEventDispatcher();
112
+        $this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
113
+    }
114
+
115
+    private function getQueryBuilder() {
116
+        return new CacheQueryBuilder(
117
+            $this->connection,
118
+            \OC::$server->getSystemConfig(),
119
+            \OC::$server->getLogger(),
120
+            $this
121
+        );
122
+    }
123
+
124
+    /**
125
+     * Get the numeric storage id for this cache's storage
126
+     *
127
+     * @return int
128
+     */
129
+    public function getNumericStorageId() {
130
+        return $this->storageCache->getNumericId();
131
+    }
132
+
133
+    /**
134
+     * get the stored metadata of a file or folder
135
+     *
136
+     * @param string | int $file either the path of a file or folder or the file id for a file or folder
137
+     * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
138
+     */
139
+    public function get($file) {
140
+        $query = $this->getQueryBuilder();
141
+        $query->selectFileCache();
142
+
143
+        if (is_string($file) or $file == '') {
144
+            // normalize file
145
+            $file = $this->normalize($file);
146
+
147
+            $query->whereStorageId()
148
+                ->wherePath($file);
149
+        } else { //file id
150
+            $query->whereFileId($file);
151
+        }
152
+
153
+        $data = $query->execute()->fetch();
154
+
155
+        //merge partial data
156
+        if (!$data and is_string($file) and isset($this->partial[$file])) {
157
+            return $this->partial[$file];
158
+        } else if (!$data) {
159
+            return $data;
160
+        } else {
161
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
162
+        }
163
+    }
164
+
165
+    /**
166
+     * Create a CacheEntry from database row
167
+     *
168
+     * @param array $data
169
+     * @param IMimeTypeLoader $mimetypeLoader
170
+     * @return CacheEntry
171
+     */
172
+    public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
173
+        //fix types
174
+        $data['fileid'] = (int)$data['fileid'];
175
+        $data['parent'] = (int)$data['parent'];
176
+        $data['size'] = 0 + $data['size'];
177
+        $data['mtime'] = (int)$data['mtime'];
178
+        $data['storage_mtime'] = (int)$data['storage_mtime'];
179
+        $data['encryptedVersion'] = (int)$data['encrypted'];
180
+        $data['encrypted'] = (bool)$data['encrypted'];
181
+        $data['storage_id'] = $data['storage'];
182
+        $data['storage'] = (int)$data['storage'];
183
+        $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
184
+        $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
185
+        if ($data['storage_mtime'] == 0) {
186
+            $data['storage_mtime'] = $data['mtime'];
187
+        }
188
+        $data['permissions'] = (int)$data['permissions'];
189
+        if (isset($data['creation_time'])) {
190
+            $data['creation_time'] = (int) $data['creation_time'];
191
+        }
192
+        if (isset($data['upload_time'])) {
193
+            $data['upload_time'] = (int) $data['upload_time'];
194
+        }
195
+        return new CacheEntry($data);
196
+    }
197
+
198
+    /**
199
+     * get the metadata of all files stored in $folder
200
+     *
201
+     * @param string $folder
202
+     * @return ICacheEntry[]
203
+     */
204
+    public function getFolderContents($folder) {
205
+        $fileId = $this->getId($folder);
206
+        return $this->getFolderContentsById($fileId);
207
+    }
208
+
209
+    /**
210
+     * get the metadata of all files stored in $folder
211
+     *
212
+     * @param int $fileId the file id of the folder
213
+     * @return ICacheEntry[]
214
+     */
215
+    public function getFolderContentsById($fileId) {
216
+        if ($fileId > -1) {
217
+            $query = $this->getQueryBuilder();
218
+            $query->selectFileCache()
219
+                ->whereParent($fileId)
220
+                ->orderBy('name', 'ASC');
221
+
222
+            $files = $query->execute()->fetchAll();
223
+            return array_map(function (array $data) {
224
+                return self::cacheEntryFromData($data, $this->mimetypeLoader);
225
+            }, $files);
226
+        }
227
+        return [];
228
+    }
229
+
230
+    /**
231
+     * insert or update meta data for a file or folder
232
+     *
233
+     * @param string $file
234
+     * @param array $data
235
+     *
236
+     * @return int file id
237
+     * @throws \RuntimeException
238
+     */
239
+    public function put($file, array $data) {
240
+        if (($id = $this->getId($file)) > -1) {
241
+            $this->update($id, $data);
242
+            return $id;
243
+        } else {
244
+            return $this->insert($file, $data);
245
+        }
246
+    }
247
+
248
+    /**
249
+     * insert meta data for a new file or folder
250
+     *
251
+     * @param string $file
252
+     * @param array $data
253
+     *
254
+     * @return int file id
255
+     * @throws \RuntimeException
256
+     *
257
+     * @suppress SqlInjectionChecker
258
+     */
259
+    public function insert($file, array $data) {
260
+        // normalize file
261
+        $file = $this->normalize($file);
262
+
263
+        if (isset($this->partial[$file])) { //add any saved partial data
264
+            $data = array_merge($this->partial[$file], $data);
265
+            unset($this->partial[$file]);
266
+        }
267
+
268
+        $requiredFields = ['size', 'mtime', 'mimetype'];
269
+        foreach ($requiredFields as $field) {
270
+            if (!isset($data[$field])) { //data not complete save as partial and return
271
+                $this->partial[$file] = $data;
272
+                return -1;
273
+            }
274
+        }
275
+
276
+        $data['path'] = $file;
277
+        if (!isset($data['parent'])) {
278
+            $data['parent'] = $this->getParentId($file);
279
+        }
280
+        $data['name'] = basename($file);
281
+
282
+        [$values, $extensionValues] = $this->normalizeData($data);
283
+        $values['storage'] = $this->getNumericStorageId();
284
+
285
+        try {
286
+            $builder = $this->connection->getQueryBuilder();
287
+            $builder->insert('filecache');
288
+
289
+            foreach ($values as $column => $value) {
290
+                $builder->setValue($column, $builder->createNamedParameter($value));
291
+            }
292
+
293
+            if ($builder->execute()) {
294
+                $fileId = $builder->getLastInsertId();
295
+
296
+                if (count($extensionValues)) {
297
+                    $query = $this->getQueryBuilder();
298
+                    $query->insert('filecache_extended');
299
+
300
+                    $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
301
+                    foreach ($extensionValues as $column => $value) {
302
+                        $query->setValue($column, $query->createNamedParameter($value));
303
+                    }
304
+                    $query->execute();
305
+                }
306
+
307
+                $this->eventDispatcher->dispatch(CacheInsertEvent::class, new CacheInsertEvent($this->storage, $file, $fileId));
308
+                return $fileId;
309
+            }
310
+        } catch (UniqueConstraintViolationException $e) {
311
+            // entry exists already
312
+            if ($this->connection->inTransaction()) {
313
+                $this->connection->commit();
314
+                $this->connection->beginTransaction();
315
+            }
316
+        }
317
+
318
+        // The file was created in the mean time
319
+        if (($id = $this->getId($file)) > -1) {
320
+            $this->update($id, $data);
321
+            return $id;
322
+        } else {
323
+            throw new \RuntimeException('File entry could not be inserted but could also not be selected with getId() in order to perform an update. Please try again.');
324
+        }
325
+    }
326
+
327
+    /**
328
+     * update the metadata of an existing file or folder in the cache
329
+     *
330
+     * @param int $id the fileid of the existing file or folder
331
+     * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged
332
+     */
333
+    public function update($id, array $data) {
334
+
335
+        if (isset($data['path'])) {
336
+            // normalize path
337
+            $data['path'] = $this->normalize($data['path']);
338
+        }
339
+
340
+        if (isset($data['name'])) {
341
+            // normalize path
342
+            $data['name'] = $this->normalize($data['name']);
343
+        }
344
+
345
+        [$values, $extensionValues] = $this->normalizeData($data);
346
+
347
+        if (count($values)) {
348
+            $query = $this->getQueryBuilder();
349
+
350
+            $query->update('filecache')
351
+                ->whereFileId($id)
352
+                ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
353
+                    return $query->expr()->orX(
354
+                        $query->expr()->neq($key, $query->createNamedParameter($value)),
355
+                        $query->expr()->isNull($key)
356
+                    );
357
+                }, array_keys($values), array_values($values))));
358
+
359
+            foreach ($values as $key => $value) {
360
+                $query->set($key, $query->createNamedParameter($value));
361
+            }
362
+
363
+            $query->execute();
364
+        }
365
+
366
+        if (count($extensionValues)) {
367
+            try {
368
+                $query = $this->getQueryBuilder();
369
+                $query->insert('filecache_extended');
370
+
371
+                $query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
372
+                foreach ($extensionValues as $column => $value) {
373
+                    $query->setValue($column, $query->createNamedParameter($value));
374
+                }
375
+
376
+                $query->execute();
377
+            } catch (UniqueConstraintViolationException $e) {
378
+                $query = $this->getQueryBuilder();
379
+                $query->update('filecache_extended')
380
+                    ->whereFileId($id)
381
+                    ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
382
+                        return $query->expr()->orX(
383
+                            $query->expr()->neq($key, $query->createNamedParameter($value)),
384
+                            $query->expr()->isNull($key)
385
+                        );
386
+                    }, array_keys($extensionValues), array_values($extensionValues))));
387
+
388
+                foreach ($extensionValues as $key => $value) {
389
+                    $query->set($key, $query->createNamedParameter($value));
390
+                }
391
+
392
+                $query->execute();
393
+            }
394
+        }
395
+
396
+        $path = $this->getPathById($id);
397
+        // path can still be null if the file doesn't exist
398
+        if ($path !== null) {
399
+            $this->eventDispatcher->dispatch(CacheUpdateEvent::class, new CacheUpdateEvent($this->storage, $path, $id));
400
+        }
401
+    }
402
+
403
+    /**
404
+     * extract query parts and params array from data array
405
+     *
406
+     * @param array $data
407
+     * @return array
408
+     */
409
+    protected function normalizeData(array $data): array {
410
+        $fields = [
411
+            'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
412
+            'etag', 'permissions', 'checksum', 'storage'];
413
+        $extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
414
+
415
+        $doNotCopyStorageMTime = false;
416
+        if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
417
+            // this horrific magic tells it to not copy storage_mtime to mtime
418
+            unset($data['mtime']);
419
+            $doNotCopyStorageMTime = true;
420
+        }
421
+
422
+        $params = [];
423
+        $extensionParams = [];
424
+        foreach ($data as $name => $value) {
425
+            if (array_search($name, $fields) !== false) {
426
+                if ($name === 'path') {
427
+                    $params['path_hash'] = md5($value);
428
+                } else if ($name === 'mimetype') {
429
+                    $params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
430
+                    $value = $this->mimetypeLoader->getId($value);
431
+                } else if ($name === 'storage_mtime') {
432
+                    if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
433
+                        $params['mtime'] = $value;
434
+                    }
435
+                } else if ($name === 'encrypted') {
436
+                    if (isset($data['encryptedVersion'])) {
437
+                        $value = $data['encryptedVersion'];
438
+                    } else {
439
+                        // Boolean to integer conversion
440
+                        $value = $value ? 1 : 0;
441
+                    }
442
+                }
443
+                $params[$name] = $value;
444
+            }
445
+            if (array_search($name, $extensionFields) !== false) {
446
+                $extensionParams[$name] = $value;
447
+            }
448
+        }
449
+        return [$params, array_filter($extensionParams)];
450
+    }
451
+
452
+    /**
453
+     * get the file id for a file
454
+     *
455
+     * A file id is a numeric id for a file or folder that's unique within an owncloud instance which stays the same for the lifetime of a file
456
+     *
457
+     * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
458
+     *
459
+     * @param string $file
460
+     * @return int
461
+     */
462
+    public function getId($file) {
463
+        // normalize file
464
+        $file = $this->normalize($file);
465
+
466
+        $query = $this->getQueryBuilder();
467
+        $query->select('fileid')
468
+            ->from('filecache')
469
+            ->whereStorageId()
470
+            ->wherePath($file);
471
+
472
+        $id = $query->execute()->fetchColumn();
473
+        return $id === false ? -1 : (int)$id;
474
+    }
475
+
476
+    /**
477
+     * get the id of the parent folder of a file
478
+     *
479
+     * @param string $file
480
+     * @return int
481
+     */
482
+    public function getParentId($file) {
483
+        if ($file === '') {
484
+            return -1;
485
+        } else {
486
+            $parent = $this->getParentPath($file);
487
+            return (int)$this->getId($parent);
488
+        }
489
+    }
490
+
491
+    private function getParentPath($path) {
492
+        $parent = dirname($path);
493
+        if ($parent === '.') {
494
+            $parent = '';
495
+        }
496
+        return $parent;
497
+    }
498
+
499
+    /**
500
+     * check if a file is available in the cache
501
+     *
502
+     * @param string $file
503
+     * @return bool
504
+     */
505
+    public function inCache($file) {
506
+        return $this->getId($file) != -1;
507
+    }
508
+
509
+    /**
510
+     * remove a file or folder from the cache
511
+     *
512
+     * when removing a folder from the cache all files and folders inside the folder will be removed as well
513
+     *
514
+     * @param string $file
515
+     */
516
+    public function remove($file) {
517
+        $entry = $this->get($file);
518
+
519
+        if ($entry) {
520
+            $query = $this->getQueryBuilder();
521
+            $query->delete('filecache')
522
+                ->whereFileId($entry->getId());
523
+            $query->execute();
524
+
525
+            $query = $this->getQueryBuilder();
526
+            $query->delete('filecache_extended')
527
+                ->whereFileId($entry->getId());
528
+            $query->execute();
529
+
530
+            if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
531
+                $this->removeChildren($entry);
532
+            }
533
+        }
534
+    }
535
+
536
+    /**
537
+     * Get all sub folders of a folder
538
+     *
539
+     * @param ICacheEntry $entry the cache entry of the folder to get the subfolders for
540
+     * @return ICacheEntry[] the cache entries for the subfolders
541
+     */
542
+    private function getSubFolders(ICacheEntry $entry) {
543
+        $children = $this->getFolderContentsById($entry->getId());
544
+        return array_filter($children, function ($child) {
545
+            return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
546
+        });
547
+    }
548
+
549
+    /**
550
+     * Recursively remove all children of a folder
551
+     *
552
+     * @param ICacheEntry $entry the cache entry of the folder to remove the children of
553
+     * @throws \OC\DatabaseException
554
+     */
555
+    private function removeChildren(ICacheEntry $entry) {
556
+        $children = $this->getFolderContentsById($entry->getId());
557
+        $childIds = array_map(function (ICacheEntry $cacheEntry) {
558
+            return $cacheEntry->getId();
559
+        }, $children);
560
+        $childFolders = array_filter($children, function ($child) {
561
+            return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
562
+        });
563
+        foreach ($childFolders as $folder) {
564
+            $this->removeChildren($folder);
565
+        }
566
+
567
+        $query = $this->getQueryBuilder();
568
+        $query->delete('filecache')
569
+            ->whereParent($entry->getId());
570
+        $query->execute();
571
+
572
+        $query = $this->getQueryBuilder();
573
+        $query->delete('filecache_extended')
574
+            ->where($query->expr()->in('fileid', $query->createNamedParameter($childIds, IQueryBuilder::PARAM_INT_ARRAY)));
575
+        $query->execute();
576
+    }
577
+
578
+    /**
579
+     * Move a file or folder in the cache
580
+     *
581
+     * @param string $source
582
+     * @param string $target
583
+     */
584
+    public function move($source, $target) {
585
+        $this->moveFromCache($this, $source, $target);
586
+    }
587
+
588
+    /**
589
+     * Get the storage id and path needed for a move
590
+     *
591
+     * @param string $path
592
+     * @return array [$storageId, $internalPath]
593
+     */
594
+    protected function getMoveInfo($path) {
595
+        return [$this->getNumericStorageId(), $path];
596
+    }
597
+
598
+    /**
599
+     * Move a file or folder in the cache
600
+     *
601
+     * @param \OCP\Files\Cache\ICache $sourceCache
602
+     * @param string $sourcePath
603
+     * @param string $targetPath
604
+     * @throws \OC\DatabaseException
605
+     * @throws \Exception if the given storages have an invalid id
606
+     * @suppress SqlInjectionChecker
607
+     */
608
+    public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
609
+        if ($sourceCache instanceof Cache) {
610
+            // normalize source and target
611
+            $sourcePath = $this->normalize($sourcePath);
612
+            $targetPath = $this->normalize($targetPath);
613
+
614
+            $sourceData = $sourceCache->get($sourcePath);
615
+            $sourceId = $sourceData['fileid'];
616
+            $newParentId = $this->getParentId($targetPath);
617
+
618
+            [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
619
+            [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
620
+
621
+            if (is_null($sourceStorageId) || $sourceStorageId === false) {
622
+                throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
623
+            }
624
+            if (is_null($targetStorageId) || $targetStorageId === false) {
625
+                throw new \Exception('Invalid target storage id: ' . $targetStorageId);
626
+            }
627
+
628
+            $this->connection->beginTransaction();
629
+            if ($sourceData['mimetype'] === 'httpd/unix-directory') {
630
+                //update all child entries
631
+                $sourceLength = mb_strlen($sourcePath);
632
+                $query = $this->connection->getQueryBuilder();
633
+
634
+                $fun = $query->func();
635
+                $newPathFunction = $fun->concat(
636
+                    $query->createNamedParameter($targetPath),
637
+                    $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
638
+                );
639
+                $query->update('filecache')
640
+                    ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
641
+                    ->set('path_hash', $fun->md5($newPathFunction))
642
+                    ->set('path', $newPathFunction)
643
+                    ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
644
+                    ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
645
+
646
+                try {
647
+                    $query->execute();
648
+                } catch (\OC\DatabaseException $e) {
649
+                    $this->connection->rollBack();
650
+                    throw $e;
651
+                }
652
+            }
653
+
654
+            $query = $this->getQueryBuilder();
655
+            $query->update('filecache')
656
+                ->set('storage', $query->createNamedParameter($targetStorageId))
657
+                ->set('path', $query->createNamedParameter($targetPath))
658
+                ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
659
+                ->set('name', $query->createNamedParameter(basename($targetPath)))
660
+                ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
661
+                ->whereFileId($sourceId);
662
+            $query->execute();
663
+
664
+            $this->connection->commit();
665
+        } else {
666
+            $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
667
+        }
668
+    }
669
+
670
+    /**
671
+     * remove all entries for files that are stored on the storage from the cache
672
+     */
673
+    public function clear() {
674
+        $query = $this->getQueryBuilder();
675
+        $query->delete('filecache')
676
+            ->whereStorageId();
677
+        $query->execute();
678
+
679
+        $query = $this->connection->getQueryBuilder();
680
+        $query->delete('storages')
681
+            ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
682
+        $query->execute();
683
+    }
684
+
685
+    /**
686
+     * Get the scan status of a file
687
+     *
688
+     * - Cache::NOT_FOUND: File is not in the cache
689
+     * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
690
+     * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
691
+     * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
692
+     *
693
+     * @param string $file
694
+     *
695
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
696
+     */
697
+    public function getStatus($file) {
698
+        // normalize file
699
+        $file = $this->normalize($file);
700
+
701
+        $query = $this->getQueryBuilder();
702
+        $query->select('size')
703
+            ->from('filecache')
704
+            ->whereStorageId()
705
+            ->wherePath($file);
706
+        $size = $query->execute()->fetchColumn();
707
+        if ($size !== false) {
708
+            if ((int)$size === -1) {
709
+                return self::SHALLOW;
710
+            } else {
711
+                return self::COMPLETE;
712
+            }
713
+        } else {
714
+            if (isset($this->partial[$file])) {
715
+                return self::PARTIAL;
716
+            } else {
717
+                return self::NOT_FOUND;
718
+            }
719
+        }
720
+    }
721
+
722
+    /**
723
+     * search for files matching $pattern
724
+     *
725
+     * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
726
+     * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
727
+     */
728
+    public function search($pattern) {
729
+        // normalize pattern
730
+        $pattern = $this->normalize($pattern);
731
+
732
+        if ($pattern === '%%') {
733
+            return [];
734
+        }
735
+
736
+        $query = $this->getQueryBuilder();
737
+        $query->selectFileCache()
738
+            ->whereStorageId()
739
+            ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
740
+
741
+        return array_map(function (array $data) {
742
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
743
+        }, $query->execute()->fetchAll());
744
+    }
745
+
746
+    /**
747
+     * @param Statement $result
748
+     * @return CacheEntry[]
749
+     */
750
+    private function searchResultToCacheEntries(Statement $result) {
751
+        $files = $result->fetchAll();
752
+
753
+        return array_map(function (array $data) {
754
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
755
+        }, $files);
756
+    }
757
+
758
+    /**
759
+     * search for files by mimetype
760
+     *
761
+     * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
762
+     *        where it will search for all mimetypes in the group ('image/*')
763
+     * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
764
+     */
765
+    public function searchByMime($mimetype) {
766
+        $mimeId = $this->mimetypeLoader->getId($mimetype);
767
+
768
+        $query = $this->getQueryBuilder();
769
+        $query->selectFileCache()
770
+            ->whereStorageId();
771
+
772
+        if (strpos($mimetype, '/')) {
773
+            $query->andWhere($query->expr()->eq('mimetype', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
774
+        } else {
775
+            $query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
776
+        }
777
+
778
+        return array_map(function (array $data) {
779
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
780
+        }, $query->execute()->fetchAll());
781
+    }
782
+
783
+    public function searchQuery(ISearchQuery $searchQuery) {
784
+        $builder = $this->getQueryBuilder();
785
+
786
+        $query = $builder->selectFileCache('file');
787
+
788
+        $query->whereStorageId();
789
+
790
+        if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
791
+            $query
792
+                ->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
793
+                ->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
794
+                    $builder->expr()->eq('tagmap.type', 'tag.type'),
795
+                    $builder->expr()->eq('tagmap.categoryid', 'tag.id')
796
+                ))
797
+                ->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
798
+                ->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($searchQuery->getUser()->getUID())));
799
+        }
800
+
801
+        $searchExpr = $this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation());
802
+        if ($searchExpr) {
803
+            $query->andWhere($searchExpr);
804
+        }
805
+
806
+        if ($searchQuery->limitToHome() && ($this instanceof HomeCache)) {
807
+            $query->andWhere($builder->expr()->like('path', $query->expr()->literal('files/%')));
808
+        }
809
+
810
+        $this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
811
+
812
+        if ($searchQuery->getLimit()) {
813
+            $query->setMaxResults($searchQuery->getLimit());
814
+        }
815
+        if ($searchQuery->getOffset()) {
816
+            $query->setFirstResult($searchQuery->getOffset());
817
+        }
818
+
819
+        $result = $query->execute();
820
+        return $this->searchResultToCacheEntries($result);
821
+    }
822
+
823
+    /**
824
+     * Re-calculate the folder size and the size of all parent folders
825
+     *
826
+     * @param string|boolean $path
827
+     * @param array $data (optional) meta data of the folder
828
+     */
829
+    public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
830
+        $this->calculateFolderSize($path, $data);
831
+        if ($path !== '') {
832
+            $parent = dirname($path);
833
+            if ($parent === '.' or $parent === '/') {
834
+                $parent = '';
835
+            }
836
+            if ($isBackgroundScan) {
837
+                $parentData = $this->get($parent);
838
+                if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
839
+                    $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
840
+                }
841
+            } else {
842
+                $this->correctFolderSize($parent);
843
+            }
844
+        }
845
+    }
846
+
847
+    /**
848
+     * get the incomplete count that shares parent $folder
849
+     *
850
+     * @param int $fileId the file id of the folder
851
+     * @return int
852
+     */
853
+    public function getIncompleteChildrenCount($fileId) {
854
+        if ($fileId > -1) {
855
+            $query = $this->getQueryBuilder();
856
+            $query->select($query->func()->count())
857
+                ->from('filecache')
858
+                ->whereParent($fileId)
859
+                ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
860
+
861
+            return (int)$query->execute()->fetchColumn();
862
+        }
863
+        return -1;
864
+    }
865
+
866
+    /**
867
+     * calculate the size of a folder and set it in the cache
868
+     *
869
+     * @param string $path
870
+     * @param array $entry (optional) meta data of the folder
871
+     * @return int
872
+     */
873
+    public function calculateFolderSize($path, $entry = null) {
874
+        $totalSize = 0;
875
+        if (is_null($entry) or !isset($entry['fileid'])) {
876
+            $entry = $this->get($path);
877
+        }
878
+        if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
879
+            $id = $entry['fileid'];
880
+
881
+            $query = $this->getQueryBuilder();
882
+            $query->selectAlias($query->func()->sum('size'), 'f1')
883
+                ->selectAlias($query->func()->min('size'), 'f2')
884
+                ->from('filecache')
885
+                ->whereStorageId()
886
+                ->whereParent($id);
887
+
888
+            if ($row = $query->execute()->fetch()) {
889
+                [$sum, $min] = array_values($row);
890
+                $sum = 0 + $sum;
891
+                $min = 0 + $min;
892
+                if ($min === -1) {
893
+                    $totalSize = $min;
894
+                } else {
895
+                    $totalSize = $sum;
896
+                }
897
+                if ($entry['size'] !== $totalSize) {
898
+                    $this->update($id, ['size' => $totalSize]);
899
+                }
900
+            }
901
+        }
902
+        return $totalSize;
903
+    }
904
+
905
+    /**
906
+     * get all file ids on the files on the storage
907
+     *
908
+     * @return int[]
909
+     */
910
+    public function getAll() {
911
+        $query = $this->getQueryBuilder();
912
+        $query->select('fileid')
913
+            ->from('filecache')
914
+            ->whereStorageId();
915
+
916
+        return array_map(function ($id) {
917
+            return (int)$id;
918
+        }, $query->execute()->fetchAll(\PDO::FETCH_COLUMN));
919
+    }
920
+
921
+    /**
922
+     * find a folder in the cache which has not been fully scanned
923
+     *
924
+     * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
925
+     * use the one with the highest id gives the best result with the background scanner, since that is most
926
+     * likely the folder where we stopped scanning previously
927
+     *
928
+     * @return string|bool the path of the folder or false when no folder matched
929
+     */
930
+    public function getIncomplete() {
931
+        $query = $this->getQueryBuilder();
932
+        $query->select('path')
933
+            ->from('filecache')
934
+            ->whereStorageId()
935
+            ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
936
+            ->orderBy('fileid', 'DESC');
937
+
938
+        return $query->execute()->fetchColumn();
939
+    }
940
+
941
+    /**
942
+     * get the path of a file on this storage by it's file id
943
+     *
944
+     * @param int $id the file id of the file or folder to search
945
+     * @return string|null the path of the file (relative to the storage) or null if a file with the given id does not exists within this cache
946
+     */
947
+    public function getPathById($id) {
948
+        $query = $this->getQueryBuilder();
949
+        $query->select('path')
950
+            ->from('filecache')
951
+            ->whereStorageId()
952
+            ->whereFileId($id);
953
+
954
+        $path = $query->execute()->fetchColumn();
955
+        return $path === false ? null : $path;
956
+    }
957
+
958
+    /**
959
+     * get the storage id of the storage for a file and the internal path of the file
960
+     * unlike getPathById this does not limit the search to files on this storage and
961
+     * instead does a global search in the cache table
962
+     *
963
+     * @param int $id
964
+     * @return array first element holding the storage id, second the path
965
+     * @deprecated use getPathById() instead
966
+     */
967
+    static public function getById($id) {
968
+        $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
969
+        $query->select('path', 'storage')
970
+            ->from('filecache')
971
+            ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
972
+        if ($row = $query->execute()->fetch()) {
973
+            $numericId = $row['storage'];
974
+            $path = $row['path'];
975
+        } else {
976
+            return null;
977
+        }
978
+
979
+        if ($id = Storage::getStorageId($numericId)) {
980
+            return [$id, $path];
981
+        } else {
982
+            return null;
983
+        }
984
+    }
985
+
986
+    /**
987
+     * normalize the given path
988
+     *
989
+     * @param string $path
990
+     * @return string
991
+     */
992
+    public function normalize($path) {
993
+
994
+        return trim(\OC_Util::normalizeUnicode($path), '/');
995
+    }
996 996
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -171,21 +171,21 @@  discard block
 block discarded – undo
171 171
 	 */
172 172
 	public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
173 173
 		//fix types
174
-		$data['fileid'] = (int)$data['fileid'];
175
-		$data['parent'] = (int)$data['parent'];
174
+		$data['fileid'] = (int) $data['fileid'];
175
+		$data['parent'] = (int) $data['parent'];
176 176
 		$data['size'] = 0 + $data['size'];
177
-		$data['mtime'] = (int)$data['mtime'];
178
-		$data['storage_mtime'] = (int)$data['storage_mtime'];
179
-		$data['encryptedVersion'] = (int)$data['encrypted'];
180
-		$data['encrypted'] = (bool)$data['encrypted'];
177
+		$data['mtime'] = (int) $data['mtime'];
178
+		$data['storage_mtime'] = (int) $data['storage_mtime'];
179
+		$data['encryptedVersion'] = (int) $data['encrypted'];
180
+		$data['encrypted'] = (bool) $data['encrypted'];
181 181
 		$data['storage_id'] = $data['storage'];
182
-		$data['storage'] = (int)$data['storage'];
182
+		$data['storage'] = (int) $data['storage'];
183 183
 		$data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
184 184
 		$data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
185 185
 		if ($data['storage_mtime'] == 0) {
186 186
 			$data['storage_mtime'] = $data['mtime'];
187 187
 		}
188
-		$data['permissions'] = (int)$data['permissions'];
188
+		$data['permissions'] = (int) $data['permissions'];
189 189
 		if (isset($data['creation_time'])) {
190 190
 			$data['creation_time'] = (int) $data['creation_time'];
191 191
 		}
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 				->orderBy('name', 'ASC');
221 221
 
222 222
 			$files = $query->execute()->fetchAll();
223
-			return array_map(function (array $data) {
223
+			return array_map(function(array $data) {
224 224
 				return self::cacheEntryFromData($data, $this->mimetypeLoader);
225 225
 			}, $files);
226 226
 		}
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 
350 350
 			$query->update('filecache')
351 351
 				->whereFileId($id)
352
-				->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
352
+				->andWhere($query->expr()->orX(...array_map(function($key, $value) use ($query) {
353 353
 					return $query->expr()->orX(
354 354
 						$query->expr()->neq($key, $query->createNamedParameter($value)),
355 355
 						$query->expr()->isNull($key)
@@ -378,7 +378,7 @@  discard block
 block discarded – undo
378 378
 				$query = $this->getQueryBuilder();
379 379
 				$query->update('filecache_extended')
380 380
 					->whereFileId($id)
381
-					->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
381
+					->andWhere($query->expr()->orX(...array_map(function($key, $value) use ($query) {
382 382
 						return $query->expr()->orX(
383 383
 							$query->expr()->neq($key, $query->createNamedParameter($value)),
384 384
 							$query->expr()->isNull($key)
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 			->wherePath($file);
471 471
 
472 472
 		$id = $query->execute()->fetchColumn();
473
-		return $id === false ? -1 : (int)$id;
473
+		return $id === false ? -1 : (int) $id;
474 474
 	}
475 475
 
476 476
 	/**
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
 			return -1;
485 485
 		} else {
486 486
 			$parent = $this->getParentPath($file);
487
-			return (int)$this->getId($parent);
487
+			return (int) $this->getId($parent);
488 488
 		}
489 489
 	}
490 490
 
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
 	 */
542 542
 	private function getSubFolders(ICacheEntry $entry) {
543 543
 		$children = $this->getFolderContentsById($entry->getId());
544
-		return array_filter($children, function ($child) {
544
+		return array_filter($children, function($child) {
545 545
 			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
546 546
 		});
547 547
 	}
@@ -554,10 +554,10 @@  discard block
 block discarded – undo
554 554
 	 */
555 555
 	private function removeChildren(ICacheEntry $entry) {
556 556
 		$children = $this->getFolderContentsById($entry->getId());
557
-		$childIds = array_map(function (ICacheEntry $cacheEntry) {
557
+		$childIds = array_map(function(ICacheEntry $cacheEntry) {
558 558
 			return $cacheEntry->getId();
559 559
 		}, $children);
560
-		$childFolders = array_filter($children, function ($child) {
560
+		$childFolders = array_filter($children, function($child) {
561 561
 			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
562 562
 		});
563 563
 		foreach ($childFolders as $folder) {
@@ -619,10 +619,10 @@  discard block
 block discarded – undo
619 619
 			[$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
620 620
 
621 621
 			if (is_null($sourceStorageId) || $sourceStorageId === false) {
622
-				throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
622
+				throw new \Exception('Invalid source storage id: '.$sourceStorageId);
623 623
 			}
624 624
 			if (is_null($targetStorageId) || $targetStorageId === false) {
625
-				throw new \Exception('Invalid target storage id: ' . $targetStorageId);
625
+				throw new \Exception('Invalid target storage id: '.$targetStorageId);
626 626
 			}
627 627
 
628 628
 			$this->connection->beginTransaction();
@@ -641,7 +641,7 @@  discard block
 block discarded – undo
641 641
 					->set('path_hash', $fun->md5($newPathFunction))
642 642
 					->set('path', $newPathFunction)
643 643
 					->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
644
-					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
644
+					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath).'/%')));
645 645
 
646 646
 				try {
647 647
 					$query->execute();
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 			->wherePath($file);
706 706
 		$size = $query->execute()->fetchColumn();
707 707
 		if ($size !== false) {
708
-			if ((int)$size === -1) {
708
+			if ((int) $size === -1) {
709 709
 				return self::SHALLOW;
710 710
 			} else {
711 711
 				return self::COMPLETE;
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
 			->whereStorageId()
739 739
 			->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
740 740
 
741
-		return array_map(function (array $data) {
741
+		return array_map(function(array $data) {
742 742
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
743 743
 		}, $query->execute()->fetchAll());
744 744
 	}
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 	private function searchResultToCacheEntries(Statement $result) {
751 751
 		$files = $result->fetchAll();
752 752
 
753
-		return array_map(function (array $data) {
753
+		return array_map(function(array $data) {
754 754
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
755 755
 		}, $files);
756 756
 	}
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 			$query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
776 776
 		}
777 777
 
778
-		return array_map(function (array $data) {
778
+		return array_map(function(array $data) {
779 779
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
780 780
 		}, $query->execute()->fetchAll());
781 781
 	}
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
 				->whereParent($fileId)
859 859
 				->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
860 860
 
861
-			return (int)$query->execute()->fetchColumn();
861
+			return (int) $query->execute()->fetchColumn();
862 862
 		}
863 863
 		return -1;
864 864
 	}
@@ -913,8 +913,8 @@  discard block
 block discarded – undo
913 913
 			->from('filecache')
914 914
 			->whereStorageId();
915 915
 
916
-		return array_map(function ($id) {
917
-			return (int)$id;
916
+		return array_map(function($id) {
917
+			return (int) $id;
918 918
 		}, $query->execute()->fetchAll(\PDO::FETCH_COLUMN));
919 919
 	}
920 920
 
Please login to merge, or discard this patch.
lib/private/Route/Route.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -33,128 +33,128 @@
 block discarded – undo
33 33
 use Symfony\Component\Routing\Route as SymfonyRoute;
34 34
 
35 35
 class Route extends SymfonyRoute implements IRoute {
36
-	/**
37
-	 * Specify the method when this route is to be used
38
-	 *
39
-	 * @param string $method HTTP method (uppercase)
40
-	 * @return \OC\Route\Route
41
-	 */
42
-	public function method($method) {
43
-		$this->setMethods($method);
44
-		return $this;
45
-	}
36
+    /**
37
+     * Specify the method when this route is to be used
38
+     *
39
+     * @param string $method HTTP method (uppercase)
40
+     * @return \OC\Route\Route
41
+     */
42
+    public function method($method) {
43
+        $this->setMethods($method);
44
+        return $this;
45
+    }
46 46
 
47
-	/**
48
-	 * Specify POST as the method to use with this route
49
-	 * @return \OC\Route\Route
50
-	 */
51
-	public function post() {
52
-		$this->method('POST');
53
-		return $this;
54
-	}
47
+    /**
48
+     * Specify POST as the method to use with this route
49
+     * @return \OC\Route\Route
50
+     */
51
+    public function post() {
52
+        $this->method('POST');
53
+        return $this;
54
+    }
55 55
 
56
-	/**
57
-	 * Specify GET as the method to use with this route
58
-	 * @return \OC\Route\Route
59
-	 */
60
-	public function get() {
61
-		$this->method('GET');
62
-		return $this;
63
-	}
56
+    /**
57
+     * Specify GET as the method to use with this route
58
+     * @return \OC\Route\Route
59
+     */
60
+    public function get() {
61
+        $this->method('GET');
62
+        return $this;
63
+    }
64 64
 
65
-	/**
66
-	 * Specify PUT as the method to use with this route
67
-	 * @return \OC\Route\Route
68
-	 */
69
-	public function put() {
70
-		$this->method('PUT');
71
-		return $this;
72
-	}
65
+    /**
66
+     * Specify PUT as the method to use with this route
67
+     * @return \OC\Route\Route
68
+     */
69
+    public function put() {
70
+        $this->method('PUT');
71
+        return $this;
72
+    }
73 73
 
74
-	/**
75
-	 * Specify DELETE as the method to use with this route
76
-	 * @return \OC\Route\Route
77
-	 */
78
-	public function delete() {
79
-		$this->method('DELETE');
80
-		return $this;
81
-	}
74
+    /**
75
+     * Specify DELETE as the method to use with this route
76
+     * @return \OC\Route\Route
77
+     */
78
+    public function delete() {
79
+        $this->method('DELETE');
80
+        return $this;
81
+    }
82 82
 
83
-	/**
84
-	 * Specify PATCH as the method to use with this route
85
-	 * @return \OC\Route\Route
86
-	 */
87
-	public function patch() {
88
-		$this->method('PATCH');
89
-		return $this;
90
-	}
83
+    /**
84
+     * Specify PATCH as the method to use with this route
85
+     * @return \OC\Route\Route
86
+     */
87
+    public function patch() {
88
+        $this->method('PATCH');
89
+        return $this;
90
+    }
91 91
 
92
-	/**
93
-	 * Defaults to use for this route
94
-	 *
95
-	 * @param array $defaults The defaults
96
-	 * @return \OC\Route\Route
97
-	 */
98
-	public function defaults($defaults) {
99
-		$action = $this->getDefault('action');
100
-		$this->setDefaults($defaults);
101
-		if (isset($defaults['action'])) {
102
-			$action = $defaults['action'];
103
-		}
104
-		$this->action($action);
105
-		return $this;
106
-	}
92
+    /**
93
+     * Defaults to use for this route
94
+     *
95
+     * @param array $defaults The defaults
96
+     * @return \OC\Route\Route
97
+     */
98
+    public function defaults($defaults) {
99
+        $action = $this->getDefault('action');
100
+        $this->setDefaults($defaults);
101
+        if (isset($defaults['action'])) {
102
+            $action = $defaults['action'];
103
+        }
104
+        $this->action($action);
105
+        return $this;
106
+    }
107 107
 
108
-	/**
109
-	 * Requirements for this route
110
-	 *
111
-	 * @param array $requirements The requirements
112
-	 * @return \OC\Route\Route
113
-	 */
114
-	public function requirements($requirements) {
115
-		$method = $this->getMethods();
116
-		$this->setRequirements($requirements);
117
-		if (isset($requirements['_method'])) {
118
-			$method = $requirements['_method'];
119
-		}
120
-		if ($method) {
121
-			$this->method($method);
122
-		}
123
-		return $this;
124
-	}
108
+    /**
109
+     * Requirements for this route
110
+     *
111
+     * @param array $requirements The requirements
112
+     * @return \OC\Route\Route
113
+     */
114
+    public function requirements($requirements) {
115
+        $method = $this->getMethods();
116
+        $this->setRequirements($requirements);
117
+        if (isset($requirements['_method'])) {
118
+            $method = $requirements['_method'];
119
+        }
120
+        if ($method) {
121
+            $this->method($method);
122
+        }
123
+        return $this;
124
+    }
125 125
 
126
-	/**
127
-	 * The action to execute when this route matches
128
-	 *
129
-	 * @param string|callable $class the class or a callable
130
-	 * @param string $function the function to use with the class
131
-	 * @return \OC\Route\Route
132
-	 *
133
-	 * This function is called with $class set to a callable or
134
-	 * to the class with $function
135
-	 */
136
-	public function action($class, $function = null) {
137
-		$action = [$class, $function];
138
-		if (is_null($function)) {
139
-			$action = $class;
140
-		}
141
-		$this->setDefault('action', $action);
142
-		return $this;
143
-	}
126
+    /**
127
+     * The action to execute when this route matches
128
+     *
129
+     * @param string|callable $class the class or a callable
130
+     * @param string $function the function to use with the class
131
+     * @return \OC\Route\Route
132
+     *
133
+     * This function is called with $class set to a callable or
134
+     * to the class with $function
135
+     */
136
+    public function action($class, $function = null) {
137
+        $action = [$class, $function];
138
+        if (is_null($function)) {
139
+            $action = $class;
140
+        }
141
+        $this->setDefault('action', $action);
142
+        return $this;
143
+    }
144 144
 
145
-	/**
146
-	 * The action to execute when this route matches, includes a file like
147
-	 * it is called directly
148
-	 * @param string $file
149
-	 * @return void
150
-	 */
151
-	public function actionInclude($file) {
152
-		$function = function ($param) use ($file) {
153
-			unset($param["_route"]);
154
-			$_GET=array_merge($_GET, $param);
155
-			unset($param);
156
-			require_once "$file";
157
-		} ;
158
-		$this->action($function);
159
-	}
145
+    /**
146
+     * The action to execute when this route matches, includes a file like
147
+     * it is called directly
148
+     * @param string $file
149
+     * @return void
150
+     */
151
+    public function actionInclude($file) {
152
+        $function = function ($param) use ($file) {
153
+            unset($param["_route"]);
154
+            $_GET=array_merge($_GET, $param);
155
+            unset($param);
156
+            require_once "$file";
157
+        } ;
158
+        $this->action($function);
159
+    }
160 160
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -149,9 +149,9 @@
 block discarded – undo
149 149
 	 * @return void
150 150
 	 */
151 151
 	public function actionInclude($file) {
152
-		$function = function ($param) use ($file) {
152
+		$function = function($param) use ($file) {
153 153
 			unset($param["_route"]);
154
-			$_GET=array_merge($_GET, $param);
154
+			$_GET = array_merge($_GET, $param);
155 155
 			unset($param);
156 156
 			require_once "$file";
157 157
 		} ;
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +2002 added lines, -2002 removed lines patch added patch discarded remove patch
@@ -242,2011 +242,2011 @@
 block discarded – undo
242 242
  * TODO: hookup all manager classes
243 243
  */
244 244
 class Server extends ServerContainer implements IServerContainer {
245
-	/** @var string */
246
-	private $webRoot;
247
-
248
-	/**
249
-	 * @param string $webRoot
250
-	 * @param \OC\Config $config
251
-	 */
252
-	public function __construct($webRoot, \OC\Config $config) {
253
-		parent::__construct();
254
-		$this->webRoot = $webRoot;
255
-
256
-		// To find out if we are running from CLI or not
257
-		$this->registerParameter('isCLI', \OC::$CLI);
258
-
259
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
260
-			return $c;
261
-		});
262
-
263
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
264
-		$this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
265
-
266
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
267
-		$this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
268
-
269
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
270
-		$this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
271
-
272
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
273
-		$this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
274
-
275
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
276
-
277
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
278
-
279
-
280
-		$this->registerService(IPreview::class, function (Server $c) {
281
-			return new PreviewManager(
282
-				$c->getConfig(),
283
-				$c->getRootFolder(),
284
-				$c->getAppDataDir('preview'),
285
-				$c->getEventDispatcher(),
286
-				$c->getGeneratorHelper(),
287
-				$c->getSession()->get('user_id')
288
-			);
289
-		});
290
-		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
291
-
292
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
293
-			return new \OC\Preview\Watcher(
294
-				$c->getAppDataDir('preview')
295
-			);
296
-		});
297
-
298
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
299
-			$view = new View();
300
-			$util = new Encryption\Util(
301
-				$view,
302
-				$c->getUserManager(),
303
-				$c->getGroupManager(),
304
-				$c->getConfig()
305
-			);
306
-			return new Encryption\Manager(
307
-				$c->getConfig(),
308
-				$c->getLogger(),
309
-				$c->getL10N('core'),
310
-				new View(),
311
-				$util,
312
-				new ArrayCache()
313
-			);
314
-		});
315
-		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
316
-
317
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
318
-			$util = new Encryption\Util(
319
-				new View(),
320
-				$c->getUserManager(),
321
-				$c->getGroupManager(),
322
-				$c->getConfig()
323
-			);
324
-			return new Encryption\File(
325
-				$util,
326
-				$c->getRootFolder(),
327
-				$c->getShareManager()
328
-			);
329
-		});
330
-
331
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
332
-			$view = new View();
333
-			$util = new Encryption\Util(
334
-				$view,
335
-				$c->getUserManager(),
336
-				$c->getGroupManager(),
337
-				$c->getConfig()
338
-			);
339
-
340
-			return new Encryption\Keys\Storage($view, $util);
341
-		});
342
-		$this->registerService('TagMapper', function (Server $c) {
343
-			return new TagMapper($c->getDatabaseConnection());
344
-		});
345
-
346
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
347
-			$tagMapper = $c->query('TagMapper');
348
-			return new TagManager($tagMapper, $c->getUserSession());
349
-		});
350
-		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
351
-
352
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
353
-			$config = $c->getConfig();
354
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
355
-			return new $factoryClass($this);
356
-		});
357
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
358
-			return $c->query('SystemTagManagerFactory')->getManager();
359
-		});
360
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
361
-
362
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
363
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
364
-		});
365
-		$this->registerService('RootFolder', function (Server $c) {
366
-			$manager = \OC\Files\Filesystem::getMountManager(null);
367
-			$view = new View();
368
-			$root = new Root(
369
-				$manager,
370
-				$view,
371
-				null,
372
-				$c->getUserMountCache(),
373
-				$this->getLogger(),
374
-				$this->getUserManager()
375
-			);
376
-			$connector = new HookConnector($root, $view, $c->getEventDispatcher());
377
-			$connector->viewToNode();
378
-
379
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
380
-			$previewConnector->connectWatcher();
381
-
382
-			return $root;
383
-		});
384
-		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
385
-
386
-		$this->registerService(IRootFolder::class, function (Server $c) {
387
-			return new LazyRoot(function () use ($c) {
388
-				return $c->query('RootFolder');
389
-			});
390
-		});
391
-		$this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
392
-
393
-		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
394
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
395
-
396
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
397
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
398
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
399
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
400
-
401
-				/** @var IEventDispatcher $dispatcher */
402
-				$dispatcher = $this->query(IEventDispatcher::class);
403
-				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
404
-			});
405
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
406
-				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
407
-
408
-				/** @var IEventDispatcher $dispatcher */
409
-				$dispatcher = $this->query(IEventDispatcher::class);
410
-				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
411
-			});
412
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
413
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
414
-
415
-				/** @var IEventDispatcher $dispatcher */
416
-				$dispatcher = $this->query(IEventDispatcher::class);
417
-				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
418
-			});
419
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
420
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
421
-
422
-				/** @var IEventDispatcher $dispatcher */
423
-				$dispatcher = $this->query(IEventDispatcher::class);
424
-				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
425
-			});
426
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
427
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
428
-
429
-				/** @var IEventDispatcher $dispatcher */
430
-				$dispatcher = $this->query(IEventDispatcher::class);
431
-				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
432
-			});
433
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
434
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
435
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
436
-				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
437
-
438
-				/** @var IEventDispatcher $dispatcher */
439
-				$dispatcher = $this->query(IEventDispatcher::class);
440
-				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
441
-			});
442
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
443
-				/** @var IEventDispatcher $dispatcher */
444
-				$dispatcher = $this->query(IEventDispatcher::class);
445
-				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
446
-			});
447
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
448
-				/** @var IEventDispatcher $dispatcher */
449
-				$dispatcher = $this->query(IEventDispatcher::class);
450
-				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
451
-			});
452
-			return $groupManager;
453
-		});
454
-		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
455
-
456
-		$this->registerService(Store::class, function (Server $c) {
457
-			$session = $c->getSession();
458
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
459
-				$tokenProvider = $c->query(IProvider::class);
460
-			} else {
461
-				$tokenProvider = null;
462
-			}
463
-			$logger = $c->getLogger();
464
-			return new Store($session, $logger, $tokenProvider);
465
-		});
466
-		$this->registerAlias(IStore::class, Store::class);
467
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
468
-			$dbConnection = $c->getDatabaseConnection();
469
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
470
-		});
471
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
472
-
473
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
474
-			$manager = $c->getUserManager();
475
-			$session = new \OC\Session\Memory('');
476
-			$timeFactory = new TimeFactory();
477
-			// Token providers might require a working database. This code
478
-			// might however be called when ownCloud is not yet setup.
479
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
480
-				$defaultTokenProvider = $c->query(IProvider::class);
481
-			} else {
482
-				$defaultTokenProvider = null;
483
-			}
484
-
485
-			$legacyDispatcher = $c->getEventDispatcher();
486
-
487
-			$userSession = new \OC\User\Session(
488
-				$manager,
489
-				$session,
490
-				$timeFactory,
491
-				$defaultTokenProvider,
492
-				$c->getConfig(),
493
-				$c->getSecureRandom(),
494
-				$c->getLockdownManager(),
495
-				$c->getLogger(),
496
-				$c->query(IEventDispatcher::class)
497
-			);
498
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
499
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
500
-
501
-				/** @var IEventDispatcher $dispatcher */
502
-				$dispatcher = $this->query(IEventDispatcher::class);
503
-				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
504
-			});
505
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
506
-				/** @var $user \OC\User\User */
507
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
508
-
509
-				/** @var IEventDispatcher $dispatcher */
510
-				$dispatcher = $this->query(IEventDispatcher::class);
511
-				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
512
-			});
513
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
514
-				/** @var $user \OC\User\User */
515
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
516
-				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
517
-
518
-				/** @var IEventDispatcher $dispatcher */
519
-				$dispatcher = $this->query(IEventDispatcher::class);
520
-				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
521
-			});
522
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
523
-				/** @var $user \OC\User\User */
524
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
525
-
526
-				/** @var IEventDispatcher $dispatcher */
527
-				$dispatcher = $this->query(IEventDispatcher::class);
528
-				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
529
-			});
530
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
531
-				/** @var $user \OC\User\User */
532
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
533
-
534
-				/** @var IEventDispatcher $dispatcher */
535
-				$dispatcher = $this->query(IEventDispatcher::class);
536
-				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
537
-			});
538
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
539
-				/** @var $user \OC\User\User */
540
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
541
-
542
-				/** @var IEventDispatcher $dispatcher */
543
-				$dispatcher = $this->query(IEventDispatcher::class);
544
-				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
545
-			});
546
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
547
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
548
-
549
-				/** @var IEventDispatcher $dispatcher */
550
-				$dispatcher = $this->query(IEventDispatcher::class);
551
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
552
-			});
553
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
554
-				/** @var $user \OC\User\User */
555
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
556
-
557
-				/** @var IEventDispatcher $dispatcher */
558
-				$dispatcher = $this->query(IEventDispatcher::class);
559
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
560
-			});
561
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
562
-				/** @var IEventDispatcher $dispatcher */
563
-				$dispatcher = $this->query(IEventDispatcher::class);
564
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
565
-			});
566
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
567
-				/** @var $user \OC\User\User */
568
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
569
-
570
-				/** @var IEventDispatcher $dispatcher */
571
-				$dispatcher = $this->query(IEventDispatcher::class);
572
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
573
-			});
574
-			$userSession->listen('\OC\User', 'logout', function ($user) {
575
-				\OC_Hook::emit('OC_User', 'logout', []);
576
-
577
-				/** @var IEventDispatcher $dispatcher */
578
-				$dispatcher = $this->query(IEventDispatcher::class);
579
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
580
-			});
581
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
582
-				/** @var IEventDispatcher $dispatcher */
583
-				$dispatcher = $this->query(IEventDispatcher::class);
584
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
585
-			});
586
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
587
-				/** @var $user \OC\User\User */
588
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
589
-
590
-				/** @var IEventDispatcher $dispatcher */
591
-				$dispatcher = $this->query(IEventDispatcher::class);
592
-				$dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
593
-			});
594
-			return $userSession;
595
-		});
596
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
597
-		$this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
598
-
599
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
600
-
601
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
602
-		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
603
-
604
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
605
-			return new \OC\AllConfig(
606
-				$c->getSystemConfig()
607
-			);
608
-		});
609
-		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
610
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
611
-
612
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
613
-			return new \OC\SystemConfig($config);
614
-		});
615
-		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
616
-
617
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
618
-			return new \OC\AppConfig($c->getDatabaseConnection());
619
-		});
620
-		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
621
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
622
-
623
-		$this->registerService(IFactory::class, function (Server $c) {
624
-			return new \OC\L10N\Factory(
625
-				$c->getConfig(),
626
-				$c->getRequest(),
627
-				$c->getUserSession(),
628
-				\OC::$SERVERROOT
629
-			);
630
-		});
631
-		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
632
-
633
-		$this->registerService(IURLGenerator::class, function (Server $c) {
634
-			$config = $c->getConfig();
635
-			$cacheFactory = $c->getMemCacheFactory();
636
-			$request = $c->getRequest();
637
-			return new \OC\URLGenerator(
638
-				$config,
639
-				$cacheFactory,
640
-				$request
641
-			);
642
-		});
643
-		$this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
644
-
645
-		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
646
-		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
647
-
648
-		$this->registerService(ICache::class, function ($c) {
649
-			return new Cache\File();
650
-		});
651
-		$this->registerDeprecatedAlias('UserCache', ICache::class);
652
-
653
-		$this->registerService(Factory::class, function (Server $c) {
654
-
655
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
656
-				ArrayCache::class,
657
-				ArrayCache::class,
658
-				ArrayCache::class
659
-			);
660
-			$config = $c->getConfig();
661
-
662
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
663
-				$v = \OC_App::getAppVersions();
664
-				$v['core'] = implode(',', \OC_Util::getVersion());
665
-				$version = implode(',', $v);
666
-				$instanceId = \OC_Util::getInstanceId();
667
-				$path = \OC::$SERVERROOT;
668
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
669
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
670
-					$config->getSystemValue('memcache.local', null),
671
-					$config->getSystemValue('memcache.distributed', null),
672
-					$config->getSystemValue('memcache.locking', null)
673
-				);
674
-			}
675
-			return $arrayCacheFactory;
676
-
677
-		});
678
-		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
679
-		$this->registerAlias(ICacheFactory::class, Factory::class);
680
-
681
-		$this->registerService('RedisFactory', function (Server $c) {
682
-			$systemConfig = $c->getSystemConfig();
683
-			return new RedisFactory($systemConfig);
684
-		});
685
-
686
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
687
-			return new \OC\Activity\Manager(
688
-				$c->getRequest(),
689
-				$c->getUserSession(),
690
-				$c->getConfig(),
691
-				$c->query(IValidator::class)
692
-			);
693
-		});
694
-		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
695
-
696
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
697
-			return new \OC\Activity\EventMerger(
698
-				$c->getL10N('lib')
699
-			);
700
-		});
701
-		$this->registerAlias(IValidator::class, Validator::class);
702
-
703
-		$this->registerService(AvatarManager::class, function (Server $c) {
704
-			return new AvatarManager(
705
-				$c->query(\OC\User\Manager::class),
706
-				$c->getAppDataDir('avatar'),
707
-				$c->getL10N('lib'),
708
-				$c->getLogger(),
709
-				$c->getConfig()
710
-			);
711
-		});
712
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
713
-		$this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
714
-
715
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
716
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
717
-
718
-		$this->registerService(\OC\Log::class, function (Server $c) {
719
-			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
720
-			$factory = new LogFactory($c, $this->getSystemConfig());
721
-			$logger = $factory->get($logType);
722
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
723
-
724
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
725
-		});
726
-		$this->registerAlias(ILogger::class, \OC\Log::class);
727
-		$this->registerDeprecatedAlias('Logger', \OC\Log::class);
728
-		// PSR-3 logger
729
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
730
-
731
-		$this->registerService(ILogFactory::class, function (Server $c) {
732
-			return new LogFactory($c, $this->getSystemConfig());
733
-		});
734
-
735
-		$this->registerService(IJobList::class, function (Server $c) {
736
-			$config = $c->getConfig();
737
-			return new \OC\BackgroundJob\JobList(
738
-				$c->getDatabaseConnection(),
739
-				$config,
740
-				new TimeFactory()
741
-			);
742
-		});
743
-		$this->registerDeprecatedAlias('JobList', IJobList::class);
744
-
745
-		$this->registerService(IRouter::class, function (Server $c) {
746
-			$cacheFactory = $c->getMemCacheFactory();
747
-			$logger = $c->getLogger();
748
-			if ($cacheFactory->isLocalCacheAvailable()) {
749
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
750
-			} else {
751
-				$router = new \OC\Route\Router($logger);
752
-			}
753
-			return $router;
754
-		});
755
-		$this->registerDeprecatedAlias('Router', IRouter::class);
756
-
757
-		$this->registerService(ISearch::class, function ($c) {
758
-			return new Search();
759
-		});
760
-		$this->registerDeprecatedAlias('Search', ISearch::class);
761
-
762
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
763
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
764
-				$this->getMemCacheFactory(),
765
-				new \OC\AppFramework\Utility\TimeFactory()
766
-			);
767
-		});
768
-
769
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
770
-			return new SecureRandom();
771
-		});
772
-		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
773
-
774
-		$this->registerService(ICrypto::class, function (Server $c) {
775
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
776
-		});
777
-		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
778
-
779
-		$this->registerService(IHasher::class, function (Server $c) {
780
-			return new Hasher($c->getConfig());
781
-		});
782
-		$this->registerDeprecatedAlias('Hasher', IHasher::class);
783
-
784
-		$this->registerService(ICredentialsManager::class, function (Server $c) {
785
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
786
-		});
787
-		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
788
-
789
-		$this->registerService(IDBConnection::class, function (Server $c) {
790
-			$systemConfig = $c->getSystemConfig();
791
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
792
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
793
-			if (!$factory->isValidType($type)) {
794
-				throw new \OC\DatabaseException('Invalid database type');
795
-			}
796
-			$connectionParams = $factory->createConnectionParams();
797
-			$connection = $factory->getConnection($type, $connectionParams);
798
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
799
-			return $connection;
800
-		});
801
-		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
802
-
803
-
804
-		$this->registerService(IClientService::class, function (Server $c) {
805
-			$user = \OC_User::getUser();
806
-			$uid = $user ? $user : null;
807
-			return new ClientService(
808
-				$c->getConfig(),
809
-				new \OC\Security\CertificateManager(
810
-					$uid,
811
-					new View(),
812
-					$c->getConfig(),
813
-					$c->getLogger(),
814
-					$c->getSecureRandom()
815
-				)
816
-			);
817
-		});
818
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
819
-		$this->registerService(IEventLogger::class, function (Server $c) {
820
-			$eventLogger = new EventLogger();
821
-			if ($c->getSystemConfig()->getValue('debug', false)) {
822
-				// In debug mode, module is being activated by default
823
-				$eventLogger->activate();
824
-			}
825
-			return $eventLogger;
826
-		});
827
-		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
828
-
829
-		$this->registerService(IQueryLogger::class, function (Server $c) {
830
-			$queryLogger = new QueryLogger();
831
-			if ($c->getSystemConfig()->getValue('debug', false)) {
832
-				// In debug mode, module is being activated by default
833
-				$queryLogger->activate();
834
-			}
835
-			return $queryLogger;
836
-		});
837
-		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
838
-
839
-		$this->registerService(TempManager::class, function (Server $c) {
840
-			return new TempManager(
841
-				$c->getLogger(),
842
-				$c->getConfig()
843
-			);
844
-		});
845
-		$this->registerDeprecatedAlias('TempManager', TempManager::class);
846
-		$this->registerAlias(ITempManager::class, TempManager::class);
847
-
848
-		$this->registerService(AppManager::class, function (Server $c) {
849
-			return new \OC\App\AppManager(
850
-				$c->getUserSession(),
851
-				$c->getConfig(),
852
-				$c->query(\OC\AppConfig::class),
853
-				$c->getGroupManager(),
854
-				$c->getMemCacheFactory(),
855
-				$c->getEventDispatcher(),
856
-				$c->getLogger()
857
-			);
858
-		});
859
-		$this->registerDeprecatedAlias('AppManager', AppManager::class);
860
-		$this->registerAlias(IAppManager::class, AppManager::class);
861
-
862
-		$this->registerService(IDateTimeZone::class, function (Server $c) {
863
-			return new DateTimeZone(
864
-				$c->getConfig(),
865
-				$c->getSession()
866
-			);
867
-		});
868
-		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869
-
870
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
871
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872
-
873
-			return new DateTimeFormatter(
874
-				$c->getDateTimeZone()->getTimeZone(),
875
-				$c->getL10N('lib', $language)
876
-			);
877
-		});
878
-		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
879
-
880
-		$this->registerService(IUserMountCache::class, function (Server $c) {
881
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
882
-			$listener = new UserMountCacheListener($mountCache);
883
-			$listener->listen($c->getUserManager());
884
-			return $mountCache;
885
-		});
886
-		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
887
-
888
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
889
-			$loader = \OC\Files\Filesystem::getLoader();
890
-			$mountCache = $c->query(IUserMountCache::class);
891
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
892
-
893
-			// builtin providers
894
-
895
-			$config = $c->getConfig();
896
-			$manager->registerProvider(new CacheMountProvider($config));
897
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
898
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
899
-
900
-			return $manager;
901
-		});
902
-		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
903
-
904
-		$this->registerService('IniWrapper', function ($c) {
905
-			return new IniGetWrapper();
906
-		});
907
-		$this->registerService('AsyncCommandBus', function (Server $c) {
908
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
909
-			if ($busClass) {
910
-				list($app, $class) = explode('::', $busClass, 2);
911
-				if ($c->getAppManager()->isInstalled($app)) {
912
-					\OC_App::loadApp($app);
913
-					return $c->query($class);
914
-				} else {
915
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
916
-				}
917
-			} else {
918
-				$jobList = $c->getJobList();
919
-				return new CronBus($jobList);
920
-			}
921
-		});
922
-		$this->registerService('TrustedDomainHelper', function ($c) {
923
-			return new TrustedDomainHelper($this->getConfig());
924
-		});
925
-		$this->registerService(Throttler::class, function (Server $c) {
926
-			return new Throttler(
927
-				$c->getDatabaseConnection(),
928
-				new TimeFactory(),
929
-				$c->getLogger(),
930
-				$c->getConfig()
931
-			);
932
-		});
933
-		$this->registerDeprecatedAlias('Throttler', Throttler::class);
934
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
935
-			// IConfig and IAppManager requires a working database. This code
936
-			// might however be called when ownCloud is not yet setup.
937
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
938
-				$config = $c->getConfig();
939
-				$appManager = $c->getAppManager();
940
-			} else {
941
-				$config = null;
942
-				$appManager = null;
943
-			}
944
-
945
-			return new Checker(
946
-				new EnvironmentHelper(),
947
-				new FileAccessHelper(),
948
-				new AppLocator(),
949
-				$config,
950
-				$c->getMemCacheFactory(),
951
-				$appManager,
952
-				$c->getTempManager(),
953
-				$c->getMimeTypeDetector()
954
-			);
955
-		});
956
-		$this->registerService(\OCP\IRequest::class, function ($c) {
957
-			if (isset($this['urlParams'])) {
958
-				$urlParams = $this['urlParams'];
959
-			} else {
960
-				$urlParams = [];
961
-			}
962
-
963
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
964
-				&& in_array('fakeinput', stream_get_wrappers())
965
-			) {
966
-				$stream = 'fakeinput://data';
967
-			} else {
968
-				$stream = 'php://input';
969
-			}
970
-
971
-			return new Request(
972
-				[
973
-					'get' => $_GET,
974
-					'post' => $_POST,
975
-					'files' => $_FILES,
976
-					'server' => $_SERVER,
977
-					'env' => $_ENV,
978
-					'cookies' => $_COOKIE,
979
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
980
-						? $_SERVER['REQUEST_METHOD']
981
-						: '',
982
-					'urlParams' => $urlParams,
983
-				],
984
-				$this->getSecureRandom(),
985
-				$this->getConfig(),
986
-				$this->getCsrfTokenManager(),
987
-				$stream
988
-			);
989
-		});
990
-		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
991
-
992
-		$this->registerService(IMailer::class, function (Server $c) {
993
-			return new Mailer(
994
-				$c->getConfig(),
995
-				$c->getLogger(),
996
-				$c->query(Defaults::class),
997
-				$c->getURLGenerator(),
998
-				$c->getL10N('lib'),
999
-				$c->query(IEventDispatcher::class)
1000
-			);
1001
-		});
1002
-		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1003
-
1004
-		$this->registerService('LDAPProvider', function (Server $c) {
1005
-			$config = $c->getConfig();
1006
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007
-			if (is_null($factoryClass)) {
1008
-				throw new \Exception('ldapProviderFactory not set');
1009
-			}
1010
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1011
-			$factory = new $factoryClass($this);
1012
-			return $factory->getLDAPProvider();
1013
-		});
1014
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1015
-			$ini = $c->getIniWrapper();
1016
-			$config = $c->getConfig();
1017
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1018
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1019
-				/** @var \OC\Memcache\Factory $memcacheFactory */
1020
-				$memcacheFactory = $c->getMemCacheFactory();
1021
-				$memcache = $memcacheFactory->createLocking('lock');
1022
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
1023
-					return new MemcacheLockingProvider($memcache, $ttl);
1024
-				}
1025
-				return new DBLockingProvider(
1026
-					$c->getDatabaseConnection(),
1027
-					$c->getLogger(),
1028
-					new TimeFactory(),
1029
-					$ttl,
1030
-					!\OC::$CLI
1031
-				);
1032
-			}
1033
-			return new NoopLockingProvider();
1034
-		});
1035
-		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1036
-
1037
-		$this->registerService(IMountManager::class, function () {
1038
-			return new \OC\Files\Mount\Manager();
1039
-		});
1040
-		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041
-
1042
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1043
-			return new \OC\Files\Type\Detection(
1044
-				$c->getURLGenerator(),
1045
-				$c->getLogger(),
1046
-				\OC::$configDir,
1047
-				\OC::$SERVERROOT . '/resources/config/'
1048
-			);
1049
-		});
1050
-		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1051
-
1052
-		$this->registerService(IMimeTypeLoader::class, function (Server $c) {
1053
-			return new \OC\Files\Type\Loader(
1054
-				$c->getDatabaseConnection()
1055
-			);
1056
-		});
1057
-		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1058
-		$this->registerService(BundleFetcher::class, function () {
1059
-			return new BundleFetcher($this->getL10N('lib'));
1060
-		});
1061
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1062
-			return new Manager(
1063
-				$c->query(IValidator::class),
1064
-				$c->getLogger()
1065
-			);
1066
-		});
1067
-		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1068
-
1069
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1070
-			$manager = new CapabilitiesManager($c->getLogger());
1071
-			$manager->registerCapability(function () use ($c) {
1072
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
1073
-			});
1074
-			$manager->registerCapability(function () use ($c) {
1075
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1076
-			});
1077
-			return $manager;
1078
-		});
1079
-		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1080
-
1081
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1082
-			$config = $c->getConfig();
1083
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1084
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1085
-			$factory = new $factoryClass($this);
1086
-			$manager = $factory->getManager();
1087
-
1088
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1089
-				$manager = $c->getUserManager();
1090
-				$user = $manager->get($id);
1091
-				if(is_null($user)) {
1092
-					$l = $c->getL10N('core');
1093
-					$displayName = $l->t('Unknown user');
1094
-				} else {
1095
-					$displayName = $user->getDisplayName();
1096
-				}
1097
-				return $displayName;
1098
-			});
1099
-
1100
-			return $manager;
1101
-		});
1102
-		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1103
-
1104
-		$this->registerService('ThemingDefaults', function (Server $c) {
1105
-			/*
245
+    /** @var string */
246
+    private $webRoot;
247
+
248
+    /**
249
+     * @param string $webRoot
250
+     * @param \OC\Config $config
251
+     */
252
+    public function __construct($webRoot, \OC\Config $config) {
253
+        parent::__construct();
254
+        $this->webRoot = $webRoot;
255
+
256
+        // To find out if we are running from CLI or not
257
+        $this->registerParameter('isCLI', \OC::$CLI);
258
+
259
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
260
+            return $c;
261
+        });
262
+
263
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
264
+        $this->registerDeprecatedAlias('CalendarManager', \OC\Calendar\Manager::class);
265
+
266
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
267
+        $this->registerDeprecatedAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
268
+
269
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
270
+        $this->registerDeprecatedAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
271
+
272
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
273
+        $this->registerDeprecatedAlias('ContactsManager', \OCP\Contacts\IManager::class);
274
+
275
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
276
+
277
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
278
+
279
+
280
+        $this->registerService(IPreview::class, function (Server $c) {
281
+            return new PreviewManager(
282
+                $c->getConfig(),
283
+                $c->getRootFolder(),
284
+                $c->getAppDataDir('preview'),
285
+                $c->getEventDispatcher(),
286
+                $c->getGeneratorHelper(),
287
+                $c->getSession()->get('user_id')
288
+            );
289
+        });
290
+        $this->registerDeprecatedAlias('PreviewManager', IPreview::class);
291
+
292
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
293
+            return new \OC\Preview\Watcher(
294
+                $c->getAppDataDir('preview')
295
+            );
296
+        });
297
+
298
+        $this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
299
+            $view = new View();
300
+            $util = new Encryption\Util(
301
+                $view,
302
+                $c->getUserManager(),
303
+                $c->getGroupManager(),
304
+                $c->getConfig()
305
+            );
306
+            return new Encryption\Manager(
307
+                $c->getConfig(),
308
+                $c->getLogger(),
309
+                $c->getL10N('core'),
310
+                new View(),
311
+                $util,
312
+                new ArrayCache()
313
+            );
314
+        });
315
+        $this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
316
+
317
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
318
+            $util = new Encryption\Util(
319
+                new View(),
320
+                $c->getUserManager(),
321
+                $c->getGroupManager(),
322
+                $c->getConfig()
323
+            );
324
+            return new Encryption\File(
325
+                $util,
326
+                $c->getRootFolder(),
327
+                $c->getShareManager()
328
+            );
329
+        });
330
+
331
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
332
+            $view = new View();
333
+            $util = new Encryption\Util(
334
+                $view,
335
+                $c->getUserManager(),
336
+                $c->getGroupManager(),
337
+                $c->getConfig()
338
+            );
339
+
340
+            return new Encryption\Keys\Storage($view, $util);
341
+        });
342
+        $this->registerService('TagMapper', function (Server $c) {
343
+            return new TagMapper($c->getDatabaseConnection());
344
+        });
345
+
346
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
347
+            $tagMapper = $c->query('TagMapper');
348
+            return new TagManager($tagMapper, $c->getUserSession());
349
+        });
350
+        $this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
351
+
352
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
353
+            $config = $c->getConfig();
354
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
355
+            return new $factoryClass($this);
356
+        });
357
+        $this->registerService(ISystemTagManager::class, function (Server $c) {
358
+            return $c->query('SystemTagManagerFactory')->getManager();
359
+        });
360
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
361
+
362
+        $this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
363
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
364
+        });
365
+        $this->registerService('RootFolder', function (Server $c) {
366
+            $manager = \OC\Files\Filesystem::getMountManager(null);
367
+            $view = new View();
368
+            $root = new Root(
369
+                $manager,
370
+                $view,
371
+                null,
372
+                $c->getUserMountCache(),
373
+                $this->getLogger(),
374
+                $this->getUserManager()
375
+            );
376
+            $connector = new HookConnector($root, $view, $c->getEventDispatcher());
377
+            $connector->viewToNode();
378
+
379
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
380
+            $previewConnector->connectWatcher();
381
+
382
+            return $root;
383
+        });
384
+        $this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
385
+
386
+        $this->registerService(IRootFolder::class, function (Server $c) {
387
+            return new LazyRoot(function () use ($c) {
388
+                return $c->query('RootFolder');
389
+            });
390
+        });
391
+        $this->registerDeprecatedAlias('LazyRootFolder', IRootFolder::class);
392
+
393
+        $this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
394
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
395
+
396
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
397
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
398
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
399
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
400
+
401
+                /** @var IEventDispatcher $dispatcher */
402
+                $dispatcher = $this->query(IEventDispatcher::class);
403
+                $dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
404
+            });
405
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
406
+                \OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
407
+
408
+                /** @var IEventDispatcher $dispatcher */
409
+                $dispatcher = $this->query(IEventDispatcher::class);
410
+                $dispatcher->dispatchTyped(new GroupCreatedEvent($group));
411
+            });
412
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
413
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
414
+
415
+                /** @var IEventDispatcher $dispatcher */
416
+                $dispatcher = $this->query(IEventDispatcher::class);
417
+                $dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
418
+            });
419
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
420
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
421
+
422
+                /** @var IEventDispatcher $dispatcher */
423
+                $dispatcher = $this->query(IEventDispatcher::class);
424
+                $dispatcher->dispatchTyped(new GroupDeletedEvent($group));
425
+            });
426
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
427
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
428
+
429
+                /** @var IEventDispatcher $dispatcher */
430
+                $dispatcher = $this->query(IEventDispatcher::class);
431
+                $dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
432
+            });
433
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
434
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
435
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
436
+                \OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
437
+
438
+                /** @var IEventDispatcher $dispatcher */
439
+                $dispatcher = $this->query(IEventDispatcher::class);
440
+                $dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
441
+            });
442
+            $groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
443
+                /** @var IEventDispatcher $dispatcher */
444
+                $dispatcher = $this->query(IEventDispatcher::class);
445
+                $dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
446
+            });
447
+            $groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
448
+                /** @var IEventDispatcher $dispatcher */
449
+                $dispatcher = $this->query(IEventDispatcher::class);
450
+                $dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
451
+            });
452
+            return $groupManager;
453
+        });
454
+        $this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
455
+
456
+        $this->registerService(Store::class, function (Server $c) {
457
+            $session = $c->getSession();
458
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
459
+                $tokenProvider = $c->query(IProvider::class);
460
+            } else {
461
+                $tokenProvider = null;
462
+            }
463
+            $logger = $c->getLogger();
464
+            return new Store($session, $logger, $tokenProvider);
465
+        });
466
+        $this->registerAlias(IStore::class, Store::class);
467
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
468
+            $dbConnection = $c->getDatabaseConnection();
469
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
470
+        });
471
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
472
+
473
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
474
+            $manager = $c->getUserManager();
475
+            $session = new \OC\Session\Memory('');
476
+            $timeFactory = new TimeFactory();
477
+            // Token providers might require a working database. This code
478
+            // might however be called when ownCloud is not yet setup.
479
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
480
+                $defaultTokenProvider = $c->query(IProvider::class);
481
+            } else {
482
+                $defaultTokenProvider = null;
483
+            }
484
+
485
+            $legacyDispatcher = $c->getEventDispatcher();
486
+
487
+            $userSession = new \OC\User\Session(
488
+                $manager,
489
+                $session,
490
+                $timeFactory,
491
+                $defaultTokenProvider,
492
+                $c->getConfig(),
493
+                $c->getSecureRandom(),
494
+                $c->getLockdownManager(),
495
+                $c->getLogger(),
496
+                $c->query(IEventDispatcher::class)
497
+            );
498
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
499
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
500
+
501
+                /** @var IEventDispatcher $dispatcher */
502
+                $dispatcher = $this->query(IEventDispatcher::class);
503
+                $dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
504
+            });
505
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
506
+                /** @var $user \OC\User\User */
507
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
508
+
509
+                /** @var IEventDispatcher $dispatcher */
510
+                $dispatcher = $this->query(IEventDispatcher::class);
511
+                $dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
512
+            });
513
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
514
+                /** @var $user \OC\User\User */
515
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
516
+                $legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
517
+
518
+                /** @var IEventDispatcher $dispatcher */
519
+                $dispatcher = $this->query(IEventDispatcher::class);
520
+                $dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
521
+            });
522
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
523
+                /** @var $user \OC\User\User */
524
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
525
+
526
+                /** @var IEventDispatcher $dispatcher */
527
+                $dispatcher = $this->query(IEventDispatcher::class);
528
+                $dispatcher->dispatchTyped(new UserDeletedEvent($user));
529
+            });
530
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
531
+                /** @var $user \OC\User\User */
532
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
533
+
534
+                /** @var IEventDispatcher $dispatcher */
535
+                $dispatcher = $this->query(IEventDispatcher::class);
536
+                $dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
537
+            });
538
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
539
+                /** @var $user \OC\User\User */
540
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
541
+
542
+                /** @var IEventDispatcher $dispatcher */
543
+                $dispatcher = $this->query(IEventDispatcher::class);
544
+                $dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
545
+            });
546
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
547
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
548
+
549
+                /** @var IEventDispatcher $dispatcher */
550
+                $dispatcher = $this->query(IEventDispatcher::class);
551
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
552
+            });
553
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
554
+                /** @var $user \OC\User\User */
555
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
556
+
557
+                /** @var IEventDispatcher $dispatcher */
558
+                $dispatcher = $this->query(IEventDispatcher::class);
559
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
560
+            });
561
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
562
+                /** @var IEventDispatcher $dispatcher */
563
+                $dispatcher = $this->query(IEventDispatcher::class);
564
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
565
+            });
566
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
567
+                /** @var $user \OC\User\User */
568
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
569
+
570
+                /** @var IEventDispatcher $dispatcher */
571
+                $dispatcher = $this->query(IEventDispatcher::class);
572
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
573
+            });
574
+            $userSession->listen('\OC\User', 'logout', function ($user) {
575
+                \OC_Hook::emit('OC_User', 'logout', []);
576
+
577
+                /** @var IEventDispatcher $dispatcher */
578
+                $dispatcher = $this->query(IEventDispatcher::class);
579
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
580
+            });
581
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
582
+                /** @var IEventDispatcher $dispatcher */
583
+                $dispatcher = $this->query(IEventDispatcher::class);
584
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
585
+            });
586
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
587
+                /** @var $user \OC\User\User */
588
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
589
+
590
+                /** @var IEventDispatcher $dispatcher */
591
+                $dispatcher = $this->query(IEventDispatcher::class);
592
+                $dispatcher->dispatchTyped(new UserChangedEvent($user, $feature, $value, $oldValue));
593
+            });
594
+            return $userSession;
595
+        });
596
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
597
+        $this->registerDeprecatedAlias('UserSession', \OC\User\Session::class);
598
+
599
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
600
+
601
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
602
+        $this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
603
+
604
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
605
+            return new \OC\AllConfig(
606
+                $c->getSystemConfig()
607
+            );
608
+        });
609
+        $this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
610
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
611
+
612
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
613
+            return new \OC\SystemConfig($config);
614
+        });
615
+        $this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
616
+
617
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
618
+            return new \OC\AppConfig($c->getDatabaseConnection());
619
+        });
620
+        $this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
621
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
622
+
623
+        $this->registerService(IFactory::class, function (Server $c) {
624
+            return new \OC\L10N\Factory(
625
+                $c->getConfig(),
626
+                $c->getRequest(),
627
+                $c->getUserSession(),
628
+                \OC::$SERVERROOT
629
+            );
630
+        });
631
+        $this->registerDeprecatedAlias('L10NFactory', IFactory::class);
632
+
633
+        $this->registerService(IURLGenerator::class, function (Server $c) {
634
+            $config = $c->getConfig();
635
+            $cacheFactory = $c->getMemCacheFactory();
636
+            $request = $c->getRequest();
637
+            return new \OC\URLGenerator(
638
+                $config,
639
+                $cacheFactory,
640
+                $request
641
+            );
642
+        });
643
+        $this->registerDeprecatedAlias('URLGenerator', IURLGenerator::class);
644
+
645
+        $this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
646
+        $this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
647
+
648
+        $this->registerService(ICache::class, function ($c) {
649
+            return new Cache\File();
650
+        });
651
+        $this->registerDeprecatedAlias('UserCache', ICache::class);
652
+
653
+        $this->registerService(Factory::class, function (Server $c) {
654
+
655
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
656
+                ArrayCache::class,
657
+                ArrayCache::class,
658
+                ArrayCache::class
659
+            );
660
+            $config = $c->getConfig();
661
+
662
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
663
+                $v = \OC_App::getAppVersions();
664
+                $v['core'] = implode(',', \OC_Util::getVersion());
665
+                $version = implode(',', $v);
666
+                $instanceId = \OC_Util::getInstanceId();
667
+                $path = \OC::$SERVERROOT;
668
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
669
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
670
+                    $config->getSystemValue('memcache.local', null),
671
+                    $config->getSystemValue('memcache.distributed', null),
672
+                    $config->getSystemValue('memcache.locking', null)
673
+                );
674
+            }
675
+            return $arrayCacheFactory;
676
+
677
+        });
678
+        $this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
679
+        $this->registerAlias(ICacheFactory::class, Factory::class);
680
+
681
+        $this->registerService('RedisFactory', function (Server $c) {
682
+            $systemConfig = $c->getSystemConfig();
683
+            return new RedisFactory($systemConfig);
684
+        });
685
+
686
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
687
+            return new \OC\Activity\Manager(
688
+                $c->getRequest(),
689
+                $c->getUserSession(),
690
+                $c->getConfig(),
691
+                $c->query(IValidator::class)
692
+            );
693
+        });
694
+        $this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
695
+
696
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
697
+            return new \OC\Activity\EventMerger(
698
+                $c->getL10N('lib')
699
+            );
700
+        });
701
+        $this->registerAlias(IValidator::class, Validator::class);
702
+
703
+        $this->registerService(AvatarManager::class, function (Server $c) {
704
+            return new AvatarManager(
705
+                $c->query(\OC\User\Manager::class),
706
+                $c->getAppDataDir('avatar'),
707
+                $c->getL10N('lib'),
708
+                $c->getLogger(),
709
+                $c->getConfig()
710
+            );
711
+        });
712
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
713
+        $this->registerDeprecatedAlias('AvatarManager', AvatarManager::class);
714
+
715
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
716
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
717
+
718
+        $this->registerService(\OC\Log::class, function (Server $c) {
719
+            $logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
720
+            $factory = new LogFactory($c, $this->getSystemConfig());
721
+            $logger = $factory->get($logType);
722
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
723
+
724
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
725
+        });
726
+        $this->registerAlias(ILogger::class, \OC\Log::class);
727
+        $this->registerDeprecatedAlias('Logger', \OC\Log::class);
728
+        // PSR-3 logger
729
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
730
+
731
+        $this->registerService(ILogFactory::class, function (Server $c) {
732
+            return new LogFactory($c, $this->getSystemConfig());
733
+        });
734
+
735
+        $this->registerService(IJobList::class, function (Server $c) {
736
+            $config = $c->getConfig();
737
+            return new \OC\BackgroundJob\JobList(
738
+                $c->getDatabaseConnection(),
739
+                $config,
740
+                new TimeFactory()
741
+            );
742
+        });
743
+        $this->registerDeprecatedAlias('JobList', IJobList::class);
744
+
745
+        $this->registerService(IRouter::class, function (Server $c) {
746
+            $cacheFactory = $c->getMemCacheFactory();
747
+            $logger = $c->getLogger();
748
+            if ($cacheFactory->isLocalCacheAvailable()) {
749
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
750
+            } else {
751
+                $router = new \OC\Route\Router($logger);
752
+            }
753
+            return $router;
754
+        });
755
+        $this->registerDeprecatedAlias('Router', IRouter::class);
756
+
757
+        $this->registerService(ISearch::class, function ($c) {
758
+            return new Search();
759
+        });
760
+        $this->registerDeprecatedAlias('Search', ISearch::class);
761
+
762
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
763
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
764
+                $this->getMemCacheFactory(),
765
+                new \OC\AppFramework\Utility\TimeFactory()
766
+            );
767
+        });
768
+
769
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
770
+            return new SecureRandom();
771
+        });
772
+        $this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
773
+
774
+        $this->registerService(ICrypto::class, function (Server $c) {
775
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
776
+        });
777
+        $this->registerDeprecatedAlias('Crypto', ICrypto::class);
778
+
779
+        $this->registerService(IHasher::class, function (Server $c) {
780
+            return new Hasher($c->getConfig());
781
+        });
782
+        $this->registerDeprecatedAlias('Hasher', IHasher::class);
783
+
784
+        $this->registerService(ICredentialsManager::class, function (Server $c) {
785
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
786
+        });
787
+        $this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
788
+
789
+        $this->registerService(IDBConnection::class, function (Server $c) {
790
+            $systemConfig = $c->getSystemConfig();
791
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
792
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
793
+            if (!$factory->isValidType($type)) {
794
+                throw new \OC\DatabaseException('Invalid database type');
795
+            }
796
+            $connectionParams = $factory->createConnectionParams();
797
+            $connection = $factory->getConnection($type, $connectionParams);
798
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
799
+            return $connection;
800
+        });
801
+        $this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
802
+
803
+
804
+        $this->registerService(IClientService::class, function (Server $c) {
805
+            $user = \OC_User::getUser();
806
+            $uid = $user ? $user : null;
807
+            return new ClientService(
808
+                $c->getConfig(),
809
+                new \OC\Security\CertificateManager(
810
+                    $uid,
811
+                    new View(),
812
+                    $c->getConfig(),
813
+                    $c->getLogger(),
814
+                    $c->getSecureRandom()
815
+                )
816
+            );
817
+        });
818
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
819
+        $this->registerService(IEventLogger::class, function (Server $c) {
820
+            $eventLogger = new EventLogger();
821
+            if ($c->getSystemConfig()->getValue('debug', false)) {
822
+                // In debug mode, module is being activated by default
823
+                $eventLogger->activate();
824
+            }
825
+            return $eventLogger;
826
+        });
827
+        $this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
828
+
829
+        $this->registerService(IQueryLogger::class, function (Server $c) {
830
+            $queryLogger = new QueryLogger();
831
+            if ($c->getSystemConfig()->getValue('debug', false)) {
832
+                // In debug mode, module is being activated by default
833
+                $queryLogger->activate();
834
+            }
835
+            return $queryLogger;
836
+        });
837
+        $this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
838
+
839
+        $this->registerService(TempManager::class, function (Server $c) {
840
+            return new TempManager(
841
+                $c->getLogger(),
842
+                $c->getConfig()
843
+            );
844
+        });
845
+        $this->registerDeprecatedAlias('TempManager', TempManager::class);
846
+        $this->registerAlias(ITempManager::class, TempManager::class);
847
+
848
+        $this->registerService(AppManager::class, function (Server $c) {
849
+            return new \OC\App\AppManager(
850
+                $c->getUserSession(),
851
+                $c->getConfig(),
852
+                $c->query(\OC\AppConfig::class),
853
+                $c->getGroupManager(),
854
+                $c->getMemCacheFactory(),
855
+                $c->getEventDispatcher(),
856
+                $c->getLogger()
857
+            );
858
+        });
859
+        $this->registerDeprecatedAlias('AppManager', AppManager::class);
860
+        $this->registerAlias(IAppManager::class, AppManager::class);
861
+
862
+        $this->registerService(IDateTimeZone::class, function (Server $c) {
863
+            return new DateTimeZone(
864
+                $c->getConfig(),
865
+                $c->getSession()
866
+            );
867
+        });
868
+        $this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869
+
870
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
871
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872
+
873
+            return new DateTimeFormatter(
874
+                $c->getDateTimeZone()->getTimeZone(),
875
+                $c->getL10N('lib', $language)
876
+            );
877
+        });
878
+        $this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
879
+
880
+        $this->registerService(IUserMountCache::class, function (Server $c) {
881
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
882
+            $listener = new UserMountCacheListener($mountCache);
883
+            $listener->listen($c->getUserManager());
884
+            return $mountCache;
885
+        });
886
+        $this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
887
+
888
+        $this->registerService(IMountProviderCollection::class, function (Server $c) {
889
+            $loader = \OC\Files\Filesystem::getLoader();
890
+            $mountCache = $c->query(IUserMountCache::class);
891
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
892
+
893
+            // builtin providers
894
+
895
+            $config = $c->getConfig();
896
+            $manager->registerProvider(new CacheMountProvider($config));
897
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
898
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
899
+
900
+            return $manager;
901
+        });
902
+        $this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
903
+
904
+        $this->registerService('IniWrapper', function ($c) {
905
+            return new IniGetWrapper();
906
+        });
907
+        $this->registerService('AsyncCommandBus', function (Server $c) {
908
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
909
+            if ($busClass) {
910
+                list($app, $class) = explode('::', $busClass, 2);
911
+                if ($c->getAppManager()->isInstalled($app)) {
912
+                    \OC_App::loadApp($app);
913
+                    return $c->query($class);
914
+                } else {
915
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
916
+                }
917
+            } else {
918
+                $jobList = $c->getJobList();
919
+                return new CronBus($jobList);
920
+            }
921
+        });
922
+        $this->registerService('TrustedDomainHelper', function ($c) {
923
+            return new TrustedDomainHelper($this->getConfig());
924
+        });
925
+        $this->registerService(Throttler::class, function (Server $c) {
926
+            return new Throttler(
927
+                $c->getDatabaseConnection(),
928
+                new TimeFactory(),
929
+                $c->getLogger(),
930
+                $c->getConfig()
931
+            );
932
+        });
933
+        $this->registerDeprecatedAlias('Throttler', Throttler::class);
934
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
935
+            // IConfig and IAppManager requires a working database. This code
936
+            // might however be called when ownCloud is not yet setup.
937
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
938
+                $config = $c->getConfig();
939
+                $appManager = $c->getAppManager();
940
+            } else {
941
+                $config = null;
942
+                $appManager = null;
943
+            }
944
+
945
+            return new Checker(
946
+                new EnvironmentHelper(),
947
+                new FileAccessHelper(),
948
+                new AppLocator(),
949
+                $config,
950
+                $c->getMemCacheFactory(),
951
+                $appManager,
952
+                $c->getTempManager(),
953
+                $c->getMimeTypeDetector()
954
+            );
955
+        });
956
+        $this->registerService(\OCP\IRequest::class, function ($c) {
957
+            if (isset($this['urlParams'])) {
958
+                $urlParams = $this['urlParams'];
959
+            } else {
960
+                $urlParams = [];
961
+            }
962
+
963
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
964
+                && in_array('fakeinput', stream_get_wrappers())
965
+            ) {
966
+                $stream = 'fakeinput://data';
967
+            } else {
968
+                $stream = 'php://input';
969
+            }
970
+
971
+            return new Request(
972
+                [
973
+                    'get' => $_GET,
974
+                    'post' => $_POST,
975
+                    'files' => $_FILES,
976
+                    'server' => $_SERVER,
977
+                    'env' => $_ENV,
978
+                    'cookies' => $_COOKIE,
979
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
980
+                        ? $_SERVER['REQUEST_METHOD']
981
+                        : '',
982
+                    'urlParams' => $urlParams,
983
+                ],
984
+                $this->getSecureRandom(),
985
+                $this->getConfig(),
986
+                $this->getCsrfTokenManager(),
987
+                $stream
988
+            );
989
+        });
990
+        $this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
991
+
992
+        $this->registerService(IMailer::class, function (Server $c) {
993
+            return new Mailer(
994
+                $c->getConfig(),
995
+                $c->getLogger(),
996
+                $c->query(Defaults::class),
997
+                $c->getURLGenerator(),
998
+                $c->getL10N('lib'),
999
+                $c->query(IEventDispatcher::class)
1000
+            );
1001
+        });
1002
+        $this->registerDeprecatedAlias('Mailer', IMailer::class);
1003
+
1004
+        $this->registerService('LDAPProvider', function (Server $c) {
1005
+            $config = $c->getConfig();
1006
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007
+            if (is_null($factoryClass)) {
1008
+                throw new \Exception('ldapProviderFactory not set');
1009
+            }
1010
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
1011
+            $factory = new $factoryClass($this);
1012
+            return $factory->getLDAPProvider();
1013
+        });
1014
+        $this->registerService(ILockingProvider::class, function (Server $c) {
1015
+            $ini = $c->getIniWrapper();
1016
+            $config = $c->getConfig();
1017
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
1018
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
1019
+                /** @var \OC\Memcache\Factory $memcacheFactory */
1020
+                $memcacheFactory = $c->getMemCacheFactory();
1021
+                $memcache = $memcacheFactory->createLocking('lock');
1022
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
1023
+                    return new MemcacheLockingProvider($memcache, $ttl);
1024
+                }
1025
+                return new DBLockingProvider(
1026
+                    $c->getDatabaseConnection(),
1027
+                    $c->getLogger(),
1028
+                    new TimeFactory(),
1029
+                    $ttl,
1030
+                    !\OC::$CLI
1031
+                );
1032
+            }
1033
+            return new NoopLockingProvider();
1034
+        });
1035
+        $this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1036
+
1037
+        $this->registerService(IMountManager::class, function () {
1038
+            return new \OC\Files\Mount\Manager();
1039
+        });
1040
+        $this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041
+
1042
+        $this->registerService(IMimeTypeDetector::class, function (Server $c) {
1043
+            return new \OC\Files\Type\Detection(
1044
+                $c->getURLGenerator(),
1045
+                $c->getLogger(),
1046
+                \OC::$configDir,
1047
+                \OC::$SERVERROOT . '/resources/config/'
1048
+            );
1049
+        });
1050
+        $this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1051
+
1052
+        $this->registerService(IMimeTypeLoader::class, function (Server $c) {
1053
+            return new \OC\Files\Type\Loader(
1054
+                $c->getDatabaseConnection()
1055
+            );
1056
+        });
1057
+        $this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1058
+        $this->registerService(BundleFetcher::class, function () {
1059
+            return new BundleFetcher($this->getL10N('lib'));
1060
+        });
1061
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1062
+            return new Manager(
1063
+                $c->query(IValidator::class),
1064
+                $c->getLogger()
1065
+            );
1066
+        });
1067
+        $this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1068
+
1069
+        $this->registerService(CapabilitiesManager::class, function (Server $c) {
1070
+            $manager = new CapabilitiesManager($c->getLogger());
1071
+            $manager->registerCapability(function () use ($c) {
1072
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
1073
+            });
1074
+            $manager->registerCapability(function () use ($c) {
1075
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1076
+            });
1077
+            return $manager;
1078
+        });
1079
+        $this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1080
+
1081
+        $this->registerService(ICommentsManager::class, function (Server $c) {
1082
+            $config = $c->getConfig();
1083
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1084
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
1085
+            $factory = new $factoryClass($this);
1086
+            $manager = $factory->getManager();
1087
+
1088
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1089
+                $manager = $c->getUserManager();
1090
+                $user = $manager->get($id);
1091
+                if(is_null($user)) {
1092
+                    $l = $c->getL10N('core');
1093
+                    $displayName = $l->t('Unknown user');
1094
+                } else {
1095
+                    $displayName = $user->getDisplayName();
1096
+                }
1097
+                return $displayName;
1098
+            });
1099
+
1100
+            return $manager;
1101
+        });
1102
+        $this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1103
+
1104
+        $this->registerService('ThemingDefaults', function (Server $c) {
1105
+            /*
1106 1106
 			 * Dark magic for autoloader.
1107 1107
 			 * If we do a class_exists it will try to load the class which will
1108 1108
 			 * make composer cache the result. Resulting in errors when enabling
1109 1109
 			 * the theming app.
1110 1110
 			 */
1111
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1112
-			if (isset($prefixes['OCA\\Theming\\'])) {
1113
-				$classExists = true;
1114
-			} else {
1115
-				$classExists = false;
1116
-			}
1117
-
1118
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1119
-				return new ThemingDefaults(
1120
-					$c->getConfig(),
1121
-					$c->getL10N('theming'),
1122
-					$c->getURLGenerator(),
1123
-					$c->getMemCacheFactory(),
1124
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1125
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1126
-					$c->getAppManager(),
1127
-					$c->getNavigationManager()
1128
-				);
1129
-			}
1130
-			return new \OC_Defaults();
1131
-		});
1132
-		$this->registerService(SCSSCacher::class, function (Server $c) {
1133
-			return new SCSSCacher(
1134
-				$c->getLogger(),
1135
-				$c->query(\OC\Files\AppData\Factory::class),
1136
-				$c->getURLGenerator(),
1137
-				$c->getConfig(),
1138
-				$c->getThemingDefaults(),
1139
-				\OC::$SERVERROOT,
1140
-				$this->getMemCacheFactory(),
1141
-				$c->query(IconsCacher::class),
1142
-				new TimeFactory()
1143
-			);
1144
-		});
1145
-		$this->registerService(JSCombiner::class, function (Server $c) {
1146
-			return new JSCombiner(
1147
-				$c->getAppDataDir('js'),
1148
-				$c->getURLGenerator(),
1149
-				$this->getMemCacheFactory(),
1150
-				$c->getSystemConfig(),
1151
-				$c->getLogger()
1152
-			);
1153
-		});
1154
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1155
-		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1156
-		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1157
-
1158
-		$this->registerService('CryptoWrapper', function (Server $c) {
1159
-			// FIXME: Instantiiated here due to cyclic dependency
1160
-			$request = new Request(
1161
-				[
1162
-					'get' => $_GET,
1163
-					'post' => $_POST,
1164
-					'files' => $_FILES,
1165
-					'server' => $_SERVER,
1166
-					'env' => $_ENV,
1167
-					'cookies' => $_COOKIE,
1168
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1169
-						? $_SERVER['REQUEST_METHOD']
1170
-						: null,
1171
-				],
1172
-				$c->getSecureRandom(),
1173
-				$c->getConfig()
1174
-			);
1175
-
1176
-			return new CryptoWrapper(
1177
-				$c->getConfig(),
1178
-				$c->getCrypto(),
1179
-				$c->getSecureRandom(),
1180
-				$request
1181
-			);
1182
-		});
1183
-		$this->registerService(CsrfTokenManager::class, function (Server $c) {
1184
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1185
-
1186
-			return new CsrfTokenManager(
1187
-				$tokenGenerator,
1188
-				$c->query(SessionStorage::class)
1189
-			);
1190
-		});
1191
-		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1192
-		$this->registerService(SessionStorage::class, function (Server $c) {
1193
-			return new SessionStorage($c->getSession());
1194
-		});
1195
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1196
-		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1197
-
1198
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1199
-			return new ContentSecurityPolicyNonceManager(
1200
-				$c->getCsrfTokenManager(),
1201
-				$c->getRequest()
1202
-			);
1203
-		});
1204
-
1205
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1206
-			$config = $c->getConfig();
1207
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1208
-			/** @var \OCP\Share\IProviderFactory $factory */
1209
-			$factory = new $factoryClass($this);
1210
-
1211
-			$manager = new \OC\Share20\Manager(
1212
-				$c->getLogger(),
1213
-				$c->getConfig(),
1214
-				$c->getSecureRandom(),
1215
-				$c->getHasher(),
1216
-				$c->getMountManager(),
1217
-				$c->getGroupManager(),
1218
-				$c->getL10N('lib'),
1219
-				$c->getL10NFactory(),
1220
-				$factory,
1221
-				$c->getUserManager(),
1222
-				$c->getLazyRootFolder(),
1223
-				$c->getEventDispatcher(),
1224
-				$c->getMailer(),
1225
-				$c->getURLGenerator(),
1226
-				$c->getThemingDefaults(),
1227
-				$c->query(IEventDispatcher::class)
1228
-			);
1229
-
1230
-			return $manager;
1231
-		});
1232
-		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1233
-
1234
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1235
-			$instance = new Collaboration\Collaborators\Search($c);
1236
-
1237
-			// register default plugins
1238
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1239
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1240
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1241
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1242
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1243
-
1244
-			return $instance;
1245
-		});
1246
-		$this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1247
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1248
-
1249
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1250
-
1251
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1252
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1253
-
1254
-		$this->registerService('SettingsManager', function (Server $c) {
1255
-			$manager = new \OC\Settings\Manager(
1256
-				$c->getLogger(),
1257
-				$c->getL10NFactory(),
1258
-				$c->getURLGenerator(),
1259
-				$c
1260
-			);
1261
-			return $manager;
1262
-		});
1263
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1264
-			return new \OC\Files\AppData\Factory(
1265
-				$c->getRootFolder(),
1266
-				$c->getSystemConfig()
1267
-			);
1268
-		});
1269
-
1270
-		$this->registerService('LockdownManager', function (Server $c) {
1271
-			return new LockdownManager(function () use ($c) {
1272
-				return $c->getSession();
1273
-			});
1274
-		});
1275
-
1276
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1277
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1278
-		});
1279
-
1280
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1281
-			return new CloudIdManager();
1282
-		});
1283
-
1284
-		$this->registerService(IConfig::class, function (Server $c) {
1285
-			return new GlobalScale\Config($c->getConfig());
1286
-		});
1287
-
1288
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1289
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1290
-		});
1291
-
1292
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1293
-			return new CloudFederationFactory();
1294
-		});
1295
-
1296
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1297
-		$this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1298
-
1299
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1300
-		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1301
-
1302
-		$this->registerService(Defaults::class, function (Server $c) {
1303
-			return new Defaults(
1304
-				$c->getThemingDefaults()
1305
-			);
1306
-		});
1307
-		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1308
-
1309
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1310
-			return $c->query(\OCP\IUserSession::class)->getSession();
1311
-		});
1312
-
1313
-		$this->registerService(IShareHelper::class, function (Server $c) {
1314
-			return new ShareHelper(
1315
-				$c->query(\OCP\Share\IManager::class)
1316
-			);
1317
-		});
1318
-
1319
-		$this->registerService(Installer::class, function (Server $c) {
1320
-			return new Installer(
1321
-				$c->getAppFetcher(),
1322
-				$c->getHTTPClientService(),
1323
-				$c->getTempManager(),
1324
-				$c->getLogger(),
1325
-				$c->getConfig(),
1326
-				\OC::$CLI
1327
-			);
1328
-		});
1329
-
1330
-		$this->registerService(IApiFactory::class, function (Server $c) {
1331
-			return new ApiFactory($c->getHTTPClientService());
1332
-		});
1333
-
1334
-		$this->registerService(IInstanceFactory::class, function (Server $c) {
1335
-			$memcacheFactory = $c->getMemCacheFactory();
1336
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1337
-		});
1338
-
1339
-		$this->registerService(IContactsStore::class, function (Server $c) {
1340
-			return new ContactsStore(
1341
-				$c->getContactsManager(),
1342
-				$c->getConfig(),
1343
-				$c->getUserManager(),
1344
-				$c->getGroupManager()
1345
-			);
1346
-		});
1347
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1348
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1349
-
1350
-		$this->registerService(IStorageFactory::class, function () {
1351
-			return new StorageFactory();
1352
-		});
1353
-
1354
-		$this->registerAlias(IDashboardManager::class, DashboardManager::class);
1355
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1356
-
1357
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1358
-
1359
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1360
-
1361
-		$this->connectDispatcher();
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OCP\Calendar\IManager
1366
-	 */
1367
-	public function getCalendarManager() {
1368
-		return $this->query(\OC\Calendar\Manager::class);
1369
-	}
1370
-
1371
-	/**
1372
-	 * @return \OCP\Calendar\Resource\IManager
1373
-	 */
1374
-	public function getCalendarResourceBackendManager() {
1375
-		return $this->query(\OC\Calendar\Resource\Manager::class);
1376
-	}
1377
-
1378
-	/**
1379
-	 * @return \OCP\Calendar\Room\IManager
1380
-	 */
1381
-	public function getCalendarRoomBackendManager() {
1382
-		return $this->query(\OC\Calendar\Room\Manager::class);
1383
-	}
1384
-
1385
-	private function connectDispatcher() {
1386
-		$dispatcher = $this->getEventDispatcher();
1387
-
1388
-		// Delete avatar on user deletion
1389
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1390
-			$logger = $this->getLogger();
1391
-			$manager = $this->getAvatarManager();
1392
-			/** @var IUser $user */
1393
-			$user = $e->getSubject();
1394
-
1395
-			try {
1396
-				$avatar = $manager->getAvatar($user->getUID());
1397
-				$avatar->remove();
1398
-			} catch (NotFoundException $e) {
1399
-				// no avatar to remove
1400
-			} catch (\Exception $e) {
1401
-				// Ignore exceptions
1402
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1403
-			}
1404
-		});
1405
-
1406
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1407
-			$manager = $this->getAvatarManager();
1408
-			/** @var IUser $user */
1409
-			$user = $e->getSubject();
1410
-			$feature = $e->getArgument('feature');
1411
-			$oldValue = $e->getArgument('oldValue');
1412
-			$value = $e->getArgument('value');
1413
-
1414
-			// We only change the avatar on display name changes
1415
-			if ($feature !== 'displayName') {
1416
-				return;
1417
-			}
1418
-
1419
-			try {
1420
-				$avatar = $manager->getAvatar($user->getUID());
1421
-				$avatar->userChanged($feature, $oldValue, $value);
1422
-			} catch (NotFoundException $e) {
1423
-				// no avatar to remove
1424
-			}
1425
-		});
1426
-
1427
-		/** @var IEventDispatcher $eventDispatched */
1428
-		$eventDispatched = $this->query(IEventDispatcher::class);
1429
-		$eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1430
-	}
1431
-
1432
-	/**
1433
-	 * @return \OCP\Contacts\IManager
1434
-	 */
1435
-	public function getContactsManager() {
1436
-		return $this->query(\OCP\Contacts\IManager::class);
1437
-	}
1438
-
1439
-	/**
1440
-	 * @return \OC\Encryption\Manager
1441
-	 */
1442
-	public function getEncryptionManager() {
1443
-		return $this->query(\OCP\Encryption\IManager::class);
1444
-	}
1445
-
1446
-	/**
1447
-	 * @return \OC\Encryption\File
1448
-	 */
1449
-	public function getEncryptionFilesHelper() {
1450
-		return $this->query('EncryptionFileHelper');
1451
-	}
1452
-
1453
-	/**
1454
-	 * @return \OCP\Encryption\Keys\IStorage
1455
-	 */
1456
-	public function getEncryptionKeyStorage() {
1457
-		return $this->query('EncryptionKeyStorage');
1458
-	}
1459
-
1460
-	/**
1461
-	 * The current request object holding all information about the request
1462
-	 * currently being processed is returned from this method.
1463
-	 * In case the current execution was not initiated by a web request null is returned
1464
-	 *
1465
-	 * @return \OCP\IRequest
1466
-	 */
1467
-	public function getRequest() {
1468
-		return $this->query(IRequest::class);
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns the preview manager which can create preview images for a given file
1473
-	 *
1474
-	 * @return IPreview
1475
-	 */
1476
-	public function getPreviewManager() {
1477
-		return $this->query(IPreview::class);
1478
-	}
1479
-
1480
-	/**
1481
-	 * Returns the tag manager which can get and set tags for different object types
1482
-	 *
1483
-	 * @see \OCP\ITagManager::load()
1484
-	 * @return ITagManager
1485
-	 */
1486
-	public function getTagManager() {
1487
-		return $this->query(ITagManager::class);
1488
-	}
1489
-
1490
-	/**
1491
-	 * Returns the system-tag manager
1492
-	 *
1493
-	 * @return ISystemTagManager
1494
-	 *
1495
-	 * @since 9.0.0
1496
-	 */
1497
-	public function getSystemTagManager() {
1498
-		return $this->query(ISystemTagManager::class);
1499
-	}
1500
-
1501
-	/**
1502
-	 * Returns the system-tag object mapper
1503
-	 *
1504
-	 * @return ISystemTagObjectMapper
1505
-	 *
1506
-	 * @since 9.0.0
1507
-	 */
1508
-	public function getSystemTagObjectMapper() {
1509
-		return $this->query(ISystemTagObjectMapper::class);
1510
-	}
1511
-
1512
-	/**
1513
-	 * Returns the avatar manager, used for avatar functionality
1514
-	 *
1515
-	 * @return IAvatarManager
1516
-	 */
1517
-	public function getAvatarManager() {
1518
-		return $this->query(IAvatarManager::class);
1519
-	}
1520
-
1521
-	/**
1522
-	 * Returns the root folder of ownCloud's data directory
1523
-	 *
1524
-	 * @return IRootFolder
1525
-	 */
1526
-	public function getRootFolder() {
1527
-		return $this->query(IRootFolder::class);
1528
-	}
1529
-
1530
-	/**
1531
-	 * Returns the root folder of ownCloud's data directory
1532
-	 * This is the lazy variant so this gets only initialized once it
1533
-	 * is actually used.
1534
-	 *
1535
-	 * @return IRootFolder
1536
-	 */
1537
-	public function getLazyRootFolder() {
1538
-		return $this->query(IRootFolder::class);
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns a view to ownCloud's files folder
1543
-	 *
1544
-	 * @param string $userId user ID
1545
-	 * @return \OCP\Files\Folder|null
1546
-	 */
1547
-	public function getUserFolder($userId = null) {
1548
-		if ($userId === null) {
1549
-			$user = $this->getUserSession()->getUser();
1550
-			if (!$user) {
1551
-				return null;
1552
-			}
1553
-			$userId = $user->getUID();
1554
-		}
1555
-		$root = $this->getRootFolder();
1556
-		return $root->getUserFolder($userId);
1557
-	}
1558
-
1559
-	/**
1560
-	 * Returns an app-specific view in ownClouds data directory
1561
-	 *
1562
-	 * @return \OCP\Files\Folder
1563
-	 * @deprecated since 9.2.0 use IAppData
1564
-	 */
1565
-	public function getAppFolder() {
1566
-		$dir = '/' . \OC_App::getCurrentApp();
1567
-		$root = $this->getRootFolder();
1568
-		if (!$root->nodeExists($dir)) {
1569
-			$folder = $root->newFolder($dir);
1570
-		} else {
1571
-			$folder = $root->get($dir);
1572
-		}
1573
-		return $folder;
1574
-	}
1575
-
1576
-	/**
1577
-	 * @return \OC\User\Manager
1578
-	 */
1579
-	public function getUserManager() {
1580
-		return $this->query(IUserManager::class);
1581
-	}
1582
-
1583
-	/**
1584
-	 * @return \OC\Group\Manager
1585
-	 */
1586
-	public function getGroupManager() {
1587
-		return $this->query(IGroupManager::class);
1588
-	}
1589
-
1590
-	/**
1591
-	 * @return \OC\User\Session
1592
-	 */
1593
-	public function getUserSession() {
1594
-		return $this->query(IUserSession::class);
1595
-	}
1596
-
1597
-	/**
1598
-	 * @return \OCP\ISession
1599
-	 */
1600
-	public function getSession() {
1601
-		return $this->getUserSession()->getSession();
1602
-	}
1603
-
1604
-	/**
1605
-	 * @param \OCP\ISession $session
1606
-	 */
1607
-	public function setSession(\OCP\ISession $session) {
1608
-		$this->query(SessionStorage::class)->setSession($session);
1609
-		$this->getUserSession()->setSession($session);
1610
-		$this->query(Store::class)->setSession($session);
1611
-	}
1612
-
1613
-	/**
1614
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1615
-	 */
1616
-	public function getTwoFactorAuthManager() {
1617
-		return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1618
-	}
1619
-
1620
-	/**
1621
-	 * @return \OC\NavigationManager
1622
-	 */
1623
-	public function getNavigationManager() {
1624
-		return $this->query(INavigationManager::class);
1625
-	}
1626
-
1627
-	/**
1628
-	 * @return \OCP\IConfig
1629
-	 */
1630
-	public function getConfig() {
1631
-		return $this->query(AllConfig::class);
1632
-	}
1633
-
1634
-	/**
1635
-	 * @return \OC\SystemConfig
1636
-	 */
1637
-	public function getSystemConfig() {
1638
-		return $this->query(SystemConfig::class);
1639
-	}
1640
-
1641
-	/**
1642
-	 * Returns the app config manager
1643
-	 *
1644
-	 * @return IAppConfig
1645
-	 */
1646
-	public function getAppConfig() {
1647
-		return $this->query(IAppConfig::class);
1648
-	}
1649
-
1650
-	/**
1651
-	 * @return IFactory
1652
-	 */
1653
-	public function getL10NFactory() {
1654
-		return $this->query(IFactory::class);
1655
-	}
1656
-
1657
-	/**
1658
-	 * get an L10N instance
1659
-	 *
1660
-	 * @param string $app appid
1661
-	 * @param string $lang
1662
-	 * @return IL10N
1663
-	 */
1664
-	public function getL10N($app, $lang = null) {
1665
-		return $this->getL10NFactory()->get($app, $lang);
1666
-	}
1667
-
1668
-	/**
1669
-	 * @return IURLGenerator
1670
-	 */
1671
-	public function getURLGenerator() {
1672
-		return $this->query(IURLGenerator::class);
1673
-	}
1674
-
1675
-	/**
1676
-	 * @return AppFetcher
1677
-	 */
1678
-	public function getAppFetcher() {
1679
-		return $this->query(AppFetcher::class);
1680
-	}
1681
-
1682
-	/**
1683
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1684
-	 * getMemCacheFactory() instead.
1685
-	 *
1686
-	 * @return ICache
1687
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1688
-	 */
1689
-	public function getCache() {
1690
-		return $this->query(ICache::class);
1691
-	}
1692
-
1693
-	/**
1694
-	 * Returns an \OCP\CacheFactory instance
1695
-	 *
1696
-	 * @return \OCP\ICacheFactory
1697
-	 */
1698
-	public function getMemCacheFactory() {
1699
-		return $this->query(Factory::class);
1700
-	}
1701
-
1702
-	/**
1703
-	 * Returns an \OC\RedisFactory instance
1704
-	 *
1705
-	 * @return \OC\RedisFactory
1706
-	 */
1707
-	public function getGetRedisFactory() {
1708
-		return $this->query('RedisFactory');
1709
-	}
1710
-
1711
-
1712
-	/**
1713
-	 * Returns the current session
1714
-	 *
1715
-	 * @return \OCP\IDBConnection
1716
-	 */
1717
-	public function getDatabaseConnection() {
1718
-		return $this->query(IDBConnection::class);
1719
-	}
1720
-
1721
-	/**
1722
-	 * Returns the activity manager
1723
-	 *
1724
-	 * @return \OCP\Activity\IManager
1725
-	 */
1726
-	public function getActivityManager() {
1727
-		return $this->query(\OCP\Activity\IManager::class);
1728
-	}
1729
-
1730
-	/**
1731
-	 * Returns an job list for controlling background jobs
1732
-	 *
1733
-	 * @return IJobList
1734
-	 */
1735
-	public function getJobList() {
1736
-		return $this->query(IJobList::class);
1737
-	}
1738
-
1739
-	/**
1740
-	 * Returns a logger instance
1741
-	 *
1742
-	 * @return ILogger
1743
-	 */
1744
-	public function getLogger() {
1745
-		return $this->query(ILogger::class);
1746
-	}
1747
-
1748
-	/**
1749
-	 * @return ILogFactory
1750
-	 * @throws \OCP\AppFramework\QueryException
1751
-	 */
1752
-	public function getLogFactory() {
1753
-		return $this->query(ILogFactory::class);
1754
-	}
1755
-
1756
-	/**
1757
-	 * Returns a router for generating and matching urls
1758
-	 *
1759
-	 * @return IRouter
1760
-	 */
1761
-	public function getRouter() {
1762
-		return $this->query(IRouter::class);
1763
-	}
1764
-
1765
-	/**
1766
-	 * Returns a search instance
1767
-	 *
1768
-	 * @return ISearch
1769
-	 */
1770
-	public function getSearch() {
1771
-		return $this->query(ISearch::class);
1772
-	}
1773
-
1774
-	/**
1775
-	 * Returns a SecureRandom instance
1776
-	 *
1777
-	 * @return \OCP\Security\ISecureRandom
1778
-	 */
1779
-	public function getSecureRandom() {
1780
-		return $this->query(ISecureRandom::class);
1781
-	}
1782
-
1783
-	/**
1784
-	 * Returns a Crypto instance
1785
-	 *
1786
-	 * @return ICrypto
1787
-	 */
1788
-	public function getCrypto() {
1789
-		return $this->query(ICrypto::class);
1790
-	}
1791
-
1792
-	/**
1793
-	 * Returns a Hasher instance
1794
-	 *
1795
-	 * @return IHasher
1796
-	 */
1797
-	public function getHasher() {
1798
-		return $this->query(IHasher::class);
1799
-	}
1800
-
1801
-	/**
1802
-	 * Returns a CredentialsManager instance
1803
-	 *
1804
-	 * @return ICredentialsManager
1805
-	 */
1806
-	public function getCredentialsManager() {
1807
-		return $this->query(ICredentialsManager::class);
1808
-	}
1809
-
1810
-	/**
1811
-	 * Get the certificate manager for the user
1812
-	 *
1813
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1814
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1815
-	 */
1816
-	public function getCertificateManager($userId = '') {
1817
-		if ($userId === '') {
1818
-			$userSession = $this->getUserSession();
1819
-			$user = $userSession->getUser();
1820
-			if (is_null($user)) {
1821
-				return null;
1822
-			}
1823
-			$userId = $user->getUID();
1824
-		}
1825
-		return new CertificateManager(
1826
-			$userId,
1827
-			new View(),
1828
-			$this->getConfig(),
1829
-			$this->getLogger(),
1830
-			$this->getSecureRandom()
1831
-		);
1832
-	}
1833
-
1834
-	/**
1835
-	 * Returns an instance of the HTTP client service
1836
-	 *
1837
-	 * @return IClientService
1838
-	 */
1839
-	public function getHTTPClientService() {
1840
-		return $this->query(IClientService::class);
1841
-	}
1842
-
1843
-	/**
1844
-	 * Create a new event source
1845
-	 *
1846
-	 * @return \OCP\IEventSource
1847
-	 */
1848
-	public function createEventSource() {
1849
-		return new \OC_EventSource();
1850
-	}
1851
-
1852
-	/**
1853
-	 * Get the active event logger
1854
-	 *
1855
-	 * The returned logger only logs data when debug mode is enabled
1856
-	 *
1857
-	 * @return IEventLogger
1858
-	 */
1859
-	public function getEventLogger() {
1860
-		return $this->query(IEventLogger::class);
1861
-	}
1862
-
1863
-	/**
1864
-	 * Get the active query logger
1865
-	 *
1866
-	 * The returned logger only logs data when debug mode is enabled
1867
-	 *
1868
-	 * @return IQueryLogger
1869
-	 */
1870
-	public function getQueryLogger() {
1871
-		return $this->query(IQueryLogger::class);
1872
-	}
1873
-
1874
-	/**
1875
-	 * Get the manager for temporary files and folders
1876
-	 *
1877
-	 * @return \OCP\ITempManager
1878
-	 */
1879
-	public function getTempManager() {
1880
-		return $this->query(ITempManager::class);
1881
-	}
1882
-
1883
-	/**
1884
-	 * Get the app manager
1885
-	 *
1886
-	 * @return \OCP\App\IAppManager
1887
-	 */
1888
-	public function getAppManager() {
1889
-		return $this->query(IAppManager::class);
1890
-	}
1891
-
1892
-	/**
1893
-	 * Creates a new mailer
1894
-	 *
1895
-	 * @return IMailer
1896
-	 */
1897
-	public function getMailer() {
1898
-		return $this->query(IMailer::class);
1899
-	}
1900
-
1901
-	/**
1902
-	 * Get the webroot
1903
-	 *
1904
-	 * @return string
1905
-	 */
1906
-	public function getWebRoot() {
1907
-		return $this->webRoot;
1908
-	}
1909
-
1910
-	/**
1911
-	 * @return \OC\OCSClient
1912
-	 */
1913
-	public function getOcsClient() {
1914
-		return $this->query('OcsClient');
1915
-	}
1916
-
1917
-	/**
1918
-	 * @return IDateTimeZone
1919
-	 */
1920
-	public function getDateTimeZone() {
1921
-		return $this->query(IDateTimeZone::class);
1922
-	}
1923
-
1924
-	/**
1925
-	 * @return IDateTimeFormatter
1926
-	 */
1927
-	public function getDateTimeFormatter() {
1928
-		return $this->query(IDateTimeFormatter::class);
1929
-	}
1930
-
1931
-	/**
1932
-	 * @return IMountProviderCollection
1933
-	 */
1934
-	public function getMountProviderCollection() {
1935
-		return $this->query(IMountProviderCollection::class);
1936
-	}
1937
-
1938
-	/**
1939
-	 * Get the IniWrapper
1940
-	 *
1941
-	 * @return IniGetWrapper
1942
-	 */
1943
-	public function getIniWrapper() {
1944
-		return $this->query('IniWrapper');
1945
-	}
1946
-
1947
-	/**
1948
-	 * @return \OCP\Command\IBus
1949
-	 */
1950
-	public function getCommandBus() {
1951
-		return $this->query('AsyncCommandBus');
1952
-	}
1953
-
1954
-	/**
1955
-	 * Get the trusted domain helper
1956
-	 *
1957
-	 * @return TrustedDomainHelper
1958
-	 */
1959
-	public function getTrustedDomainHelper() {
1960
-		return $this->query('TrustedDomainHelper');
1961
-	}
1962
-
1963
-	/**
1964
-	 * Get the locking provider
1965
-	 *
1966
-	 * @return ILockingProvider
1967
-	 * @since 8.1.0
1968
-	 */
1969
-	public function getLockingProvider() {
1970
-		return $this->query(ILockingProvider::class);
1971
-	}
1972
-
1973
-	/**
1974
-	 * @return IMountManager
1975
-	 **/
1976
-	function getMountManager() {
1977
-		return $this->query(IMountManager::class);
1978
-	}
1979
-
1980
-	/**
1981
-	 * @return IUserMountCache
1982
-	 */
1983
-	function getUserMountCache() {
1984
-		return $this->query(IUserMountCache::class);
1985
-	}
1986
-
1987
-	/**
1988
-	 * Get the MimeTypeDetector
1989
-	 *
1990
-	 * @return IMimeTypeDetector
1991
-	 */
1992
-	public function getMimeTypeDetector() {
1993
-		return $this->query(IMimeTypeDetector::class);
1994
-	}
1995
-
1996
-	/**
1997
-	 * Get the MimeTypeLoader
1998
-	 *
1999
-	 * @return IMimeTypeLoader
2000
-	 */
2001
-	public function getMimeTypeLoader() {
2002
-		return $this->query(IMimeTypeLoader::class);
2003
-	}
2004
-
2005
-	/**
2006
-	 * Get the manager of all the capabilities
2007
-	 *
2008
-	 * @return CapabilitiesManager
2009
-	 */
2010
-	public function getCapabilitiesManager() {
2011
-		return $this->query(CapabilitiesManager::class);
2012
-	}
2013
-
2014
-	/**
2015
-	 * Get the EventDispatcher
2016
-	 *
2017
-	 * @return EventDispatcherInterface
2018
-	 * @since 8.2.0
2019
-	 * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2020
-	 */
2021
-	public function getEventDispatcher() {
2022
-		return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2023
-	}
2024
-
2025
-	/**
2026
-	 * Get the Notification Manager
2027
-	 *
2028
-	 * @return \OCP\Notification\IManager
2029
-	 * @since 8.2.0
2030
-	 */
2031
-	public function getNotificationManager() {
2032
-		return $this->query(\OCP\Notification\IManager::class);
2033
-	}
2034
-
2035
-	/**
2036
-	 * @return ICommentsManager
2037
-	 */
2038
-	public function getCommentsManager() {
2039
-		return $this->query(ICommentsManager::class);
2040
-	}
2041
-
2042
-	/**
2043
-	 * @return \OCA\Theming\ThemingDefaults
2044
-	 */
2045
-	public function getThemingDefaults() {
2046
-		return $this->query('ThemingDefaults');
2047
-	}
2048
-
2049
-	/**
2050
-	 * @return \OC\IntegrityCheck\Checker
2051
-	 */
2052
-	public function getIntegrityCodeChecker() {
2053
-		return $this->query('IntegrityCodeChecker');
2054
-	}
2055
-
2056
-	/**
2057
-	 * @return \OC\Session\CryptoWrapper
2058
-	 */
2059
-	public function getSessionCryptoWrapper() {
2060
-		return $this->query('CryptoWrapper');
2061
-	}
2062
-
2063
-	/**
2064
-	 * @return CsrfTokenManager
2065
-	 */
2066
-	public function getCsrfTokenManager() {
2067
-		return $this->query(CsrfTokenManager::class);
2068
-	}
2069
-
2070
-	/**
2071
-	 * @return Throttler
2072
-	 */
2073
-	public function getBruteForceThrottler() {
2074
-		return $this->query(Throttler::class);
2075
-	}
2076
-
2077
-	/**
2078
-	 * @return IContentSecurityPolicyManager
2079
-	 */
2080
-	public function getContentSecurityPolicyManager() {
2081
-		return $this->query(ContentSecurityPolicyManager::class);
2082
-	}
2083
-
2084
-	/**
2085
-	 * @return ContentSecurityPolicyNonceManager
2086
-	 */
2087
-	public function getContentSecurityPolicyNonceManager() {
2088
-		return $this->query('ContentSecurityPolicyNonceManager');
2089
-	}
2090
-
2091
-	/**
2092
-	 * Not a public API as of 8.2, wait for 9.0
2093
-	 *
2094
-	 * @return \OCA\Files_External\Service\BackendService
2095
-	 */
2096
-	public function getStoragesBackendService() {
2097
-		return $this->query(BackendService::class);
2098
-	}
2099
-
2100
-	/**
2101
-	 * Not a public API as of 8.2, wait for 9.0
2102
-	 *
2103
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
2104
-	 */
2105
-	public function getGlobalStoragesService() {
2106
-		return $this->query(GlobalStoragesService::class);
2107
-	}
2108
-
2109
-	/**
2110
-	 * Not a public API as of 8.2, wait for 9.0
2111
-	 *
2112
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
2113
-	 */
2114
-	public function getUserGlobalStoragesService() {
2115
-		return $this->query(UserGlobalStoragesService::class);
2116
-	}
2117
-
2118
-	/**
2119
-	 * Not a public API as of 8.2, wait for 9.0
2120
-	 *
2121
-	 * @return \OCA\Files_External\Service\UserStoragesService
2122
-	 */
2123
-	public function getUserStoragesService() {
2124
-		return $this->query(UserStoragesService::class);
2125
-	}
2126
-
2127
-	/**
2128
-	 * @return \OCP\Share\IManager
2129
-	 */
2130
-	public function getShareManager() {
2131
-		return $this->query(\OCP\Share\IManager::class);
2132
-	}
2133
-
2134
-	/**
2135
-	 * @return \OCP\Collaboration\Collaborators\ISearch
2136
-	 */
2137
-	public function getCollaboratorSearch() {
2138
-		return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2139
-	}
2140
-
2141
-	/**
2142
-	 * @return \OCP\Collaboration\AutoComplete\IManager
2143
-	 */
2144
-	public function getAutoCompleteManager() {
2145
-		return $this->query(IManager::class);
2146
-	}
2147
-
2148
-	/**
2149
-	 * Returns the LDAP Provider
2150
-	 *
2151
-	 * @return \OCP\LDAP\ILDAPProvider
2152
-	 */
2153
-	public function getLDAPProvider() {
2154
-		return $this->query('LDAPProvider');
2155
-	}
2156
-
2157
-	/**
2158
-	 * @return \OCP\Settings\IManager
2159
-	 */
2160
-	public function getSettingsManager() {
2161
-		return $this->query('SettingsManager');
2162
-	}
2163
-
2164
-	/**
2165
-	 * @return \OCP\Files\IAppData
2166
-	 */
2167
-	public function getAppDataDir($app) {
2168
-		/** @var \OC\Files\AppData\Factory $factory */
2169
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
2170
-		return $factory->get($app);
2171
-	}
2172
-
2173
-	/**
2174
-	 * @return \OCP\Lockdown\ILockdownManager
2175
-	 */
2176
-	public function getLockdownManager() {
2177
-		return $this->query('LockdownManager');
2178
-	}
2179
-
2180
-	/**
2181
-	 * @return \OCP\Federation\ICloudIdManager
2182
-	 */
2183
-	public function getCloudIdManager() {
2184
-		return $this->query(ICloudIdManager::class);
2185
-	}
2186
-
2187
-	/**
2188
-	 * @return \OCP\GlobalScale\IConfig
2189
-	 */
2190
-	public function getGlobalScaleConfig() {
2191
-		return $this->query(IConfig::class);
2192
-	}
2193
-
2194
-	/**
2195
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2196
-	 */
2197
-	public function getCloudFederationProviderManager() {
2198
-		return $this->query(ICloudFederationProviderManager::class);
2199
-	}
2200
-
2201
-	/**
2202
-	 * @return \OCP\Remote\Api\IApiFactory
2203
-	 */
2204
-	public function getRemoteApiFactory() {
2205
-		return $this->query(IApiFactory::class);
2206
-	}
2207
-
2208
-	/**
2209
-	 * @return \OCP\Federation\ICloudFederationFactory
2210
-	 */
2211
-	public function getCloudFederationFactory() {
2212
-		return $this->query(ICloudFederationFactory::class);
2213
-	}
2214
-
2215
-	/**
2216
-	 * @return \OCP\Remote\IInstanceFactory
2217
-	 */
2218
-	public function getRemoteInstanceFactory() {
2219
-		return $this->query(IInstanceFactory::class);
2220
-	}
2221
-
2222
-	/**
2223
-	 * @return IStorageFactory
2224
-	 */
2225
-	public function getStorageFactory() {
2226
-		return $this->query(IStorageFactory::class);
2227
-	}
2228
-
2229
-	/**
2230
-	 * Get the Preview GeneratorHelper
2231
-	 *
2232
-	 * @return GeneratorHelper
2233
-	 * @since 17.0.0
2234
-	 */
2235
-	public function getGeneratorHelper() {
2236
-		return $this->query(\OC\Preview\GeneratorHelper::class);
2237
-	}
2238
-
2239
-	private function registerDeprecatedAlias(string $alias, string $target) {
2240
-		$this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2241
-			try {
2242
-				/** @var ILogger $logger */
2243
-				$logger = $container->query(ILogger::class);
2244
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2245
-			} catch (QueryException $e) {
2246
-				// Could not get logger. Continue
2247
-			}
2248
-
2249
-			return $container->query($target);
2250
-		}, false);
2251
-	}
1111
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
1112
+            if (isset($prefixes['OCA\\Theming\\'])) {
1113
+                $classExists = true;
1114
+            } else {
1115
+                $classExists = false;
1116
+            }
1117
+
1118
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1119
+                return new ThemingDefaults(
1120
+                    $c->getConfig(),
1121
+                    $c->getL10N('theming'),
1122
+                    $c->getURLGenerator(),
1123
+                    $c->getMemCacheFactory(),
1124
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
1125
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
1126
+                    $c->getAppManager(),
1127
+                    $c->getNavigationManager()
1128
+                );
1129
+            }
1130
+            return new \OC_Defaults();
1131
+        });
1132
+        $this->registerService(SCSSCacher::class, function (Server $c) {
1133
+            return new SCSSCacher(
1134
+                $c->getLogger(),
1135
+                $c->query(\OC\Files\AppData\Factory::class),
1136
+                $c->getURLGenerator(),
1137
+                $c->getConfig(),
1138
+                $c->getThemingDefaults(),
1139
+                \OC::$SERVERROOT,
1140
+                $this->getMemCacheFactory(),
1141
+                $c->query(IconsCacher::class),
1142
+                new TimeFactory()
1143
+            );
1144
+        });
1145
+        $this->registerService(JSCombiner::class, function (Server $c) {
1146
+            return new JSCombiner(
1147
+                $c->getAppDataDir('js'),
1148
+                $c->getURLGenerator(),
1149
+                $this->getMemCacheFactory(),
1150
+                $c->getSystemConfig(),
1151
+                $c->getLogger()
1152
+            );
1153
+        });
1154
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1155
+        $this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1156
+        $this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1157
+
1158
+        $this->registerService('CryptoWrapper', function (Server $c) {
1159
+            // FIXME: Instantiiated here due to cyclic dependency
1160
+            $request = new Request(
1161
+                [
1162
+                    'get' => $_GET,
1163
+                    'post' => $_POST,
1164
+                    'files' => $_FILES,
1165
+                    'server' => $_SERVER,
1166
+                    'env' => $_ENV,
1167
+                    'cookies' => $_COOKIE,
1168
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1169
+                        ? $_SERVER['REQUEST_METHOD']
1170
+                        : null,
1171
+                ],
1172
+                $c->getSecureRandom(),
1173
+                $c->getConfig()
1174
+            );
1175
+
1176
+            return new CryptoWrapper(
1177
+                $c->getConfig(),
1178
+                $c->getCrypto(),
1179
+                $c->getSecureRandom(),
1180
+                $request
1181
+            );
1182
+        });
1183
+        $this->registerService(CsrfTokenManager::class, function (Server $c) {
1184
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1185
+
1186
+            return new CsrfTokenManager(
1187
+                $tokenGenerator,
1188
+                $c->query(SessionStorage::class)
1189
+            );
1190
+        });
1191
+        $this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1192
+        $this->registerService(SessionStorage::class, function (Server $c) {
1193
+            return new SessionStorage($c->getSession());
1194
+        });
1195
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1196
+        $this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1197
+
1198
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1199
+            return new ContentSecurityPolicyNonceManager(
1200
+                $c->getCsrfTokenManager(),
1201
+                $c->getRequest()
1202
+            );
1203
+        });
1204
+
1205
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1206
+            $config = $c->getConfig();
1207
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1208
+            /** @var \OCP\Share\IProviderFactory $factory */
1209
+            $factory = new $factoryClass($this);
1210
+
1211
+            $manager = new \OC\Share20\Manager(
1212
+                $c->getLogger(),
1213
+                $c->getConfig(),
1214
+                $c->getSecureRandom(),
1215
+                $c->getHasher(),
1216
+                $c->getMountManager(),
1217
+                $c->getGroupManager(),
1218
+                $c->getL10N('lib'),
1219
+                $c->getL10NFactory(),
1220
+                $factory,
1221
+                $c->getUserManager(),
1222
+                $c->getLazyRootFolder(),
1223
+                $c->getEventDispatcher(),
1224
+                $c->getMailer(),
1225
+                $c->getURLGenerator(),
1226
+                $c->getThemingDefaults(),
1227
+                $c->query(IEventDispatcher::class)
1228
+            );
1229
+
1230
+            return $manager;
1231
+        });
1232
+        $this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1233
+
1234
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1235
+            $instance = new Collaboration\Collaborators\Search($c);
1236
+
1237
+            // register default plugins
1238
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1239
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1240
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1241
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1242
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1243
+
1244
+            return $instance;
1245
+        });
1246
+        $this->registerDeprecatedAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1247
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1248
+
1249
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1250
+
1251
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1252
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1253
+
1254
+        $this->registerService('SettingsManager', function (Server $c) {
1255
+            $manager = new \OC\Settings\Manager(
1256
+                $c->getLogger(),
1257
+                $c->getL10NFactory(),
1258
+                $c->getURLGenerator(),
1259
+                $c
1260
+            );
1261
+            return $manager;
1262
+        });
1263
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1264
+            return new \OC\Files\AppData\Factory(
1265
+                $c->getRootFolder(),
1266
+                $c->getSystemConfig()
1267
+            );
1268
+        });
1269
+
1270
+        $this->registerService('LockdownManager', function (Server $c) {
1271
+            return new LockdownManager(function () use ($c) {
1272
+                return $c->getSession();
1273
+            });
1274
+        });
1275
+
1276
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1277
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1278
+        });
1279
+
1280
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1281
+            return new CloudIdManager();
1282
+        });
1283
+
1284
+        $this->registerService(IConfig::class, function (Server $c) {
1285
+            return new GlobalScale\Config($c->getConfig());
1286
+        });
1287
+
1288
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1289
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1290
+        });
1291
+
1292
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1293
+            return new CloudFederationFactory();
1294
+        });
1295
+
1296
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1297
+        $this->registerDeprecatedAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1298
+
1299
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1300
+        $this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1301
+
1302
+        $this->registerService(Defaults::class, function (Server $c) {
1303
+            return new Defaults(
1304
+                $c->getThemingDefaults()
1305
+            );
1306
+        });
1307
+        $this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1308
+
1309
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1310
+            return $c->query(\OCP\IUserSession::class)->getSession();
1311
+        });
1312
+
1313
+        $this->registerService(IShareHelper::class, function (Server $c) {
1314
+            return new ShareHelper(
1315
+                $c->query(\OCP\Share\IManager::class)
1316
+            );
1317
+        });
1318
+
1319
+        $this->registerService(Installer::class, function (Server $c) {
1320
+            return new Installer(
1321
+                $c->getAppFetcher(),
1322
+                $c->getHTTPClientService(),
1323
+                $c->getTempManager(),
1324
+                $c->getLogger(),
1325
+                $c->getConfig(),
1326
+                \OC::$CLI
1327
+            );
1328
+        });
1329
+
1330
+        $this->registerService(IApiFactory::class, function (Server $c) {
1331
+            return new ApiFactory($c->getHTTPClientService());
1332
+        });
1333
+
1334
+        $this->registerService(IInstanceFactory::class, function (Server $c) {
1335
+            $memcacheFactory = $c->getMemCacheFactory();
1336
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1337
+        });
1338
+
1339
+        $this->registerService(IContactsStore::class, function (Server $c) {
1340
+            return new ContactsStore(
1341
+                $c->getContactsManager(),
1342
+                $c->getConfig(),
1343
+                $c->getUserManager(),
1344
+                $c->getGroupManager()
1345
+            );
1346
+        });
1347
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1348
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1349
+
1350
+        $this->registerService(IStorageFactory::class, function () {
1351
+            return new StorageFactory();
1352
+        });
1353
+
1354
+        $this->registerAlias(IDashboardManager::class, DashboardManager::class);
1355
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1356
+
1357
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1358
+
1359
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1360
+
1361
+        $this->connectDispatcher();
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OCP\Calendar\IManager
1366
+     */
1367
+    public function getCalendarManager() {
1368
+        return $this->query(\OC\Calendar\Manager::class);
1369
+    }
1370
+
1371
+    /**
1372
+     * @return \OCP\Calendar\Resource\IManager
1373
+     */
1374
+    public function getCalendarResourceBackendManager() {
1375
+        return $this->query(\OC\Calendar\Resource\Manager::class);
1376
+    }
1377
+
1378
+    /**
1379
+     * @return \OCP\Calendar\Room\IManager
1380
+     */
1381
+    public function getCalendarRoomBackendManager() {
1382
+        return $this->query(\OC\Calendar\Room\Manager::class);
1383
+    }
1384
+
1385
+    private function connectDispatcher() {
1386
+        $dispatcher = $this->getEventDispatcher();
1387
+
1388
+        // Delete avatar on user deletion
1389
+        $dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1390
+            $logger = $this->getLogger();
1391
+            $manager = $this->getAvatarManager();
1392
+            /** @var IUser $user */
1393
+            $user = $e->getSubject();
1394
+
1395
+            try {
1396
+                $avatar = $manager->getAvatar($user->getUID());
1397
+                $avatar->remove();
1398
+            } catch (NotFoundException $e) {
1399
+                // no avatar to remove
1400
+            } catch (\Exception $e) {
1401
+                // Ignore exceptions
1402
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1403
+            }
1404
+        });
1405
+
1406
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1407
+            $manager = $this->getAvatarManager();
1408
+            /** @var IUser $user */
1409
+            $user = $e->getSubject();
1410
+            $feature = $e->getArgument('feature');
1411
+            $oldValue = $e->getArgument('oldValue');
1412
+            $value = $e->getArgument('value');
1413
+
1414
+            // We only change the avatar on display name changes
1415
+            if ($feature !== 'displayName') {
1416
+                return;
1417
+            }
1418
+
1419
+            try {
1420
+                $avatar = $manager->getAvatar($user->getUID());
1421
+                $avatar->userChanged($feature, $oldValue, $value);
1422
+            } catch (NotFoundException $e) {
1423
+                // no avatar to remove
1424
+            }
1425
+        });
1426
+
1427
+        /** @var IEventDispatcher $eventDispatched */
1428
+        $eventDispatched = $this->query(IEventDispatcher::class);
1429
+        $eventDispatched->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1430
+    }
1431
+
1432
+    /**
1433
+     * @return \OCP\Contacts\IManager
1434
+     */
1435
+    public function getContactsManager() {
1436
+        return $this->query(\OCP\Contacts\IManager::class);
1437
+    }
1438
+
1439
+    /**
1440
+     * @return \OC\Encryption\Manager
1441
+     */
1442
+    public function getEncryptionManager() {
1443
+        return $this->query(\OCP\Encryption\IManager::class);
1444
+    }
1445
+
1446
+    /**
1447
+     * @return \OC\Encryption\File
1448
+     */
1449
+    public function getEncryptionFilesHelper() {
1450
+        return $this->query('EncryptionFileHelper');
1451
+    }
1452
+
1453
+    /**
1454
+     * @return \OCP\Encryption\Keys\IStorage
1455
+     */
1456
+    public function getEncryptionKeyStorage() {
1457
+        return $this->query('EncryptionKeyStorage');
1458
+    }
1459
+
1460
+    /**
1461
+     * The current request object holding all information about the request
1462
+     * currently being processed is returned from this method.
1463
+     * In case the current execution was not initiated by a web request null is returned
1464
+     *
1465
+     * @return \OCP\IRequest
1466
+     */
1467
+    public function getRequest() {
1468
+        return $this->query(IRequest::class);
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns the preview manager which can create preview images for a given file
1473
+     *
1474
+     * @return IPreview
1475
+     */
1476
+    public function getPreviewManager() {
1477
+        return $this->query(IPreview::class);
1478
+    }
1479
+
1480
+    /**
1481
+     * Returns the tag manager which can get and set tags for different object types
1482
+     *
1483
+     * @see \OCP\ITagManager::load()
1484
+     * @return ITagManager
1485
+     */
1486
+    public function getTagManager() {
1487
+        return $this->query(ITagManager::class);
1488
+    }
1489
+
1490
+    /**
1491
+     * Returns the system-tag manager
1492
+     *
1493
+     * @return ISystemTagManager
1494
+     *
1495
+     * @since 9.0.0
1496
+     */
1497
+    public function getSystemTagManager() {
1498
+        return $this->query(ISystemTagManager::class);
1499
+    }
1500
+
1501
+    /**
1502
+     * Returns the system-tag object mapper
1503
+     *
1504
+     * @return ISystemTagObjectMapper
1505
+     *
1506
+     * @since 9.0.0
1507
+     */
1508
+    public function getSystemTagObjectMapper() {
1509
+        return $this->query(ISystemTagObjectMapper::class);
1510
+    }
1511
+
1512
+    /**
1513
+     * Returns the avatar manager, used for avatar functionality
1514
+     *
1515
+     * @return IAvatarManager
1516
+     */
1517
+    public function getAvatarManager() {
1518
+        return $this->query(IAvatarManager::class);
1519
+    }
1520
+
1521
+    /**
1522
+     * Returns the root folder of ownCloud's data directory
1523
+     *
1524
+     * @return IRootFolder
1525
+     */
1526
+    public function getRootFolder() {
1527
+        return $this->query(IRootFolder::class);
1528
+    }
1529
+
1530
+    /**
1531
+     * Returns the root folder of ownCloud's data directory
1532
+     * This is the lazy variant so this gets only initialized once it
1533
+     * is actually used.
1534
+     *
1535
+     * @return IRootFolder
1536
+     */
1537
+    public function getLazyRootFolder() {
1538
+        return $this->query(IRootFolder::class);
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns a view to ownCloud's files folder
1543
+     *
1544
+     * @param string $userId user ID
1545
+     * @return \OCP\Files\Folder|null
1546
+     */
1547
+    public function getUserFolder($userId = null) {
1548
+        if ($userId === null) {
1549
+            $user = $this->getUserSession()->getUser();
1550
+            if (!$user) {
1551
+                return null;
1552
+            }
1553
+            $userId = $user->getUID();
1554
+        }
1555
+        $root = $this->getRootFolder();
1556
+        return $root->getUserFolder($userId);
1557
+    }
1558
+
1559
+    /**
1560
+     * Returns an app-specific view in ownClouds data directory
1561
+     *
1562
+     * @return \OCP\Files\Folder
1563
+     * @deprecated since 9.2.0 use IAppData
1564
+     */
1565
+    public function getAppFolder() {
1566
+        $dir = '/' . \OC_App::getCurrentApp();
1567
+        $root = $this->getRootFolder();
1568
+        if (!$root->nodeExists($dir)) {
1569
+            $folder = $root->newFolder($dir);
1570
+        } else {
1571
+            $folder = $root->get($dir);
1572
+        }
1573
+        return $folder;
1574
+    }
1575
+
1576
+    /**
1577
+     * @return \OC\User\Manager
1578
+     */
1579
+    public function getUserManager() {
1580
+        return $this->query(IUserManager::class);
1581
+    }
1582
+
1583
+    /**
1584
+     * @return \OC\Group\Manager
1585
+     */
1586
+    public function getGroupManager() {
1587
+        return $this->query(IGroupManager::class);
1588
+    }
1589
+
1590
+    /**
1591
+     * @return \OC\User\Session
1592
+     */
1593
+    public function getUserSession() {
1594
+        return $this->query(IUserSession::class);
1595
+    }
1596
+
1597
+    /**
1598
+     * @return \OCP\ISession
1599
+     */
1600
+    public function getSession() {
1601
+        return $this->getUserSession()->getSession();
1602
+    }
1603
+
1604
+    /**
1605
+     * @param \OCP\ISession $session
1606
+     */
1607
+    public function setSession(\OCP\ISession $session) {
1608
+        $this->query(SessionStorage::class)->setSession($session);
1609
+        $this->getUserSession()->setSession($session);
1610
+        $this->query(Store::class)->setSession($session);
1611
+    }
1612
+
1613
+    /**
1614
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1615
+     */
1616
+    public function getTwoFactorAuthManager() {
1617
+        return $this->query(\OC\Authentication\TwoFactorAuth\Manager::class);
1618
+    }
1619
+
1620
+    /**
1621
+     * @return \OC\NavigationManager
1622
+     */
1623
+    public function getNavigationManager() {
1624
+        return $this->query(INavigationManager::class);
1625
+    }
1626
+
1627
+    /**
1628
+     * @return \OCP\IConfig
1629
+     */
1630
+    public function getConfig() {
1631
+        return $this->query(AllConfig::class);
1632
+    }
1633
+
1634
+    /**
1635
+     * @return \OC\SystemConfig
1636
+     */
1637
+    public function getSystemConfig() {
1638
+        return $this->query(SystemConfig::class);
1639
+    }
1640
+
1641
+    /**
1642
+     * Returns the app config manager
1643
+     *
1644
+     * @return IAppConfig
1645
+     */
1646
+    public function getAppConfig() {
1647
+        return $this->query(IAppConfig::class);
1648
+    }
1649
+
1650
+    /**
1651
+     * @return IFactory
1652
+     */
1653
+    public function getL10NFactory() {
1654
+        return $this->query(IFactory::class);
1655
+    }
1656
+
1657
+    /**
1658
+     * get an L10N instance
1659
+     *
1660
+     * @param string $app appid
1661
+     * @param string $lang
1662
+     * @return IL10N
1663
+     */
1664
+    public function getL10N($app, $lang = null) {
1665
+        return $this->getL10NFactory()->get($app, $lang);
1666
+    }
1667
+
1668
+    /**
1669
+     * @return IURLGenerator
1670
+     */
1671
+    public function getURLGenerator() {
1672
+        return $this->query(IURLGenerator::class);
1673
+    }
1674
+
1675
+    /**
1676
+     * @return AppFetcher
1677
+     */
1678
+    public function getAppFetcher() {
1679
+        return $this->query(AppFetcher::class);
1680
+    }
1681
+
1682
+    /**
1683
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1684
+     * getMemCacheFactory() instead.
1685
+     *
1686
+     * @return ICache
1687
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1688
+     */
1689
+    public function getCache() {
1690
+        return $this->query(ICache::class);
1691
+    }
1692
+
1693
+    /**
1694
+     * Returns an \OCP\CacheFactory instance
1695
+     *
1696
+     * @return \OCP\ICacheFactory
1697
+     */
1698
+    public function getMemCacheFactory() {
1699
+        return $this->query(Factory::class);
1700
+    }
1701
+
1702
+    /**
1703
+     * Returns an \OC\RedisFactory instance
1704
+     *
1705
+     * @return \OC\RedisFactory
1706
+     */
1707
+    public function getGetRedisFactory() {
1708
+        return $this->query('RedisFactory');
1709
+    }
1710
+
1711
+
1712
+    /**
1713
+     * Returns the current session
1714
+     *
1715
+     * @return \OCP\IDBConnection
1716
+     */
1717
+    public function getDatabaseConnection() {
1718
+        return $this->query(IDBConnection::class);
1719
+    }
1720
+
1721
+    /**
1722
+     * Returns the activity manager
1723
+     *
1724
+     * @return \OCP\Activity\IManager
1725
+     */
1726
+    public function getActivityManager() {
1727
+        return $this->query(\OCP\Activity\IManager::class);
1728
+    }
1729
+
1730
+    /**
1731
+     * Returns an job list for controlling background jobs
1732
+     *
1733
+     * @return IJobList
1734
+     */
1735
+    public function getJobList() {
1736
+        return $this->query(IJobList::class);
1737
+    }
1738
+
1739
+    /**
1740
+     * Returns a logger instance
1741
+     *
1742
+     * @return ILogger
1743
+     */
1744
+    public function getLogger() {
1745
+        return $this->query(ILogger::class);
1746
+    }
1747
+
1748
+    /**
1749
+     * @return ILogFactory
1750
+     * @throws \OCP\AppFramework\QueryException
1751
+     */
1752
+    public function getLogFactory() {
1753
+        return $this->query(ILogFactory::class);
1754
+    }
1755
+
1756
+    /**
1757
+     * Returns a router for generating and matching urls
1758
+     *
1759
+     * @return IRouter
1760
+     */
1761
+    public function getRouter() {
1762
+        return $this->query(IRouter::class);
1763
+    }
1764
+
1765
+    /**
1766
+     * Returns a search instance
1767
+     *
1768
+     * @return ISearch
1769
+     */
1770
+    public function getSearch() {
1771
+        return $this->query(ISearch::class);
1772
+    }
1773
+
1774
+    /**
1775
+     * Returns a SecureRandom instance
1776
+     *
1777
+     * @return \OCP\Security\ISecureRandom
1778
+     */
1779
+    public function getSecureRandom() {
1780
+        return $this->query(ISecureRandom::class);
1781
+    }
1782
+
1783
+    /**
1784
+     * Returns a Crypto instance
1785
+     *
1786
+     * @return ICrypto
1787
+     */
1788
+    public function getCrypto() {
1789
+        return $this->query(ICrypto::class);
1790
+    }
1791
+
1792
+    /**
1793
+     * Returns a Hasher instance
1794
+     *
1795
+     * @return IHasher
1796
+     */
1797
+    public function getHasher() {
1798
+        return $this->query(IHasher::class);
1799
+    }
1800
+
1801
+    /**
1802
+     * Returns a CredentialsManager instance
1803
+     *
1804
+     * @return ICredentialsManager
1805
+     */
1806
+    public function getCredentialsManager() {
1807
+        return $this->query(ICredentialsManager::class);
1808
+    }
1809
+
1810
+    /**
1811
+     * Get the certificate manager for the user
1812
+     *
1813
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1814
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1815
+     */
1816
+    public function getCertificateManager($userId = '') {
1817
+        if ($userId === '') {
1818
+            $userSession = $this->getUserSession();
1819
+            $user = $userSession->getUser();
1820
+            if (is_null($user)) {
1821
+                return null;
1822
+            }
1823
+            $userId = $user->getUID();
1824
+        }
1825
+        return new CertificateManager(
1826
+            $userId,
1827
+            new View(),
1828
+            $this->getConfig(),
1829
+            $this->getLogger(),
1830
+            $this->getSecureRandom()
1831
+        );
1832
+    }
1833
+
1834
+    /**
1835
+     * Returns an instance of the HTTP client service
1836
+     *
1837
+     * @return IClientService
1838
+     */
1839
+    public function getHTTPClientService() {
1840
+        return $this->query(IClientService::class);
1841
+    }
1842
+
1843
+    /**
1844
+     * Create a new event source
1845
+     *
1846
+     * @return \OCP\IEventSource
1847
+     */
1848
+    public function createEventSource() {
1849
+        return new \OC_EventSource();
1850
+    }
1851
+
1852
+    /**
1853
+     * Get the active event logger
1854
+     *
1855
+     * The returned logger only logs data when debug mode is enabled
1856
+     *
1857
+     * @return IEventLogger
1858
+     */
1859
+    public function getEventLogger() {
1860
+        return $this->query(IEventLogger::class);
1861
+    }
1862
+
1863
+    /**
1864
+     * Get the active query logger
1865
+     *
1866
+     * The returned logger only logs data when debug mode is enabled
1867
+     *
1868
+     * @return IQueryLogger
1869
+     */
1870
+    public function getQueryLogger() {
1871
+        return $this->query(IQueryLogger::class);
1872
+    }
1873
+
1874
+    /**
1875
+     * Get the manager for temporary files and folders
1876
+     *
1877
+     * @return \OCP\ITempManager
1878
+     */
1879
+    public function getTempManager() {
1880
+        return $this->query(ITempManager::class);
1881
+    }
1882
+
1883
+    /**
1884
+     * Get the app manager
1885
+     *
1886
+     * @return \OCP\App\IAppManager
1887
+     */
1888
+    public function getAppManager() {
1889
+        return $this->query(IAppManager::class);
1890
+    }
1891
+
1892
+    /**
1893
+     * Creates a new mailer
1894
+     *
1895
+     * @return IMailer
1896
+     */
1897
+    public function getMailer() {
1898
+        return $this->query(IMailer::class);
1899
+    }
1900
+
1901
+    /**
1902
+     * Get the webroot
1903
+     *
1904
+     * @return string
1905
+     */
1906
+    public function getWebRoot() {
1907
+        return $this->webRoot;
1908
+    }
1909
+
1910
+    /**
1911
+     * @return \OC\OCSClient
1912
+     */
1913
+    public function getOcsClient() {
1914
+        return $this->query('OcsClient');
1915
+    }
1916
+
1917
+    /**
1918
+     * @return IDateTimeZone
1919
+     */
1920
+    public function getDateTimeZone() {
1921
+        return $this->query(IDateTimeZone::class);
1922
+    }
1923
+
1924
+    /**
1925
+     * @return IDateTimeFormatter
1926
+     */
1927
+    public function getDateTimeFormatter() {
1928
+        return $this->query(IDateTimeFormatter::class);
1929
+    }
1930
+
1931
+    /**
1932
+     * @return IMountProviderCollection
1933
+     */
1934
+    public function getMountProviderCollection() {
1935
+        return $this->query(IMountProviderCollection::class);
1936
+    }
1937
+
1938
+    /**
1939
+     * Get the IniWrapper
1940
+     *
1941
+     * @return IniGetWrapper
1942
+     */
1943
+    public function getIniWrapper() {
1944
+        return $this->query('IniWrapper');
1945
+    }
1946
+
1947
+    /**
1948
+     * @return \OCP\Command\IBus
1949
+     */
1950
+    public function getCommandBus() {
1951
+        return $this->query('AsyncCommandBus');
1952
+    }
1953
+
1954
+    /**
1955
+     * Get the trusted domain helper
1956
+     *
1957
+     * @return TrustedDomainHelper
1958
+     */
1959
+    public function getTrustedDomainHelper() {
1960
+        return $this->query('TrustedDomainHelper');
1961
+    }
1962
+
1963
+    /**
1964
+     * Get the locking provider
1965
+     *
1966
+     * @return ILockingProvider
1967
+     * @since 8.1.0
1968
+     */
1969
+    public function getLockingProvider() {
1970
+        return $this->query(ILockingProvider::class);
1971
+    }
1972
+
1973
+    /**
1974
+     * @return IMountManager
1975
+     **/
1976
+    function getMountManager() {
1977
+        return $this->query(IMountManager::class);
1978
+    }
1979
+
1980
+    /**
1981
+     * @return IUserMountCache
1982
+     */
1983
+    function getUserMountCache() {
1984
+        return $this->query(IUserMountCache::class);
1985
+    }
1986
+
1987
+    /**
1988
+     * Get the MimeTypeDetector
1989
+     *
1990
+     * @return IMimeTypeDetector
1991
+     */
1992
+    public function getMimeTypeDetector() {
1993
+        return $this->query(IMimeTypeDetector::class);
1994
+    }
1995
+
1996
+    /**
1997
+     * Get the MimeTypeLoader
1998
+     *
1999
+     * @return IMimeTypeLoader
2000
+     */
2001
+    public function getMimeTypeLoader() {
2002
+        return $this->query(IMimeTypeLoader::class);
2003
+    }
2004
+
2005
+    /**
2006
+     * Get the manager of all the capabilities
2007
+     *
2008
+     * @return CapabilitiesManager
2009
+     */
2010
+    public function getCapabilitiesManager() {
2011
+        return $this->query(CapabilitiesManager::class);
2012
+    }
2013
+
2014
+    /**
2015
+     * Get the EventDispatcher
2016
+     *
2017
+     * @return EventDispatcherInterface
2018
+     * @since 8.2.0
2019
+     * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher
2020
+     */
2021
+    public function getEventDispatcher() {
2022
+        return $this->query(\OC\EventDispatcher\SymfonyAdapter::class);
2023
+    }
2024
+
2025
+    /**
2026
+     * Get the Notification Manager
2027
+     *
2028
+     * @return \OCP\Notification\IManager
2029
+     * @since 8.2.0
2030
+     */
2031
+    public function getNotificationManager() {
2032
+        return $this->query(\OCP\Notification\IManager::class);
2033
+    }
2034
+
2035
+    /**
2036
+     * @return ICommentsManager
2037
+     */
2038
+    public function getCommentsManager() {
2039
+        return $this->query(ICommentsManager::class);
2040
+    }
2041
+
2042
+    /**
2043
+     * @return \OCA\Theming\ThemingDefaults
2044
+     */
2045
+    public function getThemingDefaults() {
2046
+        return $this->query('ThemingDefaults');
2047
+    }
2048
+
2049
+    /**
2050
+     * @return \OC\IntegrityCheck\Checker
2051
+     */
2052
+    public function getIntegrityCodeChecker() {
2053
+        return $this->query('IntegrityCodeChecker');
2054
+    }
2055
+
2056
+    /**
2057
+     * @return \OC\Session\CryptoWrapper
2058
+     */
2059
+    public function getSessionCryptoWrapper() {
2060
+        return $this->query('CryptoWrapper');
2061
+    }
2062
+
2063
+    /**
2064
+     * @return CsrfTokenManager
2065
+     */
2066
+    public function getCsrfTokenManager() {
2067
+        return $this->query(CsrfTokenManager::class);
2068
+    }
2069
+
2070
+    /**
2071
+     * @return Throttler
2072
+     */
2073
+    public function getBruteForceThrottler() {
2074
+        return $this->query(Throttler::class);
2075
+    }
2076
+
2077
+    /**
2078
+     * @return IContentSecurityPolicyManager
2079
+     */
2080
+    public function getContentSecurityPolicyManager() {
2081
+        return $this->query(ContentSecurityPolicyManager::class);
2082
+    }
2083
+
2084
+    /**
2085
+     * @return ContentSecurityPolicyNonceManager
2086
+     */
2087
+    public function getContentSecurityPolicyNonceManager() {
2088
+        return $this->query('ContentSecurityPolicyNonceManager');
2089
+    }
2090
+
2091
+    /**
2092
+     * Not a public API as of 8.2, wait for 9.0
2093
+     *
2094
+     * @return \OCA\Files_External\Service\BackendService
2095
+     */
2096
+    public function getStoragesBackendService() {
2097
+        return $this->query(BackendService::class);
2098
+    }
2099
+
2100
+    /**
2101
+     * Not a public API as of 8.2, wait for 9.0
2102
+     *
2103
+     * @return \OCA\Files_External\Service\GlobalStoragesService
2104
+     */
2105
+    public function getGlobalStoragesService() {
2106
+        return $this->query(GlobalStoragesService::class);
2107
+    }
2108
+
2109
+    /**
2110
+     * Not a public API as of 8.2, wait for 9.0
2111
+     *
2112
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
2113
+     */
2114
+    public function getUserGlobalStoragesService() {
2115
+        return $this->query(UserGlobalStoragesService::class);
2116
+    }
2117
+
2118
+    /**
2119
+     * Not a public API as of 8.2, wait for 9.0
2120
+     *
2121
+     * @return \OCA\Files_External\Service\UserStoragesService
2122
+     */
2123
+    public function getUserStoragesService() {
2124
+        return $this->query(UserStoragesService::class);
2125
+    }
2126
+
2127
+    /**
2128
+     * @return \OCP\Share\IManager
2129
+     */
2130
+    public function getShareManager() {
2131
+        return $this->query(\OCP\Share\IManager::class);
2132
+    }
2133
+
2134
+    /**
2135
+     * @return \OCP\Collaboration\Collaborators\ISearch
2136
+     */
2137
+    public function getCollaboratorSearch() {
2138
+        return $this->query(\OCP\Collaboration\Collaborators\ISearch::class);
2139
+    }
2140
+
2141
+    /**
2142
+     * @return \OCP\Collaboration\AutoComplete\IManager
2143
+     */
2144
+    public function getAutoCompleteManager() {
2145
+        return $this->query(IManager::class);
2146
+    }
2147
+
2148
+    /**
2149
+     * Returns the LDAP Provider
2150
+     *
2151
+     * @return \OCP\LDAP\ILDAPProvider
2152
+     */
2153
+    public function getLDAPProvider() {
2154
+        return $this->query('LDAPProvider');
2155
+    }
2156
+
2157
+    /**
2158
+     * @return \OCP\Settings\IManager
2159
+     */
2160
+    public function getSettingsManager() {
2161
+        return $this->query('SettingsManager');
2162
+    }
2163
+
2164
+    /**
2165
+     * @return \OCP\Files\IAppData
2166
+     */
2167
+    public function getAppDataDir($app) {
2168
+        /** @var \OC\Files\AppData\Factory $factory */
2169
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
2170
+        return $factory->get($app);
2171
+    }
2172
+
2173
+    /**
2174
+     * @return \OCP\Lockdown\ILockdownManager
2175
+     */
2176
+    public function getLockdownManager() {
2177
+        return $this->query('LockdownManager');
2178
+    }
2179
+
2180
+    /**
2181
+     * @return \OCP\Federation\ICloudIdManager
2182
+     */
2183
+    public function getCloudIdManager() {
2184
+        return $this->query(ICloudIdManager::class);
2185
+    }
2186
+
2187
+    /**
2188
+     * @return \OCP\GlobalScale\IConfig
2189
+     */
2190
+    public function getGlobalScaleConfig() {
2191
+        return $this->query(IConfig::class);
2192
+    }
2193
+
2194
+    /**
2195
+     * @return \OCP\Federation\ICloudFederationProviderManager
2196
+     */
2197
+    public function getCloudFederationProviderManager() {
2198
+        return $this->query(ICloudFederationProviderManager::class);
2199
+    }
2200
+
2201
+    /**
2202
+     * @return \OCP\Remote\Api\IApiFactory
2203
+     */
2204
+    public function getRemoteApiFactory() {
2205
+        return $this->query(IApiFactory::class);
2206
+    }
2207
+
2208
+    /**
2209
+     * @return \OCP\Federation\ICloudFederationFactory
2210
+     */
2211
+    public function getCloudFederationFactory() {
2212
+        return $this->query(ICloudFederationFactory::class);
2213
+    }
2214
+
2215
+    /**
2216
+     * @return \OCP\Remote\IInstanceFactory
2217
+     */
2218
+    public function getRemoteInstanceFactory() {
2219
+        return $this->query(IInstanceFactory::class);
2220
+    }
2221
+
2222
+    /**
2223
+     * @return IStorageFactory
2224
+     */
2225
+    public function getStorageFactory() {
2226
+        return $this->query(IStorageFactory::class);
2227
+    }
2228
+
2229
+    /**
2230
+     * Get the Preview GeneratorHelper
2231
+     *
2232
+     * @return GeneratorHelper
2233
+     * @since 17.0.0
2234
+     */
2235
+    public function getGeneratorHelper() {
2236
+        return $this->query(\OC\Preview\GeneratorHelper::class);
2237
+    }
2238
+
2239
+    private function registerDeprecatedAlias(string $alias, string $target) {
2240
+        $this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2241
+            try {
2242
+                /** @var ILogger $logger */
2243
+                $logger = $container->query(ILogger::class);
2244
+                $logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2245
+            } catch (QueryException $e) {
2246
+                // Could not get logger. Continue
2247
+            }
2248
+
2249
+            return $container->query($target);
2250
+        }, false);
2251
+    }
2252 2252
 }
Please login to merge, or discard this patch.
Spacing   +124 added lines, -124 removed lines patch added patch discarded remove patch
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 		// To find out if we are running from CLI or not
257 257
 		$this->registerParameter('isCLI', \OC::$CLI);
258 258
 
259
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
259
+		$this->registerService(\OCP\IServerContainer::class, function(IServerContainer $c) {
260 260
 			return $c;
261 261
 		});
262 262
 
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
278 278
 
279 279
 
280
-		$this->registerService(IPreview::class, function (Server $c) {
280
+		$this->registerService(IPreview::class, function(Server $c) {
281 281
 			return new PreviewManager(
282 282
 				$c->getConfig(),
283 283
 				$c->getRootFolder(),
@@ -289,13 +289,13 @@  discard block
 block discarded – undo
289 289
 		});
290 290
 		$this->registerDeprecatedAlias('PreviewManager', IPreview::class);
291 291
 
292
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
292
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
293 293
 			return new \OC\Preview\Watcher(
294 294
 				$c->getAppDataDir('preview')
295 295
 			);
296 296
 		});
297 297
 
298
-		$this->registerService(\OCP\Encryption\IManager::class, function (Server $c) {
298
+		$this->registerService(\OCP\Encryption\IManager::class, function(Server $c) {
299 299
 			$view = new View();
300 300
 			$util = new Encryption\Util(
301 301
 				$view,
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 		});
315 315
 		$this->registerDeprecatedAlias('EncryptionManager', \OCP\Encryption\IManager::class);
316 316
 
317
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
317
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
318 318
 			$util = new Encryption\Util(
319 319
 				new View(),
320 320
 				$c->getUserManager(),
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 			);
329 329
 		});
330 330
 
331
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
331
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
332 332
 			$view = new View();
333 333
 			$util = new Encryption\Util(
334 334
 				$view,
@@ -339,30 +339,30 @@  discard block
 block discarded – undo
339 339
 
340 340
 			return new Encryption\Keys\Storage($view, $util);
341 341
 		});
342
-		$this->registerService('TagMapper', function (Server $c) {
342
+		$this->registerService('TagMapper', function(Server $c) {
343 343
 			return new TagMapper($c->getDatabaseConnection());
344 344
 		});
345 345
 
346
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
346
+		$this->registerService(\OCP\ITagManager::class, function(Server $c) {
347 347
 			$tagMapper = $c->query('TagMapper');
348 348
 			return new TagManager($tagMapper, $c->getUserSession());
349 349
 		});
350 350
 		$this->registerDeprecatedAlias('TagManager', \OCP\ITagManager::class);
351 351
 
352
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
352
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
353 353
 			$config = $c->getConfig();
354 354
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
355 355
 			return new $factoryClass($this);
356 356
 		});
357
-		$this->registerService(ISystemTagManager::class, function (Server $c) {
357
+		$this->registerService(ISystemTagManager::class, function(Server $c) {
358 358
 			return $c->query('SystemTagManagerFactory')->getManager();
359 359
 		});
360 360
 		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
361 361
 
362
-		$this->registerService(ISystemTagObjectMapper::class, function (Server $c) {
362
+		$this->registerService(ISystemTagObjectMapper::class, function(Server $c) {
363 363
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
364 364
 		});
365
-		$this->registerService('RootFolder', function (Server $c) {
365
+		$this->registerService('RootFolder', function(Server $c) {
366 366
 			$manager = \OC\Files\Filesystem::getMountManager(null);
367 367
 			$view = new View();
368 368
 			$root = new Root(
@@ -383,8 +383,8 @@  discard block
 block discarded – undo
383 383
 		});
384 384
 		$this->registerDeprecatedAlias('SystemTagObjectMapper', ISystemTagObjectMapper::class);
385 385
 
386
-		$this->registerService(IRootFolder::class, function (Server $c) {
387
-			return new LazyRoot(function () use ($c) {
386
+		$this->registerService(IRootFolder::class, function(Server $c) {
387
+			return new LazyRoot(function() use ($c) {
388 388
 				return $c->query('RootFolder');
389 389
 			});
390 390
 		});
@@ -393,44 +393,44 @@  discard block
 block discarded – undo
393 393
 		$this->registerDeprecatedAlias('UserManager', \OC\User\Manager::class);
394 394
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
395 395
 
396
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
396
+		$this->registerService(\OCP\IGroupManager::class, function(Server $c) {
397 397
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $c->getEventDispatcher(), $this->getLogger());
398
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
398
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
399 399
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', ['run' => true, 'gid' => $gid]);
400 400
 
401 401
 				/** @var IEventDispatcher $dispatcher */
402 402
 				$dispatcher = $this->query(IEventDispatcher::class);
403 403
 				$dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
404 404
 			});
405
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $group) {
405
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $group) {
406 406
 				\OC_Hook::emit('OC_User', 'post_createGroup', ['gid' => $group->getGID()]);
407 407
 
408 408
 				/** @var IEventDispatcher $dispatcher */
409 409
 				$dispatcher = $this->query(IEventDispatcher::class);
410 410
 				$dispatcher->dispatchTyped(new GroupCreatedEvent($group));
411 411
 			});
412
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
412
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
413 413
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', ['run' => true, 'gid' => $group->getGID()]);
414 414
 
415 415
 				/** @var IEventDispatcher $dispatcher */
416 416
 				$dispatcher = $this->query(IEventDispatcher::class);
417 417
 				$dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group));
418 418
 			});
419
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
419
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
420 420
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', ['gid' => $group->getGID()]);
421 421
 
422 422
 				/** @var IEventDispatcher $dispatcher */
423 423
 				$dispatcher = $this->query(IEventDispatcher::class);
424 424
 				$dispatcher->dispatchTyped(new GroupDeletedEvent($group));
425 425
 			});
426
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
426
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
427 427
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', ['run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()]);
428 428
 
429 429
 				/** @var IEventDispatcher $dispatcher */
430 430
 				$dispatcher = $this->query(IEventDispatcher::class);
431 431
 				$dispatcher->dispatchTyped(new BeforeUserAddedEvent($group, $user));
432 432
 			});
433
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
433
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
434 434
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
435 435
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
436 436
 				\OC_Hook::emit('OC_User', 'post_addToGroup', ['uid' => $user->getUID(), 'gid' => $group->getGID()]);
@@ -439,12 +439,12 @@  discard block
 block discarded – undo
439 439
 				$dispatcher = $this->query(IEventDispatcher::class);
440 440
 				$dispatcher->dispatchTyped(new UserAddedEvent($group, $user));
441 441
 			});
442
-			$groupManager->listen('\OC\Group', 'preRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
442
+			$groupManager->listen('\OC\Group', 'preRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
443 443
 				/** @var IEventDispatcher $dispatcher */
444 444
 				$dispatcher = $this->query(IEventDispatcher::class);
445 445
 				$dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $user));
446 446
 			});
447
-			$groupManager->listen('\OC\Group', 'postRemoveUser', function (\OC\Group\Group $group, \OC\User\User $user) {
447
+			$groupManager->listen('\OC\Group', 'postRemoveUser', function(\OC\Group\Group $group, \OC\User\User $user) {
448 448
 				/** @var IEventDispatcher $dispatcher */
449 449
 				$dispatcher = $this->query(IEventDispatcher::class);
450 450
 				$dispatcher->dispatchTyped(new UserRemovedEvent($group, $user));
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 		});
454 454
 		$this->registerDeprecatedAlias('GroupManager', \OCP\IGroupManager::class);
455 455
 
456
-		$this->registerService(Store::class, function (Server $c) {
456
+		$this->registerService(Store::class, function(Server $c) {
457 457
 			$session = $c->getSession();
458 458
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
459 459
 				$tokenProvider = $c->query(IProvider::class);
@@ -464,13 +464,13 @@  discard block
 block discarded – undo
464 464
 			return new Store($session, $logger, $tokenProvider);
465 465
 		});
466 466
 		$this->registerAlias(IStore::class, Store::class);
467
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
467
+		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function(Server $c) {
468 468
 			$dbConnection = $c->getDatabaseConnection();
469 469
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
470 470
 		});
471 471
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
472 472
 
473
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
473
+		$this->registerService(\OC\User\Session::class, function(Server $c) {
474 474
 			$manager = $c->getUserManager();
475 475
 			$session = new \OC\Session\Memory('');
476 476
 			$timeFactory = new TimeFactory();
@@ -495,14 +495,14 @@  discard block
 block discarded – undo
495 495
 				$c->getLogger(),
496 496
 				$c->query(IEventDispatcher::class)
497 497
 			);
498
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
498
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
499 499
 				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
500 500
 
501 501
 				/** @var IEventDispatcher $dispatcher */
502 502
 				$dispatcher = $this->query(IEventDispatcher::class);
503 503
 				$dispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
504 504
 			});
505
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
505
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
506 506
 				/** @var $user \OC\User\User */
507 507
 				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
508 508
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 				$dispatcher = $this->query(IEventDispatcher::class);
511 511
 				$dispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
512 512
 			});
513
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($legacyDispatcher) {
513
+			$userSession->listen('\OC\User', 'preDelete', function($user) use ($legacyDispatcher) {
514 514
 				/** @var $user \OC\User\User */
515 515
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
516 516
 				$legacyDispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
@@ -519,7 +519,7 @@  discard block
 block discarded – undo
519 519
 				$dispatcher = $this->query(IEventDispatcher::class);
520 520
 				$dispatcher->dispatchTyped(new BeforeUserDeletedEvent($user));
521 521
 			});
522
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
522
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
523 523
 				/** @var $user \OC\User\User */
524 524
 				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
525 525
 
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
 				$dispatcher = $this->query(IEventDispatcher::class);
528 528
 				$dispatcher->dispatchTyped(new UserDeletedEvent($user));
529 529
 			});
530
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
530
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
531 531
 				/** @var $user \OC\User\User */
532 532
 				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
533 533
 
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
 				$dispatcher = $this->query(IEventDispatcher::class);
536 536
 				$dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($user, $password, $recoveryPassword));
537 537
 			});
538
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
538
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
539 539
 				/** @var $user \OC\User\User */
540 540
 				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
541 541
 
@@ -543,14 +543,14 @@  discard block
 block discarded – undo
543 543
 				$dispatcher = $this->query(IEventDispatcher::class);
544 544
 				$dispatcher->dispatchTyped(new PasswordUpdatedEvent($user, $password, $recoveryPassword));
545 545
 			});
546
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
546
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
547 547
 				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
548 548
 
549 549
 				/** @var IEventDispatcher $dispatcher */
550 550
 				$dispatcher = $this->query(IEventDispatcher::class);
551 551
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
552 552
 			});
553
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password, $isTokenLogin) {
553
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password, $isTokenLogin) {
554 554
 				/** @var $user \OC\User\User */
555 555
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
556 556
 
@@ -558,12 +558,12 @@  discard block
 block discarded – undo
558 558
 				$dispatcher = $this->query(IEventDispatcher::class);
559 559
 				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $password, $isTokenLogin));
560 560
 			});
561
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
561
+			$userSession->listen('\OC\User', 'preRememberedLogin', function($uid) {
562 562
 				/** @var IEventDispatcher $dispatcher */
563 563
 				$dispatcher = $this->query(IEventDispatcher::class);
564 564
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
565 565
 			});
566
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
566
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
567 567
 				/** @var $user \OC\User\User */
568 568
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
569 569
 
@@ -571,19 +571,19 @@  discard block
 block discarded – undo
571 571
 				$dispatcher = $this->query(IEventDispatcher::class);
572 572
 				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
573 573
 			});
574
-			$userSession->listen('\OC\User', 'logout', function ($user) {
574
+			$userSession->listen('\OC\User', 'logout', function($user) {
575 575
 				\OC_Hook::emit('OC_User', 'logout', []);
576 576
 
577 577
 				/** @var IEventDispatcher $dispatcher */
578 578
 				$dispatcher = $this->query(IEventDispatcher::class);
579 579
 				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
580 580
 			});
581
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
581
+			$userSession->listen('\OC\User', 'postLogout', function($user) {
582 582
 				/** @var IEventDispatcher $dispatcher */
583 583
 				$dispatcher = $this->query(IEventDispatcher::class);
584 584
 				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
585 585
 			});
586
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
586
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
587 587
 				/** @var $user \OC\User\User */
588 588
 				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
589 589
 
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
 		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
602 602
 		$this->registerDeprecatedAlias('NavigationManager', INavigationManager::class);
603 603
 
604
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
604
+		$this->registerService(\OC\AllConfig::class, function(Server $c) {
605 605
 			return new \OC\AllConfig(
606 606
 				$c->getSystemConfig()
607 607
 			);
@@ -609,18 +609,18 @@  discard block
 block discarded – undo
609 609
 		$this->registerDeprecatedAlias('AllConfig', \OC\AllConfig::class);
610 610
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
611 611
 
612
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
612
+		$this->registerService(\OC\SystemConfig::class, function($c) use ($config) {
613 613
 			return new \OC\SystemConfig($config);
614 614
 		});
615 615
 		$this->registerDeprecatedAlias('SystemConfig', \OC\SystemConfig::class);
616 616
 
617
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
617
+		$this->registerService(\OC\AppConfig::class, function(Server $c) {
618 618
 			return new \OC\AppConfig($c->getDatabaseConnection());
619 619
 		});
620 620
 		$this->registerDeprecatedAlias('AppConfig', \OC\AppConfig::class);
621 621
 		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
622 622
 
623
-		$this->registerService(IFactory::class, function (Server $c) {
623
+		$this->registerService(IFactory::class, function(Server $c) {
624 624
 			return new \OC\L10N\Factory(
625 625
 				$c->getConfig(),
626 626
 				$c->getRequest(),
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
 		});
631 631
 		$this->registerDeprecatedAlias('L10NFactory', IFactory::class);
632 632
 
633
-		$this->registerService(IURLGenerator::class, function (Server $c) {
633
+		$this->registerService(IURLGenerator::class, function(Server $c) {
634 634
 			$config = $c->getConfig();
635 635
 			$cacheFactory = $c->getMemCacheFactory();
636 636
 			$request = $c->getRequest();
@@ -645,12 +645,12 @@  discard block
 block discarded – undo
645 645
 		$this->registerDeprecatedAlias('AppFetcher', AppFetcher::class);
646 646
 		$this->registerDeprecatedAlias('CategoryFetcher', CategoryFetcher::class);
647 647
 
648
-		$this->registerService(ICache::class, function ($c) {
648
+		$this->registerService(ICache::class, function($c) {
649 649
 			return new Cache\File();
650 650
 		});
651 651
 		$this->registerDeprecatedAlias('UserCache', ICache::class);
652 652
 
653
-		$this->registerService(Factory::class, function (Server $c) {
653
+		$this->registerService(Factory::class, function(Server $c) {
654 654
 
655 655
 			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
656 656
 				ArrayCache::class,
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
 				$version = implode(',', $v);
666 666
 				$instanceId = \OC_Util::getInstanceId();
667 667
 				$path = \OC::$SERVERROOT;
668
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
668
+				$prefix = md5($instanceId.'-'.$version.'-'.$path);
669 669
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
670 670
 					$config->getSystemValue('memcache.local', null),
671 671
 					$config->getSystemValue('memcache.distributed', null),
@@ -678,12 +678,12 @@  discard block
 block discarded – undo
678 678
 		$this->registerDeprecatedAlias('MemCacheFactory', Factory::class);
679 679
 		$this->registerAlias(ICacheFactory::class, Factory::class);
680 680
 
681
-		$this->registerService('RedisFactory', function (Server $c) {
681
+		$this->registerService('RedisFactory', function(Server $c) {
682 682
 			$systemConfig = $c->getSystemConfig();
683 683
 			return new RedisFactory($systemConfig);
684 684
 		});
685 685
 
686
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
686
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
687 687
 			return new \OC\Activity\Manager(
688 688
 				$c->getRequest(),
689 689
 				$c->getUserSession(),
@@ -693,14 +693,14 @@  discard block
 block discarded – undo
693 693
 		});
694 694
 		$this->registerDeprecatedAlias('ActivityManager', \OCP\Activity\IManager::class);
695 695
 
696
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
696
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
697 697
 			return new \OC\Activity\EventMerger(
698 698
 				$c->getL10N('lib')
699 699
 			);
700 700
 		});
701 701
 		$this->registerAlias(IValidator::class, Validator::class);
702 702
 
703
-		$this->registerService(AvatarManager::class, function (Server $c) {
703
+		$this->registerService(AvatarManager::class, function(Server $c) {
704 704
 			return new AvatarManager(
705 705
 				$c->query(\OC\User\Manager::class),
706 706
 				$c->getAppDataDir('avatar'),
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
716 716
 		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
717 717
 
718
-		$this->registerService(\OC\Log::class, function (Server $c) {
718
+		$this->registerService(\OC\Log::class, function(Server $c) {
719 719
 			$logType = $c->query(AllConfig::class)->getSystemValue('log_type', 'file');
720 720
 			$factory = new LogFactory($c, $this->getSystemConfig());
721 721
 			$logger = $factory->get($logType);
@@ -728,11 +728,11 @@  discard block
 block discarded – undo
728 728
 		// PSR-3 logger
729 729
 		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
730 730
 
731
-		$this->registerService(ILogFactory::class, function (Server $c) {
731
+		$this->registerService(ILogFactory::class, function(Server $c) {
732 732
 			return new LogFactory($c, $this->getSystemConfig());
733 733
 		});
734 734
 
735
-		$this->registerService(IJobList::class, function (Server $c) {
735
+		$this->registerService(IJobList::class, function(Server $c) {
736 736
 			$config = $c->getConfig();
737 737
 			return new \OC\BackgroundJob\JobList(
738 738
 				$c->getDatabaseConnection(),
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 		});
743 743
 		$this->registerDeprecatedAlias('JobList', IJobList::class);
744 744
 
745
-		$this->registerService(IRouter::class, function (Server $c) {
745
+		$this->registerService(IRouter::class, function(Server $c) {
746 746
 			$cacheFactory = $c->getMemCacheFactory();
747 747
 			$logger = $c->getLogger();
748 748
 			if ($cacheFactory->isLocalCacheAvailable()) {
@@ -754,39 +754,39 @@  discard block
 block discarded – undo
754 754
 		});
755 755
 		$this->registerDeprecatedAlias('Router', IRouter::class);
756 756
 
757
-		$this->registerService(ISearch::class, function ($c) {
757
+		$this->registerService(ISearch::class, function($c) {
758 758
 			return new Search();
759 759
 		});
760 760
 		$this->registerDeprecatedAlias('Search', ISearch::class);
761 761
 
762
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
762
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
763 763
 			return new \OC\Security\RateLimiting\Backend\MemoryCache(
764 764
 				$this->getMemCacheFactory(),
765 765
 				new \OC\AppFramework\Utility\TimeFactory()
766 766
 			);
767 767
 		});
768 768
 
769
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
769
+		$this->registerService(\OCP\Security\ISecureRandom::class, function($c) {
770 770
 			return new SecureRandom();
771 771
 		});
772 772
 		$this->registerDeprecatedAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
773 773
 
774
-		$this->registerService(ICrypto::class, function (Server $c) {
774
+		$this->registerService(ICrypto::class, function(Server $c) {
775 775
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
776 776
 		});
777 777
 		$this->registerDeprecatedAlias('Crypto', ICrypto::class);
778 778
 
779
-		$this->registerService(IHasher::class, function (Server $c) {
779
+		$this->registerService(IHasher::class, function(Server $c) {
780 780
 			return new Hasher($c->getConfig());
781 781
 		});
782 782
 		$this->registerDeprecatedAlias('Hasher', IHasher::class);
783 783
 
784
-		$this->registerService(ICredentialsManager::class, function (Server $c) {
784
+		$this->registerService(ICredentialsManager::class, function(Server $c) {
785 785
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
786 786
 		});
787 787
 		$this->registerDeprecatedAlias('CredentialsManager', ICredentialsManager::class);
788 788
 
789
-		$this->registerService(IDBConnection::class, function (Server $c) {
789
+		$this->registerService(IDBConnection::class, function(Server $c) {
790 790
 			$systemConfig = $c->getSystemConfig();
791 791
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
792 792
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
 		$this->registerDeprecatedAlias('DatabaseConnection', IDBConnection::class);
802 802
 
803 803
 
804
-		$this->registerService(IClientService::class, function (Server $c) {
804
+		$this->registerService(IClientService::class, function(Server $c) {
805 805
 			$user = \OC_User::getUser();
806 806
 			$uid = $user ? $user : null;
807 807
 			return new ClientService(
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
 			);
817 817
 		});
818 818
 		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
819
-		$this->registerService(IEventLogger::class, function (Server $c) {
819
+		$this->registerService(IEventLogger::class, function(Server $c) {
820 820
 			$eventLogger = new EventLogger();
821 821
 			if ($c->getSystemConfig()->getValue('debug', false)) {
822 822
 				// In debug mode, module is being activated by default
@@ -826,7 +826,7 @@  discard block
 block discarded – undo
826 826
 		});
827 827
 		$this->registerDeprecatedAlias('EventLogger', IEventLogger::class);
828 828
 
829
-		$this->registerService(IQueryLogger::class, function (Server $c) {
829
+		$this->registerService(IQueryLogger::class, function(Server $c) {
830 830
 			$queryLogger = new QueryLogger();
831 831
 			if ($c->getSystemConfig()->getValue('debug', false)) {
832 832
 				// In debug mode, module is being activated by default
@@ -836,7 +836,7 @@  discard block
 block discarded – undo
836 836
 		});
837 837
 		$this->registerDeprecatedAlias('QueryLogger', IQueryLogger::class);
838 838
 
839
-		$this->registerService(TempManager::class, function (Server $c) {
839
+		$this->registerService(TempManager::class, function(Server $c) {
840 840
 			return new TempManager(
841 841
 				$c->getLogger(),
842 842
 				$c->getConfig()
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 		$this->registerDeprecatedAlias('TempManager', TempManager::class);
846 846
 		$this->registerAlias(ITempManager::class, TempManager::class);
847 847
 
848
-		$this->registerService(AppManager::class, function (Server $c) {
848
+		$this->registerService(AppManager::class, function(Server $c) {
849 849
 			return new \OC\App\AppManager(
850 850
 				$c->getUserSession(),
851 851
 				$c->getConfig(),
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		$this->registerDeprecatedAlias('AppManager', AppManager::class);
860 860
 		$this->registerAlias(IAppManager::class, AppManager::class);
861 861
 
862
-		$this->registerService(IDateTimeZone::class, function (Server $c) {
862
+		$this->registerService(IDateTimeZone::class, function(Server $c) {
863 863
 			return new DateTimeZone(
864 864
 				$c->getConfig(),
865 865
 				$c->getSession()
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
 		});
868 868
 		$this->registerDeprecatedAlias('DateTimeZone', IDateTimeZone::class);
869 869
 
870
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
870
+		$this->registerService(IDateTimeFormatter::class, function(Server $c) {
871 871
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
872 872
 
873 873
 			return new DateTimeFormatter(
@@ -877,7 +877,7 @@  discard block
 block discarded – undo
877 877
 		});
878 878
 		$this->registerDeprecatedAlias('DateTimeFormatter', IDateTimeFormatter::class);
879 879
 
880
-		$this->registerService(IUserMountCache::class, function (Server $c) {
880
+		$this->registerService(IUserMountCache::class, function(Server $c) {
881 881
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
882 882
 			$listener = new UserMountCacheListener($mountCache);
883 883
 			$listener->listen($c->getUserManager());
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
 		});
886 886
 		$this->registerDeprecatedAlias('UserMountCache', IUserMountCache::class);
887 887
 
888
-		$this->registerService(IMountProviderCollection::class, function (Server $c) {
888
+		$this->registerService(IMountProviderCollection::class, function(Server $c) {
889 889
 			$loader = \OC\Files\Filesystem::getLoader();
890 890
 			$mountCache = $c->query(IUserMountCache::class);
891 891
 			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
@@ -901,10 +901,10 @@  discard block
 block discarded – undo
901 901
 		});
902 902
 		$this->registerDeprecatedAlias('MountConfigManager', IMountProviderCollection::class);
903 903
 
904
-		$this->registerService('IniWrapper', function ($c) {
904
+		$this->registerService('IniWrapper', function($c) {
905 905
 			return new IniGetWrapper();
906 906
 		});
907
-		$this->registerService('AsyncCommandBus', function (Server $c) {
907
+		$this->registerService('AsyncCommandBus', function(Server $c) {
908 908
 			$busClass = $c->getConfig()->getSystemValue('commandbus');
909 909
 			if ($busClass) {
910 910
 				list($app, $class) = explode('::', $busClass, 2);
@@ -919,10 +919,10 @@  discard block
 block discarded – undo
919 919
 				return new CronBus($jobList);
920 920
 			}
921 921
 		});
922
-		$this->registerService('TrustedDomainHelper', function ($c) {
922
+		$this->registerService('TrustedDomainHelper', function($c) {
923 923
 			return new TrustedDomainHelper($this->getConfig());
924 924
 		});
925
-		$this->registerService(Throttler::class, function (Server $c) {
925
+		$this->registerService(Throttler::class, function(Server $c) {
926 926
 			return new Throttler(
927 927
 				$c->getDatabaseConnection(),
928 928
 				new TimeFactory(),
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
 			);
932 932
 		});
933 933
 		$this->registerDeprecatedAlias('Throttler', Throttler::class);
934
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
934
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
935 935
 			// IConfig and IAppManager requires a working database. This code
936 936
 			// might however be called when ownCloud is not yet setup.
937 937
 			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
 				$c->getMimeTypeDetector()
954 954
 			);
955 955
 		});
956
-		$this->registerService(\OCP\IRequest::class, function ($c) {
956
+		$this->registerService(\OCP\IRequest::class, function($c) {
957 957
 			if (isset($this['urlParams'])) {
958 958
 				$urlParams = $this['urlParams'];
959 959
 			} else {
@@ -989,7 +989,7 @@  discard block
 block discarded – undo
989 989
 		});
990 990
 		$this->registerDeprecatedAlias('Request', \OCP\IRequest::class);
991 991
 
992
-		$this->registerService(IMailer::class, function (Server $c) {
992
+		$this->registerService(IMailer::class, function(Server $c) {
993 993
 			return new Mailer(
994 994
 				$c->getConfig(),
995 995
 				$c->getLogger(),
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 		});
1002 1002
 		$this->registerDeprecatedAlias('Mailer', IMailer::class);
1003 1003
 
1004
-		$this->registerService('LDAPProvider', function (Server $c) {
1004
+		$this->registerService('LDAPProvider', function(Server $c) {
1005 1005
 			$config = $c->getConfig();
1006 1006
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
1007 1007
 			if (is_null($factoryClass)) {
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 			$factory = new $factoryClass($this);
1012 1012
 			return $factory->getLDAPProvider();
1013 1013
 		});
1014
-		$this->registerService(ILockingProvider::class, function (Server $c) {
1014
+		$this->registerService(ILockingProvider::class, function(Server $c) {
1015 1015
 			$ini = $c->getIniWrapper();
1016 1016
 			$config = $c->getConfig();
1017 1017
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -1034,31 +1034,31 @@  discard block
 block discarded – undo
1034 1034
 		});
1035 1035
 		$this->registerDeprecatedAlias('LockingProvider', ILockingProvider::class);
1036 1036
 
1037
-		$this->registerService(IMountManager::class, function () {
1037
+		$this->registerService(IMountManager::class, function() {
1038 1038
 			return new \OC\Files\Mount\Manager();
1039 1039
 		});
1040 1040
 		$this->registerDeprecatedAlias('MountManager', IMountManager::class);
1041 1041
 
1042
-		$this->registerService(IMimeTypeDetector::class, function (Server $c) {
1042
+		$this->registerService(IMimeTypeDetector::class, function(Server $c) {
1043 1043
 			return new \OC\Files\Type\Detection(
1044 1044
 				$c->getURLGenerator(),
1045 1045
 				$c->getLogger(),
1046 1046
 				\OC::$configDir,
1047
-				\OC::$SERVERROOT . '/resources/config/'
1047
+				\OC::$SERVERROOT.'/resources/config/'
1048 1048
 			);
1049 1049
 		});
1050 1050
 		$this->registerDeprecatedAlias('MimeTypeDetector', IMimeTypeDetector::class);
1051 1051
 
1052
-		$this->registerService(IMimeTypeLoader::class, function (Server $c) {
1052
+		$this->registerService(IMimeTypeLoader::class, function(Server $c) {
1053 1053
 			return new \OC\Files\Type\Loader(
1054 1054
 				$c->getDatabaseConnection()
1055 1055
 			);
1056 1056
 		});
1057 1057
 		$this->registerDeprecatedAlias('MimeTypeLoader', IMimeTypeLoader::class);
1058
-		$this->registerService(BundleFetcher::class, function () {
1058
+		$this->registerService(BundleFetcher::class, function() {
1059 1059
 			return new BundleFetcher($this->getL10N('lib'));
1060 1060
 		});
1061
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
1061
+		$this->registerService(\OCP\Notification\IManager::class, function(Server $c) {
1062 1062
 			return new Manager(
1063 1063
 				$c->query(IValidator::class),
1064 1064
 				$c->getLogger()
@@ -1066,29 +1066,29 @@  discard block
 block discarded – undo
1066 1066
 		});
1067 1067
 		$this->registerDeprecatedAlias('NotificationManager', \OCP\Notification\IManager::class);
1068 1068
 
1069
-		$this->registerService(CapabilitiesManager::class, function (Server $c) {
1069
+		$this->registerService(CapabilitiesManager::class, function(Server $c) {
1070 1070
 			$manager = new CapabilitiesManager($c->getLogger());
1071
-			$manager->registerCapability(function () use ($c) {
1071
+			$manager->registerCapability(function() use ($c) {
1072 1072
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
1073 1073
 			});
1074
-			$manager->registerCapability(function () use ($c) {
1074
+			$manager->registerCapability(function() use ($c) {
1075 1075
 				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
1076 1076
 			});
1077 1077
 			return $manager;
1078 1078
 		});
1079 1079
 		$this->registerDeprecatedAlias('CapabilitiesManager', CapabilitiesManager::class);
1080 1080
 
1081
-		$this->registerService(ICommentsManager::class, function (Server $c) {
1081
+		$this->registerService(ICommentsManager::class, function(Server $c) {
1082 1082
 			$config = $c->getConfig();
1083 1083
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
1084 1084
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
1085 1085
 			$factory = new $factoryClass($this);
1086 1086
 			$manager = $factory->getManager();
1087 1087
 
1088
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
1088
+			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
1089 1089
 				$manager = $c->getUserManager();
1090 1090
 				$user = $manager->get($id);
1091
-				if(is_null($user)) {
1091
+				if (is_null($user)) {
1092 1092
 					$l = $c->getL10N('core');
1093 1093
 					$displayName = $l->t('Unknown user');
1094 1094
 				} else {
@@ -1101,7 +1101,7 @@  discard block
 block discarded – undo
1101 1101
 		});
1102 1102
 		$this->registerDeprecatedAlias('CommentsManager', ICommentsManager::class);
1103 1103
 
1104
-		$this->registerService('ThemingDefaults', function (Server $c) {
1104
+		$this->registerService('ThemingDefaults', function(Server $c) {
1105 1105
 			/*
1106 1106
 			 * Dark magic for autoloader.
1107 1107
 			 * If we do a class_exists it will try to load the class which will
@@ -1129,7 +1129,7 @@  discard block
 block discarded – undo
1129 1129
 			}
1130 1130
 			return new \OC_Defaults();
1131 1131
 		});
1132
-		$this->registerService(SCSSCacher::class, function (Server $c) {
1132
+		$this->registerService(SCSSCacher::class, function(Server $c) {
1133 1133
 			return new SCSSCacher(
1134 1134
 				$c->getLogger(),
1135 1135
 				$c->query(\OC\Files\AppData\Factory::class),
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
 				new TimeFactory()
1143 1143
 			);
1144 1144
 		});
1145
-		$this->registerService(JSCombiner::class, function (Server $c) {
1145
+		$this->registerService(JSCombiner::class, function(Server $c) {
1146 1146
 			return new JSCombiner(
1147 1147
 				$c->getAppDataDir('js'),
1148 1148
 				$c->getURLGenerator(),
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
 		$this->registerDeprecatedAlias('EventDispatcher', \OC\EventDispatcher\SymfonyAdapter::class);
1156 1156
 		$this->registerAlias(EventDispatcherInterface::class, \OC\EventDispatcher\SymfonyAdapter::class);
1157 1157
 
1158
-		$this->registerService('CryptoWrapper', function (Server $c) {
1158
+		$this->registerService('CryptoWrapper', function(Server $c) {
1159 1159
 			// FIXME: Instantiiated here due to cyclic dependency
1160 1160
 			$request = new Request(
1161 1161
 				[
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
 				$request
1181 1181
 			);
1182 1182
 		});
1183
-		$this->registerService(CsrfTokenManager::class, function (Server $c) {
1183
+		$this->registerService(CsrfTokenManager::class, function(Server $c) {
1184 1184
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1185 1185
 
1186 1186
 			return new CsrfTokenManager(
@@ -1189,20 +1189,20 @@  discard block
 block discarded – undo
1189 1189
 			);
1190 1190
 		});
1191 1191
 		$this->registerDeprecatedAlias('CsrfTokenManager', CsrfTokenManager::class);
1192
-		$this->registerService(SessionStorage::class, function (Server $c) {
1192
+		$this->registerService(SessionStorage::class, function(Server $c) {
1193 1193
 			return new SessionStorage($c->getSession());
1194 1194
 		});
1195 1195
 		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1196 1196
 		$this->registerDeprecatedAlias('ContentSecurityPolicyManager', ContentSecurityPolicyManager::class);
1197 1197
 
1198
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1198
+		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
1199 1199
 			return new ContentSecurityPolicyNonceManager(
1200 1200
 				$c->getCsrfTokenManager(),
1201 1201
 				$c->getRequest()
1202 1202
 			);
1203 1203
 		});
1204 1204
 
1205
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1205
+		$this->registerService(\OCP\Share\IManager::class, function(Server $c) {
1206 1206
 			$config = $c->getConfig();
1207 1207
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1208 1208
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1231,7 +1231,7 @@  discard block
 block discarded – undo
1231 1231
 		});
1232 1232
 		$this->registerDeprecatedAlias('ShareManager', \OCP\Share\IManager::class);
1233 1233
 
1234
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1234
+		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1235 1235
 			$instance = new Collaboration\Collaborators\Search($c);
1236 1236
 
1237 1237
 			// register default plugins
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
 		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1252 1252
 		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1253 1253
 
1254
-		$this->registerService('SettingsManager', function (Server $c) {
1254
+		$this->registerService('SettingsManager', function(Server $c) {
1255 1255
 			$manager = new \OC\Settings\Manager(
1256 1256
 				$c->getLogger(),
1257 1257
 				$c->getL10NFactory(),
@@ -1260,36 +1260,36 @@  discard block
 block discarded – undo
1260 1260
 			);
1261 1261
 			return $manager;
1262 1262
 		});
1263
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1263
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
1264 1264
 			return new \OC\Files\AppData\Factory(
1265 1265
 				$c->getRootFolder(),
1266 1266
 				$c->getSystemConfig()
1267 1267
 			);
1268 1268
 		});
1269 1269
 
1270
-		$this->registerService('LockdownManager', function (Server $c) {
1271
-			return new LockdownManager(function () use ($c) {
1270
+		$this->registerService('LockdownManager', function(Server $c) {
1271
+			return new LockdownManager(function() use ($c) {
1272 1272
 				return $c->getSession();
1273 1273
 			});
1274 1274
 		});
1275 1275
 
1276
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1276
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(Server $c) {
1277 1277
 			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1278 1278
 		});
1279 1279
 
1280
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1280
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
1281 1281
 			return new CloudIdManager();
1282 1282
 		});
1283 1283
 
1284
-		$this->registerService(IConfig::class, function (Server $c) {
1284
+		$this->registerService(IConfig::class, function(Server $c) {
1285 1285
 			return new GlobalScale\Config($c->getConfig());
1286 1286
 		});
1287 1287
 
1288
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1288
+		$this->registerService(ICloudFederationProviderManager::class, function(Server $c) {
1289 1289
 			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1290 1290
 		});
1291 1291
 
1292
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1292
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1293 1293
 			return new CloudFederationFactory();
1294 1294
 		});
1295 1295
 
@@ -1299,24 +1299,24 @@  discard block
 block discarded – undo
1299 1299
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1300 1300
 		$this->registerDeprecatedAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1301 1301
 
1302
-		$this->registerService(Defaults::class, function (Server $c) {
1302
+		$this->registerService(Defaults::class, function(Server $c) {
1303 1303
 			return new Defaults(
1304 1304
 				$c->getThemingDefaults()
1305 1305
 			);
1306 1306
 		});
1307 1307
 		$this->registerDeprecatedAlias('Defaults', \OCP\Defaults::class);
1308 1308
 
1309
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1309
+		$this->registerService(\OCP\ISession::class, function(SimpleContainer $c) {
1310 1310
 			return $c->query(\OCP\IUserSession::class)->getSession();
1311 1311
 		});
1312 1312
 
1313
-		$this->registerService(IShareHelper::class, function (Server $c) {
1313
+		$this->registerService(IShareHelper::class, function(Server $c) {
1314 1314
 			return new ShareHelper(
1315 1315
 				$c->query(\OCP\Share\IManager::class)
1316 1316
 			);
1317 1317
 		});
1318 1318
 
1319
-		$this->registerService(Installer::class, function (Server $c) {
1319
+		$this->registerService(Installer::class, function(Server $c) {
1320 1320
 			return new Installer(
1321 1321
 				$c->getAppFetcher(),
1322 1322
 				$c->getHTTPClientService(),
@@ -1327,16 +1327,16 @@  discard block
 block discarded – undo
1327 1327
 			);
1328 1328
 		});
1329 1329
 
1330
-		$this->registerService(IApiFactory::class, function (Server $c) {
1330
+		$this->registerService(IApiFactory::class, function(Server $c) {
1331 1331
 			return new ApiFactory($c->getHTTPClientService());
1332 1332
 		});
1333 1333
 
1334
-		$this->registerService(IInstanceFactory::class, function (Server $c) {
1334
+		$this->registerService(IInstanceFactory::class, function(Server $c) {
1335 1335
 			$memcacheFactory = $c->getMemCacheFactory();
1336 1336
 			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1337 1337
 		});
1338 1338
 
1339
-		$this->registerService(IContactsStore::class, function (Server $c) {
1339
+		$this->registerService(IContactsStore::class, function(Server $c) {
1340 1340
 			return new ContactsStore(
1341 1341
 				$c->getContactsManager(),
1342 1342
 				$c->getConfig(),
@@ -1347,7 +1347,7 @@  discard block
 block discarded – undo
1347 1347
 		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1348 1348
 		$this->registerAlias(IAccountManager::class, AccountManager::class);
1349 1349
 
1350
-		$this->registerService(IStorageFactory::class, function () {
1350
+		$this->registerService(IStorageFactory::class, function() {
1351 1351
 			return new StorageFactory();
1352 1352
 		});
1353 1353
 
@@ -1386,7 +1386,7 @@  discard block
 block discarded – undo
1386 1386
 		$dispatcher = $this->getEventDispatcher();
1387 1387
 
1388 1388
 		// Delete avatar on user deletion
1389
-		$dispatcher->addListener('OCP\IUser::preDelete', function (GenericEvent $e) {
1389
+		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1390 1390
 			$logger = $this->getLogger();
1391 1391
 			$manager = $this->getAvatarManager();
1392 1392
 			/** @var IUser $user */
@@ -1399,11 +1399,11 @@  discard block
 block discarded – undo
1399 1399
 				// no avatar to remove
1400 1400
 			} catch (\Exception $e) {
1401 1401
 				// Ignore exceptions
1402
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1402
+				$logger->info('Could not cleanup avatar of '.$user->getUID());
1403 1403
 			}
1404 1404
 		});
1405 1405
 
1406
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1406
+		$dispatcher->addListener('OCP\IUser::changeUser', function(GenericEvent $e) {
1407 1407
 			$manager = $this->getAvatarManager();
1408 1408
 			/** @var IUser $user */
1409 1409
 			$user = $e->getSubject();
@@ -1563,7 +1563,7 @@  discard block
 block discarded – undo
1563 1563
 	 * @deprecated since 9.2.0 use IAppData
1564 1564
 	 */
1565 1565
 	public function getAppFolder() {
1566
-		$dir = '/' . \OC_App::getCurrentApp();
1566
+		$dir = '/'.\OC_App::getCurrentApp();
1567 1567
 		$root = $this->getRootFolder();
1568 1568
 		if (!$root->nodeExists($dir)) {
1569 1569
 			$folder = $root->newFolder($dir);
@@ -2237,11 +2237,11 @@  discard block
 block discarded – undo
2237 2237
 	}
2238 2238
 
2239 2239
 	private function registerDeprecatedAlias(string $alias, string $target) {
2240
-		$this->registerService($alias, function (IContainer $container) use ($target, $alias) {
2240
+		$this->registerService($alias, function(IContainer $container) use ($target, $alias) {
2241 2241
 			try {
2242 2242
 				/** @var ILogger $logger */
2243 2243
 				$logger = $container->query(ILogger::class);
2244
-				$logger->debug('The requested alias "' . $alias . '" is depreacted. Please request "' . $target . '" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2244
+				$logger->debug('The requested alias "'.$alias.'" is depreacted. Please request "'.$target.'" directly. This alias will be removed in a future Nextcloud version.', ['app' => 'serverDI']);
2245 2245
 			} catch (QueryException $e) {
2246 2246
 				// Could not get logger. Continue
2247 2247
 			}
Please login to merge, or discard this patch.
lib/private/Streamer.php 2 patches
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -38,148 +38,148 @@
 block discarded – undo
38 38
 use ZipStreamer\ZipStreamer;
39 39
 
40 40
 class Streamer {
41
-	// array of regexp. Matching user agents will get tar instead of zip
42
-	private $preferTarFor = [ '/macintosh|mac os x/i' ];
41
+    // array of regexp. Matching user agents will get tar instead of zip
42
+    private $preferTarFor = [ '/macintosh|mac os x/i' ];
43 43
 
44
-	// streamer instance
45
-	private $streamerInstance;
44
+    // streamer instance
45
+    private $streamerInstance;
46 46
 
47
-	/**
48
-	 * Streamer constructor.
49
-	 *
50
-	 * @param IRequest $request
51
-	 * @param int $size The size of the files in bytes
52
-	 * @param int $numberOfFiles The number of files (and directories) that will
53
-	 *        be included in the streamed file
54
-	 */
55
-	public function __construct(IRequest $request, int $size, int $numberOfFiles) {
47
+    /**
48
+     * Streamer constructor.
49
+     *
50
+     * @param IRequest $request
51
+     * @param int $size The size of the files in bytes
52
+     * @param int $numberOfFiles The number of files (and directories) that will
53
+     *        be included in the streamed file
54
+     */
55
+    public function __construct(IRequest $request, int $size, int $numberOfFiles) {
56 56
 
57
-		/**
58
-		 * zip32 constraints for a basic (without compression, volumes nor
59
-		 * encryption) zip file according to the Zip specification:
60
-		 * - No file size is larger than 4 bytes (file size < 4294967296); see
61
-		 *   4.4.9 uncompressed size
62
-		 * - The size of all files plus their local headers is not larger than
63
-		 *   4 bytes; see 4.4.16 relative offset of local header and 4.4.24
64
-		 *   offset of start of central directory with respect to the starting
65
-		 *   disk number
66
-		 * - The total number of entries (files and directories) in the zip file
67
-		 *   is not larger than 2 bytes (number of entries < 65536); see 4.4.22
68
-		 *   total number of entries in the central dir
69
-		 * - The size of the central directory is not larger than 4 bytes; see
70
-		 *   4.4.23 size of the central directory
71
-		 *
72
-		 * Due to all that, zip32 is used if the size is below 4GB and there are
73
-		 * less than 65536 files; the margin between 4*1000^3 and 4*1024^3
74
-		 * should give enough room for the extra zip metadata. Technically, it
75
-		 * would still be possible to create an invalid zip32 file (for example,
76
-		 * a zip file from files smaller than 4GB with a central directory
77
-		 * larger than 4GiB), but it should not happen in the real world.
78
-		 */
79
-		if ($size < 4 * 1000 * 1000 * 1000 && $numberOfFiles < 65536) {
80
-			$this->streamerInstance = new ZipStreamer(['zip64' => false]);
81
-		} else if ($request->isUserAgent($this->preferTarFor)) {
82
-			$this->streamerInstance = new TarStreamer();
83
-		} else {
84
-			$this->streamerInstance = new ZipStreamer(['zip64' => PHP_INT_SIZE !== 4]);
85
-		}
86
-	}
57
+        /**
58
+         * zip32 constraints for a basic (without compression, volumes nor
59
+         * encryption) zip file according to the Zip specification:
60
+         * - No file size is larger than 4 bytes (file size < 4294967296); see
61
+         *   4.4.9 uncompressed size
62
+         * - The size of all files plus their local headers is not larger than
63
+         *   4 bytes; see 4.4.16 relative offset of local header and 4.4.24
64
+         *   offset of start of central directory with respect to the starting
65
+         *   disk number
66
+         * - The total number of entries (files and directories) in the zip file
67
+         *   is not larger than 2 bytes (number of entries < 65536); see 4.4.22
68
+         *   total number of entries in the central dir
69
+         * - The size of the central directory is not larger than 4 bytes; see
70
+         *   4.4.23 size of the central directory
71
+         *
72
+         * Due to all that, zip32 is used if the size is below 4GB and there are
73
+         * less than 65536 files; the margin between 4*1000^3 and 4*1024^3
74
+         * should give enough room for the extra zip metadata. Technically, it
75
+         * would still be possible to create an invalid zip32 file (for example,
76
+         * a zip file from files smaller than 4GB with a central directory
77
+         * larger than 4GiB), but it should not happen in the real world.
78
+         */
79
+        if ($size < 4 * 1000 * 1000 * 1000 && $numberOfFiles < 65536) {
80
+            $this->streamerInstance = new ZipStreamer(['zip64' => false]);
81
+        } else if ($request->isUserAgent($this->preferTarFor)) {
82
+            $this->streamerInstance = new TarStreamer();
83
+        } else {
84
+            $this->streamerInstance = new ZipStreamer(['zip64' => PHP_INT_SIZE !== 4]);
85
+        }
86
+    }
87 87
 
88
-	/**
89
-	 * Send HTTP headers
90
-	 * @param string $name
91
-	 */
92
-	public function sendHeaders($name) {
93
-		$extension = $this->streamerInstance instanceof ZipStreamer ? '.zip' : '.tar';
94
-		$fullName = $name . $extension;
95
-		$this->streamerInstance->sendHeaders($fullName);
96
-	}
88
+    /**
89
+     * Send HTTP headers
90
+     * @param string $name
91
+     */
92
+    public function sendHeaders($name) {
93
+        $extension = $this->streamerInstance instanceof ZipStreamer ? '.zip' : '.tar';
94
+        $fullName = $name . $extension;
95
+        $this->streamerInstance->sendHeaders($fullName);
96
+    }
97 97
 
98
-	/**
99
-	 * Stream directory recursively
100
-	 *
101
-	 * @throws NotFoundException
102
-	 * @throws NotPermittedException
103
-	 * @throws InvalidPathException
104
-	 */
105
-	public function addDirRecursive(string $dir, string $internalDir = ''): void {
106
-		$dirname = basename($dir);
107
-		$rootDir = $internalDir . $dirname;
108
-		if (!empty($rootDir)) {
109
-			$this->streamerInstance->addEmptyDir($rootDir);
110
-		}
111
-		$internalDir .= $dirname . '/';
112
-		// prevent absolute dirs
113
-		$internalDir = ltrim($internalDir, '/');
98
+    /**
99
+     * Stream directory recursively
100
+     *
101
+     * @throws NotFoundException
102
+     * @throws NotPermittedException
103
+     * @throws InvalidPathException
104
+     */
105
+    public function addDirRecursive(string $dir, string $internalDir = ''): void {
106
+        $dirname = basename($dir);
107
+        $rootDir = $internalDir . $dirname;
108
+        if (!empty($rootDir)) {
109
+            $this->streamerInstance->addEmptyDir($rootDir);
110
+        }
111
+        $internalDir .= $dirname . '/';
112
+        // prevent absolute dirs
113
+        $internalDir = ltrim($internalDir, '/');
114 114
 
115
-		$userFolder = \OC::$server->getRootFolder()->get(Filesystem::getRoot());
116
-		/** @var Folder $dirNode */
117
-		$dirNode = $userFolder->get($dir);
118
-		$files = $dirNode->getDirectoryListing();
115
+        $userFolder = \OC::$server->getRootFolder()->get(Filesystem::getRoot());
116
+        /** @var Folder $dirNode */
117
+        $dirNode = $userFolder->get($dir);
118
+        $files = $dirNode->getDirectoryListing();
119 119
 
120
-		foreach($files as $file) {
121
-			if($file instanceof File) {
122
-				try {
123
-					$fh = $file->fopen('r');
124
-				} catch (NotPermittedException $e) {
125
-					continue;
126
-				}
127
-				$this->addFileFromStream(
128
-					$fh,
129
-					$internalDir . $file->getName(),
130
-					$file->getSize(),
131
-					$file->getMTime()
132
-				);
133
-				fclose($fh);
134
-			} elseif ($file instanceof Folder) {
135
-				if($file->isReadable()) {
136
-					$this->addDirRecursive($dir . '/' . $file->getName(), $internalDir);
137
-				}
138
-			}
139
-		}
140
-	}
120
+        foreach($files as $file) {
121
+            if($file instanceof File) {
122
+                try {
123
+                    $fh = $file->fopen('r');
124
+                } catch (NotPermittedException $e) {
125
+                    continue;
126
+                }
127
+                $this->addFileFromStream(
128
+                    $fh,
129
+                    $internalDir . $file->getName(),
130
+                    $file->getSize(),
131
+                    $file->getMTime()
132
+                );
133
+                fclose($fh);
134
+            } elseif ($file instanceof Folder) {
135
+                if($file->isReadable()) {
136
+                    $this->addDirRecursive($dir . '/' . $file->getName(), $internalDir);
137
+                }
138
+            }
139
+        }
140
+    }
141 141
 
142
-	/**
143
-	 * Add a file to the archive at the specified location and file name.
144
-	 *
145
-	 * @param string $stream Stream to read data from
146
-	 * @param string $internalName Filepath and name to be used in the archive.
147
-	 * @param int $size Filesize
148
-	 * @param int|bool $time File mtime as int, or false
149
-	 * @return bool $success
150
-	 */
151
-	public function addFileFromStream($stream, $internalName, $size, $time) {
152
-		$options = [];
153
-		if ($time) {
154
-			$options = [
155
-				'timestamp' => $time
156
-			];
157
-		}
142
+    /**
143
+     * Add a file to the archive at the specified location and file name.
144
+     *
145
+     * @param string $stream Stream to read data from
146
+     * @param string $internalName Filepath and name to be used in the archive.
147
+     * @param int $size Filesize
148
+     * @param int|bool $time File mtime as int, or false
149
+     * @return bool $success
150
+     */
151
+    public function addFileFromStream($stream, $internalName, $size, $time) {
152
+        $options = [];
153
+        if ($time) {
154
+            $options = [
155
+                'timestamp' => $time
156
+            ];
157
+        }
158 158
 
159
-		if ($this->streamerInstance instanceof ZipStreamer) {
160
-			return $this->streamerInstance->addFileFromStream($stream, $internalName, $options);
161
-		} else {
162
-			return $this->streamerInstance->addFileFromStream($stream, $internalName, $size, $options);
163
-		}
164
-	}
159
+        if ($this->streamerInstance instanceof ZipStreamer) {
160
+            return $this->streamerInstance->addFileFromStream($stream, $internalName, $options);
161
+        } else {
162
+            return $this->streamerInstance->addFileFromStream($stream, $internalName, $size, $options);
163
+        }
164
+    }
165 165
 
166
-	/**
167
-	 * Add an empty directory entry to the archive.
168
-	 *
169
-	 * @param string $dirName Directory Path and name to be added to the archive.
170
-	 * @return bool $success
171
-	 */
172
-	public function addEmptyDir($dirName) {
173
-		return $this->streamerInstance->addEmptyDir($dirName);
174
-	}
166
+    /**
167
+     * Add an empty directory entry to the archive.
168
+     *
169
+     * @param string $dirName Directory Path and name to be added to the archive.
170
+     * @return bool $success
171
+     */
172
+    public function addEmptyDir($dirName) {
173
+        return $this->streamerInstance->addEmptyDir($dirName);
174
+    }
175 175
 
176
-	/**
177
-	 * Close the archive.
178
-	 * A closed archive can no longer have new files added to it. After
179
-	 * closing, the file is completely written to the output stream.
180
-	 * @return bool $success
181
-	 */
182
-	public function finalize() {
183
-		return $this->streamerInstance->finalize();
184
-	}
176
+    /**
177
+     * Close the archive.
178
+     * A closed archive can no longer have new files added to it. After
179
+     * closing, the file is completely written to the output stream.
180
+     * @return bool $success
181
+     */
182
+    public function finalize() {
183
+        return $this->streamerInstance->finalize();
184
+    }
185 185
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
 
40 40
 class Streamer {
41 41
 	// array of regexp. Matching user agents will get tar instead of zip
42
-	private $preferTarFor = [ '/macintosh|mac os x/i' ];
42
+	private $preferTarFor = ['/macintosh|mac os x/i'];
43 43
 
44 44
 	// streamer instance
45 45
 	private $streamerInstance;
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	 */
92 92
 	public function sendHeaders($name) {
93 93
 		$extension = $this->streamerInstance instanceof ZipStreamer ? '.zip' : '.tar';
94
-		$fullName = $name . $extension;
94
+		$fullName = $name.$extension;
95 95
 		$this->streamerInstance->sendHeaders($fullName);
96 96
 	}
97 97
 
@@ -104,11 +104,11 @@  discard block
 block discarded – undo
104 104
 	 */
105 105
 	public function addDirRecursive(string $dir, string $internalDir = ''): void {
106 106
 		$dirname = basename($dir);
107
-		$rootDir = $internalDir . $dirname;
107
+		$rootDir = $internalDir.$dirname;
108 108
 		if (!empty($rootDir)) {
109 109
 			$this->streamerInstance->addEmptyDir($rootDir);
110 110
 		}
111
-		$internalDir .= $dirname . '/';
111
+		$internalDir .= $dirname.'/';
112 112
 		// prevent absolute dirs
113 113
 		$internalDir = ltrim($internalDir, '/');
114 114
 
@@ -117,8 +117,8 @@  discard block
 block discarded – undo
117 117
 		$dirNode = $userFolder->get($dir);
118 118
 		$files = $dirNode->getDirectoryListing();
119 119
 
120
-		foreach($files as $file) {
121
-			if($file instanceof File) {
120
+		foreach ($files as $file) {
121
+			if ($file instanceof File) {
122 122
 				try {
123 123
 					$fh = $file->fopen('r');
124 124
 				} catch (NotPermittedException $e) {
@@ -126,14 +126,14 @@  discard block
 block discarded – undo
126 126
 				}
127 127
 				$this->addFileFromStream(
128 128
 					$fh,
129
-					$internalDir . $file->getName(),
129
+					$internalDir.$file->getName(),
130 130
 					$file->getSize(),
131 131
 					$file->getMTime()
132 132
 				);
133 133
 				fclose($fh);
134 134
 			} elseif ($file instanceof Folder) {
135
-				if($file->isReadable()) {
136
-					$this->addDirRecursive($dir . '/' . $file->getName(), $internalDir);
135
+				if ($file->isReadable()) {
136
+					$this->addDirRecursive($dir.'/'.$file->getName(), $internalDir);
137 137
 				}
138 138
 			}
139 139
 		}
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 2 patches
Indentation   +350 added lines, -350 removed lines patch added patch discarded remove patch
@@ -69,354 +69,354 @@
 block discarded – undo
69 69
 
70 70
 class DIContainer extends SimpleContainer implements IAppContainer {
71 71
 
72
-	/**
73
-	 * @var array
74
-	 */
75
-	private $middleWares = [];
76
-
77
-	/** @var ServerContainer */
78
-	private $server;
79
-
80
-	/**
81
-	 * Put your class dependencies in here
82
-	 * @param string $appName the name of the app
83
-	 * @param array $urlParams
84
-	 * @param ServerContainer|null $server
85
-	 */
86
-	public function __construct($appName, $urlParams = [], ServerContainer $server = null) {
87
-		parent::__construct();
88
-		$this['AppName'] = $appName;
89
-		$this['urlParams'] = $urlParams;
90
-
91
-		$this->registerAlias('Request', IRequest::class);
92
-
93
-		/** @var \OC\ServerContainer $server */
94
-		if ($server === null) {
95
-			$server = \OC::$server;
96
-		}
97
-		$this->server = $server;
98
-		$this->server->registerAppContainer($appName, $this);
99
-
100
-		// aliases
101
-		$this->registerAlias('appName', 'AppName');
102
-		$this->registerAlias('webRoot', 'WebRoot');
103
-		$this->registerAlias('userId', 'UserId');
104
-
105
-		/**
106
-		 * Core services
107
-		 */
108
-		$this->registerService(IOutput::class, function () {
109
-			return new Output($this->getServer()->getWebRoot());
110
-		});
111
-
112
-		$this->registerService(Folder::class, function () {
113
-			return $this->getServer()->getUserFolder();
114
-		});
115
-
116
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
117
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
118
-		});
119
-
120
-		$this->registerService(IL10N::class, function ($c) {
121
-			return $this->getServer()->getL10N($c->query('AppName'));
122
-		});
123
-
124
-		// Log wrapper
125
-		$this->registerService(ILogger::class, function ($c) {
126
-			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('AppName'));
127
-		});
128
-
129
-		$this->registerService(IServerContainer::class, function () {
130
-			return $this->getServer();
131
-		});
132
-		$this->registerAlias('ServerContainer', IServerContainer::class);
133
-
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
-			return $c->query(Manager::class);
136
-		});
137
-
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
-			return $c;
140
-		});
141
-
142
-		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
144
-			return $c->query(IUserSession::class)->getSession()->get('user_id');
145
-		});
146
-
147
-		$this->registerService('WebRoot', function ($c) {
148
-			return $c->query('ServerContainer')->getWebRoot();
149
-		});
150
-
151
-		$this->registerService('OC_Defaults', function ($c) {
152
-			return $c->getServer()->getThemingDefaults();
153
-		});
154
-
155
-		$this->registerService(IConfig::class, function ($c) {
156
-			return $c->query(OC\GlobalScale\Config::class);
157
-		});
158
-
159
-		$this->registerService('Protocol', function ($c) {
160
-			/** @var \OC\Server $server */
161
-			$server = $c->query('ServerContainer');
162
-			$protocol = $server->getRequest()->getHttpProtocol();
163
-			return new Http($_SERVER, $protocol);
164
-		});
165
-
166
-		$this->registerService('Dispatcher', function ($c) {
167
-			return new Dispatcher(
168
-				$c['Protocol'],
169
-				$c['MiddlewareDispatcher'],
170
-				$c->query(IControllerMethodReflector::class),
171
-				$c['Request']
172
-			);
173
-		});
174
-
175
-		/**
176
-		 * App Framework default arguments
177
-		 */
178
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
179
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
180
-		$this->registerParameter('corsMaxAge', 1728000);
181
-
182
-		/**
183
-		 * Middleware
184
-		 */
185
-		$this->registerService('MiddlewareDispatcher', function (SimpleContainer $c) {
186
-			$server =  $this->getServer();
187
-
188
-			$dispatcher = new MiddlewareDispatcher();
189
-			$dispatcher->registerMiddleware(
190
-				$c->query(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
191
-			);
192
-
193
-			$dispatcher->registerMiddleware(
194
-				new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
195
-					$c->query(IRequest::class),
196
-					$c->query(IControllerMethodReflector::class)
197
-				)
198
-			);
199
-			$dispatcher->registerMiddleware(
200
-				new CORSMiddleware(
201
-					$c->query(IRequest::class),
202
-					$c->query(IControllerMethodReflector::class),
203
-					$c->query(IUserSession::class),
204
-					$c->query(OC\Security\Bruteforce\Throttler::class)
205
-				)
206
-			);
207
-			$dispatcher->registerMiddleware(
208
-				new OCSMiddleware(
209
-					$c->query(IRequest::class)
210
-				)
211
-			);
212
-
213
-			$securityMiddleware = new SecurityMiddleware(
214
-				$c->query(IRequest::class),
215
-				$c->query(IControllerMethodReflector::class),
216
-				$c->query(INavigationManager::class),
217
-				$c->query(IURLGenerator::class),
218
-				$server->getLogger(),
219
-				$c['AppName'],
220
-				$server->getUserSession()->isLoggedIn(),
221
-				$server->getGroupManager()->isAdmin($this->getUserId()),
222
-				$server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
223
-				$server->getAppManager(),
224
-				$server->getL10N('lib')
225
-			);
226
-			$dispatcher->registerMiddleware($securityMiddleware);
227
-			$dispatcher->registerMiddleware(
228
-				new OC\AppFramework\Middleware\Security\CSPMiddleware(
229
-					$server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
230
-					$server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
231
-					$server->query(OC\Security\CSRF\CsrfTokenManager::class)
232
-				)
233
-			);
234
-			$dispatcher->registerMiddleware(
235
-				$server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
236
-			);
237
-			$dispatcher->registerMiddleware(
238
-				new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
239
-					$c->query(IControllerMethodReflector::class),
240
-					$c->query(ISession::class),
241
-					$c->query(IUserSession::class),
242
-					$c->query(ITimeFactory::class)
243
-				)
244
-			);
245
-			$dispatcher->registerMiddleware(
246
-				new TwoFactorMiddleware(
247
-					$c->query(OC\Authentication\TwoFactorAuth\Manager::class),
248
-					$c->query(IUserSession::class),
249
-					$c->query(ISession::class),
250
-					$c->query(IURLGenerator::class),
251
-					$c->query(IControllerMethodReflector::class),
252
-					$c->query(IRequest::class)
253
-				)
254
-			);
255
-			$dispatcher->registerMiddleware(
256
-				new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
257
-					$c->query(IControllerMethodReflector::class),
258
-					$c->query(OC\Security\Bruteforce\Throttler::class),
259
-					$c->query(IRequest::class)
260
-				)
261
-			);
262
-			$dispatcher->registerMiddleware(
263
-				new RateLimitingMiddleware(
264
-					$c->query(IRequest::class),
265
-					$c->query(IUserSession::class),
266
-					$c->query(IControllerMethodReflector::class),
267
-					$c->query(OC\Security\RateLimiting\Limiter::class)
268
-				)
269
-			);
270
-			$dispatcher->registerMiddleware(
271
-				new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
272
-					$c->query(IRequest::class),
273
-					$c->query(ISession::class),
274
-					$c->query(\OCP\IConfig::class)
275
-				)
276
-			);
277
-			$dispatcher->registerMiddleware(
278
-				$c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
279
-			);
280
-
281
-			foreach($this->middleWares as $middleWare) {
282
-				$dispatcher->registerMiddleware($c->query($middleWare));
283
-			}
284
-
285
-			$dispatcher->registerMiddleware(
286
-				new SessionMiddleware(
287
-					$c->query(IControllerMethodReflector::class),
288
-					$c->query(ISession::class)
289
-				)
290
-			);
291
-			return $dispatcher;
292
-		});
293
-
294
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, OC\Collaboration\Resources\ProviderManager::class);
295
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, OC\Collaboration\Resources\Manager::class);
296
-	}
297
-
298
-	/**
299
-	 * @return \OCP\IServerContainer
300
-	 */
301
-	public function getServer()
302
-	{
303
-		return $this->server;
304
-	}
305
-
306
-	/**
307
-	 * @param string $middleWare
308
-	 * @return boolean|null
309
-	 */
310
-	public function registerMiddleWare($middleWare) {
311
-		if (in_array($middleWare, $this->middleWares, true) !== false) {
312
-			return false;
313
-		}
314
-		$this->middleWares[] = $middleWare;
315
-	}
316
-
317
-	/**
318
-	 * used to return the appname of the set application
319
-	 * @return string the name of your application
320
-	 */
321
-	public function getAppName() {
322
-		return $this->query('AppName');
323
-	}
324
-
325
-	/**
326
-	 * @deprecated use IUserSession->isLoggedIn()
327
-	 * @return boolean
328
-	 */
329
-	public function isLoggedIn() {
330
-		return \OC::$server->getUserSession()->isLoggedIn();
331
-	}
332
-
333
-	/**
334
-	 * @deprecated use IGroupManager->isAdmin($userId)
335
-	 * @return boolean
336
-	 */
337
-	public function isAdminUser() {
338
-		$uid = $this->getUserId();
339
-		return \OC_User::isAdminUser($uid);
340
-	}
341
-
342
-	private function getUserId() {
343
-		return $this->getServer()->getSession()->get('user_id');
344
-	}
345
-
346
-	/**
347
-	 * @deprecated use the ILogger instead
348
-	 * @param string $message
349
-	 * @param string $level
350
-	 * @return mixed
351
-	 */
352
-	public function log($message, $level) {
353
-		switch($level){
354
-			case 'debug':
355
-				$level = ILogger::DEBUG;
356
-				break;
357
-			case 'info':
358
-				$level = ILogger::INFO;
359
-				break;
360
-			case 'warn':
361
-				$level = ILogger::WARN;
362
-				break;
363
-			case 'fatal':
364
-				$level = ILogger::FATAL;
365
-				break;
366
-			default:
367
-				$level = ILogger::ERROR;
368
-				break;
369
-		}
370
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
371
-	}
372
-
373
-	/**
374
-	 * Register a capability
375
-	 *
376
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
377
-	 */
378
-	public function registerCapability($serviceName) {
379
-		$this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
380
-			return $this->query($serviceName);
381
-		});
382
-	}
383
-
384
-	public function query(string $name, bool $autoload = true) {
385
-		try {
386
-			return $this->queryNoFallback($name);
387
-		} catch (QueryException $firstException) {
388
-			try {
389
-				return $this->getServer()->query($name, $autoload);
390
-			} catch (QueryException $secondException) {
391
-				if ($firstException->getCode() === 1) {
392
-					throw $secondException;
393
-				}
394
-				throw $firstException;
395
-			}
396
-		}
397
-	}
398
-
399
-	/**
400
-	 * @param string $name
401
-	 * @return mixed
402
-	 * @throws QueryException if the query could not be resolved
403
-	 */
404
-	public function queryNoFallback($name) {
405
-		$name = $this->sanitizeName($name);
406
-
407
-		if ($this->offsetExists($name)) {
408
-			return parent::query($name);
409
-		} else {
410
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
411
-				return parent::query($name);
412
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
413
-				return parent::query($name);
414
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
415
-				return parent::query($name);
416
-			}
417
-		}
418
-
419
-		throw new QueryException('Could not resolve ' . $name . '!' .
420
-			' Class can not be instantiated', 1);
421
-	}
72
+    /**
73
+     * @var array
74
+     */
75
+    private $middleWares = [];
76
+
77
+    /** @var ServerContainer */
78
+    private $server;
79
+
80
+    /**
81
+     * Put your class dependencies in here
82
+     * @param string $appName the name of the app
83
+     * @param array $urlParams
84
+     * @param ServerContainer|null $server
85
+     */
86
+    public function __construct($appName, $urlParams = [], ServerContainer $server = null) {
87
+        parent::__construct();
88
+        $this['AppName'] = $appName;
89
+        $this['urlParams'] = $urlParams;
90
+
91
+        $this->registerAlias('Request', IRequest::class);
92
+
93
+        /** @var \OC\ServerContainer $server */
94
+        if ($server === null) {
95
+            $server = \OC::$server;
96
+        }
97
+        $this->server = $server;
98
+        $this->server->registerAppContainer($appName, $this);
99
+
100
+        // aliases
101
+        $this->registerAlias('appName', 'AppName');
102
+        $this->registerAlias('webRoot', 'WebRoot');
103
+        $this->registerAlias('userId', 'UserId');
104
+
105
+        /**
106
+         * Core services
107
+         */
108
+        $this->registerService(IOutput::class, function () {
109
+            return new Output($this->getServer()->getWebRoot());
110
+        });
111
+
112
+        $this->registerService(Folder::class, function () {
113
+            return $this->getServer()->getUserFolder();
114
+        });
115
+
116
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
117
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
118
+        });
119
+
120
+        $this->registerService(IL10N::class, function ($c) {
121
+            return $this->getServer()->getL10N($c->query('AppName'));
122
+        });
123
+
124
+        // Log wrapper
125
+        $this->registerService(ILogger::class, function ($c) {
126
+            return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('AppName'));
127
+        });
128
+
129
+        $this->registerService(IServerContainer::class, function () {
130
+            return $this->getServer();
131
+        });
132
+        $this->registerAlias('ServerContainer', IServerContainer::class);
133
+
134
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
135
+            return $c->query(Manager::class);
136
+        });
137
+
138
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
139
+            return $c;
140
+        });
141
+
142
+        // commonly used attributes
143
+        $this->registerService('UserId', function ($c) {
144
+            return $c->query(IUserSession::class)->getSession()->get('user_id');
145
+        });
146
+
147
+        $this->registerService('WebRoot', function ($c) {
148
+            return $c->query('ServerContainer')->getWebRoot();
149
+        });
150
+
151
+        $this->registerService('OC_Defaults', function ($c) {
152
+            return $c->getServer()->getThemingDefaults();
153
+        });
154
+
155
+        $this->registerService(IConfig::class, function ($c) {
156
+            return $c->query(OC\GlobalScale\Config::class);
157
+        });
158
+
159
+        $this->registerService('Protocol', function ($c) {
160
+            /** @var \OC\Server $server */
161
+            $server = $c->query('ServerContainer');
162
+            $protocol = $server->getRequest()->getHttpProtocol();
163
+            return new Http($_SERVER, $protocol);
164
+        });
165
+
166
+        $this->registerService('Dispatcher', function ($c) {
167
+            return new Dispatcher(
168
+                $c['Protocol'],
169
+                $c['MiddlewareDispatcher'],
170
+                $c->query(IControllerMethodReflector::class),
171
+                $c['Request']
172
+            );
173
+        });
174
+
175
+        /**
176
+         * App Framework default arguments
177
+         */
178
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
179
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
180
+        $this->registerParameter('corsMaxAge', 1728000);
181
+
182
+        /**
183
+         * Middleware
184
+         */
185
+        $this->registerService('MiddlewareDispatcher', function (SimpleContainer $c) {
186
+            $server =  $this->getServer();
187
+
188
+            $dispatcher = new MiddlewareDispatcher();
189
+            $dispatcher->registerMiddleware(
190
+                $c->query(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
191
+            );
192
+
193
+            $dispatcher->registerMiddleware(
194
+                new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
195
+                    $c->query(IRequest::class),
196
+                    $c->query(IControllerMethodReflector::class)
197
+                )
198
+            );
199
+            $dispatcher->registerMiddleware(
200
+                new CORSMiddleware(
201
+                    $c->query(IRequest::class),
202
+                    $c->query(IControllerMethodReflector::class),
203
+                    $c->query(IUserSession::class),
204
+                    $c->query(OC\Security\Bruteforce\Throttler::class)
205
+                )
206
+            );
207
+            $dispatcher->registerMiddleware(
208
+                new OCSMiddleware(
209
+                    $c->query(IRequest::class)
210
+                )
211
+            );
212
+
213
+            $securityMiddleware = new SecurityMiddleware(
214
+                $c->query(IRequest::class),
215
+                $c->query(IControllerMethodReflector::class),
216
+                $c->query(INavigationManager::class),
217
+                $c->query(IURLGenerator::class),
218
+                $server->getLogger(),
219
+                $c['AppName'],
220
+                $server->getUserSession()->isLoggedIn(),
221
+                $server->getGroupManager()->isAdmin($this->getUserId()),
222
+                $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
223
+                $server->getAppManager(),
224
+                $server->getL10N('lib')
225
+            );
226
+            $dispatcher->registerMiddleware($securityMiddleware);
227
+            $dispatcher->registerMiddleware(
228
+                new OC\AppFramework\Middleware\Security\CSPMiddleware(
229
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
230
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
231
+                    $server->query(OC\Security\CSRF\CsrfTokenManager::class)
232
+                )
233
+            );
234
+            $dispatcher->registerMiddleware(
235
+                $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
236
+            );
237
+            $dispatcher->registerMiddleware(
238
+                new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
239
+                    $c->query(IControllerMethodReflector::class),
240
+                    $c->query(ISession::class),
241
+                    $c->query(IUserSession::class),
242
+                    $c->query(ITimeFactory::class)
243
+                )
244
+            );
245
+            $dispatcher->registerMiddleware(
246
+                new TwoFactorMiddleware(
247
+                    $c->query(OC\Authentication\TwoFactorAuth\Manager::class),
248
+                    $c->query(IUserSession::class),
249
+                    $c->query(ISession::class),
250
+                    $c->query(IURLGenerator::class),
251
+                    $c->query(IControllerMethodReflector::class),
252
+                    $c->query(IRequest::class)
253
+                )
254
+            );
255
+            $dispatcher->registerMiddleware(
256
+                new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
257
+                    $c->query(IControllerMethodReflector::class),
258
+                    $c->query(OC\Security\Bruteforce\Throttler::class),
259
+                    $c->query(IRequest::class)
260
+                )
261
+            );
262
+            $dispatcher->registerMiddleware(
263
+                new RateLimitingMiddleware(
264
+                    $c->query(IRequest::class),
265
+                    $c->query(IUserSession::class),
266
+                    $c->query(IControllerMethodReflector::class),
267
+                    $c->query(OC\Security\RateLimiting\Limiter::class)
268
+                )
269
+            );
270
+            $dispatcher->registerMiddleware(
271
+                new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
272
+                    $c->query(IRequest::class),
273
+                    $c->query(ISession::class),
274
+                    $c->query(\OCP\IConfig::class)
275
+                )
276
+            );
277
+            $dispatcher->registerMiddleware(
278
+                $c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
279
+            );
280
+
281
+            foreach($this->middleWares as $middleWare) {
282
+                $dispatcher->registerMiddleware($c->query($middleWare));
283
+            }
284
+
285
+            $dispatcher->registerMiddleware(
286
+                new SessionMiddleware(
287
+                    $c->query(IControllerMethodReflector::class),
288
+                    $c->query(ISession::class)
289
+                )
290
+            );
291
+            return $dispatcher;
292
+        });
293
+
294
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, OC\Collaboration\Resources\ProviderManager::class);
295
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, OC\Collaboration\Resources\Manager::class);
296
+    }
297
+
298
+    /**
299
+     * @return \OCP\IServerContainer
300
+     */
301
+    public function getServer()
302
+    {
303
+        return $this->server;
304
+    }
305
+
306
+    /**
307
+     * @param string $middleWare
308
+     * @return boolean|null
309
+     */
310
+    public function registerMiddleWare($middleWare) {
311
+        if (in_array($middleWare, $this->middleWares, true) !== false) {
312
+            return false;
313
+        }
314
+        $this->middleWares[] = $middleWare;
315
+    }
316
+
317
+    /**
318
+     * used to return the appname of the set application
319
+     * @return string the name of your application
320
+     */
321
+    public function getAppName() {
322
+        return $this->query('AppName');
323
+    }
324
+
325
+    /**
326
+     * @deprecated use IUserSession->isLoggedIn()
327
+     * @return boolean
328
+     */
329
+    public function isLoggedIn() {
330
+        return \OC::$server->getUserSession()->isLoggedIn();
331
+    }
332
+
333
+    /**
334
+     * @deprecated use IGroupManager->isAdmin($userId)
335
+     * @return boolean
336
+     */
337
+    public function isAdminUser() {
338
+        $uid = $this->getUserId();
339
+        return \OC_User::isAdminUser($uid);
340
+    }
341
+
342
+    private function getUserId() {
343
+        return $this->getServer()->getSession()->get('user_id');
344
+    }
345
+
346
+    /**
347
+     * @deprecated use the ILogger instead
348
+     * @param string $message
349
+     * @param string $level
350
+     * @return mixed
351
+     */
352
+    public function log($message, $level) {
353
+        switch($level){
354
+            case 'debug':
355
+                $level = ILogger::DEBUG;
356
+                break;
357
+            case 'info':
358
+                $level = ILogger::INFO;
359
+                break;
360
+            case 'warn':
361
+                $level = ILogger::WARN;
362
+                break;
363
+            case 'fatal':
364
+                $level = ILogger::FATAL;
365
+                break;
366
+            default:
367
+                $level = ILogger::ERROR;
368
+                break;
369
+        }
370
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
371
+    }
372
+
373
+    /**
374
+     * Register a capability
375
+     *
376
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
377
+     */
378
+    public function registerCapability($serviceName) {
379
+        $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
380
+            return $this->query($serviceName);
381
+        });
382
+    }
383
+
384
+    public function query(string $name, bool $autoload = true) {
385
+        try {
386
+            return $this->queryNoFallback($name);
387
+        } catch (QueryException $firstException) {
388
+            try {
389
+                return $this->getServer()->query($name, $autoload);
390
+            } catch (QueryException $secondException) {
391
+                if ($firstException->getCode() === 1) {
392
+                    throw $secondException;
393
+                }
394
+                throw $firstException;
395
+            }
396
+        }
397
+    }
398
+
399
+    /**
400
+     * @param string $name
401
+     * @return mixed
402
+     * @throws QueryException if the query could not be resolved
403
+     */
404
+    public function queryNoFallback($name) {
405
+        $name = $this->sanitizeName($name);
406
+
407
+        if ($this->offsetExists($name)) {
408
+            return parent::query($name);
409
+        } else {
410
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
411
+                return parent::query($name);
412
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
413
+                return parent::query($name);
414
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
415
+                return parent::query($name);
416
+            }
417
+        }
418
+
419
+        throw new QueryException('Could not resolve ' . $name . '!' .
420
+            ' Class can not be instantiated', 1);
421
+    }
422 422
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -105,65 +105,65 @@  discard block
 block discarded – undo
105 105
 		/**
106 106
 		 * Core services
107 107
 		 */
108
-		$this->registerService(IOutput::class, function () {
108
+		$this->registerService(IOutput::class, function() {
109 109
 			return new Output($this->getServer()->getWebRoot());
110 110
 		});
111 111
 
112
-		$this->registerService(Folder::class, function () {
112
+		$this->registerService(Folder::class, function() {
113 113
 			return $this->getServer()->getUserFolder();
114 114
 		});
115 115
 
116
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
116
+		$this->registerService(IAppData::class, function(SimpleContainer $c) {
117 117
 			return $this->getServer()->getAppDataDir($c->query('AppName'));
118 118
 		});
119 119
 
120
-		$this->registerService(IL10N::class, function ($c) {
120
+		$this->registerService(IL10N::class, function($c) {
121 121
 			return $this->getServer()->getL10N($c->query('AppName'));
122 122
 		});
123 123
 
124 124
 		// Log wrapper
125
-		$this->registerService(ILogger::class, function ($c) {
125
+		$this->registerService(ILogger::class, function($c) {
126 126
 			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->query('AppName'));
127 127
 		});
128 128
 
129
-		$this->registerService(IServerContainer::class, function () {
129
+		$this->registerService(IServerContainer::class, function() {
130 130
 			return $this->getServer();
131 131
 		});
132 132
 		$this->registerAlias('ServerContainer', IServerContainer::class);
133 133
 
134
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
134
+		$this->registerService(\OCP\WorkflowEngine\IManager::class, function($c) {
135 135
 			return $c->query(Manager::class);
136 136
 		});
137 137
 
138
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
138
+		$this->registerService(\OCP\AppFramework\IAppContainer::class, function($c) {
139 139
 			return $c;
140 140
 		});
141 141
 
142 142
 		// commonly used attributes
143
-		$this->registerService('UserId', function ($c) {
143
+		$this->registerService('UserId', function($c) {
144 144
 			return $c->query(IUserSession::class)->getSession()->get('user_id');
145 145
 		});
146 146
 
147
-		$this->registerService('WebRoot', function ($c) {
147
+		$this->registerService('WebRoot', function($c) {
148 148
 			return $c->query('ServerContainer')->getWebRoot();
149 149
 		});
150 150
 
151
-		$this->registerService('OC_Defaults', function ($c) {
151
+		$this->registerService('OC_Defaults', function($c) {
152 152
 			return $c->getServer()->getThemingDefaults();
153 153
 		});
154 154
 
155
-		$this->registerService(IConfig::class, function ($c) {
155
+		$this->registerService(IConfig::class, function($c) {
156 156
 			return $c->query(OC\GlobalScale\Config::class);
157 157
 		});
158 158
 
159
-		$this->registerService('Protocol', function ($c) {
159
+		$this->registerService('Protocol', function($c) {
160 160
 			/** @var \OC\Server $server */
161 161
 			$server = $c->query('ServerContainer');
162 162
 			$protocol = $server->getRequest()->getHttpProtocol();
163 163
 			return new Http($_SERVER, $protocol);
164 164
 		});
165 165
 
166
-		$this->registerService('Dispatcher', function ($c) {
166
+		$this->registerService('Dispatcher', function($c) {
167 167
 			return new Dispatcher(
168 168
 				$c['Protocol'],
169 169
 				$c['MiddlewareDispatcher'],
@@ -182,8 +182,8 @@  discard block
 block discarded – undo
182 182
 		/**
183 183
 		 * Middleware
184 184
 		 */
185
-		$this->registerService('MiddlewareDispatcher', function (SimpleContainer $c) {
186
-			$server =  $this->getServer();
185
+		$this->registerService('MiddlewareDispatcher', function(SimpleContainer $c) {
186
+			$server = $this->getServer();
187 187
 
188 188
 			$dispatcher = new MiddlewareDispatcher();
189 189
 			$dispatcher->registerMiddleware(
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 				$c->query(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
279 279
 			);
280 280
 
281
-			foreach($this->middleWares as $middleWare) {
281
+			foreach ($this->middleWares as $middleWare) {
282 282
 				$dispatcher->registerMiddleware($c->query($middleWare));
283 283
 			}
284 284
 
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
 	 * @return mixed
351 351
 	 */
352 352
 	public function log($message, $level) {
353
-		switch($level){
353
+		switch ($level) {
354 354
 			case 'debug':
355 355
 				$level = ILogger::DEBUG;
356 356
 				break;
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
377 377
 	 */
378 378
 	public function registerCapability($serviceName) {
379
-		$this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
379
+		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
380 380
 			return $this->query($serviceName);
381 381
 		});
382 382
 	}
@@ -411,12 +411,12 @@  discard block
 block discarded – undo
411 411
 				return parent::query($name);
412 412
 			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
413 413
 				return parent::query($name);
414
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
414
+			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']).'\\') === 0) {
415 415
 				return parent::query($name);
416 416
 			}
417 417
 		}
418 418
 
419
-		throw new QueryException('Could not resolve ' . $name . '!' .
419
+		throw new QueryException('Could not resolve '.$name.'!'.
420 420
 			' Class can not be instantiated', 1);
421 421
 	}
422 422
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Utility/ControllerMethodReflector.php 2 patches
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -38,100 +38,100 @@
 block discarded – undo
38 38
  * Reads and parses annotations from doc comments
39 39
  */
40 40
 class ControllerMethodReflector implements IControllerMethodReflector {
41
-	public $annotations = [];
42
-	private $types = [];
43
-	private $parameters = [];
44
-
45
-	/**
46
-	 * @param object $object an object or classname
47
-	 * @param string $method the method which we want to inspect
48
-	 */
49
-	public function reflect($object, string $method) {
50
-		$reflection = new \ReflectionMethod($object, $method);
51
-		$docs = $reflection->getDocComment();
52
-
53
-		if ($docs !== false) {
54
-			// extract everything prefixed by @ and first letter uppercase
55
-			preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)((?P<parameter>.*))?$/m', $docs, $matches);
56
-			foreach ($matches['annotation'] as $key => $annontation) {
57
-				$annotationValue = $matches['parameter'][$key];
58
-				if (isset($annotationValue[0]) && $annotationValue[0] === '(' && $annotationValue[\strlen($annotationValue) - 1] === ')') {
59
-					$cutString = substr($annotationValue, 1, -1);
60
-					$cutString = str_replace(' ', '', $cutString);
61
-					$splittedArray = explode(',', $cutString);
62
-					foreach ($splittedArray as $annotationValues) {
63
-						list($key, $value) = explode('=', $annotationValues);
64
-						$this->annotations[$annontation][$key] = $value;
65
-					}
66
-					continue;
67
-				}
68
-
69
-				$this->annotations[$annontation] = [$annotationValue];
70
-			}
71
-
72
-			// extract type parameter information
73
-			preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
74
-			$this->types = array_combine($matches['var'], $matches['type']);
75
-		}
76
-
77
-		foreach ($reflection->getParameters() as $param) {
78
-			// extract type information from PHP 7 scalar types and prefer them over phpdoc annotations
79
-			$type = $param->getType();
80
-			if ($type instanceof \ReflectionNamedType) {
81
-				$this->types[$param->getName()] = $type->getName();
82
-			}
83
-
84
-			$default = null;
85
-			if($param->isOptional()) {
86
-				$default = $param->getDefaultValue();
87
-			}
88
-			$this->parameters[$param->name] = $default;
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * Inspects the PHPDoc parameters for types
94
-	 * @param string $parameter the parameter whose type comments should be
95
-	 * parsed
96
-	 * @return string|null type in the type parameters (@param int $something)
97
-	 * would return int or null if not existing
98
-	 */
99
-	public function getType(string $parameter) {
100
-		if(array_key_exists($parameter, $this->types)) {
101
-			return $this->types[$parameter];
102
-		}
103
-
104
-		return null;
105
-	}
106
-
107
-	/**
108
-	 * @return array the arguments of the method with key => default value
109
-	 */
110
-	public function getParameters(): array {
111
-		return $this->parameters;
112
-	}
113
-
114
-	/**
115
-	 * Check if a method contains an annotation
116
-	 * @param string $name the name of the annotation
117
-	 * @return bool true if the annotation is found
118
-	 */
119
-	public function hasAnnotation(string $name): bool {
120
-		return array_key_exists($name, $this->annotations);
121
-	}
122
-
123
-	/**
124
-	 * Get optional annotation parameter by key
125
-	 *
126
-	 * @param string $name the name of the annotation
127
-	 * @param string $key the string of the annotation
128
-	 * @return string
129
-	 */
130
-	public function getAnnotationParameter(string $name, string $key): string {
131
-		if(isset($this->annotations[$name][$key])) {
132
-			return $this->annotations[$name][$key];
133
-		}
134
-
135
-		return '';
136
-	}
41
+    public $annotations = [];
42
+    private $types = [];
43
+    private $parameters = [];
44
+
45
+    /**
46
+     * @param object $object an object or classname
47
+     * @param string $method the method which we want to inspect
48
+     */
49
+    public function reflect($object, string $method) {
50
+        $reflection = new \ReflectionMethod($object, $method);
51
+        $docs = $reflection->getDocComment();
52
+
53
+        if ($docs !== false) {
54
+            // extract everything prefixed by @ and first letter uppercase
55
+            preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)((?P<parameter>.*))?$/m', $docs, $matches);
56
+            foreach ($matches['annotation'] as $key => $annontation) {
57
+                $annotationValue = $matches['parameter'][$key];
58
+                if (isset($annotationValue[0]) && $annotationValue[0] === '(' && $annotationValue[\strlen($annotationValue) - 1] === ')') {
59
+                    $cutString = substr($annotationValue, 1, -1);
60
+                    $cutString = str_replace(' ', '', $cutString);
61
+                    $splittedArray = explode(',', $cutString);
62
+                    foreach ($splittedArray as $annotationValues) {
63
+                        list($key, $value) = explode('=', $annotationValues);
64
+                        $this->annotations[$annontation][$key] = $value;
65
+                    }
66
+                    continue;
67
+                }
68
+
69
+                $this->annotations[$annontation] = [$annotationValue];
70
+            }
71
+
72
+            // extract type parameter information
73
+            preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
74
+            $this->types = array_combine($matches['var'], $matches['type']);
75
+        }
76
+
77
+        foreach ($reflection->getParameters() as $param) {
78
+            // extract type information from PHP 7 scalar types and prefer them over phpdoc annotations
79
+            $type = $param->getType();
80
+            if ($type instanceof \ReflectionNamedType) {
81
+                $this->types[$param->getName()] = $type->getName();
82
+            }
83
+
84
+            $default = null;
85
+            if($param->isOptional()) {
86
+                $default = $param->getDefaultValue();
87
+            }
88
+            $this->parameters[$param->name] = $default;
89
+        }
90
+    }
91
+
92
+    /**
93
+     * Inspects the PHPDoc parameters for types
94
+     * @param string $parameter the parameter whose type comments should be
95
+     * parsed
96
+     * @return string|null type in the type parameters (@param int $something)
97
+     * would return int or null if not existing
98
+     */
99
+    public function getType(string $parameter) {
100
+        if(array_key_exists($parameter, $this->types)) {
101
+            return $this->types[$parameter];
102
+        }
103
+
104
+        return null;
105
+    }
106
+
107
+    /**
108
+     * @return array the arguments of the method with key => default value
109
+     */
110
+    public function getParameters(): array {
111
+        return $this->parameters;
112
+    }
113
+
114
+    /**
115
+     * Check if a method contains an annotation
116
+     * @param string $name the name of the annotation
117
+     * @return bool true if the annotation is found
118
+     */
119
+    public function hasAnnotation(string $name): bool {
120
+        return array_key_exists($name, $this->annotations);
121
+    }
122
+
123
+    /**
124
+     * Get optional annotation parameter by key
125
+     *
126
+     * @param string $name the name of the annotation
127
+     * @param string $key the string of the annotation
128
+     * @return string
129
+     */
130
+    public function getAnnotationParameter(string $name, string $key): string {
131
+        if(isset($this->annotations[$name][$key])) {
132
+            return $this->annotations[$name][$key];
133
+        }
134
+
135
+        return '';
136
+    }
137 137
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 			}
83 83
 
84 84
 			$default = null;
85
-			if($param->isOptional()) {
85
+			if ($param->isOptional()) {
86 86
 				$default = $param->getDefaultValue();
87 87
 			}
88 88
 			$this->parameters[$param->name] = $default;
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 	 * would return int or null if not existing
98 98
 	 */
99 99
 	public function getType(string $parameter) {
100
-		if(array_key_exists($parameter, $this->types)) {
100
+		if (array_key_exists($parameter, $this->types)) {
101 101
 			return $this->types[$parameter];
102 102
 		}
103 103
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 	 * @return string
129 129
 	 */
130 130
 	public function getAnnotationParameter(string $name, string $key): string {
131
-		if(isset($this->annotations[$name][$key])) {
131
+		if (isset($this->annotations[$name][$key])) {
132 132
 			return $this->annotations[$name][$key];
133 133
 		}
134 134
 
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/CORSMiddleware.php 2 patches
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -45,116 +45,116 @@
 block discarded – undo
45 45
  * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
46 46
  */
47 47
 class CORSMiddleware extends Middleware {
48
-	/** @var IRequest  */
49
-	private $request;
50
-	/** @var ControllerMethodReflector */
51
-	private $reflector;
52
-	/** @var Session */
53
-	private $session;
54
-	/** @var Throttler */
55
-	private $throttler;
48
+    /** @var IRequest  */
49
+    private $request;
50
+    /** @var ControllerMethodReflector */
51
+    private $reflector;
52
+    /** @var Session */
53
+    private $session;
54
+    /** @var Throttler */
55
+    private $throttler;
56 56
 
57
-	/**
58
-	 * @param IRequest $request
59
-	 * @param ControllerMethodReflector $reflector
60
-	 * @param Session $session
61
-	 * @param Throttler $throttler
62
-	 */
63
-	public function __construct(IRequest $request,
64
-								ControllerMethodReflector $reflector,
65
-								Session $session,
66
-								Throttler $throttler) {
67
-		$this->request = $request;
68
-		$this->reflector = $reflector;
69
-		$this->session = $session;
70
-		$this->throttler = $throttler;
71
-	}
57
+    /**
58
+     * @param IRequest $request
59
+     * @param ControllerMethodReflector $reflector
60
+     * @param Session $session
61
+     * @param Throttler $throttler
62
+     */
63
+    public function __construct(IRequest $request,
64
+                                ControllerMethodReflector $reflector,
65
+                                Session $session,
66
+                                Throttler $throttler) {
67
+        $this->request = $request;
68
+        $this->reflector = $reflector;
69
+        $this->session = $session;
70
+        $this->throttler = $throttler;
71
+    }
72 72
 
73
-	/**
74
-	 * This is being run in normal order before the controller is being
75
-	 * called which allows several modifications and checks
76
-	 *
77
-	 * @param Controller $controller the controller that is being called
78
-	 * @param string $methodName the name of the method that will be called on
79
-	 *                           the controller
80
-	 * @throws SecurityException
81
-	 * @since 6.0.0
82
-	 */
83
-	public function beforeController($controller, $methodName) {
84
-		// ensure that @CORS annotated API routes are not used in conjunction
85
-		// with session authentication since this enables CSRF attack vectors
86
-		if ($this->reflector->hasAnnotation('CORS') &&
87
-			!$this->reflector->hasAnnotation('PublicPage'))  {
88
-			$user = $this->request->server['PHP_AUTH_USER'];
89
-			$pass = $this->request->server['PHP_AUTH_PW'];
73
+    /**
74
+     * This is being run in normal order before the controller is being
75
+     * called which allows several modifications and checks
76
+     *
77
+     * @param Controller $controller the controller that is being called
78
+     * @param string $methodName the name of the method that will be called on
79
+     *                           the controller
80
+     * @throws SecurityException
81
+     * @since 6.0.0
82
+     */
83
+    public function beforeController($controller, $methodName) {
84
+        // ensure that @CORS annotated API routes are not used in conjunction
85
+        // with session authentication since this enables CSRF attack vectors
86
+        if ($this->reflector->hasAnnotation('CORS') &&
87
+            !$this->reflector->hasAnnotation('PublicPage'))  {
88
+            $user = $this->request->server['PHP_AUTH_USER'];
89
+            $pass = $this->request->server['PHP_AUTH_PW'];
90 90
 
91
-			$this->session->logout();
92
-			try {
93
-				if (!$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
94
-					throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
95
-				}
96
-			} catch (PasswordLoginForbiddenException $ex) {
97
-				throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
98
-			}
99
-		}
100
-	}
91
+            $this->session->logout();
92
+            try {
93
+                if (!$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
94
+                    throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
95
+                }
96
+            } catch (PasswordLoginForbiddenException $ex) {
97
+                throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
98
+            }
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * This is being run after a successful controllermethod call and allows
104
-	 * the manipulation of a Response object. The middleware is run in reverse order
105
-	 *
106
-	 * @param Controller $controller the controller that is being called
107
-	 * @param string $methodName the name of the method that will be called on
108
-	 *                           the controller
109
-	 * @param Response $response the generated response from the controller
110
-	 * @return Response a Response object
111
-	 * @throws SecurityException
112
-	 */
113
-	public function afterController($controller, $methodName, Response $response) {
114
-		// only react if its a CORS request and if the request sends origin and
102
+    /**
103
+     * This is being run after a successful controllermethod call and allows
104
+     * the manipulation of a Response object. The middleware is run in reverse order
105
+     *
106
+     * @param Controller $controller the controller that is being called
107
+     * @param string $methodName the name of the method that will be called on
108
+     *                           the controller
109
+     * @param Response $response the generated response from the controller
110
+     * @return Response a Response object
111
+     * @throws SecurityException
112
+     */
113
+    public function afterController($controller, $methodName, Response $response) {
114
+        // only react if its a CORS request and if the request sends origin and
115 115
 
116
-		if(isset($this->request->server['HTTP_ORIGIN']) &&
117
-			$this->reflector->hasAnnotation('CORS')) {
116
+        if(isset($this->request->server['HTTP_ORIGIN']) &&
117
+            $this->reflector->hasAnnotation('CORS')) {
118 118
 
119
-			// allow credentials headers must not be true or CSRF is possible
120
-			// otherwise
121
-			foreach($response->getHeaders() as $header => $value) {
122
-				if(strtolower($header) === 'access-control-allow-credentials' &&
123
-				   strtolower(trim($value)) === 'true') {
124
-					$msg = 'Access-Control-Allow-Credentials must not be '.
125
-						   'set to true in order to prevent CSRF';
126
-					throw new SecurityException($msg);
127
-				}
128
-			}
119
+            // allow credentials headers must not be true or CSRF is possible
120
+            // otherwise
121
+            foreach($response->getHeaders() as $header => $value) {
122
+                if(strtolower($header) === 'access-control-allow-credentials' &&
123
+                   strtolower(trim($value)) === 'true') {
124
+                    $msg = 'Access-Control-Allow-Credentials must not be '.
125
+                            'set to true in order to prevent CSRF';
126
+                    throw new SecurityException($msg);
127
+                }
128
+            }
129 129
 
130
-			$origin = $this->request->server['HTTP_ORIGIN'];
131
-			$response->addHeader('Access-Control-Allow-Origin', $origin);
132
-		}
133
-		return $response;
134
-	}
130
+            $origin = $this->request->server['HTTP_ORIGIN'];
131
+            $response->addHeader('Access-Control-Allow-Origin', $origin);
132
+        }
133
+        return $response;
134
+    }
135 135
 
136
-	/**
137
-	 * If an SecurityException is being caught return a JSON error response
138
-	 *
139
-	 * @param Controller $controller the controller that is being called
140
-	 * @param string $methodName the name of the method that will be called on
141
-	 *                           the controller
142
-	 * @param \Exception $exception the thrown exception
143
-	 * @throws \Exception the passed in exception if it can't handle it
144
-	 * @return Response a Response object or null in case that the exception could not be handled
145
-	 */
146
-	public function afterException($controller, $methodName, \Exception $exception) {
147
-		if($exception instanceof SecurityException){
148
-			$response =  new JSONResponse(['message' => $exception->getMessage()]);
149
-			if($exception->getCode() !== 0) {
150
-				$response->setStatus($exception->getCode());
151
-			} else {
152
-				$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
153
-			}
154
-			return $response;
155
-		}
136
+    /**
137
+     * If an SecurityException is being caught return a JSON error response
138
+     *
139
+     * @param Controller $controller the controller that is being called
140
+     * @param string $methodName the name of the method that will be called on
141
+     *                           the controller
142
+     * @param \Exception $exception the thrown exception
143
+     * @throws \Exception the passed in exception if it can't handle it
144
+     * @return Response a Response object or null in case that the exception could not be handled
145
+     */
146
+    public function afterException($controller, $methodName, \Exception $exception) {
147
+        if($exception instanceof SecurityException){
148
+            $response =  new JSONResponse(['message' => $exception->getMessage()]);
149
+            if($exception->getCode() !== 0) {
150
+                $response->setStatus($exception->getCode());
151
+            } else {
152
+                $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
153
+            }
154
+            return $response;
155
+        }
156 156
 
157
-		throw $exception;
158
-	}
157
+        throw $exception;
158
+    }
159 159
 
160 160
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 		// ensure that @CORS annotated API routes are not used in conjunction
85 85
 		// with session authentication since this enables CSRF attack vectors
86 86
 		if ($this->reflector->hasAnnotation('CORS') &&
87
-			!$this->reflector->hasAnnotation('PublicPage'))  {
87
+			!$this->reflector->hasAnnotation('PublicPage')) {
88 88
 			$user = $this->request->server['PHP_AUTH_USER'];
89 89
 			$pass = $this->request->server['PHP_AUTH_PW'];
90 90
 
@@ -113,13 +113,13 @@  discard block
 block discarded – undo
113 113
 	public function afterController($controller, $methodName, Response $response) {
114 114
 		// only react if its a CORS request and if the request sends origin and
115 115
 
116
-		if(isset($this->request->server['HTTP_ORIGIN']) &&
116
+		if (isset($this->request->server['HTTP_ORIGIN']) &&
117 117
 			$this->reflector->hasAnnotation('CORS')) {
118 118
 
119 119
 			// allow credentials headers must not be true or CSRF is possible
120 120
 			// otherwise
121
-			foreach($response->getHeaders() as $header => $value) {
122
-				if(strtolower($header) === 'access-control-allow-credentials' &&
121
+			foreach ($response->getHeaders() as $header => $value) {
122
+				if (strtolower($header) === 'access-control-allow-credentials' &&
123 123
 				   strtolower(trim($value)) === 'true') {
124 124
 					$msg = 'Access-Control-Allow-Credentials must not be '.
125 125
 						   'set to true in order to prevent CSRF';
@@ -144,9 +144,9 @@  discard block
 block discarded – undo
144 144
 	 * @return Response a Response object or null in case that the exception could not be handled
145 145
 	 */
146 146
 	public function afterException($controller, $methodName, \Exception $exception) {
147
-		if($exception instanceof SecurityException){
148
-			$response =  new JSONResponse(['message' => $exception->getMessage()]);
149
-			if($exception->getCode() !== 0) {
147
+		if ($exception instanceof SecurityException) {
148
+			$response = new JSONResponse(['message' => $exception->getMessage()]);
149
+			if ($exception->getCode() !== 0) {
150 150
 				$response->setStatus($exception->getCode());
151 151
 			} else {
152 152
 				$response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/MiddlewareDispatcher.php 2 patches
Indentation   +123 added lines, -123 removed lines patch added patch discarded remove patch
@@ -40,128 +40,128 @@
 block discarded – undo
40 40
  */
41 41
 class MiddlewareDispatcher {
42 42
 
43
-	/**
44
-	 * @var array array containing all the middlewares
45
-	 */
46
-	private $middlewares;
47
-
48
-	/**
49
-	 * @var int counter which tells us what middlware was executed once an
50
-	 *                  exception occurs
51
-	 */
52
-	private $middlewareCounter;
53
-
54
-
55
-	/**
56
-	 * Constructor
57
-	 */
58
-	public function __construct() {
59
-		$this->middlewares = [];
60
-		$this->middlewareCounter = 0;
61
-	}
62
-
63
-
64
-	/**
65
-	 * Adds a new middleware
66
-	 * @param Middleware $middleWare the middleware which will be added
67
-	 */
68
-	public function registerMiddleware(Middleware $middleWare) {
69
-		$this->middlewares[] = $middleWare;
70
-	}
71
-
72
-
73
-	/**
74
-	 * returns an array with all middleware elements
75
-	 * @return array the middlewares
76
-	 */
77
-	public function getMiddlewares(): array {
78
-		return $this->middlewares;
79
-	}
80
-
81
-
82
-	/**
83
-	 * This is being run in normal order before the controller is being
84
-	 * called which allows several modifications and checks
85
-	 *
86
-	 * @param Controller $controller the controller that is being called
87
-	 * @param string $methodName the name of the method that will be called on
88
-	 *                           the controller
89
-	 */
90
-	public function beforeController(Controller $controller, string $methodName) {
91
-		// we need to count so that we know which middlewares we have to ask in
92
-		// case there is an exception
93
-		$middlewareCount = \count($this->middlewares);
94
-		for($i = 0; $i < $middlewareCount; $i++){
95
-			$this->middlewareCounter++;
96
-			$middleware = $this->middlewares[$i];
97
-			$middleware->beforeController($controller, $methodName);
98
-		}
99
-	}
100
-
101
-
102
-	/**
103
-	 * This is being run when either the beforeController method or the
104
-	 * controller method itself is throwing an exception. The middleware is asked
105
-	 * in reverse order to handle the exception and to return a response.
106
-	 * If the response is null, it is assumed that the exception could not be
107
-	 * handled and the error will be thrown again
108
-	 *
109
-	 * @param Controller $controller the controller that is being called
110
-	 * @param string $methodName the name of the method that will be called on
111
-	 *                            the controller
112
-	 * @param \Exception $exception the thrown exception
113
-	 * @return Response a Response object if the middleware can handle the
114
-	 * exception
115
-	 * @throws \Exception the passed in exception if it can't handle it
116
-	 */
117
-	public function afterException(Controller $controller, string $methodName, \Exception $exception): Response {
118
-		for($i=$this->middlewareCounter-1; $i>=0; $i--){
119
-			$middleware = $this->middlewares[$i];
120
-			try {
121
-				return $middleware->afterException($controller, $methodName, $exception);
122
-			} catch(\Exception $exception){
123
-				continue;
124
-			}
125
-		}
126
-		throw $exception;
127
-	}
128
-
129
-
130
-	/**
131
-	 * This is being run after a successful controllermethod call and allows
132
-	 * the manipulation of a Response object. The middleware is run in reverse order
133
-	 *
134
-	 * @param Controller $controller the controller that is being called
135
-	 * @param string $methodName the name of the method that will be called on
136
-	 *                            the controller
137
-	 * @param Response $response the generated response from the controller
138
-	 * @return Response a Response object
139
-	 */
140
-	public function afterController(Controller $controller, string $methodName, Response $response): Response {
141
-		for($i= \count($this->middlewares)-1; $i>=0; $i--){
142
-			$middleware = $this->middlewares[$i];
143
-			$response = $middleware->afterController($controller, $methodName, $response);
144
-		}
145
-		return $response;
146
-	}
147
-
148
-
149
-	/**
150
-	 * This is being run after the response object has been rendered and
151
-	 * allows the manipulation of the output. The middleware is run in reverse order
152
-	 *
153
-	 * @param Controller $controller the controller that is being called
154
-	 * @param string $methodName the name of the method that will be called on
155
-	 *                           the controller
156
-	 * @param string $output the generated output from a response
157
-	 * @return string the output that should be printed
158
-	 */
159
-	public function beforeOutput(Controller $controller, string $methodName, string $output): string {
160
-		for($i= \count($this->middlewares)-1; $i>=0; $i--){
161
-			$middleware = $this->middlewares[$i];
162
-			$output = $middleware->beforeOutput($controller, $methodName, $output);
163
-		}
164
-		return $output;
165
-	}
43
+    /**
44
+     * @var array array containing all the middlewares
45
+     */
46
+    private $middlewares;
47
+
48
+    /**
49
+     * @var int counter which tells us what middlware was executed once an
50
+     *                  exception occurs
51
+     */
52
+    private $middlewareCounter;
53
+
54
+
55
+    /**
56
+     * Constructor
57
+     */
58
+    public function __construct() {
59
+        $this->middlewares = [];
60
+        $this->middlewareCounter = 0;
61
+    }
62
+
63
+
64
+    /**
65
+     * Adds a new middleware
66
+     * @param Middleware $middleWare the middleware which will be added
67
+     */
68
+    public function registerMiddleware(Middleware $middleWare) {
69
+        $this->middlewares[] = $middleWare;
70
+    }
71
+
72
+
73
+    /**
74
+     * returns an array with all middleware elements
75
+     * @return array the middlewares
76
+     */
77
+    public function getMiddlewares(): array {
78
+        return $this->middlewares;
79
+    }
80
+
81
+
82
+    /**
83
+     * This is being run in normal order before the controller is being
84
+     * called which allows several modifications and checks
85
+     *
86
+     * @param Controller $controller the controller that is being called
87
+     * @param string $methodName the name of the method that will be called on
88
+     *                           the controller
89
+     */
90
+    public function beforeController(Controller $controller, string $methodName) {
91
+        // we need to count so that we know which middlewares we have to ask in
92
+        // case there is an exception
93
+        $middlewareCount = \count($this->middlewares);
94
+        for($i = 0; $i < $middlewareCount; $i++){
95
+            $this->middlewareCounter++;
96
+            $middleware = $this->middlewares[$i];
97
+            $middleware->beforeController($controller, $methodName);
98
+        }
99
+    }
100
+
101
+
102
+    /**
103
+     * This is being run when either the beforeController method or the
104
+     * controller method itself is throwing an exception. The middleware is asked
105
+     * in reverse order to handle the exception and to return a response.
106
+     * If the response is null, it is assumed that the exception could not be
107
+     * handled and the error will be thrown again
108
+     *
109
+     * @param Controller $controller the controller that is being called
110
+     * @param string $methodName the name of the method that will be called on
111
+     *                            the controller
112
+     * @param \Exception $exception the thrown exception
113
+     * @return Response a Response object if the middleware can handle the
114
+     * exception
115
+     * @throws \Exception the passed in exception if it can't handle it
116
+     */
117
+    public function afterException(Controller $controller, string $methodName, \Exception $exception): Response {
118
+        for($i=$this->middlewareCounter-1; $i>=0; $i--){
119
+            $middleware = $this->middlewares[$i];
120
+            try {
121
+                return $middleware->afterException($controller, $methodName, $exception);
122
+            } catch(\Exception $exception){
123
+                continue;
124
+            }
125
+        }
126
+        throw $exception;
127
+    }
128
+
129
+
130
+    /**
131
+     * This is being run after a successful controllermethod call and allows
132
+     * the manipulation of a Response object. The middleware is run in reverse order
133
+     *
134
+     * @param Controller $controller the controller that is being called
135
+     * @param string $methodName the name of the method that will be called on
136
+     *                            the controller
137
+     * @param Response $response the generated response from the controller
138
+     * @return Response a Response object
139
+     */
140
+    public function afterController(Controller $controller, string $methodName, Response $response): Response {
141
+        for($i= \count($this->middlewares)-1; $i>=0; $i--){
142
+            $middleware = $this->middlewares[$i];
143
+            $response = $middleware->afterController($controller, $methodName, $response);
144
+        }
145
+        return $response;
146
+    }
147
+
148
+
149
+    /**
150
+     * This is being run after the response object has been rendered and
151
+     * allows the manipulation of the output. The middleware is run in reverse order
152
+     *
153
+     * @param Controller $controller the controller that is being called
154
+     * @param string $methodName the name of the method that will be called on
155
+     *                           the controller
156
+     * @param string $output the generated output from a response
157
+     * @return string the output that should be printed
158
+     */
159
+    public function beforeOutput(Controller $controller, string $methodName, string $output): string {
160
+        for($i= \count($this->middlewares)-1; $i>=0; $i--){
161
+            $middleware = $this->middlewares[$i];
162
+            $output = $middleware->beforeOutput($controller, $methodName, $output);
163
+        }
164
+        return $output;
165
+    }
166 166
 
167 167
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 		// we need to count so that we know which middlewares we have to ask in
92 92
 		// case there is an exception
93 93
 		$middlewareCount = \count($this->middlewares);
94
-		for($i = 0; $i < $middlewareCount; $i++){
94
+		for ($i = 0; $i < $middlewareCount; $i++) {
95 95
 			$this->middlewareCounter++;
96 96
 			$middleware = $this->middlewares[$i];
97 97
 			$middleware->beforeController($controller, $methodName);
@@ -115,11 +115,11 @@  discard block
 block discarded – undo
115 115
 	 * @throws \Exception the passed in exception if it can't handle it
116 116
 	 */
117 117
 	public function afterException(Controller $controller, string $methodName, \Exception $exception): Response {
118
-		for($i=$this->middlewareCounter-1; $i>=0; $i--){
118
+		for ($i = $this->middlewareCounter - 1; $i >= 0; $i--) {
119 119
 			$middleware = $this->middlewares[$i];
120 120
 			try {
121 121
 				return $middleware->afterException($controller, $methodName, $exception);
122
-			} catch(\Exception $exception){
122
+			} catch (\Exception $exception) {
123 123
 				continue;
124 124
 			}
125 125
 		}
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 	 * @return Response a Response object
139 139
 	 */
140 140
 	public function afterController(Controller $controller, string $methodName, Response $response): Response {
141
-		for($i= \count($this->middlewares)-1; $i>=0; $i--){
141
+		for ($i = \count($this->middlewares) - 1; $i >= 0; $i--) {
142 142
 			$middleware = $this->middlewares[$i];
143 143
 			$response = $middleware->afterController($controller, $methodName, $response);
144 144
 		}
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 	 * @return string the output that should be printed
158 158
 	 */
159 159
 	public function beforeOutput(Controller $controller, string $methodName, string $output): string {
160
-		for($i= \count($this->middlewares)-1; $i>=0; $i--){
160
+		for ($i = \count($this->middlewares) - 1; $i >= 0; $i--) {
161 161
 			$middleware = $this->middlewares[$i];
162 162
 			$output = $middleware->beforeOutput($controller, $methodName, $output);
163 163
 		}
Please login to merge, or discard this patch.