diff options
47 files changed, 514 insertions, 529 deletions
diff --git a/apps/files_sharing/tests/ApiTest.php b/apps/files_sharing/tests/ApiTest.php index 2279155e914..8e2b5942d14 100644 --- a/apps/files_sharing/tests/ApiTest.php +++ b/apps/files_sharing/tests/ApiTest.php @@ -62,8 +62,8 @@ class ApiTest extends TestCase { protected function setUp() { parent::setUp(); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', 'no'); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_expire_after_n_days', '7'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_expire_after_n_days', '7'); $this->folder = self::TEST_FOLDER_NAME; $this->subfolder = '/subfolder_share_api_test'; @@ -239,8 +239,8 @@ class ApiTest extends TestCase { function testEnfoceLinkPassword() { $password = md5(time()); - $appConfig = \OC::$server->getAppConfig(); - $appConfig->setValue('core', 'shareapi_enforce_links_password', 'yes'); + $config = \OC::$server->getConfig(); + $config->setAppValue('core', 'shareapi_enforce_links_password', 'yes'); $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); try { @@ -287,7 +287,7 @@ class ApiTest extends TestCase { $ocs->deleteShare($data['id']); $ocs->cleanup(); - $appConfig->setValue('core', 'shareapi_enforce_links_password', 'no'); + $config->setAppValue('core', 'shareapi_enforce_links_password', 'no'); } /** @@ -296,7 +296,7 @@ class ApiTest extends TestCase { function testSharePermissions() { // sharing file to a user should work if shareapi_exclude_groups is set // to no - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', 'no'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no'); $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2); @@ -311,8 +311,8 @@ class ApiTest extends TestCase { $ocs->cleanup(); // exclude groups, but not the group the user belongs to. Sharing should still work - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', 'yes'); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', 'admin,group1,group2'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'yes'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group1,group2'); $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); $result = $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2); @@ -327,15 +327,15 @@ class ApiTest extends TestCase { $ocs->cleanup(); // now we exclude the group the user belongs to ('group'), sharing should fail now - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', 'admin,group'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', 'admin,group'); $ocs = $this->createOCS(self::TEST_FILES_SHARING_API_USER1); $ocs->createShare($this->filename, \OCP\Constants::PERMISSION_ALL, \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2); $ocs->cleanup(); // cleanup - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', 'no'); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', ''); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups', 'no'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_exclude_groups_list', ''); } diff --git a/apps/updatenotification/appinfo/app.php b/apps/updatenotification/appinfo/app.php index fd1739bde55..5002fd7c837 100644 --- a/apps/updatenotification/appinfo/app.php +++ b/apps/updatenotification/appinfo/app.php @@ -1,56 +1,25 @@ <?php /** - * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2018, Joas Schilling <coding@schilljs.com> * * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Thomas Müller <thomas.mueller@tmit.eu> * - * @license AGPL-3.0 + * @license GNU AGPL version 3 or any later version * - * 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 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 + * 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/> + * 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/>. * */ -if(\OC::$server->getConfig()->getSystemValue('updatechecker', true) === true) { - $updater = new \OC\Updater\VersionCheck( - \OC::$server->getHTTPClientService(), - \OC::$server->getConfig() - ); - $updateChecker = new \OCA\UpdateNotification\UpdateChecker( - $updater - ); - - $userObject = \OC::$server->getUserSession()->getUser(); - if($userObject !== null) { - if(\OC::$server->getGroupManager()->isAdmin($userObject->getUID()) && - !\OC::$server->getAppManager()->isEnabledForUser('notifications')) { - if($updateChecker->getUpdateState() !== []) { - \OCP\Util::addScript('updatenotification', 'notification'); - OC_Hook::connect('\OCP\Config', 'js', $updateChecker, 'getJavaScript'); - } - } - } - - $manager = \OC::$server->getNotificationManager(); - $manager->registerNotifier(function() use ($manager) { - return \OC::$server->query(\OCA\UpdateNotification\Notification\Notifier::class); - }, function() { - $l = \OC::$server->getL10N('updatenotification'); - return [ - 'id' => 'updatenotification', - 'name' => $l->t('Update notifications'), - ]; - }); -} +$app = new \OCA\UpdateNotification\AppInfo\Application(); +$app->register(); diff --git a/apps/updatenotification/appinfo/info.xml b/apps/updatenotification/appinfo/info.xml index 5dc0889bb9d..14ec98916ab 100644 --- a/apps/updatenotification/appinfo/info.xml +++ b/apps/updatenotification/appinfo/info.xml @@ -5,7 +5,7 @@ <description>Displays update notifications for Nextcloud and provides the SSO for the updater.</description> <licence>AGPL</licence> <author>Lukas Reschke</author> - <version>1.4.0</version> + <version>1.4.1</version> <namespace>UpdateNotification</namespace> <default_enable/> <dependencies> @@ -17,6 +17,6 @@ </background-jobs> <settings> - <admin>OCA\UpdateNotification\Controller\AdminController</admin> + <admin>OCA\UpdateNotification\Settings\Admin</admin> </settings> </info> diff --git a/apps/updatenotification/composer/composer/autoload_classmap.php b/apps/updatenotification/composer/composer/autoload_classmap.php index e1833548bcf..55ad497a858 100644 --- a/apps/updatenotification/composer/composer/autoload_classmap.php +++ b/apps/updatenotification/composer/composer/autoload_classmap.php @@ -11,5 +11,6 @@ return array( 'OCA\\UpdateNotification\\Notification\\BackgroundJob' => $baseDir . '/../lib/Notification/BackgroundJob.php', 'OCA\\UpdateNotification\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php', 'OCA\\UpdateNotification\\ResetTokenBackgroundJob' => $baseDir . '/../lib/ResetTokenBackgroundJob.php', + 'OCA\\UpdateNotification\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php', 'OCA\\UpdateNotification\\UpdateChecker' => $baseDir . '/../lib/UpdateChecker.php', ); diff --git a/apps/updatenotification/composer/composer/autoload_static.php b/apps/updatenotification/composer/composer/autoload_static.php index 1c63a2d234b..4a50e180a8f 100644 --- a/apps/updatenotification/composer/composer/autoload_static.php +++ b/apps/updatenotification/composer/composer/autoload_static.php @@ -26,6 +26,7 @@ class ComposerStaticInitUpdateNotification 'OCA\\UpdateNotification\\Notification\\BackgroundJob' => __DIR__ . '/..' . '/../lib/Notification/BackgroundJob.php', 'OCA\\UpdateNotification\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php', 'OCA\\UpdateNotification\\ResetTokenBackgroundJob' => __DIR__ . '/..' . '/../lib/ResetTokenBackgroundJob.php', + 'OCA\\UpdateNotification\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php', 'OCA\\UpdateNotification\\UpdateChecker' => __DIR__ . '/..' . '/../lib/UpdateChecker.php', ); diff --git a/apps/updatenotification/lib/AppInfo/Application.php b/apps/updatenotification/lib/AppInfo/Application.php index 5eba176f312..d79f14764de 100644 --- a/apps/updatenotification/lib/AppInfo/Application.php +++ b/apps/updatenotification/lib/AppInfo/Application.php @@ -1,56 +1,84 @@ <?php +declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. + * @copyright Copyright (c) 2018, Joas Schilling <coding@schilljs.com> * - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Thomas Müller <thomas.mueller@tmit.eu> + * @author Joas Schilling <coding@schilljs.com> * - * @license AGPL-3.0 + * @license GNU AGPL version 3 or any later version * - * 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 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 + * 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/> + * 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 OCA\UpdateNotification\AppInfo; -use OC\AppFramework\Utility\TimeFactory; -use OCA\UpdateNotification\Controller\AdminController; +use OCA\UpdateNotification\Notification\Notifier; use OCA\UpdateNotification\UpdateChecker; use OCP\AppFramework\App; -use OCP\AppFramework\IAppContainer; +use OCP\AppFramework\QueryException; +use OCP\IUser; +use OCP\Util; class Application extends App { - public function __construct (array $urlParams = array()) { - parent::__construct('updatenotification', $urlParams); - $container = $this->getContainer(); - - $container->registerService('AdminController', function(IAppContainer $c) { - $updater = new \OC\Updater\VersionCheck( - \OC::$server->getHTTPClientService(), - \OC::$server->getConfig() - ); - return new AdminController( - $c->query('AppName'), - $c->query('Request'), - $c->getServer()->getJobList(), - $c->getServer()->getSecureRandom(), - $c->getServer()->getConfig(), - new TimeFactory(), - $c->getServer()->getL10N($c->query('AppName')), - new UpdateChecker($updater), - $c->getServer()->getDateTimeFormatter() - ); - }); + public function __construct() { + parent::__construct('updatenotification', []); } + public function register() { + $server = $this->getContainer()->getServer(); + + if ($server->getConfig()->getSystemValue('updatechecker', true) !== true) { + // Updater check is disabled + return; + } + + $user = $server->getUserSession()->getUser(); + if (!$user instanceof IUser) { + // Nothing to do for guests + return; + } + + if ($server->getAppManager()->isEnabledForUser('notifications')) { + // Notifications app is available, so we register. + // Since notifications also work for non-admins we don't check this here. + $this->registerNotifier(); + } else if ($server->getGroupManager()->isAdmin($user->getUID())) { + try { + $updateChecker = $this->getContainer()->query(UpdateChecker::class); + } catch (QueryException $e) { + $server->getLogger()->logException($e); + return; + } + + if ($updateChecker->getUpdateState() !== []) { + Util::addScript('updatenotification', 'notification'); + \OC_Hook::connect('\OCP\Config', 'js', $updateChecker, 'populateJavaScriptVariables'); + } + } + } + + public function registerNotifier() { + $notificationsManager = $this->getContainer()->getServer()->getNotificationManager(); + $notificationsManager->registerNotifier(function() { + return $this->getContainer()->query(Notifier::class); + }, function() { + $l = $this->getContainer()->getServer()->getL10N('updatenotification'); + return [ + 'id' => 'updatenotification', + 'name' => $l->t('Update notifications'), + ]; + }); + } } diff --git a/apps/updatenotification/lib/Controller/AdminController.php b/apps/updatenotification/lib/Controller/AdminController.php index 9d2a5074a4a..57f89969db4 100644 --- a/apps/updatenotification/lib/Controller/AdminController.php +++ b/apps/updatenotification/lib/Controller/AdminController.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -25,20 +26,18 @@ namespace OCA\UpdateNotification\Controller; -use OCA\UpdateNotification\UpdateChecker; +use OCA\UpdateNotification\ResetTokenBackgroundJob; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\DataResponse; -use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\IConfig; -use OCP\IDateTimeFormatter; use OCP\IL10N; use OCP\IRequest; use OCP\Security\ISecureRandom; -use OCP\Settings\ISettings; +use OCP\Util; -class AdminController extends Controller implements ISettings { +class AdminController extends Controller { /** @var IJobList */ private $jobList; /** @var ISecureRandom */ @@ -47,12 +46,8 @@ class AdminController extends Controller implements ISettings { private $config; /** @var ITimeFactory */ private $timeFactory; - /** @var UpdateChecker */ - private $updateChecker; /** @var IL10N */ private $l10n; - /** @var IDateTimeFormatter */ - private $dateTimeFormatter; /** * @param string $appName @@ -62,8 +57,6 @@ class AdminController extends Controller implements ISettings { * @param IConfig $config * @param ITimeFactory $timeFactory * @param IL10N $l10n - * @param UpdateChecker $updateChecker - * @param IDateTimeFormatter $dateTimeFormatter */ public function __construct($appName, IRequest $request, @@ -71,70 +64,21 @@ class AdminController extends Controller implements ISettings { ISecureRandom $secureRandom, IConfig $config, ITimeFactory $timeFactory, - IL10N $l10n, - UpdateChecker $updateChecker, - IDateTimeFormatter $dateTimeFormatter) { + IL10N $l10n) { parent::__construct($appName, $request); $this->jobList = $jobList; $this->secureRandom = $secureRandom; $this->config = $config; $this->timeFactory = $timeFactory; $this->l10n = $l10n; - $this->updateChecker = $updateChecker; - $this->dateTimeFormatter = $dateTimeFormatter; } /** - * @return TemplateResponse - */ - public function displayPanel() { - $lastUpdateCheckTimestamp = $this->config->getAppValue('core', 'lastupdatedat'); - $lastUpdateCheck = $this->dateTimeFormatter->formatDateTime($lastUpdateCheckTimestamp); - - $channels = [ - 'daily', - 'beta', - 'stable', - 'production', - ]; - $currentChannel = \OCP\Util::getChannel(); - - // Remove the currently used channel from the channels list - if(($key = array_search($currentChannel, $channels)) !== false) { - unset($channels[$key]); - } - $updateState = $this->updateChecker->getUpdateState(); - - $notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); - - $defaultUpdateServerURL = 'https://updates.nextcloud.com/server/'; - $updateServerURL = $this->config->getSystemValue('updater.server.url', $defaultUpdateServerURL); - - $params = [ - 'isNewVersionAvailable' => !empty($updateState['updateAvailable']), - 'isUpdateChecked' => $lastUpdateCheckTimestamp > 0, - 'lastChecked' => $lastUpdateCheck, - 'currentChannel' => $currentChannel, - 'channels' => $channels, - 'newVersionString' => (empty($updateState['updateVersion'])) ? '' : $updateState['updateVersion'], - 'downloadLink' => (empty($updateState['downloadLink'])) ? '' : $updateState['downloadLink'], - 'updaterEnabled' => (empty($updateState['updaterEnabled'])) ? false : $updateState['updaterEnabled'], - 'isDefaultUpdateServerURL' => $updateServerURL === $defaultUpdateServerURL, - 'updateServerURL' => $updateServerURL, - 'notify_groups' => implode('|', $notifyGroups), - ]; - - return new TemplateResponse($this->appName, 'admin', $params, ''); - } - - /** - * @UseSession - * * @param string $channel * @return DataResponse */ - public function setChannel($channel) { - \OCP\Util::setChannel($channel); + public function setChannel(string $channel): DataResponse { + Util::setChannel($channel); $this->config->setAppValue('core', 'lastupdatedat', 0); return new DataResponse(['status' => 'success', 'data' => ['message' => $this->l10n->t('Channel updated')]]); } @@ -142,9 +86,9 @@ class AdminController extends Controller implements ISettings { /** * @return DataResponse */ - public function createCredentials() { + public function createCredentials(): DataResponse { // Create a new job and store the creation date - $this->jobList->add('OCA\UpdateNotification\ResetTokenBackgroundJob'); + $this->jobList->add(ResetTokenBackgroundJob::class); $this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime()); // Create a new token @@ -153,29 +97,4 @@ class AdminController extends Controller implements ISettings { return new DataResponse($newToken); } - - /** - * @return TemplateResponse returns the instance with all parameters set, ready to be rendered - */ - public function getForm() { - return $this->displayPanel(); - } - - /** - * @return string the section ID, e.g. 'sharing' - */ - public function getSection() { - return 'server'; - } - - /** - * @return int whether the form should be rather on the top or bottom of - * the admin section. The forms are arranged in ascending order of the - * priority values. It is required to return a value between 0 and 100. - * - * E.g.: 70 - */ - public function getPriority() { - return 1; - } } diff --git a/apps/updatenotification/lib/Notification/BackgroundJob.php b/apps/updatenotification/lib/Notification/BackgroundJob.php index 3c0cac60cde..c010ccc89e5 100644 --- a/apps/updatenotification/lib/Notification/BackgroundJob.php +++ b/apps/updatenotification/lib/Notification/BackgroundJob.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -90,7 +91,7 @@ class BackgroundJob extends TimedJob { * Check for ownCloud update */ protected function checkCoreUpdate() { - if (in_array($this->getChannel(), ['daily', 'git'], true)) { + if (\in_array($this->getChannel(), ['daily', 'git'], true)) { // "These aren't the update channels you're looking for." - Ben Obi-Wan Kenobi return; } @@ -102,10 +103,10 @@ class BackgroundJob extends TimedJob { $errors = 1 + (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); $this->config->setAppValue('updatenotification', 'update_check_errors', $errors); - if (in_array($errors, $this->connectionNotifications, true)) { + if (\in_array($errors, $this->connectionNotifications, true)) { $this->sendErrorNotifications($errors); } - } else if (is_array($status)) { + } else if (\is_array($status)) { $this->config->setAppValue('updatenotification', 'update_check_errors', 0); $this->clearErrorNotifications(); @@ -178,26 +179,31 @@ class BackgroundJob extends TimedJob { if ($lastNotification === $version) { // We already notified about this update return; - } else if ($lastNotification !== false) { + } + + if ($lastNotification !== false) { // Delete old updates $this->deleteOutdatedNotifications($app, $lastNotification); } - $notification = $this->notificationManager->createNotification(); - $notification->setApp('updatenotification') - ->setDateTime(new \DateTime()) - ->setObject($app, $version); - - if ($visibleVersion !== '') { - $notification->setSubject('update_available', ['version' => $visibleVersion]); - } else { - $notification->setSubject('update_available'); - } + try { + $notification->setApp('updatenotification') + ->setDateTime(new \DateTime()) + ->setObject($app, $version); - foreach ($this->getUsersToNotify() as $uid) { - $notification->setUser($uid); - $this->notificationManager->notify($notification); + if ($visibleVersion !== '') { + $notification->setSubject('update_available', ['version' => $visibleVersion]); + } else { + $notification->setSubject('update_available'); + } + + foreach ($this->getUsersToNotify() as $uid) { + $notification->setUser($uid); + $this->notificationManager->notify($notification); + } + } catch (\InvalidArgumentException $e) { + return; } $this->config->setAppValue('updatenotification', $app, $version); @@ -206,12 +212,12 @@ class BackgroundJob extends TimedJob { /** * @return string[] */ - protected function getUsersToNotify() { + protected function getUsersToNotify(): array { if ($this->users !== null) { return $this->users; } - $notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); + $notifyGroups = (array) json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); $this->users = []; foreach ($notifyGroups as $group) { $groupToNotify = $this->groupManager->get($group); @@ -235,15 +241,19 @@ class BackgroundJob extends TimedJob { */ protected function deleteOutdatedNotifications($app, $version) { $notification = $this->notificationManager->createNotification(); - $notification->setApp('updatenotification') - ->setObject($app, $version); + try { + $notification->setApp('updatenotification') + ->setObject($app, $version); + } catch (\InvalidArgumentException $e) { + return; + } $this->notificationManager->markProcessed($notification); } /** * @return VersionCheck */ - protected function createVersionCheck() { + protected function createVersionCheck(): VersionCheck { return new VersionCheck( $this->client, $this->config @@ -253,7 +263,7 @@ class BackgroundJob extends TimedJob { /** * @return string */ - protected function getChannel() { + protected function getChannel(): string { return \OC_Util::getChannel(); } diff --git a/apps/updatenotification/lib/Notification/Notifier.php b/apps/updatenotification/lib/Notification/Notifier.php index d18a2663702..c88937f0dff 100644 --- a/apps/updatenotification/lib/Notification/Notifier.php +++ b/apps/updatenotification/lib/Notification/Notifier.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -33,6 +34,7 @@ use OCP\L10N\IFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Notification\INotifier; +use OCP\Util; class Notifier implements INotifier { @@ -84,9 +86,9 @@ class Notifier implements INotifier { * @throws \InvalidArgumentException When the notification was not prepared by a notifier * @since 9.0.0 */ - public function prepare(INotification $notification, $languageCode) { + public function prepare(INotification $notification, $languageCode): INotification { if ($notification->getApp() !== 'updatenotification') { - throw new \InvalidArgumentException(); + throw new \InvalidArgumentException('Unknown app id'); } $l = $this->l10NFactory->get('updatenotification', $languageCode); @@ -94,7 +96,7 @@ class Notifier implements INotifier { $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); if ($errors === 0) { $this->notificationManager->markProcessed($notification); - throw new \InvalidArgumentException(); + throw new \InvalidArgumentException('Update checked worked again'); } $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) @@ -145,14 +147,14 @@ class Notifier implements INotifier { protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { $this->notificationManager->markProcessed($notification); - throw new \InvalidArgumentException(); + throw new \InvalidArgumentException('Update already installed'); } } /** * @return bool */ - protected function isAdmin() { + protected function isAdmin(): bool { $user = $this->userSession->getUser(); if ($user instanceof IUser) { @@ -162,11 +164,11 @@ class Notifier implements INotifier { return false; } - protected function getCoreVersions() { - return implode('.', \OCP\Util::getVersion()); + protected function getCoreVersions(): string { + return implode('.', Util::getVersion()); } - protected function getAppVersions() { + protected function getAppVersions(): array { return \OC_App::getAppVersions(); } diff --git a/apps/updatenotification/lib/ResetTokenBackgroundJob.php b/apps/updatenotification/lib/ResetTokenBackgroundJob.php index 93b5a750789..87cca466ec7 100644 --- a/apps/updatenotification/lib/ResetTokenBackgroundJob.php +++ b/apps/updatenotification/lib/ResetTokenBackgroundJob.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -22,7 +23,6 @@ namespace OCA\UpdateNotification; -use OC\AppFramework\Utility\TimeFactory; use OC\BackgroundJob\TimedJob; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; @@ -40,28 +40,15 @@ class ResetTokenBackgroundJob extends TimedJob { private $timeFactory; /** - * @param IConfig|null $config - * @param ITimeFactory|null $timeFactory + * @param IConfig $config + * @param ITimeFactory $timeFactory */ - public function __construct(IConfig $config = null, - ITimeFactory $timeFactory = null) { + public function __construct(IConfig $config, + ITimeFactory $timeFactory) { // Run all 10 minutes $this->setInterval(60 * 10); - - if ($config instanceof IConfig && $timeFactory instanceof ITimeFactory) { - $this->config = $config; - $this->timeFactory = $timeFactory; - } else { - $this->fixDIForJobs(); - } - } - - /** - * DI for jobs - */ - private function fixDIForJobs() { - $this->config = \OC::$server->getConfig(); - $this->timeFactory = new TimeFactory(); + $this->config = $config; + $this->timeFactory = $timeFactory; } /** diff --git a/apps/updatenotification/lib/Settings/Admin.php b/apps/updatenotification/lib/Settings/Admin.php new file mode 100644 index 00000000000..7fb6cc99dea --- /dev/null +++ b/apps/updatenotification/lib/Settings/Admin.php @@ -0,0 +1,117 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2016, ownCloud, Inc. + * + * @author Arthur Schiwon <blizzz@arthur-schiwon.de> + * @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 OCA\UpdateNotification\Settings; + +use OCA\UpdateNotification\UpdateChecker; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use OCP\IDateTimeFormatter; +use OCP\Settings\ISettings; +use OCP\Util; + +class Admin implements ISettings { + /** @var IConfig */ + private $config; + /** @var UpdateChecker */ + private $updateChecker; + /** @var IDateTimeFormatter */ + private $dateTimeFormatter; + + /** + * @param IConfig $config + * @param UpdateChecker $updateChecker + * @param IDateTimeFormatter $dateTimeFormatter + */ + public function __construct(IConfig $config, + UpdateChecker $updateChecker, + IDateTimeFormatter $dateTimeFormatter) { + $this->config = $config; + $this->updateChecker = $updateChecker; + $this->dateTimeFormatter = $dateTimeFormatter; + } + + /** + * @return TemplateResponse + */ + public function getForm(): TemplateResponse { + $lastUpdateCheckTimestamp = $this->config->getAppValue('core', 'lastupdatedat'); + $lastUpdateCheck = $this->dateTimeFormatter->formatDateTime($lastUpdateCheckTimestamp); + + $channels = [ + 'daily', + 'beta', + 'stable', + 'production', + ]; + $currentChannel = Util::getChannel(); + + // Remove the currently used channel from the channels list + if(($key = array_search($currentChannel, $channels, true)) !== false) { + unset($channels[$key]); + } + $updateState = $this->updateChecker->getUpdateState(); + + $notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true); + + $defaultUpdateServerURL = 'https://updates.nextcloud.com/server/'; + $updateServerURL = $this->config->getSystemValue('updater.server.url', $defaultUpdateServerURL); + + $params = [ + 'isNewVersionAvailable' => !empty($updateState['updateAvailable']), + 'isUpdateChecked' => $lastUpdateCheckTimestamp > 0, + 'lastChecked' => $lastUpdateCheck, + 'currentChannel' => $currentChannel, + 'channels' => $channels, + 'newVersionString' => empty($updateState['updateVersion']) ? '' : $updateState['updateVersion'], + 'downloadLink' => empty($updateState['downloadLink']) ? '' : $updateState['downloadLink'], + 'updaterEnabled' => empty($updateState['updaterEnabled']) ? false : $updateState['updaterEnabled'], + 'isDefaultUpdateServerURL' => $updateServerURL === $defaultUpdateServerURL, + 'updateServerURL' => $updateServerURL, + 'notify_groups' => implode('|', $notifyGroups), + ]; + + return new TemplateResponse('updatenotification', 'admin', $params, ''); + } + + /** + * @return string the section ID, e.g. 'sharing' + */ + public function getSection(): string { + return 'server'; + } + + /** + * @return int whether the form should be rather on the top or bottom of + * the admin section. The forms are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. + * + * E.g.: 70 + */ + public function getPriority(): int { + return 1; + } +} diff --git a/apps/updatenotification/lib/UpdateChecker.php b/apps/updatenotification/lib/UpdateChecker.php index ad76de56953..5f2712423d2 100644 --- a/apps/updatenotification/lib/UpdateChecker.php +++ b/apps/updatenotification/lib/UpdateChecker.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -40,18 +41,18 @@ class UpdateChecker { /** * @return array */ - public function getUpdateState() { + public function getUpdateState(): array { $data = $this->updater->check(); $result = []; - if(isset($data['version']) && $data['version'] !== '' && $data['version'] !== []) { + if (isset($data['version']) && $data['version'] !== '' && $data['version'] !== []) { $result['updateAvailable'] = true; $result['updateVersion'] = $data['versionstring']; $result['updaterEnabled'] = $data['autoupdater'] === '1'; - if(substr($data['web'], 0, 8) === 'https://') { + if (strpos($data['web'], 'https://') === 0) { $result['updateLink'] = $data['web']; } - if(substr($data['url'], 0, 8) === 'https://') { + if (strpos($data['url'], 'https://') === 0) { $result['downloadLink'] = $data['url']; } @@ -64,11 +65,11 @@ class UpdateChecker { /** * @param array $data */ - public function getJavaScript(array $data) { + public function populateJavaScriptVariables(array $data) { $data['array']['oc_updateState'] = json_encode([ 'updateAvailable' => true, 'updateVersion' => $this->getUpdateState()['updateVersion'], - 'updateLink' => isset($this->getUpdateState()['updateLink']) ? $this->getUpdateState()['updateLink'] : '', + 'updateLink' => $this->getUpdateState()['updateLink'] ?? '', ]); } } diff --git a/apps/updatenotification/templates/admin.php b/apps/updatenotification/templates/admin.php index e09d19848e7..19bbec769d0 100644 --- a/apps/updatenotification/templates/admin.php +++ b/apps/updatenotification/templates/admin.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); script('updatenotification', 'admin'); style('updatenotification', 'admin'); @@ -40,7 +41,7 @@ <?php if (!$isDefaultUpdateServerURL) { ?> <br /> <em> - <?php p($l->t("A non-default update server is in use to be checked for updates:")); ?> + <?php p($l->t('A non-default update server is in use to be checked for updates:')); ?> <code><?php p($updateServerURL); ?></code> </em> <?php } ?> @@ -65,10 +66,10 @@ <p id="oca_updatenotification_groups"> <?php p($l->t('Notify members of the following groups about available updates:')); ?> <input name="oca_updatenotification_groups_list" type="hidden" id="oca_updatenotification_groups_list" value="<?php p($_['notify_groups']) ?>" style="width: 400px"><br /> - <em class="<?php if (!in_array($currentChannel, ['daily', 'git'])) p('hidden'); ?>"> + <em class="<?php if (!\in_array($currentChannel, ['daily', 'git'], true)) { p('hidden'); } ?>"> <?php p($l->t('Only notification for app updates are available.')); ?> - <?php if ($currentChannel === 'daily') p($l->t('The selected update channel makes dedicated notifications for the server obsolete.')); ?> - <?php if ($currentChannel === 'git') p($l->t('The selected update channel does not support updates of the server.')); ?> + <?php if ($currentChannel === 'daily') { p($l->t('The selected update channel makes dedicated notifications for the server obsolete.')); } ?> + <?php if ($currentChannel === 'git') { p($l->t('The selected update channel does not support updates of the server.')); } ?> </em> </p> </form> diff --git a/apps/updatenotification/tests/Controller/AdminControllerTest.php b/apps/updatenotification/tests/Controller/AdminControllerTest.php index 75588a1aec5..98b08e633bb 100644 --- a/apps/updatenotification/tests/Controller/AdminControllerTest.php +++ b/apps/updatenotification/tests/Controller/AdminControllerTest.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -25,50 +26,41 @@ namespace OCA\UpdateNotification\Tests\Controller; use OCA\UpdateNotification\Controller\AdminController; -use OCA\UpdateNotification\UpdateChecker; +use OCA\UpdateNotification\ResetTokenBackgroundJob; use OCP\AppFramework\Http\DataResponse; -use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\IConfig; -use OCP\IDateTimeFormatter; use OCP\IL10N; use OCP\IRequest; use OCP\Security\ISecureRandom; use Test\TestCase; class AdminControllerTest extends TestCase { - /** @var IRequest */ + /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */ private $request; - /** @var IJobList */ + /** @var IJobList|\PHPUnit_Framework_MockObject_MockObject */ private $jobList; - /** @var ISecureRandom */ + /** @var ISecureRandom|\PHPUnit_Framework_MockObject_MockObject */ private $secureRandom; - /** @var IConfig */ + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ private $config; /** @var AdminController */ private $adminController; - /** @var ITimeFactory */ + /** @var ITimeFactory|\PHPUnit_Framework_MockObject_MockObject */ private $timeFactory; - /** @var IL10N */ + /** @var IL10N|\PHPUnit_Framework_MockObject_MockObject */ private $l10n; - /** @var UpdateChecker */ - private $updateChecker; - /** @var IDateTimeFormatter */ - private $dateTimeFormatter; public function setUp() { parent::setUp(); - $this->request = $this->getMockBuilder('\\OCP\\IRequest')->getMock(); - $this->jobList = $this->getMockBuilder('\\OCP\\BackgroundJob\\IJobList')->getMock(); - $this->secureRandom = $this->getMockBuilder('\\OCP\\Security\\ISecureRandom')->getMock(); - $this->config = $this->getMockBuilder('\\OCP\\IConfig')->getMock(); - $this->timeFactory = $this->getMockBuilder('\\OCP\\AppFramework\\Utility\\ITimeFactory')->getMock(); - $this->l10n = $this->getMockBuilder('\\OCP\\IL10N')->getMock(); - $this->updateChecker = $this->getMockBuilder('\\OCA\\UpdateNotification\\UpdateChecker') - ->disableOriginalConstructor()->getMock(); - $this->dateTimeFormatter = $this->getMockBuilder('\\OCP\\IDateTimeFormatter')->getMock(); + $this->request = $this->createMock(IRequest::class); + $this->jobList = $this->createMock(IJobList::class); + $this->secureRandom = $this->createMock(ISecureRandom::class); + $this->config = $this->createMock(IConfig::class); + $this->timeFactory = $this->createMock(ITimeFactory::class); + $this->l10n = $this->createMock(IL10N::class); $this->adminController = new AdminController( 'updatenotification', @@ -77,131 +69,15 @@ class AdminControllerTest extends TestCase { $this->secureRandom, $this->config, $this->timeFactory, - $this->l10n, - $this->updateChecker, - $this->dateTimeFormatter + $this->l10n ); } - public function testDisplayPanelWithUpdate() { - $channels = [ - 'daily', - 'beta', - 'stable', - 'production', - ]; - $currentChannel = \OCP\Util::getChannel(); - - // Remove the currently used channel from the channels list - if(($key = array_search($currentChannel, $channels)) !== false) { - unset($channels[$key]); - } - - $this->config - ->expects($this->exactly(2)) - ->method('getAppValue') - ->willReturnMap([ - ['core', 'lastupdatedat', '', '12345'], - ['updatenotification', 'notify_groups', '["admin"]', '["admin"]'], - ]); - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.nextcloud.com/server/') - ->willReturn('https://updates.nextcloud.com/server/'); - $this->dateTimeFormatter - ->expects($this->once()) - ->method('formatDateTime') - ->with('12345') - ->willReturn('LastCheckedReturnValue'); - $this->updateChecker - ->expects($this->once()) - ->method('getUpdateState') - ->willReturn([ - 'updateAvailable' => true, - 'updateVersion' => '8.1.2', - 'downloadLink' => 'https://downloads.nextcloud.org/server', - 'updaterEnabled' => true, - ]); - - $params = [ - 'isNewVersionAvailable' => true, - 'isUpdateChecked' => true, - 'lastChecked' => 'LastCheckedReturnValue', - 'currentChannel' => \OCP\Util::getChannel(), - 'channels' => $channels, - 'newVersionString' => '8.1.2', - 'downloadLink' => 'https://downloads.nextcloud.org/server', - 'updaterEnabled' => true, - 'isDefaultUpdateServerURL' => true, - 'updateServerURL' => 'https://updates.nextcloud.com/server/', - 'notify_groups' => 'admin', - ]; - - $expected = new TemplateResponse('updatenotification', 'admin', $params, ''); - $this->assertEquals($expected, $this->adminController->displayPanel()); - } - - public function testDisplayPanelWithoutUpdate() { - $channels = [ - 'daily', - 'beta', - 'stable', - 'production', - ]; - $currentChannel = \OCP\Util::getChannel(); - - // Remove the currently used channel from the channels list - if(($key = array_search($currentChannel, $channels)) !== false) { - unset($channels[$key]); - } - - $this->config - ->expects($this->exactly(2)) - ->method('getAppValue') - ->willReturnMap([ - ['core', 'lastupdatedat', '', '12345'], - ['updatenotification', 'notify_groups', '["admin"]', '["admin"]'], - ]); - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('updater.server.url', 'https://updates.nextcloud.com/server/') - ->willReturn('https://updates.nextcloud.com/server/'); - $this->dateTimeFormatter - ->expects($this->once()) - ->method('formatDateTime') - ->with('12345') - ->willReturn('LastCheckedReturnValue'); - $this->updateChecker - ->expects($this->once()) - ->method('getUpdateState') - ->willReturn([]); - - $params = [ - 'isNewVersionAvailable' => false, - 'isUpdateChecked' => true, - 'lastChecked' => 'LastCheckedReturnValue', - 'currentChannel' => \OCP\Util::getChannel(), - 'channels' => $channels, - 'newVersionString' => '', - 'downloadLink' => '', - 'updaterEnabled' => 0, - 'isDefaultUpdateServerURL' => true, - 'updateServerURL' => 'https://updates.nextcloud.com/server/', - 'notify_groups' => 'admin', - ]; - - $expected = new TemplateResponse('updatenotification', 'admin', $params, ''); - $this->assertEquals($expected, $this->adminController->displayPanel()); - } - - public function testCreateCredentials() { $this->jobList ->expects($this->once()) ->method('add') - ->with('OCA\UpdateNotification\ResetTokenBackgroundJob'); + ->with(ResetTokenBackgroundJob::class); $this->secureRandom ->expects($this->once()) ->method('generate') @@ -224,11 +100,4 @@ class AdminControllerTest extends TestCase { $this->assertEquals($expected, $this->adminController->createCredentials()); } - public function testGetSection() { - $this->assertSame('server', $this->adminController->getSection()); - } - - public function testGetPriority() { - $this->assertSame(1, $this->adminController->getPriority()); - } } diff --git a/apps/updatenotification/tests/Notification/BackgroundJobTest.php b/apps/updatenotification/tests/Notification/BackgroundJobTest.php index 0355b10a09c..4ed1c350674 100644 --- a/apps/updatenotification/tests/Notification/BackgroundJobTest.php +++ b/apps/updatenotification/tests/Notification/BackgroundJobTest.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -105,7 +106,7 @@ class BackgroundJobTest extends TestCase { self::invokePrivate($job, 'run', [null]); } - public function dataCheckCoreUpdate() { + public function dataCheckCoreUpdate(): array { return [ ['daily', null, null, null, null], ['git', null, null, null, null], @@ -142,7 +143,7 @@ class BackgroundJobTest extends TestCase { * @param null|string $readableVersion * @param null|int $errorDays */ - public function testCheckCoreUpdate($channel, $versionCheck, $version, $readableVersion, $errorDays) { + public function testCheckCoreUpdate(string $channel, $versionCheck, $version, $readableVersion, $errorDays) { $job = $this->getJob([ 'getChannel', 'createVersionCheck', @@ -197,13 +198,13 @@ class BackgroundJobTest extends TestCase { ->method('clearErrorNotifications'); $job->expects($this->once()) ->method('createNotifications') - ->willReturn('core', $version, $readableVersion); + ->with('core', $version, $readableVersion); } self::invokePrivate($job, 'checkCoreUpdate'); } - public function dataCheckAppUpdates() { + public function dataCheckAppUpdates(): array { return [ [ ['app1', 'app2'], @@ -235,18 +236,18 @@ class BackgroundJobTest extends TestCase { ->method('getInstalledApps') ->willReturn($apps); - $job->expects($this->exactly(count($apps))) + $job->expects($this->exactly(\count($apps))) ->method('isUpdateAvailable') ->willReturnMap($isUpdateAvailable); - $mockedMethod = $job->expects($this->exactly(count($notifications))) + $mockedMethod = $job->expects($this->exactly(\count($notifications))) ->method('createNotifications'); - call_user_func_array([$mockedMethod, 'withConsecutive'], $notifications); + \call_user_func_array([$mockedMethod, 'withConsecutive'], $notifications); self::invokePrivate($job, 'checkAppUpdates'); } - public function dataCreateNotifications() { + public function dataCreateNotifications(): array { return [ ['app1', '1.0.0', '1.0.0', false, false, null, null], ['app2', '1.0.1', '1.0.0', '1.0.0', true, ['user1'], [['user1']]], @@ -265,7 +266,7 @@ class BackgroundJobTest extends TestCase { * @param string[]|null $users * @param array|null $userNotifications */ - public function testCreateNotifications($app, $version, $lastNotification, $callDelete, $createNotification, $users, $userNotifications) { + public function testCreateNotifications(string $app, string $version, $lastNotification, $callDelete, $createNotification, $users, $userNotifications) { $job = $this->getJob([ 'deleteOutdatedNotifications', 'getUsersToNotify', @@ -319,12 +320,12 @@ class BackgroundJobTest extends TestCase { ->willReturnSelf(); if ($userNotifications !== null) { - $mockedMethod = $notification->expects($this->exactly(count($userNotifications))) + $mockedMethod = $notification->expects($this->exactly(\count($userNotifications))) ->method('setUser') ->willReturnSelf(); - call_user_func_array([$mockedMethod, 'withConsecutive'], $userNotifications); + \call_user_func_array([$mockedMethod, 'withConsecutive'], $userNotifications); - $this->notificationManager->expects($this->exactly(count($userNotifications))) + $this->notificationManager->expects($this->exactly(\count($userNotifications))) ->method('notify') ->willReturn($notification); } @@ -340,7 +341,7 @@ class BackgroundJobTest extends TestCase { self::invokePrivate($job, 'createNotifications', [$app, $version]); } - public function dataGetUsersToNotify() { + public function dataGetUsersToNotify(): array { return [ [['g1', 'g2'], ['g1' => null, 'g2' => ['u1', 'u2']], ['u1', 'u2']], [['g3', 'g4'], ['g3' => ['u1', 'u2'], 'g4' => ['u2', 'u3']], ['u1', 'u2', 'u3']], @@ -353,7 +354,7 @@ class BackgroundJobTest extends TestCase { * @param array $groupUsers * @param string[] $expected */ - public function testGetUsersToNotify($groups, array $groupUsers, array $expected) { + public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected) { $job = $this->getJob(); $this->config->expects($this->once()) @@ -373,7 +374,7 @@ class BackgroundJobTest extends TestCase { } $groupMap[] = [$gid, $group]; } - $this->groupManager->expects($this->exactly(count($groups))) + $this->groupManager->expects($this->exactly(\count($groups))) ->method('get') ->willReturnMap($groupMap); @@ -385,7 +386,7 @@ class BackgroundJobTest extends TestCase { $this->assertEquals($expected, $result); } - public function dataDeleteOutdatedNotifications() { + public function dataDeleteOutdatedNotifications(): array { return [ ['app1', '1.1.0'], ['app2', '1.2.0'], @@ -397,7 +398,7 @@ class BackgroundJobTest extends TestCase { * @param string $app * @param string $version */ - public function testDeleteOutdatedNotifications($app, $version) { + public function testDeleteOutdatedNotifications(string $app, string $version) { $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('setApp') @@ -423,7 +424,7 @@ class BackgroundJobTest extends TestCase { * @param string[] $userIds * @return IUser[]|\PHPUnit_Framework_MockObject_MockObject[] */ - protected function getUsers(array $userIds) { + protected function getUsers(array $userIds): array { $users = []; foreach ($userIds as $uid) { $user = $this->createMock(IUser::class); @@ -436,10 +437,10 @@ class BackgroundJobTest extends TestCase { } /** - * @param $gid + * @param string $gid * @return \OCP\IGroup|\PHPUnit_Framework_MockObject_MockObject */ - protected function getGroup($gid) { + protected function getGroup(string $gid) { $group = $this->createMock(IGroup::class); $group->expects($this->any()) ->method('getGID') diff --git a/apps/updatenotification/tests/Notification/NotifierTest.php b/apps/updatenotification/tests/Notification/NotifierTest.php index 34486bf5ba5..b1ddf7b478d 100644 --- a/apps/updatenotification/tests/Notification/NotifierTest.php +++ b/apps/updatenotification/tests/Notification/NotifierTest.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -88,7 +89,7 @@ class NotifierTest extends TestCase { } } - public function dataUpdateAlreadyInstalledCheck() { + public function dataUpdateAlreadyInstalledCheck(): array { return [ ['1.1.0', '1.0.0', false], ['1.1.0', '1.1.0', true], @@ -103,7 +104,7 @@ class NotifierTest extends TestCase { * @param string $versionInstalled * @param bool $exception */ - public function testUpdateAlreadyInstalledCheck($versionNotification, $versionInstalled, $exception) { + public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception) { $notifier = $this->getNotifier(); $notification = $this->createMock(INotification::class); @@ -121,7 +122,7 @@ class NotifierTest extends TestCase { } try { - $this->invokePrivate($notifier, 'updateAlreadyInstalledCheck', [$notification, $versionInstalled]); + self::invokePrivate($notifier, 'updateAlreadyInstalledCheck', [$notification, $versionInstalled]); $this->assertFalse($exception); } catch (\Exception $e) { $this->assertTrue($exception); diff --git a/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php b/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php index 4309aed84bf..d78a5ed94cc 100644 --- a/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php +++ b/apps/updatenotification/tests/ResetTokenBackgroundJobTest.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -29,23 +30,23 @@ use OCP\IConfig; use Test\TestCase; class ResetTokenBackgroundJobTest extends TestCase { - /** @var IConfig */ + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ private $config; + /** @var ITimeFactory|\PHPUnit_Framework_MockObject_MockObject */ + private $timeFactory; /** @var ResetTokenBackgroundJob */ private $resetTokenBackgroundJob; - /** @var ITimeFactory */ - private $timeFactory; public function setUp() { parent::setUp(); - $this->config = $this->getMockBuilder('\\OCP\\IConfig')->getMock(); - $this->timeFactory = $this->getMockBuilder('\\OCP\\AppFramework\\Utility\\ITimeFactory')->getMock(); + $this->config = $this->createMock(IConfig::class); + $this->timeFactory = $this->createMock(ITimeFactory::class); $this->resetTokenBackgroundJob = new ResetTokenBackgroundJob($this->config, $this->timeFactory); } public function testRunWithNotExpiredToken() { $this->timeFactory - ->expects($this->any()) + ->expects($this->atLeastOnce()) ->method('getTime') ->willReturn(123); $this->config @@ -54,10 +55,9 @@ class ResetTokenBackgroundJobTest extends TestCase { ->with('core', 'updater.secret.created', 123); $this->config ->expects($this->never()) - ->method('deleteSystemValue') - ->with('updater.secret'); + ->method('deleteSystemValue'); - $this->invokePrivate($this->resetTokenBackgroundJob, 'run', ['']); + static::invokePrivate($this->resetTokenBackgroundJob, 'run', [null]); } public function testRunWithExpiredToken() { @@ -78,6 +78,6 @@ class ResetTokenBackgroundJobTest extends TestCase { ->method('deleteSystemValue') ->with('updater.secret'); - $this->invokePrivate($this->resetTokenBackgroundJob, 'run', ['']); + static::invokePrivate($this->resetTokenBackgroundJob, 'run', [null]); } } diff --git a/apps/updatenotification/tests/Settings/AdminTest.php b/apps/updatenotification/tests/Settings/AdminTest.php new file mode 100644 index 00000000000..12734b808c0 --- /dev/null +++ b/apps/updatenotification/tests/Settings/AdminTest.php @@ -0,0 +1,127 @@ +<?php +declare(strict_types=1); +/** + * @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 OCA\UpdateNotification\Tests\Settings; + +use OCA\UpdateNotification\Settings\Admin; +use OCA\UpdateNotification\UpdateChecker; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\IConfig; +use OCP\IDateTimeFormatter; +use OCP\Util; +use Test\TestCase; + +class AdminTest extends TestCase { + /** @var Admin */ + private $admin; + /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ + private $config; + /** @var UpdateChecker|\PHPUnit_Framework_MockObject_MockObject */ + private $updateChecker; + /** @var IDateTimeFormatter|\PHPUnit_Framework_MockObject_MockObject */ + private $dateTimeFormatter; + + public function setUp() { + parent::setUp(); + + $this->config = $this->createMock(IConfig::class); + $this->updateChecker = $this->createMock(UpdateChecker::class); + $this->dateTimeFormatter = $this->createMock(IDateTimeFormatter::class); + + $this->admin = new Admin( + $this->config, + $this->updateChecker, + $this->dateTimeFormatter + ); + } + + public function testGetFormWithUpdate() { + $channels = [ + 'daily', + 'beta', + 'stable', + 'production', + ]; + $currentChannel = Util::getChannel(); + + // Remove the currently used channel from the channels list + if(($key = array_search($currentChannel, $channels, true)) !== false) { + unset($channels[$key]); + } + + $this->config + ->expects($this->exactly(2)) + ->method('getAppValue') + ->willReturnMap([ + ['core', 'lastupdatedat', '', '12345'], + ['updatenotification', 'notify_groups', '["admin"]', '["admin"]'], + ]); + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('updater.server.url', 'https://updates.nextcloud.com/server/') + ->willReturn('https://updates.nextcloud.com/server/'); + $this->dateTimeFormatter + ->expects($this->once()) + ->method('formatDateTime') + ->with('12345') + ->willReturn('LastCheckedReturnValue'); + $this->updateChecker + ->expects($this->once()) + ->method('getUpdateState') + ->willReturn([ + 'updateAvailable' => true, + 'updateVersion' => '8.1.2', + 'downloadLink' => 'https://downloads.nextcloud.org/server', + 'updaterEnabled' => true, + ]); + + $params = [ + 'isNewVersionAvailable' => true, + 'isUpdateChecked' => true, + 'lastChecked' => 'LastCheckedReturnValue', + 'currentChannel' => Util::getChannel(), + 'channels' => $channels, + 'newVersionString' => '8.1.2', + 'downloadLink' => 'https://downloads.nextcloud.org/server', + 'updaterEnabled' => true, + 'isDefaultUpdateServerURL' => true, + 'updateServerURL' => 'https://updates.nextcloud.com/server/', + 'notify_groups' => 'admin', + ]; + + $expected = new TemplateResponse('updatenotification', 'admin', $params, ''); + $this->assertEquals($expected, $this->admin->getForm()); + } + + + public function testGetSection() { + $this->assertSame('server', $this->admin->getSection()); + } + + public function testGetPriority() { + $this->assertSame(1, $this->admin->getPriority()); + } +} diff --git a/apps/updatenotification/tests/UpdateCheckerTest.php b/apps/updatenotification/tests/UpdateCheckerTest.php index f7ed83047a6..5502e1ce8ac 100644 --- a/apps/updatenotification/tests/UpdateCheckerTest.php +++ b/apps/updatenotification/tests/UpdateCheckerTest.php @@ -1,4 +1,5 @@ <?php +declare(strict_types=1); /** * @copyright Copyright (c) 2016, ownCloud, Inc. * @@ -24,12 +25,12 @@ namespace OCA\UpdateNotification\Tests; -use OC\Updater; +use OC\Updater\VersionCheck; use OCA\UpdateNotification\UpdateChecker; use Test\TestCase; class UpdateCheckerTest extends TestCase { - /** @var Updater */ + /** @var VersionCheck|\PHPUnit_Framework_MockObject_MockObject */ private $updater; /** @var UpdateChecker */ private $updateChecker; @@ -37,8 +38,7 @@ class UpdateCheckerTest extends TestCase { public function setUp() { parent::setUp(); - $this->updater = $this->getMockBuilder('\OC\Updater\VersionCheck') - ->disableOriginalConstructor()->getMock(); + $this->updater = $this->createMock(VersionCheck::class); $this->updateChecker = new UpdateChecker($this->updater); } diff --git a/core/l10n/de.js b/core/l10n/de.js index 1632a4f90a4..07573d2aaab 100644 --- a/core/l10n/de.js +++ b/core/l10n/de.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "Benutzername oder E-Mail", "Log in" : "Anmelden", "Wrong password." : "Falsches Passwort.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Es wurden mehrere ungültige Anmeldeversuche von Deiner IP-Adresse festgestellt. Daher wird die nächste Anmeldung um 30 Sekunden verzögert.", "Stay logged in" : "Angemeldet bleiben", "Forgot password?" : "Passwort vergessen?", "Back to log in" : "Zur Anmeldung wechseln", diff --git a/core/l10n/de.json b/core/l10n/de.json index e52da650dfa..38eaf2b478c 100644 --- a/core/l10n/de.json +++ b/core/l10n/de.json @@ -275,6 +275,7 @@ "Username or email" : "Benutzername oder E-Mail", "Log in" : "Anmelden", "Wrong password." : "Falsches Passwort.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Es wurden mehrere ungültige Anmeldeversuche von Deiner IP-Adresse festgestellt. Daher wird die nächste Anmeldung um 30 Sekunden verzögert.", "Stay logged in" : "Angemeldet bleiben", "Forgot password?" : "Passwort vergessen?", "Back to log in" : "Zur Anmeldung wechseln", diff --git a/core/l10n/de_DE.js b/core/l10n/de_DE.js index 43cc1c330b4..dc4908c58f7 100644 --- a/core/l10n/de_DE.js +++ b/core/l10n/de_DE.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "Benutzername oder E-Mail", "Log in" : "Anmelden", "Wrong password." : "Falsches Passwort.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Es wurden mehrere ungültige Anmeldeversuche von Ihrer IP-Adresse festgestellt. Daher wird die nächste Anmeldung um 30 Sekunden verzögert.", "Stay logged in" : "Angemeldet bleiben", "Forgot password?" : "Passwort vergessen?", "Back to log in" : "Zur Anmeldung wechseln", diff --git a/core/l10n/de_DE.json b/core/l10n/de_DE.json index af77f6cde8b..6dc2d76a8fc 100644 --- a/core/l10n/de_DE.json +++ b/core/l10n/de_DE.json @@ -275,6 +275,7 @@ "Username or email" : "Benutzername oder E-Mail", "Log in" : "Anmelden", "Wrong password." : "Falsches Passwort.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Es wurden mehrere ungültige Anmeldeversuche von Ihrer IP-Adresse festgestellt. Daher wird die nächste Anmeldung um 30 Sekunden verzögert.", "Stay logged in" : "Angemeldet bleiben", "Forgot password?" : "Passwort vergessen?", "Back to log in" : "Zur Anmeldung wechseln", diff --git a/core/l10n/it.js b/core/l10n/it.js index 860c3b10516..72ee0826b46 100644 --- a/core/l10n/it.js +++ b/core/l10n/it.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "Nome utente o email", "Log in" : "Accedi", "Wrong password." : "Password errata.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Abbiamo rilevato molti tentativi di autenticazione falliti dal tuo indirizzo IP. Di conseguenza il prossimo tentativo è ritardato di 30 secondi.", "Stay logged in" : "Rimani collegato", "Forgot password?" : "Hai dimenticato la password?", "Back to log in" : "Torna alla schermata di accesso", diff --git a/core/l10n/it.json b/core/l10n/it.json index 788663d83df..bed41642823 100644 --- a/core/l10n/it.json +++ b/core/l10n/it.json @@ -275,6 +275,7 @@ "Username or email" : "Nome utente o email", "Log in" : "Accedi", "Wrong password." : "Password errata.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Abbiamo rilevato molti tentativi di autenticazione falliti dal tuo indirizzo IP. Di conseguenza il prossimo tentativo è ritardato di 30 secondi.", "Stay logged in" : "Rimani collegato", "Forgot password?" : "Hai dimenticato la password?", "Back to log in" : "Torna alla schermata di accesso", diff --git a/core/l10n/ka_GE.js b/core/l10n/ka_GE.js index f2f6fd31fe7..984be98ce02 100644 --- a/core/l10n/ka_GE.js +++ b/core/l10n/ka_GE.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "მომხმარებლის სახელი ან ელ-ფოსტა", "Log in" : "შესვლა", "Wrong password." : "არასწორი პაროლი.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "თქვენი IP მისამართით შევნიშნეთ არაერთი წარუმატებელი ავტორიზაციის მცდელობა. აქედან გამომდინარე თქვენი შემდეგი ავტორიზაციის მცდელობა შეიზღუდება დაახლოებით 30 წამით.", "Stay logged in" : "ავტორიზებულად დარჩენა", "Forgot password?" : "დაგავიწყდათ პაროლი?", "Back to log in" : "უკან ავტორიზაციისკენ", diff --git a/core/l10n/ka_GE.json b/core/l10n/ka_GE.json index 840d23e0503..c3b05aa93d6 100644 --- a/core/l10n/ka_GE.json +++ b/core/l10n/ka_GE.json @@ -275,6 +275,7 @@ "Username or email" : "მომხმარებლის სახელი ან ელ-ფოსტა", "Log in" : "შესვლა", "Wrong password." : "არასწორი პაროლი.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "თქვენი IP მისამართით შევნიშნეთ არაერთი წარუმატებელი ავტორიზაციის მცდელობა. აქედან გამომდინარე თქვენი შემდეგი ავტორიზაციის მცდელობა შეიზღუდება დაახლოებით 30 წამით.", "Stay logged in" : "ავტორიზებულად დარჩენა", "Forgot password?" : "დაგავიწყდათ პაროლი?", "Back to log in" : "უკან ავტორიზაციისკენ", diff --git a/core/l10n/pt_BR.js b/core/l10n/pt_BR.js index 9557788b385..99cb9f793f9 100644 --- a/core/l10n/pt_BR.js +++ b/core/l10n/pt_BR.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "Nome de usuário ou e-mail", "Log in" : "Entrar", "Wrong password." : "Senha errada", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Detectamos várias tentativas de login inválidas de seu IP. Portanto, seu próximo login será desacelerado em até 30 segundos.", "Stay logged in" : "Permaneça logado", "Forgot password?" : "Esqueceu a senha?", "Back to log in" : "Voltar ao login", diff --git a/core/l10n/pt_BR.json b/core/l10n/pt_BR.json index 5c73007222c..96a69fec9bb 100644 --- a/core/l10n/pt_BR.json +++ b/core/l10n/pt_BR.json @@ -275,6 +275,7 @@ "Username or email" : "Nome de usuário ou e-mail", "Log in" : "Entrar", "Wrong password." : "Senha errada", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "Detectamos várias tentativas de login inválidas de seu IP. Portanto, seu próximo login será desacelerado em até 30 segundos.", "Stay logged in" : "Permaneça logado", "Forgot password?" : "Esqueceu a senha?", "Back to log in" : "Voltar ao login", diff --git a/core/l10n/ru.js b/core/l10n/ru.js index e7c4bc4ea65..00003354f41 100644 --- a/core/l10n/ru.js +++ b/core/l10n/ru.js @@ -122,6 +122,7 @@ OC.L10N.register( "Some files have not passed the integrity check. Further information on how to resolve this issue can be found in the <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">documentation</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\">List of invalid files…</a> / <a href=\"{rescanEndpoint}\">Rescan…</a>)" : "Некоторые файлы не прошли проверку целостности. Дополнительная информация о способах решения этой проблемы содержится в <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">документации</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\">Список проблемных файлов…</a> / <a href=\"{rescanEndpoint}\">Выполнить повторное сканирование…</a>)", "The PHP OPcache is not properly configured. <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">For better performance it is recommended</a> to use the following settings in the <code>php.ini</code>:" : "PHP OPcache не настроен правильно. <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">Для обеспечения лучшей производительности рекомендуется </a> задать в файле <code>php.ini</code> следующие параметры настроек:", "The PHP function \"set_time_limit\" is not available. This could result in scripts being halted mid-execution, breaking your installation. Enabling this function is strongly recommended." : "Функция PHP «set_time_limit» недоступна. В случае остановки скриптов во время работы это может привести к повреждению установки сервера Nextcloud. Настоятельно рекомендуется включить эту функцию. ", + "Your PHP does not have FreeType support, resulting in breakage of profile pictures and the settings interface." : "Установленная версия PHP не поддерживает библиотеку FreeType, что приводит к неверному отображению изображений профиля и интерфейса настроек.", "Error occurred while checking server setup" : "Произошла ошибка при проверке настроек сервера", "Your data directory and files are probably accessible from the Internet. The .htaccess file is not working. It is strongly recommended that you configure your web server so that the data directory is no longer accessible, or move the data directory outside the web server document root." : "Каталог данных и файлы, возможно, доступны из Интернета. Файл .htaccess не работает. Настоятельно рекомендуется настроить веб сервер таким образом, чтобы каталог данных не был доступен из внешней сети, либо переместить каталог данных за пределы корневого каталога веб-сервера.", "The \"{header}\" HTTP header is not set to \"{expected}\". This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly." : "Заголовок HTTP «{header}» не настроен на значение «{expected}». Это потенциальная проблема безопасности для устранения которой рекомендуется задать этот параметр.", @@ -276,6 +277,7 @@ OC.L10N.register( "Username or email" : "Имя пользователя или Email", "Log in" : "Войти", "Wrong password." : "Неправильный пароль.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "С этого IP адреса было выполнено множество неудачных попыток входа. Следующую попытку входа в систему можно будет выполнить через 30 секунд.", "Stay logged in" : "Оставаться в системе", "Forgot password?" : "Забыли пароль?", "Back to log in" : "Авторизоваться повторно", diff --git a/core/l10n/ru.json b/core/l10n/ru.json index 0e6c8086dcf..afa35516b8e 100644 --- a/core/l10n/ru.json +++ b/core/l10n/ru.json @@ -120,6 +120,7 @@ "Some files have not passed the integrity check. Further information on how to resolve this issue can be found in the <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">documentation</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\">List of invalid files…</a> / <a href=\"{rescanEndpoint}\">Rescan…</a>)" : "Некоторые файлы не прошли проверку целостности. Дополнительная информация о способах решения этой проблемы содержится в <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">документации</a>. (<a href=\"{codeIntegrityDownloadEndpoint}\">Список проблемных файлов…</a> / <a href=\"{rescanEndpoint}\">Выполнить повторное сканирование…</a>)", "The PHP OPcache is not properly configured. <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">For better performance it is recommended</a> to use the following settings in the <code>php.ini</code>:" : "PHP OPcache не настроен правильно. <a target=\"_blank\" rel=\"noreferrer noopener\" href=\"{docLink}\">Для обеспечения лучшей производительности рекомендуется </a> задать в файле <code>php.ini</code> следующие параметры настроек:", "The PHP function \"set_time_limit\" is not available. This could result in scripts being halted mid-execution, breaking your installation. Enabling this function is strongly recommended." : "Функция PHP «set_time_limit» недоступна. В случае остановки скриптов во время работы это может привести к повреждению установки сервера Nextcloud. Настоятельно рекомендуется включить эту функцию. ", + "Your PHP does not have FreeType support, resulting in breakage of profile pictures and the settings interface." : "Установленная версия PHP не поддерживает библиотеку FreeType, что приводит к неверному отображению изображений профиля и интерфейса настроек.", "Error occurred while checking server setup" : "Произошла ошибка при проверке настроек сервера", "Your data directory and files are probably accessible from the Internet. The .htaccess file is not working. It is strongly recommended that you configure your web server so that the data directory is no longer accessible, or move the data directory outside the web server document root." : "Каталог данных и файлы, возможно, доступны из Интернета. Файл .htaccess не работает. Настоятельно рекомендуется настроить веб сервер таким образом, чтобы каталог данных не был доступен из внешней сети, либо переместить каталог данных за пределы корневого каталога веб-сервера.", "The \"{header}\" HTTP header is not set to \"{expected}\". This is a potential security or privacy risk, as it is recommended to adjust this setting accordingly." : "Заголовок HTTP «{header}» не настроен на значение «{expected}». Это потенциальная проблема безопасности для устранения которой рекомендуется задать этот параметр.", @@ -274,6 +275,7 @@ "Username or email" : "Имя пользователя или Email", "Log in" : "Войти", "Wrong password." : "Неправильный пароль.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "С этого IP адреса было выполнено множество неудачных попыток входа. Следующую попытку входа в систему можно будет выполнить через 30 секунд.", "Stay logged in" : "Оставаться в системе", "Forgot password?" : "Забыли пароль?", "Back to log in" : "Авторизоваться повторно", diff --git a/core/l10n/tr.js b/core/l10n/tr.js index d9c18e41335..d09c9e8e225 100644 --- a/core/l10n/tr.js +++ b/core/l10n/tr.js @@ -277,6 +277,7 @@ OC.L10N.register( "Username or email" : "Kullanıcı adı ya da e-posta", "Log in" : "Oturum Aç", "Wrong password." : "Parola yanlış.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "IP adresinizden yapılan birden çok geçersiz oturum açma girişimi algılandı. Bu nedenle oturum açmanız 30 saniye süreyle engellendi.", "Stay logged in" : "Bağlı kal", "Forgot password?" : "Parolamı unuttum", "Back to log in" : "Oturum açmaya geri dön", diff --git a/core/l10n/tr.json b/core/l10n/tr.json index 1ef2806652b..12a958b3cf0 100644 --- a/core/l10n/tr.json +++ b/core/l10n/tr.json @@ -275,6 +275,7 @@ "Username or email" : "Kullanıcı adı ya da e-posta", "Log in" : "Oturum Aç", "Wrong password." : "Parola yanlış.", + "We have detected multiple invalid login attempts from your IP. Therefore your next login is throttled up to 30 seconds." : "IP adresinizden yapılan birden çok geçersiz oturum açma girişimi algılandı. Bu nedenle oturum açmanız 30 saniye süreyle engellendi.", "Stay logged in" : "Bağlı kal", "Forgot password?" : "Parolamı unuttum", "Back to log in" : "Oturum açmaya geri dön", diff --git a/lib/private/AllConfig.php b/lib/private/AllConfig.php index f74a2f943d5..745bab367d3 100644 --- a/lib/private/AllConfig.php +++ b/lib/private/AllConfig.php @@ -152,7 +152,7 @@ class AllConfig implements \OCP\IConfig { * @return string[] the keys stored for the app */ public function getAppKeys($appName) { - return \OC::$server->getAppConfig()->getKeys($appName); + return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName); } /** @@ -163,7 +163,7 @@ class AllConfig implements \OCP\IConfig { * @param string|float|int $value the value that should be stored */ public function setAppValue($appName, $key, $value) { - \OC::$server->getAppConfig()->setValue($appName, $key, $value); + \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value); } /** @@ -175,7 +175,7 @@ class AllConfig implements \OCP\IConfig { * @return string the saved value */ public function getAppValue($appName, $key, $default = '') { - return \OC::$server->getAppConfig()->getValue($appName, $key, $default); + return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default); } /** @@ -185,7 +185,7 @@ class AllConfig implements \OCP\IConfig { * @param string $key the key of the value, under which it was saved */ public function deleteAppValue($appName, $key) { - \OC::$server->getAppConfig()->deleteKey($appName, $key); + \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key); } /** @@ -194,7 +194,7 @@ class AllConfig implements \OCP\IConfig { * @param string $appName the appName the configs are stored under */ public function deleteAppValues($appName) { - \OC::$server->getAppConfig()->deleteApp($appName); + \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName); } diff --git a/lib/private/App/AppManager.php b/lib/private/App/AppManager.php index e7d4668931c..f2b396b29d0 100644 --- a/lib/private/App/AppManager.php +++ b/lib/private/App/AppManager.php @@ -32,10 +32,10 @@ namespace OC\App; +use OC\AppConfig; use OCP\App\AppPathNotFoundException; use OCP\App\IAppManager; use OCP\App\ManagerEvent; -use OCP\IAppConfig; use OCP\ICacheFactory; use OCP\IGroupManager; use OCP\IUser; @@ -59,7 +59,7 @@ class AppManager implements IAppManager { /** @var IUserSession */ private $userSession; - /** @var IAppConfig */ + /** @var AppConfig */ private $appConfig; /** @var IGroupManager */ @@ -82,13 +82,13 @@ class AppManager implements IAppManager { /** * @param IUserSession $userSession - * @param IAppConfig $appConfig + * @param AppConfig $appConfig * @param IGroupManager $groupManager * @param ICacheFactory $memCacheFactory * @param EventDispatcherInterface $dispatcher */ public function __construct(IUserSession $userSession, - IAppConfig $appConfig, + AppConfig $appConfig, IGroupManager $groupManager, ICacheFactory $memCacheFactory, EventDispatcherInterface $dispatcher) { diff --git a/lib/private/AppConfig.php b/lib/private/AppConfig.php index 4e102522550..59a340cb491 100644 --- a/lib/private/AppConfig.php +++ b/lib/private/AppConfig.php @@ -101,7 +101,6 @@ class AppConfig implements IAppConfig { * * @param string $app the app we are looking for * @return array an array of key names - * @deprecated 8.0.0 use method getAppKeys of \OCP\IConfig * * This function gets all keys of an app. Please note that the values are * not returned. @@ -129,7 +128,6 @@ class AppConfig implements IAppConfig { * @param string $key key * @param string $default = null, default value if the key does not exist * @return string the value or $default - * @deprecated 8.0.0 use method getAppValue of \OCP\IConfig * * This function gets a value from the appconfig table. If the key does * not exist the default value will be returned @@ -164,7 +162,6 @@ class AppConfig implements IAppConfig { * @param string $key key * @param string|float|int $value value * @return bool True if the value was inserted or updated, false if the value was the same - * @deprecated 8.0.0 use method setAppValue of \OCP\IConfig */ public function setValue($app, $key, $value) { if (!$this->hasKey($app, $key)) { @@ -220,7 +217,6 @@ class AppConfig implements IAppConfig { * @param string $app app * @param string $key key * @return boolean - * @deprecated 8.0.0 use method deleteAppValue of \OCP\IConfig */ public function deleteKey($app, $key) { $this->loadConfigValues(); @@ -242,7 +238,6 @@ class AppConfig implements IAppConfig { * * @param string $app app * @return boolean - * @deprecated 8.0.0 use method deleteAppValue of \OCP\IConfig * * Removes all keys in appconfig belonging to the app. */ diff --git a/lib/private/Installer.php b/lib/private/Installer.php index 4dcf5a8dad9..1c6c3915b41 100644 --- a/lib/private/Installer.php +++ b/lib/private/Installer.php @@ -133,7 +133,7 @@ class Installer { //install the database if(is_file($basedir.'/appinfo/database.xml')) { - if (\OC::$server->getAppConfig()->getValue($info['id'], 'installed_version') === null) { + if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) { OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml'); } else { OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml'); diff --git a/lib/private/Server.php b/lib/private/Server.php index 380ab633b8c..fb4484c72af 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -677,7 +677,7 @@ class Server extends ServerContainer implements IServerContainer { $this->registerService(AppManager::class, function (Server $c) { return new \OC\App\AppManager( $c->getUserSession(), - $c->getAppConfig(), + $c->query(\OC\AppConfig::class), $c->getGroupManager(), $c->getMemCacheFactory(), $c->getEventDispatcher() diff --git a/lib/private/Share/Share.php b/lib/private/Share/Share.php index 5a88f57fb14..f06a0998668 100644 --- a/lib/private/Share/Share.php +++ b/lib/private/Share/Share.php @@ -81,7 +81,7 @@ class Share extends Constants { * @return boolean true if backend is registered or false if error */ public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) { - if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') { + if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') { if (!isset(self::$backendTypes[$itemType])) { self::$backendTypes[$itemType] = array( 'class' => $class, @@ -540,7 +540,7 @@ class Share extends Constants { $shareWith['users'] = array_diff($userIds, array($uidOwner)); } else if ($shareType === self::SHARE_TYPE_LINK) { $updateExistingShare = false; - if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') { + if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') { // IF the password is changed via the old ajax endpoint verify it before deleting the old share if ($passwordChanged === true) { @@ -977,7 +977,7 @@ class Share extends Constants { */ public static function isResharingAllowed() { if (!isset(self::$isResharingAllowed)) { - if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') { + if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') { self::$isResharingAllowed = true; } else { self::$isResharingAllowed = false; @@ -1082,7 +1082,7 @@ class Share extends Constants { public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null, $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) { - if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') != 'yes') { + if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') { return array(); } $backend = self::getBackend($itemType); @@ -1121,7 +1121,7 @@ class Share extends Constants { $queryArgs = array($itemType); } } - if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { + if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { $where .= ' AND `share_type` != ?'; $queryArgs[] = self::SHARE_TYPE_LINK; } @@ -2144,7 +2144,7 @@ class Share extends Constants { * @return bool */ public static function shareWithGroupMembersOnly() { - $value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no'); + $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no'); return ($value === 'yes') ? true : false; } diff --git a/lib/private/legacy/app.php b/lib/private/legacy/app.php index a20a88ac08f..ea44ac8a144 100644 --- a/lib/private/legacy/app.php +++ b/lib/private/legacy/app.php @@ -298,12 +298,12 @@ class OC_App { $appData['types'] = []; } - \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes); + \OC::$server->getConfig()->setAppValue($app, 'types', $appTypes); if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) { - $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes'); + $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes'); if ($enabled !== 'yes' && $enabled !== 'no') { - \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes'); + \OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes'); } } } @@ -803,7 +803,7 @@ class OC_App { continue; } - $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no'); + $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no'); $info['groups'] = null; if ($enabled === 'yes') { $active = true; @@ -1075,7 +1075,7 @@ class OC_App { self::setAppTypes($appId); $version = \OC_App::getAppVersion($appId); - \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version); + \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version); \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent( ManagerEvent::EVENT_APP_UPDATE, $appId diff --git a/lib/private/legacy/util.php b/lib/private/legacy/util.php index ca7cc1dc5cf..776a879e731 100644 --- a/lib/private/legacy/util.php +++ b/lib/private/legacy/util.php @@ -300,8 +300,7 @@ class OC_Util { * @suppress PhanDeprecatedFunction */ public static function isPublicLinkPasswordRequired() { - $appConfig = \OC::$server->getAppConfig(); - $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no'); + $enforcePassword = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_links_password', 'no'); return ($enforcePassword === 'yes') ? true : false; } @@ -1116,7 +1115,7 @@ class OC_Util { if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) { $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url'])); } else { - $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage'); + $defaultPage = \OC::$server->getConfig()->getAppValue('core', 'defaultpage'); if ($defaultPage) { $location = $urlGenerator->getAbsoluteURL($defaultPage); } else { diff --git a/lib/public/IAppConfig.php b/lib/public/IAppConfig.php index 4a92a224840..2f268185e62 100644 --- a/lib/public/IAppConfig.php +++ b/lib/public/IAppConfig.php @@ -41,42 +41,6 @@ interface IAppConfig { public function hasKey($app, $key); /** - * Gets the config value - * @param string $app app - * @param string $key key - * @param string $default = null, default value if the key does not exist - * @return string the value or $default - * @deprecated 8.0.0 use method getAppValue of \OCP\IConfig - * - * This function gets a value from the appconfig table. If the key does - * not exist the default value will be returned - * @since 7.0.0 - */ - public function getValue($app, $key, $default = null); - - /** - * Deletes a key - * @param string $app app - * @param string $key key - * @return bool - * @deprecated 8.0.0 use method deleteAppValue of \OCP\IConfig - * @since 7.0.0 - */ - public function deleteKey($app, $key); - - /** - * Get the available keys for an app - * @param string $app the app we are looking for - * @return array an array of key names - * @deprecated 8.0.0 use method getAppKeys of \OCP\IConfig - * - * This function gets all keys of an app. Please note that the values are - * not returned. - * @since 7.0.0 - */ - public function getKeys($app); - - /** * get multiply values, either the app or key can be used as wildcard by setting it to false * * @param string|false $key @@ -96,19 +60,6 @@ interface IAppConfig { public function getFilteredValues($app); /** - * sets a value in the appconfig - * @param string $app app - * @param string $key key - * @param string|float|int $value value - * @deprecated 8.0.0 use method setAppValue of \OCP\IConfig - * - * Sets a value. If the key did not exist before it will be created. - * @return void - * @since 7.0.0 - */ - public function setValue($app, $key, $value); - - /** * Get all apps using the config * @return array an array of app ids * @@ -117,15 +68,4 @@ interface IAppConfig { * @since 7.0.0 */ public function getApps(); - - /** - * Remove app from appconfig - * @param string $app app - * @return bool - * @deprecated 8.0.0 use method deleteAppValue of \OCP\IConfig - * - * Removes all keys in appconfig belonging to the app. - * @since 7.0.0 - */ - public function deleteApp($app); } diff --git a/settings/ajax/setquota.php b/settings/ajax/setquota.php index 481f0853f96..c3fde409c00 100644 --- a/settings/ajax/setquota.php +++ b/settings/ajax/setquota.php @@ -71,7 +71,7 @@ if($username) { if($quota === 'default') {//'default' as default quota makes no sense $quota='none'; } - \OC::$server->getAppConfig()->setValue('files', 'default_quota', $quota); + \OC::$server->getConfig()->setAppValue('files', 'default_quota', $quota); } OC_JSON::success(array("data" => array( "username" => $username , 'quota' => $quota))); diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index c361db7b76b..35650054105 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -10,6 +10,7 @@ namespace Test\App; use OC\App\AppManager; +use OC\AppConfig; use OC\Group\Group; use OC\User\User; use OCP\App\AppPathNotFoundException; @@ -31,11 +32,11 @@ use Test\TestCase; */ class AppManagerTest extends TestCase { /** - * @return IAppConfig|\PHPUnit_Framework_MockObject_MockObject + * @return AppConfig|\PHPUnit_Framework_MockObject_MockObject */ protected function getAppConfig() { $appConfig = array(); - $config = $this->createMock(IAppConfig::class); + $config = $this->createMock(AppConfig::class); $config->expects($this->any()) ->method('getValue') @@ -75,7 +76,7 @@ class AppManagerTest extends TestCase { /** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject */ protected $groupManager; - /** @var IAppConfig|\PHPUnit_Framework_MockObject_MockObject */ + /** @var AppConfig|\PHPUnit_Framework_MockObject_MockObject */ protected $appConfig; /** @var ICache|\PHPUnit_Framework_MockObject_MockObject */ diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 620e9344c43..d10ad387599 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -542,7 +542,7 @@ class AppTest extends \Test\TestCase { * * @param IAppConfig $appConfig app config mock */ - private function registerAppConfig(IAppConfig $appConfig) { + private function registerAppConfig(AppConfig $appConfig) { $this->overwriteService('AppConfig', $appConfig); $this->overwriteService('AppManager', new \OC\App\AppManager( \OC::$server->getUserSession(), diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index 33d5cc0a8a6..627eb71d6bf 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -284,11 +284,11 @@ class ViewTest extends \Test\TestCase { // Reset sharing disabled for users cache self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); - $appConfig = \OC::$server->getAppConfig(); - $oldExcludeGroupsFlag = $appConfig->getValue('core', 'shareapi_exclude_groups', 'no'); - $oldExcludeGroupsList = $appConfig->getValue('core', 'shareapi_exclude_groups_list', ''); - $appConfig->setValue('core', 'shareapi_exclude_groups', $excludeGroups); - $appConfig->setValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList); + $config = \OC::$server->getConfig(); + $oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no'); + $oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', ''); + $config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups); + $config->setAppValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList); $storage1 = $this->getTestStorage(); $storage2 = $this->getTestStorage(); @@ -303,8 +303,8 @@ class ViewTest extends \Test\TestCase { $folderContent = $view->getDirectoryContent('mount'); $this->assertEquals($expectedShareable, $folderContent[0]->isShareable()); - $appConfig->setValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag); - $appConfig->setValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList); + $config->setAppValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag); + $config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList); // Reset sharing disabled for users cache self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]); diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index e93b0f553cd..18d1944f193 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -103,8 +103,8 @@ class ShareTest extends \Test\TestCase { \OC\Share\Share::registerBackend('test', 'Test\Share\Backend'); \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(); - $this->resharing = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes'); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', 'yes'); + $this->resharing = \OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes'); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_allow_resharing', 'yes'); // 20 Minutes in the past, 20 minutes in the future. $now = time(); @@ -116,7 +116,7 @@ class ShareTest extends \Test\TestCase { protected function tearDown() { $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?'); $query->execute(array('test')); - \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', $this->resharing); + \OC::$server->getConfig()->setAppValue('core', 'shareapi_allow_resharing', $this->resharing); $this->user1->delete(); $this->user2->delete(); |