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