Completed
Push — master ( ff1dfc...e6bdfc )
by Robin
42:33 queued 24s
created
lib/private/Files/View.php 2 patches
Indentation   +2244 added lines, -2244 removed lines patch added patch discarded remove patch
@@ -56,2248 +56,2248 @@
 block discarded – undo
56 56
  * \OC\Files\Storage\Storage object
57 57
  */
58 58
 class View {
59
-	private string $fakeRoot = '';
60
-	private ILockingProvider $lockingProvider;
61
-	private bool $lockingEnabled;
62
-	private bool $updaterEnabled = true;
63
-	private UserManager $userManager;
64
-	private LoggerInterface $logger;
65
-
66
-	/**
67
-	 * @throws \Exception If $root contains an invalid path
68
-	 */
69
-	public function __construct(string $root = '') {
70
-		if (!Filesystem::isValidPath($root)) {
71
-			throw new \Exception();
72
-		}
73
-
74
-		$this->fakeRoot = $root;
75
-		$this->lockingProvider = \OC::$server->get(ILockingProvider::class);
76
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
77
-		$this->userManager = \OC::$server->getUserManager();
78
-		$this->logger = \OC::$server->get(LoggerInterface::class);
79
-	}
80
-
81
-	/**
82
-	 * @param ?string $path
83
-	 * @psalm-template S as string|null
84
-	 * @psalm-param S $path
85
-	 * @psalm-return (S is string ? string : null)
86
-	 */
87
-	public function getAbsolutePath($path = '/'): ?string {
88
-		if ($path === null) {
89
-			return null;
90
-		}
91
-		$this->assertPathLength($path);
92
-		if ($path === '') {
93
-			$path = '/';
94
-		}
95
-		if ($path[0] !== '/') {
96
-			$path = '/' . $path;
97
-		}
98
-		return $this->fakeRoot . $path;
99
-	}
100
-
101
-	/**
102
-	 * Change the root to a fake root
103
-	 *
104
-	 * @param string $fakeRoot
105
-	 */
106
-	public function chroot($fakeRoot): void {
107
-		if (!$fakeRoot == '') {
108
-			if ($fakeRoot[0] !== '/') {
109
-				$fakeRoot = '/' . $fakeRoot;
110
-			}
111
-		}
112
-		$this->fakeRoot = $fakeRoot;
113
-	}
114
-
115
-	/**
116
-	 * Get the fake root
117
-	 */
118
-	public function getRoot(): string {
119
-		return $this->fakeRoot;
120
-	}
121
-
122
-	/**
123
-	 * get path relative to the root of the view
124
-	 *
125
-	 * @param string $path
126
-	 */
127
-	public function getRelativePath($path): ?string {
128
-		$this->assertPathLength($path);
129
-		if ($this->fakeRoot == '') {
130
-			return $path;
131
-		}
132
-
133
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
134
-			return '/';
135
-		}
136
-
137
-		// missing slashes can cause wrong matches!
138
-		$root = rtrim($this->fakeRoot, '/') . '/';
139
-
140
-		if (!str_starts_with($path, $root)) {
141
-			return null;
142
-		} else {
143
-			$path = substr($path, strlen($this->fakeRoot));
144
-			if (strlen($path) === 0) {
145
-				return '/';
146
-			} else {
147
-				return $path;
148
-			}
149
-		}
150
-	}
151
-
152
-	/**
153
-	 * Get the mountpoint of the storage object for a path
154
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
155
-	 * returned mountpoint is relative to the absolute root of the filesystem
156
-	 * and does not take the chroot into account )
157
-	 *
158
-	 * @param string $path
159
-	 */
160
-	public function getMountPoint($path): string {
161
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
162
-	}
163
-
164
-	/**
165
-	 * Get the mountpoint of the storage object for a path
166
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
167
-	 * returned mountpoint is relative to the absolute root of the filesystem
168
-	 * and does not take the chroot into account )
169
-	 *
170
-	 * @param string $path
171
-	 */
172
-	public function getMount($path): IMountPoint {
173
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
174
-	}
175
-
176
-	/**
177
-	 * Resolve a path to a storage and internal path
178
-	 *
179
-	 * @param string $path
180
-	 * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
181
-	 */
182
-	public function resolvePath($path): array {
183
-		$a = $this->getAbsolutePath($path);
184
-		$p = Filesystem::normalizePath($a);
185
-		return Filesystem::resolvePath($p);
186
-	}
187
-
188
-	/**
189
-	 * Return the path to a local version of the file
190
-	 * we need this because we can't know if a file is stored local or not from
191
-	 * outside the filestorage and for some purposes a local file is needed
192
-	 *
193
-	 * @param string $path
194
-	 */
195
-	public function getLocalFile($path): string|false {
196
-		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
197
-		$path = $this->getAbsolutePath($path);
198
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
199
-		if (Filesystem::isValidPath($parent) && $storage) {
200
-			return $storage->getLocalFile($internalPath);
201
-		} else {
202
-			return false;
203
-		}
204
-	}
205
-
206
-	/**
207
-	 * the following functions operate with arguments and return values identical
208
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
209
-	 * for \OC\Files\Storage\Storage via basicOperation().
210
-	 */
211
-	public function mkdir($path) {
212
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
213
-	}
214
-
215
-	/**
216
-	 * remove mount point
217
-	 *
218
-	 * @param IMountPoint $mount
219
-	 * @param string $path relative to data/
220
-	 */
221
-	protected function removeMount($mount, $path): bool {
222
-		if ($mount instanceof MoveableMount) {
223
-			// cut of /user/files to get the relative path to data/user/files
224
-			$pathParts = explode('/', $path, 4);
225
-			$relPath = '/' . $pathParts[3];
226
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
227
-			\OC_Hook::emit(
228
-				Filesystem::CLASSNAME, 'umount',
229
-				[Filesystem::signal_param_path => $relPath]
230
-			);
231
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
232
-			$result = $mount->removeMount();
233
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
234
-			if ($result) {
235
-				\OC_Hook::emit(
236
-					Filesystem::CLASSNAME, 'post_umount',
237
-					[Filesystem::signal_param_path => $relPath]
238
-				);
239
-			}
240
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
241
-			return $result;
242
-		} else {
243
-			// do not allow deleting the storage's root / the mount point
244
-			// because for some storages it might delete the whole contents
245
-			// but isn't supposed to work that way
246
-			return false;
247
-		}
248
-	}
249
-
250
-	public function disableCacheUpdate(): void {
251
-		$this->updaterEnabled = false;
252
-	}
253
-
254
-	public function enableCacheUpdate(): void {
255
-		$this->updaterEnabled = true;
256
-	}
257
-
258
-	protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
259
-		if ($this->updaterEnabled) {
260
-			if (is_null($time)) {
261
-				$time = time();
262
-			}
263
-			$storage->getUpdater()->update($internalPath, $time, $sizeDifference);
264
-		}
265
-	}
266
-
267
-	protected function removeUpdate(Storage $storage, string $internalPath): void {
268
-		if ($this->updaterEnabled) {
269
-			$storage->getUpdater()->remove($internalPath);
270
-		}
271
-	}
272
-
273
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
274
-		if ($this->updaterEnabled) {
275
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
276
-		}
277
-	}
278
-
279
-	protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
280
-		if ($this->updaterEnabled) {
281
-			$targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
282
-		}
283
-	}
284
-
285
-	/**
286
-	 * @param string $path
287
-	 * @return bool|mixed
288
-	 */
289
-	public function rmdir($path) {
290
-		$absolutePath = $this->getAbsolutePath($path);
291
-		$mount = Filesystem::getMountManager()->find($absolutePath);
292
-		if ($mount->getInternalPath($absolutePath) === '') {
293
-			return $this->removeMount($mount, $absolutePath);
294
-		}
295
-		if ($this->is_dir($path)) {
296
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
297
-		} else {
298
-			$result = false;
299
-		}
300
-
301
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
302
-			$storage = $mount->getStorage();
303
-			$internalPath = $mount->getInternalPath($absolutePath);
304
-			$storage->getUpdater()->remove($internalPath);
305
-		}
306
-		return $result;
307
-	}
308
-
309
-	/**
310
-	 * @param string $path
311
-	 * @return resource|false
312
-	 */
313
-	public function opendir($path) {
314
-		return $this->basicOperation('opendir', $path, ['read']);
315
-	}
316
-
317
-	/**
318
-	 * @param string $path
319
-	 * @return bool|mixed
320
-	 */
321
-	public function is_dir($path) {
322
-		if ($path == '/') {
323
-			return true;
324
-		}
325
-		return $this->basicOperation('is_dir', $path);
326
-	}
327
-
328
-	/**
329
-	 * @param string $path
330
-	 * @return bool|mixed
331
-	 */
332
-	public function is_file($path) {
333
-		if ($path == '/') {
334
-			return false;
335
-		}
336
-		return $this->basicOperation('is_file', $path);
337
-	}
338
-
339
-	/**
340
-	 * @param string $path
341
-	 * @return mixed
342
-	 */
343
-	public function stat($path) {
344
-		return $this->basicOperation('stat', $path);
345
-	}
346
-
347
-	/**
348
-	 * @param string $path
349
-	 * @return mixed
350
-	 */
351
-	public function filetype($path) {
352
-		return $this->basicOperation('filetype', $path);
353
-	}
354
-
355
-	/**
356
-	 * @param string $path
357
-	 * @return mixed
358
-	 */
359
-	public function filesize(string $path) {
360
-		return $this->basicOperation('filesize', $path);
361
-	}
362
-
363
-	/**
364
-	 * @param string $path
365
-	 * @return bool|mixed
366
-	 * @throws InvalidPathException
367
-	 */
368
-	public function readfile($path) {
369
-		$this->assertPathLength($path);
370
-		if (ob_get_level()) {
371
-			ob_end_clean();
372
-		}
373
-		$handle = $this->fopen($path, 'rb');
374
-		if ($handle) {
375
-			$chunkSize = 524288; // 512 kiB chunks
376
-			while (!feof($handle)) {
377
-				echo fread($handle, $chunkSize);
378
-				flush();
379
-				$this->checkConnectionStatus();
380
-			}
381
-			fclose($handle);
382
-			return $this->filesize($path);
383
-		}
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * @param string $path
389
-	 * @param int $from
390
-	 * @param int $to
391
-	 * @return bool|mixed
392
-	 * @throws InvalidPathException
393
-	 * @throws \OCP\Files\UnseekableException
394
-	 */
395
-	public function readfilePart($path, $from, $to) {
396
-		$this->assertPathLength($path);
397
-		if (ob_get_level()) {
398
-			ob_end_clean();
399
-		}
400
-		$handle = $this->fopen($path, 'rb');
401
-		if ($handle) {
402
-			$chunkSize = 524288; // 512 kiB chunks
403
-			$startReading = true;
404
-
405
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
406
-				// forward file handle via chunked fread because fseek seem to have failed
407
-
408
-				$end = $from + 1;
409
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
410
-					$len = $from - ftell($handle);
411
-					if ($len > $chunkSize) {
412
-						$len = $chunkSize;
413
-					}
414
-					$result = fread($handle, $len);
415
-
416
-					if ($result === false) {
417
-						$startReading = false;
418
-						break;
419
-					}
420
-				}
421
-			}
422
-
423
-			if ($startReading) {
424
-				$end = $to + 1;
425
-				while (!feof($handle) && ftell($handle) < $end) {
426
-					$len = $end - ftell($handle);
427
-					if ($len > $chunkSize) {
428
-						$len = $chunkSize;
429
-					}
430
-					echo fread($handle, $len);
431
-					flush();
432
-					$this->checkConnectionStatus();
433
-				}
434
-				return ftell($handle) - $from;
435
-			}
436
-
437
-			throw new \OCP\Files\UnseekableException('fseek error');
438
-		}
439
-		return false;
440
-	}
441
-
442
-	private function checkConnectionStatus(): void {
443
-		$connectionStatus = \connection_status();
444
-		if ($connectionStatus !== CONNECTION_NORMAL) {
445
-			throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
446
-		}
447
-	}
448
-
449
-	/**
450
-	 * @param string $path
451
-	 * @return mixed
452
-	 */
453
-	public function isCreatable($path) {
454
-		return $this->basicOperation('isCreatable', $path);
455
-	}
456
-
457
-	/**
458
-	 * @param string $path
459
-	 * @return mixed
460
-	 */
461
-	public function isReadable($path) {
462
-		return $this->basicOperation('isReadable', $path);
463
-	}
464
-
465
-	/**
466
-	 * @param string $path
467
-	 * @return mixed
468
-	 */
469
-	public function isUpdatable($path) {
470
-		return $this->basicOperation('isUpdatable', $path);
471
-	}
472
-
473
-	/**
474
-	 * @param string $path
475
-	 * @return bool|mixed
476
-	 */
477
-	public function isDeletable($path) {
478
-		$absolutePath = $this->getAbsolutePath($path);
479
-		$mount = Filesystem::getMountManager()->find($absolutePath);
480
-		if ($mount->getInternalPath($absolutePath) === '') {
481
-			return $mount instanceof MoveableMount;
482
-		}
483
-		return $this->basicOperation('isDeletable', $path);
484
-	}
485
-
486
-	/**
487
-	 * @param string $path
488
-	 * @return mixed
489
-	 */
490
-	public function isSharable($path) {
491
-		return $this->basicOperation('isSharable', $path);
492
-	}
493
-
494
-	/**
495
-	 * @param string $path
496
-	 * @return bool|mixed
497
-	 */
498
-	public function file_exists($path) {
499
-		if ($path == '/') {
500
-			return true;
501
-		}
502
-		return $this->basicOperation('file_exists', $path);
503
-	}
504
-
505
-	/**
506
-	 * @param string $path
507
-	 * @return mixed
508
-	 */
509
-	public function filemtime($path) {
510
-		return $this->basicOperation('filemtime', $path);
511
-	}
512
-
513
-	/**
514
-	 * @param string $path
515
-	 * @param int|string $mtime
516
-	 */
517
-	public function touch($path, $mtime = null): bool {
518
-		if (!is_null($mtime) && !is_numeric($mtime)) {
519
-			$mtime = strtotime($mtime);
520
-		}
521
-
522
-		$hooks = ['touch'];
523
-
524
-		if (!$this->file_exists($path)) {
525
-			$hooks[] = 'create';
526
-			$hooks[] = 'write';
527
-		}
528
-		try {
529
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
530
-		} catch (\Exception $e) {
531
-			$this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
532
-			$result = false;
533
-		}
534
-		if (!$result) {
535
-			// If create file fails because of permissions on external storage like SMB folders,
536
-			// check file exists and return false if not.
537
-			if (!$this->file_exists($path)) {
538
-				return false;
539
-			}
540
-			if (is_null($mtime)) {
541
-				$mtime = time();
542
-			}
543
-			//if native touch fails, we emulate it by changing the mtime in the cache
544
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
545
-		}
546
-		return true;
547
-	}
548
-
549
-	/**
550
-	 * @param string $path
551
-	 * @return string|false
552
-	 * @throws LockedException
553
-	 */
554
-	public function file_get_contents($path) {
555
-		return $this->basicOperation('file_get_contents', $path, ['read']);
556
-	}
557
-
558
-	protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
559
-		if (!$exists) {
560
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
561
-				Filesystem::signal_param_path => $this->getHookPath($path),
562
-				Filesystem::signal_param_run => &$run,
563
-			]);
564
-		} else {
565
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
566
-				Filesystem::signal_param_path => $this->getHookPath($path),
567
-				Filesystem::signal_param_run => &$run,
568
-			]);
569
-		}
570
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
571
-			Filesystem::signal_param_path => $this->getHookPath($path),
572
-			Filesystem::signal_param_run => &$run,
573
-		]);
574
-	}
575
-
576
-	protected function emit_file_hooks_post(bool $exists, string $path): void {
577
-		if (!$exists) {
578
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
579
-				Filesystem::signal_param_path => $this->getHookPath($path),
580
-			]);
581
-		} else {
582
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
583
-				Filesystem::signal_param_path => $this->getHookPath($path),
584
-			]);
585
-		}
586
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
587
-			Filesystem::signal_param_path => $this->getHookPath($path),
588
-		]);
589
-	}
590
-
591
-	/**
592
-	 * @param string $path
593
-	 * @param string|resource $data
594
-	 * @return bool|mixed
595
-	 * @throws LockedException
596
-	 */
597
-	public function file_put_contents($path, $data) {
598
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
599
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
600
-			if (Filesystem::isValidPath($path)
601
-				&& !Filesystem::isFileBlacklisted($path)
602
-			) {
603
-				$path = $this->getRelativePath($absolutePath);
604
-				if ($path === null) {
605
-					throw new InvalidPathException("Path $absolutePath is not in the expected root");
606
-				}
607
-
608
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
609
-
610
-				$exists = $this->file_exists($path);
611
-				if ($this->shouldEmitHooks($path)) {
612
-					$run = true;
613
-					$this->emit_file_hooks_pre($exists, $path, $run);
614
-					if (!$run) {
615
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
616
-						return false;
617
-					}
618
-				}
619
-
620
-				try {
621
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
622
-				} catch (\Exception $e) {
623
-					// Release the shared lock before throwing.
624
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
625
-					throw $e;
626
-				}
627
-
628
-				/** @var Storage $storage */
629
-				[$storage, $internalPath] = $this->resolvePath($path);
630
-				$target = $storage->fopen($internalPath, 'w');
631
-				if ($target) {
632
-					[, $result] = \OC_Helper::streamCopy($data, $target);
633
-					fclose($target);
634
-					fclose($data);
635
-
636
-					$this->writeUpdate($storage, $internalPath);
637
-
638
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
639
-
640
-					if ($this->shouldEmitHooks($path) && $result !== false) {
641
-						$this->emit_file_hooks_post($exists, $path);
642
-					}
643
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
644
-					return $result;
645
-				} else {
646
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
647
-					return false;
648
-				}
649
-			} else {
650
-				return false;
651
-			}
652
-		} else {
653
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
654
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
655
-		}
656
-	}
657
-
658
-	/**
659
-	 * @param string $path
660
-	 * @return bool|mixed
661
-	 */
662
-	public function unlink($path) {
663
-		if ($path === '' || $path === '/') {
664
-			// do not allow deleting the root
665
-			return false;
666
-		}
667
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
668
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
669
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
670
-		if ($mount->getInternalPath($absolutePath) === '') {
671
-			return $this->removeMount($mount, $absolutePath);
672
-		}
673
-		if ($this->is_dir($path)) {
674
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
675
-		} else {
676
-			$result = $this->basicOperation('unlink', $path, ['delete']);
677
-		}
678
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
679
-			$storage = $mount->getStorage();
680
-			$internalPath = $mount->getInternalPath($absolutePath);
681
-			$storage->getUpdater()->remove($internalPath);
682
-			return true;
683
-		} else {
684
-			return $result;
685
-		}
686
-	}
687
-
688
-	/**
689
-	 * @param string $directory
690
-	 * @return bool|mixed
691
-	 */
692
-	public function deleteAll($directory) {
693
-		return $this->rmdir($directory);
694
-	}
695
-
696
-	/**
697
-	 * Rename/move a file or folder from the source path to target path.
698
-	 *
699
-	 * @param string $source source path
700
-	 * @param string $target target path
701
-	 * @param array $options
702
-	 *
703
-	 * @return bool|mixed
704
-	 * @throws LockedException
705
-	 */
706
-	public function rename($source, $target, array $options = []) {
707
-		$checkSubMounts = $options['checkSubMounts'] ?? true;
708
-
709
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
710
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
711
-
712
-		if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
713
-			throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
714
-		}
715
-
716
-		/** @var IMountManager $mountManager */
717
-		$mountManager = \OC::$server->get(IMountManager::class);
718
-
719
-		$targetParts = explode('/', $absolutePath2);
720
-		$targetUser = $targetParts[1] ?? null;
721
-		$result = false;
722
-		if (
723
-			Filesystem::isValidPath($target)
724
-			&& Filesystem::isValidPath($source)
725
-			&& !Filesystem::isFileBlacklisted($target)
726
-		) {
727
-			$source = $this->getRelativePath($absolutePath1);
728
-			$target = $this->getRelativePath($absolutePath2);
729
-			$exists = $this->file_exists($target);
730
-
731
-			if ($source == null || $target == null) {
732
-				return false;
733
-			}
734
-
735
-			try {
736
-				$this->verifyPath(dirname($target), basename($target));
737
-			} catch (InvalidPathException) {
738
-				return false;
739
-			}
740
-
741
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
742
-			try {
743
-				$this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
744
-
745
-				$run = true;
746
-				if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
747
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
748
-					$this->emit_file_hooks_pre($exists, $target, $run);
749
-				} elseif ($this->shouldEmitHooks($source)) {
750
-					$sourcePath = $this->getHookPath($source);
751
-					$targetPath = $this->getHookPath($target);
752
-					if ($sourcePath !== null && $targetPath !== null) {
753
-						\OC_Hook::emit(
754
-							Filesystem::CLASSNAME, Filesystem::signal_rename,
755
-							[
756
-								Filesystem::signal_param_oldpath => $sourcePath,
757
-								Filesystem::signal_param_newpath => $targetPath,
758
-								Filesystem::signal_param_run => &$run
759
-							]
760
-						);
761
-					}
762
-				}
763
-				if ($run) {
764
-					$manager = Filesystem::getMountManager();
765
-					$mount1 = $this->getMount($source);
766
-					$mount2 = $this->getMount($target);
767
-					$storage1 = $mount1->getStorage();
768
-					$storage2 = $mount2->getStorage();
769
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
770
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
771
-
772
-					$this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
773
-					try {
774
-						$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
775
-
776
-						if ($checkSubMounts) {
777
-							$movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
778
-						} else {
779
-							$movedMounts = [];
780
-						}
781
-
782
-						if ($internalPath1 === '') {
783
-							$sourceParentMount = $this->getMount(dirname($source));
784
-							$movedMounts[] = $mount1;
785
-							$this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
786
-							/**
787
-							 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
788
-							 */
789
-							$sourceMountPoint = $mount1->getMountPoint();
790
-							$result = $mount1->moveMount($absolutePath2);
791
-							$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
792
-
793
-							// moving a file/folder within the same mount point
794
-						} elseif ($storage1 === $storage2) {
795
-							if (count($movedMounts) > 0) {
796
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
797
-							}
798
-							if ($storage1) {
799
-								$result = $storage1->rename($internalPath1, $internalPath2);
800
-							} else {
801
-								$result = false;
802
-							}
803
-							// moving a file/folder between storages (from $storage1 to $storage2)
804
-						} else {
805
-							if (count($movedMounts) > 0) {
806
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
807
-							}
808
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
809
-						}
810
-
811
-						if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
812
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
813
-							$this->writeUpdate($storage2, $internalPath2);
814
-						} elseif ($result) {
815
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
816
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
817
-							}
818
-						}
819
-					} catch (\Exception $e) {
820
-						throw $e;
821
-					} finally {
822
-						$this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
823
-						$this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
824
-					}
825
-
826
-					if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
827
-						if ($this->shouldEmitHooks()) {
828
-							$this->emit_file_hooks_post($exists, $target);
829
-						}
830
-					} elseif ($result) {
831
-						if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
832
-							$sourcePath = $this->getHookPath($source);
833
-							$targetPath = $this->getHookPath($target);
834
-							if ($sourcePath !== null && $targetPath !== null) {
835
-								\OC_Hook::emit(
836
-									Filesystem::CLASSNAME,
837
-									Filesystem::signal_post_rename,
838
-									[
839
-										Filesystem::signal_param_oldpath => $sourcePath,
840
-										Filesystem::signal_param_newpath => $targetPath,
841
-									]
842
-								);
843
-							}
844
-						}
845
-					}
846
-				}
847
-			} catch (\Exception $e) {
848
-				throw $e;
849
-			} finally {
850
-				$this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
851
-				$this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
852
-			}
853
-		}
854
-		return $result;
855
-	}
856
-
857
-	/**
858
-	 * @throws ForbiddenException
859
-	 */
860
-	private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
861
-		$targetPath = $this->getRelativePath($targetMount->getMountPoint());
862
-		if ($targetPath) {
863
-			$targetPath = trim($targetPath, '/');
864
-		} else {
865
-			$targetPath = $targetMount->getMountPoint();
866
-		}
867
-
868
-		$l = \OC::$server->get(IFactory::class)->get('files');
869
-		foreach ($mounts as $mount) {
870
-			$sourcePath = $this->getRelativePath($mount->getMountPoint());
871
-			if ($sourcePath) {
872
-				$sourcePath = trim($sourcePath, '/');
873
-			} else {
874
-				$sourcePath = $mount->getMountPoint();
875
-			}
876
-
877
-			if (!$mount instanceof MoveableMount) {
878
-				throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
879
-			}
880
-
881
-			if ($targetIsShared) {
882
-				if ($sourceMount instanceof SharedMount) {
883
-					throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
884
-				} else {
885
-					throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
886
-				}
887
-			}
888
-
889
-			if ($sourceMount !== $targetMount) {
890
-				if ($sourceMount instanceof SharedMount) {
891
-					if ($targetMount instanceof SharedMount) {
892
-						throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
893
-					} else {
894
-						throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
895
-					}
896
-				} else {
897
-					if ($targetMount instanceof SharedMount) {
898
-						throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
899
-					} else {
900
-						throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
901
-					}
902
-				}
903
-			}
904
-		}
905
-	}
906
-
907
-	/**
908
-	 * Copy a file/folder from the source path to target path
909
-	 *
910
-	 * @param string $source source path
911
-	 * @param string $target target path
912
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
913
-	 *
914
-	 * @return bool|mixed
915
-	 */
916
-	public function copy($source, $target, $preserveMtime = false) {
917
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
918
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
919
-		$result = false;
920
-		if (
921
-			Filesystem::isValidPath($target)
922
-			&& Filesystem::isValidPath($source)
923
-			&& !Filesystem::isFileBlacklisted($target)
924
-		) {
925
-			$source = $this->getRelativePath($absolutePath1);
926
-			$target = $this->getRelativePath($absolutePath2);
927
-
928
-			if ($source == null || $target == null) {
929
-				return false;
930
-			}
931
-			$run = true;
932
-
933
-			$this->lockFile($target, ILockingProvider::LOCK_SHARED);
934
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED);
935
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
936
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
-
938
-			try {
939
-				$exists = $this->file_exists($target);
940
-				if ($this->shouldEmitHooks()) {
941
-					\OC_Hook::emit(
942
-						Filesystem::CLASSNAME,
943
-						Filesystem::signal_copy,
944
-						[
945
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
946
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
947
-							Filesystem::signal_param_run => &$run
948
-						]
949
-					);
950
-					$this->emit_file_hooks_pre($exists, $target, $run);
951
-				}
952
-				if ($run) {
953
-					$mount1 = $this->getMount($source);
954
-					$mount2 = $this->getMount($target);
955
-					$storage1 = $mount1->getStorage();
956
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
957
-					$storage2 = $mount2->getStorage();
958
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
959
-
960
-					$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
961
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
962
-
963
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
964
-						if ($storage1) {
965
-							$result = $storage1->copy($internalPath1, $internalPath2);
966
-						} else {
967
-							$result = false;
968
-						}
969
-					} else {
970
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
971
-					}
972
-
973
-					if ($result) {
974
-						$this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
975
-					}
976
-
977
-					$this->changeLock($target, ILockingProvider::LOCK_SHARED);
978
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
979
-
980
-					if ($this->shouldEmitHooks() && $result !== false) {
981
-						\OC_Hook::emit(
982
-							Filesystem::CLASSNAME,
983
-							Filesystem::signal_post_copy,
984
-							[
985
-								Filesystem::signal_param_oldpath => $this->getHookPath($source),
986
-								Filesystem::signal_param_newpath => $this->getHookPath($target)
987
-							]
988
-						);
989
-						$this->emit_file_hooks_post($exists, $target);
990
-					}
991
-				}
992
-			} catch (\Exception $e) {
993
-				$this->unlockFile($target, $lockTypePath2);
994
-				$this->unlockFile($source, $lockTypePath1);
995
-				throw $e;
996
-			}
997
-
998
-			$this->unlockFile($target, $lockTypePath2);
999
-			$this->unlockFile($source, $lockTypePath1);
1000
-		}
1001
-		return $result;
1002
-	}
1003
-
1004
-	/**
1005
-	 * @param string $path
1006
-	 * @param string $mode 'r' or 'w'
1007
-	 * @return resource|false
1008
-	 * @throws LockedException
1009
-	 */
1010
-	public function fopen($path, $mode) {
1011
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1012
-		$hooks = [];
1013
-		switch ($mode) {
1014
-			case 'r':
1015
-				$hooks[] = 'read';
1016
-				break;
1017
-			case 'r+':
1018
-			case 'w+':
1019
-			case 'x+':
1020
-			case 'a+':
1021
-				$hooks[] = 'read';
1022
-				$hooks[] = 'write';
1023
-				break;
1024
-			case 'w':
1025
-			case 'x':
1026
-			case 'a':
1027
-				$hooks[] = 'write';
1028
-				break;
1029
-			default:
1030
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1031
-		}
1032
-
1033
-		if ($mode !== 'r' && $mode !== 'w') {
1034
-			$this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1035
-		}
1036
-
1037
-		$handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1038
-		if (!is_resource($handle) && $mode === 'r') {
1039
-			// trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1040
-			$mount = $this->getMount($path);
1041
-			$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1042
-			$storage = $mount->getStorage();
1043
-			if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1044
-				$this->writeUpdate($storage, $internalPath);
1045
-			}
1046
-		}
1047
-		return $handle;
1048
-	}
1049
-
1050
-	/**
1051
-	 * @param string $path
1052
-	 * @throws InvalidPathException
1053
-	 */
1054
-	public function toTmpFile($path): string|false {
1055
-		$this->assertPathLength($path);
1056
-		if (Filesystem::isValidPath($path)) {
1057
-			$source = $this->fopen($path, 'r');
1058
-			if ($source) {
1059
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1060
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1061
-				file_put_contents($tmpFile, $source);
1062
-				return $tmpFile;
1063
-			} else {
1064
-				return false;
1065
-			}
1066
-		} else {
1067
-			return false;
1068
-		}
1069
-	}
1070
-
1071
-	/**
1072
-	 * @param string $tmpFile
1073
-	 * @param string $path
1074
-	 * @return bool|mixed
1075
-	 * @throws InvalidPathException
1076
-	 */
1077
-	public function fromTmpFile($tmpFile, $path) {
1078
-		$this->assertPathLength($path);
1079
-		if (Filesystem::isValidPath($path)) {
1080
-			// Get directory that the file is going into
1081
-			$filePath = dirname($path);
1082
-
1083
-			// Create the directories if any
1084
-			if (!$this->file_exists($filePath)) {
1085
-				$result = $this->createParentDirectories($filePath);
1086
-				if ($result === false) {
1087
-					return false;
1088
-				}
1089
-			}
1090
-
1091
-			$source = fopen($tmpFile, 'r');
1092
-			if ($source) {
1093
-				$result = $this->file_put_contents($path, $source);
1094
-				/**
1095
-				 * $this->file_put_contents() might have already closed
1096
-				 * the resource, so we check it, before trying to close it
1097
-				 * to avoid messages in the error log.
1098
-				 * @psalm-suppress RedundantCondition false-positive
1099
-				 */
1100
-				if (is_resource($source)) {
1101
-					fclose($source);
1102
-				}
1103
-				unlink($tmpFile);
1104
-				return $result;
1105
-			} else {
1106
-				return false;
1107
-			}
1108
-		} else {
1109
-			return false;
1110
-		}
1111
-	}
1112
-
1113
-
1114
-	/**
1115
-	 * @param string $path
1116
-	 * @return mixed
1117
-	 * @throws InvalidPathException
1118
-	 */
1119
-	public function getMimeType($path) {
1120
-		$this->assertPathLength($path);
1121
-		return $this->basicOperation('getMimeType', $path);
1122
-	}
1123
-
1124
-	/**
1125
-	 * @param string $type
1126
-	 * @param string $path
1127
-	 * @param bool $raw
1128
-	 */
1129
-	public function hash($type, $path, $raw = false): string|bool {
1130
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1131
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1132
-		if (Filesystem::isValidPath($path)) {
1133
-			$path = $this->getRelativePath($absolutePath);
1134
-			if ($path == null) {
1135
-				return false;
1136
-			}
1137
-			if ($this->shouldEmitHooks($path)) {
1138
-				\OC_Hook::emit(
1139
-					Filesystem::CLASSNAME,
1140
-					Filesystem::signal_read,
1141
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1142
-				);
1143
-			}
1144
-			/** @var Storage|null $storage */
1145
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1146
-			if ($storage) {
1147
-				return $storage->hash($type, $internalPath, $raw);
1148
-			}
1149
-		}
1150
-		return false;
1151
-	}
1152
-
1153
-	/**
1154
-	 * @param string $path
1155
-	 * @return mixed
1156
-	 * @throws InvalidPathException
1157
-	 */
1158
-	public function free_space($path = '/') {
1159
-		$this->assertPathLength($path);
1160
-		$result = $this->basicOperation('free_space', $path);
1161
-		if ($result === null) {
1162
-			throw new InvalidPathException();
1163
-		}
1164
-		return $result;
1165
-	}
1166
-
1167
-	/**
1168
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1169
-	 *
1170
-	 * @param mixed $extraParam (optional)
1171
-	 * @return mixed
1172
-	 * @throws LockedException
1173
-	 *
1174
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1175
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1176
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1177
-	 */
1178
-	private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1179
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1180
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1181
-		if (Filesystem::isValidPath($path)
1182
-			&& !Filesystem::isFileBlacklisted($path)
1183
-		) {
1184
-			$path = $this->getRelativePath($absolutePath);
1185
-			if ($path == null) {
1186
-				return false;
1187
-			}
1188
-
1189
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1190
-				// always a shared lock during pre-hooks so the hook can read the file
1191
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1192
-			}
1193
-
1194
-			$run = $this->runHooks($hooks, $path);
1195
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1196
-			if ($run && $storage) {
1197
-				/** @var Storage $storage */
1198
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1199
-					try {
1200
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1201
-					} catch (LockedException $e) {
1202
-						// release the shared lock we acquired before quitting
1203
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1204
-						throw $e;
1205
-					}
1206
-				}
1207
-				try {
1208
-					if (!is_null($extraParam)) {
1209
-						$result = $storage->$operation($internalPath, $extraParam);
1210
-					} else {
1211
-						$result = $storage->$operation($internalPath);
1212
-					}
1213
-				} catch (\Exception $e) {
1214
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1215
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1216
-					} elseif (in_array('read', $hooks)) {
1217
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1218
-					}
1219
-					throw $e;
1220
-				}
1221
-
1222
-				if ($result !== false && in_array('delete', $hooks)) {
1223
-					$this->removeUpdate($storage, $internalPath);
1224
-				}
1225
-				if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1226
-					$isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1227
-					$sizeDifference = $operation === 'mkdir' ? 0 : $result;
1228
-					$this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1229
-				}
1230
-				if ($result !== false && in_array('touch', $hooks)) {
1231
-					$this->writeUpdate($storage, $internalPath, $extraParam, 0);
1232
-				}
1233
-
1234
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1235
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1236
-				}
1237
-
1238
-				$unlockLater = false;
1239
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1240
-					$unlockLater = true;
1241
-					// make sure our unlocking callback will still be called if connection is aborted
1242
-					ignore_user_abort(true);
1243
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1244
-						if (in_array('write', $hooks)) {
1245
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1246
-						} elseif (in_array('read', $hooks)) {
1247
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1248
-						}
1249
-					});
1250
-				}
1251
-
1252
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1253
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1254
-						$this->runHooks($hooks, $path, true);
1255
-					}
1256
-				}
1257
-
1258
-				if (!$unlockLater
1259
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1260
-				) {
1261
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1262
-				}
1263
-				return $result;
1264
-			} else {
1265
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1266
-			}
1267
-		}
1268
-		return null;
1269
-	}
1270
-
1271
-	/**
1272
-	 * get the path relative to the default root for hook usage
1273
-	 *
1274
-	 * @param string $path
1275
-	 * @return ?string
1276
-	 */
1277
-	private function getHookPath($path): ?string {
1278
-		$view = Filesystem::getView();
1279
-		if (!$view) {
1280
-			return $path;
1281
-		}
1282
-		return $view->getRelativePath($this->getAbsolutePath($path));
1283
-	}
1284
-
1285
-	private function shouldEmitHooks(string $path = ''): bool {
1286
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1287
-			return false;
1288
-		}
1289
-		if (!Filesystem::$loaded) {
1290
-			return false;
1291
-		}
1292
-		$defaultRoot = Filesystem::getRoot();
1293
-		if ($defaultRoot === null) {
1294
-			return false;
1295
-		}
1296
-		if ($this->fakeRoot === $defaultRoot) {
1297
-			return true;
1298
-		}
1299
-		$fullPath = $this->getAbsolutePath($path);
1300
-
1301
-		if ($fullPath === $defaultRoot) {
1302
-			return true;
1303
-		}
1304
-
1305
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1306
-	}
1307
-
1308
-	/**
1309
-	 * @param string[] $hooks
1310
-	 * @param string $path
1311
-	 * @param bool $post
1312
-	 * @return bool
1313
-	 */
1314
-	private function runHooks($hooks, $path, $post = false) {
1315
-		$relativePath = $path;
1316
-		$path = $this->getHookPath($path);
1317
-		$prefix = $post ? 'post_' : '';
1318
-		$run = true;
1319
-		if ($this->shouldEmitHooks($relativePath)) {
1320
-			foreach ($hooks as $hook) {
1321
-				if ($hook != 'read') {
1322
-					\OC_Hook::emit(
1323
-						Filesystem::CLASSNAME,
1324
-						$prefix . $hook,
1325
-						[
1326
-							Filesystem::signal_param_run => &$run,
1327
-							Filesystem::signal_param_path => $path
1328
-						]
1329
-					);
1330
-				} elseif (!$post) {
1331
-					\OC_Hook::emit(
1332
-						Filesystem::CLASSNAME,
1333
-						$prefix . $hook,
1334
-						[
1335
-							Filesystem::signal_param_path => $path
1336
-						]
1337
-					);
1338
-				}
1339
-			}
1340
-		}
1341
-		return $run;
1342
-	}
1343
-
1344
-	/**
1345
-	 * check if a file or folder has been updated since $time
1346
-	 *
1347
-	 * @param string $path
1348
-	 * @param int $time
1349
-	 * @return bool
1350
-	 */
1351
-	public function hasUpdated($path, $time) {
1352
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1353
-	}
1354
-
1355
-	/**
1356
-	 * @param string $ownerId
1357
-	 * @return IUser
1358
-	 */
1359
-	private function getUserObjectForOwner(string $ownerId) {
1360
-		return new LazyUser($ownerId, $this->userManager);
1361
-	}
1362
-
1363
-	/**
1364
-	 * Get file info from cache
1365
-	 *
1366
-	 * If the file is not in cached it will be scanned
1367
-	 * If the file has changed on storage the cache will be updated
1368
-	 *
1369
-	 * @param Storage $storage
1370
-	 * @param string $internalPath
1371
-	 * @param string $relativePath
1372
-	 * @return ICacheEntry|bool
1373
-	 */
1374
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1375
-		$cache = $storage->getCache($internalPath);
1376
-		$data = $cache->get($internalPath);
1377
-		$watcher = $storage->getWatcher($internalPath);
1378
-
1379
-		try {
1380
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1381
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1382
-				if (!$storage->file_exists($internalPath)) {
1383
-					return false;
1384
-				}
1385
-				// don't need to get a lock here since the scanner does it's own locking
1386
-				$scanner = $storage->getScanner($internalPath);
1387
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1388
-				$data = $cache->get($internalPath);
1389
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1390
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1391
-				$watcher->update($internalPath, $data);
1392
-				$storage->getPropagator()->propagateChange($internalPath, time());
1393
-				$data = $cache->get($internalPath);
1394
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1395
-			}
1396
-		} catch (LockedException $e) {
1397
-			// if the file is locked we just use the old cache info
1398
-		}
1399
-
1400
-		return $data;
1401
-	}
1402
-
1403
-	/**
1404
-	 * get the filesystem info
1405
-	 *
1406
-	 * @param string $path
1407
-	 * @param bool|string $includeMountPoints true to add mountpoint sizes,
1408
-	 *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1409
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1410
-	 */
1411
-	public function getFileInfo($path, $includeMountPoints = true) {
1412
-		$this->assertPathLength($path);
1413
-		if (!Filesystem::isValidPath($path)) {
1414
-			return false;
1415
-		}
1416
-		$relativePath = $path;
1417
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1418
-
1419
-		$mount = Filesystem::getMountManager()->find($path);
1420
-		$storage = $mount->getStorage();
1421
-		$internalPath = $mount->getInternalPath($path);
1422
-		if ($storage) {
1423
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1424
-
1425
-			if (!$data instanceof ICacheEntry) {
1426
-				if (Cache\Scanner::isPartialFile($relativePath)) {
1427
-					return $this->getPartFileInfo($relativePath);
1428
-				}
1429
-
1430
-				return false;
1431
-			}
1432
-
1433
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1434
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1435
-			}
1436
-			if ($internalPath === '' && $data['name']) {
1437
-				$data['name'] = basename($path);
1438
-			}
1439
-
1440
-			$ownerId = $storage->getOwner($internalPath);
1441
-			$owner = null;
1442
-			if ($ownerId !== false) {
1443
-				// ownerId might be null if files are accessed with an access token without file system access
1444
-				$owner = $this->getUserObjectForOwner($ownerId);
1445
-			}
1446
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1447
-
1448
-			if (isset($data['fileid'])) {
1449
-				if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1450
-					//add the sizes of other mount points to the folder
1451
-					$extOnly = ($includeMountPoints === 'ext');
1452
-					$this->addSubMounts($info, $extOnly);
1453
-				}
1454
-			}
1455
-
1456
-			return $info;
1457
-		} else {
1458
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1459
-		}
1460
-
1461
-		return false;
1462
-	}
1463
-
1464
-	/**
1465
-	 * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1466
-	 */
1467
-	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1468
-		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1469
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1470
-			return !($extOnly && $mount instanceof SharedMount);
1471
-		}));
1472
-	}
1473
-
1474
-	/**
1475
-	 * get the content of a directory
1476
-	 *
1477
-	 * @param string $directory path under datadirectory
1478
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1479
-	 * @return FileInfo[]
1480
-	 */
1481
-	public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1482
-		$this->assertPathLength($directory);
1483
-		if (!Filesystem::isValidPath($directory)) {
1484
-			return [];
1485
-		}
1486
-
1487
-		$path = $this->getAbsolutePath($directory);
1488
-		$path = Filesystem::normalizePath($path);
1489
-		$mount = $this->getMount($directory);
1490
-		$storage = $mount->getStorage();
1491
-		$internalPath = $mount->getInternalPath($path);
1492
-		if (!$storage) {
1493
-			return [];
1494
-		}
1495
-
1496
-		$cache = $storage->getCache($internalPath);
1497
-		$user = \OC_User::getUser();
1498
-
1499
-		if (!$directoryInfo) {
1500
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1501
-			if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1502
-				return [];
1503
-			}
1504
-		} else {
1505
-			$data = $directoryInfo;
1506
-		}
1507
-
1508
-		if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1509
-			return [];
1510
-		}
1511
-
1512
-		$folderId = $data->getId();
1513
-		$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1514
-
1515
-		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1516
-
1517
-		$fileNames = array_map(function (ICacheEntry $content) {
1518
-			return $content->getName();
1519
-		}, $contents);
1520
-		/**
1521
-		 * @var \OC\Files\FileInfo[] $fileInfos
1522
-		 */
1523
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1524
-			if ($sharingDisabled) {
1525
-				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1526
-			}
1527
-			$ownerId = $storage->getOwner($content['path']);
1528
-			if ($ownerId !== false) {
1529
-				$owner = $this->getUserObjectForOwner($ownerId);
1530
-			} else {
1531
-				$owner = null;
1532
-			}
1533
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1534
-		}, $contents);
1535
-		$files = array_combine($fileNames, $fileInfos);
1536
-
1537
-		//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1538
-		$mounts = Filesystem::getMountManager()->findIn($path);
1539
-
1540
-		// make sure nested mounts are sorted after their parent mounts
1541
-		// otherwise doesn't propagate the etag across storage boundaries correctly
1542
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1543
-			return $a->getMountPoint() <=> $b->getMountPoint();
1544
-		});
1545
-
1546
-		$dirLength = strlen($path);
1547
-		foreach ($mounts as $mount) {
1548
-			$mountPoint = $mount->getMountPoint();
1549
-			$subStorage = $mount->getStorage();
1550
-			if ($subStorage) {
1551
-				$subCache = $subStorage->getCache('');
1552
-
1553
-				$rootEntry = $subCache->get('');
1554
-				if (!$rootEntry) {
1555
-					$subScanner = $subStorage->getScanner();
1556
-					try {
1557
-						$subScanner->scanFile('');
1558
-					} catch (\OCP\Files\StorageNotAvailableException $e) {
1559
-						continue;
1560
-					} catch (\OCP\Files\StorageInvalidException $e) {
1561
-						continue;
1562
-					} catch (\Exception $e) {
1563
-						// sometimes when the storage is not available it can be any exception
1564
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1565
-							'exception' => $e,
1566
-							'app' => 'core',
1567
-						]);
1568
-						continue;
1569
-					}
1570
-					$rootEntry = $subCache->get('');
1571
-				}
1572
-
1573
-				if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1574
-					$relativePath = trim(substr($mountPoint, $dirLength), '/');
1575
-					if ($pos = strpos($relativePath, '/')) {
1576
-						//mountpoint inside subfolder add size to the correct folder
1577
-						$entryName = substr($relativePath, 0, $pos);
1578
-
1579
-						// Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1580
-						if (!isset($files[$entryName])) {
1581
-							try {
1582
-								[$storage, ] = $this->resolvePath($path . '/' . $entryName);
1583
-								// make sure we can create the mountpoint folder, even if the user has a quota of 0
1584
-								if ($storage->instanceOfStorage(Quota::class)) {
1585
-									$storage->enableQuota(false);
1586
-								}
1587
-
1588
-								if ($this->mkdir($path . '/' . $entryName) !== false) {
1589
-									$info = $this->getFileInfo($path . '/' . $entryName);
1590
-									if ($info !== false) {
1591
-										$files[$entryName] = $info;
1592
-									}
1593
-								}
1594
-
1595
-								if ($storage->instanceOfStorage(Quota::class)) {
1596
-									$storage->enableQuota(true);
1597
-								}
1598
-							} catch (\Exception $e) {
1599
-								// Creating the parent folder might not be possible, for example due to a lack of permissions.
1600
-								$this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1601
-							}
1602
-						}
1603
-
1604
-						if (isset($files[$entryName])) {
1605
-							$files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1606
-						}
1607
-					} else { //mountpoint in this folder, add an entry for it
1608
-						$rootEntry['name'] = $relativePath;
1609
-						$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1610
-						$permissions = $rootEntry['permissions'];
1611
-						// do not allow renaming/deleting the mount point if they are not shared files/folders
1612
-						// for shared files/folders we use the permissions given by the owner
1613
-						if ($mount instanceof MoveableMount) {
1614
-							$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1615
-						} else {
1616
-							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1617
-						}
1618
-
1619
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1620
-
1621
-						// if sharing was disabled for the user we remove the share permissions
1622
-						if ($sharingDisabled) {
1623
-							$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1624
-						}
1625
-
1626
-						$ownerId = $subStorage->getOwner('');
1627
-						if ($ownerId !== false) {
1628
-							$owner = $this->getUserObjectForOwner($ownerId);
1629
-						} else {
1630
-							$owner = null;
1631
-						}
1632
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1633
-					}
1634
-				}
1635
-			}
1636
-		}
1637
-
1638
-		if ($mimetype_filter) {
1639
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1640
-				if (strpos($mimetype_filter, '/')) {
1641
-					return $file->getMimetype() === $mimetype_filter;
1642
-				} else {
1643
-					return $file->getMimePart() === $mimetype_filter;
1644
-				}
1645
-			});
1646
-		}
1647
-
1648
-		return array_values($files);
1649
-	}
1650
-
1651
-	/**
1652
-	 * change file metadata
1653
-	 *
1654
-	 * @param string $path
1655
-	 * @param array|\OCP\Files\FileInfo $data
1656
-	 * @return int
1657
-	 *
1658
-	 * returns the fileid of the updated file
1659
-	 */
1660
-	public function putFileInfo($path, $data) {
1661
-		$this->assertPathLength($path);
1662
-		if ($data instanceof FileInfo) {
1663
-			$data = $data->getData();
1664
-		}
1665
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1666
-		/**
1667
-		 * @var Storage $storage
1668
-		 * @var string $internalPath
1669
-		 */
1670
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1671
-		if ($storage) {
1672
-			$cache = $storage->getCache($path);
1673
-
1674
-			if (!$cache->inCache($internalPath)) {
1675
-				$scanner = $storage->getScanner($internalPath);
1676
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1677
-			}
1678
-
1679
-			return $cache->put($internalPath, $data);
1680
-		} else {
1681
-			return -1;
1682
-		}
1683
-	}
1684
-
1685
-	/**
1686
-	 * search for files with the name matching $query
1687
-	 *
1688
-	 * @param string $query
1689
-	 * @return FileInfo[]
1690
-	 */
1691
-	public function search($query) {
1692
-		return $this->searchCommon('search', ['%' . $query . '%']);
1693
-	}
1694
-
1695
-	/**
1696
-	 * search for files with the name matching $query
1697
-	 *
1698
-	 * @param string $query
1699
-	 * @return FileInfo[]
1700
-	 */
1701
-	public function searchRaw($query) {
1702
-		return $this->searchCommon('search', [$query]);
1703
-	}
1704
-
1705
-	/**
1706
-	 * search for files by mimetype
1707
-	 *
1708
-	 * @param string $mimetype
1709
-	 * @return FileInfo[]
1710
-	 */
1711
-	public function searchByMime($mimetype) {
1712
-		return $this->searchCommon('searchByMime', [$mimetype]);
1713
-	}
1714
-
1715
-	/**
1716
-	 * search for files by tag
1717
-	 *
1718
-	 * @param string|int $tag name or tag id
1719
-	 * @param string $userId owner of the tags
1720
-	 * @return FileInfo[]
1721
-	 */
1722
-	public function searchByTag($tag, $userId) {
1723
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1724
-	}
1725
-
1726
-	/**
1727
-	 * @param string $method cache method
1728
-	 * @param array $args
1729
-	 * @return FileInfo[]
1730
-	 */
1731
-	private function searchCommon($method, $args) {
1732
-		$files = [];
1733
-		$rootLength = strlen($this->fakeRoot);
1734
-
1735
-		$mount = $this->getMount('');
1736
-		$mountPoint = $mount->getMountPoint();
1737
-		$storage = $mount->getStorage();
1738
-		$userManager = \OC::$server->getUserManager();
1739
-		if ($storage) {
1740
-			$cache = $storage->getCache('');
1741
-
1742
-			$results = call_user_func_array([$cache, $method], $args);
1743
-			foreach ($results as $result) {
1744
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1745
-					$internalPath = $result['path'];
1746
-					$path = $mountPoint . $result['path'];
1747
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1748
-					$ownerId = $storage->getOwner($internalPath);
1749
-					if ($ownerId !== false) {
1750
-						$owner = $userManager->get($ownerId);
1751
-					} else {
1752
-						$owner = null;
1753
-					}
1754
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1755
-				}
1756
-			}
1757
-
1758
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1759
-			foreach ($mounts as $mount) {
1760
-				$mountPoint = $mount->getMountPoint();
1761
-				$storage = $mount->getStorage();
1762
-				if ($storage) {
1763
-					$cache = $storage->getCache('');
1764
-
1765
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1766
-					$results = call_user_func_array([$cache, $method], $args);
1767
-					if ($results) {
1768
-						foreach ($results as $result) {
1769
-							$internalPath = $result['path'];
1770
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1771
-							$path = rtrim($mountPoint . $internalPath, '/');
1772
-							$ownerId = $storage->getOwner($internalPath);
1773
-							if ($ownerId !== false) {
1774
-								$owner = $userManager->get($ownerId);
1775
-							} else {
1776
-								$owner = null;
1777
-							}
1778
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1779
-						}
1780
-					}
1781
-				}
1782
-			}
1783
-		}
1784
-		return $files;
1785
-	}
1786
-
1787
-	/**
1788
-	 * Get the owner for a file or folder
1789
-	 *
1790
-	 * @throws NotFoundException
1791
-	 */
1792
-	public function getOwner(string $path): string {
1793
-		$info = $this->getFileInfo($path);
1794
-		if (!$info) {
1795
-			throw new NotFoundException($path . ' not found while trying to get owner');
1796
-		}
1797
-
1798
-		if ($info->getOwner() === null) {
1799
-			throw new NotFoundException($path . ' has no owner');
1800
-		}
1801
-
1802
-		return $info->getOwner()->getUID();
1803
-	}
1804
-
1805
-	/**
1806
-	 * get the ETag for a file or folder
1807
-	 *
1808
-	 * @param string $path
1809
-	 * @return string|false
1810
-	 */
1811
-	public function getETag($path) {
1812
-		[$storage, $internalPath] = $this->resolvePath($path);
1813
-		if ($storage) {
1814
-			return $storage->getETag($internalPath);
1815
-		} else {
1816
-			return false;
1817
-		}
1818
-	}
1819
-
1820
-	/**
1821
-	 * Get the path of a file by id, relative to the view
1822
-	 *
1823
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1824
-	 *
1825
-	 * @param int $id
1826
-	 * @param int|null $storageId
1827
-	 * @return string
1828
-	 * @throws NotFoundException
1829
-	 */
1830
-	public function getPath($id, ?int $storageId = null) {
1831
-		$id = (int)$id;
1832
-		$manager = Filesystem::getMountManager();
1833
-		$mounts = $manager->findIn($this->fakeRoot);
1834
-		$mounts[] = $manager->find($this->fakeRoot);
1835
-		$mounts = array_filter($mounts);
1836
-		// reverse the array, so we start with the storage this view is in
1837
-		// which is the most likely to contain the file we're looking for
1838
-		$mounts = array_reverse($mounts);
1839
-
1840
-		// put non-shared mounts in front of the shared mount
1841
-		// this prevents unneeded recursion into shares
1842
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1843
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1844
-		});
1845
-
1846
-		if (!is_null($storageId)) {
1847
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1848
-				return $mount->getNumericStorageId() === $storageId;
1849
-			});
1850
-		}
1851
-
1852
-		foreach ($mounts as $mount) {
1853
-			/**
1854
-			 * @var \OC\Files\Mount\MountPoint $mount
1855
-			 */
1856
-			if ($mount->getStorage()) {
1857
-				$cache = $mount->getStorage()->getCache();
1858
-				$internalPath = $cache->getPathById($id);
1859
-				if (is_string($internalPath)) {
1860
-					$fullPath = $mount->getMountPoint() . $internalPath;
1861
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1862
-						return $path;
1863
-					}
1864
-				}
1865
-			}
1866
-		}
1867
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1868
-	}
1869
-
1870
-	/**
1871
-	 * @param string $path
1872
-	 * @throws InvalidPathException
1873
-	 */
1874
-	private function assertPathLength($path): void {
1875
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1876
-		// Check for the string length - performed using isset() instead of strlen()
1877
-		// because isset() is about 5x-40x faster.
1878
-		if (isset($path[$maxLen])) {
1879
-			$pathLen = strlen($path);
1880
-			throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1881
-		}
1882
-	}
1883
-
1884
-	/**
1885
-	 * check if it is allowed to move a mount point to a given target.
1886
-	 * It is not allowed to move a mount point into a different mount point or
1887
-	 * into an already shared folder
1888
-	 */
1889
-	private function targetIsNotShared(string $user, string $targetPath): bool {
1890
-		$providers = [
1891
-			IShare::TYPE_USER,
1892
-			IShare::TYPE_GROUP,
1893
-			IShare::TYPE_EMAIL,
1894
-			IShare::TYPE_CIRCLE,
1895
-			IShare::TYPE_ROOM,
1896
-			IShare::TYPE_DECK,
1897
-			IShare::TYPE_SCIENCEMESH
1898
-		];
1899
-		$shareManager = Server::get(IManager::class);
1900
-		/** @var IShare[] $shares */
1901
-		$shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1902
-			return $shareManager->getSharesBy($user, $type);
1903
-		}, $providers));
1904
-
1905
-		foreach ($shares as $share) {
1906
-			$sharedPath = $share->getNode()->getPath();
1907
-			if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1908
-				$this->logger->debug(
1909
-					'It is not allowed to move one mount point into a shared folder',
1910
-					['app' => 'files']);
1911
-				return false;
1912
-			}
1913
-		}
1914
-
1915
-		return true;
1916
-	}
1917
-
1918
-	/**
1919
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1920
-	 */
1921
-	private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1922
-		$mount = $this->getMount($path);
1923
-		$storage = $mount->getStorage();
1924
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1925
-		$ownerId = $storage->getOwner($internalPath);
1926
-		if ($ownerId !== false) {
1927
-			$owner = Server::get(IUserManager::class)->get($ownerId);
1928
-		} else {
1929
-			$owner = null;
1930
-		}
1931
-		return new FileInfo(
1932
-			$this->getAbsolutePath($path),
1933
-			$storage,
1934
-			$internalPath,
1935
-			[
1936
-				'fileid' => null,
1937
-				'mimetype' => $storage->getMimeType($internalPath),
1938
-				'name' => basename($path),
1939
-				'etag' => null,
1940
-				'size' => $storage->filesize($internalPath),
1941
-				'mtime' => $storage->filemtime($internalPath),
1942
-				'encrypted' => false,
1943
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1944
-			],
1945
-			$mount,
1946
-			$owner
1947
-		);
1948
-	}
1949
-
1950
-	/**
1951
-	 * @param string $path
1952
-	 * @param string $fileName
1953
-	 * @param bool $readonly Check only if the path is allowed for read-only access
1954
-	 * @throws InvalidPathException
1955
-	 */
1956
-	public function verifyPath($path, $fileName, $readonly = false): void {
1957
-		// All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1958
-		if (!Filesystem::isValidPath($path ?: '/')) {
1959
-			$l = \OCP\Util::getL10N('lib');
1960
-			throw new InvalidPathException($l->t('Path contains invalid segments'));
1961
-		}
1962
-
1963
-		// Short cut for read-only validation
1964
-		if ($readonly) {
1965
-			$validator = Server::get(FilenameValidator::class);
1966
-			if ($validator->isForbidden($fileName)) {
1967
-				$l = \OCP\Util::getL10N('lib');
1968
-				throw new InvalidPathException($l->t('Filename is a reserved word'));
1969
-			}
1970
-			return;
1971
-		}
1972
-
1973
-		try {
1974
-			/** @type \OCP\Files\Storage $storage */
1975
-			[$storage, $internalPath] = $this->resolvePath($path);
1976
-			$storage->verifyPath($internalPath, $fileName);
1977
-		} catch (ReservedWordException $ex) {
1978
-			$l = \OCP\Util::getL10N('lib');
1979
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1980
-		} catch (InvalidCharacterInPathException $ex) {
1981
-			$l = \OCP\Util::getL10N('lib');
1982
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1983
-		} catch (FileNameTooLongException $ex) {
1984
-			$l = \OCP\Util::getL10N('lib');
1985
-			throw new InvalidPathException($l->t('Filename is too long'));
1986
-		} catch (InvalidDirectoryException $ex) {
1987
-			$l = \OCP\Util::getL10N('lib');
1988
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1989
-		} catch (EmptyFileNameException $ex) {
1990
-			$l = \OCP\Util::getL10N('lib');
1991
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1992
-		}
1993
-	}
1994
-
1995
-	/**
1996
-	 * get all parent folders of $path
1997
-	 *
1998
-	 * @param string $path
1999
-	 * @return string[]
2000
-	 */
2001
-	private function getParents($path) {
2002
-		$path = trim($path, '/');
2003
-		if (!$path) {
2004
-			return [];
2005
-		}
2006
-
2007
-		$parts = explode('/', $path);
2008
-
2009
-		// remove the single file
2010
-		array_pop($parts);
2011
-		$result = ['/'];
2012
-		$resultPath = '';
2013
-		foreach ($parts as $part) {
2014
-			if ($part) {
2015
-				$resultPath .= '/' . $part;
2016
-				$result[] = $resultPath;
2017
-			}
2018
-		}
2019
-		return $result;
2020
-	}
2021
-
2022
-	/**
2023
-	 * Returns the mount point for which to lock
2024
-	 *
2025
-	 * @param string $absolutePath absolute path
2026
-	 * @param bool $useParentMount true to return parent mount instead of whatever
2027
-	 *                             is mounted directly on the given path, false otherwise
2028
-	 * @return IMountPoint mount point for which to apply locks
2029
-	 */
2030
-	private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2031
-		$mount = Filesystem::getMountManager()->find($absolutePath);
2032
-
2033
-		if ($useParentMount) {
2034
-			// find out if something is mounted directly on the path
2035
-			$internalPath = $mount->getInternalPath($absolutePath);
2036
-			if ($internalPath === '') {
2037
-				// resolve the parent mount instead
2038
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2039
-			}
2040
-		}
2041
-
2042
-		return $mount;
2043
-	}
2044
-
2045
-	/**
2046
-	 * Lock the given path
2047
-	 *
2048
-	 * @param string $path the path of the file to lock, relative to the view
2049
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2050
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2051
-	 *
2052
-	 * @return bool False if the path is excluded from locking, true otherwise
2053
-	 * @throws LockedException if the path is already locked
2054
-	 */
2055
-	private function lockPath($path, $type, $lockMountPoint = false) {
2056
-		$absolutePath = $this->getAbsolutePath($path);
2057
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2058
-		if (!$this->shouldLockFile($absolutePath)) {
2059
-			return false;
2060
-		}
2061
-
2062
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2063
-		try {
2064
-			$storage = $mount->getStorage();
2065
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2066
-				$storage->acquireLock(
2067
-					$mount->getInternalPath($absolutePath),
2068
-					$type,
2069
-					$this->lockingProvider
2070
-				);
2071
-			}
2072
-		} catch (LockedException $e) {
2073
-			// rethrow with the human-readable path
2074
-			throw new LockedException(
2075
-				$path,
2076
-				$e,
2077
-				$e->getExistingLock()
2078
-			);
2079
-		}
2080
-
2081
-		return true;
2082
-	}
2083
-
2084
-	/**
2085
-	 * Change the lock type
2086
-	 *
2087
-	 * @param string $path the path of the file to lock, relative to the view
2088
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2089
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2090
-	 *
2091
-	 * @return bool False if the path is excluded from locking, true otherwise
2092
-	 * @throws LockedException if the path is already locked
2093
-	 */
2094
-	public function changeLock($path, $type, $lockMountPoint = false) {
2095
-		$path = Filesystem::normalizePath($path);
2096
-		$absolutePath = $this->getAbsolutePath($path);
2097
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2098
-		if (!$this->shouldLockFile($absolutePath)) {
2099
-			return false;
2100
-		}
2101
-
2102
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2103
-		try {
2104
-			$storage = $mount->getStorage();
2105
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2106
-				$storage->changeLock(
2107
-					$mount->getInternalPath($absolutePath),
2108
-					$type,
2109
-					$this->lockingProvider
2110
-				);
2111
-			}
2112
-		} catch (LockedException $e) {
2113
-			// rethrow with the a human-readable path
2114
-			throw new LockedException(
2115
-				$path,
2116
-				$e,
2117
-				$e->getExistingLock()
2118
-			);
2119
-		}
2120
-
2121
-		return true;
2122
-	}
2123
-
2124
-	/**
2125
-	 * Unlock the given path
2126
-	 *
2127
-	 * @param string $path the path of the file to unlock, relative to the view
2128
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2129
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2130
-	 *
2131
-	 * @return bool False if the path is excluded from locking, true otherwise
2132
-	 * @throws LockedException
2133
-	 */
2134
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2135
-		$absolutePath = $this->getAbsolutePath($path);
2136
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2137
-		if (!$this->shouldLockFile($absolutePath)) {
2138
-			return false;
2139
-		}
2140
-
2141
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2142
-		$storage = $mount->getStorage();
2143
-		if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2144
-			$storage->releaseLock(
2145
-				$mount->getInternalPath($absolutePath),
2146
-				$type,
2147
-				$this->lockingProvider
2148
-			);
2149
-		}
2150
-
2151
-		return true;
2152
-	}
2153
-
2154
-	/**
2155
-	 * Lock a path and all its parents up to the root of the view
2156
-	 *
2157
-	 * @param string $path the path of the file to lock relative to the view
2158
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2159
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2160
-	 *
2161
-	 * @return bool False if the path is excluded from locking, true otherwise
2162
-	 * @throws LockedException
2163
-	 */
2164
-	public function lockFile($path, $type, $lockMountPoint = false) {
2165
-		$absolutePath = $this->getAbsolutePath($path);
2166
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2167
-		if (!$this->shouldLockFile($absolutePath)) {
2168
-			return false;
2169
-		}
2170
-
2171
-		$this->lockPath($path, $type, $lockMountPoint);
2172
-
2173
-		$parents = $this->getParents($path);
2174
-		foreach ($parents as $parent) {
2175
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2176
-		}
2177
-
2178
-		return true;
2179
-	}
2180
-
2181
-	/**
2182
-	 * Unlock a path and all its parents up to the root of the view
2183
-	 *
2184
-	 * @param string $path the path of the file to lock relative to the view
2185
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2186
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2187
-	 *
2188
-	 * @return bool False if the path is excluded from locking, true otherwise
2189
-	 * @throws LockedException
2190
-	 */
2191
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2192
-		$absolutePath = $this->getAbsolutePath($path);
2193
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2194
-		if (!$this->shouldLockFile($absolutePath)) {
2195
-			return false;
2196
-		}
2197
-
2198
-		$this->unlockPath($path, $type, $lockMountPoint);
2199
-
2200
-		$parents = $this->getParents($path);
2201
-		foreach ($parents as $parent) {
2202
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2203
-		}
2204
-
2205
-		return true;
2206
-	}
2207
-
2208
-	/**
2209
-	 * Only lock files in data/user/files/
2210
-	 *
2211
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2212
-	 * @return bool
2213
-	 */
2214
-	protected function shouldLockFile($path) {
2215
-		$path = Filesystem::normalizePath($path);
2216
-
2217
-		$pathSegments = explode('/', $path);
2218
-		if (isset($pathSegments[2])) {
2219
-			// E.g.: /username/files/path-to-file
2220
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2221
-		}
2222
-
2223
-		return !str_starts_with($path, '/appdata_');
2224
-	}
2225
-
2226
-	/**
2227
-	 * Shortens the given absolute path to be relative to
2228
-	 * "$user/files".
2229
-	 *
2230
-	 * @param string $absolutePath absolute path which is under "files"
2231
-	 *
2232
-	 * @return string path relative to "files" with trimmed slashes or null
2233
-	 *                if the path was NOT relative to files
2234
-	 *
2235
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2236
-	 * @since 8.1.0
2237
-	 */
2238
-	public function getPathRelativeToFiles($absolutePath) {
2239
-		$path = Filesystem::normalizePath($absolutePath);
2240
-		$parts = explode('/', trim($path, '/'), 3);
2241
-		// "$user", "files", "path/to/dir"
2242
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2243
-			$this->logger->error(
2244
-				'$absolutePath must be relative to "files", value is "{absolutePath}"',
2245
-				[
2246
-					'absolutePath' => $absolutePath,
2247
-				]
2248
-			);
2249
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2250
-		}
2251
-		if (isset($parts[2])) {
2252
-			return $parts[2];
2253
-		}
2254
-		return '';
2255
-	}
2256
-
2257
-	/**
2258
-	 * @param string $filename
2259
-	 * @return array
2260
-	 * @throws \OC\User\NoUserException
2261
-	 * @throws NotFoundException
2262
-	 */
2263
-	public function getUidAndFilename($filename) {
2264
-		$info = $this->getFileInfo($filename);
2265
-		if (!$info instanceof \OCP\Files\FileInfo) {
2266
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2267
-		}
2268
-		$uid = $info->getOwner()->getUID();
2269
-		if ($uid != \OC_User::getUser()) {
2270
-			Filesystem::initMountPoints($uid);
2271
-			$ownerView = new View('/' . $uid . '/files');
2272
-			try {
2273
-				$filename = $ownerView->getPath($info['fileid']);
2274
-			} catch (NotFoundException $e) {
2275
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2276
-			}
2277
-		}
2278
-		return [$uid, $filename];
2279
-	}
2280
-
2281
-	/**
2282
-	 * Creates parent non-existing folders
2283
-	 *
2284
-	 * @param string $filePath
2285
-	 * @return bool
2286
-	 */
2287
-	private function createParentDirectories($filePath) {
2288
-		$directoryParts = explode('/', $filePath);
2289
-		$directoryParts = array_filter($directoryParts);
2290
-		foreach ($directoryParts as $key => $part) {
2291
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2292
-			$currentPath = '/' . implode('/', $currentPathElements);
2293
-			if ($this->is_file($currentPath)) {
2294
-				return false;
2295
-			}
2296
-			if (!$this->file_exists($currentPath)) {
2297
-				$this->mkdir($currentPath);
2298
-			}
2299
-		}
2300
-
2301
-		return true;
2302
-	}
59
+    private string $fakeRoot = '';
60
+    private ILockingProvider $lockingProvider;
61
+    private bool $lockingEnabled;
62
+    private bool $updaterEnabled = true;
63
+    private UserManager $userManager;
64
+    private LoggerInterface $logger;
65
+
66
+    /**
67
+     * @throws \Exception If $root contains an invalid path
68
+     */
69
+    public function __construct(string $root = '') {
70
+        if (!Filesystem::isValidPath($root)) {
71
+            throw new \Exception();
72
+        }
73
+
74
+        $this->fakeRoot = $root;
75
+        $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
76
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
77
+        $this->userManager = \OC::$server->getUserManager();
78
+        $this->logger = \OC::$server->get(LoggerInterface::class);
79
+    }
80
+
81
+    /**
82
+     * @param ?string $path
83
+     * @psalm-template S as string|null
84
+     * @psalm-param S $path
85
+     * @psalm-return (S is string ? string : null)
86
+     */
87
+    public function getAbsolutePath($path = '/'): ?string {
88
+        if ($path === null) {
89
+            return null;
90
+        }
91
+        $this->assertPathLength($path);
92
+        if ($path === '') {
93
+            $path = '/';
94
+        }
95
+        if ($path[0] !== '/') {
96
+            $path = '/' . $path;
97
+        }
98
+        return $this->fakeRoot . $path;
99
+    }
100
+
101
+    /**
102
+     * Change the root to a fake root
103
+     *
104
+     * @param string $fakeRoot
105
+     */
106
+    public function chroot($fakeRoot): void {
107
+        if (!$fakeRoot == '') {
108
+            if ($fakeRoot[0] !== '/') {
109
+                $fakeRoot = '/' . $fakeRoot;
110
+            }
111
+        }
112
+        $this->fakeRoot = $fakeRoot;
113
+    }
114
+
115
+    /**
116
+     * Get the fake root
117
+     */
118
+    public function getRoot(): string {
119
+        return $this->fakeRoot;
120
+    }
121
+
122
+    /**
123
+     * get path relative to the root of the view
124
+     *
125
+     * @param string $path
126
+     */
127
+    public function getRelativePath($path): ?string {
128
+        $this->assertPathLength($path);
129
+        if ($this->fakeRoot == '') {
130
+            return $path;
131
+        }
132
+
133
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
134
+            return '/';
135
+        }
136
+
137
+        // missing slashes can cause wrong matches!
138
+        $root = rtrim($this->fakeRoot, '/') . '/';
139
+
140
+        if (!str_starts_with($path, $root)) {
141
+            return null;
142
+        } else {
143
+            $path = substr($path, strlen($this->fakeRoot));
144
+            if (strlen($path) === 0) {
145
+                return '/';
146
+            } else {
147
+                return $path;
148
+            }
149
+        }
150
+    }
151
+
152
+    /**
153
+     * Get the mountpoint of the storage object for a path
154
+     * ( note: because a storage is not always mounted inside the fakeroot, the
155
+     * returned mountpoint is relative to the absolute root of the filesystem
156
+     * and does not take the chroot into account )
157
+     *
158
+     * @param string $path
159
+     */
160
+    public function getMountPoint($path): string {
161
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
162
+    }
163
+
164
+    /**
165
+     * Get the mountpoint of the storage object for a path
166
+     * ( note: because a storage is not always mounted inside the fakeroot, the
167
+     * returned mountpoint is relative to the absolute root of the filesystem
168
+     * and does not take the chroot into account )
169
+     *
170
+     * @param string $path
171
+     */
172
+    public function getMount($path): IMountPoint {
173
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
174
+    }
175
+
176
+    /**
177
+     * Resolve a path to a storage and internal path
178
+     *
179
+     * @param string $path
180
+     * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
181
+     */
182
+    public function resolvePath($path): array {
183
+        $a = $this->getAbsolutePath($path);
184
+        $p = Filesystem::normalizePath($a);
185
+        return Filesystem::resolvePath($p);
186
+    }
187
+
188
+    /**
189
+     * Return the path to a local version of the file
190
+     * we need this because we can't know if a file is stored local or not from
191
+     * outside the filestorage and for some purposes a local file is needed
192
+     *
193
+     * @param string $path
194
+     */
195
+    public function getLocalFile($path): string|false {
196
+        $parent = substr($path, 0, strrpos($path, '/') ?: 0);
197
+        $path = $this->getAbsolutePath($path);
198
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
199
+        if (Filesystem::isValidPath($parent) && $storage) {
200
+            return $storage->getLocalFile($internalPath);
201
+        } else {
202
+            return false;
203
+        }
204
+    }
205
+
206
+    /**
207
+     * the following functions operate with arguments and return values identical
208
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
209
+     * for \OC\Files\Storage\Storage via basicOperation().
210
+     */
211
+    public function mkdir($path) {
212
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
213
+    }
214
+
215
+    /**
216
+     * remove mount point
217
+     *
218
+     * @param IMountPoint $mount
219
+     * @param string $path relative to data/
220
+     */
221
+    protected function removeMount($mount, $path): bool {
222
+        if ($mount instanceof MoveableMount) {
223
+            // cut of /user/files to get the relative path to data/user/files
224
+            $pathParts = explode('/', $path, 4);
225
+            $relPath = '/' . $pathParts[3];
226
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
227
+            \OC_Hook::emit(
228
+                Filesystem::CLASSNAME, 'umount',
229
+                [Filesystem::signal_param_path => $relPath]
230
+            );
231
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
232
+            $result = $mount->removeMount();
233
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
234
+            if ($result) {
235
+                \OC_Hook::emit(
236
+                    Filesystem::CLASSNAME, 'post_umount',
237
+                    [Filesystem::signal_param_path => $relPath]
238
+                );
239
+            }
240
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
241
+            return $result;
242
+        } else {
243
+            // do not allow deleting the storage's root / the mount point
244
+            // because for some storages it might delete the whole contents
245
+            // but isn't supposed to work that way
246
+            return false;
247
+        }
248
+    }
249
+
250
+    public function disableCacheUpdate(): void {
251
+        $this->updaterEnabled = false;
252
+    }
253
+
254
+    public function enableCacheUpdate(): void {
255
+        $this->updaterEnabled = true;
256
+    }
257
+
258
+    protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
259
+        if ($this->updaterEnabled) {
260
+            if (is_null($time)) {
261
+                $time = time();
262
+            }
263
+            $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
264
+        }
265
+    }
266
+
267
+    protected function removeUpdate(Storage $storage, string $internalPath): void {
268
+        if ($this->updaterEnabled) {
269
+            $storage->getUpdater()->remove($internalPath);
270
+        }
271
+    }
272
+
273
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
274
+        if ($this->updaterEnabled) {
275
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
276
+        }
277
+    }
278
+
279
+    protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
280
+        if ($this->updaterEnabled) {
281
+            $targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
282
+        }
283
+    }
284
+
285
+    /**
286
+     * @param string $path
287
+     * @return bool|mixed
288
+     */
289
+    public function rmdir($path) {
290
+        $absolutePath = $this->getAbsolutePath($path);
291
+        $mount = Filesystem::getMountManager()->find($absolutePath);
292
+        if ($mount->getInternalPath($absolutePath) === '') {
293
+            return $this->removeMount($mount, $absolutePath);
294
+        }
295
+        if ($this->is_dir($path)) {
296
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
297
+        } else {
298
+            $result = false;
299
+        }
300
+
301
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
302
+            $storage = $mount->getStorage();
303
+            $internalPath = $mount->getInternalPath($absolutePath);
304
+            $storage->getUpdater()->remove($internalPath);
305
+        }
306
+        return $result;
307
+    }
308
+
309
+    /**
310
+     * @param string $path
311
+     * @return resource|false
312
+     */
313
+    public function opendir($path) {
314
+        return $this->basicOperation('opendir', $path, ['read']);
315
+    }
316
+
317
+    /**
318
+     * @param string $path
319
+     * @return bool|mixed
320
+     */
321
+    public function is_dir($path) {
322
+        if ($path == '/') {
323
+            return true;
324
+        }
325
+        return $this->basicOperation('is_dir', $path);
326
+    }
327
+
328
+    /**
329
+     * @param string $path
330
+     * @return bool|mixed
331
+     */
332
+    public function is_file($path) {
333
+        if ($path == '/') {
334
+            return false;
335
+        }
336
+        return $this->basicOperation('is_file', $path);
337
+    }
338
+
339
+    /**
340
+     * @param string $path
341
+     * @return mixed
342
+     */
343
+    public function stat($path) {
344
+        return $this->basicOperation('stat', $path);
345
+    }
346
+
347
+    /**
348
+     * @param string $path
349
+     * @return mixed
350
+     */
351
+    public function filetype($path) {
352
+        return $this->basicOperation('filetype', $path);
353
+    }
354
+
355
+    /**
356
+     * @param string $path
357
+     * @return mixed
358
+     */
359
+    public function filesize(string $path) {
360
+        return $this->basicOperation('filesize', $path);
361
+    }
362
+
363
+    /**
364
+     * @param string $path
365
+     * @return bool|mixed
366
+     * @throws InvalidPathException
367
+     */
368
+    public function readfile($path) {
369
+        $this->assertPathLength($path);
370
+        if (ob_get_level()) {
371
+            ob_end_clean();
372
+        }
373
+        $handle = $this->fopen($path, 'rb');
374
+        if ($handle) {
375
+            $chunkSize = 524288; // 512 kiB chunks
376
+            while (!feof($handle)) {
377
+                echo fread($handle, $chunkSize);
378
+                flush();
379
+                $this->checkConnectionStatus();
380
+            }
381
+            fclose($handle);
382
+            return $this->filesize($path);
383
+        }
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * @param string $path
389
+     * @param int $from
390
+     * @param int $to
391
+     * @return bool|mixed
392
+     * @throws InvalidPathException
393
+     * @throws \OCP\Files\UnseekableException
394
+     */
395
+    public function readfilePart($path, $from, $to) {
396
+        $this->assertPathLength($path);
397
+        if (ob_get_level()) {
398
+            ob_end_clean();
399
+        }
400
+        $handle = $this->fopen($path, 'rb');
401
+        if ($handle) {
402
+            $chunkSize = 524288; // 512 kiB chunks
403
+            $startReading = true;
404
+
405
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
406
+                // forward file handle via chunked fread because fseek seem to have failed
407
+
408
+                $end = $from + 1;
409
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
410
+                    $len = $from - ftell($handle);
411
+                    if ($len > $chunkSize) {
412
+                        $len = $chunkSize;
413
+                    }
414
+                    $result = fread($handle, $len);
415
+
416
+                    if ($result === false) {
417
+                        $startReading = false;
418
+                        break;
419
+                    }
420
+                }
421
+            }
422
+
423
+            if ($startReading) {
424
+                $end = $to + 1;
425
+                while (!feof($handle) && ftell($handle) < $end) {
426
+                    $len = $end - ftell($handle);
427
+                    if ($len > $chunkSize) {
428
+                        $len = $chunkSize;
429
+                    }
430
+                    echo fread($handle, $len);
431
+                    flush();
432
+                    $this->checkConnectionStatus();
433
+                }
434
+                return ftell($handle) - $from;
435
+            }
436
+
437
+            throw new \OCP\Files\UnseekableException('fseek error');
438
+        }
439
+        return false;
440
+    }
441
+
442
+    private function checkConnectionStatus(): void {
443
+        $connectionStatus = \connection_status();
444
+        if ($connectionStatus !== CONNECTION_NORMAL) {
445
+            throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
446
+        }
447
+    }
448
+
449
+    /**
450
+     * @param string $path
451
+     * @return mixed
452
+     */
453
+    public function isCreatable($path) {
454
+        return $this->basicOperation('isCreatable', $path);
455
+    }
456
+
457
+    /**
458
+     * @param string $path
459
+     * @return mixed
460
+     */
461
+    public function isReadable($path) {
462
+        return $this->basicOperation('isReadable', $path);
463
+    }
464
+
465
+    /**
466
+     * @param string $path
467
+     * @return mixed
468
+     */
469
+    public function isUpdatable($path) {
470
+        return $this->basicOperation('isUpdatable', $path);
471
+    }
472
+
473
+    /**
474
+     * @param string $path
475
+     * @return bool|mixed
476
+     */
477
+    public function isDeletable($path) {
478
+        $absolutePath = $this->getAbsolutePath($path);
479
+        $mount = Filesystem::getMountManager()->find($absolutePath);
480
+        if ($mount->getInternalPath($absolutePath) === '') {
481
+            return $mount instanceof MoveableMount;
482
+        }
483
+        return $this->basicOperation('isDeletable', $path);
484
+    }
485
+
486
+    /**
487
+     * @param string $path
488
+     * @return mixed
489
+     */
490
+    public function isSharable($path) {
491
+        return $this->basicOperation('isSharable', $path);
492
+    }
493
+
494
+    /**
495
+     * @param string $path
496
+     * @return bool|mixed
497
+     */
498
+    public function file_exists($path) {
499
+        if ($path == '/') {
500
+            return true;
501
+        }
502
+        return $this->basicOperation('file_exists', $path);
503
+    }
504
+
505
+    /**
506
+     * @param string $path
507
+     * @return mixed
508
+     */
509
+    public function filemtime($path) {
510
+        return $this->basicOperation('filemtime', $path);
511
+    }
512
+
513
+    /**
514
+     * @param string $path
515
+     * @param int|string $mtime
516
+     */
517
+    public function touch($path, $mtime = null): bool {
518
+        if (!is_null($mtime) && !is_numeric($mtime)) {
519
+            $mtime = strtotime($mtime);
520
+        }
521
+
522
+        $hooks = ['touch'];
523
+
524
+        if (!$this->file_exists($path)) {
525
+            $hooks[] = 'create';
526
+            $hooks[] = 'write';
527
+        }
528
+        try {
529
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
530
+        } catch (\Exception $e) {
531
+            $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
532
+            $result = false;
533
+        }
534
+        if (!$result) {
535
+            // If create file fails because of permissions on external storage like SMB folders,
536
+            // check file exists and return false if not.
537
+            if (!$this->file_exists($path)) {
538
+                return false;
539
+            }
540
+            if (is_null($mtime)) {
541
+                $mtime = time();
542
+            }
543
+            //if native touch fails, we emulate it by changing the mtime in the cache
544
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
545
+        }
546
+        return true;
547
+    }
548
+
549
+    /**
550
+     * @param string $path
551
+     * @return string|false
552
+     * @throws LockedException
553
+     */
554
+    public function file_get_contents($path) {
555
+        return $this->basicOperation('file_get_contents', $path, ['read']);
556
+    }
557
+
558
+    protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
559
+        if (!$exists) {
560
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
561
+                Filesystem::signal_param_path => $this->getHookPath($path),
562
+                Filesystem::signal_param_run => &$run,
563
+            ]);
564
+        } else {
565
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
566
+                Filesystem::signal_param_path => $this->getHookPath($path),
567
+                Filesystem::signal_param_run => &$run,
568
+            ]);
569
+        }
570
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
571
+            Filesystem::signal_param_path => $this->getHookPath($path),
572
+            Filesystem::signal_param_run => &$run,
573
+        ]);
574
+    }
575
+
576
+    protected function emit_file_hooks_post(bool $exists, string $path): void {
577
+        if (!$exists) {
578
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
579
+                Filesystem::signal_param_path => $this->getHookPath($path),
580
+            ]);
581
+        } else {
582
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
583
+                Filesystem::signal_param_path => $this->getHookPath($path),
584
+            ]);
585
+        }
586
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
587
+            Filesystem::signal_param_path => $this->getHookPath($path),
588
+        ]);
589
+    }
590
+
591
+    /**
592
+     * @param string $path
593
+     * @param string|resource $data
594
+     * @return bool|mixed
595
+     * @throws LockedException
596
+     */
597
+    public function file_put_contents($path, $data) {
598
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
599
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
600
+            if (Filesystem::isValidPath($path)
601
+                && !Filesystem::isFileBlacklisted($path)
602
+            ) {
603
+                $path = $this->getRelativePath($absolutePath);
604
+                if ($path === null) {
605
+                    throw new InvalidPathException("Path $absolutePath is not in the expected root");
606
+                }
607
+
608
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
609
+
610
+                $exists = $this->file_exists($path);
611
+                if ($this->shouldEmitHooks($path)) {
612
+                    $run = true;
613
+                    $this->emit_file_hooks_pre($exists, $path, $run);
614
+                    if (!$run) {
615
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
616
+                        return false;
617
+                    }
618
+                }
619
+
620
+                try {
621
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
622
+                } catch (\Exception $e) {
623
+                    // Release the shared lock before throwing.
624
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
625
+                    throw $e;
626
+                }
627
+
628
+                /** @var Storage $storage */
629
+                [$storage, $internalPath] = $this->resolvePath($path);
630
+                $target = $storage->fopen($internalPath, 'w');
631
+                if ($target) {
632
+                    [, $result] = \OC_Helper::streamCopy($data, $target);
633
+                    fclose($target);
634
+                    fclose($data);
635
+
636
+                    $this->writeUpdate($storage, $internalPath);
637
+
638
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
639
+
640
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
641
+                        $this->emit_file_hooks_post($exists, $path);
642
+                    }
643
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
644
+                    return $result;
645
+                } else {
646
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
647
+                    return false;
648
+                }
649
+            } else {
650
+                return false;
651
+            }
652
+        } else {
653
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
654
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
655
+        }
656
+    }
657
+
658
+    /**
659
+     * @param string $path
660
+     * @return bool|mixed
661
+     */
662
+    public function unlink($path) {
663
+        if ($path === '' || $path === '/') {
664
+            // do not allow deleting the root
665
+            return false;
666
+        }
667
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
668
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
669
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
670
+        if ($mount->getInternalPath($absolutePath) === '') {
671
+            return $this->removeMount($mount, $absolutePath);
672
+        }
673
+        if ($this->is_dir($path)) {
674
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
675
+        } else {
676
+            $result = $this->basicOperation('unlink', $path, ['delete']);
677
+        }
678
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
679
+            $storage = $mount->getStorage();
680
+            $internalPath = $mount->getInternalPath($absolutePath);
681
+            $storage->getUpdater()->remove($internalPath);
682
+            return true;
683
+        } else {
684
+            return $result;
685
+        }
686
+    }
687
+
688
+    /**
689
+     * @param string $directory
690
+     * @return bool|mixed
691
+     */
692
+    public function deleteAll($directory) {
693
+        return $this->rmdir($directory);
694
+    }
695
+
696
+    /**
697
+     * Rename/move a file or folder from the source path to target path.
698
+     *
699
+     * @param string $source source path
700
+     * @param string $target target path
701
+     * @param array $options
702
+     *
703
+     * @return bool|mixed
704
+     * @throws LockedException
705
+     */
706
+    public function rename($source, $target, array $options = []) {
707
+        $checkSubMounts = $options['checkSubMounts'] ?? true;
708
+
709
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
710
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
711
+
712
+        if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
713
+            throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
714
+        }
715
+
716
+        /** @var IMountManager $mountManager */
717
+        $mountManager = \OC::$server->get(IMountManager::class);
718
+
719
+        $targetParts = explode('/', $absolutePath2);
720
+        $targetUser = $targetParts[1] ?? null;
721
+        $result = false;
722
+        if (
723
+            Filesystem::isValidPath($target)
724
+            && Filesystem::isValidPath($source)
725
+            && !Filesystem::isFileBlacklisted($target)
726
+        ) {
727
+            $source = $this->getRelativePath($absolutePath1);
728
+            $target = $this->getRelativePath($absolutePath2);
729
+            $exists = $this->file_exists($target);
730
+
731
+            if ($source == null || $target == null) {
732
+                return false;
733
+            }
734
+
735
+            try {
736
+                $this->verifyPath(dirname($target), basename($target));
737
+            } catch (InvalidPathException) {
738
+                return false;
739
+            }
740
+
741
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
742
+            try {
743
+                $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
744
+
745
+                $run = true;
746
+                if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
747
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
748
+                    $this->emit_file_hooks_pre($exists, $target, $run);
749
+                } elseif ($this->shouldEmitHooks($source)) {
750
+                    $sourcePath = $this->getHookPath($source);
751
+                    $targetPath = $this->getHookPath($target);
752
+                    if ($sourcePath !== null && $targetPath !== null) {
753
+                        \OC_Hook::emit(
754
+                            Filesystem::CLASSNAME, Filesystem::signal_rename,
755
+                            [
756
+                                Filesystem::signal_param_oldpath => $sourcePath,
757
+                                Filesystem::signal_param_newpath => $targetPath,
758
+                                Filesystem::signal_param_run => &$run
759
+                            ]
760
+                        );
761
+                    }
762
+                }
763
+                if ($run) {
764
+                    $manager = Filesystem::getMountManager();
765
+                    $mount1 = $this->getMount($source);
766
+                    $mount2 = $this->getMount($target);
767
+                    $storage1 = $mount1->getStorage();
768
+                    $storage2 = $mount2->getStorage();
769
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
770
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
771
+
772
+                    $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
773
+                    try {
774
+                        $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
775
+
776
+                        if ($checkSubMounts) {
777
+                            $movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
778
+                        } else {
779
+                            $movedMounts = [];
780
+                        }
781
+
782
+                        if ($internalPath1 === '') {
783
+                            $sourceParentMount = $this->getMount(dirname($source));
784
+                            $movedMounts[] = $mount1;
785
+                            $this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
786
+                            /**
787
+                             * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
788
+                             */
789
+                            $sourceMountPoint = $mount1->getMountPoint();
790
+                            $result = $mount1->moveMount($absolutePath2);
791
+                            $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
792
+
793
+                            // moving a file/folder within the same mount point
794
+                        } elseif ($storage1 === $storage2) {
795
+                            if (count($movedMounts) > 0) {
796
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
797
+                            }
798
+                            if ($storage1) {
799
+                                $result = $storage1->rename($internalPath1, $internalPath2);
800
+                            } else {
801
+                                $result = false;
802
+                            }
803
+                            // moving a file/folder between storages (from $storage1 to $storage2)
804
+                        } else {
805
+                            if (count($movedMounts) > 0) {
806
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
807
+                            }
808
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
809
+                        }
810
+
811
+                        if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
812
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
813
+                            $this->writeUpdate($storage2, $internalPath2);
814
+                        } elseif ($result) {
815
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
816
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
817
+                            }
818
+                        }
819
+                    } catch (\Exception $e) {
820
+                        throw $e;
821
+                    } finally {
822
+                        $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
823
+                        $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
824
+                    }
825
+
826
+                    if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
827
+                        if ($this->shouldEmitHooks()) {
828
+                            $this->emit_file_hooks_post($exists, $target);
829
+                        }
830
+                    } elseif ($result) {
831
+                        if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
832
+                            $sourcePath = $this->getHookPath($source);
833
+                            $targetPath = $this->getHookPath($target);
834
+                            if ($sourcePath !== null && $targetPath !== null) {
835
+                                \OC_Hook::emit(
836
+                                    Filesystem::CLASSNAME,
837
+                                    Filesystem::signal_post_rename,
838
+                                    [
839
+                                        Filesystem::signal_param_oldpath => $sourcePath,
840
+                                        Filesystem::signal_param_newpath => $targetPath,
841
+                                    ]
842
+                                );
843
+                            }
844
+                        }
845
+                    }
846
+                }
847
+            } catch (\Exception $e) {
848
+                throw $e;
849
+            } finally {
850
+                $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
851
+                $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
852
+            }
853
+        }
854
+        return $result;
855
+    }
856
+
857
+    /**
858
+     * @throws ForbiddenException
859
+     */
860
+    private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
861
+        $targetPath = $this->getRelativePath($targetMount->getMountPoint());
862
+        if ($targetPath) {
863
+            $targetPath = trim($targetPath, '/');
864
+        } else {
865
+            $targetPath = $targetMount->getMountPoint();
866
+        }
867
+
868
+        $l = \OC::$server->get(IFactory::class)->get('files');
869
+        foreach ($mounts as $mount) {
870
+            $sourcePath = $this->getRelativePath($mount->getMountPoint());
871
+            if ($sourcePath) {
872
+                $sourcePath = trim($sourcePath, '/');
873
+            } else {
874
+                $sourcePath = $mount->getMountPoint();
875
+            }
876
+
877
+            if (!$mount instanceof MoveableMount) {
878
+                throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
879
+            }
880
+
881
+            if ($targetIsShared) {
882
+                if ($sourceMount instanceof SharedMount) {
883
+                    throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
884
+                } else {
885
+                    throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
886
+                }
887
+            }
888
+
889
+            if ($sourceMount !== $targetMount) {
890
+                if ($sourceMount instanceof SharedMount) {
891
+                    if ($targetMount instanceof SharedMount) {
892
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
893
+                    } else {
894
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
895
+                    }
896
+                } else {
897
+                    if ($targetMount instanceof SharedMount) {
898
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
899
+                    } else {
900
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
901
+                    }
902
+                }
903
+            }
904
+        }
905
+    }
906
+
907
+    /**
908
+     * Copy a file/folder from the source path to target path
909
+     *
910
+     * @param string $source source path
911
+     * @param string $target target path
912
+     * @param bool $preserveMtime whether to preserve mtime on the copy
913
+     *
914
+     * @return bool|mixed
915
+     */
916
+    public function copy($source, $target, $preserveMtime = false) {
917
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
918
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
919
+        $result = false;
920
+        if (
921
+            Filesystem::isValidPath($target)
922
+            && Filesystem::isValidPath($source)
923
+            && !Filesystem::isFileBlacklisted($target)
924
+        ) {
925
+            $source = $this->getRelativePath($absolutePath1);
926
+            $target = $this->getRelativePath($absolutePath2);
927
+
928
+            if ($source == null || $target == null) {
929
+                return false;
930
+            }
931
+            $run = true;
932
+
933
+            $this->lockFile($target, ILockingProvider::LOCK_SHARED);
934
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED);
935
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
936
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
937
+
938
+            try {
939
+                $exists = $this->file_exists($target);
940
+                if ($this->shouldEmitHooks()) {
941
+                    \OC_Hook::emit(
942
+                        Filesystem::CLASSNAME,
943
+                        Filesystem::signal_copy,
944
+                        [
945
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
946
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
947
+                            Filesystem::signal_param_run => &$run
948
+                        ]
949
+                    );
950
+                    $this->emit_file_hooks_pre($exists, $target, $run);
951
+                }
952
+                if ($run) {
953
+                    $mount1 = $this->getMount($source);
954
+                    $mount2 = $this->getMount($target);
955
+                    $storage1 = $mount1->getStorage();
956
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
957
+                    $storage2 = $mount2->getStorage();
958
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
959
+
960
+                    $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
961
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
962
+
963
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
964
+                        if ($storage1) {
965
+                            $result = $storage1->copy($internalPath1, $internalPath2);
966
+                        } else {
967
+                            $result = false;
968
+                        }
969
+                    } else {
970
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
971
+                    }
972
+
973
+                    if ($result) {
974
+                        $this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
975
+                    }
976
+
977
+                    $this->changeLock($target, ILockingProvider::LOCK_SHARED);
978
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
979
+
980
+                    if ($this->shouldEmitHooks() && $result !== false) {
981
+                        \OC_Hook::emit(
982
+                            Filesystem::CLASSNAME,
983
+                            Filesystem::signal_post_copy,
984
+                            [
985
+                                Filesystem::signal_param_oldpath => $this->getHookPath($source),
986
+                                Filesystem::signal_param_newpath => $this->getHookPath($target)
987
+                            ]
988
+                        );
989
+                        $this->emit_file_hooks_post($exists, $target);
990
+                    }
991
+                }
992
+            } catch (\Exception $e) {
993
+                $this->unlockFile($target, $lockTypePath2);
994
+                $this->unlockFile($source, $lockTypePath1);
995
+                throw $e;
996
+            }
997
+
998
+            $this->unlockFile($target, $lockTypePath2);
999
+            $this->unlockFile($source, $lockTypePath1);
1000
+        }
1001
+        return $result;
1002
+    }
1003
+
1004
+    /**
1005
+     * @param string $path
1006
+     * @param string $mode 'r' or 'w'
1007
+     * @return resource|false
1008
+     * @throws LockedException
1009
+     */
1010
+    public function fopen($path, $mode) {
1011
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1012
+        $hooks = [];
1013
+        switch ($mode) {
1014
+            case 'r':
1015
+                $hooks[] = 'read';
1016
+                break;
1017
+            case 'r+':
1018
+            case 'w+':
1019
+            case 'x+':
1020
+            case 'a+':
1021
+                $hooks[] = 'read';
1022
+                $hooks[] = 'write';
1023
+                break;
1024
+            case 'w':
1025
+            case 'x':
1026
+            case 'a':
1027
+                $hooks[] = 'write';
1028
+                break;
1029
+            default:
1030
+                $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1031
+        }
1032
+
1033
+        if ($mode !== 'r' && $mode !== 'w') {
1034
+            $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1035
+        }
1036
+
1037
+        $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1038
+        if (!is_resource($handle) && $mode === 'r') {
1039
+            // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1040
+            $mount = $this->getMount($path);
1041
+            $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1042
+            $storage = $mount->getStorage();
1043
+            if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1044
+                $this->writeUpdate($storage, $internalPath);
1045
+            }
1046
+        }
1047
+        return $handle;
1048
+    }
1049
+
1050
+    /**
1051
+     * @param string $path
1052
+     * @throws InvalidPathException
1053
+     */
1054
+    public function toTmpFile($path): string|false {
1055
+        $this->assertPathLength($path);
1056
+        if (Filesystem::isValidPath($path)) {
1057
+            $source = $this->fopen($path, 'r');
1058
+            if ($source) {
1059
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1060
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1061
+                file_put_contents($tmpFile, $source);
1062
+                return $tmpFile;
1063
+            } else {
1064
+                return false;
1065
+            }
1066
+        } else {
1067
+            return false;
1068
+        }
1069
+    }
1070
+
1071
+    /**
1072
+     * @param string $tmpFile
1073
+     * @param string $path
1074
+     * @return bool|mixed
1075
+     * @throws InvalidPathException
1076
+     */
1077
+    public function fromTmpFile($tmpFile, $path) {
1078
+        $this->assertPathLength($path);
1079
+        if (Filesystem::isValidPath($path)) {
1080
+            // Get directory that the file is going into
1081
+            $filePath = dirname($path);
1082
+
1083
+            // Create the directories if any
1084
+            if (!$this->file_exists($filePath)) {
1085
+                $result = $this->createParentDirectories($filePath);
1086
+                if ($result === false) {
1087
+                    return false;
1088
+                }
1089
+            }
1090
+
1091
+            $source = fopen($tmpFile, 'r');
1092
+            if ($source) {
1093
+                $result = $this->file_put_contents($path, $source);
1094
+                /**
1095
+                 * $this->file_put_contents() might have already closed
1096
+                 * the resource, so we check it, before trying to close it
1097
+                 * to avoid messages in the error log.
1098
+                 * @psalm-suppress RedundantCondition false-positive
1099
+                 */
1100
+                if (is_resource($source)) {
1101
+                    fclose($source);
1102
+                }
1103
+                unlink($tmpFile);
1104
+                return $result;
1105
+            } else {
1106
+                return false;
1107
+            }
1108
+        } else {
1109
+            return false;
1110
+        }
1111
+    }
1112
+
1113
+
1114
+    /**
1115
+     * @param string $path
1116
+     * @return mixed
1117
+     * @throws InvalidPathException
1118
+     */
1119
+    public function getMimeType($path) {
1120
+        $this->assertPathLength($path);
1121
+        return $this->basicOperation('getMimeType', $path);
1122
+    }
1123
+
1124
+    /**
1125
+     * @param string $type
1126
+     * @param string $path
1127
+     * @param bool $raw
1128
+     */
1129
+    public function hash($type, $path, $raw = false): string|bool {
1130
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1131
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1132
+        if (Filesystem::isValidPath($path)) {
1133
+            $path = $this->getRelativePath($absolutePath);
1134
+            if ($path == null) {
1135
+                return false;
1136
+            }
1137
+            if ($this->shouldEmitHooks($path)) {
1138
+                \OC_Hook::emit(
1139
+                    Filesystem::CLASSNAME,
1140
+                    Filesystem::signal_read,
1141
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1142
+                );
1143
+            }
1144
+            /** @var Storage|null $storage */
1145
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1146
+            if ($storage) {
1147
+                return $storage->hash($type, $internalPath, $raw);
1148
+            }
1149
+        }
1150
+        return false;
1151
+    }
1152
+
1153
+    /**
1154
+     * @param string $path
1155
+     * @return mixed
1156
+     * @throws InvalidPathException
1157
+     */
1158
+    public function free_space($path = '/') {
1159
+        $this->assertPathLength($path);
1160
+        $result = $this->basicOperation('free_space', $path);
1161
+        if ($result === null) {
1162
+            throw new InvalidPathException();
1163
+        }
1164
+        return $result;
1165
+    }
1166
+
1167
+    /**
1168
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1169
+     *
1170
+     * @param mixed $extraParam (optional)
1171
+     * @return mixed
1172
+     * @throws LockedException
1173
+     *
1174
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1175
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1176
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1177
+     */
1178
+    private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1179
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1180
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1181
+        if (Filesystem::isValidPath($path)
1182
+            && !Filesystem::isFileBlacklisted($path)
1183
+        ) {
1184
+            $path = $this->getRelativePath($absolutePath);
1185
+            if ($path == null) {
1186
+                return false;
1187
+            }
1188
+
1189
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1190
+                // always a shared lock during pre-hooks so the hook can read the file
1191
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1192
+            }
1193
+
1194
+            $run = $this->runHooks($hooks, $path);
1195
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1196
+            if ($run && $storage) {
1197
+                /** @var Storage $storage */
1198
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1199
+                    try {
1200
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1201
+                    } catch (LockedException $e) {
1202
+                        // release the shared lock we acquired before quitting
1203
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1204
+                        throw $e;
1205
+                    }
1206
+                }
1207
+                try {
1208
+                    if (!is_null($extraParam)) {
1209
+                        $result = $storage->$operation($internalPath, $extraParam);
1210
+                    } else {
1211
+                        $result = $storage->$operation($internalPath);
1212
+                    }
1213
+                } catch (\Exception $e) {
1214
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1215
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1216
+                    } elseif (in_array('read', $hooks)) {
1217
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1218
+                    }
1219
+                    throw $e;
1220
+                }
1221
+
1222
+                if ($result !== false && in_array('delete', $hooks)) {
1223
+                    $this->removeUpdate($storage, $internalPath);
1224
+                }
1225
+                if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1226
+                    $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1227
+                    $sizeDifference = $operation === 'mkdir' ? 0 : $result;
1228
+                    $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1229
+                }
1230
+                if ($result !== false && in_array('touch', $hooks)) {
1231
+                    $this->writeUpdate($storage, $internalPath, $extraParam, 0);
1232
+                }
1233
+
1234
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1235
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1236
+                }
1237
+
1238
+                $unlockLater = false;
1239
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1240
+                    $unlockLater = true;
1241
+                    // make sure our unlocking callback will still be called if connection is aborted
1242
+                    ignore_user_abort(true);
1243
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1244
+                        if (in_array('write', $hooks)) {
1245
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1246
+                        } elseif (in_array('read', $hooks)) {
1247
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1248
+                        }
1249
+                    });
1250
+                }
1251
+
1252
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1253
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1254
+                        $this->runHooks($hooks, $path, true);
1255
+                    }
1256
+                }
1257
+
1258
+                if (!$unlockLater
1259
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1260
+                ) {
1261
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1262
+                }
1263
+                return $result;
1264
+            } else {
1265
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1266
+            }
1267
+        }
1268
+        return null;
1269
+    }
1270
+
1271
+    /**
1272
+     * get the path relative to the default root for hook usage
1273
+     *
1274
+     * @param string $path
1275
+     * @return ?string
1276
+     */
1277
+    private function getHookPath($path): ?string {
1278
+        $view = Filesystem::getView();
1279
+        if (!$view) {
1280
+            return $path;
1281
+        }
1282
+        return $view->getRelativePath($this->getAbsolutePath($path));
1283
+    }
1284
+
1285
+    private function shouldEmitHooks(string $path = ''): bool {
1286
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1287
+            return false;
1288
+        }
1289
+        if (!Filesystem::$loaded) {
1290
+            return false;
1291
+        }
1292
+        $defaultRoot = Filesystem::getRoot();
1293
+        if ($defaultRoot === null) {
1294
+            return false;
1295
+        }
1296
+        if ($this->fakeRoot === $defaultRoot) {
1297
+            return true;
1298
+        }
1299
+        $fullPath = $this->getAbsolutePath($path);
1300
+
1301
+        if ($fullPath === $defaultRoot) {
1302
+            return true;
1303
+        }
1304
+
1305
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1306
+    }
1307
+
1308
+    /**
1309
+     * @param string[] $hooks
1310
+     * @param string $path
1311
+     * @param bool $post
1312
+     * @return bool
1313
+     */
1314
+    private function runHooks($hooks, $path, $post = false) {
1315
+        $relativePath = $path;
1316
+        $path = $this->getHookPath($path);
1317
+        $prefix = $post ? 'post_' : '';
1318
+        $run = true;
1319
+        if ($this->shouldEmitHooks($relativePath)) {
1320
+            foreach ($hooks as $hook) {
1321
+                if ($hook != 'read') {
1322
+                    \OC_Hook::emit(
1323
+                        Filesystem::CLASSNAME,
1324
+                        $prefix . $hook,
1325
+                        [
1326
+                            Filesystem::signal_param_run => &$run,
1327
+                            Filesystem::signal_param_path => $path
1328
+                        ]
1329
+                    );
1330
+                } elseif (!$post) {
1331
+                    \OC_Hook::emit(
1332
+                        Filesystem::CLASSNAME,
1333
+                        $prefix . $hook,
1334
+                        [
1335
+                            Filesystem::signal_param_path => $path
1336
+                        ]
1337
+                    );
1338
+                }
1339
+            }
1340
+        }
1341
+        return $run;
1342
+    }
1343
+
1344
+    /**
1345
+     * check if a file or folder has been updated since $time
1346
+     *
1347
+     * @param string $path
1348
+     * @param int $time
1349
+     * @return bool
1350
+     */
1351
+    public function hasUpdated($path, $time) {
1352
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1353
+    }
1354
+
1355
+    /**
1356
+     * @param string $ownerId
1357
+     * @return IUser
1358
+     */
1359
+    private function getUserObjectForOwner(string $ownerId) {
1360
+        return new LazyUser($ownerId, $this->userManager);
1361
+    }
1362
+
1363
+    /**
1364
+     * Get file info from cache
1365
+     *
1366
+     * If the file is not in cached it will be scanned
1367
+     * If the file has changed on storage the cache will be updated
1368
+     *
1369
+     * @param Storage $storage
1370
+     * @param string $internalPath
1371
+     * @param string $relativePath
1372
+     * @return ICacheEntry|bool
1373
+     */
1374
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1375
+        $cache = $storage->getCache($internalPath);
1376
+        $data = $cache->get($internalPath);
1377
+        $watcher = $storage->getWatcher($internalPath);
1378
+
1379
+        try {
1380
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1381
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1382
+                if (!$storage->file_exists($internalPath)) {
1383
+                    return false;
1384
+                }
1385
+                // don't need to get a lock here since the scanner does it's own locking
1386
+                $scanner = $storage->getScanner($internalPath);
1387
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1388
+                $data = $cache->get($internalPath);
1389
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1390
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1391
+                $watcher->update($internalPath, $data);
1392
+                $storage->getPropagator()->propagateChange($internalPath, time());
1393
+                $data = $cache->get($internalPath);
1394
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1395
+            }
1396
+        } catch (LockedException $e) {
1397
+            // if the file is locked we just use the old cache info
1398
+        }
1399
+
1400
+        return $data;
1401
+    }
1402
+
1403
+    /**
1404
+     * get the filesystem info
1405
+     *
1406
+     * @param string $path
1407
+     * @param bool|string $includeMountPoints true to add mountpoint sizes,
1408
+     *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1409
+     * @return \OC\Files\FileInfo|false False if file does not exist
1410
+     */
1411
+    public function getFileInfo($path, $includeMountPoints = true) {
1412
+        $this->assertPathLength($path);
1413
+        if (!Filesystem::isValidPath($path)) {
1414
+            return false;
1415
+        }
1416
+        $relativePath = $path;
1417
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1418
+
1419
+        $mount = Filesystem::getMountManager()->find($path);
1420
+        $storage = $mount->getStorage();
1421
+        $internalPath = $mount->getInternalPath($path);
1422
+        if ($storage) {
1423
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1424
+
1425
+            if (!$data instanceof ICacheEntry) {
1426
+                if (Cache\Scanner::isPartialFile($relativePath)) {
1427
+                    return $this->getPartFileInfo($relativePath);
1428
+                }
1429
+
1430
+                return false;
1431
+            }
1432
+
1433
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1434
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1435
+            }
1436
+            if ($internalPath === '' && $data['name']) {
1437
+                $data['name'] = basename($path);
1438
+            }
1439
+
1440
+            $ownerId = $storage->getOwner($internalPath);
1441
+            $owner = null;
1442
+            if ($ownerId !== false) {
1443
+                // ownerId might be null if files are accessed with an access token without file system access
1444
+                $owner = $this->getUserObjectForOwner($ownerId);
1445
+            }
1446
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1447
+
1448
+            if (isset($data['fileid'])) {
1449
+                if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1450
+                    //add the sizes of other mount points to the folder
1451
+                    $extOnly = ($includeMountPoints === 'ext');
1452
+                    $this->addSubMounts($info, $extOnly);
1453
+                }
1454
+            }
1455
+
1456
+            return $info;
1457
+        } else {
1458
+            $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1459
+        }
1460
+
1461
+        return false;
1462
+    }
1463
+
1464
+    /**
1465
+     * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1466
+     */
1467
+    public function addSubMounts(FileInfo $info, $extOnly = false): void {
1468
+        $mounts = Filesystem::getMountManager()->findIn($info->getPath());
1469
+        $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1470
+            return !($extOnly && $mount instanceof SharedMount);
1471
+        }));
1472
+    }
1473
+
1474
+    /**
1475
+     * get the content of a directory
1476
+     *
1477
+     * @param string $directory path under datadirectory
1478
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1479
+     * @return FileInfo[]
1480
+     */
1481
+    public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1482
+        $this->assertPathLength($directory);
1483
+        if (!Filesystem::isValidPath($directory)) {
1484
+            return [];
1485
+        }
1486
+
1487
+        $path = $this->getAbsolutePath($directory);
1488
+        $path = Filesystem::normalizePath($path);
1489
+        $mount = $this->getMount($directory);
1490
+        $storage = $mount->getStorage();
1491
+        $internalPath = $mount->getInternalPath($path);
1492
+        if (!$storage) {
1493
+            return [];
1494
+        }
1495
+
1496
+        $cache = $storage->getCache($internalPath);
1497
+        $user = \OC_User::getUser();
1498
+
1499
+        if (!$directoryInfo) {
1500
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1501
+            if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1502
+                return [];
1503
+            }
1504
+        } else {
1505
+            $data = $directoryInfo;
1506
+        }
1507
+
1508
+        if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1509
+            return [];
1510
+        }
1511
+
1512
+        $folderId = $data->getId();
1513
+        $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1514
+
1515
+        $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1516
+
1517
+        $fileNames = array_map(function (ICacheEntry $content) {
1518
+            return $content->getName();
1519
+        }, $contents);
1520
+        /**
1521
+         * @var \OC\Files\FileInfo[] $fileInfos
1522
+         */
1523
+        $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1524
+            if ($sharingDisabled) {
1525
+                $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1526
+            }
1527
+            $ownerId = $storage->getOwner($content['path']);
1528
+            if ($ownerId !== false) {
1529
+                $owner = $this->getUserObjectForOwner($ownerId);
1530
+            } else {
1531
+                $owner = null;
1532
+            }
1533
+            return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1534
+        }, $contents);
1535
+        $files = array_combine($fileNames, $fileInfos);
1536
+
1537
+        //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1538
+        $mounts = Filesystem::getMountManager()->findIn($path);
1539
+
1540
+        // make sure nested mounts are sorted after their parent mounts
1541
+        // otherwise doesn't propagate the etag across storage boundaries correctly
1542
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1543
+            return $a->getMountPoint() <=> $b->getMountPoint();
1544
+        });
1545
+
1546
+        $dirLength = strlen($path);
1547
+        foreach ($mounts as $mount) {
1548
+            $mountPoint = $mount->getMountPoint();
1549
+            $subStorage = $mount->getStorage();
1550
+            if ($subStorage) {
1551
+                $subCache = $subStorage->getCache('');
1552
+
1553
+                $rootEntry = $subCache->get('');
1554
+                if (!$rootEntry) {
1555
+                    $subScanner = $subStorage->getScanner();
1556
+                    try {
1557
+                        $subScanner->scanFile('');
1558
+                    } catch (\OCP\Files\StorageNotAvailableException $e) {
1559
+                        continue;
1560
+                    } catch (\OCP\Files\StorageInvalidException $e) {
1561
+                        continue;
1562
+                    } catch (\Exception $e) {
1563
+                        // sometimes when the storage is not available it can be any exception
1564
+                        $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1565
+                            'exception' => $e,
1566
+                            'app' => 'core',
1567
+                        ]);
1568
+                        continue;
1569
+                    }
1570
+                    $rootEntry = $subCache->get('');
1571
+                }
1572
+
1573
+                if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1574
+                    $relativePath = trim(substr($mountPoint, $dirLength), '/');
1575
+                    if ($pos = strpos($relativePath, '/')) {
1576
+                        //mountpoint inside subfolder add size to the correct folder
1577
+                        $entryName = substr($relativePath, 0, $pos);
1578
+
1579
+                        // Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1580
+                        if (!isset($files[$entryName])) {
1581
+                            try {
1582
+                                [$storage, ] = $this->resolvePath($path . '/' . $entryName);
1583
+                                // make sure we can create the mountpoint folder, even if the user has a quota of 0
1584
+                                if ($storage->instanceOfStorage(Quota::class)) {
1585
+                                    $storage->enableQuota(false);
1586
+                                }
1587
+
1588
+                                if ($this->mkdir($path . '/' . $entryName) !== false) {
1589
+                                    $info = $this->getFileInfo($path . '/' . $entryName);
1590
+                                    if ($info !== false) {
1591
+                                        $files[$entryName] = $info;
1592
+                                    }
1593
+                                }
1594
+
1595
+                                if ($storage->instanceOfStorage(Quota::class)) {
1596
+                                    $storage->enableQuota(true);
1597
+                                }
1598
+                            } catch (\Exception $e) {
1599
+                                // Creating the parent folder might not be possible, for example due to a lack of permissions.
1600
+                                $this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1601
+                            }
1602
+                        }
1603
+
1604
+                        if (isset($files[$entryName])) {
1605
+                            $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1606
+                        }
1607
+                    } else { //mountpoint in this folder, add an entry for it
1608
+                        $rootEntry['name'] = $relativePath;
1609
+                        $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1610
+                        $permissions = $rootEntry['permissions'];
1611
+                        // do not allow renaming/deleting the mount point if they are not shared files/folders
1612
+                        // for shared files/folders we use the permissions given by the owner
1613
+                        if ($mount instanceof MoveableMount) {
1614
+                            $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1615
+                        } else {
1616
+                            $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1617
+                        }
1618
+
1619
+                        $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1620
+
1621
+                        // if sharing was disabled for the user we remove the share permissions
1622
+                        if ($sharingDisabled) {
1623
+                            $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1624
+                        }
1625
+
1626
+                        $ownerId = $subStorage->getOwner('');
1627
+                        if ($ownerId !== false) {
1628
+                            $owner = $this->getUserObjectForOwner($ownerId);
1629
+                        } else {
1630
+                            $owner = null;
1631
+                        }
1632
+                        $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1633
+                    }
1634
+                }
1635
+            }
1636
+        }
1637
+
1638
+        if ($mimetype_filter) {
1639
+            $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1640
+                if (strpos($mimetype_filter, '/')) {
1641
+                    return $file->getMimetype() === $mimetype_filter;
1642
+                } else {
1643
+                    return $file->getMimePart() === $mimetype_filter;
1644
+                }
1645
+            });
1646
+        }
1647
+
1648
+        return array_values($files);
1649
+    }
1650
+
1651
+    /**
1652
+     * change file metadata
1653
+     *
1654
+     * @param string $path
1655
+     * @param array|\OCP\Files\FileInfo $data
1656
+     * @return int
1657
+     *
1658
+     * returns the fileid of the updated file
1659
+     */
1660
+    public function putFileInfo($path, $data) {
1661
+        $this->assertPathLength($path);
1662
+        if ($data instanceof FileInfo) {
1663
+            $data = $data->getData();
1664
+        }
1665
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1666
+        /**
1667
+         * @var Storage $storage
1668
+         * @var string $internalPath
1669
+         */
1670
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1671
+        if ($storage) {
1672
+            $cache = $storage->getCache($path);
1673
+
1674
+            if (!$cache->inCache($internalPath)) {
1675
+                $scanner = $storage->getScanner($internalPath);
1676
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1677
+            }
1678
+
1679
+            return $cache->put($internalPath, $data);
1680
+        } else {
1681
+            return -1;
1682
+        }
1683
+    }
1684
+
1685
+    /**
1686
+     * search for files with the name matching $query
1687
+     *
1688
+     * @param string $query
1689
+     * @return FileInfo[]
1690
+     */
1691
+    public function search($query) {
1692
+        return $this->searchCommon('search', ['%' . $query . '%']);
1693
+    }
1694
+
1695
+    /**
1696
+     * search for files with the name matching $query
1697
+     *
1698
+     * @param string $query
1699
+     * @return FileInfo[]
1700
+     */
1701
+    public function searchRaw($query) {
1702
+        return $this->searchCommon('search', [$query]);
1703
+    }
1704
+
1705
+    /**
1706
+     * search for files by mimetype
1707
+     *
1708
+     * @param string $mimetype
1709
+     * @return FileInfo[]
1710
+     */
1711
+    public function searchByMime($mimetype) {
1712
+        return $this->searchCommon('searchByMime', [$mimetype]);
1713
+    }
1714
+
1715
+    /**
1716
+     * search for files by tag
1717
+     *
1718
+     * @param string|int $tag name or tag id
1719
+     * @param string $userId owner of the tags
1720
+     * @return FileInfo[]
1721
+     */
1722
+    public function searchByTag($tag, $userId) {
1723
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1724
+    }
1725
+
1726
+    /**
1727
+     * @param string $method cache method
1728
+     * @param array $args
1729
+     * @return FileInfo[]
1730
+     */
1731
+    private function searchCommon($method, $args) {
1732
+        $files = [];
1733
+        $rootLength = strlen($this->fakeRoot);
1734
+
1735
+        $mount = $this->getMount('');
1736
+        $mountPoint = $mount->getMountPoint();
1737
+        $storage = $mount->getStorage();
1738
+        $userManager = \OC::$server->getUserManager();
1739
+        if ($storage) {
1740
+            $cache = $storage->getCache('');
1741
+
1742
+            $results = call_user_func_array([$cache, $method], $args);
1743
+            foreach ($results as $result) {
1744
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1745
+                    $internalPath = $result['path'];
1746
+                    $path = $mountPoint . $result['path'];
1747
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1748
+                    $ownerId = $storage->getOwner($internalPath);
1749
+                    if ($ownerId !== false) {
1750
+                        $owner = $userManager->get($ownerId);
1751
+                    } else {
1752
+                        $owner = null;
1753
+                    }
1754
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1755
+                }
1756
+            }
1757
+
1758
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1759
+            foreach ($mounts as $mount) {
1760
+                $mountPoint = $mount->getMountPoint();
1761
+                $storage = $mount->getStorage();
1762
+                if ($storage) {
1763
+                    $cache = $storage->getCache('');
1764
+
1765
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1766
+                    $results = call_user_func_array([$cache, $method], $args);
1767
+                    if ($results) {
1768
+                        foreach ($results as $result) {
1769
+                            $internalPath = $result['path'];
1770
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1771
+                            $path = rtrim($mountPoint . $internalPath, '/');
1772
+                            $ownerId = $storage->getOwner($internalPath);
1773
+                            if ($ownerId !== false) {
1774
+                                $owner = $userManager->get($ownerId);
1775
+                            } else {
1776
+                                $owner = null;
1777
+                            }
1778
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1779
+                        }
1780
+                    }
1781
+                }
1782
+            }
1783
+        }
1784
+        return $files;
1785
+    }
1786
+
1787
+    /**
1788
+     * Get the owner for a file or folder
1789
+     *
1790
+     * @throws NotFoundException
1791
+     */
1792
+    public function getOwner(string $path): string {
1793
+        $info = $this->getFileInfo($path);
1794
+        if (!$info) {
1795
+            throw new NotFoundException($path . ' not found while trying to get owner');
1796
+        }
1797
+
1798
+        if ($info->getOwner() === null) {
1799
+            throw new NotFoundException($path . ' has no owner');
1800
+        }
1801
+
1802
+        return $info->getOwner()->getUID();
1803
+    }
1804
+
1805
+    /**
1806
+     * get the ETag for a file or folder
1807
+     *
1808
+     * @param string $path
1809
+     * @return string|false
1810
+     */
1811
+    public function getETag($path) {
1812
+        [$storage, $internalPath] = $this->resolvePath($path);
1813
+        if ($storage) {
1814
+            return $storage->getETag($internalPath);
1815
+        } else {
1816
+            return false;
1817
+        }
1818
+    }
1819
+
1820
+    /**
1821
+     * Get the path of a file by id, relative to the view
1822
+     *
1823
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1824
+     *
1825
+     * @param int $id
1826
+     * @param int|null $storageId
1827
+     * @return string
1828
+     * @throws NotFoundException
1829
+     */
1830
+    public function getPath($id, ?int $storageId = null) {
1831
+        $id = (int)$id;
1832
+        $manager = Filesystem::getMountManager();
1833
+        $mounts = $manager->findIn($this->fakeRoot);
1834
+        $mounts[] = $manager->find($this->fakeRoot);
1835
+        $mounts = array_filter($mounts);
1836
+        // reverse the array, so we start with the storage this view is in
1837
+        // which is the most likely to contain the file we're looking for
1838
+        $mounts = array_reverse($mounts);
1839
+
1840
+        // put non-shared mounts in front of the shared mount
1841
+        // this prevents unneeded recursion into shares
1842
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1843
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1844
+        });
1845
+
1846
+        if (!is_null($storageId)) {
1847
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1848
+                return $mount->getNumericStorageId() === $storageId;
1849
+            });
1850
+        }
1851
+
1852
+        foreach ($mounts as $mount) {
1853
+            /**
1854
+             * @var \OC\Files\Mount\MountPoint $mount
1855
+             */
1856
+            if ($mount->getStorage()) {
1857
+                $cache = $mount->getStorage()->getCache();
1858
+                $internalPath = $cache->getPathById($id);
1859
+                if (is_string($internalPath)) {
1860
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1861
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1862
+                        return $path;
1863
+                    }
1864
+                }
1865
+            }
1866
+        }
1867
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1868
+    }
1869
+
1870
+    /**
1871
+     * @param string $path
1872
+     * @throws InvalidPathException
1873
+     */
1874
+    private function assertPathLength($path): void {
1875
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1876
+        // Check for the string length - performed using isset() instead of strlen()
1877
+        // because isset() is about 5x-40x faster.
1878
+        if (isset($path[$maxLen])) {
1879
+            $pathLen = strlen($path);
1880
+            throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1881
+        }
1882
+    }
1883
+
1884
+    /**
1885
+     * check if it is allowed to move a mount point to a given target.
1886
+     * It is not allowed to move a mount point into a different mount point or
1887
+     * into an already shared folder
1888
+     */
1889
+    private function targetIsNotShared(string $user, string $targetPath): bool {
1890
+        $providers = [
1891
+            IShare::TYPE_USER,
1892
+            IShare::TYPE_GROUP,
1893
+            IShare::TYPE_EMAIL,
1894
+            IShare::TYPE_CIRCLE,
1895
+            IShare::TYPE_ROOM,
1896
+            IShare::TYPE_DECK,
1897
+            IShare::TYPE_SCIENCEMESH
1898
+        ];
1899
+        $shareManager = Server::get(IManager::class);
1900
+        /** @var IShare[] $shares */
1901
+        $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1902
+            return $shareManager->getSharesBy($user, $type);
1903
+        }, $providers));
1904
+
1905
+        foreach ($shares as $share) {
1906
+            $sharedPath = $share->getNode()->getPath();
1907
+            if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1908
+                $this->logger->debug(
1909
+                    'It is not allowed to move one mount point into a shared folder',
1910
+                    ['app' => 'files']);
1911
+                return false;
1912
+            }
1913
+        }
1914
+
1915
+        return true;
1916
+    }
1917
+
1918
+    /**
1919
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1920
+     */
1921
+    private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1922
+        $mount = $this->getMount($path);
1923
+        $storage = $mount->getStorage();
1924
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1925
+        $ownerId = $storage->getOwner($internalPath);
1926
+        if ($ownerId !== false) {
1927
+            $owner = Server::get(IUserManager::class)->get($ownerId);
1928
+        } else {
1929
+            $owner = null;
1930
+        }
1931
+        return new FileInfo(
1932
+            $this->getAbsolutePath($path),
1933
+            $storage,
1934
+            $internalPath,
1935
+            [
1936
+                'fileid' => null,
1937
+                'mimetype' => $storage->getMimeType($internalPath),
1938
+                'name' => basename($path),
1939
+                'etag' => null,
1940
+                'size' => $storage->filesize($internalPath),
1941
+                'mtime' => $storage->filemtime($internalPath),
1942
+                'encrypted' => false,
1943
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1944
+            ],
1945
+            $mount,
1946
+            $owner
1947
+        );
1948
+    }
1949
+
1950
+    /**
1951
+     * @param string $path
1952
+     * @param string $fileName
1953
+     * @param bool $readonly Check only if the path is allowed for read-only access
1954
+     * @throws InvalidPathException
1955
+     */
1956
+    public function verifyPath($path, $fileName, $readonly = false): void {
1957
+        // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1958
+        if (!Filesystem::isValidPath($path ?: '/')) {
1959
+            $l = \OCP\Util::getL10N('lib');
1960
+            throw new InvalidPathException($l->t('Path contains invalid segments'));
1961
+        }
1962
+
1963
+        // Short cut for read-only validation
1964
+        if ($readonly) {
1965
+            $validator = Server::get(FilenameValidator::class);
1966
+            if ($validator->isForbidden($fileName)) {
1967
+                $l = \OCP\Util::getL10N('lib');
1968
+                throw new InvalidPathException($l->t('Filename is a reserved word'));
1969
+            }
1970
+            return;
1971
+        }
1972
+
1973
+        try {
1974
+            /** @type \OCP\Files\Storage $storage */
1975
+            [$storage, $internalPath] = $this->resolvePath($path);
1976
+            $storage->verifyPath($internalPath, $fileName);
1977
+        } catch (ReservedWordException $ex) {
1978
+            $l = \OCP\Util::getL10N('lib');
1979
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1980
+        } catch (InvalidCharacterInPathException $ex) {
1981
+            $l = \OCP\Util::getL10N('lib');
1982
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1983
+        } catch (FileNameTooLongException $ex) {
1984
+            $l = \OCP\Util::getL10N('lib');
1985
+            throw new InvalidPathException($l->t('Filename is too long'));
1986
+        } catch (InvalidDirectoryException $ex) {
1987
+            $l = \OCP\Util::getL10N('lib');
1988
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1989
+        } catch (EmptyFileNameException $ex) {
1990
+            $l = \OCP\Util::getL10N('lib');
1991
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1992
+        }
1993
+    }
1994
+
1995
+    /**
1996
+     * get all parent folders of $path
1997
+     *
1998
+     * @param string $path
1999
+     * @return string[]
2000
+     */
2001
+    private function getParents($path) {
2002
+        $path = trim($path, '/');
2003
+        if (!$path) {
2004
+            return [];
2005
+        }
2006
+
2007
+        $parts = explode('/', $path);
2008
+
2009
+        // remove the single file
2010
+        array_pop($parts);
2011
+        $result = ['/'];
2012
+        $resultPath = '';
2013
+        foreach ($parts as $part) {
2014
+            if ($part) {
2015
+                $resultPath .= '/' . $part;
2016
+                $result[] = $resultPath;
2017
+            }
2018
+        }
2019
+        return $result;
2020
+    }
2021
+
2022
+    /**
2023
+     * Returns the mount point for which to lock
2024
+     *
2025
+     * @param string $absolutePath absolute path
2026
+     * @param bool $useParentMount true to return parent mount instead of whatever
2027
+     *                             is mounted directly on the given path, false otherwise
2028
+     * @return IMountPoint mount point for which to apply locks
2029
+     */
2030
+    private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2031
+        $mount = Filesystem::getMountManager()->find($absolutePath);
2032
+
2033
+        if ($useParentMount) {
2034
+            // find out if something is mounted directly on the path
2035
+            $internalPath = $mount->getInternalPath($absolutePath);
2036
+            if ($internalPath === '') {
2037
+                // resolve the parent mount instead
2038
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2039
+            }
2040
+        }
2041
+
2042
+        return $mount;
2043
+    }
2044
+
2045
+    /**
2046
+     * Lock the given path
2047
+     *
2048
+     * @param string $path the path of the file to lock, relative to the view
2049
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2050
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2051
+     *
2052
+     * @return bool False if the path is excluded from locking, true otherwise
2053
+     * @throws LockedException if the path is already locked
2054
+     */
2055
+    private function lockPath($path, $type, $lockMountPoint = false) {
2056
+        $absolutePath = $this->getAbsolutePath($path);
2057
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2058
+        if (!$this->shouldLockFile($absolutePath)) {
2059
+            return false;
2060
+        }
2061
+
2062
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2063
+        try {
2064
+            $storage = $mount->getStorage();
2065
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2066
+                $storage->acquireLock(
2067
+                    $mount->getInternalPath($absolutePath),
2068
+                    $type,
2069
+                    $this->lockingProvider
2070
+                );
2071
+            }
2072
+        } catch (LockedException $e) {
2073
+            // rethrow with the human-readable path
2074
+            throw new LockedException(
2075
+                $path,
2076
+                $e,
2077
+                $e->getExistingLock()
2078
+            );
2079
+        }
2080
+
2081
+        return true;
2082
+    }
2083
+
2084
+    /**
2085
+     * Change the lock type
2086
+     *
2087
+     * @param string $path the path of the file to lock, relative to the view
2088
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2089
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2090
+     *
2091
+     * @return bool False if the path is excluded from locking, true otherwise
2092
+     * @throws LockedException if the path is already locked
2093
+     */
2094
+    public function changeLock($path, $type, $lockMountPoint = false) {
2095
+        $path = Filesystem::normalizePath($path);
2096
+        $absolutePath = $this->getAbsolutePath($path);
2097
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2098
+        if (!$this->shouldLockFile($absolutePath)) {
2099
+            return false;
2100
+        }
2101
+
2102
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2103
+        try {
2104
+            $storage = $mount->getStorage();
2105
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2106
+                $storage->changeLock(
2107
+                    $mount->getInternalPath($absolutePath),
2108
+                    $type,
2109
+                    $this->lockingProvider
2110
+                );
2111
+            }
2112
+        } catch (LockedException $e) {
2113
+            // rethrow with the a human-readable path
2114
+            throw new LockedException(
2115
+                $path,
2116
+                $e,
2117
+                $e->getExistingLock()
2118
+            );
2119
+        }
2120
+
2121
+        return true;
2122
+    }
2123
+
2124
+    /**
2125
+     * Unlock the given path
2126
+     *
2127
+     * @param string $path the path of the file to unlock, relative to the view
2128
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2129
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2130
+     *
2131
+     * @return bool False if the path is excluded from locking, true otherwise
2132
+     * @throws LockedException
2133
+     */
2134
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2135
+        $absolutePath = $this->getAbsolutePath($path);
2136
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2137
+        if (!$this->shouldLockFile($absolutePath)) {
2138
+            return false;
2139
+        }
2140
+
2141
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2142
+        $storage = $mount->getStorage();
2143
+        if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2144
+            $storage->releaseLock(
2145
+                $mount->getInternalPath($absolutePath),
2146
+                $type,
2147
+                $this->lockingProvider
2148
+            );
2149
+        }
2150
+
2151
+        return true;
2152
+    }
2153
+
2154
+    /**
2155
+     * Lock a path and all its parents up to the root of the view
2156
+     *
2157
+     * @param string $path the path of the file to lock relative to the view
2158
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2159
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2160
+     *
2161
+     * @return bool False if the path is excluded from locking, true otherwise
2162
+     * @throws LockedException
2163
+     */
2164
+    public function lockFile($path, $type, $lockMountPoint = false) {
2165
+        $absolutePath = $this->getAbsolutePath($path);
2166
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2167
+        if (!$this->shouldLockFile($absolutePath)) {
2168
+            return false;
2169
+        }
2170
+
2171
+        $this->lockPath($path, $type, $lockMountPoint);
2172
+
2173
+        $parents = $this->getParents($path);
2174
+        foreach ($parents as $parent) {
2175
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2176
+        }
2177
+
2178
+        return true;
2179
+    }
2180
+
2181
+    /**
2182
+     * Unlock a path and all its parents up to the root of the view
2183
+     *
2184
+     * @param string $path the path of the file to lock relative to the view
2185
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2186
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2187
+     *
2188
+     * @return bool False if the path is excluded from locking, true otherwise
2189
+     * @throws LockedException
2190
+     */
2191
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2192
+        $absolutePath = $this->getAbsolutePath($path);
2193
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2194
+        if (!$this->shouldLockFile($absolutePath)) {
2195
+            return false;
2196
+        }
2197
+
2198
+        $this->unlockPath($path, $type, $lockMountPoint);
2199
+
2200
+        $parents = $this->getParents($path);
2201
+        foreach ($parents as $parent) {
2202
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2203
+        }
2204
+
2205
+        return true;
2206
+    }
2207
+
2208
+    /**
2209
+     * Only lock files in data/user/files/
2210
+     *
2211
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2212
+     * @return bool
2213
+     */
2214
+    protected function shouldLockFile($path) {
2215
+        $path = Filesystem::normalizePath($path);
2216
+
2217
+        $pathSegments = explode('/', $path);
2218
+        if (isset($pathSegments[2])) {
2219
+            // E.g.: /username/files/path-to-file
2220
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2221
+        }
2222
+
2223
+        return !str_starts_with($path, '/appdata_');
2224
+    }
2225
+
2226
+    /**
2227
+     * Shortens the given absolute path to be relative to
2228
+     * "$user/files".
2229
+     *
2230
+     * @param string $absolutePath absolute path which is under "files"
2231
+     *
2232
+     * @return string path relative to "files" with trimmed slashes or null
2233
+     *                if the path was NOT relative to files
2234
+     *
2235
+     * @throws \InvalidArgumentException if the given path was not under "files"
2236
+     * @since 8.1.0
2237
+     */
2238
+    public function getPathRelativeToFiles($absolutePath) {
2239
+        $path = Filesystem::normalizePath($absolutePath);
2240
+        $parts = explode('/', trim($path, '/'), 3);
2241
+        // "$user", "files", "path/to/dir"
2242
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2243
+            $this->logger->error(
2244
+                '$absolutePath must be relative to "files", value is "{absolutePath}"',
2245
+                [
2246
+                    'absolutePath' => $absolutePath,
2247
+                ]
2248
+            );
2249
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2250
+        }
2251
+        if (isset($parts[2])) {
2252
+            return $parts[2];
2253
+        }
2254
+        return '';
2255
+    }
2256
+
2257
+    /**
2258
+     * @param string $filename
2259
+     * @return array
2260
+     * @throws \OC\User\NoUserException
2261
+     * @throws NotFoundException
2262
+     */
2263
+    public function getUidAndFilename($filename) {
2264
+        $info = $this->getFileInfo($filename);
2265
+        if (!$info instanceof \OCP\Files\FileInfo) {
2266
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2267
+        }
2268
+        $uid = $info->getOwner()->getUID();
2269
+        if ($uid != \OC_User::getUser()) {
2270
+            Filesystem::initMountPoints($uid);
2271
+            $ownerView = new View('/' . $uid . '/files');
2272
+            try {
2273
+                $filename = $ownerView->getPath($info['fileid']);
2274
+            } catch (NotFoundException $e) {
2275
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2276
+            }
2277
+        }
2278
+        return [$uid, $filename];
2279
+    }
2280
+
2281
+    /**
2282
+     * Creates parent non-existing folders
2283
+     *
2284
+     * @param string $filePath
2285
+     * @return bool
2286
+     */
2287
+    private function createParentDirectories($filePath) {
2288
+        $directoryParts = explode('/', $filePath);
2289
+        $directoryParts = array_filter($directoryParts);
2290
+        foreach ($directoryParts as $key => $part) {
2291
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2292
+            $currentPath = '/' . implode('/', $currentPathElements);
2293
+            if ($this->is_file($currentPath)) {
2294
+                return false;
2295
+            }
2296
+            if (!$this->file_exists($currentPath)) {
2297
+                $this->mkdir($currentPath);
2298
+            }
2299
+        }
2300
+
2301
+        return true;
2302
+    }
2303 2303
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -93,9 +93,9 @@  discard block
 block discarded – undo
93 93
 			$path = '/';
94 94
 		}
95 95
 		if ($path[0] !== '/') {
96
-			$path = '/' . $path;
96
+			$path = '/'.$path;
97 97
 		}
98
-		return $this->fakeRoot . $path;
98
+		return $this->fakeRoot.$path;
99 99
 	}
100 100
 
101 101
 	/**
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 	public function chroot($fakeRoot): void {
107 107
 		if (!$fakeRoot == '') {
108 108
 			if ($fakeRoot[0] !== '/') {
109
-				$fakeRoot = '/' . $fakeRoot;
109
+				$fakeRoot = '/'.$fakeRoot;
110 110
 			}
111 111
 		}
112 112
 		$this->fakeRoot = $fakeRoot;
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 		}
136 136
 
137 137
 		// missing slashes can cause wrong matches!
138
-		$root = rtrim($this->fakeRoot, '/') . '/';
138
+		$root = rtrim($this->fakeRoot, '/').'/';
139 139
 
140 140
 		if (!str_starts_with($path, $root)) {
141 141
 			return null;
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	 *
193 193
 	 * @param string $path
194 194
 	 */
195
-	public function getLocalFile($path): string|false {
195
+	public function getLocalFile($path): string | false {
196 196
 		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
197 197
 		$path = $this->getAbsolutePath($path);
198 198
 		[$storage, $internalPath] = Filesystem::resolvePath($path);
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		if ($mount instanceof MoveableMount) {
223 223
 			// cut of /user/files to get the relative path to data/user/files
224 224
 			$pathParts = explode('/', $path, 4);
225
-			$relPath = '/' . $pathParts[3];
225
+			$relPath = '/'.$pathParts[3];
226 226
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
227 227
 			\OC_Hook::emit(
228 228
 				Filesystem::CLASSNAME, 'umount',
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 		}
667 667
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
668 668
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
669
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
669
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
670 670
 		if ($mount->getInternalPath($absolutePath) === '') {
671 671
 			return $this->removeMount($mount, $absolutePath);
672 672
 		}
@@ -709,7 +709,7 @@  discard block
 block discarded – undo
709 709
 		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
710 710
 		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
711 711
 
712
-		if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
712
+		if (str_starts_with($absolutePath2, $absolutePath1.'/')) {
713 713
 			throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
714 714
 		}
715 715
 
@@ -1027,7 +1027,7 @@  discard block
 block discarded – undo
1027 1027
 				$hooks[] = 'write';
1028 1028
 				break;
1029 1029
 			default:
1030
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1030
+				$this->logger->error('invalid mode ('.$mode.') for '.$path, ['app' => 'core']);
1031 1031
 		}
1032 1032
 
1033 1033
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1051,7 +1051,7 @@  discard block
 block discarded – undo
1051 1051
 	 * @param string $path
1052 1052
 	 * @throws InvalidPathException
1053 1053
 	 */
1054
-	public function toTmpFile($path): string|false {
1054
+	public function toTmpFile($path): string | false {
1055 1055
 		$this->assertPathLength($path);
1056 1056
 		if (Filesystem::isValidPath($path)) {
1057 1057
 			$source = $this->fopen($path, 'r');
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
 	 * @param string $path
1127 1127
 	 * @param bool $raw
1128 1128
 	 */
1129
-	public function hash($type, $path, $raw = false): string|bool {
1129
+	public function hash($type, $path, $raw = false): string | bool {
1130 1130
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
1131 1131
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1132 1132
 		if (Filesystem::isValidPath($path)) {
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
 				);
1143 1143
 			}
1144 1144
 			/** @var Storage|null $storage */
1145
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1145
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1146 1146
 			if ($storage) {
1147 1147
 				return $storage->hash($type, $internalPath, $raw);
1148 1148
 			}
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
 			}
1193 1193
 
1194 1194
 			$run = $this->runHooks($hooks, $path);
1195
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1195
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1196 1196
 			if ($run && $storage) {
1197 1197
 				/** @var Storage $storage */
1198 1198
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
@@ -1240,7 +1240,7 @@  discard block
 block discarded – undo
1240 1240
 					$unlockLater = true;
1241 1241
 					// make sure our unlocking callback will still be called if connection is aborted
1242 1242
 					ignore_user_abort(true);
1243
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1243
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1244 1244
 						if (in_array('write', $hooks)) {
1245 1245
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1246 1246
 						} elseif (in_array('read', $hooks)) {
@@ -1302,7 +1302,7 @@  discard block
 block discarded – undo
1302 1302
 			return true;
1303 1303
 		}
1304 1304
 
1305
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1305
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1306 1306
 	}
1307 1307
 
1308 1308
 	/**
@@ -1321,7 +1321,7 @@  discard block
 block discarded – undo
1321 1321
 				if ($hook != 'read') {
1322 1322
 					\OC_Hook::emit(
1323 1323
 						Filesystem::CLASSNAME,
1324
-						$prefix . $hook,
1324
+						$prefix.$hook,
1325 1325
 						[
1326 1326
 							Filesystem::signal_param_run => &$run,
1327 1327
 							Filesystem::signal_param_path => $path
@@ -1330,7 +1330,7 @@  discard block
 block discarded – undo
1330 1330
 				} elseif (!$post) {
1331 1331
 					\OC_Hook::emit(
1332 1332
 						Filesystem::CLASSNAME,
1333
-						$prefix . $hook,
1333
+						$prefix.$hook,
1334 1334
 						[
1335 1335
 							Filesystem::signal_param_path => $path
1336 1336
 						]
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
 			return false;
1415 1415
 		}
1416 1416
 		$relativePath = $path;
1417
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1417
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1418 1418
 
1419 1419
 		$mount = Filesystem::getMountManager()->find($path);
1420 1420
 		$storage = $mount->getStorage();
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
 
1456 1456
 			return $info;
1457 1457
 		} else {
1458
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1458
+			$this->logger->warning('Storage not valid for mountpoint: '.$mount->getMountPoint(), ['app' => 'core']);
1459 1459
 		}
1460 1460
 
1461 1461
 		return false;
@@ -1466,7 +1466,7 @@  discard block
 block discarded – undo
1466 1466
 	 */
1467 1467
 	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1468 1468
 		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1469
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1469
+		$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1470 1470
 			return !($extOnly && $mount instanceof SharedMount);
1471 1471
 		}));
1472 1472
 	}
@@ -1514,13 +1514,13 @@  discard block
 block discarded – undo
1514 1514
 
1515 1515
 		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1516 1516
 
1517
-		$fileNames = array_map(function (ICacheEntry $content) {
1517
+		$fileNames = array_map(function(ICacheEntry $content) {
1518 1518
 			return $content->getName();
1519 1519
 		}, $contents);
1520 1520
 		/**
1521 1521
 		 * @var \OC\Files\FileInfo[] $fileInfos
1522 1522
 		 */
1523
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1523
+		$fileInfos = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1524 1524
 			if ($sharingDisabled) {
1525 1525
 				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1526 1526
 			}
@@ -1530,7 +1530,7 @@  discard block
 block discarded – undo
1530 1530
 			} else {
1531 1531
 				$owner = null;
1532 1532
 			}
1533
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1533
+			return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1534 1534
 		}, $contents);
1535 1535
 		$files = array_combine($fileNames, $fileInfos);
1536 1536
 
@@ -1539,7 +1539,7 @@  discard block
 block discarded – undo
1539 1539
 
1540 1540
 		// make sure nested mounts are sorted after their parent mounts
1541 1541
 		// otherwise doesn't propagate the etag across storage boundaries correctly
1542
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1542
+		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1543 1543
 			return $a->getMountPoint() <=> $b->getMountPoint();
1544 1544
 		});
1545 1545
 
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
 						continue;
1562 1562
 					} catch (\Exception $e) {
1563 1563
 						// sometimes when the storage is not available it can be any exception
1564
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1564
+						$this->logger->error('Exception while scanning storage "'.$subStorage->getId().'"', [
1565 1565
 							'exception' => $e,
1566 1566
 							'app' => 'core',
1567 1567
 						]);
@@ -1579,14 +1579,14 @@  discard block
 block discarded – undo
1579 1579
 						// Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1580 1580
 						if (!isset($files[$entryName])) {
1581 1581
 							try {
1582
-								[$storage, ] = $this->resolvePath($path . '/' . $entryName);
1582
+								[$storage, ] = $this->resolvePath($path.'/'.$entryName);
1583 1583
 								// make sure we can create the mountpoint folder, even if the user has a quota of 0
1584 1584
 								if ($storage->instanceOfStorage(Quota::class)) {
1585 1585
 									$storage->enableQuota(false);
1586 1586
 								}
1587 1587
 
1588
-								if ($this->mkdir($path . '/' . $entryName) !== false) {
1589
-									$info = $this->getFileInfo($path . '/' . $entryName);
1588
+								if ($this->mkdir($path.'/'.$entryName) !== false) {
1589
+									$info = $this->getFileInfo($path.'/'.$entryName);
1590 1590
 									if ($info !== false) {
1591 1591
 										$files[$entryName] = $info;
1592 1592
 									}
@@ -1597,7 +1597,7 @@  discard block
 block discarded – undo
1597 1597
 								}
1598 1598
 							} catch (\Exception $e) {
1599 1599
 								// Creating the parent folder might not be possible, for example due to a lack of permissions.
1600
-								$this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1600
+								$this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path.'/'.$entryName]);
1601 1601
 							}
1602 1602
 						}
1603 1603
 
@@ -1616,7 +1616,7 @@  discard block
 block discarded – undo
1616 1616
 							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1617 1617
 						}
1618 1618
 
1619
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1619
+						$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1620 1620
 
1621 1621
 						// if sharing was disabled for the user we remove the share permissions
1622 1622
 						if ($sharingDisabled) {
@@ -1629,14 +1629,14 @@  discard block
 block discarded – undo
1629 1629
 						} else {
1630 1630
 							$owner = null;
1631 1631
 						}
1632
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1632
+						$files[$rootEntry->getName()] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1633 1633
 					}
1634 1634
 				}
1635 1635
 			}
1636 1636
 		}
1637 1637
 
1638 1638
 		if ($mimetype_filter) {
1639
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1639
+			$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1640 1640
 				if (strpos($mimetype_filter, '/')) {
1641 1641
 					return $file->getMimetype() === $mimetype_filter;
1642 1642
 				} else {
@@ -1662,7 +1662,7 @@  discard block
 block discarded – undo
1662 1662
 		if ($data instanceof FileInfo) {
1663 1663
 			$data = $data->getData();
1664 1664
 		}
1665
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1665
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1666 1666
 		/**
1667 1667
 		 * @var Storage $storage
1668 1668
 		 * @var string $internalPath
@@ -1689,7 +1689,7 @@  discard block
 block discarded – undo
1689 1689
 	 * @return FileInfo[]
1690 1690
 	 */
1691 1691
 	public function search($query) {
1692
-		return $this->searchCommon('search', ['%' . $query . '%']);
1692
+		return $this->searchCommon('search', ['%'.$query.'%']);
1693 1693
 	}
1694 1694
 
1695 1695
 	/**
@@ -1741,10 +1741,10 @@  discard block
 block discarded – undo
1741 1741
 
1742 1742
 			$results = call_user_func_array([$cache, $method], $args);
1743 1743
 			foreach ($results as $result) {
1744
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1744
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1745 1745
 					$internalPath = $result['path'];
1746
-					$path = $mountPoint . $result['path'];
1747
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1746
+					$path = $mountPoint.$result['path'];
1747
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1748 1748
 					$ownerId = $storage->getOwner($internalPath);
1749 1749
 					if ($ownerId !== false) {
1750 1750
 						$owner = $userManager->get($ownerId);
@@ -1767,8 +1767,8 @@  discard block
 block discarded – undo
1767 1767
 					if ($results) {
1768 1768
 						foreach ($results as $result) {
1769 1769
 							$internalPath = $result['path'];
1770
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1771
-							$path = rtrim($mountPoint . $internalPath, '/');
1770
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1771
+							$path = rtrim($mountPoint.$internalPath, '/');
1772 1772
 							$ownerId = $storage->getOwner($internalPath);
1773 1773
 							if ($ownerId !== false) {
1774 1774
 								$owner = $userManager->get($ownerId);
@@ -1792,11 +1792,11 @@  discard block
 block discarded – undo
1792 1792
 	public function getOwner(string $path): string {
1793 1793
 		$info = $this->getFileInfo($path);
1794 1794
 		if (!$info) {
1795
-			throw new NotFoundException($path . ' not found while trying to get owner');
1795
+			throw new NotFoundException($path.' not found while trying to get owner');
1796 1796
 		}
1797 1797
 
1798 1798
 		if ($info->getOwner() === null) {
1799
-			throw new NotFoundException($path . ' has no owner');
1799
+			throw new NotFoundException($path.' has no owner');
1800 1800
 		}
1801 1801
 
1802 1802
 		return $info->getOwner()->getUID();
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
 	 * @throws NotFoundException
1829 1829
 	 */
1830 1830
 	public function getPath($id, ?int $storageId = null) {
1831
-		$id = (int)$id;
1831
+		$id = (int) $id;
1832 1832
 		$manager = Filesystem::getMountManager();
1833 1833
 		$mounts = $manager->findIn($this->fakeRoot);
1834 1834
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1839,12 +1839,12 @@  discard block
 block discarded – undo
1839 1839
 
1840 1840
 		// put non-shared mounts in front of the shared mount
1841 1841
 		// this prevents unneeded recursion into shares
1842
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1842
+		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1843 1843
 			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1844 1844
 		});
1845 1845
 
1846 1846
 		if (!is_null($storageId)) {
1847
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1847
+			$mounts = array_filter($mounts, function(IMountPoint $mount) use ($storageId) {
1848 1848
 				return $mount->getNumericStorageId() === $storageId;
1849 1849
 			});
1850 1850
 		}
@@ -1857,7 +1857,7 @@  discard block
 block discarded – undo
1857 1857
 				$cache = $mount->getStorage()->getCache();
1858 1858
 				$internalPath = $cache->getPathById($id);
1859 1859
 				if (is_string($internalPath)) {
1860
-					$fullPath = $mount->getMountPoint() . $internalPath;
1860
+					$fullPath = $mount->getMountPoint().$internalPath;
1861 1861
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1862 1862
 						return $path;
1863 1863
 					}
@@ -1898,13 +1898,13 @@  discard block
 block discarded – undo
1898 1898
 		];
1899 1899
 		$shareManager = Server::get(IManager::class);
1900 1900
 		/** @var IShare[] $shares */
1901
-		$shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1901
+		$shares = array_merge(...array_map(function(int $type) use ($shareManager, $user) {
1902 1902
 			return $shareManager->getSharesBy($user, $type);
1903 1903
 		}, $providers));
1904 1904
 
1905 1905
 		foreach ($shares as $share) {
1906 1906
 			$sharedPath = $share->getNode()->getPath();
1907
-			if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1907
+			if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath.'/')) {
1908 1908
 				$this->logger->debug(
1909 1909
 					'It is not allowed to move one mount point into a shared folder',
1910 1910
 					['app' => 'files']);
@@ -2012,7 +2012,7 @@  discard block
 block discarded – undo
2012 2012
 		$resultPath = '';
2013 2013
 		foreach ($parts as $part) {
2014 2014
 			if ($part) {
2015
-				$resultPath .= '/' . $part;
2015
+				$resultPath .= '/'.$part;
2016 2016
 				$result[] = $resultPath;
2017 2017
 			}
2018 2018
 		}
@@ -2263,16 +2263,16 @@  discard block
 block discarded – undo
2263 2263
 	public function getUidAndFilename($filename) {
2264 2264
 		$info = $this->getFileInfo($filename);
2265 2265
 		if (!$info instanceof \OCP\Files\FileInfo) {
2266
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2266
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2267 2267
 		}
2268 2268
 		$uid = $info->getOwner()->getUID();
2269 2269
 		if ($uid != \OC_User::getUser()) {
2270 2270
 			Filesystem::initMountPoints($uid);
2271
-			$ownerView = new View('/' . $uid . '/files');
2271
+			$ownerView = new View('/'.$uid.'/files');
2272 2272
 			try {
2273 2273
 				$filename = $ownerView->getPath($info['fileid']);
2274 2274
 			} catch (NotFoundException $e) {
2275
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2275
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2276 2276
 			}
2277 2277
 		}
2278 2278
 		return [$uid, $filename];
@@ -2289,7 +2289,7 @@  discard block
 block discarded – undo
2289 2289
 		$directoryParts = array_filter($directoryParts);
2290 2290
 		foreach ($directoryParts as $key => $part) {
2291 2291
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2292
-			$currentPath = '/' . implode('/', $currentPathElements);
2292
+			$currentPath = '/'.implode('/', $currentPathElements);
2293 2293
 			if ($this->is_file($currentPath)) {
2294 2294
 				return false;
2295 2295
 			}
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Quota.php 1 patch
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -14,195 +14,195 @@
 block discarded – undo
14 14
 use OCP\Files\Storage\IStorage;
15 15
 
16 16
 class Quota extends Wrapper {
17
-	/** @var callable|null */
18
-	protected $quotaCallback;
19
-	/** @var int|float|null int on 64bits, float on 32bits for bigint */
20
-	protected int|float|null $quota;
21
-	protected string $sizeRoot;
22
-	private SystemConfig $config;
23
-	private bool $quotaIncludeExternalStorage;
24
-	private bool $enabled = true;
25
-
26
-	/**
27
-	 * @param array $parameters
28
-	 */
29
-	public function __construct(array $parameters) {
30
-		parent::__construct($parameters);
31
-		$this->quota = $parameters['quota'] ?? null;
32
-		$this->quotaCallback = $parameters['quotaCallback'] ?? null;
33
-		$this->sizeRoot = $parameters['root'] ?? '';
34
-		$this->quotaIncludeExternalStorage = $parameters['include_external_storage'] ?? false;
35
-	}
36
-
37
-	public function getQuota(): int|float {
38
-		if ($this->quota === null) {
39
-			$quotaCallback = $this->quotaCallback;
40
-			if ($quotaCallback === null) {
41
-				throw new \Exception('No quota or quota callback provider');
42
-			}
43
-			$this->quota = $quotaCallback();
44
-		}
45
-
46
-		return $this->quota;
47
-	}
48
-
49
-	private function hasQuota(): bool {
50
-		if (!$this->enabled) {
51
-			return false;
52
-		}
53
-		return $this->getQuota() !== FileInfo::SPACE_UNLIMITED;
54
-	}
55
-
56
-	protected function getSize(string $path, ?IStorage $storage = null): int|float {
57
-		if ($this->quotaIncludeExternalStorage) {
58
-			$rootInfo = Filesystem::getFileInfo('', 'ext');
59
-			if ($rootInfo) {
60
-				return $rootInfo->getSize(true);
61
-			}
62
-			return FileInfo::SPACE_NOT_COMPUTED;
63
-		} else {
64
-			$cache = is_null($storage) ? $this->getCache() : $storage->getCache();
65
-			$data = $cache->get($path);
66
-			if ($data instanceof ICacheEntry && isset($data['size'])) {
67
-				return $data['size'];
68
-			} else {
69
-				return FileInfo::SPACE_NOT_COMPUTED;
70
-			}
71
-		}
72
-	}
73
-
74
-	public function free_space(string $path): int|float|false {
75
-		if (!$this->hasQuota()) {
76
-			return $this->storage->free_space($path);
77
-		}
78
-		if ($this->getQuota() < 0 || str_starts_with($path, 'cache') || str_starts_with($path, 'uploads')) {
79
-			return $this->storage->free_space($path);
80
-		} else {
81
-			$used = $this->getSize($this->sizeRoot);
82
-			if ($used < 0) {
83
-				return FileInfo::SPACE_NOT_COMPUTED;
84
-			} else {
85
-				$free = $this->storage->free_space($path);
86
-				$quotaFree = max($this->getQuota() - $used, 0);
87
-				// if free space is known
88
-				$free = $free >= 0 ? min($free, $quotaFree) : $quotaFree;
89
-				return $free;
90
-			}
91
-		}
92
-	}
93
-
94
-	public function file_put_contents(string $path, mixed $data): int|float|false {
95
-		if (!$this->hasQuota()) {
96
-			return $this->storage->file_put_contents($path, $data);
97
-		}
98
-		$free = $this->free_space($path);
99
-		if ($free < 0 || strlen($data) < $free) {
100
-			return $this->storage->file_put_contents($path, $data);
101
-		} else {
102
-			return false;
103
-		}
104
-	}
105
-
106
-	public function copy(string $source, string $target): bool {
107
-		if (!$this->hasQuota()) {
108
-			return $this->storage->copy($source, $target);
109
-		}
110
-		$free = $this->free_space($target);
111
-		if ($free < 0 || $this->getSize($source) < $free) {
112
-			return $this->storage->copy($source, $target);
113
-		} else {
114
-			return false;
115
-		}
116
-	}
117
-
118
-	public function fopen(string $path, string $mode) {
119
-		if (!$this->hasQuota()) {
120
-			return $this->storage->fopen($path, $mode);
121
-		}
122
-		$source = $this->storage->fopen($path, $mode);
123
-
124
-		// don't apply quota for part files
125
-		if (!$this->isPartFile($path)) {
126
-			$free = $this->free_space($path);
127
-			if ($source && (is_int($free) || is_float($free)) && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
128
-				// only apply quota for files, not metadata, trash or others
129
-				if ($this->shouldApplyQuota($path)) {
130
-					return \OC\Files\Stream\Quota::wrap($source, $free);
131
-				}
132
-			}
133
-		}
134
-
135
-		return $source;
136
-	}
137
-
138
-	/**
139
-	 * Checks whether the given path is a part file
140
-	 *
141
-	 * @param string $path Path that may identify a .part file
142
-	 * @note this is needed for reusing keys
143
-	 */
144
-	private function isPartFile(string $path): bool {
145
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
146
-
147
-		return ($extension === 'part');
148
-	}
149
-
150
-	/**
151
-	 * Only apply quota for files, not metadata, trash or others
152
-	 */
153
-	protected function shouldApplyQuota(string $path): bool {
154
-		return str_starts_with(ltrim($path, '/'), 'files/');
155
-	}
156
-
157
-	public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
158
-		if (!$this->hasQuota()) {
159
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
160
-		}
161
-		$free = $this->free_space($targetInternalPath);
162
-		if ($free < 0 || $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
163
-			return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
164
-		} else {
165
-			return false;
166
-		}
167
-	}
168
-
169
-	public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
170
-		if (!$this->hasQuota()) {
171
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
172
-		}
173
-		$free = $this->free_space($targetInternalPath);
174
-		if ($free < 0 || $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
175
-			return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
176
-		} else {
177
-			return false;
178
-		}
179
-	}
180
-
181
-	public function mkdir(string $path): bool {
182
-		if (!$this->hasQuota()) {
183
-			return $this->storage->mkdir($path);
184
-		}
185
-		$free = $this->free_space($path);
186
-		if ($this->shouldApplyQuota($path) && $free == 0) {
187
-			return false;
188
-		}
189
-
190
-		return parent::mkdir($path);
191
-	}
192
-
193
-	public function touch(string $path, ?int $mtime = null): bool {
194
-		if (!$this->hasQuota()) {
195
-			return $this->storage->touch($path, $mtime);
196
-		}
197
-		$free = $this->free_space($path);
198
-		if ($free == 0) {
199
-			return false;
200
-		}
201
-
202
-		return parent::touch($path, $mtime);
203
-	}
204
-
205
-	public function enableQuota(bool $enabled): void {
206
-		$this->enabled = $enabled;
207
-	}
17
+    /** @var callable|null */
18
+    protected $quotaCallback;
19
+    /** @var int|float|null int on 64bits, float on 32bits for bigint */
20
+    protected int|float|null $quota;
21
+    protected string $sizeRoot;
22
+    private SystemConfig $config;
23
+    private bool $quotaIncludeExternalStorage;
24
+    private bool $enabled = true;
25
+
26
+    /**
27
+     * @param array $parameters
28
+     */
29
+    public function __construct(array $parameters) {
30
+        parent::__construct($parameters);
31
+        $this->quota = $parameters['quota'] ?? null;
32
+        $this->quotaCallback = $parameters['quotaCallback'] ?? null;
33
+        $this->sizeRoot = $parameters['root'] ?? '';
34
+        $this->quotaIncludeExternalStorage = $parameters['include_external_storage'] ?? false;
35
+    }
36
+
37
+    public function getQuota(): int|float {
38
+        if ($this->quota === null) {
39
+            $quotaCallback = $this->quotaCallback;
40
+            if ($quotaCallback === null) {
41
+                throw new \Exception('No quota or quota callback provider');
42
+            }
43
+            $this->quota = $quotaCallback();
44
+        }
45
+
46
+        return $this->quota;
47
+    }
48
+
49
+    private function hasQuota(): bool {
50
+        if (!$this->enabled) {
51
+            return false;
52
+        }
53
+        return $this->getQuota() !== FileInfo::SPACE_UNLIMITED;
54
+    }
55
+
56
+    protected function getSize(string $path, ?IStorage $storage = null): int|float {
57
+        if ($this->quotaIncludeExternalStorage) {
58
+            $rootInfo = Filesystem::getFileInfo('', 'ext');
59
+            if ($rootInfo) {
60
+                return $rootInfo->getSize(true);
61
+            }
62
+            return FileInfo::SPACE_NOT_COMPUTED;
63
+        } else {
64
+            $cache = is_null($storage) ? $this->getCache() : $storage->getCache();
65
+            $data = $cache->get($path);
66
+            if ($data instanceof ICacheEntry && isset($data['size'])) {
67
+                return $data['size'];
68
+            } else {
69
+                return FileInfo::SPACE_NOT_COMPUTED;
70
+            }
71
+        }
72
+    }
73
+
74
+    public function free_space(string $path): int|float|false {
75
+        if (!$this->hasQuota()) {
76
+            return $this->storage->free_space($path);
77
+        }
78
+        if ($this->getQuota() < 0 || str_starts_with($path, 'cache') || str_starts_with($path, 'uploads')) {
79
+            return $this->storage->free_space($path);
80
+        } else {
81
+            $used = $this->getSize($this->sizeRoot);
82
+            if ($used < 0) {
83
+                return FileInfo::SPACE_NOT_COMPUTED;
84
+            } else {
85
+                $free = $this->storage->free_space($path);
86
+                $quotaFree = max($this->getQuota() - $used, 0);
87
+                // if free space is known
88
+                $free = $free >= 0 ? min($free, $quotaFree) : $quotaFree;
89
+                return $free;
90
+            }
91
+        }
92
+    }
93
+
94
+    public function file_put_contents(string $path, mixed $data): int|float|false {
95
+        if (!$this->hasQuota()) {
96
+            return $this->storage->file_put_contents($path, $data);
97
+        }
98
+        $free = $this->free_space($path);
99
+        if ($free < 0 || strlen($data) < $free) {
100
+            return $this->storage->file_put_contents($path, $data);
101
+        } else {
102
+            return false;
103
+        }
104
+    }
105
+
106
+    public function copy(string $source, string $target): bool {
107
+        if (!$this->hasQuota()) {
108
+            return $this->storage->copy($source, $target);
109
+        }
110
+        $free = $this->free_space($target);
111
+        if ($free < 0 || $this->getSize($source) < $free) {
112
+            return $this->storage->copy($source, $target);
113
+        } else {
114
+            return false;
115
+        }
116
+    }
117
+
118
+    public function fopen(string $path, string $mode) {
119
+        if (!$this->hasQuota()) {
120
+            return $this->storage->fopen($path, $mode);
121
+        }
122
+        $source = $this->storage->fopen($path, $mode);
123
+
124
+        // don't apply quota for part files
125
+        if (!$this->isPartFile($path)) {
126
+            $free = $this->free_space($path);
127
+            if ($source && (is_int($free) || is_float($free)) && $free >= 0 && $mode !== 'r' && $mode !== 'rb') {
128
+                // only apply quota for files, not metadata, trash or others
129
+                if ($this->shouldApplyQuota($path)) {
130
+                    return \OC\Files\Stream\Quota::wrap($source, $free);
131
+                }
132
+            }
133
+        }
134
+
135
+        return $source;
136
+    }
137
+
138
+    /**
139
+     * Checks whether the given path is a part file
140
+     *
141
+     * @param string $path Path that may identify a .part file
142
+     * @note this is needed for reusing keys
143
+     */
144
+    private function isPartFile(string $path): bool {
145
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
146
+
147
+        return ($extension === 'part');
148
+    }
149
+
150
+    /**
151
+     * Only apply quota for files, not metadata, trash or others
152
+     */
153
+    protected function shouldApplyQuota(string $path): bool {
154
+        return str_starts_with(ltrim($path, '/'), 'files/');
155
+    }
156
+
157
+    public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
158
+        if (!$this->hasQuota()) {
159
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
160
+        }
161
+        $free = $this->free_space($targetInternalPath);
162
+        if ($free < 0 || $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
163
+            return $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
164
+        } else {
165
+            return false;
166
+        }
167
+    }
168
+
169
+    public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
170
+        if (!$this->hasQuota()) {
171
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
172
+        }
173
+        $free = $this->free_space($targetInternalPath);
174
+        if ($free < 0 || $this->getSize($sourceInternalPath, $sourceStorage) < $free) {
175
+            return $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
176
+        } else {
177
+            return false;
178
+        }
179
+    }
180
+
181
+    public function mkdir(string $path): bool {
182
+        if (!$this->hasQuota()) {
183
+            return $this->storage->mkdir($path);
184
+        }
185
+        $free = $this->free_space($path);
186
+        if ($this->shouldApplyQuota($path) && $free == 0) {
187
+            return false;
188
+        }
189
+
190
+        return parent::mkdir($path);
191
+    }
192
+
193
+    public function touch(string $path, ?int $mtime = null): bool {
194
+        if (!$this->hasQuota()) {
195
+            return $this->storage->touch($path, $mtime);
196
+        }
197
+        $free = $this->free_space($path);
198
+        if ($free == 0) {
199
+            return false;
200
+        }
201
+
202
+        return parent::touch($path, $mtime);
203
+    }
204
+
205
+    public function enableQuota(bool $enabled): void {
206
+        $this->enabled = $enabled;
207
+    }
208 208
 }
Please login to merge, or discard this patch.