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