Folder.php 13 KB

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