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.

ScanAppData.php 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /**
  3. *
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author J0WI <J0WI@users.noreply.github.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Joel S <joel.devbox@protonmail.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. *
  13. * @license GNU AGPL version 3 or any later version
  14. *
  15. * This program is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License as
  17. * published by the Free Software Foundation, either version 3 of the
  18. * License, or (at your option) any later version.
  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
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. *
  28. */
  29. namespace OCA\Files\Command;
  30. use Doctrine\DBAL\Connection;
  31. use OC\Core\Command\Base;
  32. use OC\Core\Command\InterruptedException;
  33. use OC\ForbiddenException;
  34. use OCP\EventDispatcher\IEventDispatcher;
  35. use OCP\Files\IRootFolder;
  36. use OCP\Files\NotFoundException;
  37. use OCP\Files\StorageNotAvailableException;
  38. use OCP\IConfig;
  39. use OCP\IDBConnection;
  40. use Symfony\Component\Console\Helper\Table;
  41. use Symfony\Component\Console\Input\InputArgument;
  42. use Symfony\Component\Console\Input\InputInterface;
  43. use Symfony\Component\Console\Output\OutputInterface;
  44. class ScanAppData extends Base {
  45. /** @var IRootFolder */
  46. protected $root;
  47. /** @var IConfig */
  48. protected $config;
  49. /** @var float */
  50. protected $execTime = 0;
  51. /** @var int */
  52. protected $foldersCounter = 0;
  53. /** @var int */
  54. protected $filesCounter = 0;
  55. public function __construct(IRootFolder $rootFolder, IConfig $config) {
  56. parent::__construct();
  57. $this->root = $rootFolder;
  58. $this->config = $config;
  59. }
  60. protected function configure() {
  61. parent::configure();
  62. $this
  63. ->setName('files:scan-app-data')
  64. ->setDescription('rescan the AppData folder');
  65. $this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
  66. }
  67. public function checkScanWarning($fullPath, OutputInterface $output) {
  68. $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
  69. $path = basename($fullPath);
  70. if ($normalizedPath !== $path) {
  71. $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
  72. }
  73. }
  74. protected function scanFiles(OutputInterface $output, string $folder): int {
  75. try {
  76. $appData = $this->getAppDataFolder();
  77. } catch (NotFoundException $e) {
  78. $output->writeln('<error>NoAppData folder found</error>');
  79. return 1;
  80. }
  81. if ($folder !== '') {
  82. try {
  83. $appData = $appData->get($folder);
  84. } catch (NotFoundException $e) {
  85. $output->writeln('<error>Could not find folder: ' . $folder . '</error>');
  86. return 1;
  87. }
  88. }
  89. $connection = $this->reconnectToDatabase($output);
  90. $scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->query(IEventDispatcher::class), \OC::$server->getLogger());
  91. # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
  92. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
  93. $output->writeln("\tFile <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  94. ++$this->filesCounter;
  95. $this->abortIfInterrupted();
  96. });
  97. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
  98. $output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  99. ++$this->foldersCounter;
  100. $this->abortIfInterrupted();
  101. });
  102. $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
  103. $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
  104. });
  105. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
  106. $this->checkScanWarning($path, $output);
  107. });
  108. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
  109. $this->checkScanWarning($path, $output);
  110. });
  111. try {
  112. $scanner->scan($appData->getPath());
  113. } catch (ForbiddenException $e) {
  114. $output->writeln('<error>Storage not writable</error>');
  115. $output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
  116. return 1;
  117. } catch (InterruptedException $e) {
  118. # exit the function if ctrl-c has been pressed
  119. $output->writeln('<info>Interrupted by user</info>');
  120. return 1;
  121. } catch (NotFoundException $e) {
  122. $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
  123. return 1;
  124. } catch (\Exception $e) {
  125. $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
  126. $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
  127. return 1;
  128. }
  129. return 0;
  130. }
  131. protected function execute(InputInterface $input, OutputInterface $output): int {
  132. # restrict the verbosity level to VERBOSITY_VERBOSE
  133. if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
  134. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  135. }
  136. $output->writeln('Scanning AppData for files');
  137. $output->writeln('');
  138. $folder = $input->getArgument('folder');
  139. $this->initTools();
  140. $exitCode = $this->scanFiles($output, $folder);
  141. if ($exitCode === 0) {
  142. $this->presentStats($output);
  143. }
  144. return $exitCode;
  145. }
  146. /**
  147. * Initialises some useful tools for the Command
  148. */
  149. protected function initTools() {
  150. // Start the timer
  151. $this->execTime = -microtime(true);
  152. // Convert PHP errors to exceptions
  153. set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
  154. }
  155. /**
  156. * Processes PHP errors as exceptions in order to be able to keep track of problems
  157. *
  158. * @see https://www.php.net/manual/en/function.set-error-handler.php
  159. *
  160. * @param int $severity the level of the error raised
  161. * @param string $message
  162. * @param string $file the filename that the error was raised in
  163. * @param int $line the line number the error was raised
  164. *
  165. * @throws \ErrorException
  166. */
  167. public function exceptionErrorHandler($severity, $message, $file, $line) {
  168. if (!(error_reporting() & $severity)) {
  169. // This error code is not included in error_reporting
  170. return;
  171. }
  172. throw new \ErrorException($message, 0, $severity, $file, $line);
  173. }
  174. /**
  175. * @param OutputInterface $output
  176. */
  177. protected function presentStats(OutputInterface $output) {
  178. // Stop the timer
  179. $this->execTime += microtime(true);
  180. $headers = [
  181. 'Folders', 'Files', 'Elapsed time'
  182. ];
  183. $this->showSummary($headers, null, $output);
  184. }
  185. /**
  186. * Shows a summary of operations
  187. *
  188. * @param string[] $headers
  189. * @param string[] $rows
  190. * @param OutputInterface $output
  191. */
  192. protected function showSummary($headers, $rows, OutputInterface $output) {
  193. $niceDate = $this->formatExecTime();
  194. if (!$rows) {
  195. $rows = [
  196. $this->foldersCounter,
  197. $this->filesCounter,
  198. $niceDate,
  199. ];
  200. }
  201. $table = new Table($output);
  202. $table
  203. ->setHeaders($headers)
  204. ->setRows([$rows]);
  205. $table->render();
  206. }
  207. /**
  208. * Formats microtime into a human readable format
  209. *
  210. * @return string
  211. */
  212. protected function formatExecTime() {
  213. $secs = round($this->execTime);
  214. # convert seconds into HH:MM:SS form
  215. return sprintf('%02d:%02d:%02d', ($secs / 3600), ($secs / 60 % 60), $secs % 60);
  216. }
  217. /**
  218. * @return \OCP\IDBConnection
  219. */
  220. protected function reconnectToDatabase(OutputInterface $output) {
  221. /** @var Connection | IDBConnection $connection*/
  222. $connection = \OC::$server->getDatabaseConnection();
  223. try {
  224. $connection->close();
  225. } catch (\Exception $ex) {
  226. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  227. }
  228. while (!$connection->isConnected()) {
  229. try {
  230. $connection->connect();
  231. } catch (\Exception $ex) {
  232. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  233. sleep(60);
  234. }
  235. }
  236. return $connection;
  237. }
  238. /**
  239. * @return \OCP\Files\Folder
  240. * @throws NotFoundException
  241. */
  242. private function getAppDataFolder() {
  243. $instanceId = $this->config->getSystemValue('instanceid', null);
  244. if ($instanceId === null) {
  245. throw new NotFoundException();
  246. }
  247. return $this->root->get('appdata_'.$instanceId);
  248. }
  249. }