Folder.php 13 KB

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