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