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,200 @@
<?php
/**
* @copyright Copyright (c) 2016 Julius Haertl <jus@bitgrid.net>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Haertl <jus@bitgrid.net>
* @author Julius Härtl <jus@bitgrid.net>
* @author Michael Weimann <mail@michael-weimann.eu>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @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\Theming\Controller;
use OC\IntegrityCheck\Helpers\FileAccessHelper;
use OCA\Theming\IconBuilder;
use OCA\Theming\ImageManager;
use OCA\Theming\ThemingDefaults;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataDisplayResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\Http\Response;
use OCP\Files\NotFoundException;
use OCP\IRequest;
class IconController extends Controller {
/** @var ThemingDefaults */
private $themingDefaults;
/** @var IconBuilder */
private $iconBuilder;
/** @var ImageManager */
private $imageManager;
/** @var FileAccessHelper */
private $fileAccessHelper;
/** @var IAppManager */
private $appManager;
public function __construct(
$appName,
IRequest $request,
ThemingDefaults $themingDefaults,
IconBuilder $iconBuilder,
ImageManager $imageManager,
FileAccessHelper $fileAccessHelper,
IAppManager $appManager
) {
parent::__construct($appName, $request);
$this->themingDefaults = $themingDefaults;
$this->iconBuilder = $iconBuilder;
$this->imageManager = $imageManager;
$this->fileAccessHelper = $fileAccessHelper;
$this->appManager = $appManager;
}
/**
* @PublicPage
* @NoCSRFRequired
*
* Get a themed icon
*
* @param string $app ID of the app
* @param string $image image file name (svg required)
* @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: 'image/svg+xml'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
* @throws \Exception
*
* 200: Themed icon returned
* 404: Themed icon not found
*/
public function getThemedIcon(string $app, string $image): Response {
if ($app !== 'core' && !$this->appManager->isEnabledForUser($app)) {
$app = 'core';
$image = 'favicon.png';
}
$color = $this->themingDefaults->getColorPrimary();
try {
$iconFileName = $this->imageManager->getCachedImage('icon-' . $app . '-' . $color . str_replace('/', '_', $image));
} catch (NotFoundException $exception) {
$icon = $this->iconBuilder->colorSvg($app, $image);
if ($icon === false || $icon === '') {
return new NotFoundResponse();
}
$iconFileName = $this->imageManager->setCachedImage('icon-' . $app . '-' . $color . str_replace('/', '_', $image), $icon);
}
$response = new FileDisplayResponse($iconFileName, Http::STATUS_OK, ['Content-Type' => 'image/svg+xml']);
$response->cacheFor(86400, false, true);
return $response;
}
/**
* Return a 32x32 favicon as png
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $app ID of the app
* @return DataDisplayResponse<Http::STATUS_OK, array{Content-Type: 'image/x-icon'}>|FileDisplayResponse<Http::STATUS_OK, array{Content-Type: 'image/x-icon'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
* @throws \Exception
*
* 200: Favicon returned
* 404: Favicon not found
*/
public function getFavicon(string $app = 'core'): Response {
if ($app !== 'core' && !$this->appManager->isEnabledForUser($app)) {
$app = 'core';
}
$response = null;
$iconFile = null;
try {
$iconFile = $this->imageManager->getImage('favicon', false);
$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
} catch (NotFoundException $e) {
}
if ($iconFile === null && $this->imageManager->shouldReplaceIcons()) {
$color = $this->themingDefaults->getColorPrimary();
try {
$iconFile = $this->imageManager->getCachedImage('favIcon-' . $app . $color);
} catch (NotFoundException $exception) {
$icon = $this->iconBuilder->getFavicon($app);
if ($icon === false || $icon === '') {
return new NotFoundResponse();
}
$iconFile = $this->imageManager->setCachedImage('favIcon-' . $app . $color, $icon);
}
$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
}
if ($response === null) {
$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon.png';
$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
}
$response->cacheFor(86400);
return $response;
}
/**
* Return a 512x512 icon for touch devices
*
* @PublicPage
* @NoCSRFRequired
*
* @param string $app ID of the app
* @return DataDisplayResponse<Http::STATUS_OK, array{Content-Type: 'image/png'}>|FileDisplayResponse<Http::STATUS_OK, array{Content-Type: 'image/x-icon'|'image/png'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
* @throws \Exception
*
* 200: Touch icon returned
* 404: Touch icon not found
*/
public function getTouchIcon(string $app = 'core'): Response {
if ($app !== 'core' && !$this->appManager->isEnabledForUser($app)) {
$app = 'core';
}
$response = null;
try {
$iconFile = $this->imageManager->getImage('favicon');
$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/x-icon']);
} catch (NotFoundException $e) {
}
if ($this->imageManager->shouldReplaceIcons()) {
$color = $this->themingDefaults->getColorPrimary();
try {
$iconFile = $this->imageManager->getCachedImage('touchIcon-' . $app . $color);
} catch (NotFoundException $exception) {
$icon = $this->iconBuilder->getTouchIcon($app);
if ($icon === false || $icon === '') {
return new NotFoundResponse();
}
$iconFile = $this->imageManager->setCachedImage('touchIcon-' . $app . $color, $icon);
}
$response = new FileDisplayResponse($iconFile, Http::STATUS_OK, ['Content-Type' => 'image/png']);
}
if ($response === null) {
$fallbackLogo = \OC::$SERVERROOT . '/core/img/favicon-touch.png';
$response = new DataDisplayResponse($this->fileAccessHelper->file_get_contents($fallbackLogo), Http::STATUS_OK, ['Content-Type' => 'image/png']);
}
$response->cacheFor(86400);
return $response;
}
}
@@ -0,0 +1,515 @@
<?php
/**
* @copyright Copyright (c) 2016 Bjoern Schiessle <bjoern@schiessle.org>
* @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Calviño Sánchez <danxuliu@gmail.com>
* @author Jan-Christoph Borchardt <hey@jancborchardt.net>
* @author Joas Schilling <coding@schilljs.com>
* @author Julius Haertl <jus@bitgrid.net>
* @author Julius Härtl <jus@bitgrid.net>
* @author Kyle Fazzari <kyrofa@ubuntu.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author nhirokinet <nhirokinet@nhiroki.net>
* @author rakekniven <mark.ziegler@rakekniven.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Citharel <nextcloud@tcit.fr>
* @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\Theming\Controller;
use InvalidArgumentException;
use OCA\Theming\ImageManager;
use OCA\Theming\Service\ThemesService;
use OCA\Theming\ThemingDefaults;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataDisplayResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IRequest;
use OCP\ITempManager;
use OCP\IURLGenerator;
use ScssPhp\ScssPhp\Compiler;
/**
* Class ThemingController
*
* handle ajax requests to update the theme
*
* @package OCA\Theming\Controller
*/
class ThemingController extends Controller {
public const VALID_UPLOAD_KEYS = ['header', 'logo', 'logoheader', 'background', 'favicon'];
private ThemingDefaults $themingDefaults;
private IL10N $l10n;
private IConfig $config;
private ITempManager $tempManager;
private IAppData $appData;
private IURLGenerator $urlGenerator;
private IAppManager $appManager;
private ImageManager $imageManager;
private ThemesService $themesService;
public function __construct(
$appName,
IRequest $request,
IConfig $config,
ThemingDefaults $themingDefaults,
IL10N $l,
ITempManager $tempManager,
IAppData $appData,
IURLGenerator $urlGenerator,
IAppManager $appManager,
ImageManager $imageManager,
ThemesService $themesService
) {
parent::__construct($appName, $request);
$this->themingDefaults = $themingDefaults;
$this->l10n = $l;
$this->config = $config;
$this->tempManager = $tempManager;
$this->appData = $appData;
$this->urlGenerator = $urlGenerator;
$this->appManager = $appManager;
$this->imageManager = $imageManager;
$this->themesService = $themesService;
}
/**
* @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
* @param string $setting
* @param string $value
* @return DataResponse
* @throws NotPermittedException
*/
public function updateStylesheet($setting, $value) {
$value = trim($value);
$error = null;
switch ($setting) {
case 'name':
if (strlen($value) > 250) {
$error = $this->l10n->t('The given name is too long');
}
break;
case 'url':
if (strlen($value) > 500) {
$error = $this->l10n->t('The given web address is too long');
}
if (!$this->isValidUrl($value)) {
$error = $this->l10n->t('The given web address is not a valid URL');
}
break;
case 'imprintUrl':
if (strlen($value) > 500) {
$error = $this->l10n->t('The given legal notice address is too long');
}
if (!$this->isValidUrl($value)) {
$error = $this->l10n->t('The given legal notice address is not a valid URL');
}
break;
case 'privacyUrl':
if (strlen($value) > 500) {
$error = $this->l10n->t('The given privacy policy address is too long');
}
if (!$this->isValidUrl($value)) {
$error = $this->l10n->t('The given privacy policy address is not a valid URL');
}
break;
case 'slogan':
if (strlen($value) > 500) {
$error = $this->l10n->t('The given slogan is too long');
}
break;
case 'color':
if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
$error = $this->l10n->t('The given color is invalid');
}
break;
case 'disable-user-theming':
if ($value !== 'yes' && $value !== 'no') {
$error = $this->l10n->t('Disable-user-theming should be true or false');
}
break;
}
if ($error !== null) {
return new DataResponse([
'data' => [
'message' => $error,
],
'status' => 'error'
], Http::STATUS_BAD_REQUEST);
}
$this->themingDefaults->set($setting, $value);
return new DataResponse([
'data' => [
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]);
}
/**
* @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
* @param string $setting
* @param mixed $value
* @return DataResponse
* @throws NotPermittedException
*/
public function updateAppMenu($setting, $value) {
$error = null;
switch ($setting) {
case 'defaultApps':
if (is_array($value)) {
try {
$this->appManager->setDefaultApps($value);
} catch (InvalidArgumentException $e) {
$error = $this->l10n->t('Invalid app given');
}
} else {
$error = $this->l10n->t('Invalid type for setting "defaultApp" given');
}
break;
default:
$error = $this->l10n->t('Invalid setting key');
}
if ($error !== null) {
return new DataResponse([
'data' => [
'message' => $error,
],
'status' => 'error'
], Http::STATUS_BAD_REQUEST);
}
return new DataResponse([
'data' => [
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]);
}
/**
* Check that a string is a valid http/https url
*/
private function isValidUrl(string $url): bool {
return ((str_starts_with($url, 'http://') || str_starts_with($url, 'https://')) &&
filter_var($url, FILTER_VALIDATE_URL) !== false);
}
/**
* @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
* @return DataResponse
* @throws NotPermittedException
*/
public function uploadImage(): DataResponse {
$key = $this->request->getParam('key');
if (!in_array($key, self::VALID_UPLOAD_KEYS, true)) {
return new DataResponse(
[
'data' => [
'message' => 'Invalid key'
],
'status' => 'failure',
],
Http::STATUS_BAD_REQUEST
);
}
$image = $this->request->getUploadedFile('image');
$error = null;
$phpFileUploadErrors = [
UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
];
if (empty($image)) {
$error = $this->l10n->t('No file uploaded');
}
if (!empty($image) && array_key_exists('error', $image) && $image['error'] !== UPLOAD_ERR_OK) {
$error = $phpFileUploadErrors[$image['error']];
}
if ($error !== null) {
return new DataResponse(
[
'data' => [
'message' => $error
],
'status' => 'failure',
],
Http::STATUS_UNPROCESSABLE_ENTITY
);
}
try {
$mime = $this->imageManager->updateImage($key, $image['tmp_name']);
$this->themingDefaults->set($key . 'Mime', $mime);
} catch (\Exception $e) {
return new DataResponse(
[
'data' => [
'message' => $e->getMessage()
],
'status' => 'failure',
],
Http::STATUS_UNPROCESSABLE_ENTITY
);
}
$name = $image['name'];
return new DataResponse(
[
'data' =>
[
'name' => $name,
'url' => $this->imageManager->getImageUrl($key),
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]
);
}
/**
* Revert setting to default value
* @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
*
* @param string $setting setting which should be reverted
* @return DataResponse
* @throws NotPermittedException
*/
public function undo(string $setting): DataResponse {
$value = $this->themingDefaults->undo($setting);
return new DataResponse(
[
'data' =>
[
'value' => $value,
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]
);
}
/**
* Revert all theming settings to their default values
* @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
*
* @return DataResponse
* @throws NotPermittedException
*/
public function undoAll(): DataResponse {
$this->themingDefaults->undoAll();
$this->appManager->setDefaultApps([]);
return new DataResponse(
[
'data' =>
[
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]
);
}
/**
* @PublicPage
* @NoCSRFRequired
* @NoSameSiteCookieRequired
*
* Get an image
*
* @param string $key Key of the image
* @param bool $useSvg Return image as SVG
* @return FileDisplayResponse<Http::STATUS_OK, array{}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
* @throws NotPermittedException
*
* 200: Image returned
* 404: Image not found
*/
public function getImage(string $key, bool $useSvg = true) {
try {
$file = $this->imageManager->getImage($key, $useSvg);
} catch (NotFoundException $e) {
return new NotFoundResponse();
}
$response = new FileDisplayResponse($file);
$csp = new Http\ContentSecurityPolicy();
$csp->allowInlineStyle();
$response->setContentSecurityPolicy($csp);
$response->cacheFor(3600);
$response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
$response->addHeader('Content-Disposition', 'attachment; filename="' . $key . '"');
if (!$useSvg) {
$response->addHeader('Content-Type', 'image/png');
} else {
$response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
}
return $response;
}
/**
* @NoCSRFRequired
* @PublicPage
* @NoSameSiteCookieRequired
* @NoTwoFactorRequired
*
* Get the CSS stylesheet for a theme
*
* @param string $themeId ID of the theme
* @param bool $plain Let the browser decide the CSS priority
* @param bool $withCustomCss Include custom CSS
* @return DataDisplayResponse<Http::STATUS_OK, array{Content-Type: 'text/css'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
*
* 200: Stylesheet returned
* 404: Theme not found
*/
public function getThemeStylesheet(string $themeId, bool $plain = false, bool $withCustomCss = false) {
$themes = $this->themesService->getThemes();
if (!in_array($themeId, array_keys($themes))) {
return new NotFoundResponse();
}
$theme = $themes[$themeId];
$customCss = $theme->getCustomCss();
// Generate variables
$variables = '';
foreach ($theme->getCSSVariables() as $variable => $value) {
$variables .= "$variable:$value; ";
};
// If plain is set, the browser decides of the css priority
if ($plain) {
$css = ":root { $variables } " . $customCss;
} else {
// If not set, we'll rely on the body class
$compiler = new Compiler();
$compiledCss = $compiler->compileString("[data-theme-$themeId] { $variables $customCss }");
$css = $compiledCss->getCss();
;
}
try {
$response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
$response->cacheFor(86400);
return $response;
} catch (NotFoundException $e) {
return new NotFoundResponse();
}
}
/**
* @NoCSRFRequired
* @PublicPage
* @BruteForceProtection(action=manifest)
*
* Get the manifest for an app
*
* @param string $app ID of the app
* @psalm-suppress LessSpecificReturnStatement The content of the Manifest doesn't need to be described in the return type
* @return JSONResponse<Http::STATUS_OK, array{name: string, short_name: string, start_url: string, theme_color: string, background_color: string, description: string, icons: array{src: non-empty-string, type: string, sizes: string}[], display: string}, array{}>|JSONResponse<Http::STATUS_NOT_FOUND, array{}, array{}>
*
* 200: Manifest returned
* 404: App not found
*/
public function getManifest(string $app): JSONResponse {
$cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
if ($app === 'core' || $app === 'settings') {
$name = $this->themingDefaults->getName();
$shortName = $this->themingDefaults->getName();
$startUrl = $this->urlGenerator->getBaseUrl();
$description = $this->themingDefaults->getSlogan();
} else {
if (!$this->appManager->isEnabledForUser($app)) {
$response = new JSONResponse([], Http::STATUS_NOT_FOUND);
$response->throttle(['action' => 'manifest', 'app' => $app]);
return $response;
}
$info = $this->appManager->getAppInfo($app, false, $this->l10n->getLanguageCode());
$name = $info['name'] . ' - ' . $this->themingDefaults->getName();
$shortName = $info['name'];
if (str_contains($this->request->getRequestUri(), '/index.php/')) {
$startUrl = $this->urlGenerator->getBaseUrl() . '/index.php/apps/' . $app . '/';
} else {
$startUrl = $this->urlGenerator->getBaseUrl() . '/apps/' . $app . '/';
}
$description = $info['summary'] ?? '';
}
/**
* @var string $description
* @var string $shortName
*/
$responseJS = [
'name' => $name,
'short_name' => $shortName,
'start_url' => $startUrl,
'theme_color' => $this->themingDefaults->getColorPrimary(),
'background_color' => $this->themingDefaults->getColorPrimary(),
'description' => $description,
'icons' =>
[
[
'src' => $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon',
['app' => $app]) . '?v=' . $cacheBusterValue,
'type' => 'image/png',
'sizes' => '512x512'
],
[
'src' => $this->urlGenerator->linkToRoute('theming.Icon.getFavicon',
['app' => $app]) . '?v=' . $cacheBusterValue,
'type' => 'image/svg+xml',
'sizes' => '16x16'
]
],
'display' => 'standalone'
];
$response = new JSONResponse($responseJS);
$response->cacheFor(3600);
return $response;
}
}
@@ -0,0 +1,248 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
* @copyright Copyright (c) 2019 Janis Köhr <janiskoehr@icloud.com>
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Kesselberg <mail@danielkesselberg.de>
* @author Janis Köhr <janis.koehr@novatec-gmbh.de>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @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\Theming\Controller;
use OCA\Theming\AppInfo\Application;
use OCA\Theming\ITheme;
use OCA\Theming\ResponseDefinitions;
use OCA\Theming\Service\BackgroundService;
use OCA\Theming\Service\ThemesService;
use OCA\Theming\ThemingDefaults;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\FileDisplayResponse;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\NotFoundResponse;
use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSForbiddenException;
use OCP\AppFramework\OCSController;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\PreConditionNotMetException;
/**
* @psalm-import-type ThemingBackground from ResponseDefinitions
*/
class UserThemeController extends OCSController {
protected ?string $userId = null;
private IConfig $config;
private IUserSession $userSession;
private ThemesService $themesService;
private ThemingDefaults $themingDefaults;
private BackgroundService $backgroundService;
public function __construct(string $appName,
IRequest $request,
IConfig $config,
IUserSession $userSession,
ThemesService $themesService,
ThemingDefaults $themingDefaults,
BackgroundService $backgroundService) {
parent::__construct($appName, $request);
$this->config = $config;
$this->userSession = $userSession;
$this->themesService = $themesService;
$this->themingDefaults = $themingDefaults;
$this->backgroundService = $backgroundService;
$user = $userSession->getUser();
if ($user !== null) {
$this->userId = $user->getUID();
}
}
/**
* @NoAdminRequired
*
* Enable theme
*
* @param string $themeId the theme ID
* @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
* @throws OCSBadRequestException Enabling theme is not possible
* @throws PreConditionNotMetException
*
* 200: Theme enabled successfully
*/
public function enableTheme(string $themeId): DataResponse {
$theme = $this->validateTheme($themeId);
// Enable selected theme
$this->themesService->enableTheme($theme);
return new DataResponse();
}
/**
* @NoAdminRequired
*
* Disable theme
*
* @param string $themeId the theme ID
* @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
* @throws OCSBadRequestException Disabling theme is not possible
* @throws PreConditionNotMetException
*
* 200: Theme disabled successfully
*/
public function disableTheme(string $themeId): DataResponse {
$theme = $this->validateTheme($themeId);
// Enable selected theme
$this->themesService->disableTheme($theme);
return new DataResponse();
}
/**
* Validate and return the matching ITheme
*
* Disable theme
*
* @param string $themeId the theme ID
* @return ITheme
* @throws OCSBadRequestException
* @throws PreConditionNotMetException
*/
private function validateTheme(string $themeId): ITheme {
if ($themeId === '' || !$themeId) {
throw new OCSBadRequestException('Invalid theme id: ' . $themeId);
}
$themes = $this->themesService->getThemes();
if (!isset($themes[$themeId])) {
throw new OCSBadRequestException('Invalid theme id: ' . $themeId);
}
// If trying to toggle another theme but this is enforced
if ($this->config->getSystemValueString('enforce_theme', '') !== ''
&& $themes[$themeId]->getType() === ITheme::TYPE_THEME) {
throw new OCSForbiddenException('Theme switching is disabled');
}
return $themes[$themeId];
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*
* Get the background image
* @return FileDisplayResponse<Http::STATUS_OK, array{Content-Type: string}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
*
* 200: Background image returned
* 404: Background image not found
*/
public function getBackground(): Http\Response {
$file = $this->backgroundService->getBackground();
if ($file !== null) {
$response = new FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => $file->getMimeType()]);
$response->cacheFor(24 * 60 * 60, false, true);
return $response;
}
return new NotFoundResponse();
}
/**
* @NoAdminRequired
*
* Delete the background
*
* @return JSONResponse<Http::STATUS_OK, ThemingBackground, array{}>
*
* 200: Background deleted successfully
*/
public function deleteBackground(): JSONResponse {
$currentVersion = (int)$this->config->getUserValue($this->userId, Application::APP_ID, 'userCacheBuster', '0');
$this->backgroundService->deleteBackgroundImage();
return new JSONResponse([
'backgroundImage' => null,
'backgroundColor' => $this->themingDefaults->getColorPrimary(),
'version' => $currentVersion,
]);
}
/**
* @NoAdminRequired
*
* Set the background
*
* @param string $type Type of background
* @param string $value Path of the background image
* @param string|null $color Color for the background
* @return JSONResponse<Http::STATUS_OK, ThemingBackground, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_INTERNAL_SERVER_ERROR, array{error: string}, array{}>
*
* 200: Background set successfully
* 400: Setting background is not possible
*/
public function setBackground(string $type = BackgroundService::BACKGROUND_DEFAULT, string $value = '', string $color = null): JSONResponse {
$currentVersion = (int)$this->config->getUserValue($this->userId, Application::APP_ID, 'userCacheBuster', '0');
// Set color if provided
if ($color) {
$this->backgroundService->setColorBackground($color);
}
// Set background image if provided
try {
switch ($type) {
case BackgroundService::BACKGROUND_SHIPPED:
$this->backgroundService->setShippedBackground($value);
break;
case BackgroundService::BACKGROUND_CUSTOM:
$this->backgroundService->setFileBackground($value);
break;
case BackgroundService::BACKGROUND_DEFAULT:
// Delete both background and color keys
$this->backgroundService->setDefaultBackground();
break;
default:
if (!$color) {
return new JSONResponse(['error' => 'Invalid type provided'], Http::STATUS_BAD_REQUEST);
}
}
} catch (\InvalidArgumentException $e) {
return new JSONResponse(['error' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
} catch (\Throwable $e) {
return new JSONResponse(['error' => $e->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
$currentVersion++;
$this->config->setUserValue($this->userId, Application::APP_ID, 'userCacheBuster', (string)$currentVersion);
return new JSONResponse([
'backgroundImage' => $this->config->getUserValue($this->userId, Application::APP_ID, 'background_image', BackgroundService::BACKGROUND_DEFAULT),
'backgroundColor' => $this->themingDefaults->getColorPrimary(),
'version' => $currentVersion,
]);
}
}