Root.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Julius Härtl <jus@bitgrid.net>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Stefan Weil <sw@weilnetz.de>
  15. * @author Vincent Petry <vincent@nextcloud.com>
  16. *
  17. * @license AGPL-3.0
  18. *
  19. * This code is free software: you can redistribute it and/or modify
  20. * it under the terms of the GNU Affero General Public License, version 3,
  21. * as published by the Free Software Foundation.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License, version 3,
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>
  30. *
  31. */
  32. namespace OC\Files\Node;
  33. use OCP\Cache\CappedMemoryCache;
  34. use OC\Files\FileInfo;
  35. use OC\Files\Mount\Manager;
  36. use OC\Files\Mount\MountPoint;
  37. use OC\Files\Utils\PathHelper;
  38. use OC\Files\View;
  39. use OC\Hooks\PublicEmitter;
  40. use OC\User\NoUserException;
  41. use OCP\EventDispatcher\IEventDispatcher;
  42. use OCP\Files\Config\IUserMountCache;
  43. use OCP\Files\Events\Node\FilesystemTornDownEvent;
  44. use OCP\Files\IRootFolder;
  45. use OCP\Files\Mount\IMountPoint;
  46. use OCP\Files\NotFoundException;
  47. use OCP\Files\NotPermittedException;
  48. use OCP\IUser;
  49. use OCP\IUserManager;
  50. use Psr\Log\LoggerInterface;
  51. /**
  52. * Class Root
  53. *
  54. * Hooks available in scope \OC\Files
  55. * - preWrite(\OCP\Files\Node $node)
  56. * - postWrite(\OCP\Files\Node $node)
  57. * - preCreate(\OCP\Files\Node $node)
  58. * - postCreate(\OCP\Files\Node $node)
  59. * - preDelete(\OCP\Files\Node $node)
  60. * - postDelete(\OCP\Files\Node $node)
  61. * - preTouch(\OC\FilesP\Node $node, int $mtime)
  62. * - postTouch(\OCP\Files\Node $node)
  63. * - preCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  64. * - postCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  65. * - preRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  66. * - postRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  67. *
  68. * @package OC\Files\Node
  69. */
  70. class Root extends Folder implements IRootFolder {
  71. private Manager $mountManager;
  72. private PublicEmitter $emitter;
  73. private ?IUser $user;
  74. private CappedMemoryCache $userFolderCache;
  75. private IUserMountCache $userMountCache;
  76. private LoggerInterface $logger;
  77. private IUserManager $userManager;
  78. private IEventDispatcher $eventDispatcher;
  79. /**
  80. * @param Manager $manager
  81. * @param View $view
  82. * @param IUser|null $user
  83. */
  84. public function __construct(
  85. $manager,
  86. $view,
  87. $user,
  88. IUserMountCache $userMountCache,
  89. LoggerInterface $logger,
  90. IUserManager $userManager,
  91. IEventDispatcher $eventDispatcher
  92. ) {
  93. parent::__construct($this, $view, '');
  94. $this->mountManager = $manager;
  95. $this->user = $user;
  96. $this->emitter = new PublicEmitter();
  97. $this->userFolderCache = new CappedMemoryCache();
  98. $this->userMountCache = $userMountCache;
  99. $this->logger = $logger;
  100. $this->userManager = $userManager;
  101. $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
  102. $this->userFolderCache = new CappedMemoryCache();
  103. });
  104. }
  105. /**
  106. * Get the user for which the filesystem is setup
  107. *
  108. * @return \OC\User\User
  109. */
  110. public function getUser() {
  111. return $this->user;
  112. }
  113. /**
  114. * @param string $scope
  115. * @param string $method
  116. * @param callable $callback
  117. */
  118. public function listen($scope, $method, callable $callback) {
  119. $this->emitter->listen($scope, $method, $callback);
  120. }
  121. /**
  122. * @param string $scope optional
  123. * @param string $method optional
  124. * @param callable $callback optional
  125. */
  126. public function removeListener($scope = null, $method = null, callable $callback = null) {
  127. $this->emitter->removeListener($scope, $method, $callback);
  128. }
  129. /**
  130. * @param string $scope
  131. * @param string $method
  132. * @param Node[] $arguments
  133. */
  134. public function emit($scope, $method, $arguments = []) {
  135. $this->emitter->emit($scope, $method, $arguments);
  136. }
  137. /**
  138. * @param \OC\Files\Storage\Storage $storage
  139. * @param string $mountPoint
  140. * @param array $arguments
  141. */
  142. public function mount($storage, $mountPoint, $arguments = []) {
  143. $mount = new MountPoint($storage, $mountPoint, $arguments);
  144. $this->mountManager->addMount($mount);
  145. }
  146. /**
  147. * @param string $mountPoint
  148. * @return \OC\Files\Mount\MountPoint
  149. */
  150. public function getMount($mountPoint) {
  151. return $this->mountManager->find($mountPoint);
  152. }
  153. /**
  154. * @param string $mountPoint
  155. * @return \OC\Files\Mount\MountPoint[]
  156. */
  157. public function getMountsIn($mountPoint) {
  158. return $this->mountManager->findIn($mountPoint);
  159. }
  160. /**
  161. * @param string $storageId
  162. * @return \OC\Files\Mount\MountPoint[]
  163. */
  164. public function getMountByStorageId($storageId) {
  165. return $this->mountManager->findByStorageId($storageId);
  166. }
  167. /**
  168. * @param int $numericId
  169. * @return MountPoint[]
  170. */
  171. public function getMountByNumericStorageId($numericId) {
  172. return $this->mountManager->findByNumericId($numericId);
  173. }
  174. /**
  175. * @param \OC\Files\Mount\MountPoint $mount
  176. */
  177. public function unMount($mount) {
  178. $this->mountManager->remove($mount);
  179. }
  180. /**
  181. * @param string $path
  182. * @return Node
  183. * @throws \OCP\Files\NotPermittedException
  184. * @throws \OCP\Files\NotFoundException
  185. */
  186. public function get($path) {
  187. $path = $this->normalizePath($path);
  188. if ($this->isValidPath($path)) {
  189. $fullPath = $this->getFullPath($path);
  190. $fileInfo = $this->view->getFileInfo($fullPath, false);
  191. if ($fileInfo) {
  192. return $this->createNode($fullPath, $fileInfo, false);
  193. } else {
  194. throw new NotFoundException($path);
  195. }
  196. } else {
  197. throw new NotPermittedException();
  198. }
  199. }
  200. //most operations can't be done on the root
  201. /**
  202. * @param string $targetPath
  203. * @return Node
  204. * @throws \OCP\Files\NotPermittedException
  205. */
  206. public function rename($targetPath) {
  207. throw new NotPermittedException();
  208. }
  209. public function delete() {
  210. throw new NotPermittedException();
  211. }
  212. /**
  213. * @param string $targetPath
  214. * @return Node
  215. * @throws \OCP\Files\NotPermittedException
  216. */
  217. public function copy($targetPath) {
  218. throw new NotPermittedException();
  219. }
  220. /**
  221. * @param int $mtime
  222. * @throws \OCP\Files\NotPermittedException
  223. */
  224. public function touch($mtime = null) {
  225. throw new NotPermittedException();
  226. }
  227. /**
  228. * @return \OC\Files\Storage\Storage
  229. * @throws \OCP\Files\NotFoundException
  230. */
  231. public function getStorage() {
  232. throw new NotFoundException();
  233. }
  234. /**
  235. * @return string
  236. */
  237. public function getPath() {
  238. return '/';
  239. }
  240. /**
  241. * @return string
  242. */
  243. public function getInternalPath() {
  244. return '';
  245. }
  246. /**
  247. * @return int
  248. */
  249. public function getId() {
  250. return 0;
  251. }
  252. /**
  253. * @return array
  254. */
  255. public function stat() {
  256. return [];
  257. }
  258. /**
  259. * @return int
  260. */
  261. public function getMTime() {
  262. return 0;
  263. }
  264. /**
  265. * @param bool $includeMounts
  266. * @return int|float
  267. */
  268. public function getSize($includeMounts = true): int|float {
  269. return 0;
  270. }
  271. /**
  272. * @return string
  273. */
  274. public function getEtag() {
  275. return '';
  276. }
  277. /**
  278. * @return int
  279. */
  280. public function getPermissions() {
  281. return \OCP\Constants::PERMISSION_CREATE;
  282. }
  283. /**
  284. * @return bool
  285. */
  286. public function isReadable() {
  287. return false;
  288. }
  289. /**
  290. * @return bool
  291. */
  292. public function isUpdateable() {
  293. return false;
  294. }
  295. /**
  296. * @return bool
  297. */
  298. public function isDeletable() {
  299. return false;
  300. }
  301. /**
  302. * @return bool
  303. */
  304. public function isShareable() {
  305. return false;
  306. }
  307. /**
  308. * @return Node
  309. * @throws \OCP\Files\NotFoundException
  310. */
  311. public function getParent() {
  312. throw new NotFoundException();
  313. }
  314. /**
  315. * @return string
  316. */
  317. public function getName() {
  318. return '';
  319. }
  320. /**
  321. * Returns a view to user's files folder
  322. *
  323. * @param string $userId user ID
  324. * @return \OCP\Files\Folder
  325. * @throws NoUserException
  326. * @throws NotPermittedException
  327. */
  328. public function getUserFolder($userId) {
  329. $userObject = $this->userManager->get($userId);
  330. if (is_null($userObject)) {
  331. $e = new NoUserException('Backends provided no user object');
  332. $this->logger->error(
  333. sprintf(
  334. 'Backends provided no user object for %s',
  335. $userId
  336. ),
  337. [
  338. 'app' => 'files',
  339. 'exception' => $e,
  340. ]
  341. );
  342. throw $e;
  343. }
  344. $userId = $userObject->getUID();
  345. if (!$this->userFolderCache->hasKey($userId)) {
  346. if ($this->mountManager->getSetupManager()->isSetupComplete($userObject)) {
  347. try {
  348. $folder = $this->get('/' . $userId . '/files');
  349. if (!$folder instanceof \OCP\Files\Folder) {
  350. throw new \Exception("User folder for $userId exists as a file");
  351. }
  352. } catch (NotFoundException $e) {
  353. if (!$this->nodeExists('/' . $userId)) {
  354. $this->newFolder('/' . $userId);
  355. }
  356. $folder = $this->newFolder('/' . $userId . '/files');
  357. }
  358. } else {
  359. $folder = new LazyUserFolder($this, $userObject, $this->mountManager);
  360. }
  361. $this->userFolderCache->set($userId, $folder);
  362. }
  363. return $this->userFolderCache->get($userId);
  364. }
  365. public function getUserMountCache() {
  366. return $this->userMountCache;
  367. }
  368. /**
  369. * @param int $id
  370. * @return Node[]
  371. */
  372. public function getByIdInPath(int $id, string $path): array {
  373. $mountCache = $this->getUserMountCache();
  374. if (strpos($path, '/', 1) > 0) {
  375. [, $user] = explode('/', $path);
  376. } else {
  377. $user = null;
  378. }
  379. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  380. // if the mount isn't in the cache yet, perform a setup first, then try again
  381. if (count($mountsContainingFile) === 0) {
  382. $this->mountManager->getSetupManager()->setupForPath($path, true);
  383. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  384. }
  385. // when a user has access through the same storage through multiple paths
  386. // (such as an external storage that is both mounted for a user and shared to the user)
  387. // the mount cache will only hold a single entry for the storage
  388. // this can lead to issues as the different ways the user has access to a storage can have different permissions
  389. //
  390. // so instead of using the cached entries directly, we instead filter the current mounts by the rootid of the cache entry
  391. $mountRootIds = array_map(function ($mount) {
  392. return $mount->getRootId();
  393. }, $mountsContainingFile);
  394. $mountRootPaths = array_map(function ($mount) {
  395. return $mount->getRootInternalPath();
  396. }, $mountsContainingFile);
  397. $mountProviders = array_unique(array_map(function ($mount) {
  398. return $mount->getMountProvider();
  399. }, $mountsContainingFile));
  400. $mountRoots = array_combine($mountRootIds, $mountRootPaths);
  401. $mounts = $this->mountManager->getMountsByMountProvider($path, $mountProviders);
  402. $mountsContainingFile = array_filter($mounts, function ($mount) use ($mountRoots) {
  403. return isset($mountRoots[$mount->getStorageRootId()]);
  404. });
  405. if (count($mountsContainingFile) === 0) {
  406. if ($user === $this->getAppDataDirectoryName()) {
  407. $folder = $this->get($path);
  408. if ($folder instanceof Folder) {
  409. return $folder->getByIdInRootMount($id);
  410. } else {
  411. throw new \Exception("getByIdInPath with non folder");
  412. }
  413. }
  414. return [];
  415. }
  416. $nodes = array_map(function (IMountPoint $mount) use ($id, $mountRoots) {
  417. $rootInternalPath = $mountRoots[$mount->getStorageRootId()];
  418. $cacheEntry = $mount->getStorage()->getCache()->get($id);
  419. if (!$cacheEntry) {
  420. return null;
  421. }
  422. // cache jails will hide the "true" internal path
  423. $internalPath = ltrim($rootInternalPath . '/' . $cacheEntry->getPath(), '/');
  424. $pathRelativeToMount = substr($internalPath, strlen($rootInternalPath));
  425. $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
  426. $absolutePath = rtrim($mount->getMountPoint() . $pathRelativeToMount, '/');
  427. return $this->createNode($absolutePath, new FileInfo(
  428. $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
  429. \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
  430. ));
  431. }, $mountsContainingFile);
  432. $nodes = array_filter($nodes);
  433. $folders = array_filter($nodes, function (Node $node) use ($path) {
  434. return PathHelper::getRelativePath($path, $node->getPath()) !== null;
  435. });
  436. usort($folders, function ($a, $b) {
  437. return $b->getPath() <=> $a->getPath();
  438. });
  439. return $folders;
  440. }
  441. }