Root.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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\Node as INode;
  47. use OCP\Files\NotFoundException;
  48. use OCP\Files\NotPermittedException;
  49. use OCP\IUser;
  50. use OCP\IUserManager;
  51. use Psr\Log\LoggerInterface;
  52. /**
  53. * Class Root
  54. *
  55. * Hooks available in scope \OC\Files
  56. * - preWrite(\OCP\Files\Node $node)
  57. * - postWrite(\OCP\Files\Node $node)
  58. * - preCreate(\OCP\Files\Node $node)
  59. * - postCreate(\OCP\Files\Node $node)
  60. * - preDelete(\OCP\Files\Node $node)
  61. * - postDelete(\OCP\Files\Node $node)
  62. * - preTouch(\OC\FilesP\Node $node, int $mtime)
  63. * - postTouch(\OCP\Files\Node $node)
  64. * - preCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  65. * - postCopy(\OCP\Files\Node $source, \OCP\Files\Node $target)
  66. * - preRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  67. * - postRename(\OCP\Files\Node $source, \OCP\Files\Node $target)
  68. *
  69. * @package OC\Files\Node
  70. */
  71. class Root extends Folder implements IRootFolder {
  72. private Manager $mountManager;
  73. private PublicEmitter $emitter;
  74. private ?IUser $user;
  75. private CappedMemoryCache $userFolderCache;
  76. private IUserMountCache $userMountCache;
  77. private LoggerInterface $logger;
  78. private IUserManager $userManager;
  79. private IEventDispatcher $eventDispatcher;
  80. /**
  81. * @param Manager $manager
  82. * @param View $view
  83. * @param IUser|null $user
  84. */
  85. public function __construct(
  86. $manager,
  87. $view,
  88. $user,
  89. IUserMountCache $userMountCache,
  90. LoggerInterface $logger,
  91. IUserManager $userManager,
  92. IEventDispatcher $eventDispatcher
  93. ) {
  94. parent::__construct($this, $view, '');
  95. $this->mountManager = $manager;
  96. $this->user = $user;
  97. $this->emitter = new PublicEmitter();
  98. $this->userFolderCache = new CappedMemoryCache();
  99. $this->userMountCache = $userMountCache;
  100. $this->logger = $logger;
  101. $this->userManager = $userManager;
  102. $eventDispatcher->addListener(FilesystemTornDownEvent::class, function () {
  103. $this->userFolderCache = new CappedMemoryCache();
  104. });
  105. }
  106. /**
  107. * Get the user for which the filesystem is setup
  108. *
  109. * @return \OC\User\User
  110. */
  111. public function getUser() {
  112. return $this->user;
  113. }
  114. /**
  115. * @param string $scope
  116. * @param string $method
  117. * @param callable $callback
  118. */
  119. public function listen($scope, $method, callable $callback) {
  120. $this->emitter->listen($scope, $method, $callback);
  121. }
  122. /**
  123. * @param string $scope optional
  124. * @param string $method optional
  125. * @param callable $callback optional
  126. */
  127. public function removeListener($scope = null, $method = null, callable $callback = null) {
  128. $this->emitter->removeListener($scope, $method, $callback);
  129. }
  130. /**
  131. * @param string $scope
  132. * @param string $method
  133. * @param Node[] $arguments
  134. */
  135. public function emit($scope, $method, $arguments = []) {
  136. $this->emitter->emit($scope, $method, $arguments);
  137. }
  138. /**
  139. * @param \OC\Files\Storage\Storage $storage
  140. * @param string $mountPoint
  141. * @param array $arguments
  142. */
  143. public function mount($storage, $mountPoint, $arguments = []) {
  144. $mount = new MountPoint($storage, $mountPoint, $arguments);
  145. $this->mountManager->addMount($mount);
  146. }
  147. public function getMount(string $mountPoint): IMountPoint {
  148. return $this->mountManager->find($mountPoint);
  149. }
  150. /**
  151. * @param string $mountPoint
  152. * @return \OC\Files\Mount\MountPoint[]
  153. */
  154. public function getMountsIn(string $mountPoint): array {
  155. return $this->mountManager->findIn($mountPoint);
  156. }
  157. /**
  158. * @param string $storageId
  159. * @return \OC\Files\Mount\MountPoint[]
  160. */
  161. public function getMountByStorageId($storageId) {
  162. return $this->mountManager->findByStorageId($storageId);
  163. }
  164. /**
  165. * @param int $numericId
  166. * @return MountPoint[]
  167. */
  168. public function getMountByNumericStorageId($numericId) {
  169. return $this->mountManager->findByNumericId($numericId);
  170. }
  171. /**
  172. * @param \OC\Files\Mount\MountPoint $mount
  173. */
  174. public function unMount($mount) {
  175. $this->mountManager->remove($mount);
  176. }
  177. /**
  178. * @param string $path
  179. * @return Node
  180. * @throws \OCP\Files\NotPermittedException
  181. * @throws \OCP\Files\NotFoundException
  182. */
  183. public function get($path) {
  184. $path = $this->normalizePath($path);
  185. if ($this->isValidPath($path)) {
  186. $fullPath = $this->getFullPath($path);
  187. $fileInfo = $this->view->getFileInfo($fullPath, false);
  188. if ($fileInfo) {
  189. return $this->createNode($fullPath, $fileInfo, false);
  190. } else {
  191. throw new NotFoundException($path);
  192. }
  193. } else {
  194. throw new NotPermittedException();
  195. }
  196. }
  197. //most operations can't be done on the root
  198. /**
  199. * @param string $targetPath
  200. * @return Node
  201. * @throws \OCP\Files\NotPermittedException
  202. */
  203. public function rename($targetPath) {
  204. throw new NotPermittedException();
  205. }
  206. public function delete() {
  207. throw new NotPermittedException();
  208. }
  209. /**
  210. * @param string $targetPath
  211. * @return Node
  212. * @throws \OCP\Files\NotPermittedException
  213. */
  214. public function copy($targetPath) {
  215. throw new NotPermittedException();
  216. }
  217. /**
  218. * @param int $mtime
  219. * @throws \OCP\Files\NotPermittedException
  220. */
  221. public function touch($mtime = null) {
  222. throw new NotPermittedException();
  223. }
  224. /**
  225. * @return \OC\Files\Storage\Storage
  226. * @throws \OCP\Files\NotFoundException
  227. */
  228. public function getStorage() {
  229. throw new NotFoundException();
  230. }
  231. /**
  232. * @return string
  233. */
  234. public function getPath() {
  235. return '/';
  236. }
  237. /**
  238. * @return string
  239. */
  240. public function getInternalPath() {
  241. return '';
  242. }
  243. /**
  244. * @return int
  245. */
  246. public function getId() {
  247. return 0;
  248. }
  249. /**
  250. * @return array
  251. */
  252. public function stat() {
  253. return [];
  254. }
  255. /**
  256. * @return int
  257. */
  258. public function getMTime() {
  259. return 0;
  260. }
  261. /**
  262. * @param bool $includeMounts
  263. * @return int|float
  264. */
  265. public function getSize($includeMounts = true): int|float {
  266. return 0;
  267. }
  268. /**
  269. * @return string
  270. */
  271. public function getEtag() {
  272. return '';
  273. }
  274. /**
  275. * @return int
  276. */
  277. public function getPermissions() {
  278. return \OCP\Constants::PERMISSION_CREATE;
  279. }
  280. /**
  281. * @return bool
  282. */
  283. public function isReadable() {
  284. return false;
  285. }
  286. /**
  287. * @return bool
  288. */
  289. public function isUpdateable() {
  290. return false;
  291. }
  292. /**
  293. * @return bool
  294. */
  295. public function isDeletable() {
  296. return false;
  297. }
  298. /**
  299. * @return bool
  300. */
  301. public function isShareable() {
  302. return false;
  303. }
  304. /**
  305. * @throws \OCP\Files\NotFoundException
  306. */
  307. public function getParent(): INode|IRootFolder {
  308. throw new NotFoundException();
  309. }
  310. /**
  311. * @return string
  312. */
  313. public function getName() {
  314. return '';
  315. }
  316. /**
  317. * Returns a view to user's files folder
  318. *
  319. * @param string $userId user ID
  320. * @return \OCP\Files\Folder
  321. * @throws NoUserException
  322. * @throws NotPermittedException
  323. */
  324. public function getUserFolder($userId) {
  325. $userObject = $this->userManager->get($userId);
  326. if (is_null($userObject)) {
  327. $e = new NoUserException('Backends provided no user object');
  328. $this->logger->error(
  329. sprintf(
  330. 'Backends provided no user object for %s',
  331. $userId
  332. ),
  333. [
  334. 'app' => 'files',
  335. 'exception' => $e,
  336. ]
  337. );
  338. throw $e;
  339. }
  340. $userId = $userObject->getUID();
  341. if (!$this->userFolderCache->hasKey($userId)) {
  342. if ($this->mountManager->getSetupManager()->isSetupComplete($userObject)) {
  343. try {
  344. $folder = $this->get('/' . $userId . '/files');
  345. if (!$folder instanceof \OCP\Files\Folder) {
  346. throw new \Exception("User folder for $userId exists as a file");
  347. }
  348. } catch (NotFoundException $e) {
  349. if (!$this->nodeExists('/' . $userId)) {
  350. $this->newFolder('/' . $userId);
  351. }
  352. $folder = $this->newFolder('/' . $userId . '/files');
  353. }
  354. } else {
  355. $folder = new LazyUserFolder($this, $userObject, $this->mountManager);
  356. }
  357. $this->userFolderCache->set($userId, $folder);
  358. }
  359. return $this->userFolderCache->get($userId);
  360. }
  361. public function getUserMountCache() {
  362. return $this->userMountCache;
  363. }
  364. /**
  365. * @param int $id
  366. * @return Node[]
  367. */
  368. public function getByIdInPath(int $id, string $path): array {
  369. $mountCache = $this->getUserMountCache();
  370. if (strpos($path, '/', 1) > 0) {
  371. [, $user] = explode('/', $path);
  372. } else {
  373. $user = null;
  374. }
  375. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  376. // if the mount isn't in the cache yet, perform a setup first, then try again
  377. if (count($mountsContainingFile) === 0) {
  378. $this->mountManager->getSetupManager()->setupForPath($path, true);
  379. $mountsContainingFile = $mountCache->getMountsForFileId($id, $user);
  380. }
  381. // when a user has access through the same storage through multiple paths
  382. // (such as an external storage that is both mounted for a user and shared to the user)
  383. // the mount cache will only hold a single entry for the storage
  384. // this can lead to issues as the different ways the user has access to a storage can have different permissions
  385. //
  386. // so instead of using the cached entries directly, we instead filter the current mounts by the rootid of the cache entry
  387. $mountRootIds = array_map(function ($mount) {
  388. return $mount->getRootId();
  389. }, $mountsContainingFile);
  390. $mountRootPaths = array_map(function ($mount) {
  391. return $mount->getRootInternalPath();
  392. }, $mountsContainingFile);
  393. $mountProviders = array_unique(array_map(function ($mount) {
  394. return $mount->getMountProvider();
  395. }, $mountsContainingFile));
  396. $mountRoots = array_combine($mountRootIds, $mountRootPaths);
  397. $mounts = $this->mountManager->getMountsByMountProvider($path, $mountProviders);
  398. $mountsContainingFile = array_filter($mounts, function ($mount) use ($mountRoots) {
  399. return isset($mountRoots[$mount->getStorageRootId()]);
  400. });
  401. if (count($mountsContainingFile) === 0) {
  402. if ($user === $this->getAppDataDirectoryName()) {
  403. $folder = $this->get($path);
  404. if ($folder instanceof Folder) {
  405. return $folder->getByIdInRootMount($id);
  406. } else {
  407. throw new \Exception("getByIdInPath with non folder");
  408. }
  409. }
  410. return [];
  411. }
  412. $nodes = array_map(function (IMountPoint $mount) use ($id, $mountRoots) {
  413. $rootInternalPath = $mountRoots[$mount->getStorageRootId()];
  414. $cacheEntry = $mount->getStorage()->getCache()->get($id);
  415. if (!$cacheEntry) {
  416. return null;
  417. }
  418. // cache jails will hide the "true" internal path
  419. $internalPath = ltrim($rootInternalPath . '/' . $cacheEntry->getPath(), '/');
  420. $pathRelativeToMount = substr($internalPath, strlen($rootInternalPath));
  421. $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
  422. $absolutePath = rtrim($mount->getMountPoint() . $pathRelativeToMount, '/');
  423. return $this->createNode($absolutePath, new FileInfo(
  424. $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
  425. \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
  426. ));
  427. }, $mountsContainingFile);
  428. $nodes = array_filter($nodes);
  429. $folders = array_filter($nodes, function (Node $node) use ($path) {
  430. return PathHelper::getRelativePath($path, $node->getPath()) !== null;
  431. });
  432. usort($folders, function ($a, $b) {
  433. return $b->getPath() <=> $a->getPath();
  434. });
  435. return $folders;
  436. }
  437. }