SharedMount.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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, ISharedMountPoint {
  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. if ($folderExistCache->hasKey($parent)) {
  105. $parentExists = $folderExistCache->get($parent);
  106. } else {
  107. $parentExists = $this->recipientView->is_dir($parent);
  108. $folderExistCache->set($parent, $parentExists);
  109. }
  110. if (!$parentExists) {
  111. $parent = Helper::getShareFolder($this->recipientView, $this->user->getUID());
  112. }
  113. $newMountPoint = $this->generateUniqueTarget(
  114. \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
  115. $this->recipientView,
  116. $mountpoints
  117. );
  118. if ($newMountPoint !== $share->getTarget()) {
  119. $this->updateFileTarget($newMountPoint, $share);
  120. }
  121. $this->cache->set($cacheKey, $newMountPoint, 60 * 60);
  122. return $newMountPoint;
  123. }
  124. /**
  125. * update fileTarget in the database if the mount point changed
  126. *
  127. * @param string $newPath
  128. * @param \OCP\Share\IShare $share
  129. * @return bool
  130. */
  131. private function updateFileTarget($newPath, &$share) {
  132. $share->setTarget($newPath);
  133. foreach ($this->groupedShares as $tmpShare) {
  134. $tmpShare->setTarget($newPath);
  135. \OC::$server->getShareManager()->moveShare($tmpShare, $this->user->getUID());
  136. }
  137. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent($this->user));
  138. }
  139. /**
  140. * @param string $path
  141. * @param View $view
  142. * @param SharedMount[] $mountpoints
  143. * @return mixed
  144. */
  145. private function generateUniqueTarget($path, $view, array $mountpoints) {
  146. $pathinfo = pathinfo($path);
  147. $ext = isset($pathinfo['extension']) ? '.' . $pathinfo['extension'] : '';
  148. $name = $pathinfo['filename'];
  149. $dir = $pathinfo['dirname'];
  150. $i = 2;
  151. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  152. while ($view->file_exists($path) || isset($mountpoints[$absolutePath])) {
  153. $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
  154. $absolutePath = $this->recipientView->getAbsolutePath($path) . '/';
  155. $i++;
  156. }
  157. return $path;
  158. }
  159. /**
  160. * Format a path to be relative to the /user/files/ directory
  161. *
  162. * @param string $path the absolute path
  163. * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
  164. * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
  165. */
  166. protected function stripUserFilesPath($path) {
  167. $trimmed = ltrim($path, '/');
  168. $split = explode('/', $trimmed);
  169. // it is not a file relative to data/user/files
  170. if (count($split) < 3 || $split[1] !== 'files') {
  171. \OC::$server->getLogger()->error('Can not strip userid and "files/" from path: ' . $path, ['app' => 'files_sharing']);
  172. throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
  173. }
  174. // skip 'user' and 'files'
  175. $sliced = array_slice($split, 2);
  176. $relPath = implode('/', $sliced);
  177. return '/' . $relPath;
  178. }
  179. /**
  180. * Move the mount point to $target
  181. *
  182. * @param string $target the target mount point
  183. * @return bool
  184. */
  185. public function moveMount($target) {
  186. $relTargetPath = $this->stripUserFilesPath($target);
  187. $share = $this->storage->getShare();
  188. $result = true;
  189. try {
  190. $this->updateFileTarget($relTargetPath, $share);
  191. $this->setMountPoint($target);
  192. $this->storage->setMountPoint($relTargetPath);
  193. } catch (\Exception $e) {
  194. \OC::$server->getLogger()->logException($e, ['app' => 'files_sharing', 'message' => 'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"']);
  195. }
  196. return $result;
  197. }
  198. /**
  199. * Remove the mount points
  200. *
  201. * @return bool
  202. */
  203. public function removeMount() {
  204. $mountManager = \OC\Files\Filesystem::getMountManager();
  205. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  206. $storage = $this->getStorage();
  207. $result = $storage->unshareStorage();
  208. $mountManager->removeMount($this->mountPoint);
  209. return $result;
  210. }
  211. /**
  212. * @return \OCP\Share\IShare
  213. */
  214. public function getShare() {
  215. return $this->superShare;
  216. }
  217. /**
  218. * @return \OCP\Share\IShare[]
  219. */
  220. public function getGroupedShares(): array {
  221. return $this->groupedShares;
  222. }
  223. /**
  224. * Get the file id of the root of the storage
  225. *
  226. * @return int
  227. */
  228. public function getStorageRootId() {
  229. return $this->getShare()->getNodeId();
  230. }
  231. /**
  232. * @return int
  233. */
  234. public function getNumericStorageId() {
  235. if (!is_null($this->getShare()->getNodeCacheEntry())) {
  236. return $this->getShare()->getNodeCacheEntry()->getStorageId();
  237. } else {
  238. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  239. $query = $builder->select('storage')
  240. ->from('filecache')
  241. ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
  242. $result = $query->execute();
  243. $row = $result->fetch();
  244. $result->closeCursor();
  245. if ($row) {
  246. return (int)$row['storage'];
  247. }
  248. return -1;
  249. }
  250. }
  251. public function getMountType() {
  252. return 'shared';
  253. }
  254. }