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