SharedMount.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Björn Schießle <bjoern@schiessle.org>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Frédéric Fortier <frederic.fortier@oronospolytechnique.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Vincent Petry <vincent@nextcloud.com>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\Files_Sharing;
  30. use OCP\Cache\CappedMemoryCache;
  31. use OC\Files\Filesystem;
  32. use OC\Files\Mount\MountPoint;
  33. use OC\Files\Mount\MoveableMount;
  34. use OC\Files\View;
  35. use OCP\EventDispatcher\IEventDispatcher;
  36. use OCP\Files\Events\InvalidateMountCacheEvent;
  37. use OCP\Files\Storage\IStorageFactory;
  38. use OCP\ICache;
  39. use OCP\IUser;
  40. use OCP\Share\Events\VerifyMountPointEvent;
  41. /**
  42. * Shared mount points can be moved by the user
  43. */
  44. class SharedMount extends MountPoint implements MoveableMount {
  45. /**
  46. * @var \OCA\Files_Sharing\SharedStorage $storage
  47. */
  48. protected $storage = null;
  49. /**
  50. * @var \OC\Files\View
  51. */
  52. private $recipientView;
  53. private IUser $user;
  54. /** @var \OCP\Share\IShare */
  55. private $superShare;
  56. /** @var \OCP\Share\IShare[] */
  57. private $groupedShares;
  58. private IEventDispatcher $eventDispatcher;
  59. private ICache $cache;
  60. public function __construct(
  61. $storage,
  62. array $mountpoints,
  63. $arguments,
  64. IStorageFactory $loader,
  65. View $recipientView,
  66. CappedMemoryCache $folderExistCache,
  67. IEventDispatcher $eventDispatcher,
  68. IUser $user,
  69. ICache $cache
  70. ) {
  71. $this->user = $user;
  72. $this->recipientView = $recipientView;
  73. $this->eventDispatcher = $eventDispatcher;
  74. $this->cache = $cache;
  75. $this->superShare = $arguments['superShare'];
  76. $this->groupedShares = $arguments['groupedShares'];
  77. $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints, $folderExistCache);
  78. $absMountPoint = '/' . $user->getUID() . '/files' . $newMountPoint;
  79. parent::__construct($storage, $absMountPoint, $arguments, $loader, null, null, MountProvider::class);
  80. }
  81. /**
  82. * check if the parent folder exists otherwise move the mount point up
  83. *
  84. * @param \OCP\Share\IShare $share
  85. * @param SharedMount[] $mountpoints
  86. * @param CappedMemoryCache<bool> $folderExistCache
  87. * @return string
  88. */
  89. private function verifyMountPoint(
  90. \OCP\Share\IShare $share,
  91. array $mountpoints,
  92. CappedMemoryCache $folderExistCache
  93. ) {
  94. $cacheKey = $this->user->getUID() . '/' . $share->getId() . '/' . $share->getTarget();
  95. $cached = $this->cache->get($cacheKey);
  96. if ($cached !== null) {
  97. return $cached;
  98. }
  99. $mountPoint = basename($share->getTarget());
  100. $parent = dirname($share->getTarget());
  101. $event = new VerifyMountPointEvent($share, $this->recipientView, $parent);
  102. $this->eventDispatcher->dispatchTyped($event);
  103. $parent = $event->getParent();
  104. $cached = $folderExistCache->get($parent);
  105. if ($cached) {
  106. $parentExists = $cached;
  107. } else {
  108. $parentExists = $this->recipientView->is_dir($parent);
  109. $folderExistCache->set($parent, $parentExists);
  110. }
  111. if (!$parentExists) {
  112. $parent = Helper::getShareFolder($this->recipientView, $this->user->getUID());
  113. }
  114. $newMountPoint = $this->generateUniqueTarget(
  115. \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
  116. $this->recipientView,
  117. $mountpoints
  118. );
  119. if ($newMountPoint !== $share->getTarget()) {
  120. $this->updateFileTarget($newMountPoint, $share);
  121. }
  122. $this->cache->set($cacheKey, $newMountPoint, 60 * 60);
  123. return $newMountPoint;
  124. }
  125. /**
  126. * update fileTarget in the database if the mount point changed
  127. *
  128. * @param string $newPath
  129. * @param \OCP\Share\IShare $share
  130. * @return bool
  131. */
  132. private function updateFileTarget($newPath, &$share) {
  133. $share->setTarget($newPath);
  134. foreach ($this->groupedShares as $tmpShare) {
  135. $tmpShare->setTarget($newPath);
  136. \OC::$server->getShareManager()->moveShare($tmpShare, $this->user->getUID());
  137. }
  138. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent($this->user));
  139. }
  140. /**
  141. * @param string $path
  142. * @param View $view
  143. * @param SharedMount[] $mountpoints
  144. * @return mixed
  145. */
  146. private function generateUniqueTarget($path, $view, array $mountpoints) {
  147. $pathinfo = pathinfo($path);
  148. $ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
  149. $name = $pathinfo['filename'];
  150. $dir = $pathinfo['dirname'];
  151. $i = 2;
  152. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  153. while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
  154. $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
  155. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  156. $i++;
  157. }
  158. return $path;
  159. }
  160. /**
  161. * Format a path to be relative to the /user/files/ directory
  162. *
  163. * @param string $path the absolute path
  164. * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
  165. * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
  166. */
  167. protected function stripUserFilesPath($path) {
  168. $trimmed = ltrim($path, '/');
  169. $split = explode('/', $trimmed);
  170. // it is not a file relative to data/user/files
  171. if (count($split) < 3 || $split[1] !== 'files') {
  172. \OC::$server->getLogger()->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
  173. throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
  174. }
  175. // skip 'user' and 'files'
  176. $sliced = array_slice($split, 2);
  177. $relPath = implode('/', $sliced);
  178. return '/' . $relPath;
  179. }
  180. /**
  181. * Move the mount point to $target
  182. *
  183. * @param string $target the target mount point
  184. * @return bool
  185. */
  186. public function moveMount($target) {
  187. $relTargetPath = $this->stripUserFilesPath($target);
  188. $share = $this->storage->getShare();
  189. $result = true;
  190. try {
  191. $this->updateFileTarget($relTargetPath, $share);
  192. $this->setMountPoint($target);
  193. $this->storage->setMountPoint($relTargetPath);
  194. } catch (\Exception $e) {
  195. \OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"']);
  196. }
  197. return $result;
  198. }
  199. /**
  200. * Remove the mount points
  201. *
  202. * @return bool
  203. */
  204. public function removeMount() {
  205. $mountManager = \OC\Files\Filesystem::getMountManager();
  206. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  207. $storage = $this->getStorage();
  208. $result = $storage->unshareStorage();
  209. $mountManager->removeMount($this->mountPoint);
  210. return $result;
  211. }
  212. /**
  213. * @return \OCP\Share\IShare
  214. */
  215. public function getShare() {
  216. return $this->superShare;
  217. }
  218. /**
  219. * @return \OCP\Share\IShare[]
  220. */
  221. public function getGroupedShares(): array {
  222. return $this->groupedShares;
  223. }
  224. /**
  225. * Get the file id of the root of the storage
  226. *
  227. * @return int
  228. */
  229. public function getStorageRootId() {
  230. return $this->getShare()->getNodeId();
  231. }
  232. /**
  233. * @return int
  234. */
  235. public function getNumericStorageId() {
  236. if (!is_null($this->getShare()->getNodeCacheEntry())) {
  237. return $this->getShare()->getNodeCacheEntry()->getStorageId();
  238. } else {
  239. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  240. $query = $builder->select('storage')
  241. ->from('filecache')
  242. ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
  243. $result = $query->execute();
  244. $row = $result->fetch();
  245. $result->closeCursor();
  246. if ($row) {
  247. return (int)$row['storage'];
  248. }
  249. return -1;
  250. }
  251. }
  252. public function getMountType() {
  253. return 'shared';
  254. }
  255. }