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.4KB

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