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