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