SharedMount.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_Sharing;
  8. use OC\Files\Filesystem;
  9. use OC\Files\Mount\MountPoint;
  10. use OC\Files\Mount\MoveableMount;
  11. use OC\Files\View;
  12. use OCP\Cache\CappedMemoryCache;
  13. use OCP\EventDispatcher\IEventDispatcher;
  14. use OCP\Files\Events\InvalidateMountCacheEvent;
  15. use OCP\Files\Storage\IStorageFactory;
  16. use OCP\ICache;
  17. use OCP\IUser;
  18. use OCP\Share\Events\VerifyMountPointEvent;
  19. use Psr\Log\LoggerInterface;
  20. /**
  21. * Shared mount points can be moved by the user
  22. */
  23. class SharedMount extends MountPoint implements MoveableMount, ISharedMountPoint {
  24. /**
  25. * @var \OCA\Files_Sharing\SharedStorage $storage
  26. */
  27. protected $storage = null;
  28. /**
  29. * @var \OC\Files\View
  30. */
  31. private $recipientView;
  32. private IUser $user;
  33. /** @var \OCP\Share\IShare */
  34. private $superShare;
  35. /** @var \OCP\Share\IShare[] */
  36. private $groupedShares;
  37. private IEventDispatcher $eventDispatcher;
  38. private ICache $cache;
  39. public function __construct(
  40. $storage,
  41. array $mountpoints,
  42. $arguments,
  43. IStorageFactory $loader,
  44. View $recipientView,
  45. CappedMemoryCache $folderExistCache,
  46. IEventDispatcher $eventDispatcher,
  47. IUser $user,
  48. ICache $cache
  49. ) {
  50. $this->user = $user;
  51. $this->recipientView = $recipientView;
  52. $this->eventDispatcher = $eventDispatcher;
  53. $this->cache = $cache;
  54. $this->superShare = $arguments['superShare'];
  55. $this->groupedShares = $arguments['groupedShares'];
  56. $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints, $folderExistCache);
  57. $absMountPoint = '/' . $user->getUID() . '/files' . $newMountPoint;
  58. parent::__construct($storage, $absMountPoint, $arguments, $loader, null, null, MountProvider::class);
  59. }
  60. /**
  61. * check if the parent folder exists otherwise move the mount point up
  62. *
  63. * @param \OCP\Share\IShare $share
  64. * @param SharedMount[] $mountpoints
  65. * @param CappedMemoryCache<bool> $folderExistCache
  66. * @return string
  67. */
  68. private function verifyMountPoint(
  69. \OCP\Share\IShare $share,
  70. array $mountpoints,
  71. CappedMemoryCache $folderExistCache
  72. ) {
  73. $cacheKey = $this->user->getUID() . '/' . $share->getId() . '/' . $share->getTarget();
  74. $cached = $this->cache->get($cacheKey);
  75. if ($cached !== null) {
  76. return $cached;
  77. }
  78. $mountPoint = basename($share->getTarget());
  79. $parent = dirname($share->getTarget());
  80. $event = new VerifyMountPointEvent($share, $this->recipientView, $parent);
  81. $this->eventDispatcher->dispatchTyped($event);
  82. $parent = $event->getParent();
  83. $cached = $folderExistCache->get($parent);
  84. if ($cached) {
  85. $parentExists = $cached;
  86. } else {
  87. $parentExists = $this->recipientView->is_dir($parent);
  88. $folderExistCache->set($parent, $parentExists);
  89. }
  90. if (!$parentExists) {
  91. $parent = Helper::getShareFolder($this->recipientView, $this->user->getUID());
  92. }
  93. $newMountPoint = $this->generateUniqueTarget(
  94. \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
  95. $this->recipientView,
  96. $mountpoints
  97. );
  98. if ($newMountPoint !== $share->getTarget()) {
  99. $this->updateFileTarget($newMountPoint, $share);
  100. }
  101. $this->cache->set($cacheKey, $newMountPoint, 60 * 60);
  102. return $newMountPoint;
  103. }
  104. /**
  105. * update fileTarget in the database if the mount point changed
  106. *
  107. * @param string $newPath
  108. * @param \OCP\Share\IShare $share
  109. * @return bool
  110. */
  111. private function updateFileTarget($newPath, &$share) {
  112. $share->setTarget($newPath);
  113. foreach ($this->groupedShares as $tmpShare) {
  114. $tmpShare->setTarget($newPath);
  115. \OC::$server->getShareManager()->moveShare($tmpShare, $this->user->getUID());
  116. }
  117. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent($this->user));
  118. }
  119. /**
  120. * @param string $path
  121. * @param View $view
  122. * @param SharedMount[] $mountpoints
  123. * @return mixed
  124. */
  125. private function generateUniqueTarget($path, $view, array $mountpoints) {
  126. $pathinfo = pathinfo($path);
  127. $ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
  128. $name = $pathinfo['filename'];
  129. $dir = $pathinfo['dirname'];
  130. $i = 2;
  131. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  132. while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
  133. $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
  134. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  135. $i++;
  136. }
  137. return $path;
  138. }
  139. /**
  140. * Format a path to be relative to the /user/files/ directory
  141. *
  142. * @param string $path the absolute path
  143. * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
  144. * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
  145. */
  146. protected function stripUserFilesPath($path) {
  147. $trimmed = ltrim($path, '/');
  148. $split = explode('/', $trimmed);
  149. // it is not a file relative to data/user/files
  150. if (count($split) < 3 || $split[1] !== 'files') {
  151. \OCP\Server::get(LoggerInterface::class)->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
  152. throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
  153. }
  154. // skip 'user' and 'files'
  155. $sliced = array_slice($split, 2);
  156. $relPath = implode('/', $sliced);
  157. return '/' . $relPath;
  158. }
  159. /**
  160. * Move the mount point to $target
  161. *
  162. * @param string $target the target mount point
  163. * @return bool
  164. */
  165. public function moveMount($target) {
  166. $relTargetPath = $this->stripUserFilesPath($target);
  167. $share = $this->storage->getShare();
  168. $result = true;
  169. try {
  170. $this->updateFileTarget($relTargetPath, $share);
  171. $this->setMountPoint($target);
  172. $this->storage->setMountPoint($relTargetPath);
  173. } catch (\Exception $e) {
  174. \OCP\Server::get(LoggerInterface::class)->error(
  175. 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
  176. [
  177. 'app' => 'files_sharing',
  178. 'exception' => $e,
  179. ]
  180. );
  181. }
  182. return $result;
  183. }
  184. /**
  185. * Remove the mount points
  186. *
  187. * @return bool
  188. */
  189. public function removeMount() {
  190. $mountManager = \OC\Files\Filesystem::getMountManager();
  191. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  192. $storage = $this->getStorage();
  193. $result = $storage->unshareStorage();
  194. $mountManager->removeMount($this->mountPoint);
  195. return $result;
  196. }
  197. /**
  198. * @return \OCP\Share\IShare
  199. */
  200. public function getShare() {
  201. return $this->superShare;
  202. }
  203. /**
  204. * @return \OCP\Share\IShare[]
  205. */
  206. public function getGroupedShares(): array {
  207. return $this->groupedShares;
  208. }
  209. /**
  210. * Get the file id of the root of the storage
  211. *
  212. * @return int
  213. */
  214. public function getStorageRootId() {
  215. return $this->getShare()->getNodeId();
  216. }
  217. /**
  218. * @return int
  219. */
  220. public function getNumericStorageId() {
  221. if (!is_null($this->getShare()->getNodeCacheEntry())) {
  222. return $this->getShare()->getNodeCacheEntry()->getStorageId();
  223. } else {
  224. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  225. $query = $builder->select('storage')
  226. ->from('filecache')
  227. ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
  228. $result = $query->execute();
  229. $row = $result->fetch();
  230. $result->closeCursor();
  231. if ($row) {
  232. return (int)$row['storage'];
  233. }
  234. return -1;
  235. }
  236. }
  237. public function getMountType() {
  238. return 'shared';
  239. }
  240. }