Folder.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Node;
  8. use OC\Files\Cache\QuerySearchHelper;
  9. use OC\Files\Search\SearchBinaryOperator;
  10. use OC\Files\Search\SearchComparison;
  11. use OC\Files\Search\SearchOrder;
  12. use OC\Files\Search\SearchQuery;
  13. use OC\Files\Utils\PathHelper;
  14. use OC\User\LazyUser;
  15. use OCP\Files\Cache\ICacheEntry;
  16. use OCP\Files\FileInfo;
  17. use OCP\Files\Mount\IMountPoint;
  18. use OCP\Files\Node as INode;
  19. use OCP\Files\NotFoundException;
  20. use OCP\Files\NotPermittedException;
  21. use OCP\Files\Search\ISearchBinaryOperator;
  22. use OCP\Files\Search\ISearchComparison;
  23. use OCP\Files\Search\ISearchOperator;
  24. use OCP\Files\Search\ISearchOrder;
  25. use OCP\Files\Search\ISearchQuery;
  26. use OCP\IUserManager;
  27. class Folder extends Node implements \OCP\Files\Folder {
  28. private ?IUserManager $userManager = null;
  29. /**
  30. * Creates a Folder that represents a non-existing path
  31. *
  32. * @param string $path path
  33. * @return NonExistingFolder non-existing node
  34. */
  35. protected function createNonExistingNode($path) {
  36. return new NonExistingFolder($this->root, $this->view, $path);
  37. }
  38. /**
  39. * @param string $path path relative to the folder
  40. * @return string
  41. * @throws \OCP\Files\NotPermittedException
  42. */
  43. public function getFullPath($path) {
  44. $path = $this->normalizePath($path);
  45. if (!$this->isValidPath($path)) {
  46. throw new NotPermittedException('Invalid path "' . $path . '"');
  47. }
  48. return $this->path . $path;
  49. }
  50. /**
  51. * @param string $path
  52. * @return string|null
  53. */
  54. public function getRelativePath($path) {
  55. return PathHelper::getRelativePath($this->getPath(), $path);
  56. }
  57. /**
  58. * check if a node is a (grand-)child of the folder
  59. *
  60. * @param \OC\Files\Node\Node $node
  61. * @return bool
  62. */
  63. public function isSubNode($node) {
  64. return str_starts_with($node->getPath(), $this->path . '/');
  65. }
  66. /**
  67. * get the content of this directory
  68. *
  69. * @return Node[]
  70. * @throws \OCP\Files\NotFoundException
  71. */
  72. public function getDirectoryListing() {
  73. $folderContent = $this->view->getDirectoryContent($this->path, '', $this->getFileInfo(false));
  74. return array_map(function (FileInfo $info) {
  75. if ($info->getMimetype() === FileInfo::MIMETYPE_FOLDER) {
  76. return new Folder($this->root, $this->view, $info->getPath(), $info, $this);
  77. } else {
  78. return new File($this->root, $this->view, $info->getPath(), $info, $this);
  79. }
  80. }, $folderContent);
  81. }
  82. protected function createNode(string $path, ?FileInfo $info = null, bool $infoHasSubMountsIncluded = true): INode {
  83. if (is_null($info)) {
  84. $isDir = $this->view->is_dir($path);
  85. } else {
  86. $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
  87. }
  88. $parent = dirname($path) === $this->getPath() ? $this : null;
  89. if ($isDir) {
  90. return new Folder($this->root, $this->view, $path, $info, $parent, $infoHasSubMountsIncluded);
  91. } else {
  92. return new File($this->root, $this->view, $path, $info, $parent);
  93. }
  94. }
  95. /**
  96. * Get the node at $path
  97. *
  98. * @param string $path
  99. * @return \OC\Files\Node\Node
  100. * @throws \OCP\Files\NotFoundException
  101. */
  102. public function get($path) {
  103. return $this->root->get($this->getFullPath($path));
  104. }
  105. /**
  106. * @param string $path
  107. * @return bool
  108. */
  109. public function nodeExists($path) {
  110. try {
  111. $this->get($path);
  112. return true;
  113. } catch (NotFoundException $e) {
  114. return false;
  115. }
  116. }
  117. /**
  118. * @param string $path
  119. * @return \OC\Files\Node\Folder
  120. * @throws \OCP\Files\NotPermittedException
  121. */
  122. public function newFolder($path) {
  123. if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
  124. $fullPath = $this->getFullPath($path);
  125. $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
  126. $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
  127. if (!$this->view->mkdir($fullPath) && !$this->view->is_dir($fullPath)) {
  128. throw new NotPermittedException('Could not create folder "' . $fullPath . '"');
  129. }
  130. $parent = dirname($fullPath) === $this->getPath() ? $this : null;
  131. $node = new Folder($this->root, $this->view, $fullPath, null, $parent);
  132. $this->sendHooks(['postWrite', 'postCreate'], [$node]);
  133. return $node;
  134. } else {
  135. throw new NotPermittedException('No create permission for folder "' . $path . '"');
  136. }
  137. }
  138. /**
  139. * @param string $path
  140. * @param string | resource | null $content
  141. * @return \OC\Files\Node\File
  142. * @throws \OCP\Files\NotPermittedException
  143. */
  144. public function newFile($path, $content = null) {
  145. if ($path === '') {
  146. throw new NotPermittedException('Could not create as provided path is empty');
  147. }
  148. if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
  149. $fullPath = $this->getFullPath($path);
  150. $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
  151. $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
  152. if ($content !== null) {
  153. $result = $this->view->file_put_contents($fullPath, $content);
  154. } else {
  155. $result = $this->view->touch($fullPath);
  156. }
  157. if ($result === false) {
  158. throw new NotPermittedException('Could not create path "' . $fullPath . '"');
  159. }
  160. $node = new File($this->root, $this->view, $fullPath, null, $this);
  161. $this->sendHooks(['postWrite', 'postCreate'], [$node]);
  162. return $node;
  163. }
  164. throw new NotPermittedException('No create permission for path "' . $path . '"');
  165. }
  166. private function queryFromOperator(ISearchOperator $operator, ?string $uid = null, int $limit = 0, int $offset = 0): ISearchQuery {
  167. if ($uid === null) {
  168. $user = null;
  169. } else {
  170. /** @var IUserManager $userManager */
  171. $userManager = \OCP\Server::get(IUserManager::class);
  172. $user = $userManager->get($uid);
  173. }
  174. return new SearchQuery($operator, $limit, $offset, [], $user);
  175. }
  176. /**
  177. * search for files with the name matching $query
  178. *
  179. * @param string|ISearchQuery $query
  180. * @return \OC\Files\Node\Node[]
  181. */
  182. public function search($query) {
  183. if (is_string($query)) {
  184. $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'));
  185. }
  186. // search is handled by a single query covering all caches that this folder contains
  187. // this is done by collect
  188. $limitToHome = $query->limitToHome();
  189. if ($limitToHome && count(explode('/', $this->path)) !== 3) {
  190. throw new \InvalidArgumentException('searching by owner is only allowed in the users home folder');
  191. }
  192. /** @var QuerySearchHelper $searchHelper */
  193. $searchHelper = \OC::$server->get(QuerySearchHelper::class);
  194. [$caches, $mountByMountPoint] = $searchHelper->getCachesAndMountPointsForSearch($this->root, $this->path, $limitToHome);
  195. $resultsPerCache = $searchHelper->searchInCaches($query, $caches);
  196. // loop through all results per-cache, constructing the FileInfo object from the CacheEntry and merge them all
  197. $files = array_merge(...array_map(function (array $results, string $relativeMountPoint) use ($mountByMountPoint) {
  198. $mount = $mountByMountPoint[$relativeMountPoint];
  199. return array_map(function (ICacheEntry $result) use ($relativeMountPoint, $mount) {
  200. return $this->cacheEntryToFileInfo($mount, $relativeMountPoint, $result);
  201. }, $results);
  202. }, array_values($resultsPerCache), array_keys($resultsPerCache)));
  203. // don't include this folder in the results
  204. $files = array_values(array_filter($files, function (FileInfo $file) {
  205. return $file->getPath() !== $this->getPath();
  206. }));
  207. // since results were returned per-cache, they are no longer fully sorted
  208. $order = $query->getOrder();
  209. if ($order) {
  210. usort($files, function (FileInfo $a, FileInfo $b) use ($order) {
  211. foreach ($order as $orderField) {
  212. $cmp = $orderField->sortFileInfo($a, $b);
  213. if ($cmp !== 0) {
  214. return $cmp;
  215. }
  216. }
  217. return 0;
  218. });
  219. }
  220. return array_map(function (FileInfo $file) {
  221. return $this->createNode($file->getPath(), $file);
  222. }, $files);
  223. }
  224. private function cacheEntryToFileInfo(IMountPoint $mount, string $appendRoot, ICacheEntry $cacheEntry): FileInfo {
  225. $cacheEntry['internalPath'] = $cacheEntry['path'];
  226. $cacheEntry['path'] = rtrim($appendRoot . $cacheEntry->getPath(), '/');
  227. $subPath = $cacheEntry['path'] !== '' ? '/' . $cacheEntry['path'] : '';
  228. $storage = $mount->getStorage();
  229. $owner = null;
  230. $ownerId = $storage->getOwner($cacheEntry['internalPath']);
  231. if (!empty($ownerId)) {
  232. // Cache the user manager (for performance)
  233. if ($this->userManager === null) {
  234. $this->userManager = \OCP\Server::get(IUserManager::class);
  235. }
  236. $owner = new LazyUser($ownerId, $this->userManager);
  237. }
  238. return new \OC\Files\FileInfo(
  239. $this->path . $subPath,
  240. $storage,
  241. $cacheEntry['internalPath'],
  242. $cacheEntry,
  243. $mount,
  244. $owner,
  245. );
  246. }
  247. /**
  248. * search for files by mimetype
  249. *
  250. * @param string $mimetype
  251. * @return Node[]
  252. */
  253. public function searchByMime($mimetype) {
  254. if (!str_contains($mimetype, '/')) {
  255. $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
  256. } else {
  257. $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
  258. }
  259. return $this->search($query);
  260. }
  261. /**
  262. * search for files by tag
  263. *
  264. * @param string|int $tag name or tag id
  265. * @param string $userId owner of the tags
  266. * @return Node[]
  267. */
  268. public function searchByTag($tag, $userId) {
  269. $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'tagname', $tag), $userId);
  270. return $this->search($query);
  271. }
  272. public function searchBySystemTag(string $tagName, string $userId, int $limit = 0, int $offset = 0): array {
  273. $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'systemtag', $tagName), $userId, $limit, $offset);
  274. return $this->search($query);
  275. }
  276. /**
  277. * @param int $id
  278. * @return \OCP\Files\Node[]
  279. */
  280. public function getById($id) {
  281. return $this->root->getByIdInPath((int)$id, $this->getPath());
  282. }
  283. public function getFirstNodeById(int $id): ?\OCP\Files\Node {
  284. return $this->root->getFirstNodeByIdInPath($id, $this->getPath());
  285. }
  286. public function getAppDataDirectoryName(): string {
  287. $instanceId = \OC::$server->getConfig()->getSystemValueString('instanceid');
  288. return 'appdata_' . $instanceId;
  289. }
  290. /**
  291. * In case the path we are currently in is inside the appdata_* folder,
  292. * the original getById method does not work, because it can only look inside
  293. * the user's mount points. But the user has no mount point for the root storage.
  294. *
  295. * So in that case we directly check the mount of the root if it contains
  296. * the id. If it does we check if the path is inside the path we are working
  297. * in.
  298. *
  299. * @param int $id
  300. * @return array
  301. */
  302. protected function getByIdInRootMount(int $id): array {
  303. if (!method_exists($this->root, 'createNode')) {
  304. // Always expected to be false. Being a method of Folder, this is
  305. // always implemented. For it is an internal method and should not
  306. // be exposed and made public, it is not part of an interface.
  307. return [];
  308. }
  309. $mount = $this->root->getMount('');
  310. $storage = $mount->getStorage();
  311. $cacheEntry = $storage?->getCache($this->path)->get($id);
  312. if (!$cacheEntry) {
  313. return [];
  314. }
  315. $absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
  316. $currentPath = rtrim($this->path, '/') . '/';
  317. if (!str_starts_with($absolutePath, $currentPath)) {
  318. return [];
  319. }
  320. return [$this->root->createNode(
  321. $absolutePath, new \OC\Files\FileInfo(
  322. $absolutePath,
  323. $storage,
  324. $cacheEntry->getPath(),
  325. $cacheEntry,
  326. $mount
  327. ))];
  328. }
  329. public function getFreeSpace() {
  330. return $this->view->free_space($this->path);
  331. }
  332. public function delete() {
  333. if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
  334. $this->sendHooks(['preDelete']);
  335. $fileInfo = $this->getFileInfo();
  336. $this->view->rmdir($this->path);
  337. $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
  338. $this->sendHooks(['postDelete'], [$nonExisting]);
  339. } else {
  340. throw new NotPermittedException('No delete permission for path "' . $this->path . '"');
  341. }
  342. }
  343. /**
  344. * Add a suffix to the name in case the file exists
  345. *
  346. * @param string $name
  347. * @return string
  348. * @throws NotPermittedException
  349. */
  350. public function getNonExistingName($name) {
  351. $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
  352. return trim($this->getRelativePath($uniqueName), '/');
  353. }
  354. /**
  355. * @param int $limit
  356. * @param int $offset
  357. * @return INode[]
  358. */
  359. public function getRecent($limit, $offset = 0) {
  360. $filterOutNonEmptyFolder = new SearchBinaryOperator(
  361. // filter out non empty folders
  362. ISearchBinaryOperator::OPERATOR_OR,
  363. [
  364. new SearchBinaryOperator(
  365. ISearchBinaryOperator::OPERATOR_NOT,
  366. [
  367. new SearchComparison(
  368. ISearchComparison::COMPARE_EQUAL,
  369. 'mimetype',
  370. FileInfo::MIMETYPE_FOLDER
  371. ),
  372. ]
  373. ),
  374. new SearchComparison(
  375. ISearchComparison::COMPARE_EQUAL,
  376. 'size',
  377. 0
  378. ),
  379. ]
  380. );
  381. $filterNonRecentFiles = new SearchComparison(
  382. ISearchComparison::COMPARE_GREATER_THAN,
  383. 'mtime',
  384. strtotime("-2 week")
  385. );
  386. if ($offset === 0 && $limit <= 100) {
  387. $query = new SearchQuery(
  388. new SearchBinaryOperator(
  389. ISearchBinaryOperator::OPERATOR_AND,
  390. [
  391. $filterOutNonEmptyFolder,
  392. $filterNonRecentFiles,
  393. ],
  394. ),
  395. $limit,
  396. $offset,
  397. [
  398. new SearchOrder(
  399. ISearchOrder::DIRECTION_DESCENDING,
  400. 'mtime'
  401. ),
  402. ]
  403. );
  404. } else {
  405. $query = new SearchQuery(
  406. $filterOutNonEmptyFolder,
  407. $limit,
  408. $offset,
  409. [
  410. new SearchOrder(
  411. ISearchOrder::DIRECTION_DESCENDING,
  412. 'mtime'
  413. ),
  414. ]
  415. );
  416. }
  417. return $this->search($query);
  418. }
  419. }