You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OwnershipTransferService.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Julius Härtl <jus@bitgrid.net>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author rawtaz <rawtaz@users.noreply.github.com>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Sascha Wiswedel <sascha.wiswedel@nextcloud.com>
  13. * @author Tobia De Koninck <LEDfan@users.noreply.github.com>
  14. *
  15. * @license GNU AGPL version 3 or any later version
  16. *
  17. * This program is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License as
  19. * published by the Free Software Foundation, either version 3 of the
  20. * License, or (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. *
  30. */
  31. namespace OCA\Files\Service;
  32. use Closure;
  33. use OC\Files\Filesystem;
  34. use OC\Files\View;
  35. use OCA\Files\Exception\TransferOwnershipException;
  36. use OCP\Encryption\IManager as IEncryptionManager;
  37. use OCP\Files\Config\IUserMountCache;
  38. use OCP\Files\FileInfo;
  39. use OCP\Files\IHomeStorage;
  40. use OCP\Files\InvalidPathException;
  41. use OCP\Files\Mount\IMountManager;
  42. use OCP\IUser;
  43. use OCP\Share\IManager as IShareManager;
  44. use OCP\Share\IShare;
  45. use Symfony\Component\Console\Helper\ProgressBar;
  46. use Symfony\Component\Console\Output\NullOutput;
  47. use Symfony\Component\Console\Output\OutputInterface;
  48. use function array_merge;
  49. use function basename;
  50. use function count;
  51. use function date;
  52. use function is_dir;
  53. use function rtrim;
  54. class OwnershipTransferService {
  55. /** @var IEncryptionManager */
  56. private $encryptionManager;
  57. /** @var IShareManager */
  58. private $shareManager;
  59. /** @var IMountManager */
  60. private $mountManager;
  61. /** @var IUserMountCache */
  62. private $userMountCache;
  63. public function __construct(IEncryptionManager $manager,
  64. IShareManager $shareManager,
  65. IMountManager $mountManager,
  66. IUserMountCache $userMountCache) {
  67. $this->encryptionManager = $manager;
  68. $this->shareManager = $shareManager;
  69. $this->mountManager = $mountManager;
  70. $this->userMountCache = $userMountCache;
  71. }
  72. /**
  73. * @param IUser $sourceUser
  74. * @param IUser $destinationUser
  75. * @param string $path
  76. *
  77. * @param OutputInterface|null $output
  78. * @param bool $move
  79. * @throws TransferOwnershipException
  80. * @throws \OC\User\NoUserException
  81. */
  82. public function transfer(IUser $sourceUser,
  83. IUser $destinationUser,
  84. string $path,
  85. ?OutputInterface $output = null,
  86. bool $move = false,
  87. bool $firstLogin = false): void {
  88. $output = $output ?? new NullOutput();
  89. $sourceUid = $sourceUser->getUID();
  90. $destinationUid = $destinationUser->getUID();
  91. $sourcePath = rtrim($sourceUid . '/files/' . $path, '/');
  92. // target user has to be ready
  93. if ($destinationUser->getLastLogin() === 0 || !$this->encryptionManager->isReadyForUser($destinationUid)) {
  94. throw new TransferOwnershipException("The target user is not ready to accept files. The user has at least to have logged in once.", 2);
  95. }
  96. // setup filesystem
  97. Filesystem::initMountPoints($sourceUid);
  98. Filesystem::initMountPoints($destinationUid);
  99. $view = new View();
  100. if ($move) {
  101. $finalTarget = "$destinationUid/files/";
  102. } else {
  103. $date = date('Y-m-d H-i-s');
  104. // Remove some characters which are prone to cause errors
  105. $cleanUserName = str_replace(['\\', '/', ':', '.', '?', '#', '\'', '"'], '-', $sourceUser->getDisplayName());
  106. // Replace multiple dashes with one dash
  107. $cleanUserName = preg_replace('/-{2,}/s', '-', $cleanUserName);
  108. $cleanUserName = $cleanUserName ?: $sourceUid;
  109. $finalTarget = "$destinationUid/files/transferred from $cleanUserName on $date";
  110. try {
  111. $view->verifyPath(dirname($finalTarget), basename($finalTarget));
  112. } catch (InvalidPathException $e) {
  113. $finalTarget = "$destinationUid/files/transferred from $sourceUid on $date";
  114. }
  115. }
  116. if (!($view->is_dir($sourcePath) || $view->is_file($sourcePath))) {
  117. throw new TransferOwnershipException("Unknown path provided: $path", 1);
  118. }
  119. if ($move && (
  120. !$view->is_dir($finalTarget) || (
  121. !$firstLogin &&
  122. count($view->getDirectoryContent($finalTarget)) > 0
  123. )
  124. )
  125. ) {
  126. throw new TransferOwnershipException("Destination path does not exists or is not empty", 1);
  127. }
  128. // analyse source folder
  129. $this->analyse(
  130. $sourceUid,
  131. $destinationUid,
  132. $sourcePath,
  133. $view,
  134. $output
  135. );
  136. // collect all the shares
  137. $shares = $this->collectUsersShares(
  138. $sourceUid,
  139. $output,
  140. $view,
  141. $sourcePath
  142. );
  143. // transfer the files
  144. $this->transferFiles(
  145. $sourceUid,
  146. $sourcePath,
  147. $finalTarget,
  148. $view,
  149. $output
  150. );
  151. // restore the shares
  152. $this->restoreShares(
  153. $sourceUid,
  154. $destinationUid,
  155. $shares,
  156. $output
  157. );
  158. }
  159. private function walkFiles(View $view, $path, Closure $callBack) {
  160. foreach ($view->getDirectoryContent($path) as $fileInfo) {
  161. if (!$callBack($fileInfo)) {
  162. return;
  163. }
  164. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  165. $this->walkFiles($view, $fileInfo->getPath(), $callBack);
  166. }
  167. }
  168. }
  169. /**
  170. * @param OutputInterface $output
  171. *
  172. * @throws \Exception
  173. */
  174. protected function analyse(string $sourceUid,
  175. string $destinationUid,
  176. string $sourcePath,
  177. View $view,
  178. OutputInterface $output): void {
  179. $output->writeln('Validating quota');
  180. $size = $view->getFileInfo($sourcePath, false)->getSize(false);
  181. $freeSpace = $view->free_space($destinationUid . '/files/');
  182. if ($size > $freeSpace && $freeSpace !== FileInfo::SPACE_UNKNOWN) {
  183. $output->writeln('<error>Target user does not have enough free space available.</error>');
  184. throw new \Exception('Execution terminated.');
  185. }
  186. $output->writeln("Analysing files of $sourceUid ...");
  187. $progress = new ProgressBar($output);
  188. $progress->start();
  189. $encryptedFiles = [];
  190. $this->walkFiles($view, $sourcePath,
  191. function (FileInfo $fileInfo) use ($progress) {
  192. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  193. // only analyze into folders from main storage,
  194. if (!$fileInfo->getStorage()->instanceOfStorage(IHomeStorage::class)) {
  195. return false;
  196. }
  197. return true;
  198. }
  199. $progress->advance();
  200. if ($fileInfo->isEncrypted()) {
  201. $encryptedFiles[] = $fileInfo;
  202. }
  203. return true;
  204. });
  205. $progress->finish();
  206. $output->writeln('');
  207. // no file is allowed to be encrypted
  208. if (!empty($encryptedFiles)) {
  209. $output->writeln("<error>Some files are encrypted - please decrypt them first.</error>");
  210. foreach ($encryptedFiles as $encryptedFile) {
  211. /** @var FileInfo $encryptedFile */
  212. $output->writeln(" " . $encryptedFile->getPath());
  213. }
  214. throw new \Exception('Execution terminated.');
  215. }
  216. }
  217. private function collectUsersShares(string $sourceUid,
  218. OutputInterface $output,
  219. View $view,
  220. ?string $path = null): array {
  221. $output->writeln("Collecting all share information for files and folders of $sourceUid ...");
  222. $shares = [];
  223. $progress = new ProgressBar($output);
  224. foreach ([IShare::TYPE_GROUP, IShare::TYPE_USER, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_ROOM, IShare::TYPE_EMAIL, IShare::TYPE_CIRCLE] as $shareType) {
  225. $offset = 0;
  226. while (true) {
  227. $sharePage = $this->shareManager->getSharesBy($sourceUid, $shareType, null, true, 50, $offset);
  228. $progress->advance(count($sharePage));
  229. if (empty($sharePage)) {
  230. break;
  231. }
  232. if ($path !== null) {
  233. $sharePage = array_filter($sharePage, function (IShare $share) use ($view, $path) {
  234. try {
  235. $relativePath = $view->getPath($share->getNodeId());
  236. $singleFileTranfer = $view->is_file($path);
  237. if ($singleFileTranfer) {
  238. return Filesystem::normalizePath($relativePath) === Filesystem::normalizePath($path);
  239. }
  240. return mb_strpos(
  241. Filesystem::normalizePath($relativePath . '/', false),
  242. Filesystem::normalizePath($path . '/', false)) === 0;
  243. } catch (\Exception $e) {
  244. return false;
  245. }
  246. });
  247. }
  248. $shares = array_merge($shares, $sharePage);
  249. $offset += 50;
  250. }
  251. }
  252. $progress->finish();
  253. $output->writeln('');
  254. return $shares;
  255. }
  256. /**
  257. * @throws TransferOwnershipException
  258. */
  259. protected function transferFiles(string $sourceUid,
  260. string $sourcePath,
  261. string $finalTarget,
  262. View $view,
  263. OutputInterface $output): void {
  264. $output->writeln("Transferring files to $finalTarget ...");
  265. // This change will help user to transfer the folder specified using --path option.
  266. // Else only the content inside folder is transferred which is not correct.
  267. if ($sourcePath !== "$sourceUid/files") {
  268. $view->mkdir($finalTarget);
  269. $finalTarget = $finalTarget . '/' . basename($sourcePath);
  270. }
  271. if ($view->rename($sourcePath, $finalTarget) === false) {
  272. throw new TransferOwnershipException("Could not transfer files.", 1);
  273. }
  274. if (!is_dir("$sourceUid/files")) {
  275. // because the files folder is moved away we need to recreate it
  276. $view->mkdir("$sourceUid/files");
  277. }
  278. }
  279. private function restoreShares(string $sourceUid,
  280. string $destinationUid,
  281. array $shares,
  282. OutputInterface $output) {
  283. $output->writeln("Restoring shares ...");
  284. $progress = new ProgressBar($output, count($shares));
  285. foreach ($shares as $share) {
  286. try {
  287. if ($share->getShareType() === IShare::TYPE_USER &&
  288. $share->getSharedWith() === $destinationUid) {
  289. // Unmount the shares before deleting, so we don't try to get the storage later on.
  290. $shareMountPoint = $this->mountManager->find('/' . $destinationUid . '/files' . $share->getTarget());
  291. if ($shareMountPoint) {
  292. $this->mountManager->removeMount($shareMountPoint->getMountPoint());
  293. }
  294. $this->shareManager->deleteShare($share);
  295. } else {
  296. if ($share->getShareOwner() === $sourceUid) {
  297. $share->setShareOwner($destinationUid);
  298. }
  299. if ($share->getSharedBy() === $sourceUid) {
  300. $share->setSharedBy($destinationUid);
  301. }
  302. // trigger refetching of the node so that the new owner and mountpoint are taken into account
  303. // otherwise the checks on the share update will fail due to the original node not being available in the new user scope
  304. $this->userMountCache->clear();
  305. $share->setNodeId($share->getNode()->getId());
  306. $this->shareManager->updateShare($share);
  307. }
  308. } catch (\OCP\Files\NotFoundException $e) {
  309. $output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
  310. } catch (\Throwable $e) {
  311. $output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
  312. }
  313. $progress->advance();
  314. }
  315. $progress->finish();
  316. $output->writeln('');
  317. }
  318. }