ScanAppData.php 7.5 KB

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