RestoreAllFiles.php 9.3 KB

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