Folder.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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)) {
  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 (empty($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 = \OC::$server->query(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. /**
  279. * @param int $id
  280. * @return \OC\Files\Node\Node[]
  281. */
  282. public function getById($id) {
  283. return $this->root->getByIdInPath((int)$id, $this->getPath());
  284. }
  285. protected function getAppDataDirectoryName(): string {
  286. $instanceId = \OC::$server->getConfig()->getSystemValueString('instanceid');
  287. return 'appdata_' . $instanceId;
  288. }
  289. /**
  290. * In case the path we are currently in is inside the appdata_* folder,
  291. * the original getById method does not work, because it can only look inside
  292. * the user's mount points. But the user has no mount point for the root storage.
  293. *
  294. * So in that case we directly check the mount of the root if it contains
  295. * the id. If it does we check if the path is inside the path we are working
  296. * in.
  297. *
  298. * @param int $id
  299. * @return array
  300. */
  301. protected function getByIdInRootMount(int $id): array {
  302. if (!method_exists($this->root, 'createNode')) {
  303. // Always expected to be false. Being a method of Folder, this is
  304. // always implemented. For it is an internal method and should not
  305. // be exposed and made public, it is not part of an interface.
  306. return [];
  307. }
  308. $mount = $this->root->getMount('');
  309. $storage = $mount->getStorage();
  310. $cacheEntry = $storage?->getCache($this->path)->get($id);
  311. if (!$cacheEntry) {
  312. return [];
  313. }
  314. $absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
  315. $currentPath = rtrim($this->path, '/') . '/';
  316. if (!str_starts_with($absolutePath, $currentPath)) {
  317. return [];
  318. }
  319. return [$this->root->createNode(
  320. $absolutePath, new \OC\Files\FileInfo(
  321. $absolutePath,
  322. $storage,
  323. $cacheEntry->getPath(),
  324. $cacheEntry,
  325. $mount
  326. ))];
  327. }
  328. public function getFreeSpace() {
  329. return $this->view->free_space($this->path);
  330. }
  331. public function delete() {
  332. if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
  333. $this->sendHooks(['preDelete']);
  334. $fileInfo = $this->getFileInfo();
  335. $this->view->rmdir($this->path);
  336. $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
  337. $this->sendHooks(['postDelete'], [$nonExisting]);
  338. } else {
  339. throw new NotPermittedException('No delete permission for path "' . $this->path . '"');
  340. }
  341. }
  342. /**
  343. * Add a suffix to the name in case the file exists
  344. *
  345. * @param string $name
  346. * @return string
  347. * @throws NotPermittedException
  348. */
  349. public function getNonExistingName($name) {
  350. $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
  351. return trim($this->getRelativePath($uniqueName), '/');
  352. }
  353. /**
  354. * @param int $limit
  355. * @param int $offset
  356. * @return INode[]
  357. */
  358. public function getRecent($limit, $offset = 0) {
  359. $filterOutNonEmptyFolder = new SearchBinaryOperator(
  360. // filter out non empty folders
  361. ISearchBinaryOperator::OPERATOR_OR,
  362. [
  363. new SearchBinaryOperator(
  364. ISearchBinaryOperator::OPERATOR_NOT,
  365. [
  366. new SearchComparison(
  367. ISearchComparison::COMPARE_EQUAL,
  368. 'mimetype',
  369. FileInfo::MIMETYPE_FOLDER
  370. ),
  371. ]
  372. ),
  373. new SearchComparison(
  374. ISearchComparison::COMPARE_EQUAL,
  375. 'size',
  376. 0
  377. ),
  378. ]
  379. );
  380. $filterNonRecentFiles = new SearchComparison(
  381. ISearchComparison::COMPARE_GREATER_THAN,
  382. 'mtime',
  383. strtotime("-2 week")
  384. );
  385. if ($offset === 0 && $limit <= 100) {
  386. $query = new SearchQuery(
  387. new SearchBinaryOperator(
  388. ISearchBinaryOperator::OPERATOR_AND,
  389. [
  390. $filterOutNonEmptyFolder,
  391. $filterNonRecentFiles,
  392. ],
  393. ),
  394. $limit,
  395. $offset,
  396. [
  397. new SearchOrder(
  398. ISearchOrder::DIRECTION_DESCENDING,
  399. 'mtime'
  400. ),
  401. ]
  402. );
  403. } else {
  404. $query = new SearchQuery(
  405. $filterOutNonEmptyFolder,
  406. $limit,
  407. $offset,
  408. [
  409. new SearchOrder(
  410. ISearchOrder::DIRECTION_DESCENDING,
  411. 'mtime'
  412. ),
  413. ]
  414. );
  415. }
  416. return $this->search($query);
  417. }
  418. }