RestoreAllFiles.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-only
  5. */
  6. namespace OCA\Files_Trashbin\Command;
  7. use OC\Core\Command\Base;
  8. use OCA\Files_Trashbin\Trash\ITrashManager;
  9. use OCP\Files\IRootFolder;
  10. use OCP\IDBConnection;
  11. use OCP\IL10N;
  12. use OCP\IUserBackend;
  13. use OCP\IUserManager;
  14. use OCP\L10N\IFactory;
  15. use Symfony\Component\Console\Exception\InvalidOptionException;
  16. use Symfony\Component\Console\Input\InputArgument;
  17. use Symfony\Component\Console\Input\InputInterface;
  18. use Symfony\Component\Console\Input\InputOption;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. class RestoreAllFiles extends Base {
  21. private const SCOPE_ALL = 0;
  22. private const SCOPE_USER = 1;
  23. private const SCOPE_GROUPFOLDERS = 2;
  24. private static array $SCOPE_MAP = [
  25. 'user' => self::SCOPE_USER,
  26. 'groupfolders' => self::SCOPE_GROUPFOLDERS,
  27. 'all' => self::SCOPE_ALL
  28. ];
  29. /** @var IUserManager */
  30. protected $userManager;
  31. /** @var IRootFolder */
  32. protected $rootFolder;
  33. /** @var \OCP\IDBConnection */
  34. protected $dbConnection;
  35. protected ITrashManager $trashManager;
  36. /** @var IL10N */
  37. protected $l10n;
  38. /**
  39. * @param IRootFolder $rootFolder
  40. * @param IUserManager $userManager
  41. * @param IDBConnection $dbConnection
  42. * @param ITrashManager $trashManager
  43. * @param IFactory $l10nFactory
  44. */
  45. public function __construct(IRootFolder $rootFolder, IUserManager $userManager, IDBConnection $dbConnection, ITrashManager $trashManager, IFactory $l10nFactory) {
  46. parent::__construct();
  47. $this->userManager = $userManager;
  48. $this->rootFolder = $rootFolder;
  49. $this->dbConnection = $dbConnection;
  50. $this->trashManager = $trashManager;
  51. $this->l10n = $l10nFactory->get('files_trashbin');
  52. }
  53. protected function configure(): void {
  54. parent::configure();
  55. $this
  56. ->setName('trashbin:restore')
  57. ->setDescription('Restore all deleted files according to the given filters')
  58. ->addArgument(
  59. 'user_id',
  60. InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
  61. 'restore all deleted files of the given user(s)'
  62. )
  63. ->addOption(
  64. 'all-users',
  65. null,
  66. InputOption::VALUE_NONE,
  67. 'run action on all users'
  68. )
  69. ->addOption(
  70. 'scope',
  71. 's',
  72. InputOption::VALUE_OPTIONAL,
  73. 'Restore files from the given scope. Possible values are "user", "groupfolders" or "all"',
  74. 'user'
  75. )
  76. ->addOption(
  77. 'since',
  78. null,
  79. InputOption::VALUE_OPTIONAL,
  80. 'Only restore files deleted after the given date and time, see https://www.php.net/manual/en/function.strtotime.php for more information on supported formats'
  81. )
  82. ->addOption(
  83. 'until',
  84. null,
  85. InputOption::VALUE_OPTIONAL,
  86. 'Only restore files deleted before the given date and time, see https://www.php.net/manual/en/function.strtotime.php for more information on supported formats'
  87. )
  88. ->addOption(
  89. 'dry-run',
  90. 'd',
  91. InputOption::VALUE_NONE,
  92. 'Only show which files would be restored but do not perform any action'
  93. );
  94. }
  95. protected function execute(InputInterface $input, OutputInterface $output): int {
  96. /** @var string[] $users */
  97. $users = $input->getArgument('user_id');
  98. if ((!empty($users)) && ($input->getOption('all-users'))) {
  99. throw new InvalidOptionException('Either specify a user_id or --all-users');
  100. }
  101. [$scope, $since, $until, $dryRun] = $this->parseArgs($input);
  102. if (!empty($users)) {
  103. foreach ($users as $user) {
  104. $output->writeln("Restoring deleted files for user <info>$user</info>");
  105. $this->restoreDeletedFiles($user, $scope, $since, $until, $dryRun, $output);
  106. }
  107. } elseif ($input->getOption('all-users')) {
  108. $output->writeln('Restoring deleted files for all users');
  109. foreach ($this->userManager->getBackends() as $backend) {
  110. $name = get_class($backend);
  111. if ($backend instanceof IUserBackend) {
  112. $name = $backend->getBackendName();
  113. }
  114. $output->writeln("Restoring deleted files for users on backend <info>$name</info>");
  115. $limit = 500;
  116. $offset = 0;
  117. do {
  118. $users = $backend->getUsers('', $limit, $offset);
  119. foreach ($users as $user) {
  120. $output->writeln("<info>$user</info>");
  121. $this->restoreDeletedFiles($user, $scope, $since, $until, $dryRun, $output);
  122. }
  123. $offset += $limit;
  124. } while (count($users) >= $limit);
  125. }
  126. } else {
  127. throw new InvalidOptionException('Either specify a user_id or --all-users');
  128. }
  129. return 0;
  130. }
  131. /**
  132. * Restore deleted files for the given user according to the given filters
  133. */
  134. protected function restoreDeletedFiles(string $uid, int $scope, ?int $since, ?int $until, bool $dryRun, OutputInterface $output): void {
  135. \OC_Util::tearDownFS();
  136. \OC_Util::setupFS($uid);
  137. \OC_User::setUserId($uid);
  138. $user = $this->userManager->get($uid);
  139. if ($user === null) {
  140. $output->writeln("<error>Unknown user $uid</error>");
  141. return;
  142. }
  143. $userTrashItems = $this->filterTrashItems(
  144. $this->trashManager->listTrashRoot($user),
  145. $scope,
  146. $since,
  147. $until,
  148. $output);
  149. $trashCount = count($userTrashItems);
  150. if ($trashCount == 0) {
  151. $output->writeln("User has no deleted files in the trashbin matching the given filters");
  152. return;
  153. }
  154. $prepMsg = $dryRun ? 'Would restore' : 'Preparing to restore';
  155. $output->writeln("$prepMsg <info>$trashCount</info> files...");
  156. $count = 0;
  157. foreach($userTrashItems as $trashItem) {
  158. $filename = $trashItem->getName();
  159. $humanTime = $this->l10n->l('datetime', $trashItem->getDeletedTime());
  160. // We use getTitle() here instead of getOriginalLocation() because
  161. // for groupfolders this contains the groupfolder name itself as prefix
  162. // which makes it more human readable
  163. $location = $trashItem->getTitle();
  164. if ($dryRun) {
  165. $output->writeln("Would restore <info>$filename</info> originally deleted at <info>$humanTime</info> to <info>/$location</info>");
  166. continue;
  167. }
  168. $output->write("File <info>$filename</info> originally deleted at <info>$humanTime</info> restoring to <info>/$location</info>:");
  169. try {
  170. $trashItem->getTrashBackend()->restoreItem($trashItem);
  171. } catch (\Throwable $e) {
  172. $output->writeln(" <error>Failed: " . $e->getMessage() . "</error>");
  173. $output->writeln(" <error>" . $e->getTraceAsString() . "</error>", OutputInterface::VERBOSITY_VERY_VERBOSE);
  174. continue;
  175. }
  176. $count++;
  177. $output->writeln(" <info>success</info>");
  178. }
  179. if (!$dryRun) {
  180. $output->writeln("Successfully restored <info>$count</info> out of <info>$trashCount</info> files.");
  181. }
  182. }
  183. protected function parseArgs(InputInterface $input): array {
  184. $since = $this->parseTimestamp($input->getOption('since'));
  185. $until = $this->parseTimestamp($input->getOption('until'));
  186. if ($since !== null && $until !== null && $since > $until) {
  187. throw new InvalidOptionException('since must be before until');
  188. }
  189. return [
  190. $this->parseScope($input->getOption('scope')),
  191. $since,
  192. $until,
  193. $input->getOption('dry-run')
  194. ];
  195. }
  196. protected function parseScope(string $scope): int {
  197. if (isset(self::$SCOPE_MAP[$scope])) {
  198. return self::$SCOPE_MAP[$scope];
  199. }
  200. throw new InvalidOptionException("Invalid scope '$scope'");
  201. }
  202. protected function parseTimestamp(?string $timestamp): ?int {
  203. if ($timestamp === null) {
  204. return null;
  205. }
  206. $timestamp = strtotime($timestamp);
  207. if ($timestamp === false) {
  208. throw new InvalidOptionException("Invalid timestamp '$timestamp'");
  209. }
  210. return $timestamp;
  211. }
  212. protected function filterTrashItems(array $trashItems, int $scope, ?int $since, ?int $until, OutputInterface $output): array {
  213. $filteredTrashItems = [];
  214. foreach ($trashItems as $trashItem) {
  215. $trashItemClass = get_class($trashItem);
  216. // Check scope with exact class name for locally deleted files
  217. if ($scope === self::SCOPE_USER && $trashItemClass !== \OCA\Files_Trashbin\Trash\TrashItem::class) {
  218. $output->writeln("Skipping <info>" . $trashItem->getName() . "</info> because it is not a user trash item", OutputInterface::VERBOSITY_VERBOSE);
  219. continue;
  220. }
  221. /**
  222. * Check scope for groupfolders by string because the groupfolders app might not be installed.
  223. * That's why PSALM doesn't know the class GroupTrashItem.
  224. * @psalm-suppress RedundantCondition
  225. */
  226. if ($scope === self::SCOPE_GROUPFOLDERS && $trashItemClass !== 'OCA\GroupFolders\Trash\GroupTrashItem') {
  227. $output->writeln("Skipping <info>" . $trashItem->getName() . "</info> because it is not a groupfolders trash item", OutputInterface::VERBOSITY_VERBOSE);
  228. continue;
  229. }
  230. // Check left timestamp boundary
  231. if ($since !== null && $trashItem->getDeletedTime() <= $since) {
  232. $output->writeln("Skipping <info>" . $trashItem->getName() . "</info> because it was deleted before the 'since' timestamp", OutputInterface::VERBOSITY_VERBOSE);
  233. continue;
  234. }
  235. // Check right timestamp boundary
  236. if ($until !== null && $trashItem->getDeletedTime() >= $until) {
  237. $output->writeln("Skipping <info>" . $trashItem->getName() . "</info> because it was deleted after the 'until' timestamp", OutputInterface::VERBOSITY_VERBOSE);
  238. continue;
  239. }
  240. $filteredTrashItems[] = $trashItem;
  241. }
  242. return $filteredTrashItems;
  243. }
  244. }