1
0

TransferOwnership.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Carla Schroder <carla@owncloud.com>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. * @author Sujith H <sharidasan@owncloud.com>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Files\Command;
  29. use OC\Files\Filesystem;
  30. use OC\Files\View;
  31. use OCP\Files\FileInfo;
  32. use OCP\Files\IHomeStorage;
  33. use OCP\Files\IRootFolder;
  34. use OCP\Files\Mount\IMountManager;
  35. use OCP\IUser;
  36. use OCP\IUserManager;
  37. use OCP\Share\IManager;
  38. use OCP\Share\IShare;
  39. use Symfony\Component\Console\Command\Command;
  40. use Symfony\Component\Console\Input\InputOption;
  41. use Symfony\Component\Console\Helper\ProgressBar;
  42. use Symfony\Component\Console\Input\InputArgument;
  43. use Symfony\Component\Console\Input\InputInterface;
  44. use Symfony\Component\Console\Output\OutputInterface;
  45. class TransferOwnership extends Command {
  46. /** @var IUserManager $userManager */
  47. private $userManager;
  48. /** @var IManager */
  49. private $shareManager;
  50. /** @var IMountManager */
  51. private $mountManager;
  52. /** @var FileInfo[] */
  53. private $allFiles = [];
  54. /** @var FileInfo[] */
  55. private $encryptedFiles = [];
  56. /** @var IShare[] */
  57. private $shares = [];
  58. /** @var string */
  59. private $sourceUser;
  60. /** @var string */
  61. private $destinationUser;
  62. /** @var string */
  63. private $sourcePath;
  64. /** @var string */
  65. private $finalTarget;
  66. public function __construct(IUserManager $userManager,
  67. IManager $shareManager,
  68. IMountManager $mountManager,
  69. IRootFolder $rootFolder) {
  70. $this->userManager = $userManager;
  71. $this->shareManager = $shareManager;
  72. $this->mountManager = $mountManager;
  73. parent::__construct();
  74. }
  75. protected function configure() {
  76. $this
  77. ->setName('files:transfer-ownership')
  78. ->setDescription('All files and folders are moved to another user - shares are moved as well.')
  79. ->addArgument(
  80. 'source-user',
  81. InputArgument::REQUIRED,
  82. 'owner of files which shall be moved'
  83. )
  84. ->addArgument(
  85. 'destination-user',
  86. InputArgument::REQUIRED,
  87. 'user who will be the new owner of the files'
  88. )
  89. ->addOption(
  90. 'path',
  91. null,
  92. InputOption::VALUE_REQUIRED,
  93. 'selectively provide the path to transfer. For example --path="folder_name"',
  94. ''
  95. );
  96. }
  97. protected function execute(InputInterface $input, OutputInterface $output) {
  98. $sourceUserObject = $this->userManager->get($input->getArgument('source-user'));
  99. $destinationUserObject = $this->userManager->get($input->getArgument('destination-user'));
  100. if (!$sourceUserObject instanceof IUser) {
  101. $output->writeln("<error>Unknown source user $this->sourceUser</error>");
  102. return 1;
  103. }
  104. if (!$destinationUserObject instanceof IUser) {
  105. $output->writeln("<error>Unknown destination user $this->destinationUser</error>");
  106. return 1;
  107. }
  108. $this->sourceUser = $sourceUserObject->getUID();
  109. $this->destinationUser = $destinationUserObject->getUID();
  110. $sourcePathOption = ltrim($input->getOption('path'), '/');
  111. $this->sourcePath = rtrim($this->sourceUser . '/files/' . $sourcePathOption, '/');
  112. // target user has to be ready
  113. if (!\OC::$server->getEncryptionManager()->isReadyForUser($this->destinationUser)) {
  114. $output->writeln("<error>The target user is not ready to accept files. The user has at least to be logged in once.</error>");
  115. return 2;
  116. }
  117. $date = date('Y-m-d H-i-s');
  118. $this->finalTarget = "$this->destinationUser/files/transferred from $this->sourceUser on $date";
  119. // setup filesystem
  120. Filesystem::initMountPoints($this->sourceUser);
  121. Filesystem::initMountPoints($this->destinationUser);
  122. $view = new View();
  123. if (!$view->is_dir($this->sourcePath)) {
  124. $output->writeln("<error>Unknown path provided: $sourcePathOption</error>");
  125. return 1;
  126. }
  127. // analyse source folder
  128. $this->analyse($output);
  129. // collect all the shares
  130. $this->collectUsersShares($output);
  131. // transfer the files
  132. $this->transfer($output);
  133. // restore the shares
  134. $this->restoreShares($output);
  135. }
  136. private function walkFiles(View $view, $path, \Closure $callBack) {
  137. foreach ($view->getDirectoryContent($path) as $fileInfo) {
  138. if (!$callBack($fileInfo)) {
  139. return;
  140. }
  141. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  142. $this->walkFiles($view, $fileInfo->getPath(), $callBack);
  143. }
  144. }
  145. }
  146. /**
  147. * @param OutputInterface $output
  148. * @throws \Exception
  149. */
  150. protected function analyse(OutputInterface $output) {
  151. $view = new View();
  152. $output->writeln('Validating quota');
  153. $size = $view->getFileInfo($this->sourcePath, false)->getSize(false);
  154. $freeSpace = $view->free_space($this->destinationUser . '/files/');
  155. if ($size > $freeSpace) {
  156. $output->writeln('<error>Target user does not have enough free space available</error>');
  157. throw new \Exception('Execution terminated');
  158. }
  159. $output->writeln("Analysing files of $this->sourceUser ...");
  160. $progress = new ProgressBar($output);
  161. $progress->start();
  162. $self = $this;
  163. $this->walkFiles($view, $this->sourcePath,
  164. function (FileInfo $fileInfo) use ($progress, $self) {
  165. if ($fileInfo->getType() === FileInfo::TYPE_FOLDER) {
  166. // only analyze into folders from main storage,
  167. if (!$fileInfo->getStorage()->instanceOfStorage(IHomeStorage::class)) {
  168. return false;
  169. }
  170. return true;
  171. }
  172. $progress->advance();
  173. $this->allFiles[] = $fileInfo;
  174. if ($fileInfo->isEncrypted()) {
  175. $this->encryptedFiles[] = $fileInfo;
  176. }
  177. return true;
  178. });
  179. $progress->finish();
  180. $output->writeln('');
  181. // no file is allowed to be encrypted
  182. if (!empty($this->encryptedFiles)) {
  183. $output->writeln("<error>Some files are encrypted - please decrypt them first</error>");
  184. foreach($this->encryptedFiles as $encryptedFile) {
  185. /** @var FileInfo $encryptedFile */
  186. $output->writeln(" " . $encryptedFile->getPath());
  187. }
  188. throw new \Exception('Execution terminated.');
  189. }
  190. }
  191. /**
  192. * @param OutputInterface $output
  193. */
  194. private function collectUsersShares(OutputInterface $output) {
  195. $output->writeln("Collecting all share information for files and folder of $this->sourceUser ...");
  196. $progress = new ProgressBar($output, count($this->shares));
  197. foreach([\OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_ROOM] as $shareType) {
  198. $offset = 0;
  199. while (true) {
  200. $sharePage = $this->shareManager->getSharesBy($this->sourceUser, $shareType, null, true, 50, $offset);
  201. $progress->advance(count($sharePage));
  202. if (empty($sharePage)) {
  203. break;
  204. }
  205. $this->shares = array_merge($this->shares, $sharePage);
  206. $offset += 50;
  207. }
  208. }
  209. $progress->finish();
  210. $output->writeln('');
  211. }
  212. /**
  213. * @param OutputInterface $output
  214. */
  215. protected function transfer(OutputInterface $output) {
  216. $view = new View();
  217. $output->writeln("Transferring files to $this->finalTarget ...");
  218. // This change will help user to transfer the folder specified using --path option.
  219. // Else only the content inside folder is transferred which is not correct.
  220. if($this->sourcePath !== "$this->sourceUser/files") {
  221. $view->mkdir($this->finalTarget);
  222. $this->finalTarget = $this->finalTarget . '/' . basename($this->sourcePath);
  223. }
  224. $view->rename($this->sourcePath, $this->finalTarget);
  225. if (!is_dir("$this->sourceUser/files")) {
  226. // because the files folder is moved away we need to recreate it
  227. $view->mkdir("$this->sourceUser/files");
  228. }
  229. }
  230. /**
  231. * @param OutputInterface $output
  232. */
  233. private function restoreShares(OutputInterface $output) {
  234. $output->writeln("Restoring shares ...");
  235. $progress = new ProgressBar($output, count($this->shares));
  236. foreach($this->shares as $share) {
  237. try {
  238. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  239. $share->getSharedWith() === $this->destinationUser) {
  240. // Unmount the shares before deleting, so we don't try to get the storage later on.
  241. $shareMountPoint = $this->mountManager->find('/' . $this->destinationUser . '/files' . $share->getTarget());
  242. if ($shareMountPoint) {
  243. $this->mountManager->removeMount($shareMountPoint->getMountPoint());
  244. }
  245. $this->shareManager->deleteShare($share);
  246. } else {
  247. if ($share->getShareOwner() === $this->sourceUser) {
  248. $share->setShareOwner($this->destinationUser);
  249. }
  250. if ($share->getSharedBy() === $this->sourceUser) {
  251. $share->setSharedBy($this->destinationUser);
  252. }
  253. $this->shareManager->updateShare($share);
  254. }
  255. } catch (\OCP\Files\NotFoundException $e) {
  256. $output->writeln('<error>Share with id ' . $share->getId() . ' points at deleted file, skipping</error>');
  257. } catch (\Exception $e) {
  258. $output->writeln('<error>Could not restore share with id ' . $share->getId() . ':' . $e->getTraceAsString() . '</error>');
  259. }
  260. $progress->advance();
  261. }
  262. $progress->finish();
  263. $output->writeln('');
  264. }
  265. }