Folder.php 14 KB

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