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