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