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