Application.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Console;
  8. use ArgumentCountError;
  9. use OC\MemoryInfo;
  10. use OC\NeedsUpdateException;
  11. use OC\SystemConfig;
  12. use OCP\App\AppPathNotFoundException;
  13. use OCP\App\IAppManager;
  14. use OCP\Console\ConsoleEvent;
  15. use OCP\Defaults;
  16. use OCP\EventDispatcher\IEventDispatcher;
  17. use OCP\IConfig;
  18. use OCP\IRequest;
  19. use OCP\Server;
  20. use Psr\Container\ContainerExceptionInterface;
  21. use Psr\Log\LoggerInterface;
  22. use Symfony\Component\Console\Application as SymfonyApplication;
  23. use Symfony\Component\Console\Input\InputInterface;
  24. use Symfony\Component\Console\Input\InputOption;
  25. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  26. use Symfony\Component\Console\Output\OutputInterface;
  27. class Application {
  28. private SymfonyApplication $application;
  29. public function __construct(
  30. private IConfig $config,
  31. private IEventDispatcher $dispatcher,
  32. private IRequest $request,
  33. private LoggerInterface $logger,
  34. private MemoryInfo $memoryInfo,
  35. private IAppManager $appManager,
  36. private Defaults $defaults,
  37. ) {
  38. $this->application = new SymfonyApplication($defaults->getName(), \OC_Util::getVersionString());
  39. }
  40. /**
  41. * @throws \Exception
  42. */
  43. public function loadCommands(
  44. InputInterface $input,
  45. ConsoleOutputInterface $output
  46. ): void {
  47. // $application is required to be defined in the register_command scripts
  48. $application = $this->application;
  49. $inputDefinition = $application->getDefinition();
  50. $inputDefinition->addOption(
  51. new InputOption(
  52. 'no-warnings',
  53. null,
  54. InputOption::VALUE_NONE,
  55. 'Skip global warnings, show command output only',
  56. null
  57. )
  58. );
  59. try {
  60. $input->bind($inputDefinition);
  61. } catch (\RuntimeException $e) {
  62. //expected if there are extra options
  63. }
  64. if ($input->getOption('no-warnings')) {
  65. $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
  66. }
  67. if ($this->memoryInfo->isMemoryLimitSufficient() === false) {
  68. $output->getErrorOutput()->writeln(
  69. '<comment>The current PHP memory limit ' .
  70. 'is below the recommended value of 512MB.</comment>'
  71. );
  72. }
  73. try {
  74. require_once __DIR__ . '/../../../core/register_command.php';
  75. if ($this->config->getSystemValueBool('installed', false)) {
  76. if (\OCP\Util::needUpgrade()) {
  77. throw new NeedsUpdateException();
  78. } elseif ($this->config->getSystemValueBool('maintenance')) {
  79. $this->writeMaintenanceModeInfo($input, $output);
  80. } else {
  81. $this->appManager->loadApps();
  82. foreach ($this->appManager->getInstalledApps() as $app) {
  83. try {
  84. $appPath = $this->appManager->getAppPath($app);
  85. } catch (AppPathNotFoundException) {
  86. continue;
  87. }
  88. // load commands using info.xml
  89. $info = $this->appManager->getAppInfo($app);
  90. if (isset($info['commands'])) {
  91. try {
  92. $this->loadCommandsFromInfoXml($info['commands']);
  93. } catch (\Throwable $e) {
  94. $output->writeln('<error>' . $e->getMessage() . '</error>');
  95. $this->logger->error($e->getMessage(), [
  96. 'exception' => $e,
  97. ]);
  98. }
  99. }
  100. // load from register_command.php
  101. \OC_App::registerAutoloading($app, $appPath);
  102. $file = $appPath . '/appinfo/register_command.php';
  103. if (file_exists($file)) {
  104. try {
  105. require $file;
  106. } catch (\Exception $e) {
  107. $this->logger->error($e->getMessage(), [
  108. 'exception' => $e,
  109. ]);
  110. }
  111. }
  112. }
  113. }
  114. } elseif ($input->getArgument('command') !== '_completion' && $input->getArgument('command') !== 'maintenance:install') {
  115. $errorOutput = $output->getErrorOutput();
  116. $errorOutput->writeln('Nextcloud is not installed - only a limited number of commands are available');
  117. }
  118. } catch (NeedsUpdateException) {
  119. if ($input->getArgument('command') !== '_completion') {
  120. $errorOutput = $output->getErrorOutput();
  121. $errorOutput->writeln('Nextcloud or one of the apps require upgrade - only a limited number of commands are available');
  122. $errorOutput->writeln('You may use your browser or the occ upgrade command to do the upgrade');
  123. }
  124. }
  125. if ($input->getFirstArgument() !== 'check') {
  126. $errors = \OC_Util::checkServer(Server::get(SystemConfig::class));
  127. if (!empty($errors)) {
  128. foreach ($errors as $error) {
  129. $output->writeln((string)$error['error']);
  130. $output->writeln((string)$error['hint']);
  131. $output->writeln('');
  132. }
  133. throw new \Exception('Environment not properly prepared.');
  134. }
  135. }
  136. }
  137. /**
  138. * Write a maintenance mode info.
  139. * The commands "_completion" and "maintenance:mode" are excluded.
  140. *
  141. * @param InputInterface $input The input implementation for reading inputs.
  142. * @param ConsoleOutputInterface $output The output implementation
  143. * for writing outputs.
  144. * @return void
  145. */
  146. private function writeMaintenanceModeInfo(InputInterface $input, ConsoleOutputInterface $output): void {
  147. if ($input->getArgument('command') !== '_completion'
  148. && $input->getArgument('command') !== 'maintenance:mode'
  149. && $input->getArgument('command') !== 'status') {
  150. $errOutput = $output->getErrorOutput();
  151. $errOutput->writeln('<comment>Nextcloud is in maintenance mode, no apps are loaded.</comment>');
  152. $errOutput->writeln('<comment>Commands provided by apps are unavailable.</comment>');
  153. }
  154. }
  155. /**
  156. * Sets whether to automatically exit after a command execution or not.
  157. *
  158. * @param bool $boolean Whether to automatically exit after a command execution or not
  159. */
  160. public function setAutoExit(bool $boolean): void {
  161. $this->application->setAutoExit($boolean);
  162. }
  163. /**
  164. * @return int
  165. * @throws \Exception
  166. */
  167. public function run(?InputInterface $input = null, ?OutputInterface $output = null) {
  168. $event = new ConsoleEvent(
  169. ConsoleEvent::EVENT_RUN,
  170. $this->request->server['argv']
  171. );
  172. $this->dispatcher->dispatchTyped($event);
  173. $this->dispatcher->dispatch(ConsoleEvent::EVENT_RUN, $event);
  174. return $this->application->run($input, $output);
  175. }
  176. /**
  177. * @throws \Exception
  178. */
  179. private function loadCommandsFromInfoXml(iterable $commands): void {
  180. foreach ($commands as $command) {
  181. try {
  182. $c = Server::get($command);
  183. } catch (ContainerExceptionInterface $e) {
  184. if (class_exists($command)) {
  185. try {
  186. $c = new $command();
  187. } catch (ArgumentCountError) {
  188. throw new \Exception("Failed to construct console command '$command': " . $e->getMessage(), 0, $e);
  189. }
  190. } else {
  191. throw new \Exception("Console command '$command' is unknown and could not be loaded");
  192. }
  193. }
  194. $this->application->add($c);
  195. }
  196. }
  197. }