Folder.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Robin Appelman <robin@icewind.nl>
  8. * @author Robin McCorkell <robin@mccorkell.me.uk>
  9. * @author Vincent Petry <pvince81@owncloud.com>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Files\Node;
  27. use OC\DB\QueryBuilder\Literal;
  28. use OCP\DB\QueryBuilder\IQueryBuilder;
  29. use OCP\Files\Config\ICachedMountInfo;
  30. use OCP\Files\FileInfo;
  31. use OCP\Files\Mount\IMountPoint;
  32. use OCP\Files\NotFoundException;
  33. use OCP\Files\NotPermittedException;
  34. use OCP\Files\Search\ISearchOperator;
  35. class Folder extends Node implements \OCP\Files\Folder {
  36. /**
  37. * Creates a Folder that represents a non-existing path
  38. *
  39. * @param string $path path
  40. * @return string non-existing node class
  41. */
  42. protected function createNonExistingNode($path) {
  43. return new NonExistingFolder($this->root, $this->view, $path);
  44. }
  45. /**
  46. * @param string $path path relative to the folder
  47. * @return string
  48. * @throws \OCP\Files\NotPermittedException
  49. */
  50. public function getFullPath($path) {
  51. if (!$this->isValidPath($path)) {
  52. throw new NotPermittedException('Invalid path');
  53. }
  54. return $this->path . $this->normalizePath($path);
  55. }
  56. /**
  57. * @param string $path
  58. * @return string
  59. */
  60. public function getRelativePath($path) {
  61. if ($this->path === '' or $this->path === '/') {
  62. return $this->normalizePath($path);
  63. }
  64. if ($path === $this->path) {
  65. return '/';
  66. } else if (strpos($path, $this->path . '/') !== 0) {
  67. return null;
  68. } else {
  69. $path = substr($path, strlen($this->path));
  70. return $this->normalizePath($path);
  71. }
  72. }
  73. /**
  74. * check if a node is a (grand-)child of the folder
  75. *
  76. * @param \OC\Files\Node\Node $node
  77. * @return bool
  78. */
  79. public function isSubNode($node) {
  80. return strpos($node->getPath(), $this->path . '/') === 0;
  81. }
  82. /**
  83. * get the content of this directory
  84. *
  85. * @throws \OCP\Files\NotFoundException
  86. * @return Node[]
  87. */
  88. public function getDirectoryListing() {
  89. $folderContent = $this->view->getDirectoryContent($this->path);
  90. return array_map(function (FileInfo $info) {
  91. if ($info->getMimetype() === 'httpd/unix-directory') {
  92. return new Folder($this->root, $this->view, $info->getPath(), $info);
  93. } else {
  94. return new File($this->root, $this->view, $info->getPath(), $info);
  95. }
  96. }, $folderContent);
  97. }
  98. /**
  99. * @param string $path
  100. * @param FileInfo $info
  101. * @return File|Folder
  102. */
  103. protected function createNode($path, FileInfo $info = null) {
  104. if (is_null($info)) {
  105. $isDir = $this->view->is_dir($path);
  106. } else {
  107. $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
  108. }
  109. if ($isDir) {
  110. return new Folder($this->root, $this->view, $path, $info);
  111. } else {
  112. return new File($this->root, $this->view, $path, $info);
  113. }
  114. }
  115. /**
  116. * Get the node at $path
  117. *
  118. * @param string $path
  119. * @return \OC\Files\Node\Node
  120. * @throws \OCP\Files\NotFoundException
  121. */
  122. public function get($path) {
  123. return $this->root->get($this->getFullPath($path));
  124. }
  125. /**
  126. * @param string $path
  127. * @return bool
  128. */
  129. public function nodeExists($path) {
  130. try {
  131. $this->get($path);
  132. return true;
  133. } catch (NotFoundException $e) {
  134. return false;
  135. }
  136. }
  137. /**
  138. * @param string $path
  139. * @return \OC\Files\Node\Folder
  140. * @throws \OCP\Files\NotPermittedException
  141. */
  142. public function newFolder($path) {
  143. if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
  144. $fullPath = $this->getFullPath($path);
  145. $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
  146. $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
  147. $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
  148. $this->view->mkdir($fullPath);
  149. $node = new Folder($this->root, $this->view, $fullPath);
  150. $this->root->emit('\OC\Files', 'postWrite', array($node));
  151. $this->root->emit('\OC\Files', 'postCreate', array($node));
  152. return $node;
  153. } else {
  154. throw new NotPermittedException('No create permission for folder');
  155. }
  156. }
  157. /**
  158. * @param string $path
  159. * @return \OC\Files\Node\File
  160. * @throws \OCP\Files\NotPermittedException
  161. */
  162. public function newFile($path) {
  163. if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
  164. $fullPath = $this->getFullPath($path);
  165. $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
  166. $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
  167. $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
  168. $this->view->touch($fullPath);
  169. $node = new File($this->root, $this->view, $fullPath);
  170. $this->root->emit('\OC\Files', 'postWrite', array($node));
  171. $this->root->emit('\OC\Files', 'postCreate', array($node));
  172. return $node;
  173. } else {
  174. throw new NotPermittedException('No create permission for path');
  175. }
  176. }
  177. /**
  178. * search for files with the name matching $query
  179. *
  180. * @param string|ISearchOperator $query
  181. * @return \OC\Files\Node\Node[]
  182. */
  183. public function search($query) {
  184. if (is_string($query)) {
  185. return $this->searchCommon('search', array('%' . $query . '%'));
  186. } else {
  187. return $this->searchCommon('searchQuery', array($query));
  188. }
  189. }
  190. /**
  191. * search for files by mimetype
  192. *
  193. * @param string $mimetype
  194. * @return Node[]
  195. */
  196. public function searchByMime($mimetype) {
  197. return $this->searchCommon('searchByMime', array($mimetype));
  198. }
  199. /**
  200. * search for files by tag
  201. *
  202. * @param string|int $tag name or tag id
  203. * @param string $userId owner of the tags
  204. * @return Node[]
  205. */
  206. public function searchByTag($tag, $userId) {
  207. return $this->searchCommon('searchByTag', array($tag, $userId));
  208. }
  209. /**
  210. * @param string $method cache method
  211. * @param array $args call args
  212. * @return \OC\Files\Node\Node[]
  213. */
  214. private function searchCommon($method, $args) {
  215. $files = array();
  216. $rootLength = strlen($this->path);
  217. $mount = $this->root->getMount($this->path);
  218. $storage = $mount->getStorage();
  219. $internalPath = $mount->getInternalPath($this->path);
  220. $internalPath = rtrim($internalPath, '/');
  221. if ($internalPath !== '') {
  222. $internalPath = $internalPath . '/';
  223. }
  224. $internalRootLength = strlen($internalPath);
  225. $cache = $storage->getCache('');
  226. $results = call_user_func_array(array($cache, $method), $args);
  227. foreach ($results as $result) {
  228. if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
  229. $result['internalPath'] = $result['path'];
  230. $result['path'] = substr($result['path'], $internalRootLength);
  231. $result['storage'] = $storage;
  232. $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
  233. }
  234. }
  235. $mounts = $this->root->getMountsIn($this->path);
  236. foreach ($mounts as $mount) {
  237. $storage = $mount->getStorage();
  238. if ($storage) {
  239. $cache = $storage->getCache('');
  240. $relativeMountPoint = ltrim(substr($mount->getMountPoint(), $rootLength), '/');
  241. $results = call_user_func_array(array($cache, $method), $args);
  242. foreach ($results as $result) {
  243. $result['internalPath'] = $result['path'];
  244. $result['path'] = $relativeMountPoint . $result['path'];
  245. $result['storage'] = $storage;
  246. $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
  247. }
  248. }
  249. }
  250. return array_map(function (FileInfo $file) {
  251. return $this->createNode($file->getPath(), $file);
  252. }, $files);
  253. }
  254. /**
  255. * @param int $id
  256. * @return \OC\Files\Node\Node[]
  257. */
  258. public function getById($id) {
  259. $mountCache = $this->root->getUserMountCache();
  260. if (strpos($this->getPath(), '/', 1) > 0) {
  261. list(, $user) = explode('/', $this->getPath());
  262. } else {
  263. $user = null;
  264. }
  265. $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
  266. $mounts = $this->root->getMountsIn($this->path);
  267. $mounts[] = $this->root->getMount($this->path);
  268. /** @var IMountPoint[] $folderMounts */
  269. $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
  270. return $mountPoint->getMountPoint();
  271. }, $mounts), $mounts);
  272. /** @var ICachedMountInfo[] $mountsContainingFile */
  273. $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
  274. return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
  275. }));
  276. if (count($mountsContainingFile) === 0) {
  277. return [];
  278. }
  279. $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
  280. $mount = $folderMounts[$cachedMountInfo->getMountPoint()];
  281. $cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
  282. if (!$cacheEntry) {
  283. return null;
  284. }
  285. // cache jails will hide the "true" internal path
  286. $internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
  287. $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
  288. $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
  289. $absolutePath = rtrim($cachedMountInfo->getMountPoint() . $pathRelativeToMount, '/');
  290. return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
  291. $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
  292. \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
  293. ));
  294. }, $mountsContainingFile);
  295. $nodes = array_filter($nodes);
  296. return array_filter($nodes, function (Node $node) {
  297. return $this->getRelativePath($node->getPath());
  298. });
  299. }
  300. public function getFreeSpace() {
  301. return $this->view->free_space($this->path);
  302. }
  303. public function delete() {
  304. if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
  305. $this->sendHooks(array('preDelete'));
  306. $fileInfo = $this->getFileInfo();
  307. $this->view->rmdir($this->path);
  308. $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
  309. $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
  310. $this->exists = false;
  311. } else {
  312. throw new NotPermittedException('No delete permission for path');
  313. }
  314. }
  315. /**
  316. * Add a suffix to the name in case the file exists
  317. *
  318. * @param string $name
  319. * @return string
  320. * @throws NotPermittedException
  321. */
  322. public function getNonExistingName($name) {
  323. $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
  324. return trim($this->getRelativePath($uniqueName), '/');
  325. }
  326. /**
  327. * @param int $limit
  328. * @param int $offset
  329. * @return \OCP\Files\Node[]
  330. */
  331. public function getRecent($limit, $offset = 0) {
  332. $mimetypeLoader = \OC::$server->getMimeTypeLoader();
  333. $mounts = $this->root->getMountsIn($this->path);
  334. $mounts[] = $this->getMountPoint();
  335. $mounts = array_filter($mounts, function (IMountPoint $mount) {
  336. return $mount->getStorage();
  337. });
  338. $storageIds = array_map(function (IMountPoint $mount) {
  339. return $mount->getStorage()->getCache()->getNumericStorageId();
  340. }, $mounts);
  341. /** @var IMountPoint[] $mountMap */
  342. $mountMap = array_combine($storageIds, $mounts);
  343. $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
  344. //todo look into options of filtering path based on storage id (only search in files/ for home storage, filter by share root for shared, etc)
  345. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  346. $query = $builder
  347. ->select('f.*')
  348. ->from('filecache', 'f')
  349. ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
  350. ->andWhere($builder->expr()->orX(
  351. // handle non empty folders separate
  352. $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
  353. $builder->expr()->eq('f.size', new Literal(0))
  354. ))
  355. ->orderBy('f.mtime', 'DESC')
  356. ->setMaxResults($limit)
  357. ->setFirstResult($offset);
  358. $result = $query->execute()->fetchAll();
  359. $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
  360. $mount = $mountMap[$entry['storage']];
  361. $entry['internalPath'] = $entry['path'];
  362. $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
  363. $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
  364. $path = $this->getAbsolutePath($mount, $entry['path']);
  365. if (is_null($path)) {
  366. return null;
  367. }
  368. $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
  369. return $this->root->createNode($fileInfo->getPath(), $fileInfo);
  370. }, $result));
  371. return array_values(array_filter($files, function (Node $node) {
  372. $relative = $this->getRelativePath($node->getPath());
  373. return $relative !== null && $relative !== '/';
  374. }));
  375. }
  376. private function getAbsolutePath(IMountPoint $mount, $path) {
  377. $storage = $mount->getStorage();
  378. if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
  379. /** @var \OC\Files\Storage\Wrapper\Jail $storage */
  380. $jailRoot = $storage->getUnjailedPath('');
  381. $rootLength = strlen($jailRoot) + 1;
  382. if ($path === $jailRoot) {
  383. return $mount->getMountPoint();
  384. } else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
  385. return $mount->getMountPoint() . substr($path, $rootLength);
  386. } else {
  387. return null;
  388. }
  389. } else {
  390. return $mount->getMountPoint() . $path;
  391. }
  392. }
  393. }