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