1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
|
<?php
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Theming\Controller;
use InvalidArgumentException;
use OCA\Theming\ImageManager;
use OCA\Theming\Service\ThemesService;
use OCA\Theming\Settings\Admin;
use OCA\Theming\ThemingDefaults;
use OCP\App\IAppManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting;
use OCP\AppFramework\Http\Attribute\BruteForceProtection;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
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\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IConfig;
use OCP\IL10N;
use OCP\INavigationManager;
use OCP\IRequest;
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 IURLGenerator $urlGenerator;
private IAppManager $appManager;
private ImageManager $imageManager;
private ThemesService $themesService;
private INavigationManager $navigationManager;
public function __construct(
$appName,
IRequest $request,
IConfig $config,
ThemingDefaults $themingDefaults,
IL10N $l,
IURLGenerator $urlGenerator,
IAppManager $appManager,
ImageManager $imageManager,
ThemesService $themesService,
INavigationManager $navigationManager,
) {
parent::__construct($appName, $request);
$this->themingDefaults = $themingDefaults;
$this->l10n = $l;
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->appManager = $appManager;
$this->imageManager = $imageManager;
$this->themesService = $themesService;
$this->navigationManager = $navigationManager;
}
/**
* @param string $setting
* @param string $value
* @return DataResponse
* @throws NotPermittedException
*/
#[AuthorizedAdminSetting(settings: Admin::class)]
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 'primary_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 'background_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'
]);
}
/**
* @param string $setting
* @param mixed $value
* @return DataResponse
* @throws NotPermittedException
*/
#[AuthorizedAdminSetting(settings: Admin::class)]
public function updateAppMenu($setting, $value) {
$error = null;
switch ($setting) {
case 'defaultApps':
if (is_array($value)) {
try {
$this->navigationManager->setDefaultEntryIds($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);
}
/**
* @return DataResponse
* @throws NotPermittedException
*/
#[AuthorizedAdminSetting(settings: Admin::class)]
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
*
* @param string $setting setting which should be reverted
* @return DataResponse
* @throws NotPermittedException
*/
#[AuthorizedAdminSetting(settings: Admin::class)]
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
*
* @return DataResponse
* @throws NotPermittedException
*/
#[AuthorizedAdminSetting(settings: Admin::class)]
public function undoAll(): DataResponse {
$this->themingDefaults->undoAll();
$this->navigationManager->setDefaultEntryIds([]);
return new DataResponse(
[
'data' =>
[
'message' => $this->l10n->t('Saved'),
],
'status' => 'success'
]
);
}
/**
* @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
*/
#[PublicPage]
#[NoCSRFRequired]
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;
}
/**
* @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
*/
#[PublicPage]
#[NoCSRFRequired]
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();
}
}
/**
* 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
*/
#[PublicPage]
#[NoCSRFRequired]
#[BruteForceProtection(action: 'manifest')]
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;
}
}
|