migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\App;
use OCP\App\IAppManager;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Disable extends Command implements CompletionAwareInterface {
protected int $exitCode = 0;
public function __construct(
protected IAppManager $appManager,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('app:disable')
->setDescription('disable an app')
->addArgument(
'app-id',
InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'disable the specified app'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appIds = $input->getArgument('app-id');
foreach ($appIds as $appId) {
$this->disableApp($appId, $output);
}
return $this->exitCode;
}
private function disableApp(string $appId, OutputInterface $output): void {
if ($this->appManager->isInstalled($appId) === false) {
$output->writeln('No such app enabled: ' . $appId);
return;
}
try {
$this->appManager->disableApp($appId);
$appVersion = $this->appManager->getAppVersion($appId);
$output->writeln($appId . ' ' . $appVersion . ' disabled');
} catch (\Exception $e) {
$output->writeln($e->getMessage());
$this->exitCode = 2;
}
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app-id') {
return array_diff(\OC_App::getEnabledApps(true, true), $this->appManager->getAlwaysEnabledApps());
}
return [];
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Sander Ruitenbeek <s.ruitenbeek@getgoing.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\App;
use OC\Installer;
use OCP\App\AppPathNotFoundException;
use OCP\App\IAppManager;
use OCP\IGroup;
use OCP\IGroupManager;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Enable extends Command implements CompletionAwareInterface {
protected int $exitCode = 0;
public function __construct(
protected IAppManager $appManager,
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('app:enable')
->setDescription('enable an app')
->addArgument(
'app-id',
InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'enable the specified app'
)
->addOption(
'groups',
'g',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'enable the app only for a list of groups'
)
->addOption(
'force',
'f',
InputOption::VALUE_NONE,
'enable the app regardless of the Nextcloud version requirement'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appIds = $input->getArgument('app-id');
$groups = $this->resolveGroupIds($input->getOption('groups'));
$forceEnable = (bool) $input->getOption('force');
foreach ($appIds as $appId) {
$this->enableApp($appId, $groups, $forceEnable, $output);
}
return $this->exitCode;
}
/**
* @param string $appId
* @param array $groupIds
* @param bool $forceEnable
* @param OutputInterface $output
*/
private function enableApp(string $appId, array $groupIds, bool $forceEnable, OutputInterface $output): void {
$groupNames = array_map(function (IGroup $group) {
return $group->getDisplayName();
}, $groupIds);
if ($this->appManager->isInstalled($appId) && $groupIds === []) {
$output->writeln($appId . ' already enabled');
return;
}
try {
/** @var Installer $installer */
$installer = \OC::$server->query(Installer::class);
if (false === $installer->isDownloaded($appId)) {
$installer->downloadApp($appId);
}
$installer->installApp($appId, $forceEnable);
$appVersion = $this->appManager->getAppVersion($appId);
if ($groupIds === []) {
$this->appManager->enableApp($appId, $forceEnable);
$output->writeln($appId . ' ' . $appVersion . ' enabled');
} else {
$this->appManager->enableAppForGroups($appId, $groupIds, $forceEnable);
$output->writeln($appId . ' ' . $appVersion . ' enabled for groups: ' . implode(', ', $groupNames));
}
} catch (AppPathNotFoundException $e) {
$output->writeln($appId . ' not found');
$this->exitCode = 1;
} catch (\Exception $e) {
$output->writeln($e->getMessage());
$this->exitCode = 1;
}
}
/**
* @param array $groupIds
* @return array
*/
private function resolveGroupIds(array $groupIds): array {
$groups = [];
foreach ($groupIds as $groupId) {
$group = $this->groupManager->get($groupId);
if ($group instanceof IGroup) {
$groups[] = $group;
}
}
return $groups;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'groups') {
return array_map(function (IGroup $group) {
return $group->getGID();
}, $this->groupManager->search($context->getCurrentWord()));
}
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app-id') {
$allApps = \OC_App::getAllApps();
return array_diff($allApps, \OC_App::getEnabledApps(true, true));
}
return [];
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\App;
use OC\Core\Command\Base;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class GetPath extends Base {
protected function configure() {
parent::configure();
$this
->setName('app:getpath')
->setDescription('Get an absolute path to the app directory')
->addArgument(
'app',
InputArgument::REQUIRED,
'Name of the app'
)
;
}
/**
* Executes the current command.
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
* @return int 0 if everything went fine, or an error code
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$path = \OC_App::getAppPath($appName);
if ($path !== false) {
$output->writeln($path);
return 0;
}
// App not found, exit with non-zero
return 1;
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
return \OC_App::getAllApps();
}
return [];
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Maxopoly <max@dermax.org>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author sualko <klaus@jsxc.org>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\App;
use OC\Installer;
use OCP\App\IAppManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Install extends Command {
protected function configure() {
$this
->setName('app:install')
->setDescription('install an app')
->addArgument(
'app-id',
InputArgument::REQUIRED,
'install the specified app'
)
->addOption(
'keep-disabled',
null,
InputOption::VALUE_NONE,
'don\'t enable the app afterwards'
)
->addOption(
'force',
'f',
InputOption::VALUE_NONE,
'install the app regardless of the Nextcloud version requirement'
)
->addOption(
'allow-unstable',
null,
InputOption::VALUE_NONE,
'allow installing an unstable releases'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appId = $input->getArgument('app-id');
$forceEnable = (bool) $input->getOption('force');
if (\OC_App::getAppPath($appId)) {
$output->writeln($appId . ' already installed');
return 1;
}
try {
/** @var Installer $installer */
$installer = \OC::$server->query(Installer::class);
$installer->downloadApp($appId, $input->getOption('allow-unstable'));
$result = $installer->installApp($appId, $forceEnable);
} catch (\Exception $e) {
$output->writeln('Error: ' . $e->getMessage());
return 1;
}
if ($result === false) {
$output->writeln($appId . ' couldn\'t be installed');
return 1;
}
$appVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId);
$output->writeln($appId . ' ' . $appVersion . ' installed');
if (!$input->getOption('keep-disabled')) {
$appClass = new \OC_App();
$appClass->enable($appId);
$output->writeln($appId . ' enabled');
}
return 0;
}
}
+137
View File
@@ -0,0 +1,137 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\App;
use OC\Core\Command\Base;
use OCP\App\IAppManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListApps extends Base {
public function __construct(
protected IAppManager $manager,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('app:list')
->setDescription('List all available apps')
->addOption(
'shipped',
null,
InputOption::VALUE_REQUIRED,
'true - limit to shipped apps only, false - limit to non-shipped apps only'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if ($input->getOption('shipped') === 'true' || $input->getOption('shipped') === 'false') {
$shippedFilter = $input->getOption('shipped') === 'true';
} else {
$shippedFilter = null;
}
$apps = \OC_App::getAllApps();
$enabledApps = $disabledApps = [];
$versions = \OC_App::getAppVersions();
//sort enabled apps above disabled apps
foreach ($apps as $app) {
if ($shippedFilter !== null && $this->manager->isShipped($app) !== $shippedFilter) {
continue;
}
if ($this->manager->isInstalled($app)) {
$enabledApps[] = $app;
} else {
$disabledApps[] = $app;
}
}
$apps = ['enabled' => [], 'disabled' => []];
sort($enabledApps);
foreach ($enabledApps as $app) {
$apps['enabled'][$app] = $versions[$app] ?? true;
}
sort($disabledApps);
foreach ($disabledApps as $app) {
$apps['disabled'][$app] = $this->manager->getAppVersion($app) . (isset($versions[$app]) ? ' (installed ' . $versions[$app] . ')' : '');
}
$this->writeAppList($input, $output, $apps);
return 0;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param array $items
*/
protected function writeAppList(InputInterface $input, OutputInterface $output, $items) {
switch ($input->getOption('output')) {
case self::OUTPUT_FORMAT_PLAIN:
$output->writeln('Enabled:');
parent::writeArrayInOutputFormat($input, $output, $items['enabled']);
$output->writeln('Disabled:');
parent::writeArrayInOutputFormat($input, $output, $items['disabled']);
break;
default:
parent::writeArrayInOutputFormat($input, $output, $items);
break;
}
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return array
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'shipped') {
return ['true', 'false'];
}
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
return [];
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
/**
* @copyright Copyright (c) 2018, Patrik Kernstock <info@pkern.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Patrik Kernstock <info@pkern.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\App;
use OC\Installer;
use OCP\App\IAppManager;
use Psr\Log\LoggerInterface;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Throwable;
class Remove extends Command implements CompletionAwareInterface {
public function __construct(
protected IAppManager $manager,
private Installer $installer,
private LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('app:remove')
->setDescription('remove an app')
->addArgument(
'app-id',
InputArgument::REQUIRED,
'remove the specified app'
)
->addOption(
'keep-data',
null,
InputOption::VALUE_NONE,
'keep app data and do not remove them'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appId = $input->getArgument('app-id');
// Check if the app is installed
if (!\OC_App::getAppPath($appId)) {
$output->writeln($appId . ' is not installed');
return 1;
}
// Removing shipped apps is not possible, therefore we pre-check that
// before trying to remove it
if ($this->manager->isShipped($appId)) {
$output->writeln($appId . ' could not be removed as it is a shipped app');
return 1;
}
// If we want to keep the data of the app, we simply don't disable it here.
// App uninstall tasks are being executed when disabled. More info: PR #11627.
if (!$input->getOption('keep-data')) {
try {
$this->manager->disableApp($appId);
$output->writeln($appId . ' disabled');
} catch (Throwable $e) {
$output->writeln('<error>Error: ' . $e->getMessage() . '</error>');
$this->logger->error($e->getMessage(), [
'app' => 'CLI',
'exception' => $e,
]);
return 1;
}
}
// Let's try to remove the app...
try {
$result = $this->installer->removeApp($appId);
} catch (Throwable $e) {
$output->writeln('<error>Error: ' . $e->getMessage() . '</error>');
$this->logger->error($e->getMessage(), [
'app' => 'CLI',
'exception' => $e,
]);
return 1;
}
if ($result === false) {
$output->writeln($appId . ' could not be removed');
return 1;
}
$appVersion = $this->manager->getAppVersion($appId);
$output->writeln($appId . ' ' . $appVersion . ' removed');
return 0;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app-id') {
return \OC_App::getAllApps();
}
return [];
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
/**
* @copyright Copyright (c) 2018, michag86 (michag86@arcor.de)
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author michag86 <micha_g@arcor.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\App;
use OC\Installer;
use OCP\App\IAppManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Update extends Command {
public function __construct(
protected IAppManager $manager,
private Installer $installer,
private LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('app:update')
->setDescription('update an app or all apps')
->addArgument(
'app-id',
InputArgument::OPTIONAL,
'update the specified app'
)
->addOption(
'all',
null,
InputOption::VALUE_NONE,
'update all updatable apps'
)
->addOption(
'showonly',
null,
InputOption::VALUE_NONE,
'show update(s) without updating'
)
->addOption(
'allow-unstable',
null,
InputOption::VALUE_NONE,
'allow updating to unstable releases'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$singleAppId = $input->getArgument('app-id');
if ($singleAppId) {
$apps = [$singleAppId];
try {
$this->manager->getAppPath($singleAppId);
} catch (\OCP\App\AppPathNotFoundException $e) {
$output->writeln($singleAppId . ' not installed');
return 1;
}
} elseif ($input->getOption('all') || $input->getOption('showonly')) {
$apps = \OC_App::getAllApps();
} else {
$output->writeln("<error>Please specify an app to update or \"--all\" to update all updatable apps\"</error>");
return 1;
}
$return = 0;
foreach ($apps as $appId) {
$newVersion = $this->installer->isUpdateAvailable($appId, $input->getOption('allow-unstable'));
if ($newVersion) {
$output->writeln($appId . ' new version available: ' . $newVersion);
if (!$input->getOption('showonly')) {
try {
$result = $this->installer->updateAppstoreApp($appId, $input->getOption('allow-unstable'));
} catch (\Exception $e) {
$this->logger->error('Failure during update of app "' . $appId . '"', [
'app' => 'app:update',
'exception' => $e,
]);
$output->writeln('Error: ' . $e->getMessage());
$return = 1;
}
if ($result === false) {
$output->writeln($appId . ' couldn\'t be updated');
$return = 1;
} elseif ($result === true) {
$output->writeln($appId . ' updated');
}
}
}
}
return $return;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Christian Kampka <christian@kampka.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace OC\Core\Command\Background;
class Ajax extends Base {
protected function getMode() {
return 'ajax';
}
}
@@ -0,0 +1,69 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Christian Kampka <christian@kampka.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace OC\Core\Command\Background;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* An abstract base class for configuring the background job mode
* from the command line interface.
* Subclasses will override the getMode() function to specify the mode to configure.
*/
abstract class Base extends Command {
abstract protected function getMode();
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$mode = $this->getMode();
$this
->setName("background:$mode")
->setDescription("Use $mode to run background jobs");
}
/**
* Executing this command will set the background job mode for owncloud.
* The mode to set is specified by the concrete sub class by implementing the
* getMode() function.
*
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$mode = $this->getMode();
$this->config->setAppValue('core', 'backgroundjobs_mode', $mode);
$output->writeln("Set mode for background jobs to '$mode'");
return 0;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Christian Kampka <christian@kampka.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace OC\Core\Command\Background;
class Cron extends Base {
protected function getMode() {
return 'cron';
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2024, Maxence Lange <maxence@artificial-owl.com>
*
* @author Maxence Lange <maxence@artificial-owl.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Background;
use OC\Core\Command\Base;
use OCP\BackgroundJob\IJobList;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class Delete extends Base {
public function __construct(
protected IJobList $jobList,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('background-job:delete')
->setDescription('Remove a background job from database')
->addArgument(
'job-id',
InputArgument::REQUIRED,
'The ID of the job in the database'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$jobId = (int) $input->getArgument('job-id');
$job = $this->jobList->getById($jobId);
if ($job === null) {
$output->writeln('<error>Job with ID ' . $jobId . ' could not be found in the database</error>');
return 1;
}
$output->writeln('Job class: ' . get_class($job));
$output->writeln('Arguments: ' . json_encode($job->getArgument()));
$output->writeln('');
$question = new ConfirmationQuestion(
'<comment>Do you really want to delete this background job ? It could create some misbehaviours in Nextcloud.</comment> (y/N) ', false,
'/^(y|Y)/i'
);
$helper = $this->getHelper('question');
if (!$helper->ask($input, $output, $question)) {
$output->writeln('aborted.');
return 0;
}
$this->jobList->remove($job, $job->getArgument());
return 0;
}
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021, Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Background;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\IJobList;
use OCP\ILogger;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Job extends Command {
public function __construct(
protected IJobList $jobList,
protected ILogger $logger,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('background-job:execute')
->setDescription('Execute a single background job manually')
->addArgument(
'job-id',
InputArgument::REQUIRED,
'The ID of the job in the database'
)
->addOption(
'force-execute',
null,
InputOption::VALUE_NONE,
'Force execute the background job, independent from last run and being reserved'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$jobId = (int) $input->getArgument('job-id');
$job = $this->jobList->getById($jobId);
if ($job === null) {
$output->writeln('<error>Job with ID ' . $jobId . ' could not be found in the database</error>');
return 1;
}
$this->printJobInfo($jobId, $job, $output);
$output->writeln('');
$lastRun = $job->getLastRun();
if ($input->getOption('force-execute')) {
$lastRun = 0;
$output->writeln('<comment>Forcing execution of the job</comment>');
$output->writeln('');
$this->jobList->resetBackgroundJob($job);
}
$job = $this->jobList->getById($jobId);
if ($job === null) {
$output->writeln('<error>Something went wrong when trying to retrieve Job with ID ' . $jobId . ' from database</error>');
return 1;
}
$job->execute($this->jobList, $this->logger);
$job = $this->jobList->getById($jobId);
if (($job === null) || ($lastRun !== $job->getLastRun())) {
$output->writeln('<info>Job executed!</info>');
$output->writeln('');
if ($job instanceof \OC\BackgroundJob\TimedJob || $job instanceof \OCP\BackgroundJob\TimedJob) {
$this->printJobInfo($jobId, $job, $output);
}
} else {
$output->writeln('<comment>Job was not executed because it is not due</comment>');
$output->writeln('Specify the <question>--force-execute</question> option to run it anyway');
}
return 0;
}
protected function printJobInfo(int $jobId, IJob $job, OutputInterface$output): void {
$row = $this->jobList->getDetailsById($jobId);
$lastRun = new \DateTime();
$lastRun->setTimestamp((int) $row['last_run']);
$lastChecked = new \DateTime();
$lastChecked->setTimestamp((int) $row['last_checked']);
$reservedAt = new \DateTime();
$reservedAt->setTimestamp((int) $row['reserved_at']);
$output->writeln('Job class: ' . get_class($job));
$output->writeln('Arguments: ' . json_encode($job->getArgument()));
$isTimedJob = $job instanceof \OC\BackgroundJob\TimedJob || $job instanceof \OCP\BackgroundJob\TimedJob;
if ($isTimedJob) {
$output->writeln('Type: timed');
} elseif ($job instanceof \OC\BackgroundJob\QueuedJob || $job instanceof \OCP\BackgroundJob\QueuedJob) {
$output->writeln('Type: queued');
} else {
$output->writeln('Type: job');
}
$output->writeln('');
$output->writeln('Last checked: ' . $lastChecked->format(\DateTimeInterface::ATOM));
if ((int) $row['reserved_at'] === 0) {
$output->writeln('Reserved at: -');
} else {
$output->writeln('Reserved at: <comment>' . $reservedAt->format(\DateTimeInterface::ATOM) . '</comment>');
}
$output->writeln('Last executed: ' . $lastRun->format(\DateTimeInterface::ATOM));
$output->writeln('Last duration: ' . $row['execution_duration']);
if ($isTimedJob) {
$reflection = new \ReflectionClass($job);
$intervalProperty = $reflection->getProperty('interval');
$intervalProperty->setAccessible(true);
$interval = $intervalProperty->getValue($job);
$nextRun = new \DateTime();
$nextRun->setTimestamp($row['last_run'] + $interval);
if ($nextRun > new \DateTime()) {
$output->writeln('Next execution: <comment>' . $nextRun->format(\DateTimeInterface::ATOM) . '</comment>');
} else {
$output->writeln('Next execution: <info>' . $nextRun->format(\DateTimeInterface::ATOM) . '</info>');
}
}
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022, Côme Chilliet <come.chilliet@nextcloud.com>
*
* @author Côme Chilliet <come.chilliet@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Background;
use OC\Core\Command\Base;
use OCP\BackgroundJob\IJobList;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListCommand extends Base {
public function __construct(
protected IJobList $jobList,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('background-job:list')
->setDescription('List background jobs')
->addOption(
'class',
'c',
InputOption::VALUE_OPTIONAL,
'Job class to search for',
null
)->addOption(
'limit',
'l',
InputOption::VALUE_OPTIONAL,
'Number of jobs to retrieve',
'500'
)->addOption(
'offset',
'o',
InputOption::VALUE_OPTIONAL,
'Offset for retrieving jobs',
'0'
)
;
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$limit = (int)$input->getOption('limit');
$jobsInfo = $this->formatJobs($this->jobList->getJobsIterator($input->getOption('class'), $limit, (int)$input->getOption('offset')));
$this->writeTableInOutputFormat($input, $output, $jobsInfo);
if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN && count($jobsInfo) >= $limit) {
$output->writeln("\n<comment>Output is currently limited to " . $limit . " jobs. Specify `-l, --limit[=LIMIT]` to override.</comment>");
}
return 0;
}
protected function formatJobs(iterable $jobs): array {
$jobsInfo = [];
foreach ($jobs as $job) {
$jobsInfo[] = [
'id' => $job->getId(),
'class' => get_class($job),
'last_run' => date(DATE_ATOM, $job->getLastRun()),
'argument' => json_encode($job->getArgument()),
];
}
return $jobsInfo;
}
}
@@ -0,0 +1,32 @@
<?php
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Christian Kampka <christian@kampka.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace OC\Core\Command\Background;
class WebCron extends Base {
protected function getMode() {
return 'webcron';
}
}
+200
View File
@@ -0,0 +1,200 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
use OC\Core\Command\User\ListCommand;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Base extends Command implements CompletionAwareInterface {
public const OUTPUT_FORMAT_PLAIN = 'plain';
public const OUTPUT_FORMAT_JSON = 'json';
public const OUTPUT_FORMAT_JSON_PRETTY = 'json_pretty';
protected string $defaultOutputFormat = self::OUTPUT_FORMAT_PLAIN;
private bool $php_pcntl_signal = false;
private bool $interrupted = false;
protected function configure() {
$this
->addOption(
'output',
null,
InputOption::VALUE_OPTIONAL,
'Output format (plain, json or json_pretty, default is plain)',
$this->defaultOutputFormat
)
;
}
protected function writeArrayInOutputFormat(InputInterface $input, OutputInterface $output, array $items, string $prefix = ' - '): void {
switch ($input->getOption('output')) {
case self::OUTPUT_FORMAT_JSON:
$output->writeln(json_encode($items));
break;
case self::OUTPUT_FORMAT_JSON_PRETTY:
$output->writeln(json_encode($items, JSON_PRETTY_PRINT));
break;
default:
foreach ($items as $key => $item) {
if (is_array($item)) {
$output->writeln($prefix . $key . ':');
$this->writeArrayInOutputFormat($input, $output, $item, ' ' . $prefix);
continue;
}
if (!is_int($key) || ListCommand::class === get_class($this)) {
$value = $this->valueToString($item);
if (!is_null($value)) {
$output->writeln($prefix . $key . ': ' . $value);
} else {
$output->writeln($prefix . $key);
}
} else {
$output->writeln($prefix . $this->valueToString($item));
}
}
break;
}
}
protected function writeTableInOutputFormat(InputInterface $input, OutputInterface $output, array $items): void {
switch ($input->getOption('output')) {
case self::OUTPUT_FORMAT_JSON:
$output->writeln(json_encode($items));
break;
case self::OUTPUT_FORMAT_JSON_PRETTY:
$output->writeln(json_encode($items, JSON_PRETTY_PRINT));
break;
default:
$table = new Table($output);
$table->setRows($items);
if (!empty($items) && is_string(array_key_first(reset($items)))) {
$table->setHeaders(array_keys(reset($items)));
}
$table->render();
break;
}
}
/**
* @param mixed $item
*/
protected function writeMixedInOutputFormat(InputInterface $input, OutputInterface $output, $item) {
if (is_array($item)) {
$this->writeArrayInOutputFormat($input, $output, $item, '');
return;
}
switch ($input->getOption('output')) {
case self::OUTPUT_FORMAT_JSON:
$output->writeln(json_encode($item));
break;
case self::OUTPUT_FORMAT_JSON_PRETTY:
$output->writeln(json_encode($item, JSON_PRETTY_PRINT));
break;
default:
$output->writeln($this->valueToString($item, false));
break;
}
}
protected function valueToString($value, bool $returnNull = true): ?string {
if ($value === false) {
return 'false';
} elseif ($value === true) {
return 'true';
} elseif ($value === null) {
return $returnNull ? null : 'null';
} else {
return $value;
}
}
/**
* Throw InterruptedException when interrupted by user
*
* @throws InterruptedException
*/
protected function abortIfInterrupted() {
if ($this->php_pcntl_signal === false) {
return;
}
pcntl_signal_dispatch();
if ($this->interrupted === true) {
throw new InterruptedException('Command interrupted by user');
}
}
/**
* Changes the status of the command to "interrupted" if ctrl-c has been pressed
*
* Gives a chance to the command to properly terminate what it's doing
*/
public function cancelOperation(): void {
$this->interrupted = true;
}
public function run(InputInterface $input, OutputInterface $output) {
// check if the php pcntl_signal functions are accessible
$this->php_pcntl_signal = function_exists('pcntl_signal');
if ($this->php_pcntl_signal) {
// Collect interrupts and notify the running command
pcntl_signal(SIGTERM, [$this, 'cancelOperation']);
pcntl_signal(SIGINT, [$this, 'cancelOperation']);
}
return parent::run($input, $output);
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'output') {
return ['plain', 'json', 'json_pretty'];
}
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
return [];
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
/**
* @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Broadcast;
use OCP\EventDispatcher\ABroadcastedEvent;
use OCP\EventDispatcher\IEventDispatcher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Test extends Command {
public function __construct(
private IEventDispatcher $eventDispatcher,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('broadcast:test')
->setDescription('test the SSE broadcaster')
->addArgument(
'uid',
InputArgument::REQUIRED,
'the UID of the users to receive the event'
)
->addArgument(
'name',
InputArgument::OPTIONAL,
'the event name',
'test'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$name = $input->getArgument('name');
$uid = $input->getArgument('uid');
$event = new class($name, $uid) extends ABroadcastedEvent {
/** @var string */
private $name;
/** @var string */
private $uid;
public function __construct(string $name,
string $uid) {
parent::__construct();
$this->name = $name;
$this->uid = $uid;
}
public function broadcastAs(): string {
return $this->name;
}
public function getUids(): array {
return [
$this->uid,
];
}
public function jsonSerialize(): array {
return [
'description' => 'this is a test event',
];
}
};
$this->eventDispatcher->dispatch('broadcasttest', $event);
return 0;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
use OC\SystemConfig;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Check extends Base {
public function __construct(
private SystemConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('check')
->setDescription('check dependencies of the server environment')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$errors = \OC_Util::checkServer($this->config);
if (!empty($errors)) {
$errors = array_map(function ($item) {
return (string) $item['error'];
}, $errors);
$this->writeArrayInOutputFormat($input, $output, $errors);
return 1;
}
return 0;
}
}
@@ -0,0 +1,47 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Config\App;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
abstract class Base extends \OC\Core\Command\Base {
protected IConfig $config;
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
return \OC_App::getAllApps();
}
if ($argumentName === 'name') {
$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
return $this->config->getAppKeys($appName);
}
return [];
}
}
@@ -0,0 +1,75 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\App;
use OCP\IConfig;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DeleteConfig extends Base {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('config:app:delete')
->setDescription('Delete an app config value')
->addArgument(
'app',
InputArgument::REQUIRED,
'Name of the app'
)
->addArgument(
'name',
InputArgument::REQUIRED,
'Name of the config to delete'
)
->addOption(
'error-if-not-exists',
null,
InputOption::VALUE_NONE,
'Checks whether the config exists before deleting it'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$configName = $input->getArgument('name');
if ($input->hasParameterOption('--error-if-not-exists') && !in_array($configName, $this->config->getAppKeys($appName))) {
$output->writeln('<error>Config ' . $configName . ' of app ' . $appName . ' could not be deleted because it did not exist</error>');
return 1;
}
$this->config->deleteAppValue($appName, $configName);
$output->writeln('<info>Config value ' . $configName . ' of app ' . $appName . ' deleted</info>');
return 0;
}
}
@@ -0,0 +1,87 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\App;
use OCP\IConfig;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GetConfig extends Base {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('config:app:get')
->setDescription('Get an app config value')
->addArgument(
'app',
InputArgument::REQUIRED,
'Name of the app'
)
->addArgument(
'name',
InputArgument::REQUIRED,
'Name of the config to get'
)
->addOption(
'default-value',
null,
InputOption::VALUE_OPTIONAL,
'If no default value is set and the config does not exist, the command will exit with 1'
)
;
}
/**
* Executes the current command.
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
* @return int 0 if everything went fine, or an error code
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$configName = $input->getArgument('name');
$defaultValue = $input->getOption('default-value');
if (!in_array($configName, $this->config->getAppKeys($appName)) && !$input->hasParameterOption('--default-value')) {
return 1;
}
if (!in_array($configName, $this->config->getAppKeys($appName))) {
$configValue = $defaultValue;
} else {
$configValue = $this->config->getAppValue($appName, $configName);
}
$this->writeMixedInOutputFormat($input, $output, $configValue);
return 0;
}
}
@@ -0,0 +1,83 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\App;
use OCP\IConfig;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetConfig extends Base {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('config:app:set')
->setDescription('Set an app config value')
->addArgument(
'app',
InputArgument::REQUIRED,
'Name of the app'
)
->addArgument(
'name',
InputArgument::REQUIRED,
'Name of the config to set'
)
->addOption(
'value',
null,
InputOption::VALUE_REQUIRED,
'The new value of the config'
)
->addOption(
'update-only',
null,
InputOption::VALUE_NONE,
'Only updates the value, if it is not set before, it is not being added'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$configName = $input->getArgument('name');
if (!in_array($configName, $this->config->getAppKeys($appName)) && $input->hasParameterOption('--update-only')) {
$output->writeln('<comment>Config value ' . $configName . ' for app ' . $appName . ' not updated, as it has not been set before.</comment>');
return 1;
}
$configValue = $input->getOption('value');
$this->config->setAppValue($appName, $configName, $configValue);
$output->writeln('<info>Config value ' . $configName . ' for app ' . $appName . ' set to ' . $configValue . '</info>');
return 0;
}
}
+222
View File
@@ -0,0 +1,222 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\Completion;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\ShellPathCompletion;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Import extends Command implements CompletionAwareInterface {
protected array $validRootKeys = ['system', 'apps'];
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('config:import')
->setDescription('Import a list of configs')
->addArgument(
'file',
InputArgument::OPTIONAL,
'File with the json array to import'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$importFile = $input->getArgument('file');
if ($importFile !== null) {
$content = $this->getArrayFromFile($importFile);
} else {
$content = $this->getArrayFromStdin();
}
try {
$configs = $this->validateFileContent($content);
} catch (\UnexpectedValueException $e) {
$output->writeln('<error>' . $e->getMessage(). '</error>');
return 1;
}
if (!empty($configs['system'])) {
$this->config->setSystemValues($configs['system']);
}
if (!empty($configs['apps'])) {
foreach ($configs['apps'] as $app => $appConfigs) {
foreach ($appConfigs as $key => $value) {
if ($value === null) {
$this->config->deleteAppValue($app, $key);
} else {
$this->config->setAppValue($app, $key, $value);
}
}
}
}
$output->writeln('<info>Config successfully imported from: ' . $importFile . '</info>');
return 0;
}
/**
* Get the content from stdin ("config:import < file.json")
*
* @return string
*/
protected function getArrayFromStdin() {
// Read from stdin. stream_set_blocking is used to prevent blocking
// when nothing is passed via stdin.
stream_set_blocking(STDIN, 0);
$content = file_get_contents('php://stdin');
stream_set_blocking(STDIN, 1);
return $content;
}
/**
* Get the content of the specified file ("config:import file.json")
*
* @param string $importFile
* @return string
*/
protected function getArrayFromFile($importFile) {
return file_get_contents($importFile);
}
/**
* @param string $content
* @return array
* @throws \UnexpectedValueException when the array is invalid
*/
protected function validateFileContent($content) {
$decodedContent = json_decode($content, true);
if (!is_array($decodedContent) || empty($decodedContent)) {
throw new \UnexpectedValueException('The file must contain a valid json array');
}
$this->validateArray($decodedContent);
return $decodedContent;
}
/**
* Validates that the array only contains `system` and `apps`
*
* @param array $array
*/
protected function validateArray($array) {
$arrayKeys = array_keys($array);
$additionalKeys = array_diff($arrayKeys, $this->validRootKeys);
$commonKeys = array_intersect($arrayKeys, $this->validRootKeys);
if (!empty($additionalKeys)) {
throw new \UnexpectedValueException('Found invalid entries in root: ' . implode(', ', $additionalKeys));
}
if (empty($commonKeys)) {
throw new \UnexpectedValueException('At least one key of the following is expected: ' . implode(', ', $this->validRootKeys));
}
if (isset($array['system'])) {
if (is_array($array['system'])) {
foreach ($array['system'] as $name => $value) {
$this->checkTypeRecursively($value, $name);
}
} else {
throw new \UnexpectedValueException('The system config array is not an array');
}
}
if (isset($array['apps'])) {
if (is_array($array['apps'])) {
$this->validateAppsArray($array['apps']);
} else {
throw new \UnexpectedValueException('The apps config array is not an array');
}
}
}
/**
* @param mixed $configValue
* @param string $configName
*/
protected function checkTypeRecursively($configValue, $configName) {
if (!is_array($configValue) && !is_bool($configValue) && !is_int($configValue) && !is_string($configValue) && !is_null($configValue) && !is_float($configValue)) {
throw new \UnexpectedValueException('Invalid system config value for "' . $configName . '". Only arrays, bools, integers, floats, strings and null (delete) are allowed.');
}
if (is_array($configValue)) {
foreach ($configValue as $key => $value) {
$this->checkTypeRecursively($value, $configName);
}
}
}
/**
* Validates that app configs are only integers and strings
*
* @param array $array
*/
protected function validateAppsArray($array) {
foreach ($array as $app => $configs) {
foreach ($configs as $name => $value) {
if (!is_int($value) && !is_string($value) && !is_null($value)) {
throw new \UnexpectedValueException('Invalid app config value for "' . $app . '":"' . $name . '". Only integers, strings and null (delete) are allowed.');
}
}
}
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'file') {
$helper = new ShellPathCompletion(
$this->getName(),
'file',
Completion::TYPE_ARGUMENT
);
return $helper->run();
}
return [];
}
}
@@ -0,0 +1,155 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config;
use OC\Core\Command\Base;
use OC\SystemConfig;
use OCP\IAppConfig;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListConfigs extends Base {
protected string $defaultOutputFormat = self::OUTPUT_FORMAT_JSON_PRETTY;
public function __construct(
protected SystemConfig $systemConfig,
protected IAppConfig $appConfig,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('config:list')
->setDescription('List all configs')
->addArgument(
'app',
InputArgument::OPTIONAL,
'Name of the app ("system" to get the config.php values, "all" for all apps and system)',
'all'
)
->addOption(
'private',
null,
InputOption::VALUE_NONE,
'Use this option when you want to include sensitive configs like passwords, salts, ...'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$app = $input->getArgument('app');
$noSensitiveValues = !$input->getOption('private');
if (!is_string($app)) {
$output->writeln('<error>Invalid app value given</error>');
return 1;
}
switch ($app) {
case 'system':
$configs = [
'system' => $this->getSystemConfigs($noSensitiveValues),
];
break;
case 'all':
$apps = $this->appConfig->getApps();
$configs = [
'system' => $this->getSystemConfigs($noSensitiveValues),
'apps' => [],
];
foreach ($apps as $appName) {
$configs['apps'][$appName] = $this->getAppConfigs($appName, $noSensitiveValues);
}
break;
default:
$configs = [
'apps' => [
$app => $this->getAppConfigs($app, $noSensitiveValues),
],
];
}
$this->writeArrayInOutputFormat($input, $output, $configs);
return 0;
}
/**
* Get the system configs
*
* @param bool $noSensitiveValues
* @return array
*/
protected function getSystemConfigs($noSensitiveValues) {
$keys = $this->systemConfig->getKeys();
$configs = [];
foreach ($keys as $key) {
if ($noSensitiveValues) {
$value = $this->systemConfig->getFilteredValue($key, serialize(null));
} else {
$value = $this->systemConfig->getValue($key, serialize(null));
}
if ($value !== 'N;') {
$configs[$key] = $value;
}
}
return $configs;
}
/**
* Get the app configs
*
* @param string $app
* @param bool $noSensitiveValues
* @return array
*/
protected function getAppConfigs($app, $noSensitiveValues) {
if ($noSensitiveValues) {
return $this->appConfig->getFilteredValues($app, false);
} else {
return $this->appConfig->getValues($app, false);
}
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
return array_merge(['all', 'system'], \OC_App::getAllApps());
}
return [];
}
}
@@ -0,0 +1,81 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Config\System;
use OC\SystemConfig;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
abstract class Base extends \OC\Core\Command\Base {
public function __construct(
protected SystemConfig $systemConfig,
) {
parent::__construct();
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'name') {
$words = $this->getPreviousNames($context, $context->getWordIndex());
if (empty($words)) {
$completions = $this->systemConfig->getKeys();
} else {
$key = array_shift($words);
$value = $this->systemConfig->getValue($key);
$completions = array_keys($value);
while (!empty($words) && is_array($value)) {
$key = array_shift($words);
if (!isset($value[$key]) || !is_array($value[$key])) {
break;
}
$value = $value[$key];
$completions = array_keys($value);
}
}
return $completions;
}
return parent::completeArgumentValues($argumentName, $context);
}
/**
* @param CompletionContext $context
* @param int $currentIndex
* @return string[]
*/
protected function getPreviousNames(CompletionContext $context, $currentIndex) {
$word = $context->getWordAtIndex($currentIndex - 1);
if ($word === $this->getName() || $currentIndex <= 0) {
return [];
}
$words = $this->getPreviousNames($context, $currentIndex - 1);
$words[] = $word;
return $words;
}
}
@@ -0,0 +1,112 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\System;
use OC\SystemConfig;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class DeleteConfig extends Base {
public function __construct(
SystemConfig $systemConfig,
) {
parent::__construct($systemConfig);
}
protected function configure() {
parent::configure();
$this
->setName('config:system:delete')
->setDescription('Delete a system config value')
->addArgument(
'name',
InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'Name of the config to delete, specify multiple for array parameter'
)
->addOption(
'error-if-not-exists',
null,
InputOption::VALUE_NONE,
'Checks whether the config exists before deleting it'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$configNames = $input->getArgument('name');
$configName = $configNames[0];
if (count($configNames) > 1) {
if ($input->hasParameterOption('--error-if-not-exists') && !in_array($configName, $this->systemConfig->getKeys())) {
$output->writeln('<error>System config ' . implode(' => ', $configNames) . ' could not be deleted because it did not exist</error>');
return 1;
}
$value = $this->systemConfig->getValue($configName);
try {
$value = $this->removeSubValue(array_slice($configNames, 1), $value, $input->hasParameterOption('--error-if-not-exists'));
} catch (\UnexpectedValueException $e) {
$output->writeln('<error>System config ' . implode(' => ', $configNames) . ' could not be deleted because it did not exist</error>');
return 1;
}
$this->systemConfig->setValue($configName, $value);
$output->writeln('<info>System config value ' . implode(' => ', $configNames) . ' deleted</info>');
return 0;
} else {
if ($input->hasParameterOption('--error-if-not-exists') && !in_array($configName, $this->systemConfig->getKeys())) {
$output->writeln('<error>System config ' . $configName . ' could not be deleted because it did not exist</error>');
return 1;
}
$this->systemConfig->deleteValue($configName);
$output->writeln('<info>System config value ' . $configName . ' deleted</info>');
return 0;
}
}
protected function removeSubValue($keys, $currentValue, $throwError) {
$nextKey = array_shift($keys);
if (is_array($currentValue)) {
if (isset($currentValue[$nextKey])) {
if (empty($keys)) {
unset($currentValue[$nextKey]);
} else {
$currentValue[$nextKey] = $this->removeSubValue($keys, $currentValue[$nextKey], $throwError);
}
} elseif ($throwError) {
throw new \UnexpectedValueException('Config parameter does not exist');
}
} elseif ($throwError) {
throw new \UnexpectedValueException('Config parameter does not exist');
}
return $currentValue;
}
}
@@ -0,0 +1,95 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\System;
use OC\SystemConfig;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GetConfig extends Base {
public function __construct(
SystemConfig $systemConfig,
) {
parent::__construct($systemConfig);
}
protected function configure() {
parent::configure();
$this
->setName('config:system:get')
->setDescription('Get a system config value')
->addArgument(
'name',
InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'Name of the config to get, specify multiple for array parameter'
)
->addOption(
'default-value',
null,
InputOption::VALUE_OPTIONAL,
'If no default value is set and the config does not exist, the command will exit with 1'
)
;
}
/**
* Executes the current command.
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
* @return int 0 if everything went fine, or an error code
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$configNames = $input->getArgument('name');
$configName = array_shift($configNames);
$defaultValue = $input->getOption('default-value');
if (!in_array($configName, $this->systemConfig->getKeys()) && !$input->hasParameterOption('--default-value')) {
return 1;
}
if (!in_array($configName, $this->systemConfig->getKeys())) {
$configValue = $defaultValue;
} else {
$configValue = $this->systemConfig->getValue($configName);
if (!empty($configNames)) {
foreach ($configNames as $configName) {
if (isset($configValue[$configName])) {
$configValue = $configValue[$configName];
} elseif (!$input->hasParameterOption('--default-value')) {
return 1;
} else {
$configValue = $defaultValue;
break;
}
}
}
}
$this->writeMixedInOutputFormat($input, $output, $configValue);
return 0;
}
}
@@ -0,0 +1,207 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin McCorkell <robin@mccorkell.me.uk>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Config\System;
use OC\SystemConfig;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetConfig extends Base {
public function __construct(
SystemConfig $systemConfig,
) {
parent::__construct($systemConfig);
}
protected function configure() {
parent::configure();
$this
->setName('config:system:set')
->setDescription('Set a system config value')
->addArgument(
'name',
InputArgument::REQUIRED | InputArgument::IS_ARRAY,
'Name of the config parameter, specify multiple for array parameter'
)
->addOption(
'type',
null,
InputOption::VALUE_REQUIRED,
'Value type [string, integer, double, boolean]',
'string'
)
->addOption(
'value',
null,
InputOption::VALUE_REQUIRED,
'The new value of the config'
)
->addOption(
'update-only',
null,
InputOption::VALUE_NONE,
'Only updates the value, if it is not set before, it is not being added'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$configNames = $input->getArgument('name');
$configName = $configNames[0];
$configValue = $this->castValue($input->getOption('value'), $input->getOption('type'));
$updateOnly = $input->getOption('update-only');
if (count($configNames) > 1) {
$existingValue = $this->systemConfig->getValue($configName);
$newValue = $this->mergeArrayValue(
array_slice($configNames, 1), $existingValue, $configValue['value'], $updateOnly
);
$this->systemConfig->setValue($configName, $newValue);
} else {
if ($updateOnly && !in_array($configName, $this->systemConfig->getKeys(), true)) {
throw new \UnexpectedValueException('Config parameter does not exist');
}
$this->systemConfig->setValue($configName, $configValue['value']);
}
$output->writeln('<info>System config value ' . implode(' => ', $configNames) . ' set to ' . $configValue['readable-value'] . '</info>');
return 0;
}
/**
* @param string $value
* @param string $type
* @return mixed
* @throws \InvalidArgumentException
*/
protected function castValue($value, $type) {
switch ($type) {
case 'integer':
case 'int':
if (!is_numeric($value)) {
throw new \InvalidArgumentException('Non-numeric value specified');
}
return [
'value' => (int) $value,
'readable-value' => 'integer ' . (int) $value,
];
case 'double':
case 'float':
if (!is_numeric($value)) {
throw new \InvalidArgumentException('Non-numeric value specified');
}
return [
'value' => (double) $value,
'readable-value' => 'double ' . (double) $value,
];
case 'boolean':
case 'bool':
$value = strtolower($value);
switch ($value) {
case 'true':
return [
'value' => true,
'readable-value' => 'boolean ' . $value,
];
case 'false':
return [
'value' => false,
'readable-value' => 'boolean ' . $value,
];
default:
throw new \InvalidArgumentException('Unable to parse value as boolean');
}
// no break
case 'null':
return [
'value' => null,
'readable-value' => 'null',
];
case 'string':
$value = (string) $value;
return [
'value' => $value,
'readable-value' => ($value === '') ? 'empty string' : 'string ' . $value,
];
default:
throw new \InvalidArgumentException('Invalid type');
}
}
/**
* @param array $configNames
* @param mixed $existingValues
* @param mixed $value
* @param bool $updateOnly
* @return array merged value
* @throws \UnexpectedValueException
*/
protected function mergeArrayValue(array $configNames, $existingValues, $value, $updateOnly) {
$configName = array_shift($configNames);
if (!is_array($existingValues)) {
$existingValues = [];
}
if (!empty($configNames)) {
if (isset($existingValues[$configName])) {
$existingValue = $existingValues[$configName];
} else {
$existingValue = [];
}
$existingValues[$configName] = $this->mergeArrayValue($configNames, $existingValue, $value, $updateOnly);
} else {
if (!isset($existingValues[$configName]) && $updateOnly) {
throw new \UnexpectedValueException('Config parameter does not exist');
}
$existingValues[$configName] = $value;
}
return $existingValues;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'type') {
return ['string', 'integer', 'double', 'boolean'];
}
return parent::completeOptionValues($optionName, $context);
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Db;
use OC\DB\Connection;
use OC\DB\SchemaWrapper;
use OCP\DB\Events\AddMissingColumnsEvent;
use OCP\EventDispatcher\IEventDispatcher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class AddMissingColumns
*
* if you added a new lazy column to the database, this is the right place to add
* your update routine for existing instances
*
* @package OC\Core\Command\Db
*/
class AddMissingColumns extends Command {
public function __construct(
private Connection $connection,
private IEventDispatcher $dispatcher,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:add-missing-columns')
->setDescription('Add missing optional columns to the database tables')
->addOption('dry-run', null, InputOption::VALUE_NONE, "Output the SQL queries instead of running them.");
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$dryRun = $input->getOption('dry-run');
// Dispatch event so apps can also update columns if needed
$event = new AddMissingColumnsEvent();
$this->dispatcher->dispatchTyped($event);
$missingColumns = $event->getMissingColumns();
$updated = false;
if (!empty($missingColumns)) {
$schema = new SchemaWrapper($this->connection);
foreach ($missingColumns as $missingColumn) {
if ($schema->hasTable($missingColumn['tableName'])) {
$table = $schema->getTable($missingColumn['tableName']);
if (!$table->hasColumn($missingColumn['columnName'])) {
$output->writeln('<info>Adding additional ' . $missingColumn['columnName'] . ' column to the ' . $missingColumn['tableName'] . ' table, this can take some time...</info>');
$table->addColumn($missingColumn['columnName'], $missingColumn['typeName'], $missingColumn['options']);
$sqlQueries = $this->connection->migrateToSchema($schema->getWrappedSchema(), $dryRun);
if ($dryRun && $sqlQueries !== null) {
$output->writeln($sqlQueries);
}
$updated = true;
$output->writeln('<info>' . $missingColumn['tableName'] . ' table updated successfully.</info>');
}
}
}
}
if (!$updated) {
$output->writeln('<info>Done.</info>');
}
return 0;
}
}
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Bjoern Schiessle <bjoern@schiessle.org>
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Mario Danic <mario@lovelyhq.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Db;
use OC\DB\Connection;
use OC\DB\SchemaWrapper;
use OCP\DB\Events\AddMissingIndicesEvent;
use OCP\EventDispatcher\IEventDispatcher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class AddMissingIndices
*
* if you added any new indices to the database, this is the right place to add
* your update routine for existing instances
*
* @package OC\Core\Command\Db
*/
class AddMissingIndices extends Command {
public function __construct(
private Connection $connection,
private IEventDispatcher $dispatcher,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:add-missing-indices')
->setDescription('Add missing indices to the database tables')
->addOption('dry-run', null, InputOption::VALUE_NONE, "Output the SQL queries instead of running them.");
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$dryRun = $input->getOption('dry-run');
// Dispatch event so apps can also update indexes if needed
$event = new AddMissingIndicesEvent();
$this->dispatcher->dispatchTyped($event);
$missingIndices = $event->getMissingIndices();
if ($missingIndices !== []) {
$schema = new SchemaWrapper($this->connection);
foreach ($missingIndices as $missingIndex) {
if ($schema->hasTable($missingIndex['tableName'])) {
$table = $schema->getTable($missingIndex['tableName']);
if (!$table->hasIndex($missingIndex['indexName'])) {
$output->writeln('<info>Adding additional ' . $missingIndex['indexName'] . ' index to the ' . $table->getName() . ' table, this can take some time...</info>');
if ($missingIndex['dropUnnamedIndex']) {
foreach ($table->getIndexes() as $index) {
$columns = $index->getColumns();
if ($columns === $missingIndex['columns']) {
$table->dropIndex($index->getName());
}
}
}
if ($missingIndex['uniqueIndex']) {
$table->addUniqueIndex($missingIndex['columns'], $missingIndex['indexName'], $missingIndex['options']);
} else {
$table->addIndex($missingIndex['columns'], $missingIndex['indexName'], [], $missingIndex['options']);
}
$sqlQueries = $this->connection->migrateToSchema($schema->getWrappedSchema(), $dryRun);
if ($dryRun && $sqlQueries !== null) {
$output->writeln($sqlQueries);
}
$output->writeln('<info>' . $table->getName() . ' table updated successfully.</info>');
}
}
}
}
return 0;
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 Bjoern Schiessle <bjoern@schiessle.org>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Db;
use OC\DB\Connection;
use OC\DB\SchemaWrapper;
use OCP\DB\Events\AddMissingPrimaryKeyEvent;
use OCP\EventDispatcher\IEventDispatcher;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class AddMissingPrimaryKeys
*
* if you added primary keys to the database, this is the right place to add
* your update routine for existing instances
*
* @package OC\Core\Command\Db
*/
class AddMissingPrimaryKeys extends Command {
public function __construct(
private Connection $connection,
private IEventDispatcher $dispatcher,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:add-missing-primary-keys')
->setDescription('Add missing primary keys to the database tables')
->addOption('dry-run', null, InputOption::VALUE_NONE, "Output the SQL queries instead of running them.");
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$dryRun = $input->getOption('dry-run');
// Dispatch event so apps can also update indexes if needed
$event = new AddMissingPrimaryKeyEvent();
$this->dispatcher->dispatchTyped($event);
$missingKeys = $event->getMissingPrimaryKeys();
$updated = false;
if (!empty($missingKeys)) {
$schema = new SchemaWrapper($this->connection);
foreach ($missingKeys as $missingKey) {
if ($schema->hasTable($missingKey['tableName'])) {
$table = $schema->getTable($missingKey['tableName']);
if (!$table->hasPrimaryKey()) {
$output->writeln('<info>Adding primary key to the ' . $missingKey['tableName'] . ' table, this can take some time...</info>');
$table->setPrimaryKey($missingKey['columns'], $missingKey['primaryKeyName']);
if ($missingKey['formerIndex'] && $table->hasIndex($missingKey['formerIndex'])) {
$table->dropIndex($missingKey['formerIndex']);
}
$sqlQueries = $this->connection->migrateToSchema($schema->getWrappedSchema(), $dryRun);
if ($dryRun && $sqlQueries !== null) {
$output->writeln($sqlQueries);
}
$updated = true;
$output->writeln('<info>' . $missingKey['tableName'] . ' table updated successfully.</info>');
}
}
}
}
if (!$updated) {
$output->writeln('<info>Done.</info>');
}
return 0;
}
}
@@ -0,0 +1,130 @@
<?php
/**
* @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
*
* @author Alecks Gates <alecks.g@gmail.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author timm2k <timm2k@gmx.de>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Db;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Types\Type;
use OC\DB\Connection;
use OC\DB\SchemaWrapper;
use OCP\DB\Types;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class ConvertFilecacheBigInt extends Command {
public function __construct(
private Connection $connection,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:convert-filecache-bigint')
->setDescription('Convert the ID columns of the filecache to BigInt');
}
/**
* @return array<string,string[]>
*/
public static function getColumnsByTable(): array {
return [
'activity' => ['activity_id', 'object_id'],
'activity_mq' => ['mail_id'],
'authtoken' => ['id'],
'bruteforce_attempts' => ['id'],
'federated_reshares' => ['share_id'],
'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart', 'mtime', 'storage_mtime'],
'filecache_extended' => ['fileid'],
'files_trash' => ['auto_id'],
'file_locks' => ['id'],
'file_metadata' => ['id'],
'jobs' => ['id'],
'mimetypes' => ['id'],
'mounts' => ['id', 'storage_id', 'root_id', 'mount_id'],
'share_external' => ['id', 'parent'],
'storages' => ['numeric_id'],
];
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$schema = new SchemaWrapper($this->connection);
$isSqlite = $this->connection->getDatabasePlatform() instanceof SqlitePlatform;
$updates = [];
$tables = static::getColumnsByTable();
foreach ($tables as $tableName => $columns) {
if (!$schema->hasTable($tableName)) {
continue;
}
$table = $schema->getTable($tableName);
foreach ($columns as $columnName) {
$column = $table->getColumn($columnName);
$isAutoIncrement = $column->getAutoincrement();
$isAutoIncrementOnSqlite = $isSqlite && $isAutoIncrement;
if ($column->getType()->getName() !== Types::BIGINT && !$isAutoIncrementOnSqlite) {
$column->setType(Type::getType(Types::BIGINT));
$column->setOptions(['length' => 20]);
$updates[] = '* ' . $tableName . '.' . $columnName;
}
}
}
if (empty($updates)) {
$output->writeln('<info>All tables already up to date!</info>');
return 0;
}
$output->writeln('<comment>Following columns will be updated:</comment>');
$output->writeln('');
$output->writeln($updates);
$output->writeln('');
$output->writeln('<comment>This can take up to hours, depending on the number of files in your instance!</comment>');
if ($input->isInteractive()) {
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('Continue with the conversion (y/n)? [n] ', false);
if (!$helper->ask($input, $output, $question)) {
return 1;
}
}
$this->connection->migrateToSchema($schema->getWrappedSchema());
return 0;
}
}
@@ -0,0 +1,78 @@
<?php
/**
* @copyright Copyright (c) 2017, ownCloud GmbH
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db;
use Doctrine\DBAL\Platforms\MySQLPlatform;
use OC\DB\MySqlTools;
use OC\Migration\ConsoleOutput;
use OC\Repair\Collation;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IURLGenerator;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ConvertMysqlToMB4 extends Command {
public function __construct(
private IConfig $config,
private IDBConnection $connection,
private IURLGenerator $urlGenerator,
private LoggerInterface $logger,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:convert-mysql-charset')
->setDescription('Convert charset of MySQL/MariaDB to use utf8mb4');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if (!$this->connection->getDatabasePlatform() instanceof MySQLPlatform) {
$output->writeln("This command is only valid for MySQL/MariaDB databases.");
return 1;
}
$tools = new MySqlTools();
if (!$tools->supports4ByteCharset($this->connection)) {
$url = $this->urlGenerator->linkToDocs('admin-mysql-utf8mb4');
$output->writeln("The database is not properly setup to use the charset utf8mb4.");
$output->writeln("For more information please read the documentation at $url");
return 1;
}
// enable charset
$this->config->setSystemValue('mysql.utf8mb4', true);
// run conversion
$coll = new Collation($this->config, $this->logger, $this->connection, false);
$coll->run(new ConsoleOutput($output));
return 0;
}
}
@@ -0,0 +1,466 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Andreas Fischer <bantu@owncloud.com>
* @author Bart Visscher <bartv@thisnet.nl>
* @author Bernhard Ostertag <bernieo.code@gmx.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Łukasz Buśko <busko.lukasz@pm.me>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Sander Ruitenbeek <sander@grids.be>
* @author Simon Spannagel <simonspa@kth.se>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Schema\AbstractAsset;
use Doctrine\DBAL\Schema\Table;
use OC\DB\Connection;
use OC\DB\ConnectionFactory;
use OC\DB\MigrationService;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\DB\Types;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use function preg_match;
use function preg_quote;
class ConvertType extends Command implements CompletionAwareInterface {
protected array $columnTypes = [];
public function __construct(
protected IConfig $config,
protected ConnectionFactory $connectionFactory,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('db:convert-type')
->setDescription('Convert the Nextcloud database to the newly configured one')
->addArgument(
'type',
InputArgument::REQUIRED,
'the type of the database to convert to'
)
->addArgument(
'username',
InputArgument::REQUIRED,
'the username of the database to convert to'
)
->addArgument(
'hostname',
InputArgument::REQUIRED,
'the hostname of the database to convert to'
)
->addArgument(
'database',
InputArgument::REQUIRED,
'the name of the database to convert to'
)
->addOption(
'port',
null,
InputOption::VALUE_REQUIRED,
'the port of the database to convert to'
)
->addOption(
'password',
null,
InputOption::VALUE_REQUIRED,
'the password of the database to convert to. Will be asked when not specified. Can also be passed via stdin.'
)
->addOption(
'clear-schema',
null,
InputOption::VALUE_NONE,
'remove all tables from the destination database'
)
->addOption(
'all-apps',
null,
InputOption::VALUE_NONE,
'whether to create schema for all apps instead of only installed apps'
)
->addOption(
'chunk-size',
null,
InputOption::VALUE_REQUIRED,
'the maximum number of database rows to handle in a single query, bigger tables will be handled in chunks of this size. Lower this if the process runs out of memory during conversion.',
'1000'
)
;
}
protected function validateInput(InputInterface $input, OutputInterface $output) {
$type = $this->connectionFactory->normalizeType($input->getArgument('type'));
if ($type === 'sqlite3') {
throw new \InvalidArgumentException(
'Converting to SQLite (sqlite3) is currently not supported.'
);
}
if ($type === $this->config->getSystemValue('dbtype', '')) {
throw new \InvalidArgumentException(sprintf(
'Can not convert from %1$s to %1$s.',
$type
));
}
if ($type === 'oci' && $input->getOption('clear-schema')) {
// Doctrine unconditionally tries (at least in version 2.3)
// to drop sequence triggers when dropping a table, even though
// such triggers may not exist. This results in errors like
// "ORA-04080: trigger 'OC_STORAGES_AI_PK' does not exist".
throw new \InvalidArgumentException(
'The --clear-schema option is not supported when converting to Oracle (oci).'
);
}
}
protected function readPassword(InputInterface $input, OutputInterface $output) {
// Explicitly specified password
if ($input->getOption('password')) {
return;
}
// Read from stdin. stream_set_blocking is used to prevent blocking
// when nothing is passed via stdin.
stream_set_blocking(STDIN, 0);
$password = file_get_contents('php://stdin');
stream_set_blocking(STDIN, 1);
if (trim($password) !== '') {
$input->setOption('password', $password);
return;
}
// Read password by interacting
if ($input->isInteractive()) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new Question('What is the database password?');
$question->setHidden(true);
$question->setHiddenFallback(false);
$password = $helper->ask($input, $output, $question);
$input->setOption('password', $password);
return;
}
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$this->validateInput($input, $output);
$this->readPassword($input, $output);
/** @var Connection $fromDB */
$fromDB = \OC::$server->get(Connection::class);
$toDB = $this->getToDBConnection($input, $output);
if ($input->getOption('clear-schema')) {
$this->clearSchema($toDB, $input, $output);
}
$this->createSchema($fromDB, $toDB, $input, $output);
$toTables = $this->getTables($toDB);
$fromTables = $this->getTables($fromDB);
// warn/fail if there are more tables in 'from' database
$extraFromTables = array_diff($fromTables, $toTables);
if (!empty($extraFromTables)) {
$output->writeln('<comment>The following tables will not be converted:</comment>');
$output->writeln($extraFromTables);
if (!$input->getOption('all-apps')) {
$output->writeln('<comment>Please note that tables belonging to available but currently not installed apps</comment>');
$output->writeln('<comment>can be included by specifying the --all-apps option.</comment>');
}
$continueConversion = !$input->isInteractive(); // assume yes for --no-interaction and no otherwise.
$question = new ConfirmationQuestion('Continue with the conversion (y/n)? [n] ', $continueConversion);
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
if (!$helper->ask($input, $output, $question)) {
return 1;
}
}
$intersectingTables = array_intersect($toTables, $fromTables);
$this->convertDB($fromDB, $toDB, $intersectingTables, $input, $output);
return 0;
}
protected function createSchema(Connection $fromDB, Connection $toDB, InputInterface $input, OutputInterface $output) {
$output->writeln('<info>Creating schema in new database</info>');
$fromMS = new MigrationService('core', $fromDB);
$currentMigration = $fromMS->getMigration('current');
if ($currentMigration !== '0') {
$toMS = new MigrationService('core', $toDB);
$toMS->migrate($currentMigration);
}
$apps = $input->getOption('all-apps') ? \OC_App::getAllApps() : \OC_App::getEnabledApps();
foreach ($apps as $app) {
$output->writeln('<info> - '.$app.'</info>');
// Make sure autoloading works...
\OC_App::loadApp($app);
$fromMS = new MigrationService($app, $fromDB);
$currentMigration = $fromMS->getMigration('current');
if ($currentMigration !== '0') {
$toMS = new MigrationService($app, $toDB);
$toMS->migrate($currentMigration, true);
}
}
}
protected function getToDBConnection(InputInterface $input, OutputInterface $output) {
$type = $input->getArgument('type');
$connectionParams = $this->connectionFactory->createConnectionParams();
$connectionParams = array_merge($connectionParams, [
'host' => $input->getArgument('hostname'),
'user' => $input->getArgument('username'),
'password' => $input->getOption('password'),
'dbname' => $input->getArgument('database'),
]);
if ($input->getOption('port')) {
$connectionParams['port'] = $input->getOption('port');
}
return $this->connectionFactory->getConnection($type, $connectionParams);
}
protected function clearSchema(Connection $db, InputInterface $input, OutputInterface $output) {
$toTables = $this->getTables($db);
if (!empty($toTables)) {
$output->writeln('<info>Clearing schema in new database</info>');
}
foreach ($toTables as $table) {
$db->getSchemaManager()->dropTable($table);
}
}
protected function getTables(Connection $db) {
$db->getConfiguration()->setSchemaAssetsFilter(function ($asset) {
/** @var string|AbstractAsset $asset */
$filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
if ($asset instanceof AbstractAsset) {
return preg_match($filterExpression, $asset->getName()) !== false;
}
return preg_match($filterExpression, $asset) !== false;
});
return $db->getSchemaManager()->listTableNames();
}
/**
* @param Connection $fromDB
* @param Connection $toDB
* @param Table $table
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function copyTable(Connection $fromDB, Connection $toDB, Table $table, InputInterface $input, OutputInterface $output) {
if ($table->getName() === $toDB->getPrefix() . 'migrations') {
$output->writeln('<comment>Skipping migrations table because it was already filled by running the migrations</comment>');
return;
}
$chunkSize = (int)$input->getOption('chunk-size');
$query = $fromDB->getQueryBuilder();
$query->automaticTablePrefix(false);
$query->select($query->func()->count('*', 'num_entries'))
->from($table->getName());
$result = $query->execute();
$count = $result->fetchOne();
$result->closeCursor();
$numChunks = ceil($count / $chunkSize);
if ($numChunks > 1) {
$output->writeln('chunked query, ' . $numChunks . ' chunks');
}
$progress = new ProgressBar($output, $count);
$progress->setFormat('very_verbose');
$progress->start();
$redraw = $count > $chunkSize ? 100 : ($count > 100 ? 5 : 1);
$progress->setRedrawFrequency($redraw);
$query = $fromDB->getQueryBuilder();
$query->automaticTablePrefix(false);
$query->select('*')
->from($table->getName())
->setMaxResults($chunkSize);
try {
$orderColumns = $table->getPrimaryKeyColumns();
} catch (Exception $e) {
$orderColumns = $table->getColumns();
}
foreach ($orderColumns as $column) {
$query->addOrderBy($column->getName());
}
$insertQuery = $toDB->getQueryBuilder();
$insertQuery->automaticTablePrefix(false);
$insertQuery->insert($table->getName());
$parametersCreated = false;
for ($chunk = 0; $chunk < $numChunks; $chunk++) {
$query->setFirstResult($chunk * $chunkSize);
$result = $query->execute();
try {
$toDB->beginTransaction();
while ($row = $result->fetch()) {
$progress->advance();
if (!$parametersCreated) {
foreach ($row as $key => $value) {
$insertQuery->setValue($key, $insertQuery->createParameter($key));
}
$parametersCreated = true;
}
foreach ($row as $key => $value) {
$type = $this->getColumnType($table, $key);
if ($type !== false) {
$insertQuery->setParameter($key, $value, $type);
} else {
$insertQuery->setParameter($key, $value);
}
}
$insertQuery->execute();
}
$result->closeCursor();
$toDB->commit();
} catch (\Throwable $e) {
$toDB->rollBack();
throw $e;
}
}
$progress->finish();
$output->writeln('');
}
protected function getColumnType(Table $table, $columnName) {
$tableName = $table->getName();
if (isset($this->columnTypes[$tableName][$columnName])) {
return $this->columnTypes[$tableName][$columnName];
}
$type = $table->getColumn($columnName)->getType()->getName();
switch ($type) {
case Types::BLOB:
case Types::TEXT:
$this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_LOB;
break;
case Types::BOOLEAN:
$this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_BOOL;
break;
default:
$this->columnTypes[$tableName][$columnName] = false;
}
return $this->columnTypes[$tableName][$columnName];
}
protected function convertDB(Connection $fromDB, Connection $toDB, array $tables, InputInterface $input, OutputInterface $output) {
$this->config->setSystemValue('maintenance', true);
$schema = $fromDB->createSchema();
try {
// copy table rows
foreach ($tables as $table) {
$output->writeln('<info> - '.$table.'</info>');
$this->copyTable($fromDB, $toDB, $schema->getTable($table), $input, $output);
}
if ($input->getArgument('type') === 'pgsql') {
$tools = new \OC\DB\PgSqlTools($this->config);
$tools->resynchronizeDatabaseSequences($toDB);
}
// save new database config
$this->saveDBInfo($input);
} catch (\Exception $e) {
$this->config->setSystemValue('maintenance', false);
throw $e;
}
$this->config->setSystemValue('maintenance', false);
}
protected function saveDBInfo(InputInterface $input) {
$type = $input->getArgument('type');
$username = $input->getArgument('username');
$dbHost = $input->getArgument('hostname');
$dbName = $input->getArgument('database');
$password = $input->getOption('password');
if ($input->getOption('port')) {
$dbHost .= ':'.$input->getOption('port');
}
$this->config->setSystemValues([
'dbtype' => $type,
'dbname' => $dbName,
'dbhost' => $dbHost,
'dbuser' => $username,
'dbpassword' => $password,
]);
}
/**
* Return possible values for the named option
*
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* Return possible values for the named argument
*
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'type') {
return ['mysql', 'oci', 'pgsql'];
}
return [];
}
}
@@ -0,0 +1,112 @@
<?php
/**
* @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
* @copyright Copyright (c) 2017, ownCloud GmbH
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db\Migrations;
use OC\DB\Connection;
use OC\DB\MigrationService;
use OC\Migration\ConsoleOutput;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ExecuteCommand extends Command implements CompletionAwareInterface {
public function __construct(
private Connection $connection,
private IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('migrations:execute')
->setDescription('Execute a single migration version manually.')
->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on')
->addArgument('version', InputArgument::REQUIRED, 'The version to execute.', null);
parent::configure();
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
public function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
$version = $input->getArgument('version');
if ($this->config->getSystemValue('debug', false) === false) {
$olderVersions = $ms->getMigratedVersions();
$olderVersions[] = '0';
$olderVersions[] = 'prev';
if (in_array($version, $olderVersions, true)) {
$output->writeln('<error>Can not go back to previous migration without debug enabled</error>');
return 1;
}
}
$ms->executeStep($version);
return 0;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
$allApps = \OC_App::getAllApps();
return array_diff($allApps, \OC_App::getEnabledApps(true, true));
}
if ($argumentName === 'version') {
$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
$ms = new MigrationService($appName, $this->connection);
$migrations = $ms->getAvailableVersions();
array_unshift($migrations, 'next', 'latest');
return $migrations;
}
return [];
}
}
@@ -0,0 +1,259 @@
<?php
/**
* @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
* @copyright Copyright (c) 2017, ownCloud GmbH
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db\Migrations;
use OC\DB\Connection;
use OC\DB\MigrationService;
use OC\Migration\ConsoleOutput;
use OCP\App\IAppManager;
use OCP\Util;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class GenerateCommand extends Command implements CompletionAwareInterface {
protected static $_templateSimple =
'<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) {{year}} Your name <your@email.com>
*
* @author Your name <your@email.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace {{namespace}};
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
/**
* Auto-generated migration step: Please modify to your needs!
*/
class {{classname}} extends SimpleMigrationStep {
/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
*/
public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
}
/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
{{schemabody}}
}
/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
*/
public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
}
}
';
protected Connection $connection;
protected IAppManager $appManager;
public function __construct(Connection $connection, IAppManager $appManager) {
$this->connection = $connection;
$this->appManager = $appManager;
parent::__construct();
}
protected function configure() {
$this
->setName('migrations:generate')
->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on')
->addArgument('version', InputArgument::REQUIRED, 'Major version of this app, to allow versions on parallel development branches')
;
parent::configure();
}
public function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$version = $input->getArgument('version');
if (!preg_match('/^\d{1,16}$/', $version)) {
$output->writeln('<error>The given version is invalid. Only 0-9 are allowed (max. 16 digits)</error>');
return 1;
}
if ($appName === 'core') {
$fullVersion = implode('.', Util::getVersion());
} else {
try {
$fullVersion = $this->appManager->getAppVersion($appName, false);
} catch (\Throwable $e) {
$fullVersion = '';
}
}
if ($fullVersion) {
[$major, $minor] = explode('.', $fullVersion);
$shouldVersion = (string) ((int)$major * 1000 + (int)$minor);
if ($version !== $shouldVersion) {
$output->writeln('<comment>Unexpected migration version for current version: ' . $fullVersion . '</comment>');
$output->writeln('<comment> - Pattern: XYYY </comment>');
$output->writeln('<comment> - Expected: ' . $shouldVersion . '</comment>');
$output->writeln('<comment> - Actual: ' . $version . '</comment>');
if ($input->isInteractive()) {
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('Continue with your given version? (y/n) [n] ', false);
if (!$helper->ask($input, $output, $question)) {
return 1;
}
}
}
}
$ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
$date = date('YmdHis');
$path = $this->generateMigration($ms, 'Version' . $version . 'Date' . $date);
$output->writeln("New migration class has been generated to <info>$path</info>");
return 0;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
$allApps = \OC_App::getAllApps();
return array_diff($allApps, \OC_App::getEnabledApps(true, true));
}
if ($argumentName === 'version') {
$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
$version = explode('.', $this->appManager->getAppVersion($appName));
return [$version[0] . sprintf('%1$03d', $version[1])];
}
return [];
}
/**
* @param MigrationService $ms
* @param string $className
* @param string $schemaBody
* @return string
*/
protected function generateMigration(MigrationService $ms, $className, $schemaBody = '') {
if ($schemaBody === '') {
$schemaBody = "\t\t" . 'return null;';
}
$placeHolders = [
'{{namespace}}',
'{{classname}}',
'{{schemabody}}',
'{{year}}',
];
$replacements = [
$ms->getMigrationsNamespace(),
$className,
$schemaBody,
date('Y')
];
$code = str_replace($placeHolders, $replacements, self::$_templateSimple);
$dir = $ms->getMigrationsDirectory();
$this->ensureMigrationDirExists($dir);
$path = $dir . '/' . $className . '.php';
if (file_put_contents($path, $code) === false) {
throw new RuntimeException('Failed to generate new migration step. Could not write to ' . $path);
}
return $path;
}
protected function ensureMigrationDirExists($directory) {
if (file_exists($directory) && is_dir($directory)) {
return;
}
if (file_exists($directory)) {
throw new \RuntimeException("Could not create folder \"$directory\"");
}
$this->ensureMigrationDirExists(dirname($directory));
if (!@mkdir($directory) && !is_dir($directory)) {
throw new \RuntimeException("Could not create folder \"$directory\"");
}
}
}
@@ -0,0 +1,93 @@
<?php
/**
* @copyright Copyright (c) 2017, ownCloud GmbH
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db\Migrations;
use OC\DB\Connection;
use OC\DB\MigrationService;
use OC\Migration\ConsoleOutput;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MigrateCommand extends Command implements CompletionAwareInterface {
public function __construct(
private Connection $connection,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('migrations:migrate')
->setDescription('Execute a migration to a specified version or the latest available version.')
->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on')
->addArgument('version', InputArgument::OPTIONAL, 'The version number (YYYYMMDDHHMMSS) or alias (first, prev, next, latest) to migrate to.', 'latest');
parent::configure();
}
public function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
$version = $input->getArgument('version');
$ms->migrate($version);
return 0;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
$allApps = \OC_App::getAllApps();
return array_diff($allApps, \OC_App::getEnabledApps(true, true));
}
if ($argumentName === 'version') {
$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
$ms = new MigrationService($appName, $this->connection);
$migrations = $ms->getAvailableVersions();
array_unshift($migrations, 'next', 'latest');
return $migrations;
}
return [];
}
}
@@ -0,0 +1,142 @@
<?php
/**
* @copyright Copyright (c) 2017, ownCloud GmbH
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Db\Migrations;
use OC\DB\Connection;
use OC\DB\MigrationService;
use OC\Migration\ConsoleOutput;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class StatusCommand extends Command implements CompletionAwareInterface {
public function __construct(
private Connection $connection,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('migrations:status')
->setDescription('View the status of a set of migrations.')
->addArgument('app', InputArgument::REQUIRED, 'Name of the app this migration command shall work on');
}
public function execute(InputInterface $input, OutputInterface $output): int {
$appName = $input->getArgument('app');
$ms = new MigrationService($appName, $this->connection, new ConsoleOutput($output));
$infos = $this->getMigrationsInfos($ms);
foreach ($infos as $key => $value) {
if (is_array($value)) {
$output->writeln(" <comment>>></comment> $key:");
foreach ($value as $subKey => $subValue) {
$output->writeln(" <comment>>></comment> $subKey: " . str_repeat(' ', 46 - strlen($subKey)) . $subValue);
}
} else {
$output->writeln(" <comment>>></comment> $key: " . str_repeat(' ', 50 - strlen($key)) . $value);
}
}
return 0;
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
$allApps = \OC_App::getAllApps();
return array_diff($allApps, \OC_App::getEnabledApps(true, true));
}
return [];
}
/**
* @param MigrationService $ms
* @return array associative array of human readable info name as key and the actual information as value
*/
public function getMigrationsInfos(MigrationService $ms) {
$executedMigrations = $ms->getMigratedVersions();
$availableMigrations = $ms->getAvailableVersions();
$executedUnavailableMigrations = array_diff($executedMigrations, array_keys($availableMigrations));
$numExecutedUnavailableMigrations = count($executedUnavailableMigrations);
$numNewMigrations = count(array_diff(array_keys($availableMigrations), $executedMigrations));
$pending = $ms->describeMigrationStep('lastest');
$infos = [
'App' => $ms->getApp(),
'Version Table Name' => $ms->getMigrationsTableName(),
'Migrations Namespace' => $ms->getMigrationsNamespace(),
'Migrations Directory' => $ms->getMigrationsDirectory(),
'Previous Version' => $this->getFormattedVersionAlias($ms, 'prev'),
'Current Version' => $this->getFormattedVersionAlias($ms, 'current'),
'Next Version' => $this->getFormattedVersionAlias($ms, 'next'),
'Latest Version' => $this->getFormattedVersionAlias($ms, 'latest'),
'Executed Migrations' => count($executedMigrations),
'Executed Unavailable Migrations' => $numExecutedUnavailableMigrations,
'Available Migrations' => count($availableMigrations),
'New Migrations' => $numNewMigrations,
'Pending Migrations' => count($pending) ? $pending : 'None'
];
return $infos;
}
/**
* @param MigrationService $migrationService
* @param string $alias
* @return mixed|null|string
*/
private function getFormattedVersionAlias(MigrationService $migrationService, $alias) {
$migration = $migrationService->getMigration($alias);
//No version found
if ($migration === null) {
if ($alias === 'next') {
return 'Already at latest migration step';
}
if ($alias === 'prev') {
return 'Already at first migration step';
}
}
return $migration;
}
}
@@ -0,0 +1,247 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OC\Encryption\Keys\Storage;
use OC\Encryption\Util;
use OC\Files\Filesystem;
use OC\Files\View;
use OCP\IConfig;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class ChangeKeyStorageRoot extends Command {
public function __construct(
protected View $rootView,
protected IUserManager $userManager,
protected IConfig $config,
protected Util $util,
protected QuestionHelper $questionHelper,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:change-key-storage-root')
->setDescription('Change key storage root')
->addArgument(
'newRoot',
InputArgument::OPTIONAL,
'new root of the key storage relative to the data folder'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$oldRoot = $this->util->getKeyStorageRoot();
$newRoot = $input->getArgument('newRoot');
if ($newRoot === null) {
$question = new ConfirmationQuestion('No storage root given, do you want to reset the key storage root to the default location? (y/n) ', false);
if (!$this->questionHelper->ask($input, $output, $question)) {
return 1;
}
$newRoot = '';
}
$oldRootDescription = $oldRoot !== '' ? $oldRoot : 'default storage location';
$newRootDescription = $newRoot !== '' ? $newRoot : 'default storage location';
$output->writeln("Change key storage root from <info>$oldRootDescription</info> to <info>$newRootDescription</info>");
$success = $this->moveAllKeys($oldRoot, $newRoot, $output);
if ($success) {
$this->util->setKeyStorageRoot($newRoot);
$output->writeln('');
$output->writeln("Key storage root successfully changed to <info>$newRootDescription</info>");
return 0;
}
return 1;
}
/**
* move keys to new key storage root
*
* @param string $oldRoot
* @param string $newRoot
* @param OutputInterface $output
* @return bool
* @throws \Exception
*/
protected function moveAllKeys($oldRoot, $newRoot, OutputInterface $output) {
$output->writeln("Start to move keys:");
if ($this->rootView->is_dir($oldRoot) === false) {
$output->writeln("No old keys found: Nothing needs to be moved");
return false;
}
$this->prepareNewRoot($newRoot);
$this->moveSystemKeys($oldRoot, $newRoot);
$this->moveUserKeys($oldRoot, $newRoot, $output);
return true;
}
/**
* prepare new key storage
*
* @param string $newRoot
* @throws \Exception
*/
protected function prepareNewRoot($newRoot) {
if ($this->rootView->is_dir($newRoot) === false) {
throw new \Exception("New root folder doesn't exist. Please create the folder or check the permissions and try again.");
}
$result = $this->rootView->file_put_contents(
$newRoot . '/' . Storage::KEY_STORAGE_MARKER,
'Nextcloud will detect this folder as key storage root only if this file exists'
);
if (!$result) {
throw new \Exception("Can't access the new root folder. Please check the permissions and make sure that the folder is in your data folder");
}
}
/**
* move system key folder
*
* @param string $oldRoot
* @param string $newRoot
*/
protected function moveSystemKeys($oldRoot, $newRoot) {
if (
$this->rootView->is_dir($oldRoot . '/files_encryption') &&
$this->targetExists($newRoot . '/files_encryption') === false
) {
$this->rootView->rename($oldRoot . '/files_encryption', $newRoot . '/files_encryption');
}
}
/**
* setup file system for the given user
*
* @param string $uid
*/
protected function setupUserFS($uid) {
\OC_Util::tearDownFS();
\OC_Util::setupFS($uid);
}
/**
* iterate over each user and move the keys to the new storage
*
* @param string $oldRoot
* @param string $newRoot
* @param OutputInterface $output
*/
protected function moveUserKeys($oldRoot, $newRoot, OutputInterface $output) {
$progress = new ProgressBar($output);
$progress->start();
foreach ($this->userManager->getBackends() as $backend) {
$limit = 500;
$offset = 0;
do {
$users = $backend->getUsers('', $limit, $offset);
foreach ($users as $user) {
$progress->advance();
$this->setupUserFS($user);
$this->moveUserEncryptionFolder($user, $oldRoot, $newRoot);
}
$offset += $limit;
} while (count($users) >= $limit);
}
$progress->finish();
}
/**
* move user encryption folder to new root folder
*
* @param string $user
* @param string $oldRoot
* @param string $newRoot
* @throws \Exception
*/
protected function moveUserEncryptionFolder($user, $oldRoot, $newRoot) {
if ($this->userManager->userExists($user)) {
$source = $oldRoot . '/' . $user . '/files_encryption';
$target = $newRoot . '/' . $user . '/files_encryption';
if (
$this->rootView->is_dir($source) &&
$this->targetExists($target) === false
) {
$this->prepareParentFolder($newRoot . '/' . $user);
$this->rootView->rename($source, $target);
}
}
}
/**
* Make preparations to filesystem for saving a key file
*
* @param string $path relative to data/
*/
protected function prepareParentFolder($path) {
$path = Filesystem::normalizePath($path);
// If the file resides within a subdirectory, create it
if ($this->rootView->file_exists($path) === false) {
$sub_dirs = explode('/', ltrim($path, '/'));
$dir = '';
foreach ($sub_dirs as $sub_dir) {
$dir .= '/' . $sub_dir;
if ($this->rootView->file_exists($dir) === false) {
$this->rootView->mkdir($dir);
}
}
}
}
/**
* check if target already exists
*
* @param $path
* @return bool
* @throws \Exception
*/
protected function targetExists($path) {
if ($this->rootView->file_exists($path)) {
throw new \Exception("new folder '$path' already exists");
}
return false;
}
}
@@ -0,0 +1,165 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author davitol <dtoledo@solidgear.es>
* @author Evgeny Golyshev <eugulixes@gmail.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Marius Blüm <marius@lineone.io>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Ruben Homs <ruben@homs.codes>
* @author Sergio Bertolín <sbertolin@solidgear.es>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OCP\App\IAppManager;
use OCP\Encryption\IManager;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class DecryptAll extends Command {
protected bool $wasTrashbinEnabled = false;
protected bool $wasMaintenanceModeEnabled = false;
public function __construct(
protected IManager $encryptionManager,
protected IAppManager $appManager,
protected IConfig $config,
protected \OC\Encryption\DecryptAll $decryptAll,
protected QuestionHelper $questionHelper,
) {
parent::__construct();
}
/**
* Set maintenance mode and disable the trashbin app
*/
protected function forceMaintenanceAndTrashbin(): void {
$this->wasTrashbinEnabled = $this->appManager->isEnabledForUser('files_trashbin');
$this->wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance');
$this->config->setSystemValue('maintenance', true);
$this->appManager->disableApp('files_trashbin');
}
/**
* Reset the maintenance mode and re-enable the trashbin app
*/
protected function resetMaintenanceAndTrashbin(): void {
$this->config->setSystemValue('maintenance', $this->wasMaintenanceModeEnabled);
if ($this->wasTrashbinEnabled) {
$this->appManager->enableApp('files_trashbin');
}
}
protected function configure() {
parent::configure();
$this->setName('encryption:decrypt-all');
$this->setDescription('Disable server-side encryption and decrypt all files');
$this->setHelp(
'This will disable server-side encryption and decrypt all files for '
. 'all users if it is supported by your encryption module. '
. 'Please make sure that no user access his files during this process!'
);
$this->addArgument(
'user',
InputArgument::OPTIONAL,
'user for which you want to decrypt all files (optional)',
''
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if (!$input->isInteractive()) {
$output->writeln('Invalid TTY.');
$output->writeln('If you are trying to execute the command in a Docker ');
$output->writeln("container, do not forget to execute 'docker exec' with");
$output->writeln("the '-i' and '-t' options.");
$output->writeln('');
return 1;
}
$isMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
if ($isMaintenanceModeEnabled) {
$output->writeln("Maintenance mode must be disabled when starting decryption,");
$output->writeln("in order to load the relevant encryption modules correctly.");
$output->writeln("Your instance will automatically be put to maintenance mode");
$output->writeln("during the actual decryption of the files.");
return 1;
}
try {
if ($this->encryptionManager->isEnabled() === true) {
$output->write('Disable server side encryption... ');
$this->config->setAppValue('core', 'encryption_enabled', 'no');
$output->writeln('done.');
} else {
$output->writeln('Server side encryption not enabled. Nothing to do.');
return 0;
}
$uid = $input->getArgument('user');
if ($uid === '') {
$message = 'your Nextcloud';
} else {
$message = "$uid's account";
}
$output->writeln("\n");
$output->writeln("You are about to start to decrypt all files stored in $message.");
$output->writeln('It will depend on the encryption module and your setup if this is possible.');
$output->writeln('Depending on the number and size of your files this can take some time');
$output->writeln('Please make sure that no user access his files during this process!');
$output->writeln('');
$question = new ConfirmationQuestion('Do you really want to continue? (y/n) ', false);
if ($this->questionHelper->ask($input, $output, $question)) {
$this->forceMaintenanceAndTrashbin();
$user = $input->getArgument('user');
$result = $this->decryptAll->decryptAll($input, $output, $user);
if ($result === false) {
$output->writeln(' aborted.');
$output->writeln('Server side encryption remains enabled');
$this->config->setAppValue('core', 'encryption_enabled', 'yes');
} elseif ($uid !== '') {
$output->writeln('Server side encryption remains enabled');
$this->config->setAppValue('core', 'encryption_enabled', 'yes');
}
$this->resetMaintenanceAndTrashbin();
return 0;
}
$output->write('Enable server side encryption... ');
$this->config->setAppValue('core', 'encryption_enabled', 'yes');
$output->writeln('done.');
$output->writeln('aborted');
return 1;
} catch (\Exception $e) {
// enable server side encryption again if something went wrong
$this->config->setAppValue('core', 'encryption_enabled', 'yes');
$this->resetMaintenanceAndTrashbin();
throw $e;
}
}
}
@@ -0,0 +1,52 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Disable extends Command {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('encryption:disable')
->setDescription('Disable encryption')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if ($this->config->getAppValue('core', 'encryption_enabled', 'no') !== 'yes') {
$output->writeln('Encryption is already disabled');
} else {
$this->config->setAppValue('core', 'encryption_enabled', 'no');
$output->writeln('<info>Encryption disabled</info>');
}
return 0;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OCP\Encryption\IManager;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Enable extends Command {
public function __construct(
protected IConfig $config,
protected IManager $encryptionManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('encryption:enable')
->setDescription('Enable encryption')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if ($this->config->getAppValue('core', 'encryption_enabled', 'no') === 'yes') {
$output->writeln('Encryption is already enabled');
} else {
$this->config->setAppValue('core', 'encryption_enabled', 'yes');
$output->writeln('<info>Encryption enabled</info>');
}
$output->writeln('');
$modules = $this->encryptionManager->getEncryptionModules();
if (empty($modules)) {
$output->writeln('<error>No encryption module is loaded</error>');
return 1;
}
$defaultModule = $this->config->getAppValue('core', 'default_encryption_module', null);
if ($defaultModule === null) {
$output->writeln('<error>No default module is set</error>');
return 1;
}
if (!isset($modules[$defaultModule])) {
$output->writeln('<error>The current default module does not exist: ' . $defaultModule . '</error>');
return 1;
}
$output->writeln('Default module: ' . $defaultModule);
return 0;
}
}
@@ -0,0 +1,120 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Evgeny Golyshev <eugulixes@gmail.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Matthew Setter <matthew@matthewsetter.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OCP\App\IAppManager;
use OCP\Encryption\IManager;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class EncryptAll extends Command {
protected bool $wasTrashbinEnabled = false;
protected bool $wasMaintenanceModeEnabled = false;
public function __construct(
protected IManager $encryptionManager,
protected IAppManager $appManager,
protected IConfig $config,
protected QuestionHelper $questionHelper,
) {
parent::__construct();
}
/**
* Set maintenance mode and disable the trashbin app
*/
protected function forceMaintenanceAndTrashbin(): void {
$this->wasTrashbinEnabled = (bool)$this->appManager->isEnabledForUser('files_trashbin');
$this->wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance');
$this->config->setSystemValue('maintenance', true);
$this->appManager->disableApp('files_trashbin');
}
/**
* Reset the maintenance mode and re-enable the trashbin app
*/
protected function resetMaintenanceAndTrashbin(): void {
$this->config->setSystemValue('maintenance', $this->wasMaintenanceModeEnabled);
if ($this->wasTrashbinEnabled) {
$this->appManager->enableApp('files_trashbin');
}
}
protected function configure() {
parent::configure();
$this->setName('encryption:encrypt-all');
$this->setDescription('Encrypt all files for all users');
$this->setHelp(
'This will encrypt all files for all users. '
. 'Please make sure that no user access his files during this process!'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if (!$input->isInteractive()) {
$output->writeln('Invalid TTY.');
$output->writeln('If you are trying to execute the command in a Docker ');
$output->writeln("container, do not forget to execute 'docker exec' with");
$output->writeln("the '-i' and '-t' options.");
$output->writeln('');
return 1;
}
if ($this->encryptionManager->isEnabled() === false) {
throw new \Exception('Server side encryption is not enabled');
}
$output->writeln("\n");
$output->writeln('You are about to encrypt all files stored in your Nextcloud installation.');
$output->writeln('Depending on the number of available files, and their size, this may take quite some time.');
$output->writeln('Please ensure that no user accesses their files during this time!');
$output->writeln('Note: The encryption module you use determines which files get encrypted.');
$output->writeln('');
$question = new ConfirmationQuestion('Do you really want to continue? (y/n) ', false);
if ($this->questionHelper->ask($input, $output, $question)) {
$this->forceMaintenanceAndTrashbin();
try {
$defaultModule = $this->encryptionManager->getEncryptionModule();
$defaultModule->encryptAll($input, $output);
} catch (\Exception $ex) {
$this->resetMaintenanceAndTrashbin();
throw $ex;
}
$this->resetMaintenanceAndTrashbin();
return 0;
}
$output->writeln('aborted');
return 1;
}
}
@@ -0,0 +1,87 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Ruben Homs <ruben@homs.codes>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OC\Core\Command\Base;
use OCP\Encryption\IManager;
use OCP\IConfig;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListModules extends Base {
public function __construct(
protected IManager $encryptionManager,
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:list-modules')
->setDescription('List all available encryption modules')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$isMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
if ($isMaintenanceModeEnabled) {
$output->writeln("Maintenance mode must be disabled when listing modules");
$output->writeln("in order to list the relevant encryption modules correctly.");
return 1;
}
$encryptionModules = $this->encryptionManager->getEncryptionModules();
$defaultEncryptionModuleId = $this->encryptionManager->getDefaultEncryptionModuleId();
$encModules = [];
foreach ($encryptionModules as $module) {
$encModules[$module['id']]['displayName'] = $module['displayName'];
$encModules[$module['id']]['default'] = $module['id'] === $defaultEncryptionModuleId;
}
$this->writeModuleList($input, $output, $encModules);
return 0;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param array $items
*/
protected function writeModuleList(InputInterface $input, OutputInterface $output, $items) {
if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
array_walk($items, function (&$item) {
if (!$item['default']) {
$item = $item['displayName'];
} else {
$item = $item['displayName'] . ' [default*]';
}
});
}
$this->writeArrayInOutputFormat($input, $output, $items);
}
}
@@ -0,0 +1,229 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Roeland Jago Douma <roeland@famdouma.nl>
*
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Encryption;
use OC\Encryption\Keys\Storage;
use OC\Encryption\Util;
use OC\Files\View;
use OCP\IConfig;
use OCP\IUserManager;
use OCP\Security\ICrypto;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class MigrateKeyStorage extends Command {
public function __construct(
protected View $rootView,
protected IUserManager $userManager,
protected IConfig $config,
protected Util $util,
private ICrypto $crypto,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:migrate-key-storage-format')
->setDescription('Migrate the format of the keystorage to a newer format');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$root = $this->util->getKeyStorageRoot();
$output->writeln("Updating key storage format");
$this->updateKeys($root, $output);
$output->writeln("Key storage format successfully updated");
return 0;
}
/**
* Move keys to new key storage root
*
* @param string $root
* @param OutputInterface $output
* @return bool
* @throws \Exception
*/
protected function updateKeys(string $root, OutputInterface $output): bool {
$output->writeln("Start to update the keys:");
$this->updateSystemKeys($root);
$this->updateUsersKeys($root, $output);
$this->config->deleteSystemValue('encryption.key_storage_migrated');
return true;
}
/**
* Move system key folder
*/
protected function updateSystemKeys(string $root): void {
if (!$this->rootView->is_dir($root . '/files_encryption')) {
return;
}
$this->traverseKeys($root . '/files_encryption', null);
}
private function traverseKeys(string $folder, ?string $uid) {
$listing = $this->rootView->getDirectoryContent($folder);
foreach ($listing as $node) {
if ($node['mimetype'] === 'httpd/unix-directory') {
continue;
}
if ($node['name'] === 'fileKey' ||
str_ends_with($node['name'], '.privateKey') ||
str_ends_with($node['name'], '.publicKey') ||
str_ends_with($node['name'], '.shareKey')) {
$path = $folder . '/' . $node['name'];
$content = $this->rootView->file_get_contents($path);
try {
$this->crypto->decrypt($content);
continue;
} catch (\Exception $e) {
// Ignore we now update the data.
}
$data = [
'key' => base64_encode($content),
'uid' => $uid,
];
$enc = $this->crypto->encrypt(json_encode($data));
$this->rootView->file_put_contents($path, $enc);
}
}
}
private function traverseFileKeys(string $folder) {
$listing = $this->rootView->getDirectoryContent($folder);
foreach ($listing as $node) {
if ($node['mimetype'] === 'httpd/unix-directory') {
$this->traverseFileKeys($folder . '/' . $node['name']);
} else {
$endsWith = function ($haystack, $needle) {
$length = strlen($needle);
if ($length === 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
};
if ($node['name'] === 'fileKey' ||
$endsWith($node['name'], '.privateKey') ||
$endsWith($node['name'], '.publicKey') ||
$endsWith($node['name'], '.shareKey')) {
$path = $folder . '/' . $node['name'];
$content = $this->rootView->file_get_contents($path);
try {
$this->crypto->decrypt($content);
continue;
} catch (\Exception $e) {
// Ignore we now update the data.
}
$data = [
'key' => base64_encode($content)
];
$enc = $this->crypto->encrypt(json_encode($data));
$this->rootView->file_put_contents($path, $enc);
}
}
}
}
/**
* setup file system for the given user
*
* @param string $uid
*/
protected function setupUserFS($uid) {
\OC_Util::tearDownFS();
\OC_Util::setupFS($uid);
}
/**
* iterate over each user and move the keys to the new storage
*
* @param string $root
* @param OutputInterface $output
*/
protected function updateUsersKeys(string $root, OutputInterface $output) {
$progress = new ProgressBar($output);
$progress->start();
foreach ($this->userManager->getBackends() as $backend) {
$limit = 500;
$offset = 0;
do {
$users = $backend->getUsers('', $limit, $offset);
foreach ($users as $user) {
$progress->advance();
$this->setupUserFS($user);
$this->updateUserKeys($root, $user);
}
$offset += $limit;
} while (count($users) >= $limit);
}
$progress->finish();
}
/**
* move user encryption folder to new root folder
*
* @param string $root
* @param string $user
* @throws \Exception
*/
protected function updateUserKeys(string $root, string $user) {
if ($this->userManager->userExists($user)) {
$source = $root . '/' . $user . '/files_encryption/OC_DEFAULT_MODULE';
if ($this->rootView->is_dir($source)) {
$this->traverseKeys($source, $user);
}
$source = $root . '/' . $user . '/files_encryption/keys';
if ($this->rootView->is_dir($source)) {
$this->traverseFileKeys($source);
}
}
}
}
@@ -0,0 +1,75 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Ruben Homs <ruben@homs.codes>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OCP\Encryption\IManager;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SetDefaultModule extends Command {
public function __construct(
protected IManager $encryptionManager,
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:set-default-module')
->setDescription('Set the encryption default module')
->addArgument(
'module',
InputArgument::REQUIRED,
'ID of the encryption module that should be used'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$isMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
if ($isMaintenanceModeEnabled) {
$output->writeln("Maintenance mode must be disabled when setting default module,");
$output->writeln("in order to load the relevant encryption modules correctly.");
return 1;
}
$moduleId = $input->getArgument('module');
if ($moduleId === $this->encryptionManager->getDefaultEncryptionModuleId()) {
$output->writeln('"' . $moduleId . '"" is already the default module');
} elseif ($this->encryptionManager->setDefaultEncryptionModule($moduleId)) {
$output->writeln('<info>Set default module to "' . $moduleId . '"</info>');
} else {
$output->writeln('<error>The specified module "' . $moduleId . '" does not exist</error>');
return 1;
}
return 0;
}
}
@@ -0,0 +1,53 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OC\Encryption\Util;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ShowKeyStorageRoot extends Command {
public function __construct(
protected Util $util,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:show-key-storage-root')
->setDescription('Show current key storage root');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$currentRoot = $this->util->getKeyStorageRoot();
$rootDescription = $currentRoot !== '' ? $currentRoot : 'default storage location (data/)';
$output->writeln("Current key storage root: <info>$rootDescription</info>");
return 0;
}
}
@@ -0,0 +1,52 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Encryption;
use OC\Core\Command\Base;
use OCP\Encryption\IManager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Status extends Base {
public function __construct(
protected IManager $encryptionManager,
) {
parent::__construct();
}
protected function configure() {
parent::configure();
$this
->setName('encryption:status')
->setDescription('Lists the current status of encryption')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$this->writeArrayInOutputFormat($input, $output, [
'enabled' => $this->encryptionManager->isEnabled(),
'defaultModule' => $this->encryptionManager->getDefaultEncryptionModuleId(),
]);
return 0;
}
}
@@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Maxence Lange <maxence@artificial-owl.com>
*
* @author Maxence Lange <maxence@artificial-owl.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\FilesMetadata;
use OC\User\NoUserException;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\FilesMetadata\Exceptions\FilesMetadataNotFoundException;
use OCP\FilesMetadata\IFilesMetadataManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Get extends Command {
public function __construct(
private IRootFolder $rootFolder,
private IFilesMetadataManager $filesMetadataManager,
) {
parent::__construct();
}
protected function configure(): void {
$this->setName('metadata:get')
->setDescription('get stored metadata about a file, by its id')
->addArgument(
'fileId',
InputArgument::REQUIRED,
'id of the file document'
)
->addArgument(
'userId',
InputArgument::OPTIONAL,
'file owner'
)
->addOption(
'as-array',
'',
InputOption::VALUE_NONE,
'display metadata as a simple key=>value array'
)
->addOption(
'refresh',
'',
InputOption::VALUE_NONE,
'refresh metadata'
)
->addOption(
'reset',
'',
InputOption::VALUE_NONE,
'refresh metadata from scratch'
);
}
/**
* @throws NotPermittedException
* @throws FilesMetadataNotFoundException
* @throws NoUserException
* @throws NotFoundException
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$fileId = (int)$input->getArgument('fileId');
if ($input->getOption('reset')) {
$this->filesMetadataManager->deleteMetadata($fileId);
if (!$input->getOption('refresh')) {
return self::SUCCESS;
}
}
if ($input->getOption('refresh')) {
$node = $this->rootFolder->getUserFolder($input->getArgument('userId'))->getById($fileId);
if (count($node) === 0) {
throw new NotFoundException();
}
$metadata = $this->filesMetadataManager->refreshMetadata(
$node[0],
IFilesMetadataManager::PROCESS_LIVE | IFilesMetadataManager::PROCESS_BACKGROUND
);
} else {
$metadata = $this->filesMetadataManager->getMetadata($fileId);
}
if ($input->getOption('as-array')) {
$output->writeln(json_encode($metadata->asArray(), JSON_PRETTY_PRINT));
} else {
$output->writeln(json_encode($metadata, JSON_PRETTY_PRINT));
}
return self::SUCCESS;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Denis Mosolov <denismosolov@gmail.com>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Denis Mosolov <denismosolov@gmail.com>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Add extends Base {
public function __construct(
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:add')
->setDescription('Add a group')
->addArgument(
'groupid',
InputArgument::REQUIRED,
'Group id'
)
->addOption(
'display-name',
null,
InputOption::VALUE_REQUIRED,
'Group name used in the web UI (can contain any characters)'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$gid = $input->getArgument('groupid');
$group = $this->groupManager->get($gid);
if ($group) {
$output->writeln('<error>Group "' . $gid . '" already exists.</error>');
return 1;
} else {
$group = $this->groupManager->createGroup($gid);
if (!$group instanceof IGroup) {
$output->writeln('<error>Could not create group</error>');
return 2;
}
$output->writeln('Created group "' . $group->getGID() . '"');
$displayName = trim((string)$input->getOption('display-name'));
if ($displayName !== '') {
$group->setDisplayName($displayName);
}
}
return 0;
}
}
@@ -0,0 +1,96 @@
<?php
/**
* @copyright Copyright (c) 2016 Robin Appelman <robin@icewind.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class AddUser extends Base {
public function __construct(
protected IUserManager $userManager,
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:adduser')
->setDescription('add a user to a group')
->addArgument(
'group',
InputArgument::REQUIRED,
'group to add the user to'
)->addArgument(
'user',
InputArgument::REQUIRED,
'user to add to the group'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$group = $this->groupManager->get($input->getArgument('group'));
if (is_null($group)) {
$output->writeln('<error>group not found</error>');
return 1;
}
$user = $this->userManager->get($input->getArgument('user'));
if (is_null($user)) {
$output->writeln('<error>user not found</error>');
return 1;
}
$group->addUser($user);
return 0;
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'group') {
return array_map(static fn (IGroup $group) => $group->getGID(), $this->groupManager->search($context->getCurrentWord()));
}
if ($argumentName === 'user') {
$groupId = $context->getWordAtIndex($context->getWordIndex() - 1);
$group = $this->groupManager->get($groupId);
if ($group === null) {
return [];
}
$members = array_map(static fn (IUser $user) => $user->getUID(), $group->searchUsers($context->getCurrentWord()));
$users = array_map(static fn (IUser $user) => $user->getUID(), $this->userManager->search($context->getCurrentWord()));
return array_diff($users, $members);
}
return [];
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 Denis Mosolov <denismosolov@gmail.com>
*
* @author Denis Mosolov <denismosolov@gmail.com>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Delete extends Base {
public function __construct(
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:delete')
->setDescription('Remove a group')
->addArgument(
'groupid',
InputArgument::REQUIRED,
'Group name'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$gid = $input->getArgument('groupid');
if ($gid === 'admin') {
$output->writeln('<error>Group "' . $gid . '" could not be deleted.</error>');
return 1;
}
if (!$this->groupManager->groupExists($gid)) {
$output->writeln('<error>Group "' . $gid . '" does not exist.</error>');
return 1;
}
$group = $this->groupManager->get($gid);
if ($group->delete()) {
$output->writeln('Group "' . $gid . '" was removed');
} else {
$output->writeln('<error>Group "' . $gid . '" could not be deleted. Please check the logs.</error>');
return 1;
}
return 0;
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'groupid') {
return array_map(static fn (IGroup $group) => $group->getGID(), $this->groupManager->search($context->getCurrentWord()));
}
return [];
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021, hosting.de, Johannes Leuker <developers@hosting.de>
*
* @author Johannes Leuker <j.leuker@hosting.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Info extends Base {
public function __construct(
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:info')
->setDescription('Show information about a group')
->addArgument(
'groupid',
InputArgument::REQUIRED,
'Group id'
)->addOption(
'output',
null,
InputOption::VALUE_OPTIONAL,
'Output format (plain, json or json_pretty, default is plain)',
$this->defaultOutputFormat
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$gid = $input->getArgument('groupid');
$group = $this->groupManager->get($gid);
if (!$group instanceof IGroup) {
$output->writeln('<error>Group "' . $gid . '" does not exist.</error>');
return 1;
} else {
$groupOutput = [
'groupID' => $gid,
'displayName' => $group->getDisplayName(),
'backends' => $group->getBackendNames(),
];
$this->writeArrayInOutputFormat($input, $output, $groupOutput);
return 0;
}
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'groupid') {
return array_map(static fn (IGroup $group) => $group->getGID(), $this->groupManager->search($context->getCurrentWord()));
}
return [];
}
}
@@ -0,0 +1,111 @@
<?php
/**
* @copyright Copyright (c) 2016 Robin Appelman <robin@icewind.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Johannes Leuker <j.leuker@hosting.de>
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListCommand extends Base {
public function __construct(
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:list')
->setDescription('list configured groups')
->addOption(
'limit',
'l',
InputOption::VALUE_OPTIONAL,
'Number of groups to retrieve',
'500'
)->addOption(
'offset',
'o',
InputOption::VALUE_OPTIONAL,
'Offset for retrieving groups',
'0'
)->addOption(
'info',
'i',
InputOption::VALUE_NONE,
'Show additional info (backend)'
)->addOption(
'output',
null,
InputOption::VALUE_OPTIONAL,
'Output format (plain, json or json_pretty, default is plain)',
$this->defaultOutputFormat
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$groups = $this->groupManager->search('', (int)$input->getOption('limit'), (int)$input->getOption('offset'));
$this->writeArrayInOutputFormat($input, $output, $this->formatGroups($groups, (bool)$input->getOption('info')));
return 0;
}
/**
* @param IGroup $group
* @return string[]
*/
public function usersForGroup(IGroup $group) {
$users = array_keys($group->getUsers());
return array_map(function ($userId) {
return (string)$userId;
}, $users);
}
/**
* @param IGroup[] $groups
* @return array
*/
private function formatGroups(array $groups, bool $addInfo = false) {
$keys = array_map(function (IGroup $group) {
return $group->getGID();
}, $groups);
if ($addInfo) {
$values = array_map(function (IGroup $group) {
return [
'backends' => $group->getBackendNames(),
'users' => $this->usersForGroup($group),
];
}, $groups);
} else {
$values = array_map(function (IGroup $group) {
return $this->usersForGroup($group);
}, $groups);
}
return array_combine($keys, $values);
}
}
@@ -0,0 +1,93 @@
<?php
/**
* @copyright Copyright (c) 2016 Robin Appelman <robin@icewind.nl>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Group;
use OC\Core\Command\Base;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RemoveUser extends Base {
public function __construct(
protected IUserManager $userManager,
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('group:removeuser')
->setDescription('remove a user from a group')
->addArgument(
'group',
InputArgument::REQUIRED,
'group to remove the user from'
)->addArgument(
'user',
InputArgument::REQUIRED,
'user to remove from the group'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$group = $this->groupManager->get($input->getArgument('group'));
if (is_null($group)) {
$output->writeln('<error>group not found</error>');
return 1;
}
$user = $this->userManager->get($input->getArgument('user'));
if (is_null($user)) {
$output->writeln('<error>user not found</error>');
return 1;
}
$group->removeUser($user);
return 0;
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'group') {
return array_map(static fn (IGroup $group) => $group->getGID(), $this->groupManager->search($context->getCurrentWord()));
}
if ($argumentName === 'user') {
$groupId = $context->getWordAtIndex($context->getWordIndex() - 1);
$group = $this->groupManager->get($groupId);
if ($group === null) {
return [];
}
return array_map(static fn (IUser $user) => $user->getUID(), $group->searchUsers($context->getCurrentWord()));
}
return [];
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace OC\Core\Command\Info;
use OC\Files\ObjectStore\ObjectStoreStorage;
use OCA\Files_External\Config\ExternalMountPoint;
use OCA\GroupFolders\Mount\GroupMountPoint;
use OCP\Files\Folder;
use OCP\Files\IHomeStorage;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\IL10N;
use OCP\L10N\IFactory;
use OCP\Util;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class File extends Command {
private IL10N $l10n;
public function __construct(
IFactory $l10nFactory,
private FileUtils $fileUtils,
) {
$this->l10n = $l10nFactory->get("core");
parent::__construct();
}
protected function configure(): void {
$this
->setName('info:file')
->setDescription('get information for a file')
->addArgument('file', InputArgument::REQUIRED, "File id or path")
->addOption('children', 'c', InputOption::VALUE_NONE, "List children of folders");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$fileInput = $input->getArgument('file');
$showChildren = $input->getOption('children');
$node = $this->fileUtils->getNode($fileInput);
if (!$node) {
$output->writeln("<error>file $fileInput not found</error>");
return 1;
}
$output->writeln($node->getName());
$output->writeln(" fileid: " . $node->getId());
$output->writeln(" mimetype: " . $node->getMimetype());
$output->writeln(" modified: " . (string)$this->l10n->l("datetime", $node->getMTime()));
$output->writeln(" " . ($node->isEncrypted() ? "encrypted" : "not encrypted"));
$output->writeln(" size: " . Util::humanFileSize($node->getSize()));
$output->writeln(" etag: " . $node->getEtag());
if ($node instanceof Folder) {
$children = $node->getDirectoryListing();
$childSize = array_sum(array_map(function (Node $node) {
return $node->getSize();
}, $children));
if ($childSize != $node->getSize()) {
$output->writeln(" <error>warning: folder has a size of " . Util::humanFileSize($node->getSize()) ." but it's children sum up to " . Util::humanFileSize($childSize) . "</error>.");
$output->writeln(" Run <info>occ files:scan --path " . $node->getPath() . "</info> to attempt to resolve this.");
}
if ($showChildren) {
$output->writeln(" children: " . count($children) . ":");
foreach ($children as $child) {
$output->writeln(" - " . $child->getName());
}
} else {
$output->writeln(" children: " . count($children) . " (use <info>--children</info> option to list)");
}
}
$this->outputStorageDetails($node->getMountPoint(), $node, $output);
$filesPerUser = $this->fileUtils->getFilesByUser($node);
$output->writeln("");
$output->writeln("The following users have access to the file");
$output->writeln("");
foreach ($filesPerUser as $user => $files) {
$output->writeln("$user:");
foreach ($files as $userFile) {
$output->writeln(" " . $userFile->getPath() . ": " . $this->fileUtils->formatPermissions($userFile->getType(), $userFile->getPermissions()));
$mount = $userFile->getMountPoint();
$output->writeln(" " . $this->fileUtils->formatMountType($mount));
}
}
return 0;
}
/**
* @psalm-suppress UndefinedClass
* @psalm-suppress UndefinedInterfaceMethod
*/
private function outputStorageDetails(IMountPoint $mountPoint, Node $node, OutputInterface $output): void {
$storage = $mountPoint->getStorage();
if (!$storage) {
return;
}
if (!$storage->instanceOfStorage(IHomeStorage::class)) {
$output->writeln(" mounted at: " . $mountPoint->getMountPoint());
}
if ($storage->instanceOfStorage(ObjectStoreStorage::class)) {
/** @var ObjectStoreStorage $storage */
$objectStoreId = $storage->getObjectStore()->getStorageId();
$parts = explode(':', $objectStoreId);
/** @var string $bucket */
$bucket = array_pop($parts);
$output->writeln(" bucket: " . $bucket);
if ($node instanceof \OC\Files\Node\File) {
$output->writeln(" object id: " . $storage->getURN($node->getId()));
try {
$fh = $node->fopen('r');
if (!$fh) {
throw new NotFoundException();
}
$stat = fstat($fh);
fclose($fh);
if ($stat['size'] !== $node->getSize()) {
$output->writeln(" <error>warning: object had a size of " . $stat['size'] . " but cache entry has a size of " . $node->getSize() . "</error>. This should have been automatically repaired");
}
} catch (\Exception $e) {
$output->writeln(" <error>warning: object not found in bucket</error>");
}
}
} else {
if (!$storage->file_exists($node->getInternalPath())) {
$output->writeln(" <error>warning: file not found in storage</error>");
}
}
if ($mountPoint instanceof ExternalMountPoint) {
$storageConfig = $mountPoint->getStorageConfig();
$output->writeln(" external storage id: " . $storageConfig->getId());
$output->writeln(" external type: " . $storageConfig->getBackend()->getText());
} elseif ($mountPoint instanceof GroupMountPoint) {
$output->writeln(" groupfolder id: " . $mountPoint->getFolderId());
}
}
}
@@ -0,0 +1,241 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Info;
use OCA\Circles\MountManager\CircleMount;
use OCA\Files_External\Config\ExternalMountPoint;
use OCA\Files_Sharing\SharedMount;
use OCA\GroupFolders\Mount\GroupMountPoint;
use OCP\Constants;
use OCP\Files\Config\IUserMountCache;
use OCP\Files\FileInfo;
use OCP\Files\Folder;
use OCP\Files\IHomeStorage;
use OCP\Files\IRootFolder;
use OCP\Files\Mount\IMountPoint;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\Share\IShare;
use OCP\Util;
use Symfony\Component\Console\Output\OutputInterface;
class FileUtils {
public function __construct(
private IRootFolder $rootFolder,
private IUserMountCache $userMountCache,
) {
}
/**
* @param FileInfo $file
* @return array<string, Node[]>
* @throws \OCP\Files\NotPermittedException
* @throws \OC\User\NoUserException
*/
public function getFilesByUser(FileInfo $file): array {
$id = $file->getId();
if (!$id) {
return [];
}
$mounts = $this->userMountCache->getMountsForFileId($id);
$result = [];
foreach ($mounts as $mount) {
if (isset($result[$mount->getUser()->getUID()])) {
continue;
}
$userFolder = $this->rootFolder->getUserFolder($mount->getUser()->getUID());
$result[$mount->getUser()->getUID()] = $userFolder->getById($id);
}
return $result;
}
/**
* Get file by either id of path
*
* @param string $fileInput
* @return Node|null
*/
public function getNode(string $fileInput): ?Node {
if (is_numeric($fileInput)) {
$mounts = $this->userMountCache->getMountsForFileId((int)$fileInput);
if (!$mounts) {
return null;
}
$mount = $mounts[0];
$userFolder = $this->rootFolder->getUserFolder($mount->getUser()->getUID());
$nodes = $userFolder->getById((int)$fileInput);
if (!$nodes) {
return null;
}
return $nodes[0];
} else {
try {
return $this->rootFolder->get($fileInput);
} catch (NotFoundException $e) {
return null;
}
}
}
public function formatPermissions(string $type, int $permissions): string {
if ($permissions == Constants::PERMISSION_ALL || ($type === 'file' && $permissions == (Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE))) {
return "full permissions";
}
$perms = [];
$allPerms = [Constants::PERMISSION_READ => "read", Constants::PERMISSION_UPDATE => "update", Constants::PERMISSION_CREATE => "create", Constants::PERMISSION_DELETE => "delete", Constants::PERMISSION_SHARE => "share"];
foreach ($allPerms as $perm => $name) {
if (($permissions & $perm) === $perm) {
$perms[] = $name;
}
}
return implode(", ", $perms);
}
/**
* @psalm-suppress UndefinedClass
* @psalm-suppress UndefinedInterfaceMethod
*/
public function formatMountType(IMountPoint $mountPoint): string {
$storage = $mountPoint->getStorage();
if ($storage && $storage->instanceOfStorage(IHomeStorage::class)) {
return "home storage";
} elseif ($mountPoint instanceof SharedMount) {
$share = $mountPoint->getShare();
$shares = $mountPoint->getGroupedShares();
$sharedBy = array_map(function (IShare $share) {
$shareType = $this->formatShareType($share);
if ($shareType) {
return $share->getSharedBy() . " (via " . $shareType . " " . $share->getSharedWith() . ")";
} else {
return $share->getSharedBy();
}
}, $shares);
$description = "shared by " . implode(', ', $sharedBy);
if ($share->getSharedBy() !== $share->getShareOwner()) {
$description .= " owned by " . $share->getShareOwner();
}
return $description;
} elseif ($mountPoint instanceof GroupMountPoint) {
return "groupfolder " . $mountPoint->getFolderId();
} elseif ($mountPoint instanceof ExternalMountPoint) {
return "external storage " . $mountPoint->getStorageConfig()->getId();
} elseif ($mountPoint instanceof CircleMount) {
return "circle";
}
return get_class($mountPoint);
}
public function formatShareType(IShare $share): ?string {
switch ($share->getShareType()) {
case IShare::TYPE_GROUP:
return "group";
case IShare::TYPE_CIRCLE:
return "circle";
case IShare::TYPE_DECK:
return "deck";
case IShare::TYPE_ROOM:
return "room";
case IShare::TYPE_USER:
return null;
default:
return "Unknown (" . $share->getShareType() . ")";
}
}
/**
* Print out the largest count($sizeLimits) files in the directory tree
*
* @param OutputInterface $output
* @param Folder $node
* @param string $prefix
* @param array $sizeLimits largest items that are still in the queue to be printed, ordered ascending
* @return int how many items we've printed
*/
public function outputLargeFilesTree(
OutputInterface $output,
Folder $node,
string $prefix,
array &$sizeLimits,
bool $all,
): int {
/**
* Algorithm to print the N largest items in a folder without requiring to query or sort the entire three
*
* This is done by keeping a list ($sizeLimits) of size N that contain the largest items outside of this
* folders that are could be printed if there aren't enough items in this folder that are larger.
*
* We loop over the items in this folder by size descending until the size of the item falls before the smallest
* size in $sizeLimits (at that point there are enough items outside this folder to complete the N items).
*
* When encountering a folder, we create an updated $sizeLimits with the largest items in the current folder still
* remaining which we pass into the recursion. (We don't update the current $sizeLimits because that should only
* hold items *outside* of the current folder.)
*
* For every item printed we remove the first item of $sizeLimits are there is no longer room in the output to print
* items that small.
*/
$count = 0;
$children = $node->getDirectoryListing();
usort($children, function (Node $a, Node $b) {
return $b->getSize() <=> $a->getSize();
});
foreach ($children as $i => $child) {
if (!$all) {
if (count($sizeLimits) === 0 || $child->getSize() < $sizeLimits[0]) {
return $count;
}
array_shift($sizeLimits);
}
$count += 1;
/** @var Node $child */
$output->writeln("$prefix- " . $child->getName() . ": <info>" . Util::humanFileSize($child->getSize()) . "</info>");
if ($child instanceof Folder) {
$recurseSizeLimits = $sizeLimits;
if (!$all) {
for ($j = 0; $j < count($recurseSizeLimits); $j++) {
if (isset($children[$i + $j + 1])) {
$nextChildSize = $children[$i + $j + 1]->getSize();
if ($nextChildSize > $recurseSizeLimits[0]) {
array_shift($recurseSizeLimits);
$recurseSizeLimits[] = $nextChildSize;
}
}
}
sort($recurseSizeLimits);
}
$recurseCount = $this->outputLargeFilesTree($output, $child, $prefix . " ", $recurseSizeLimits, $all);
$sizeLimits = array_slice($sizeLimits, $recurseCount);
$count += $recurseCount;
}
}
return $count;
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Info;
use OCP\Files\Folder;
use OCP\Util;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Space extends Command {
public function __construct(
private FileUtils $fileUtils,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('info:file:space')
->setDescription('Summarize space usage of specified folder')
->addArgument('file', InputArgument::REQUIRED, "File id or path")
->addOption('count', 'c', InputOption::VALUE_REQUIRED, "Number of items to display", 25)
->addOption('all', 'a', InputOption::VALUE_NONE, "Display all items");
}
public function execute(InputInterface $input, OutputInterface $output): int {
$fileInput = $input->getArgument('file');
$count = (int)$input->getOption('count');
$all = $input->getOption('all');
$node = $this->fileUtils->getNode($fileInput);
if (!$node) {
$output->writeln("<error>file $fileInput not found</error>");
return 1;
}
$output->writeln($node->getName() . ": <info>" . Util::humanFileSize($node->getSize()) . "</info>");
if ($node instanceof Folder) {
$limits = $all ? [] : array_fill(0, $count - 1, 0);
$this->fileUtils->outputLargeFilesTree($output, $node, '', $limits, $all);
}
return 0;
}
}
@@ -0,0 +1,76 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Carla Schroder <carla@owncloud.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Integrity;
use OC\Core\Command\Base;
use OC\IntegrityCheck\Checker;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class CheckApp
*
* @package OC\Core\Command\Integrity
*/
class CheckApp extends Base {
public function __construct(
private Checker $checker,
) {
parent::__construct();
}
/**
* {@inheritdoc }
*/
protected function configure() {
parent::configure();
$this
->setName('integrity:check-app')
->setDescription('Check integrity of an app using a signature.')
->addArgument('appid', InputArgument::REQUIRED, 'Application to check')
->addOption('path', null, InputOption::VALUE_OPTIONAL, 'Path to application. If none is given it will be guessed.');
}
/**
* {@inheritdoc }
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$appid = $input->getArgument('appid');
$path = (string)$input->getOption('path');
$result = $this->checker->verifyAppSignature($appid, $path, true);
$this->writeArrayInOutputFormat($input, $output, $result);
if (count($result) > 0) {
$output->writeln('<error>' . count($result) . ' errors found</error>', OutputInterface::VERBOSITY_VERBOSE);
return 1;
}
$output->writeln('<info>No errors found</info>', OutputInterface::VERBOSITY_VERBOSE);
return 0;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Carla Schroder <carla@owncloud.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Integrity;
use OC\Core\Command\Base;
use OC\IntegrityCheck\Checker;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class CheckCore
*
* @package OC\Core\Command\Integrity
*/
class CheckCore extends Base {
public function __construct(
private Checker $checker,
) {
parent::__construct();
}
/**
* {@inheritdoc }
*/
protected function configure() {
parent::configure();
$this
->setName('integrity:check-core')
->setDescription('Check integrity of core code using a signature.');
}
/**
* {@inheritdoc }
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
if (!$this->checker->isCodeCheckEnforced()) {
$output->writeln('<comment>integrity:check-core can not be used on git checkouts</comment>');
return 2;
}
$result = $this->checker->verifyCoreSignature();
$this->writeArrayInOutputFormat($input, $output, $result);
if (count($result) > 0) {
$output->writeln('<error>' . count($result) . ' errors found</error>', OutputInterface::VERBOSITY_VERBOSE);
return 1;
}
$output->writeln('<info>No errors found</info>', OutputInterface::VERBOSITY_VERBOSE);
return 0;
}
}
@@ -0,0 +1,102 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Integrity;
use OC\IntegrityCheck\Checker;
use OC\IntegrityCheck\Helpers\FileAccessHelper;
use OCP\IURLGenerator;
use phpseclib\Crypt\RSA;
use phpseclib\File\X509;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class SignApp
*
* @package OC\Core\Command\Integrity
*/
class SignApp extends Command {
public function __construct(
private Checker $checker,
private FileAccessHelper $fileAccessHelper,
private IURLGenerator $urlGenerator,
) {
parent::__construct(null);
}
protected function configure() {
$this
->setName('integrity:sign-app')
->setDescription('Signs an app using a private key.')
->addOption('path', null, InputOption::VALUE_REQUIRED, 'Application to sign')
->addOption('privateKey', null, InputOption::VALUE_REQUIRED, 'Path to private key to use for signing')
->addOption('certificate', null, InputOption::VALUE_REQUIRED, 'Path to certificate to use for signing');
}
/**
* {@inheritdoc }
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$path = $input->getOption('path');
$privateKeyPath = $input->getOption('privateKey');
$keyBundlePath = $input->getOption('certificate');
if (is_null($path) || is_null($privateKeyPath) || is_null($keyBundlePath)) {
$documentationUrl = $this->urlGenerator->linkToDocs('developer-code-integrity');
$output->writeln('This command requires the --path, --privateKey and --certificate.');
$output->writeln('Example: ./occ integrity:sign-app --path="/Users/lukasreschke/Programming/myapp/" --privateKey="/Users/lukasreschke/private/myapp.key" --certificate="/Users/lukasreschke/public/mycert.crt"');
$output->writeln('For more information please consult the documentation: '. $documentationUrl);
return 1;
}
$privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath);
$keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath);
if ($privateKey === false) {
$output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath));
return 1;
}
if ($keyBundle === false) {
$output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath));
return 1;
}
$rsa = new RSA();
$rsa->loadKey($privateKey);
$x509 = new X509();
$x509->loadX509($keyBundle);
$x509->setPrivateKey($rsa);
try {
$this->checker->writeAppSignature($path, $x509, $rsa);
$output->writeln('Successfully signed "'.$path.'"');
} catch (\Exception $e) {
$output->writeln('Error: ' . $e->getMessage());
return 1;
}
return 0;
}
}
@@ -0,0 +1,98 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Victor Dubiniuk <dubiniuk@owncloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Integrity;
use OC\IntegrityCheck\Checker;
use OC\IntegrityCheck\Helpers\FileAccessHelper;
use phpseclib\Crypt\RSA;
use phpseclib\File\X509;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class SignCore
*
* @package OC\Core\Command\Integrity
*/
class SignCore extends Command {
public function __construct(
private Checker $checker,
private FileAccessHelper $fileAccessHelper,
) {
parent::__construct(null);
}
protected function configure() {
$this
->setName('integrity:sign-core')
->setDescription('Sign core using a private key.')
->addOption('privateKey', null, InputOption::VALUE_REQUIRED, 'Path to private key to use for signing')
->addOption('certificate', null, InputOption::VALUE_REQUIRED, 'Path to certificate to use for signing')
->addOption('path', null, InputOption::VALUE_REQUIRED, 'Path of core to sign');
}
/**
* {@inheritdoc }
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
$privateKeyPath = $input->getOption('privateKey');
$keyBundlePath = $input->getOption('certificate');
$path = $input->getOption('path');
if (is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) {
$output->writeln('--privateKey, --certificate and --path are required.');
return 1;
}
$privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath);
$keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath);
if ($privateKey === false) {
$output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath));
return 1;
}
if ($keyBundle === false) {
$output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath));
return 1;
}
$rsa = new RSA();
$rsa->loadKey($privateKey);
$x509 = new X509();
$x509->loadX509($keyBundle);
$x509->setPrivateKey($rsa);
try {
$this->checker->writeCoreSignature($x509, $rsa, $path);
$output->writeln('Successfully signed "core"');
} catch (\Exception $e) {
$output->writeln('Error: ' . $e->getMessage());
return 1;
}
return 0;
}
}
@@ -0,0 +1,29 @@
<?php
/**
* @copyright Copyright (c) 2017, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
/**
* Exception for when the user hit ctrl-c
*/
class InterruptedException extends \Exception {
}
+169
View File
@@ -0,0 +1,169 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\L10n;
use DirectoryIterator;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use UnexpectedValueException;
class CreateJs extends Command implements CompletionAwareInterface {
protected function configure() {
$this
->setName('l10n:createjs')
->setDescription('Create javascript translation files for a given app')
->addArgument(
'app',
InputOption::VALUE_REQUIRED,
'name of the app'
)
->addArgument(
'lang',
InputOption::VALUE_OPTIONAL,
'name of the language'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$app = $input->getArgument('app');
$lang = $input->getArgument('lang');
$path = \OC_App::getAppPath($app);
if ($path === false) {
$output->writeln("The app <$app> is unknown.");
return 1;
}
$languages = $lang;
if (empty($lang)) {
$languages = $this->getAllLanguages($path);
}
foreach ($languages as $lang) {
$this->writeFiles($app, $path, $lang, $output);
}
return 0;
}
private function getAllLanguages($path) {
$result = [];
foreach (new DirectoryIterator("$path/l10n") as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
if ($fileInfo->isDir()) {
continue;
}
if ($fileInfo->getExtension() !== 'php') {
continue;
}
$result[] = substr($fileInfo->getBasename(), 0, -4);
}
return $result;
}
private function writeFiles($app, $path, $lang, OutputInterface $output) {
[$translations, $plurals] = $this->loadTranslations($path, $lang);
$this->writeJsFile($app, $path, $lang, $output, $translations, $plurals);
$this->writeJsonFile($path, $lang, $output, $translations, $plurals);
}
private function writeJsFile($app, $path, $lang, OutputInterface $output, $translations, $plurals) {
$jsFile = "$path/l10n/$lang.js";
if (file_exists($jsFile)) {
$output->writeln("File already exists: $jsFile");
return;
}
$content = "OC.L10N.register(\n \"$app\",\n {\n ";
$jsTrans = [];
foreach ($translations as $id => $val) {
if (is_array($val)) {
$val = '[ ' . implode(',', $val) . ']';
}
$jsTrans[] = "\"$id\" : \"$val\"";
}
$content .= implode(",\n ", $jsTrans);
$content .= "\n},\n\"$plurals\");\n";
file_put_contents($jsFile, $content);
$output->writeln("Javascript translation file generated: $jsFile");
}
private function writeJsonFile($path, $lang, OutputInterface $output, $translations, $plurals) {
$jsFile = "$path/l10n/$lang.json";
if (file_exists($jsFile)) {
$output->writeln("File already exists: $jsFile");
return;
}
$content = ['translations' => $translations, 'pluralForm' => $plurals];
file_put_contents($jsFile, json_encode($content));
$output->writeln("Json translation file generated: $jsFile");
}
private function loadTranslations($path, $lang) {
$phpFile = "$path/l10n/$lang.php";
$TRANSLATIONS = [];
$PLURAL_FORMS = '';
if (!file_exists($phpFile)) {
throw new UnexpectedValueException("PHP translation file <$phpFile> does not exist.");
}
require $phpFile;
return [$TRANSLATIONS, $PLURAL_FORMS];
}
/**
* Return possible values for the named option
*
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* Return possible values for the named argument
*
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'app') {
return \OC_App::getAllApps();
} elseif ($argumentName === 'lang') {
$appName = $context->getWordAtIndex($context->getWordIndex() - 1);
return $this->getAllLanguages(\OC_App::getAppPath($appName));
}
return [];
}
}
+155
View File
@@ -0,0 +1,155 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Pulzer <t.pulzer@kniel.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Log;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\Completion;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\ShellPathCompletion;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class File extends Command implements Completion\CompletionAwareInterface {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('log:file')
->setDescription('manipulate logging backend')
->addOption(
'enable',
null,
InputOption::VALUE_NONE,
'enable this logging backend'
)
->addOption(
'file',
null,
InputOption::VALUE_REQUIRED,
'set the log file path'
)
->addOption(
'rotate-size',
null,
InputOption::VALUE_REQUIRED,
'set the file size for log rotation, 0 = disabled'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$toBeSet = [];
if ($input->getOption('enable')) {
$toBeSet['log_type'] = 'file';
}
if ($file = $input->getOption('file')) {
$toBeSet['logfile'] = $file;
}
if (($rotateSize = $input->getOption('rotate-size')) !== null) {
$rotateSize = \OCP\Util::computerFileSize($rotateSize);
$this->validateRotateSize($rotateSize);
$toBeSet['log_rotate_size'] = $rotateSize;
}
// set config
foreach ($toBeSet as $option => $value) {
$this->config->setSystemValue($option, $value);
}
// display config
// TODO: Drop backwards compatibility for config in the future
$logType = $this->config->getSystemValue('log_type', 'file');
if ($logType === 'file' || $logType === 'owncloud') {
$enabledText = 'enabled';
} else {
$enabledText = 'disabled';
}
$output->writeln('Log backend file: '.$enabledText);
$dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data');
$defaultLogFile = rtrim($dataDir, '/').'/nextcloud.log';
$output->writeln('Log file: '.$this->config->getSystemValue('logfile', $defaultLogFile));
$rotateSize = $this->config->getSystemValue('log_rotate_size', 100 * 1024 * 1024);
if ($rotateSize) {
$rotateString = \OCP\Util::humanFileSize($rotateSize);
} else {
$rotateString = 'disabled';
}
$output->writeln('Rotate at: '.$rotateString);
return 0;
}
/**
* @throws \InvalidArgumentException
*/
protected function validateRotateSize(false|int|float $rotateSize): void {
if ($rotateSize === false) {
throw new \InvalidArgumentException('Error parsing log rotation file size');
}
if ($rotateSize < 0) {
throw new \InvalidArgumentException('Log rotation file size must be non-negative');
}
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'file') {
$helper = new ShellPathCompletion(
$this->getName(),
'file',
Completion::TYPE_OPTION
);
return $helper->run();
} elseif ($optionName === 'rotate-size') {
return [0];
}
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
return [];
}
}
+204
View File
@@ -0,0 +1,204 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Johannes Ernst <jernst@indiecomputing.com>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Tim Terhorst <mynamewastaken+gitlab@gmail.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Log;
use OCP\IConfig;
use Stecman\Component\Symfony\Console\BashCompletion\Completion\CompletionAwareInterface;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Manage extends Command implements CompletionAwareInterface {
public const DEFAULT_BACKEND = 'file';
public const DEFAULT_LOG_LEVEL = 2;
public const DEFAULT_TIMEZONE = 'UTC';
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('log:manage')
->setDescription('manage logging configuration')
->addOption(
'backend',
null,
InputOption::VALUE_REQUIRED,
'set the logging backend [file, syslog, errorlog, systemd]'
)
->addOption(
'level',
null,
InputOption::VALUE_REQUIRED,
'set the log level [debug, info, warning, error, fatal]'
)
->addOption(
'timezone',
null,
InputOption::VALUE_REQUIRED,
'set the logging timezone'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
// collate config setting to the end, to avoid partial configuration
$toBeSet = [];
if ($backend = $input->getOption('backend')) {
$this->validateBackend($backend);
$toBeSet['log_type'] = $backend;
}
$level = $input->getOption('level');
if ($level !== null) {
if (is_numeric($level)) {
$levelNum = $level;
// sanity check
$this->convertLevelNumber($levelNum);
} else {
$levelNum = $this->convertLevelString($level);
}
$toBeSet['loglevel'] = $levelNum;
}
if ($timezone = $input->getOption('timezone')) {
$this->validateTimezone($timezone);
$toBeSet['logtimezone'] = $timezone;
}
// set config
foreach ($toBeSet as $option => $value) {
$this->config->setSystemValue($option, $value);
}
// display configuration
$backend = $this->config->getSystemValue('log_type', self::DEFAULT_BACKEND);
$output->writeln('Enabled logging backend: '.$backend);
$levelNum = $this->config->getSystemValue('loglevel', self::DEFAULT_LOG_LEVEL);
$level = $this->convertLevelNumber($levelNum);
$output->writeln('Log level: '.$level.' ('.$levelNum.')');
$timezone = $this->config->getSystemValue('logtimezone', self::DEFAULT_TIMEZONE);
$output->writeln('Log timezone: '.$timezone);
return 0;
}
/**
* @param string $backend
* @throws \InvalidArgumentException
*/
protected function validateBackend($backend) {
if (!class_exists('OC\\Log\\'.ucfirst($backend))) {
throw new \InvalidArgumentException('Invalid backend');
}
}
/**
* @param string $timezone
* @throws \Exception
*/
protected function validateTimezone($timezone) {
new \DateTimeZone($timezone);
}
/**
* @param string $level
* @return int
* @throws \InvalidArgumentException
*/
protected function convertLevelString($level) {
$level = strtolower($level);
switch ($level) {
case 'debug':
return 0;
case 'info':
return 1;
case 'warning':
case 'warn':
return 2;
case 'error':
case 'err':
return 3;
case 'fatal':
return 4;
}
throw new \InvalidArgumentException('Invalid log level string');
}
/**
* @param int $levelNum
* @return string
* @throws \InvalidArgumentException
*/
protected function convertLevelNumber($levelNum) {
switch ($levelNum) {
case 0:
return 'Debug';
case 1:
return 'Info';
case 2:
return 'Warning';
case 3:
return 'Error';
case 4:
return 'Fatal';
}
throw new \InvalidArgumentException('Invalid log level number');
}
/**
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
if ($optionName === 'backend') {
return ['file', 'syslog', 'errorlog', 'systemd'];
} elseif ($optionName === 'level') {
return ['debug', 'info', 'warning', 'error', 'fatal'];
} elseif ($optionName === 'timezone') {
return \DateTimeZone::listIdentifiers();
}
return [];
}
/**
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
return [];
}
}
@@ -0,0 +1,49 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DataFingerprint extends Command {
public function __construct(
protected IConfig $config,
protected ITimeFactory $timeFactory,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:data-fingerprint')
->setDescription('update the systems data-fingerprint after a backup is restored');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$this->config->setSystemValue('data-fingerprint', md5($this->timeFactory->getTime()));
return 0;
}
}
@@ -0,0 +1,236 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Hansson <daniel@techandme.se>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Pulzer <t.pulzer@kniel.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance;
use bantu\IniGetWrapper\IniGetWrapper;
use InvalidArgumentException;
use OC\Console\TimestampFormatter;
use OC\Installer;
use OC\Migration\ConsoleOutput;
use OC\Setup;
use OC\SystemConfig;
use OCP\Defaults;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Throwable;
use function get_class;
class Install extends Command {
public function __construct(
private SystemConfig $config,
private IniGetWrapper $iniGetWrapper,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:install')
->setDescription('install Nextcloud')
->addOption('database', null, InputOption::VALUE_REQUIRED, 'Supported database type', 'sqlite')
->addOption('database-name', null, InputOption::VALUE_REQUIRED, 'Name of the database')
->addOption('database-host', null, InputOption::VALUE_REQUIRED, 'Hostname of the database', 'localhost')
->addOption('database-port', null, InputOption::VALUE_REQUIRED, 'Port the database is listening on')
->addOption('database-user', null, InputOption::VALUE_REQUIRED, 'User name to connect to the database')
->addOption('database-pass', null, InputOption::VALUE_OPTIONAL, 'Password of the database user', null)
->addOption('database-table-space', null, InputOption::VALUE_OPTIONAL, 'Table space of the database (oci only)', null)
->addOption('admin-user', null, InputOption::VALUE_REQUIRED, 'User name of the admin account', 'admin')
->addOption('admin-pass', null, InputOption::VALUE_REQUIRED, 'Password of the admin account')
->addOption('admin-email', null, InputOption::VALUE_OPTIONAL, 'E-Mail of the admin account')
->addOption('data-dir', null, InputOption::VALUE_REQUIRED, 'Path to data directory', \OC::$SERVERROOT."/data");
}
protected function execute(InputInterface $input, OutputInterface $output): int {
// validate the environment
$server = \OC::$server;
$setupHelper = new Setup(
$this->config,
$this->iniGetWrapper,
$server->getL10N('lib'),
$server->query(Defaults::class),
$server->get(LoggerInterface::class),
$server->getSecureRandom(),
\OC::$server->query(Installer::class)
);
$sysInfo = $setupHelper->getSystemInfo(true);
$errors = $sysInfo['errors'];
if (count($errors) > 0) {
$this->printErrors($output, $errors);
// ignore the OS X setup warning
if (count($errors) !== 1 ||
(string)$errors[0]['error'] !== 'Mac OS X is not supported and Nextcloud will not work properly on this platform. Use it at your own risk! ') {
return 1;
}
}
// validate user input
$options = $this->validateInput($input, $output, array_keys($sysInfo['databases']));
if ($output->isVerbose()) {
// Prepend each line with a little timestamp
$timestampFormatter = new TimestampFormatter(null, $output->getFormatter());
$output->setFormatter($timestampFormatter);
$migrationOutput = new ConsoleOutput($output);
} else {
$migrationOutput = null;
}
// perform installation
$errors = $setupHelper->install($options, $migrationOutput);
if (count($errors) > 0) {
$this->printErrors($output, $errors);
return 1;
}
if ($setupHelper->shouldRemoveCanInstallFile()) {
$output->writeln('<warn>Could not remove CAN_INSTALL from the config folder. Please remove this file manually.</warn>');
}
$output->writeln("Nextcloud was successfully installed");
return 0;
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param string[] $supportedDatabases
* @return array
*/
protected function validateInput(InputInterface $input, OutputInterface $output, $supportedDatabases) {
$db = strtolower($input->getOption('database'));
if (!in_array($db, $supportedDatabases)) {
throw new InvalidArgumentException("Database <$db> is not supported. " . implode(", ", $supportedDatabases) . " are supported.");
}
$dbUser = $input->getOption('database-user');
$dbPass = $input->getOption('database-pass');
$dbName = $input->getOption('database-name');
$dbPort = $input->getOption('database-port');
if ($db === 'oci') {
// an empty hostname needs to be read from the raw parameters
$dbHost = $input->getParameterOption('--database-host', '');
} else {
$dbHost = $input->getOption('database-host');
}
if ($dbPort) {
// Append the port to the host so it is the same as in the config (there is no dbport config)
$dbHost .= ':' . $dbPort;
}
if ($input->hasParameterOption('--database-pass')) {
$dbPass = (string) $input->getOption('database-pass');
}
$adminLogin = $input->getOption('admin-user');
$adminPassword = $input->getOption('admin-pass');
$adminEmail = $input->getOption('admin-email');
$dataDir = $input->getOption('data-dir');
if ($db !== 'sqlite') {
if (is_null($dbUser)) {
throw new InvalidArgumentException("Database user not provided.");
}
if (is_null($dbName)) {
throw new InvalidArgumentException("Database name not provided.");
}
if (is_null($dbPass)) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new Question('What is the password to access the database with user <'.$dbUser.'>?');
$question->setHidden(true);
$question->setHiddenFallback(false);
$dbPass = $helper->ask($input, $output, $question);
}
}
if (is_null($adminPassword)) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new Question('What is the password you like to use for the admin account <'.$adminLogin.'>?');
$question->setHidden(true);
$question->setHiddenFallback(false);
$adminPassword = $helper->ask($input, $output, $question);
}
if ($adminEmail !== null && !filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid e-mail-address <' . $adminEmail . '> for <' . $adminLogin . '>.');
}
$options = [
'dbtype' => $db,
'dbuser' => $dbUser,
'dbpass' => $dbPass,
'dbname' => $dbName,
'dbhost' => $dbHost,
'adminlogin' => $adminLogin,
'adminpass' => $adminPassword,
'adminemail' => $adminEmail,
'directory' => $dataDir
];
if ($db === 'oci') {
$options['dbtablespace'] = $input->getParameterOption('--database-table-space', '');
}
return $options;
}
/**
* @param OutputInterface $output
* @param $errors
*/
protected function printErrors(OutputInterface $output, $errors) {
foreach ($errors as $error) {
if (is_array($error)) {
$output->writeln('<error>' . $error['error'] . '</error>');
if (isset($error['hint']) && !empty($error['hint'])) {
$output->writeln('<info> -> ' . $error['hint'] . '</info>');
}
if (isset($error['exception']) && $error['exception'] instanceof Throwable) {
$this->printThrowable($output, $error['exception']);
}
} else {
$output->writeln('<error>' . $error . '</error>');
}
}
}
private function printThrowable(OutputInterface $output, Throwable $t): void {
$output->write('<info>Trace: ' . $t->getTraceAsString() . '</info>');
$output->writeln('');
if ($t->getPrevious() !== null) {
$output->writeln('');
$output->writeln('<info>Previous: ' . get_class($t->getPrevious()) . ': ' . $t->getPrevious()->getMessage() . '</info>');
$this->printThrowable($output, $t->getPrevious());
}
}
}
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Xheni Myrtaj <xheni@protonmail.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Xheni Myrtaj <myrtajxheni@gmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Maintenance\Mimetype;
class GenerateMimetypeFileBuilder {
/**
* Generate mime type list file
*
* @param array $aliases
* @return string
*/
public function generateFile(array $aliases): string {
// Remove comments
$aliases = array_filter($aliases, static function ($key) {
return !($key === '' || $key[0] === '_');
}, ARRAY_FILTER_USE_KEY);
// Fetch all files
$dir = new \DirectoryIterator(\OC::$SERVERROOT.'/core/img/filetypes');
$files = [];
foreach ($dir as $fileInfo) {
if ($fileInfo->isFile()) {
$file = preg_replace('/.[^.]*$/', '', $fileInfo->getFilename());
$files[] = $file;
}
}
//Remove duplicates
$files = array_values(array_unique($files));
sort($files);
// Fetch all themes!
$themes = [];
$dirs = new \DirectoryIterator(\OC::$SERVERROOT.'/themes/');
foreach ($dirs as $dir) {
//Valid theme dir
if ($dir->isFile() || $dir->isDot()) {
continue;
}
$theme = $dir->getFilename();
$themeDir = $dir->getPath() . '/' . $theme . '/core/img/filetypes/';
// Check if this theme has its own filetype icons
if (!file_exists($themeDir)) {
continue;
}
$themes[$theme] = [];
// Fetch all the theme icons!
$themeIt = new \DirectoryIterator($themeDir);
foreach ($themeIt as $fileInfo) {
if ($fileInfo->isFile()) {
$file = preg_replace('/.[^.]*$/', '', $fileInfo->getFilename());
$themes[$theme][] = $file;
}
}
//Remove Duplicates
$themes[$theme] = array_values(array_unique($themes[$theme]));
sort($themes[$theme]);
}
//Generate the JS
return '/**
* This file is automatically generated
* DO NOT EDIT MANUALLY!
*
* You can update the list of MimeType Aliases in config/mimetypealiases.json
* The list of files is fetched from core/img/filetypes
* To regenerate this file run ./occ maintenance:mimetype:update-js
*/
OC.MimeTypeList={
aliases: ' . json_encode($aliases, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . ',
files: ' . json_encode($files, JSON_PRETTY_PRINT) . ',
themes: ' . json_encode($themes, JSON_PRETTY_PRINT) . '
};
';
}
}
@@ -0,0 +1,92 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance\Mimetype;
use OCP\Files\IMimeTypeDetector;
use OCP\Files\IMimeTypeLoader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class UpdateDB extends Command {
public const DEFAULT_MIMETYPE = 'application/octet-stream';
public function __construct(
protected IMimeTypeDetector $mimetypeDetector,
protected IMimeTypeLoader $mimetypeLoader,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:mimetype:update-db')
->setDescription('Update database mimetypes and update filecache')
->addOption(
'repair-filecache',
null,
InputOption::VALUE_NONE,
'Repair filecache for all mimetypes, not just new ones'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$mappings = $this->mimetypeDetector->getAllMappings();
$totalFilecacheUpdates = 0;
$totalNewMimetypes = 0;
foreach ($mappings as $ext => $mimetypes) {
if ($ext[0] === '_') {
// comment
continue;
}
$mimetype = $mimetypes[0];
$existing = $this->mimetypeLoader->exists($mimetype);
// this will add the mimetype if it didn't exist
$mimetypeId = $this->mimetypeLoader->getId($mimetype);
if (!$existing) {
$output->writeln('Added mimetype "'.$mimetype.'" to database');
$totalNewMimetypes++;
}
if (!$existing || $input->getOption('repair-filecache')) {
$touchedFilecacheRows = $this->mimetypeLoader->updateFilecache($ext, $mimetypeId);
if ($touchedFilecacheRows > 0) {
$output->writeln('Updated '.$touchedFilecacheRows.' filecache rows for mimetype "'.$mimetype.'"');
}
$totalFilecacheUpdates += $touchedFilecacheRows;
}
}
$output->writeln('Added '.$totalNewMimetypes.' new mimetypes');
$output->writeln('Updated '.$totalFilecacheUpdates.' filecache rows');
return 0;
}
}
@@ -0,0 +1,57 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Xheni Myrtaj <myrtajxheni@gmail.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance\Mimetype;
use OCP\Files\IMimeTypeDetector;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UpdateJS extends Command {
public function __construct(
protected IMimeTypeDetector $mimetypeDetector,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:mimetype:update-js')
->setDescription('Update mimetypelist.js');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
// Fetch all the aliases
$aliases = $this->mimetypeDetector->getAllAliases();
// Output the JS
$generatedMimetypeFile = new GenerateMimetypeFileBuilder();
file_put_contents(\OC::$SERVERROOT.'/core/js/mimetypelist.js', $generatedMimetypeFile->generateFile($aliases));
$output->writeln('<info>mimetypelist.js is updated');
return 0;
}
}
@@ -0,0 +1,85 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Michael Weimann <mail@michael-weimann.eu>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author scolebrook <scolebrook@mac.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Mode extends Command {
public function __construct(
protected IConfig $config,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:mode')
->setDescription('set maintenance mode')
->addOption(
'on',
null,
InputOption::VALUE_NONE,
'enable maintenance mode'
)
->addOption(
'off',
null,
InputOption::VALUE_NONE,
'disable maintenance mode'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$maintenanceMode = $this->config->getSystemValueBool('maintenance');
if ($input->getOption('on')) {
if ($maintenanceMode === false) {
$this->config->setSystemValue('maintenance', true);
$output->writeln('Maintenance mode enabled');
} else {
$output->writeln('Maintenance mode already enabled');
}
} elseif ($input->getOption('off')) {
if ($maintenanceMode === true) {
$this->config->setSystemValue('maintenance', false);
$output->writeln('Maintenance mode disabled');
} else {
$output->writeln('Maintenance mode already disabled');
}
} else {
if ($maintenanceMode) {
$output->writeln('Maintenance mode is currently enabled');
} else {
$output->writeln('Maintenance mode is currently disabled');
}
}
return 0;
}
}
@@ -0,0 +1,145 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Temtaime <temtaime@gmail.com>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance;
use Exception;
use OC\Repair\Events\RepairAdvanceEvent;
use OC\Repair\Events\RepairErrorEvent;
use OC\Repair\Events\RepairFinishEvent;
use OC\Repair\Events\RepairInfoEvent;
use OC\Repair\Events\RepairStartEvent;
use OC\Repair\Events\RepairStepEvent;
use OC\Repair\Events\RepairWarningEvent;
use OCP\App\IAppManager;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Repair extends Command {
private ProgressBar $progress;
private OutputInterface $output;
protected bool $errored = false;
public function __construct(
protected \OC\Repair $repair,
protected IConfig $config,
private IEventDispatcher $dispatcher,
private IAppManager $appManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:repair')
->setDescription('repair this installation')
->addOption(
'include-expensive',
null,
InputOption::VALUE_NONE,
'Use this option when you want to include resource and load expensive tasks');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$repairSteps = $this->repair::getRepairSteps();
if ($input->getOption('include-expensive')) {
$repairSteps = array_merge($repairSteps, $this->repair::getExpensiveRepairSteps());
}
foreach ($repairSteps as $step) {
$this->repair->addStep($step);
}
$apps = $this->appManager->getInstalledApps();
foreach ($apps as $app) {
if (!$this->appManager->isEnabledForUser($app)) {
continue;
}
$info = $this->appManager->getAppInfo($app);
if (!is_array($info)) {
continue;
}
\OC_App::loadApp($app);
$steps = $info['repair-steps']['post-migration'];
foreach ($steps as $step) {
try {
$this->repair->addStep($step);
} catch (Exception $ex) {
$output->writeln("<error>Failed to load repair step for $app: {$ex->getMessage()}</error>");
}
}
}
$maintenanceMode = $this->config->getSystemValueBool('maintenance');
$this->config->setSystemValue('maintenance', true);
$this->progress = new ProgressBar($output);
$this->output = $output;
$this->dispatcher->addListener(RepairStartEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairAdvanceEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairFinishEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairStepEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairInfoEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairWarningEvent::class, [$this, 'handleRepairFeedBack']);
$this->dispatcher->addListener(RepairErrorEvent::class, [$this, 'handleRepairFeedBack']);
$this->repair->run();
$this->config->setSystemValue('maintenance', $maintenanceMode);
return $this->errored ? 1 : 0;
}
public function handleRepairFeedBack(Event $event): void {
if ($event instanceof RepairStartEvent) {
$this->progress->start($event->getMaxStep());
} elseif ($event instanceof RepairAdvanceEvent) {
$this->progress->advance($event->getIncrement());
} elseif ($event instanceof RepairFinishEvent) {
$this->progress->finish();
$this->output->writeln('');
} elseif ($event instanceof RepairStepEvent) {
$this->output->writeln('<info> - ' . $event->getStepName() . '</info>');
} elseif ($event instanceof RepairInfoEvent) {
$this->output->writeln('<info> - ' . $event->getMessage() . '</info>');
} elseif ($event instanceof RepairWarningEvent) {
$this->output->writeln('<comment> - WARNING: ' . $event->getMessage() . '</comment>');
} elseif ($event instanceof RepairErrorEvent) {
$this->output->writeln('<error> - ERROR: ' . $event->getMessage() . '</error>');
$this->errored = true;
}
}
}
@@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020 Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Maintenance;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\IUser;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class RepairShareOwnership extends Command {
public function __construct(
private IDBConnection $dbConnection,
private IUserManager $userManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('maintenance:repair-share-owner')
->setDescription('repair invalid share-owner entries in the database')
->addOption('no-confirm', 'y', InputOption::VALUE_NONE, "Don't ask for confirmation before repairing the shares")
->addArgument('user', InputArgument::OPTIONAL, "User to fix incoming shares for, if omitted all users will be fixed");
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$noConfirm = $input->getOption('no-confirm');
$userId = $input->getArgument('user');
if ($userId) {
$user = $this->userManager->get($userId);
if (!$user) {
$output->writeln("<error>user $userId not found</error>");
return 1;
}
$shares = $this->getWrongShareOwnershipForUser($user);
} else {
$shares = $this->getWrongShareOwnership();
}
if ($shares) {
$output->writeln("");
$output->writeln("Found " . count($shares) . " shares with invalid share owner");
foreach ($shares as $share) {
/** @var array{shareId: int, fileTarget: string, initiator: string, receiver: string, owner: string, mountOwner: string} $share */
$output->writeln(" - share {$share['shareId']} from \"{$share['initiator']}\" to \"{$share['receiver']}\" at \"{$share['fileTarget']}\", owned by \"{$share['owner']}\", that should be owned by \"{$share['mountOwner']}\"");
}
$output->writeln("");
if (!$noConfirm) {
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('Repair these shares? [y/N]', false);
if (!$helper->ask($input, $output, $question)) {
return 0;
}
}
$output->writeln("Repairing " . count($shares) . " shares");
$this->repairShares($shares);
} else {
$output->writeln("Found no shares with invalid share owner");
}
return 0;
}
/**
* @return array{shareId: int, fileTarget: string, initiator: string, receiver: string, owner: string, mountOwner: string}[]
* @throws \OCP\DB\Exception
*/
protected function getWrongShareOwnership(): array {
$qb = $this->dbConnection->getQueryBuilder();
$brokenShares = $qb
->select('s.id', 'm.user_id', 's.uid_owner', 's.uid_initiator', 's.share_with', 's.file_target')
->from('share', 's')
->join('s', 'filecache', 'f', $qb->expr()->eq('s.item_source', $qb->expr()->castColumn('f.fileid', IQueryBuilder::PARAM_STR)))
->join('s', 'mounts', 'm', $qb->expr()->eq('f.storage', 'm.storage_id'))
->where($qb->expr()->neq('m.user_id', 's.uid_owner'))
->andWhere($qb->expr()->eq($qb->func()->concat($qb->expr()->literal('/'), 'm.user_id', $qb->expr()->literal('/')), 'm.mount_point'))
->executeQuery()
->fetchAll();
$found = [];
foreach ($brokenShares as $share) {
$found[] = [
'shareId' => (int) $share['id'],
'fileTarget' => $share['file_target'],
'initiator' => $share['uid_initiator'],
'receiver' => $share['share_with'],
'owner' => $share['uid_owner'],
'mountOwner' => $share['user_id'],
];
}
return $found;
}
/**
* @param IUser $user
* @return array{shareId: int, fileTarget: string, initiator: string, receiver: string, owner: string, mountOwner: string}[]
* @throws \OCP\DB\Exception
*/
protected function getWrongShareOwnershipForUser(IUser $user): array {
$qb = $this->dbConnection->getQueryBuilder();
$brokenShares = $qb
->select('s.id', 'm.user_id', 's.uid_owner', 's.uid_initiator', 's.share_with', 's.file_target')
->from('share', 's')
->join('s', 'filecache', 'f', $qb->expr()->eq('s.item_source', $qb->expr()->castColumn('f.fileid', IQueryBuilder::PARAM_STR)))
->join('s', 'mounts', 'm', $qb->expr()->eq('f.storage', 'm.storage_id'))
->where($qb->expr()->neq('m.user_id', 's.uid_owner'))
->andWhere($qb->expr()->eq($qb->func()->concat($qb->expr()->literal('/'), 'm.user_id', $qb->expr()->literal('/')), 'm.mount_point'))
->andWhere($qb->expr()->eq('s.share_with', $qb->createNamedParameter($user->getUID())))
->executeQuery()
->fetchAll();
$found = [];
foreach ($brokenShares as $share) {
$found[] = [
'shareId' => (int) $share['id'],
'fileTarget' => $share['file_target'],
'initiator' => $share['uid_initiator'],
'receiver' => $share['share_with'],
'owner' => $share['uid_owner'],
'mountOwner' => $share['user_id'],
];
}
return $found;
}
/**
* @param array{shareId: int, fileTarget: string, initiator: string, receiver: string, owner: string, mountOwner: string}[] $shares
* @return void
*/
protected function repairShares(array $shares) {
$this->dbConnection->beginTransaction();
$update = $this->dbConnection->getQueryBuilder();
$update->update('share')
->set('uid_owner', $update->createParameter('share_owner'))
->set('uid_initiator', $update->createParameter('share_initiator'))
->where($update->expr()->eq('id', $update->createParameter('share_id')));
foreach ($shares as $share) {
/** @var array{shareId: int, fileTarget: string, initiator: string, receiver: string, owner: string, mountOwner: string} $share */
$update->setParameter('share_id', $share['shareId'], IQueryBuilder::PARAM_INT);
$update->setParameter('share_owner', $share['mountOwner']);
// if the broken owner is also the initiator it's safe to update them both, otherwise we don't touch the initiator
if ($share['initiator'] === $share['owner']) {
$update->setParameter('share_initiator', $share['mountOwner']);
} else {
$update->setParameter('share_initiator', $share['initiator']);
}
$update->executeStatement();
}
$this->dbConnection->commit();
}
}
@@ -0,0 +1,46 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Maintenance;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UpdateHtaccess extends Command {
protected function configure() {
$this
->setName('maintenance:update:htaccess')
->setDescription('Updates the .htaccess file');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if (\OC\Setup::updateHtaccess()) {
$output->writeln('.htaccess has been updated');
return 0;
} else {
$output->writeln('<error>Error updating .htaccess file, not enough permissions, not enough free space or "overwrite.cli.url" set to an invalid URL?</error>');
return 1;
}
}
}
@@ -0,0 +1,59 @@
<?php
/**
* @copyright Copyright (c) 2017 Julius Härtl <jus@bitgrid.net>
*
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Maintenance;
use OC\Core\Command\Maintenance\Mimetype\UpdateJS;
use OCP\Files\IMimeTypeDetector;
use OCP\ICacheFactory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UpdateTheme extends UpdateJS {
public function __construct(
IMimeTypeDetector $mimetypeDetector,
protected ICacheFactory $cacheFactory,
) {
parent::__construct($mimetypeDetector);
}
protected function configure() {
$this
->setName('maintenance:theme:update')
->setDescription('Apply custom theme changes');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
// run mimetypelist.js update since themes might change mimetype icons
parent::execute($input, $output);
// cleanup image cache
$c = $this->cacheFactory->createDistributed('imagePath');
$c->clear('');
$output->writeln('<info>Image cache cleared</info>');
return 0;
}
}
@@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Preview;
use OCP\Files\Config\IUserMountCache;
use OCP\Files\File;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
use OCP\IPreview;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Generate extends Command {
public function __construct(
private IRootFolder $rootFolder,
private IUserMountCache $userMountCache,
private IPreview $previewManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('preview:generate')
->setDescription('generate a preview for a file')
->addArgument("file", InputArgument::REQUIRED, "path or fileid of the file to generate the preview for")
->addOption("size", "s", InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, "size to generate the preview for in pixels, defaults to 64x64", ["64x64"])
->addOption("crop", "c", InputOption::VALUE_NONE, "crop the previews instead of maintaining aspect ratio")
->addOption("mode", "m", InputOption::VALUE_REQUIRED, "mode for generating uncropped previews, 'cover' or 'fill'", IPreview::MODE_FILL);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$fileInput = $input->getArgument("file");
$sizes = $input->getOption("size");
$sizes = array_map(function (string $size) use ($output, &$error) {
if (str_contains($size, 'x')) {
$sizeParts = explode('x', $size, 2);
} else {
$sizeParts = [$size, $size];
}
if (!is_numeric($sizeParts[0]) || !is_numeric($sizeParts[1])) {
$output->writeln("<error>Invalid size $size</error>");
return null;
}
return array_map("intval", $sizeParts);
}, $sizes);
if (in_array(null, $sizes)) {
return 1;
}
$mode = $input->getOption("mode");
if ($mode !== IPreview::MODE_FILL && $mode !== IPreview::MODE_COVER) {
$output->writeln("<error>Invalid mode $mode</error>");
return 1;
}
$crop = $input->getOption("crop");
$file = $this->getFile($fileInput);
if (!$file) {
$output->writeln("<error>File $fileInput not found</error>");
return 1;
}
if (!$file instanceof File) {
$output->writeln("<error>Can't generate previews for folders</error>");
return 1;
}
if (!$this->previewManager->isAvailable($file)) {
$output->writeln("<error>No preview generator available for file of type" . $file->getMimetype() . "</error>");
return 1;
}
$specifications = array_map(function (array $sizes) use ($crop, $mode) {
return [
'width' => $sizes[0],
'height' => $sizes[1],
'crop' => $crop,
'mode' => $mode,
];
}, $sizes);
$this->previewManager->generatePreviews($file, $specifications);
if (count($specifications) > 1) {
$output->writeln("generated <info>" . count($specifications) . "</info> previews");
} else {
$output->writeln("preview generated");
}
return 0;
}
private function getFile(string $fileInput): ?Node {
if (is_numeric($fileInput)) {
$mounts = $this->userMountCache->getMountsForFileId((int)$fileInput);
if (!$mounts) {
return null;
}
$mount = $mounts[0];
$userFolder = $this->rootFolder->getUserFolder($mount->getUser()->getUID());
$nodes = $userFolder->getById((int)$fileInput);
if (!$nodes) {
return null;
}
return $nodes[0];
} else {
try {
return $this->rootFolder->get($fileInput);
} catch (NotFoundException $e) {
return null;
}
}
}
}
@@ -0,0 +1,309 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Morris Jobke <hey@morrisjobke.de>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Preview;
use bantu\IniGetWrapper\IniGetWrapper;
use OC\Preview\Storage\Root;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\IConfig;
use OCP\Lock\ILockingProvider;
use OCP\Lock\LockedException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use function pcntl_signal;
class Repair extends Command {
private bool $stopSignalReceived = false;
private int $memoryLimit;
private int $memoryTreshold;
public function __construct(
protected IConfig $config,
private IRootFolder $rootFolder,
private LoggerInterface $logger,
IniGetWrapper $phpIni,
private ILockingProvider $lockingProvider,
) {
$this->memoryLimit = (int)$phpIni->getBytes('memory_limit');
$this->memoryTreshold = $this->memoryLimit - 25 * 1024 * 1024;
parent::__construct();
}
protected function configure() {
$this
->setName('preview:repair')
->setDescription('distributes the existing previews into subfolders')
->addOption('batch', 'b', InputOption::VALUE_NONE, 'Batch mode - will not ask to start the migration and start it right away.')
->addOption('dry', 'd', InputOption::VALUE_NONE, 'Dry mode - will not create, move or delete any files - in combination with the verbose mode one could check the operations.')
->addOption('delete', null, InputOption::VALUE_NONE, 'Delete instead of migrating them. Usefull if too many entries to migrate.');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if ($this->memoryLimit !== -1) {
$limitInMiB = round($this->memoryLimit / 1024 / 1024, 1);
$thresholdInMiB = round($this->memoryTreshold / 1024 / 1024, 1);
$output->writeln("Memory limit is $limitInMiB MiB");
$output->writeln("Memory threshold is $thresholdInMiB MiB");
$output->writeln("");
$memoryCheckEnabled = true;
} else {
$output->writeln("No memory limit in place - disabled memory check. Set a PHP memory limit to automatically stop the execution of this migration script once memory consumption is close to this limit.");
$output->writeln("");
$memoryCheckEnabled = false;
}
$dryMode = $input->getOption('dry');
$deleteMode = $input->getOption('delete');
if ($dryMode) {
$output->writeln("INFO: The migration is run in dry mode and will not modify anything.");
$output->writeln("");
} elseif ($deleteMode) {
$output->writeln("WARN: The migration will _DELETE_ old previews.");
$output->writeln("");
}
$instanceId = $this->config->getSystemValueString('instanceid');
$output->writeln("This will migrate all previews from the old preview location to the new one.");
$output->writeln('');
$output->writeln('Fetching previews that need to be migrated …');
/** @var \OCP\Files\Folder $currentPreviewFolder */
$currentPreviewFolder = $this->rootFolder->get("appdata_$instanceId/preview");
$directoryListing = $currentPreviewFolder->getDirectoryListing();
$total = count($directoryListing);
/**
* by default there could be 0-9 a-f and the old-multibucket folder which are all fine
*/
if ($total < 18) {
$directoryListing = array_filter($directoryListing, function ($dir) {
if ($dir->getName() === 'old-multibucket') {
return false;
}
// a-f can't be a file ID -> removing from migration
if (preg_match('!^[a-f]$!', $dir->getName())) {
return false;
}
if (preg_match('!^[0-9]$!', $dir->getName())) {
// ignore folders that only has folders in them
if ($dir instanceof Folder) {
foreach ($dir->getDirectoryListing() as $entry) {
if (!$entry instanceof Folder) {
return true;
}
}
return false;
}
}
return true;
});
$total = count($directoryListing);
}
if ($total === 0) {
$output->writeln("All previews are already migrated.");
return 0;
}
$output->writeln("A total of $total preview files need to be migrated.");
$output->writeln("");
$output->writeln("The migration will always migrate all previews of a single file in a batch. After each batch the process can be canceled by pressing CTRL-C. This will finish the current batch and then stop the migration. This migration can then just be started and it will continue.");
if ($input->getOption('batch')) {
$output->writeln('Batch mode active: migration is started right away.');
} else {
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion('<info>Should the migration be started? (y/[n]) </info>', false);
if (!$helper->ask($input, $output, $question)) {
return 0;
}
}
// register the SIGINT listener late in here to be able to exit in the early process of this command
pcntl_signal(SIGINT, [$this, 'sigIntHandler']);
$output->writeln("");
$output->writeln("");
$section1 = $output->section();
$section2 = $output->section();
$progressBar = new ProgressBar($section2, $total);
$progressBar->setFormat("%current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% Used Memory: %memory:6s%");
$time = (new \DateTime())->format('H:i:s');
$progressBar->setMessage("$time Starting …");
$progressBar->maxSecondsBetweenRedraws(0.2);
$progressBar->start();
foreach ($directoryListing as $oldPreviewFolder) {
pcntl_signal_dispatch();
$name = $oldPreviewFolder->getName();
$time = (new \DateTime())->format('H:i:s');
$section1->writeln("$time Migrating previews of file with fileId $name");
$progressBar->display();
if ($this->stopSignalReceived) {
$section1->writeln("$time Stopping migration …");
return 0;
}
if (!$oldPreviewFolder instanceof Folder) {
$section1->writeln(" Skipping non-folder $name");
$progressBar->advance();
continue;
}
if ($name === 'old-multibucket') {
$section1->writeln(" Skipping fallback mount point $name");
$progressBar->advance();
continue;
}
if (in_array($name, ['a', 'b', 'c', 'd', 'e', 'f'])) {
$section1->writeln(" Skipping hex-digit folder $name");
$progressBar->advance();
continue;
}
if (!preg_match('!^\d+$!', $name)) {
$section1->writeln(" Skipping non-numeric folder $name");
$progressBar->advance();
continue;
}
$newFoldername = Root::getInternalFolder($name);
$memoryUsage = memory_get_usage();
if ($memoryCheckEnabled && $memoryUsage > $this->memoryTreshold) {
$section1->writeln("");
$section1->writeln("");
$section1->writeln("");
$section1->writeln(" Stopped process 25 MB before reaching the memory limit to avoid a hard crash.");
$time = (new \DateTime())->format('H:i:s');
$section1->writeln("$time Reached memory limit and stopped to avoid hard crash.");
return 1;
}
$lockName = 'occ preview:repair lock ' . $oldPreviewFolder->getId();
try {
$section1->writeln(" Locking \"$lockName\"", OutputInterface::VERBOSITY_VERBOSE);
$this->lockingProvider->acquireLock($lockName, ILockingProvider::LOCK_EXCLUSIVE);
} catch (LockedException $e) {
$section1->writeln(" Skipping because it is locked - another process seems to work on this …");
continue;
}
$previews = $oldPreviewFolder->getDirectoryListing();
if ($previews !== []) {
try {
$this->rootFolder->get("appdata_$instanceId/preview/$newFoldername");
} catch (NotFoundException $e) {
$section1->writeln(" Create folder preview/$newFoldername", OutputInterface::VERBOSITY_VERBOSE);
if (!$dryMode) {
$this->rootFolder->newFolder("appdata_$instanceId/preview/$newFoldername");
}
}
foreach ($previews as $preview) {
pcntl_signal_dispatch();
$previewName = $preview->getName();
if ($preview instanceof Folder) {
$section1->writeln(" Skipping folder $name/$previewName");
$progressBar->advance();
continue;
}
// Execute process
if (!$dryMode) {
// Delete preview instead of moving
if ($deleteMode) {
try {
$section1->writeln(" Delete preview/$name/$previewName", OutputInterface::VERBOSITY_VERBOSE);
$preview->delete();
} catch (\Exception $e) {
$this->logger->error("Failed to delete preview at preview/$name/$previewName", [
'app' => 'core',
'exception' => $e,
]);
}
} else {
try {
$section1->writeln(" Move preview/$name/$previewName to preview/$newFoldername", OutputInterface::VERBOSITY_VERBOSE);
$preview->move("appdata_$instanceId/preview/$newFoldername/$previewName");
} catch (\Exception $e) {
$this->logger->error("Failed to move preview from preview/$name/$previewName to preview/$newFoldername", [
'app' => 'core',
'exception' => $e,
]);
}
}
}
}
}
if ($oldPreviewFolder->getDirectoryListing() === []) {
$section1->writeln(" Delete empty folder preview/$name", OutputInterface::VERBOSITY_VERBOSE);
if (!$dryMode) {
try {
$oldPreviewFolder->delete();
} catch (\Exception $e) {
$this->logger->error("Failed to delete empty folder preview/$name", [
'app' => 'core',
'exception' => $e,
]);
}
}
}
$this->lockingProvider->releaseLock($lockName, ILockingProvider::LOCK_EXCLUSIVE);
$section1->writeln(" Unlocked", OutputInterface::VERBOSITY_VERBOSE);
$section1->writeln(" Finished migrating previews of file with fileId $name");
$progressBar->advance();
}
$progressBar->finish();
$output->writeln("");
return 0;
}
protected function sigIntHandler() {
echo "\nSignal received - will finish the step and then stop the migration.\n\n\n";
$this->stopSignalReceived = true;
}
}
@@ -0,0 +1,181 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021, Daniel Calviño Sánchez <danxuliu@gmail.com>
*
* @author Daniel Calviño Sánchez <danxuliu@gmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Preview;
use OC\Preview\Storage\Root;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\Files\IMimeTypeLoader;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IAvatarManager;
use OCP\IDBConnection;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ResetRenderedTexts extends Command {
public function __construct(
protected IDBConnection $connection,
protected IUserManager $userManager,
protected IAvatarManager $avatarManager,
private Root $previewFolder,
private IMimeTypeLoader $mimeTypeLoader,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('preview:reset-rendered-texts')
->setDescription('Deletes all generated avatars and previews of text and md files')
->addOption('dry', 'd', InputOption::VALUE_NONE, 'Dry mode - will not delete any files - in combination with the verbose mode one could check the operations.');
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$dryMode = $input->getOption('dry');
if ($dryMode) {
$output->writeln('INFO: The command is run in dry mode and will not modify anything.');
$output->writeln('');
}
$this->deleteAvatars($output, $dryMode);
$this->deletePreviews($output, $dryMode);
return 0;
}
private function deleteAvatars(OutputInterface $output, bool $dryMode): void {
$avatarsToDeleteCount = 0;
foreach ($this->getAvatarsToDelete() as [$userId, $avatar]) {
$output->writeln('Deleting avatar for ' . $userId, OutputInterface::VERBOSITY_VERBOSE);
$avatarsToDeleteCount++;
if ($dryMode) {
continue;
}
try {
$avatar->remove();
} catch (NotFoundException $e) {
// continue
} catch (NotPermittedException $e) {
// continue
}
}
$output->writeln('Deleted ' . $avatarsToDeleteCount . ' avatars');
$output->writeln('');
}
private function getAvatarsToDelete(): \Iterator {
foreach ($this->userManager->search('') as $user) {
$avatar = $this->avatarManager->getAvatar($user->getUID());
if (!$avatar->isCustomAvatar()) {
yield [$user->getUID(), $avatar];
}
}
}
private function deletePreviews(OutputInterface $output, bool $dryMode): void {
$previewsToDeleteCount = 0;
foreach ($this->getPreviewsToDelete() as ['name' => $previewFileId, 'path' => $filePath]) {
$output->writeln('Deleting previews for ' . $filePath, OutputInterface::VERBOSITY_VERBOSE);
$previewsToDeleteCount++;
if ($dryMode) {
continue;
}
try {
$preview = $this->previewFolder->getFolder((string)$previewFileId);
$preview->delete();
} catch (NotFoundException $e) {
// continue
} catch (NotPermittedException $e) {
// continue
}
}
$output->writeln('Deleted ' . $previewsToDeleteCount . ' previews');
}
// Copy pasted and adjusted from
// "lib/private/Preview/BackgroundCleanupJob.php".
private function getPreviewsToDelete(): \Iterator {
$qb = $this->connection->getQueryBuilder();
$qb->select('path', 'mimetype')
->from('filecache')
->where($qb->expr()->eq('fileid', $qb->createNamedParameter($this->previewFolder->getId())));
$cursor = $qb->execute();
$data = $cursor->fetch();
$cursor->closeCursor();
if ($data === null) {
return [];
}
/*
* This lovely like is the result of the way the new previews are stored
* We take the md5 of the name (fileid) and split the first 7 chars. That way
* there are not a gazillion files in the root of the preview appdata.
*/
$like = $this->connection->escapeLikeParameter($data['path']) . '/_/_/_/_/_/_/_/%';
$qb = $this->connection->getQueryBuilder();
$qb->select('a.name', 'b.path')
->from('filecache', 'a')
->leftJoin('a', 'filecache', 'b', $qb->expr()->eq(
$qb->expr()->castColumn('a.name', IQueryBuilder::PARAM_INT), 'b.fileid'
))
->where(
$qb->expr()->andX(
$qb->expr()->like('a.path', $qb->createNamedParameter($like)),
$qb->expr()->eq('a.mimetype', $qb->createNamedParameter($this->mimeTypeLoader->getId('httpd/unix-directory'))),
$qb->expr()->orX(
$qb->expr()->eq('b.mimetype', $qb->createNamedParameter($this->mimeTypeLoader->getId('text/plain'))),
$qb->expr()->eq('b.mimetype', $qb->createNamedParameter($this->mimeTypeLoader->getId('text/markdown'))),
$qb->expr()->eq('b.mimetype', $qb->createNamedParameter($this->mimeTypeLoader->getId('text/x-markdown')))
)
)
);
$cursor = $qb->execute();
while ($row = $cursor->fetch()) {
yield $row;
}
$cursor->closeCursor();
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
*
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Security;
use OC\Core\Command\Base;
use OCP\Security\Bruteforce\IThrottler;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class BruteforceAttempts extends Base {
public function __construct(
protected IThrottler $throttler,
) {
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('security:bruteforce:attempts')
->setDescription('Show bruteforce attempts status for a given IP address')
->addArgument(
'ipaddress',
InputArgument::REQUIRED,
'IP address for which the attempts status is to be shown',
)
->addArgument(
'action',
InputArgument::OPTIONAL,
'Only count attempts for the given action',
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$ip = $input->getArgument('ipaddress');
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
$output->writeln('<error>"' . $ip . '" is not a valid IP address</error>');
return 1;
}
$data = [
'bypass-listed' => $this->throttler->isBypassListed($ip),
'attempts' => $this->throttler->getAttempts(
$ip,
(string) $input->getArgument('action'),
),
'delay' => $this->throttler->getDelay(
$ip,
(string) $input->getArgument('action'),
),
];
$this->writeArrayInOutputFormat($input, $output, $data);
return 0;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, Johannes Riedel (johannes@johannes-riedel.de)
*
* @author Joas Schilling <coding@schilljs.com>
* @author Johannes Riedel <joeried@users.noreply.github.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\Security;
use OC\Core\Command\Base;
use OCP\Security\Bruteforce\IThrottler;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class BruteforceResetAttempts extends Base {
public function __construct(
protected IThrottler $throttler,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('security:bruteforce:reset')
->setDescription('resets bruteforce attempts for given IP address')
->addArgument(
'ipaddress',
InputArgument::REQUIRED,
'IP address for which the attempts are to be reset'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$ip = $input->getArgument('ipaddress');
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
$output->writeln('<error>"' . $ip . '" is not a valid IP address</error>');
return 1;
}
$this->throttler->resetDelayForIP($ip);
return 0;
}
}
@@ -0,0 +1,64 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Security;
use OC\Core\Command\Base;
use OCP\ICertificateManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ImportCertificate extends Base {
public function __construct(
protected ICertificateManager $certificateManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('security:certificates:import')
->setDescription('import trusted certificate in PEM format')
->addArgument(
'path',
InputArgument::REQUIRED,
'path to the PEM certificate to import'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$path = $input->getArgument('path');
if (!file_exists($path)) {
$output->writeln('<error>Certificate not found, please provide a path accessible by the web server user</error>');
return 1;
}
$certData = file_get_contents($path);
$name = basename($path);
$this->certificateManager->addCertificate($certData, $name);
return 0;
}
}
@@ -0,0 +1,91 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Security;
use OC\Core\Command\Base;
use OCP\ICertificate;
use OCP\ICertificateManager;
use OCP\IL10N;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListCertificates extends Base {
public function __construct(
protected ICertificateManager $certificateManager,
protected IL10N $l,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('security:certificates')
->setDescription('list trusted certificates');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$outputType = $input->getOption('output');
if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
$certificates = array_map(function (ICertificate $certificate) {
return [
'name' => $certificate->getName(),
'common_name' => $certificate->getCommonName(),
'organization' => $certificate->getOrganization(),
'expire' => $certificate->getExpireDate()->format(\DateTimeInterface::ATOM),
'issuer' => $certificate->getIssuerName(),
'issuer_organization' => $certificate->getIssuerOrganization(),
'issue_date' => $certificate->getIssueDate()->format(\DateTimeInterface::ATOM)
];
}, $this->certificateManager->listCertificates());
if ($outputType === self::OUTPUT_FORMAT_JSON) {
$output->writeln(json_encode(array_values($certificates)));
} else {
$output->writeln(json_encode(array_values($certificates), JSON_PRETTY_PRINT));
}
} else {
$table = new Table($output);
$table->setHeaders([
'File Name',
'Common Name',
'Organization',
'Valid Until',
'Issued By'
]);
$rows = array_map(function (ICertificate $certificate) {
return [
$certificate->getName(),
$certificate->getCommonName(),
$certificate->getOrganization(),
$this->l->l('date', $certificate->getExpireDate()),
$certificate->getIssuerName()
];
}, $this->certificateManager->listCertificates());
$table->setRows($rows);
$table->render();
}
return 0;
}
}
@@ -0,0 +1,56 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Carla Schroder <carla@owncloud.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\Security;
use OC\Core\Command\Base;
use OCP\ICertificateManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class RemoveCertificate extends Base {
public function __construct(
protected ICertificateManager $certificateManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('security:certificates:remove')
->setDescription('remove trusted certificate')
->addArgument(
'name',
InputArgument::REQUIRED,
'the file name of the certificate to remove'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$name = $input->getArgument('name');
$this->certificateManager->removeCertificate($name);
return 0;
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Côme Chilliet <come.chilliet@nextcloud.com>
*
* @author Côme Chilliet <come.chilliet@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
use OCP\SetupCheck\ISetupCheckManager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SetupChecks extends Base {
public function __construct(
private ISetupCheckManager $setupCheckManager,
) {
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('setupchecks')
->setDescription('Run setup checks and output the results')
;
}
/**
* @TODO move this method to a common service used by notifications, activity and this command
* @throws \InvalidArgumentException if a parameter has no name or no type
*/
private function richToParsed(string $message, array $parameters): string {
$placeholders = [];
$replacements = [];
foreach ($parameters as $placeholder => $parameter) {
$placeholders[] = '{' . $placeholder . '}';
foreach (['name','type'] as $requiredField) {
if (!isset($parameter[$requiredField]) || !is_string($parameter[$requiredField])) {
throw new \InvalidArgumentException("Invalid rich object, {$requiredField} field is missing");
}
}
$replacements[] = match($parameter['type']) {
'user' => '@' . $parameter['name'],
'file' => $parameter['path'] ?? $parameter['name'],
default => $parameter['name'],
};
}
return str_replace($placeholders, $replacements, $message);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$results = $this->setupCheckManager->runAll();
switch ($input->getOption('output')) {
case self::OUTPUT_FORMAT_JSON:
case self::OUTPUT_FORMAT_JSON_PRETTY:
$this->writeArrayInOutputFormat($input, $output, $results);
break;
default:
foreach ($results as $category => $checks) {
$output->writeln("\t{$category}:");
foreach ($checks as $check) {
$styleTag = match ($check->getSeverity()) {
'success' => 'info',
'error' => 'error',
'warning' => 'comment',
default => null,
};
$emoji = match ($check->getSeverity()) {
'success' => '✓',
'error' => '✗',
'warning' => '⚠',
default => '',
};
$verbosity = ($check->getSeverity() === 'error' ? OutputInterface::VERBOSITY_QUIET : OutputInterface::VERBOSITY_NORMAL);
$description = $check->getDescription();
$descriptionParameters = $check->getDescriptionParameters();
if ($description !== null && $descriptionParameters !== null) {
$description = $this->richToParsed($description, $descriptionParameters);
}
$output->writeln(
"\t\t".
($styleTag !== null ? "<{$styleTag}>" : '').
"{$emoji} ".
($check->getName() ?? $check::class).
($description !== null ? ': '.$description : '').
($styleTag !== null ? "</{$styleTag}>" : ''),
$verbosity
);
}
}
}
foreach ($results as $category => $checks) {
foreach ($checks as $check) {
if ($check->getSeverity() !== 'success') {
return self::FAILURE;
}
}
}
return self::SUCCESS;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Bart Visscher <bartv@thisnet.nl>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
use OC_Util;
use OCP\Defaults;
use OCP\IConfig;
use OCP\Util;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Status extends Base {
public function __construct(
private IConfig $config,
private Defaults $themingDefaults,
) {
parent::__construct('status');
}
protected function configure() {
parent::configure();
$this
->setDescription('show some status information')
->addOption(
'exit-code',
'e',
InputOption::VALUE_NONE,
'exit with 0 if running in normal mode, 1 when in maintenance mode, 2 when `./occ upgrade` is needed. Does not write any output to STDOUT.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$maintenanceMode = $this->config->getSystemValueBool('maintenance', false);
$needUpgrade = Util::needUpgrade();
$values = [
'installed' => $this->config->getSystemValueBool('installed', false),
'version' => implode('.', Util::getVersion()),
'versionstring' => OC_Util::getVersionString(),
'edition' => '',
'maintenance' => $maintenanceMode,
'needsDbUpgrade' => $needUpgrade,
'productname' => $this->themingDefaults->getProductName(),
'extendedSupport' => Util::hasExtendedSupport()
];
if ($input->getOption('verbose') || !$input->getOption('exit-code')) {
$this->writeArrayInOutputFormat($input, $output, $values);
}
if ($input->getOption('exit-code')) {
if ($maintenanceMode === true) {
return 1;
}
if ($needUpgrade === true) {
return 2;
}
}
return 0;
}
}
@@ -0,0 +1,97 @@
<?php
/**
* @copyright Copyright (c) 2021, hosting.de, Johannes Leuker <developers@hosting.de>
*
* @author Johannes Leuker <j.leuker@hosting.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\SystemTag;
use OC\Core\Command\Base;
use OCP\SystemTag\ISystemTag;
use OCP\SystemTag\ISystemTagManager;
use OCP\SystemTag\TagAlreadyExistsException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Add extends Base {
public function __construct(
protected ISystemTagManager $systemTagManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('tag:add')
->setDescription('Add new tag')
->addArgument(
'name',
InputArgument::REQUIRED,
'name of the tag',
)
->addArgument(
'access',
InputArgument::REQUIRED,
'access level of the tag (public, restricted or invisible)',
);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$name = $input->getArgument('name');
if ($name === '') {
$output->writeln('<error>`name` can\'t be empty</error>');
return 3;
}
switch ($input->getArgument('access')) {
case 'public':
$userVisible = true;
$userAssignable = true;
break;
case 'restricted':
$userVisible = true;
$userAssignable = false;
break;
case 'invisible':
$userVisible = false;
$userAssignable = false;
break;
default:
$output->writeln('<error>`access` property is invalid</error>');
return 1;
}
try {
$tag = $this->systemTagManager->createTag($name, $userVisible, $userAssignable);
$this->writeArrayInOutputFormat($input, $output,
[
'id' => $tag->getId(),
'name' => $tag->getName(),
'access' => ISystemTag::ACCESS_LEVEL_LOOKUP[$tag->getAccessLevel()],
]);
return 0;
} catch (TagAlreadyExistsException $e) {
$output->writeln('<error>'.$e->getMessage().'</error>');
return 2;
}
}
}
@@ -0,0 +1,60 @@
<?php
/**
* @copyright Copyright (c) 2021, hosting.de, Johannes Leuker <developers@hosting.de>
*
* @author Johannes Leuker <j.leuker@hosting.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\SystemTag;
use OC\Core\Command\Base;
use OCP\SystemTag\ISystemTagManager;
use OCP\SystemTag\TagNotFoundException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Delete extends Base {
public function __construct(
protected ISystemTagManager $systemTagManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('tag:delete')
->setDescription('delete a tag')
->addArgument(
'id',
InputOption::VALUE_REQUIRED,
'The ID of the tag that should be deleted',
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
try {
$this->systemTagManager->deleteTags($input->getArgument('id'));
$output->writeln('<info>The specified tag was deleted</info>');
return 0;
} catch (TagNotFoundException $e) {
$output->writeln('<error>Tag not found</error>');
return 1;
}
}
}
@@ -0,0 +1,112 @@
<?php
/**
* @copyright Copyright (c) 2021, hosting.de, Johannes Leuker <developers@hosting.de>
*
* @author Johannes Leuker <j.leuker@hosting.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\SystemTag;
use OC\Core\Command\Base;
use OCP\SystemTag\ISystemTagManager;
use OCP\SystemTag\TagAlreadyExistsException;
use OCP\SystemTag\TagNotFoundException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Edit extends Base {
public function __construct(
protected ISystemTagManager $systemTagManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('tag:edit')
->setDescription('edit tag attributes')
->addArgument(
'id',
InputOption::VALUE_REQUIRED,
'The ID of the tag that should be deleted',
)
->addOption(
'name',
null,
InputOption::VALUE_OPTIONAL,
'sets the \'name\' parameter',
)
->addOption(
'access',
null,
InputOption::VALUE_OPTIONAL,
'sets the access control level (public, restricted, invisible)',
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$tagArray = $this->systemTagManager->getTagsByIds($input->getArgument('id'));
// returns an array, but we always expect 0 or 1 results
if (!$tagArray) {
$output->writeln('<error>Tag not found</error>');
return 3;
}
$tag = array_values($tagArray)[0];
$name = $tag->getName();
if (!empty($input->getOption('name'))) {
$name = $input->getOption('name');
}
$userVisible = $tag->isUserVisible();
$userAssignable = $tag->isUserAssignable();
if ($input->getOption('access')) {
switch ($input->getOption('access')) {
case 'public':
$userVisible = true;
$userAssignable = true;
break;
case 'restricted':
$userVisible = true;
$userAssignable = false;
break;
case 'invisible':
$userVisible = false;
$userAssignable = false;
break;
default:
$output->writeln('<error>`access` property is invalid</error>');
return 1;
}
}
try {
$this->systemTagManager->updateTag($input->getArgument('id'), $name, $userVisible, $userAssignable);
$output->writeln('<info>Tag updated ("' . $name . '", '. $userVisible . ', ' . $userAssignable . ')</info>');
return 0;
} catch (TagNotFoundException $e) {
$output->writeln('<error>Tag not found</error>');
return 1;
} catch (TagAlreadyExistsException $e) {
$output->writeln('<error>'.$e->getMessage().'</error>');
return 2;
}
}
}
@@ -0,0 +1,83 @@
<?php
/**
* @copyright Copyright (c) 2021, hosting.de, Johannes Leuker <developers@hosting.de>
*
* @author Johannes Leuker <j.leuker@hosting.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\SystemTag;
use OC\Core\Command\Base;
use OCP\SystemTag\ISystemTag;
use OCP\SystemTag\ISystemTagManager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ListCommand extends Base {
public function __construct(
protected ISystemTagManager $systemTagManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('tag:list')
->setDescription('list tags')
->addOption(
'visibilityFilter',
null,
InputOption::VALUE_OPTIONAL,
'filter by visibility (1,0)'
)
->addOption(
'nameSearchPattern',
null,
InputOption::VALUE_OPTIONAL,
'optional search pattern for the tag name (infix)'
);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$tags = $this->systemTagManager->getAllTags(
$input->getOption('visibilityFilter'),
$input->getOption('nameSearchPattern')
);
$this->writeArrayInOutputFormat($input, $output, $this->formatTags($tags));
return 0;
}
/**
* @param ISystemtag[] $tags
* @return array
*/
private function formatTags(array $tags): array {
$result = [];
foreach ($tags as $tag) {
$result[$tag->getId()] = [
'name' => $tag->getName(),
'access' => ISystemTag::ACCESS_LEVEL_LOOKUP[$tag->getAccessLevel()],
];
}
return $result;
}
}
@@ -0,0 +1,66 @@
<?php
/**
* @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OCP\IUser;
use OCP\IUserManager;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
class Base extends \OC\Core\Command\Base {
public function __construct(
?string $name,
protected IUserManager $userManager,
) {
parent::__construct($name);
}
/**
* Return possible values for the named option
*
* @param string $optionName
* @param CompletionContext $context
* @return string[]
*/
public function completeOptionValues($optionName, CompletionContext $context) {
return [];
}
/**
* Return possible values for the named argument
*
* @param string $argumentName
* @param CompletionContext $context
* @return string[]
*/
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'uid') {
return array_map(function (IUser $user) {
return $user->getUID();
}, $this->userManager->search($context->getCurrentWord(), 100));
}
return [];
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Cleanup extends Base {
public function __construct(
private IRegistry $registry,
IUserManager $userManager,
) {
parent::__construct(
null,
$userManager,
);
}
protected function configure() {
parent::configure();
$this->setName('twofactorauth:cleanup');
$this->setDescription('Clean up the two-factor user-provider association of an uninstalled/removed provider');
$this->addArgument('provider-id', InputArgument::REQUIRED);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$providerId = $input->getArgument('provider-id');
$this->registry->cleanUp($providerId);
$output->writeln("<info>All user-provider associations for provider <options=bold>$providerId</> have been removed.</info>");
return 0;
}
}
@@ -0,0 +1,67 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OC\Authentication\TwoFactorAuth\ProviderManager;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Disable extends Base {
public function __construct(
private ProviderManager $manager,
IUserManager $userManager,
) {
parent::__construct(
'twofactorauth:disable',
$userManager,
);
}
protected function configure() {
parent::configure();
$this->setName('twofactorauth:disable');
$this->setDescription('Disable two-factor authentication for a user');
$this->addArgument('uid', InputArgument::REQUIRED);
$this->addArgument('provider_id', InputArgument::REQUIRED);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
$providerId = $input->getArgument('provider_id');
$user = $this->userManager->get($uid);
if (is_null($user)) {
$output->writeln("<error>Invalid UID</error>");
return 1;
}
if ($this->manager->tryDisableProviderFor($providerId, $user)) {
$output->writeln("Two-factor provider <options=bold>$providerId</> disabled for user <options=bold>$uid</>.");
return 0;
} else {
$output->writeln("<error>The provider does not support this operation.</error>");
return 2;
}
}
}
@@ -0,0 +1,67 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OC\Authentication\TwoFactorAuth\ProviderManager;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Enable extends Base {
public function __construct(
private ProviderManager $manager,
IUserManager $userManager,
) {
parent::__construct(
'twofactorauth:enable',
$userManager,
);
}
protected function configure() {
parent::configure();
$this->setName('twofactorauth:enable');
$this->setDescription('Enable two-factor authentication for a user');
$this->addArgument('uid', InputArgument::REQUIRED);
$this->addArgument('provider_id', InputArgument::REQUIRED);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
$providerId = $input->getArgument('provider_id');
$user = $this->userManager->get($uid);
if (is_null($user)) {
$output->writeln("<error>Invalid UID</error>");
return 1;
}
if ($this->manager->tryEnableProviderFor($providerId, $user)) {
$output->writeln("Two-factor provider <options=bold>$providerId</> enabled for user <options=bold>$uid</>.");
return 0;
} else {
$output->writeln("<error>The provider does not support this operation.</error>");
return 2;
}
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OC\Authentication\TwoFactorAuth\EnforcementState;
use OC\Authentication\TwoFactorAuth\MandatoryTwoFactor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function implode;
class Enforce extends Command {
public function __construct(
private MandatoryTwoFactor $mandatoryTwoFactor,
) {
parent::__construct();
}
protected function configure() {
$this->setName('twofactorauth:enforce');
$this->setDescription('Enabled/disable enforced two-factor authentication');
$this->addOption(
'on',
null,
InputOption::VALUE_NONE,
'enforce two-factor authentication'
);
$this->addOption(
'off',
null,
InputOption::VALUE_NONE,
'don\'t enforce two-factor authenticaton'
);
$this->addOption(
'group',
null,
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
'enforce only for the given group(s)'
);
$this->addOption(
'exclude',
null,
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
'exclude mandatory two-factor auth for the given group(s)'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
if ($input->getOption('on')) {
$enforcedGroups = $input->getOption('group');
$excludedGroups = $input->getOption('exclude');
$this->mandatoryTwoFactor->setState(new EnforcementState(true, $enforcedGroups, $excludedGroups));
} elseif ($input->getOption('off')) {
$this->mandatoryTwoFactor->setState(new EnforcementState(false));
}
$state = $this->mandatoryTwoFactor->getState();
if ($state->isEnforced()) {
$this->writeEnforced($output, $state);
} else {
$this->writeNotEnforced($output);
}
return 0;
}
protected function writeEnforced(OutputInterface $output, EnforcementState $state) {
if (empty($state->getEnforcedGroups())) {
$message = 'Two-factor authentication is enforced for all users';
} else {
$message = 'Two-factor authentication is enforced for members of the group(s) ' . implode(', ', $state->getEnforcedGroups());
}
if (!empty($state->getExcludedGroups())) {
$message .= ', except members of ' . implode(', ', $state->getExcludedGroups());
}
$output->writeln($message);
}
protected function writeNotEnforced(OutputInterface $output) {
$output->writeln('Two-factor authentication is not enforced');
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
/**
* @copyright 2018 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\TwoFactorAuth;
use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class State extends Base {
public function __construct(
private IRegistry $registry,
IUserManager $userManager,
) {
parent::__construct(
'twofactorauth:state',
$userManager,
);
}
protected function configure() {
parent::configure();
$this->setName('twofactorauth:state');
$this->setDescription('Get the two-factor authentication (2FA) state of a user');
$this->addArgument('uid', InputArgument::REQUIRED);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
$user = $this->userManager->get($uid);
if (is_null($user)) {
$output->writeln("<error>Invalid UID</error>");
return 1;
}
$providerStates = $this->registry->getProviderStates($user);
$filtered = $this->filterEnabledDisabledUnknownProviders($providerStates);
[$enabled, $disabled] = $filtered;
if (!empty($enabled)) {
$output->writeln("Two-factor authentication is enabled for user $uid");
} else {
$output->writeln("Two-factor authentication is not enabled for user $uid");
}
$output->writeln("");
$this->printProviders("Enabled providers", $enabled, $output);
$this->printProviders("Disabled providers", $disabled, $output);
return 0;
}
private function filterEnabledDisabledUnknownProviders(array $providerStates): array {
$enabled = [];
$disabled = [];
foreach ($providerStates as $providerId => $isEnabled) {
if ($isEnabled) {
$enabled[] = $providerId;
} else {
$disabled[] = $providerId;
}
}
return [$enabled, $disabled];
}
private function printProviders(string $title, array $providers,
OutputInterface $output) {
if (empty($providers)) {
// Ignore and don't print anything
return;
}
$output->writeln($title . ":");
foreach ($providers as $provider) {
$output->writeln("- " . $provider);
}
}
}
+261
View File
@@ -0,0 +1,261 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Andreas Fischer <bantu@owncloud.com>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Nils Wittenbrink <nilswittenbrink@web.de>
* @author Owen Winkler <a_github@midnightcircus.com>
* @author Robin Appelman <robin@icewind.nl>
* @author Sander Ruitenbeek <sander@grids.be>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Thomas Pulzer <t.pulzer@kniel.de>
* @author Valdnet <47037905+Valdnet@users.noreply.github.com>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command;
use OC\Console\TimestampFormatter;
use OC\DB\MigratorExecuteSqlEvent;
use OC\Installer;
use OC\Repair\Events\RepairAdvanceEvent;
use OC\Repair\Events\RepairErrorEvent;
use OC\Repair\Events\RepairFinishEvent;
use OC\Repair\Events\RepairInfoEvent;
use OC\Repair\Events\RepairStartEvent;
use OC\Repair\Events\RepairStepEvent;
use OC\Repair\Events\RepairWarningEvent;
use OC\Updater;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\Util;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Upgrade extends Command {
public const ERROR_SUCCESS = 0;
public const ERROR_NOT_INSTALLED = 1;
public const ERROR_MAINTENANCE_MODE = 2;
public const ERROR_UP_TO_DATE = 0;
public const ERROR_INVALID_ARGUMENTS = 4;
public const ERROR_FAILURE = 5;
public function __construct(
private IConfig $config,
private LoggerInterface $logger,
private Installer $installer,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('upgrade')
->setDescription('run upgrade routines after installation of a new release. The release has to be installed before.');
}
/**
* Execute the upgrade command
*
* @param InputInterface $input input interface
* @param OutputInterface $output output interface
*/
protected function execute(InputInterface $input, OutputInterface $output): int {
if (Util::needUpgrade()) {
if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
// Prepend each line with a little timestamp
$timestampFormatter = new TimestampFormatter($this->config, $output->getFormatter());
$output->setFormatter($timestampFormatter);
}
$self = $this;
$updater = new Updater(
$this->config,
\OC::$server->getIntegrityCodeChecker(),
$this->logger,
$this->installer
);
/** @var IEventDispatcher $dispatcher */
$dispatcher = \OC::$server->get(IEventDispatcher::class);
$progress = new ProgressBar($output);
$progress->setFormat(" %message%\n %current%/%max% [%bar%] %percent:3s%%");
$listener = function (MigratorExecuteSqlEvent $event) use ($progress, $output): void {
$message = $event->getSql();
if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
$output->writeln(' Executing SQL ' . $message);
} else {
if (strlen($message) > 60) {
$message = substr($message, 0, 57) . '...';
}
$progress->setMessage($message);
if ($event->getCurrentStep() === 1) {
$output->writeln('');
$progress->start($event->getMaxStep());
}
$progress->setProgress($event->getCurrentStep());
if ($event->getCurrentStep() === $event->getMaxStep()) {
$progress->setMessage('Done');
$progress->finish();
$output->writeln('');
}
}
};
$repairListener = function (Event $event) use ($progress, $output): void {
if ($event instanceof RepairStartEvent) {
$progress->setMessage('Starting ...');
$output->writeln($event->getCurrentStepName());
$output->writeln('');
$progress->start($event->getMaxStep());
} elseif ($event instanceof RepairAdvanceEvent) {
$desc = $event->getDescription();
if (!empty($desc)) {
$progress->setMessage($desc);
}
$progress->advance($event->getIncrement());
} elseif ($event instanceof RepairFinishEvent) {
$progress->setMessage('Done');
$progress->finish();
$output->writeln('');
} elseif ($event instanceof RepairStepEvent) {
if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
$output->writeln('<info>Repair step: ' . $event->getStepName() . '</info>');
}
} elseif ($event instanceof RepairInfoEvent) {
if (OutputInterface::VERBOSITY_NORMAL < $output->getVerbosity()) {
$output->writeln('<info>Repair info: ' . $event->getMessage() . '</info>');
}
} elseif ($event instanceof RepairWarningEvent) {
$output->writeln('<error>Repair warning: ' . $event->getMessage() . '</error>');
} elseif ($event instanceof RepairErrorEvent) {
$output->writeln('<error>Repair error: ' . $event->getMessage() . '</error>');
}
};
$dispatcher->addListener(MigratorExecuteSqlEvent::class, $listener);
$dispatcher->addListener(RepairStartEvent::class, $repairListener);
$dispatcher->addListener(RepairAdvanceEvent::class, $repairListener);
$dispatcher->addListener(RepairFinishEvent::class, $repairListener);
$dispatcher->addListener(RepairStepEvent::class, $repairListener);
$dispatcher->addListener(RepairInfoEvent::class, $repairListener);
$dispatcher->addListener(RepairWarningEvent::class, $repairListener);
$dispatcher->addListener(RepairErrorEvent::class, $repairListener);
$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($output) {
$output->writeln('<info>Turned on maintenance mode</info>');
});
$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($output) {
$output->writeln('<info>Turned off maintenance mode</info>');
});
$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($output) {
$output->writeln('<info>Maintenance mode is kept active</info>');
});
$updater->listen('\OC\Updater', 'updateEnd',
function ($success) use ($output, $self) {
if ($success) {
$message = "<info>Update successful</info>";
} else {
$message = "<error>Update failed</error>";
}
$output->writeln($message);
});
$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($output) {
$output->writeln('<info>Updating database schema</info>');
});
$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($output) {
$output->writeln('<info>Updated database</info>');
});
$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($output) {
$output->writeln('<comment>Disabled incompatible app: ' . $app . '</comment>');
});
$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($output) {
$output->writeln('<info>Update app ' . $app . ' from App Store</info>');
});
$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($output) {
$output->writeln("<info>Checking whether the database schema for <$app> can be updated (this can take a long time depending on the database size)</info>");
});
$updater->listen('\OC\Updater', 'appUpgradeStarted', function ($app, $version) use ($output) {
$output->writeln("<info>Updating <$app> ...</info>");
});
$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($output) {
$output->writeln("<info>Updated <$app> to $version</info>");
});
$updater->listen('\OC\Updater', 'failure', function ($message) use ($output, $self) {
$output->writeln("<error>$message</error>");
});
$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use ($output) {
$output->writeln("<info>Setting log level to debug</info>");
});
$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($output) {
$output->writeln("<info>Resetting log level</info>");
});
$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($output) {
$output->writeln("<info>Starting code integrity check...</info>");
});
$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($output) {
$output->writeln("<info>Finished code integrity check</info>");
});
$success = $updater->upgrade();
$this->postUpgradeCheck($input, $output);
if (!$success) {
return self::ERROR_FAILURE;
}
return self::ERROR_SUCCESS;
} elseif ($this->config->getSystemValueBool('maintenance')) {
//Possible scenario: Nextcloud core is updated but an app failed
$output->writeln('<comment>Nextcloud is in maintenance mode</comment>');
$output->write('<comment>Maybe an upgrade is already in process. Please check the '
. 'logfile (data/nextcloud.log). If you want to re-run the '
. 'upgrade procedure, remove the "maintenance mode" from '
. 'config.php and call this script again.</comment>', true);
return self::ERROR_MAINTENANCE_MODE;
} else {
$output->writeln('<info>Nextcloud is already latest version</info>');
return self::ERROR_UP_TO_DATE;
}
}
/**
* Perform a post upgrade check (specific to the command line tool)
*
* @param InputInterface $input input interface
* @param OutputInterface $output output interface
*/
protected function postUpgradeCheck(InputInterface $input, OutputInterface $output) {
$trustedDomains = $this->config->getSystemValue('trusted_domains', []);
if (empty($trustedDomains)) {
$output->write(
'<warning>The setting "trusted_domains" could not be ' .
'set automatically by the upgrade script, ' .
'please set it manually</warning>'
);
}
}
}
+159
View File
@@ -0,0 +1,159 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Laurens Post <lkpost@scept.re>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Core\Command\User;
use OC\Files\Filesystem;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
class Add extends Command {
public function __construct(
protected IUserManager $userManager,
protected IGroupManager $groupManager,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('user:add')
->setDescription('adds a user')
->addArgument(
'uid',
InputArgument::REQUIRED,
'User ID used to login (must only contain a-z, A-Z, 0-9, -, _ and @)'
)
->addOption(
'password-from-env',
null,
InputOption::VALUE_NONE,
'read password from environment variable OC_PASS'
)
->addOption(
'display-name',
null,
InputOption::VALUE_OPTIONAL,
'User name used in the web UI (can contain any characters)'
)
->addOption(
'group',
'g',
InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY,
'groups the user should be added to (The group will be created if it does not exist)'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
if ($this->userManager->userExists($uid)) {
$output->writeln('<error>The user "' . $uid . '" already exists.</error>');
return 1;
}
if ($input->getOption('password-from-env')) {
$password = getenv('OC_PASS');
if (!$password) {
$output->writeln('<error>--password-from-env given, but OC_PASS is empty!</error>');
return 1;
}
} elseif ($input->isInteractive()) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new Question('Enter password: ');
$question->setHidden(true);
$password = $helper->ask($input, $output, $question);
$question = new Question('Confirm password: ');
$question->setHidden(true);
$confirm = $helper->ask($input, $output, $question);
if ($password !== $confirm) {
$output->writeln("<error>Passwords did not match!</error>");
return 1;
}
} else {
$output->writeln("<error>Interactive input or --password-from-env is needed for entering a password!</error>");
return 1;
}
try {
$user = $this->userManager->createUser(
$input->getArgument('uid'),
$password
);
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage() . '</error>');
return 1;
}
if ($user instanceof IUser) {
$output->writeln('<info>The user "' . $user->getUID() . '" was created successfully</info>');
} else {
$output->writeln('<error>An error occurred while creating the user</error>');
return 1;
}
if ($input->getOption('display-name')) {
$user->setDisplayName($input->getOption('display-name'));
$output->writeln('Display name set to "' . $user->getDisplayName() . '"');
}
$groups = $input->getOption('group');
if (!empty($groups)) {
// Make sure we init the Filesystem for the user, in case we need to
// init some group shares.
Filesystem::init($user->getUID(), '');
}
foreach ($groups as $groupName) {
$group = $this->groupManager->get($groupName);
if (!$group) {
$this->groupManager->createGroup($groupName);
$group = $this->groupManager->get($groupName);
if ($group instanceof IGroup) {
$output->writeln('Created group "' . $group->getGID() . '"');
}
}
if ($group instanceof IGroup) {
$group->addUser($user);
$output->writeln('User "' . $user->getUID() . '" added to group "' . $group->getGID() . '"');
}
}
return 0;
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2020, NextCloud, Inc.
*
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Sean Molenaar <sean@seanmolenaar.eu>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User\AuthTokens;
use OC\Authentication\Events\AppPasswordCreatedEvent;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IUserManager;
use OCP\Security\ISecureRandom;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
class Add extends Command {
public function __construct(
protected IUserManager $userManager,
protected IProvider $tokenProvider,
private ISecureRandom $random,
private IEventDispatcher $eventDispatcher,
) {
parent::__construct();
}
protected function configure() {
$this
->setName('user:auth-tokens:add')
->setAliases(['user:add-app-password'])
->setDescription('Add app password for the named user')
->addArgument(
'user',
InputArgument::REQUIRED,
'Username to add app password for'
)
->addOption(
'password-from-env',
null,
InputOption::VALUE_NONE,
'Read password from environment variable NC_PASS/OC_PASS. Alternatively it will be asked for interactively or an app password without the login password will be created.'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$username = $input->getArgument('user');
$password = null;
$user = $this->userManager->get($username);
if (is_null($user)) {
$output->writeln('<error>User does not exist</error>');
return 1;
}
if ($input->getOption('password-from-env')) {
$password = getenv('NC_PASS') ?? getenv('OC_PASS');
if (!$password) {
$output->writeln('<error>--password-from-env given, but NC_PASS is empty!</error>');
return 1;
}
} elseif ($input->isInteractive()) {
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
$question = new Question('Enter the user password: ');
$question->setHidden(true);
/** @var null|string $password */
$password = $helper->ask($input, $output, $question);
}
if ($password === null) {
$output->writeln('<info>No password provided. The generated app password will therefore have limited capabilities. Any operation that requires the login password will fail.</info>');
}
$token = $this->random->generate(72, ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS);
$generatedToken = $this->tokenProvider->generateToken(
$token,
$user->getUID(),
$user->getUID(),
$password,
'cli',
IToken::PERMANENT_TOKEN,
IToken::DO_NOT_REMEMBER
);
$this->eventDispatcher->dispatchTyped(
new AppPasswordCreatedEvent($generatedToken)
);
$output->writeln('app password:');
$output->writeln($token);
return 0;
}
}
@@ -0,0 +1,120 @@
<?php
/**
* @copyright Copyright (c) 2023 Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @author Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User\AuthTokens;
use DateTimeImmutable;
use OC\Authentication\Token\IProvider;
use OC\Core\Command\Base;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Delete extends Base {
public function __construct(
protected IProvider $tokenProvider,
) {
parent::__construct();
}
protected function configure(): void {
$this
->setName('user:auth-tokens:delete')
->setDescription('Deletes an authentication token')
->addArgument(
'uid',
InputArgument::REQUIRED,
'ID of the user to delete tokens for'
)
->addArgument(
'id',
InputArgument::OPTIONAL,
'ID of the auth token to delete'
)
->addOption(
'last-used-before',
null,
InputOption::VALUE_REQUIRED,
'Delete tokens last used before a given date.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$uid = $input->getArgument('uid');
$id = (int) $input->getArgument('id');
$before = $input->getOption('last-used-before');
if ($before) {
if ($id) {
throw new RuntimeException('Option --last-used-before cannot be used with [<id>]');
}
return $this->deleteLastUsedBefore($uid, $before);
}
if (!$id) {
throw new RuntimeException('Not enough arguments. Specify the token <id> or use the --last-used-before option.');
}
return $this->deleteById($uid, $id);
}
protected function deleteById(string $uid, int $id): int {
$this->tokenProvider->invalidateTokenById($uid, $id);
return Command::SUCCESS;
}
protected function deleteLastUsedBefore(string $uid, string $before): int {
$date = $this->parseDateOption($before);
if (!$date) {
throw new RuntimeException('Invalid date format. Acceptable formats are: ISO8601 (w/o fractions), "YYYY-MM-DD" and Unix time in seconds.');
}
$this->tokenProvider->invalidateLastUsedBefore($uid, $date->getTimestamp());
return Command::SUCCESS;
}
/**
* @return \DateTimeImmutable|false
*/
protected function parseDateOption(string $input) {
$date = false;
// Handle Unix timestamp
if (filter_var($input, FILTER_VALIDATE_INT)) {
return new DateTimeImmutable('@' . $input);
}
// ISO8601
$date = DateTimeImmutable::createFromFormat(DateTimeImmutable::ATOM, $input);
if ($date) {
return $date;
}
// YYYY-MM-DD
return DateTimeImmutable::createFromFormat('!Y-m-d', $input);
}
}
@@ -0,0 +1,100 @@
<?php
/**
* @copyright Copyright (c) 2023 Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @author Lucas Azevedo <lhs_azevedo@hotmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\Core\Command\User\AuthTokens;
use OC\Authentication\Token\IProvider;
use OC\Authentication\Token\IToken;
use OC\Core\Command\Base;
use OCP\IUserManager;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ListCommand extends Base {
public function __construct(
protected IUserManager $userManager,
protected IProvider $tokenProvider,
) {
parent::__construct();
}
protected function configure(): void {
parent::configure();
$this
->setName('user:auth-tokens:list')
->setDescription('List authentication tokens of an user')
->addArgument(
'user',
InputArgument::REQUIRED,
'User to list auth tokens for'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$user = $this->userManager->get($input->getArgument('user'));
if (is_null($user)) {
$output->writeln('<error>user not found</error>');
return 1;
}
$tokens = $this->tokenProvider->getTokenByUser($user->getUID());
$tokens = array_map(function (IToken $token) use ($input): mixed {
$sensitive = [
'password',
'password_hash',
'token',
'public_key',
'private_key',
];
$data = array_diff_key($token->jsonSerialize(), array_flip($sensitive));
if ($input->getOption('output') === self::OUTPUT_FORMAT_PLAIN) {
$data = $this->formatTokenForPlainOutput($data);
}
return $data;
}, $tokens);
$this->writeTableInOutputFormat($input, $output, $tokens);
return 0;
}
public function formatTokenForPlainOutput(array $token): array {
$token['scope'] = implode(', ', array_keys(array_filter($token['scope'] ?? [])));
$token['lastActivity'] = date(DATE_ATOM, $token['lastActivity']);
$token['type'] = match ($token['type']) {
IToken::TEMPORARY_TOKEN => 'temporary',
IToken::PERMANENT_TOKEN => 'permanent',
IToken::WIPE_TOKEN => 'wipe',
default => $token['type'],
};
return $token;
}
}

Some files were not shown because too many files have changed in this diff Show More