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