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
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018, Joas Schilling <coding@schilljs.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 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 OCA\UpdateNotification\AppInfo;
use OCA\UpdateNotification\Notification\Notifier;
use OCA\UpdateNotification\UpdateChecker;
use OCP\App\IAppManager;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\AppFramework\IAppContainer;
use OCP\AppFramework\QueryException;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserSession;
use OCP\Util;
use Psr\Log\LoggerInterface;
class Application extends App implements IBootstrap {
public function __construct() {
parent::__construct('updatenotification', []);
}
public function register(IRegistrationContext $context): void {
$context->registerNotifierService(Notifier::class);
}
public function boot(IBootContext $context): void {
$context->injectFn(function (IConfig $config,
IUserSession $userSession,
IAppManager $appManager,
IGroupManager $groupManager,
IAppContainer $appContainer,
LoggerInterface $logger) {
if ($config->getSystemValue('updatechecker', true) !== true) {
// Updater check is disabled
return;
}
$user = $userSession->getUser();
if (!$user instanceof IUser) {
// Nothing to do for guests
return;
}
if (!$appManager->isEnabledForUser('notifications') &&
$groupManager->isAdmin($user->getUID())) {
try {
$updateChecker = $appContainer->get(UpdateChecker::class);
} catch (QueryException $e) {
$logger->error($e->getMessage(), ['exception' => $e]);
return;
}
if ($updateChecker->getUpdateState() !== []) {
Util::addScript('updatenotification', 'legacy-notification');
\OC_Hook::connect('\OCP\Config', 'js', $updateChecker, 'populateJavaScriptVariables');
}
}
});
}
}
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018, Tobia De Koninck (tobia@ledfan.be)
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author J0WI <J0WI@users.noreply.github.com>
* @author Joas Schilling <coding@schilljs.com>
* @author Tobia De Koninck <LEDfan@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 OCA\UpdateNotification\Command;
use OC\App\AppManager;
use OC\Installer;
use OCA\UpdateNotification\UpdateChecker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Check extends Command {
/**
* @var Installer $installer
*/
private $installer;
/**
* @var AppManager $appManager
*/
private $appManager;
/**
* @var UpdateChecker $updateChecker
*/
private $updateChecker;
public function __construct(AppManager $appManager, UpdateChecker $updateChecker, Installer $installer) {
parent::__construct();
$this->installer = $installer;
$this->appManager = $appManager;
$this->updateChecker = $updateChecker;
}
protected function configure(): void {
$this
->setName('update:check')
->setDescription('Check for server and app updates')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$updatesAvailableCount = 0;
// Server
$r = $this->updateChecker->getUpdateState();
if (isset($r['updateAvailable']) && $r['updateAvailable']) {
$output->writeln($r['updateVersionString'] . ' is available. Get more information on how to update at '. $r['updateLink'] . '.');
$updatesAvailableCount += 1;
}
// Apps
$apps = $this->appManager->getInstalledApps();
foreach ($apps as $app) {
$update = $this->installer->isUpdateAvailable($app);
if ($update !== false) {
$output->writeln('Update for ' . $app . ' to version ' . $update . ' is available.');
$updatesAvailableCount += 1;
}
}
// Report summary
if ($updatesAvailableCount === 0) {
$output->writeln('<info>Everything up to date</info>');
} elseif ($updatesAvailableCount === 1) {
$output->writeln('<comment>1 update available</comment>');
} else {
$output->writeln('<comment>' . $updatesAvailableCount . ' updates available</comment>');
}
return 0;
}
}
@@ -0,0 +1,181 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2017 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 OCA\UpdateNotification\Controller;
use OC\App\AppStore\Fetcher\AppFetcher;
use OCA\UpdateNotification\ResponseDefinitions;
use OCP\App\AppPathNotFoundException;
use OCP\App\IAppManager;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\L10N\IFactory;
/**
* @psalm-import-type UpdateNotificationApp from ResponseDefinitions
*/
class APIController extends OCSController {
/** @var IConfig */
protected $config;
/** @var IAppManager */
protected $appManager;
/** @var AppFetcher */
protected $appFetcher;
/** @var IFactory */
protected $l10nFactory;
/** @var IUserSession */
protected $userSession;
/** @var string */
protected $language;
/**
* List of apps that were in the appstore but are now shipped and don't have
* a compatible update available.
*
* @var array<string, int>
*/
protected array $appsShippedInFutureVersion = [
'bruteforcesettings' => 25,
'suspicious_login' => 25,
'twofactor_totp' => 25,
];
public function __construct(string $appName,
IRequest $request,
IConfig $config,
IAppManager $appManager,
AppFetcher $appFetcher,
IFactory $l10nFactory,
IUserSession $userSession) {
parent::__construct($appName, $request);
$this->config = $config;
$this->appManager = $appManager;
$this->appFetcher = $appFetcher;
$this->l10nFactory = $l10nFactory;
$this->userSession = $userSession;
}
/**
* List available updates for apps
*
* @param string $newVersion Server version to check updates for
*
* @return DataResponse<Http::STATUS_OK, array{missing: UpdateNotificationApp[], available: UpdateNotificationApp[]}, array{}>|DataResponse<Http::STATUS_NOT_FOUND, array{appstore_disabled: bool, already_on_latest?: bool}, array{}>
*
* 200: Apps returned
* 404: New versions not found
*/
public function getAppList(string $newVersion): DataResponse {
if (!$this->config->getSystemValue('appstoreenabled', true)) {
return new DataResponse([
'appstore_disabled' => true,
], Http::STATUS_NOT_FOUND);
}
// Get list of installed custom apps
$installedApps = $this->appManager->getInstalledApps();
$installedApps = array_filter($installedApps, function ($app) {
try {
$this->appManager->getAppPath($app);
} catch (AppPathNotFoundException $e) {
return false;
}
return !$this->appManager->isShipped($app) && !isset($this->appsShippedInFutureVersion[$app]);
});
if (empty($installedApps)) {
return new DataResponse([
'missing' => [],
'available' => [],
]);
}
$this->appFetcher->setVersion($newVersion, 'future-apps.json', false);
// Apps available on the app store for that version
$availableApps = array_map(static function (array $app) {
return $app['id'];
}, $this->appFetcher->get());
if (empty($availableApps)) {
return new DataResponse([
'appstore_disabled' => false,
'already_on_latest' => false,
], Http::STATUS_NOT_FOUND);
}
$this->language = $this->l10nFactory->getUserLanguage($this->userSession->getUser());
// Ignore apps that are deployed from git
$installedApps = array_filter($installedApps, function (string $appId) {
try {
return !file_exists($this->appManager->getAppPath($appId) . '/.git');
} catch (AppPathNotFoundException $e) {
return true;
}
});
$missing = array_diff($installedApps, $availableApps);
$missing = array_map([$this, 'getAppDetails'], $missing);
sort($missing);
$available = array_intersect($installedApps, $availableApps);
$available = array_map([$this, 'getAppDetails'], $available);
sort($available);
return new DataResponse([
'missing' => $missing,
'available' => $available,
]);
}
/**
* Get translated app name
*
* @param string $appId
* @return UpdateNotificationApp
*/
protected function getAppDetails(string $appId): array {
$app = $this->appManager->getAppInfo($appId, false, $this->language);
/** @var ?string $name */
$name = $app['name'];
return [
'appId' => $appId,
'appName' => $name ?? $appId,
];
}
}
@@ -0,0 +1,110 @@
<?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>
* @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 OCA\UpdateNotification\Controller;
use OCA\UpdateNotification\ResetTokenBackgroundJob;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\Security\ISecureRandom;
use OCP\Util;
class AdminController extends Controller {
/** @var IJobList */
private $jobList;
/** @var ISecureRandom */
private $secureRandom;
/** @var IConfig */
private $config;
/** @var ITimeFactory */
private $timeFactory;
/** @var IL10N */
private $l10n;
/**
* @param string $appName
* @param IRequest $request
* @param IJobList $jobList
* @param ISecureRandom $secureRandom
* @param IConfig $config
* @param ITimeFactory $timeFactory
* @param IL10N $l10n
*/
public function __construct($appName,
IRequest $request,
IJobList $jobList,
ISecureRandom $secureRandom,
IConfig $config,
ITimeFactory $timeFactory,
IL10N $l10n) {
parent::__construct($appName, $request);
$this->jobList = $jobList;
$this->secureRandom = $secureRandom;
$this->config = $config;
$this->timeFactory = $timeFactory;
$this->l10n = $l10n;
}
private function isUpdaterEnabled() {
return !$this->config->getSystemValue('upgrade.disable-web', false);
}
/**
* @param string $channel
* @return DataResponse
*/
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')]]);
}
/**
* @return DataResponse
*/
public function createCredentials(): DataResponse {
if (!$this->isUpdaterEnabled()) {
return new DataResponse(['status' => 'error', 'message' => $this->l10n->t('Web updater is disabled')], Http::STATUS_FORBIDDEN);
}
// Create a new job and store the creation date
$this->jobList->add(ResetTokenBackgroundJob::class);
$this->config->setAppValue('core', 'updater.secret.created', (string)$this->timeFactory->getTime());
// Create a new token
$newToken = $this->secureRandom->generate(64);
$this->config->setSystemValue('updater.secret', password_hash($newToken, PASSWORD_DEFAULT));
return new DataResponse($newToken);
}
}
@@ -0,0 +1,254 @@
<?php
declare(strict_types=1);
/**
* @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 OCA\UpdateNotification\Notification;
use OC\Installer;
use OC\Updater\VersionCheck;
use OCP\App\IAppManager;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\Notification\IManager;
class BackgroundJob extends TimedJob {
protected $connectionNotifications = [3, 7, 14, 30];
/** @var string[] */
protected $users;
public function __construct(
ITimeFactory $timeFactory,
protected IConfig $config,
protected IManager $notificationManager,
protected IGroupManager $groupManager,
protected IAppManager $appManager,
protected Installer $installer,
protected VersionCheck $versionCheck,
) {
parent::__construct($timeFactory);
// Run once a day
$this->setInterval(60 * 60 * 24);
}
protected function run($argument) {
// Do not check for updates if not connected to the internet
if (!$this->config->getSystemValueBool('has_internet_connection', true)) {
return;
}
if (\OC::$CLI && !$this->config->getSystemValueBool('debug', false)) {
try {
// Jitter the pinging of the updater server and the appstore a bit.
// Otherwise all Nextcloud installations are pinging the servers
// in one of 288
sleep(random_int(1, 180));
} catch (\Exception $e) {
}
}
$this->checkCoreUpdate();
$this->checkAppUpdates();
}
/**
* Check for ownCloud update
*/
protected function checkCoreUpdate() {
if (\in_array($this->getChannel(), ['daily', 'git'], true)) {
// "These aren't the update channels you're looking for." - Ben Obi-Wan Kenobi
return;
}
$status = $this->versionCheck->check();
if ($status === false) {
$errors = 1 + (int) $this->config->getAppValue('updatenotification', 'update_check_errors', '0');
$this->config->setAppValue('updatenotification', 'update_check_errors', (string) $errors);
if (\in_array($errors, $this->connectionNotifications, true)) {
$this->sendErrorNotifications($errors);
}
} elseif (\is_array($status)) {
$this->config->setAppValue('updatenotification', 'update_check_errors', '0');
$this->clearErrorNotifications();
if (isset($status['version'])) {
$this->createNotifications('core', $status['version'], $status['versionstring']);
}
}
}
/**
* Send a message to the admin when the update server could not be reached
* @param int $numDays
*/
protected function sendErrorNotifications($numDays) {
$this->clearErrorNotifications();
$notification = $this->notificationManager->createNotification();
try {
$notification->setApp('updatenotification')
->setDateTime(new \DateTime())
->setObject('updatenotification', 'error')
->setSubject('connection_error', ['days' => $numDays]);
foreach ($this->getUsersToNotify() as $uid) {
$notification->setUser($uid);
$this->notificationManager->notify($notification);
}
} catch (\InvalidArgumentException $e) {
return;
}
}
/**
* Remove error notifications again
*/
protected function clearErrorNotifications() {
$notification = $this->notificationManager->createNotification();
try {
$notification->setApp('updatenotification')
->setSubject('connection_error')
->setObject('updatenotification', 'error');
} catch (\InvalidArgumentException $e) {
return;
}
$this->notificationManager->markProcessed($notification);
}
/**
* Check all installed apps for updates
*/
protected function checkAppUpdates() {
$apps = $this->appManager->getInstalledApps();
foreach ($apps as $app) {
$update = $this->isUpdateAvailable($app);
if ($update !== false) {
$this->createNotifications($app, $update);
}
}
}
/**
* Create notifications for this app version
*
* @param string $app
* @param string $version
* @param string $visibleVersion
*/
protected function createNotifications($app, $version, $visibleVersion = '') {
$lastNotification = $this->config->getAppValue('updatenotification', $app, false);
if ($lastNotification === $version) {
// We already notified about this update
return;
}
if ($lastNotification !== false) {
// Delete old updates
$this->deleteOutdatedNotifications($app, $lastNotification);
}
$notification = $this->notificationManager->createNotification();
try {
$notification->setApp('updatenotification')
->setDateTime(new \DateTime())
->setObject($app, $version);
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);
}
/**
* @return string[]
*/
protected function getUsersToNotify(): array {
if ($this->users !== null) {
return $this->users;
}
$notifyGroups = (array) json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true);
$this->users = [];
foreach ($notifyGroups as $group) {
$groupToNotify = $this->groupManager->get($group);
if ($groupToNotify instanceof IGroup) {
foreach ($groupToNotify->getUsers() as $user) {
$this->users[$user->getUID()] = true;
}
}
}
$this->users = array_keys($this->users);
return $this->users;
}
/**
* Delete notifications for old updates
*
* @param string $app
* @param string $version
*/
protected function deleteOutdatedNotifications($app, $version) {
$notification = $this->notificationManager->createNotification();
try {
$notification->setApp('updatenotification')
->setObject($app, $version);
} catch (\InvalidArgumentException $e) {
return;
}
$this->notificationManager->markProcessed($notification);
}
/**
* @return string
*/
protected function getChannel(): string {
return \OC_Util::getChannel();
}
/**
* @param string $app
* @return string|false
*/
protected function isUpdateAvailable($app) {
return $this->installer->isUpdateAvailable($app);
}
}
@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Härtl <jus@bitgrid.net>
* @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 OCA\UpdateNotification\Notification;
use OCP\App\IAppManager;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Notification\AlreadyProcessedException;
use OCP\Notification\IManager;
use OCP\Notification\INotification;
use OCP\Notification\INotifier;
use OCP\Util;
class Notifier implements INotifier {
/** @var IURLGenerator */
protected $url;
/** @var IConfig */
protected $config;
/** @var IManager */
protected $notificationManager;
/** @var IFactory */
protected $l10NFactory;
/** @var IUserSession */
protected $userSession;
/** @var IGroupManager */
protected $groupManager;
/** @var string[] */
protected $appVersions;
/**
* Notifier constructor.
*
* @param IURLGenerator $url
* @param IConfig $config
* @param IManager $notificationManager
* @param IFactory $l10NFactory
* @param IUserSession $userSession
* @param IGroupManager $groupManager
*/
public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) {
$this->url = $url;
$this->notificationManager = $notificationManager;
$this->config = $config;
$this->l10NFactory = $l10NFactory;
$this->userSession = $userSession;
$this->groupManager = $groupManager;
$this->appVersions = $this->getAppVersions();
}
/**
* Identifier of the notifier, only use [a-z0-9_]
*
* @return string
* @since 17.0.0
*/
public function getID(): string {
return 'updatenotification';
}
/**
* Human readable name describing the notifier
*
* @return string
* @since 17.0.0
*/
public function getName(): string {
return $this->l10NFactory->get('updatenotification')->t('Update notifications');
}
/**
* @param INotification $notification
* @param string $languageCode The code of the language that should be used to prepare the notification
* @return INotification
* @throws \InvalidArgumentException When the notification was not prepared by a notifier
* @throws AlreadyProcessedException When the notification is not needed anymore and should be deleted
* @since 9.0.0
*/
public function prepare(INotification $notification, string $languageCode): INotification {
if ($notification->getApp() !== 'updatenotification') {
throw new \InvalidArgumentException('Unknown app id');
}
$l = $this->l10NFactory->get('updatenotification', $languageCode);
if ($notification->getSubject() === 'connection_error') {
$errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', '0');
if ($errors === 0) {
$this->notificationManager->markProcessed($notification);
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]))
->setParsedMessage($l->t('Please check the Nextcloud and server log files for errors.'));
} elseif ($notification->getObjectType() === 'core') {
$this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions());
$parameters = $notification->getSubjectParameters();
$notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']]))
->setRichSubject($l->t('Update to {serverAndVersion} is available.'), [
'serverAndVersion' => [
'type' => 'highlight',
'id' => $notification->getObjectType(),
'name' => $parameters['version'],
]
]);
if ($this->isAdmin()) {
$notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index', ['section' => 'overview']) . '#version');
}
} else {
$appInfo = $this->getAppInfo($notification->getObjectType(), $languageCode);
$appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name'];
if (isset($this->appVersions[$notification->getObjectType()])) {
$this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]);
}
$notification->setRichSubject($l->t('Update for {app} to version %s is available.', [$notification->getObjectId()]), [
'app' => [
'type' => 'app',
'id' => $notification->getObjectType(),
'name' => $appName,
]
]);
if ($this->isAdmin()) {
$notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps', ['category' => 'updates']) . '#app-' . $notification->getObjectType());
}
}
$notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg')));
return $notification;
}
/**
* Remove the notification and prevent rendering, when the update is installed
*
* @param INotification $notification
* @param string $installedVersion
* @throws AlreadyProcessedException When the update is already installed
*/
protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) {
if (version_compare($notification->getObjectId(), $installedVersion, '<=')) {
throw new AlreadyProcessedException();
}
}
/**
* @return bool
*/
protected function isAdmin(): bool {
$user = $this->userSession->getUser();
if ($user instanceof IUser) {
return $this->groupManager->isAdmin($user->getUID());
}
return false;
}
protected function getCoreVersions(): string {
return implode('.', Util::getVersion());
}
protected function getAppVersions(): array {
return \OC_App::getAppVersions();
}
protected function getAppInfo($appId, $languageCode) {
return \OCP\Server::get(IAppManager::class)->getAppInfo($appId, false, $languageCode);
}
}
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/**
* @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>
*
* @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;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use OCP\IConfig;
/**
* Class ResetTokenBackgroundJob deletes any configured token all 24 hours for
*
*
* @package OCA\UpdateNotification
*/
class ResetTokenBackgroundJob extends TimedJob {
/** @var IConfig */
private $config;
/** @var ITimeFactory */
private $timeFactory;
/**
* @param IConfig $config
* @param ITimeFactory $timeFactory
*/
public function __construct(IConfig $config,
ITimeFactory $timeFactory) {
parent::__construct($timeFactory);
// Run all 10 minutes
parent::setInterval(60 * 10);
$this->config = $config;
$this->timeFactory = $timeFactory;
}
/**
* @param $argument
*/
protected function run($argument) {
// Delete old tokens after 2 days
if ($this->config->getSystemValueBool('config_is_read_only') === false && $this->timeFactory->getTime() - (int) $this->config->getAppValue('core', 'updater.secret.created', (string) $this->timeFactory->getTime()) >= 172800) {
$this->config->deleteSystemValue('updater.secret');
}
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2023 Kate Döen <kate.doeen@nextcloud.com>
*
* @author Kate Döen <kate.doeen@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 OCA\UpdateNotification;
/**
* @psalm-type UpdateNotificationApp = array{
* appId: string,
* appName: string,
* }
*/
class ResponseDefinitions {
}
@@ -0,0 +1,204 @@
<?php
declare(strict_types=1);
/**
* @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 Julius Härtl <jus@bitgrid.net>
* @author Morris Jobke <hey@morrisjobke.de>
* @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 OCA\UpdateNotification\Settings;
use OC\User\Backend;
use OCA\UpdateNotification\UpdateChecker;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\IConfig;
use OCP\IDateTimeFormatter;
use OCP\IGroupManager;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Settings\ISettings;
use OCP\Support\Subscription\IRegistry;
use OCP\User\Backend\ICountUsersBackend;
use OCP\Util;
use Psr\Log\LoggerInterface;
class Admin implements ISettings {
private IConfig $config;
private UpdateChecker $updateChecker;
private IGroupManager $groupManager;
private IDateTimeFormatter $dateTimeFormatter;
private IFactory $l10nFactory;
private IRegistry $subscriptionRegistry;
private IUserManager $userManager;
private LoggerInterface $logger;
private IInitialState $initialState;
public function __construct(
IConfig $config,
UpdateChecker $updateChecker,
IGroupManager $groupManager,
IDateTimeFormatter $dateTimeFormatter,
IFactory $l10nFactory,
IRegistry $subscriptionRegistry,
IUserManager $userManager,
LoggerInterface $logger,
IInitialState $initialState
) {
$this->config = $config;
$this->updateChecker = $updateChecker;
$this->groupManager = $groupManager;
$this->dateTimeFormatter = $dateTimeFormatter;
$this->l10nFactory = $l10nFactory;
$this->subscriptionRegistry = $subscriptionRegistry;
$this->userManager = $userManager;
$this->logger = $logger;
$this->initialState = $initialState;
}
public function getForm(): TemplateResponse {
$lastUpdateCheckTimestamp = (int)$this->config->getAppValue('core', 'lastupdatedat');
$lastUpdateCheck = $this->dateTimeFormatter->formatDateTime($lastUpdateCheckTimestamp);
$channels = [
'daily',
'beta',
'stable',
'production',
];
$currentChannel = Util::getChannel();
if ($currentChannel === 'git') {
$channels[] = 'git';
}
$updateState = $this->updateChecker->getUpdateState();
$notifyGroups = json_decode($this->config->getAppValue('updatenotification', 'notify_groups', '["admin"]'), true);
$defaultUpdateServerURL = 'https://updates.nextcloud.com/updater_server/';
$updateServerURL = $this->config->getSystemValue('updater.server.url', $defaultUpdateServerURL);
$defaultCustomerUpdateServerURLPrefix = 'https://updates.nextcloud.com/customers/';
$isDefaultUpdateServerURL = $updateServerURL === $defaultUpdateServerURL
|| strpos($updateServerURL, $defaultCustomerUpdateServerURLPrefix) === 0;
$hasValidSubscription = $this->subscriptionRegistry->delegateHasValidSubscription();
$params = [
'isNewVersionAvailable' => !empty($updateState['updateAvailable']),
'isUpdateChecked' => $lastUpdateCheckTimestamp > 0,
'lastChecked' => $lastUpdateCheck,
'currentChannel' => $currentChannel,
'channels' => $channels,
'newVersion' => empty($updateState['updateVersion']) ? '' : $updateState['updateVersion'],
'newVersionString' => empty($updateState['updateVersionString']) ? '' : $updateState['updateVersionString'],
'downloadLink' => empty($updateState['downloadLink']) ? '' : $updateState['downloadLink'],
'changes' => $this->filterChanges($updateState['changes'] ?? []),
'webUpdaterEnabled' => !$this->config->getSystemValue('upgrade.disable-web', false),
'isWebUpdaterRecommended' => $this->isWebUpdaterRecommended(),
'updaterEnabled' => empty($updateState['updaterEnabled']) ? false : $updateState['updaterEnabled'],
'versionIsEol' => empty($updateState['versionIsEol']) ? false : $updateState['versionIsEol'],
'isDefaultUpdateServerURL' => $isDefaultUpdateServerURL,
'updateServerURL' => $updateServerURL,
'notifyGroups' => $this->getSelectedGroups($notifyGroups),
'hasValidSubscription' => $hasValidSubscription,
];
$this->initialState->provideInitialState('data', $params);
return new TemplateResponse('updatenotification', 'admin', [], '');
}
protected function filterChanges(array $changes): array {
$filtered = [];
if (isset($changes['changelogURL'])) {
$filtered['changelogURL'] = $changes['changelogURL'];
}
if (!isset($changes['whatsNew'])) {
return $filtered;
}
$iterator = $this->l10nFactory->getLanguageIterator();
do {
$lang = $iterator->current();
if (isset($changes['whatsNew'][$lang])) {
$filtered['whatsNew'] = $changes['whatsNew'][$lang];
return $filtered;
}
$iterator->next();
} while ($lang !== 'en' && $iterator->valid());
return $filtered;
}
/**
* @param list<string> $groupIds
* @return list<array{id: string, displayname: string}>
*/
protected function getSelectedGroups(array $groupIds): array {
$result = [];
foreach ($groupIds as $groupId) {
$group = $this->groupManager->get($groupId);
if ($group === null) {
continue;
}
$result[] = ['id' => $group->getGID(), 'displayname' => $group->getDisplayName()];
}
return $result;
}
public function getSection(): string {
return 'overview';
}
public function getPriority(): int {
return 11;
}
private function isWebUpdaterRecommended(): bool {
return $this->getUserCount() < 100;
}
/**
* @see https://github.com/nextcloud/server/blob/39494fbf794d982f6f6551c984e6ca4c4e947d01/lib/private/Support/Subscription/Registry.php#L188-L216 implementation reference
*/
private function getUserCount(): int {
$userCount = 0;
$backends = $this->userManager->getBackends();
foreach ($backends as $backend) {
// TODO: change below to 'if ($backend instanceof ICountUsersBackend) {'
if ($backend->implementsActions(Backend::COUNT_USERS)) {
/** @var ICountUsersBackend $backend */
$backendUsers = $backend->countUsers();
if ($backendUsers !== false) {
$userCount += $backendUsers;
}
}
}
return $userCount;
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
/**
* @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 Lukas Reschke <lukas@statuscode.ch>
* @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 OCA\UpdateNotification;
use OC\Updater\ChangesCheck;
use OC\Updater\VersionCheck;
class UpdateChecker {
/** @var VersionCheck */
private $updater;
/** @var ChangesCheck */
private $changesCheck;
/**
* @param VersionCheck $updater
*/
public function __construct(VersionCheck $updater, ChangesCheck $changesCheck) {
$this->updater = $updater;
$this->changesCheck = $changesCheck;
}
/**
* @return array
*/
public function getUpdateState(): array {
$data = $this->updater->check();
$result = [];
if (isset($data['version']) && $data['version'] !== '' && $data['version'] !== []) {
$result['updateAvailable'] = true;
$result['updateVersion'] = $data['version'];
$result['updateVersionString'] = $data['versionstring'];
$result['updaterEnabled'] = $data['autoupdater'] === '1';
$result['versionIsEol'] = $data['eol'] === '1';
if (strpos($data['web'], 'https://') === 0) {
$result['updateLink'] = $data['web'];
}
if (strpos($data['url'], 'https://') === 0) {
$result['downloadLink'] = $data['url'];
}
if (strpos($data['changes'], 'https://') === 0) {
try {
$result['changes'] = $this->changesCheck->check($data['changes'], $data['version']);
} catch (\Exception $e) {
// no info, not a problem
}
}
return $result;
}
return [];
}
/**
* @param array $data
*/
public function populateJavaScriptVariables(array $data) {
$data['array']['oc_updateState'] = json_encode([
'updateAvailable' => true,
'updateVersion' => $this->getUpdateState()['updateVersionString'],
'updateLink' => $this->getUpdateState()['updateLink'] ?? '',
]);
}
}