You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ThemingController.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Bjoern Schiessle <bjoern@schiessle.org>
  4. * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Julius Haertl <jus@bitgrid.net>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Kyle Fazzari <kyrofa@ubuntu.com>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author nhirokinet <nhirokinet@nhiroki.net>
  17. * @author rakekniven <mark.ziegler@rakekniven.de>
  18. * @author Robin Appelman <robin@icewind.nl>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Thomas Citharel <nextcloud@tcit.fr>
  21. * @author Kate Döen <kate.doeen@nextcloud.com>
  22. *
  23. * @license GNU AGPL version 3 or any later version
  24. *
  25. * This program is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License as
  27. * published by the Free Software Foundation, either version 3 of the
  28. * License, or (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  37. *
  38. */
  39. namespace OCA\Theming\Controller;
  40. use InvalidArgumentException;
  41. use OCA\Theming\ImageManager;
  42. use OCA\Theming\Service\ThemesService;
  43. use OCA\Theming\ThemingDefaults;
  44. use OCP\App\IAppManager;
  45. use OCP\AppFramework\Controller;
  46. use OCP\AppFramework\Http;
  47. use OCP\AppFramework\Http\DataDisplayResponse;
  48. use OCP\AppFramework\Http\DataResponse;
  49. use OCP\AppFramework\Http\FileDisplayResponse;
  50. use OCP\AppFramework\Http\JSONResponse;
  51. use OCP\AppFramework\Http\NotFoundResponse;
  52. use OCP\Files\IAppData;
  53. use OCP\Files\NotFoundException;
  54. use OCP\Files\NotPermittedException;
  55. use OCP\IConfig;
  56. use OCP\IL10N;
  57. use OCP\IRequest;
  58. use OCP\ITempManager;
  59. use OCP\IURLGenerator;
  60. use ScssPhp\ScssPhp\Compiler;
  61. /**
  62. * Class ThemingController
  63. *
  64. * handle ajax requests to update the theme
  65. *
  66. * @package OCA\Theming\Controller
  67. */
  68. class ThemingController extends Controller {
  69. const VALID_UPLOAD_KEYS = ['header', 'logo', 'logoheader', 'background', 'favicon'];
  70. private ThemingDefaults $themingDefaults;
  71. private IL10N $l10n;
  72. private IConfig $config;
  73. private ITempManager $tempManager;
  74. private IAppData $appData;
  75. private IURLGenerator $urlGenerator;
  76. private IAppManager $appManager;
  77. private ImageManager $imageManager;
  78. private ThemesService $themesService;
  79. public function __construct(
  80. $appName,
  81. IRequest $request,
  82. IConfig $config,
  83. ThemingDefaults $themingDefaults,
  84. IL10N $l,
  85. ITempManager $tempManager,
  86. IAppData $appData,
  87. IURLGenerator $urlGenerator,
  88. IAppManager $appManager,
  89. ImageManager $imageManager,
  90. ThemesService $themesService
  91. ) {
  92. parent::__construct($appName, $request);
  93. $this->themingDefaults = $themingDefaults;
  94. $this->l10n = $l;
  95. $this->config = $config;
  96. $this->tempManager = $tempManager;
  97. $this->appData = $appData;
  98. $this->urlGenerator = $urlGenerator;
  99. $this->appManager = $appManager;
  100. $this->imageManager = $imageManager;
  101. $this->themesService = $themesService;
  102. }
  103. /**
  104. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  105. * @param string $setting
  106. * @param string $value
  107. * @return DataResponse
  108. * @throws NotPermittedException
  109. */
  110. public function updateStylesheet($setting, $value) {
  111. $value = trim($value);
  112. $error = null;
  113. switch ($setting) {
  114. case 'name':
  115. if (strlen($value) > 250) {
  116. $error = $this->l10n->t('The given name is too long');
  117. }
  118. break;
  119. case 'url':
  120. if (strlen($value) > 500) {
  121. $error = $this->l10n->t('The given web address is too long');
  122. }
  123. if (!$this->isValidUrl($value)) {
  124. $error = $this->l10n->t('The given web address is not a valid URL');
  125. }
  126. break;
  127. case 'imprintUrl':
  128. if (strlen($value) > 500) {
  129. $error = $this->l10n->t('The given legal notice address is too long');
  130. }
  131. if (!$this->isValidUrl($value)) {
  132. $error = $this->l10n->t('The given legal notice address is not a valid URL');
  133. }
  134. break;
  135. case 'privacyUrl':
  136. if (strlen($value) > 500) {
  137. $error = $this->l10n->t('The given privacy policy address is too long');
  138. }
  139. if (!$this->isValidUrl($value)) {
  140. $error = $this->l10n->t('The given privacy policy address is not a valid URL');
  141. }
  142. break;
  143. case 'slogan':
  144. if (strlen($value) > 500) {
  145. $error = $this->l10n->t('The given slogan is too long');
  146. }
  147. break;
  148. case 'color':
  149. if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
  150. $error = $this->l10n->t('The given color is invalid');
  151. }
  152. break;
  153. case 'disable-user-theming':
  154. if ($value !== 'yes' && $value !== 'no') {
  155. $error = $this->l10n->t('Disable-user-theming should be true or false');
  156. }
  157. break;
  158. }
  159. if ($error !== null) {
  160. return new DataResponse([
  161. 'data' => [
  162. 'message' => $error,
  163. ],
  164. 'status' => 'error'
  165. ], Http::STATUS_BAD_REQUEST);
  166. }
  167. $this->themingDefaults->set($setting, $value);
  168. return new DataResponse([
  169. 'data' => [
  170. 'message' => $this->l10n->t('Saved'),
  171. ],
  172. 'status' => 'success'
  173. ]);
  174. }
  175. /**
  176. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  177. * @param string $setting
  178. * @param mixed $value
  179. * @return DataResponse
  180. * @throws NotPermittedException
  181. */
  182. public function updateAppMenu($setting, $value) {
  183. $error = null;
  184. switch ($setting) {
  185. case 'defaultApps':
  186. if (is_array($value)) {
  187. try {
  188. $this->appManager->setDefaultApps($value);
  189. } catch (InvalidArgumentException $e) {
  190. $error = $this->l10n->t('Invalid app given');
  191. }
  192. } else {
  193. $error = $this->l10n->t('Invalid type for setting "defaultApp" given');
  194. }
  195. break;
  196. default:
  197. $error = $this->l10n->t('Invalid setting key');
  198. }
  199. if ($error !== null) {
  200. return new DataResponse([
  201. 'data' => [
  202. 'message' => $error,
  203. ],
  204. 'status' => 'error'
  205. ], Http::STATUS_BAD_REQUEST);
  206. }
  207. return new DataResponse([
  208. 'data' => [
  209. 'message' => $this->l10n->t('Saved'),
  210. ],
  211. 'status' => 'success'
  212. ]);
  213. }
  214. /**
  215. * Check that a string is a valid http/https url
  216. */
  217. private function isValidUrl(string $url): bool {
  218. return ((str_starts_with($url, 'http://') || str_starts_with($url, 'https://')) &&
  219. filter_var($url, FILTER_VALIDATE_URL) !== false);
  220. }
  221. /**
  222. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  223. * @return DataResponse
  224. * @throws NotPermittedException
  225. */
  226. public function uploadImage(): DataResponse {
  227. $key = $this->request->getParam('key');
  228. if (!in_array($key, self::VALID_UPLOAD_KEYS, true)) {
  229. return new DataResponse(
  230. [
  231. 'data' => [
  232. 'message' => 'Invalid key'
  233. ],
  234. 'status' => 'failure',
  235. ],
  236. Http::STATUS_BAD_REQUEST
  237. );
  238. }
  239. $image = $this->request->getUploadedFile('image');
  240. $error = null;
  241. $phpFileUploadErrors = [
  242. UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
  243. UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  244. UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  245. UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
  246. UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
  247. UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
  248. UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
  249. UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
  250. ];
  251. if (empty($image)) {
  252. $error = $this->l10n->t('No file uploaded');
  253. }
  254. if (!empty($image) && array_key_exists('error', $image) && $image['error'] !== UPLOAD_ERR_OK) {
  255. $error = $phpFileUploadErrors[$image['error']];
  256. }
  257. if ($error !== null) {
  258. return new DataResponse(
  259. [
  260. 'data' => [
  261. 'message' => $error
  262. ],
  263. 'status' => 'failure',
  264. ],
  265. Http::STATUS_UNPROCESSABLE_ENTITY
  266. );
  267. }
  268. try {
  269. $mime = $this->imageManager->updateImage($key, $image['tmp_name']);
  270. $this->themingDefaults->set($key . 'Mime', $mime);
  271. } catch (\Exception $e) {
  272. return new DataResponse(
  273. [
  274. 'data' => [
  275. 'message' => $e->getMessage()
  276. ],
  277. 'status' => 'failure',
  278. ],
  279. Http::STATUS_UNPROCESSABLE_ENTITY
  280. );
  281. }
  282. $name = $image['name'];
  283. return new DataResponse(
  284. [
  285. 'data' =>
  286. [
  287. 'name' => $name,
  288. 'url' => $this->imageManager->getImageUrl($key),
  289. 'message' => $this->l10n->t('Saved'),
  290. ],
  291. 'status' => 'success'
  292. ]
  293. );
  294. }
  295. /**
  296. * Revert setting to default value
  297. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  298. *
  299. * @param string $setting setting which should be reverted
  300. * @return DataResponse
  301. * @throws NotPermittedException
  302. */
  303. public function undo(string $setting): DataResponse {
  304. $value = $this->themingDefaults->undo($setting);
  305. return new DataResponse(
  306. [
  307. 'data' =>
  308. [
  309. 'value' => $value,
  310. 'message' => $this->l10n->t('Saved'),
  311. ],
  312. 'status' => 'success'
  313. ]
  314. );
  315. }
  316. /**
  317. * Revert all theming settings to their default values
  318. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  319. *
  320. * @return DataResponse
  321. * @throws NotPermittedException
  322. */
  323. public function undoAll(): DataResponse {
  324. $this->themingDefaults->undoAll();
  325. $this->appManager->setDefaultApps([]);
  326. return new DataResponse(
  327. [
  328. 'data' =>
  329. [
  330. 'message' => $this->l10n->t('Saved'),
  331. ],
  332. 'status' => 'success'
  333. ]
  334. );
  335. }
  336. /**
  337. * @PublicPage
  338. * @NoCSRFRequired
  339. * @NoSameSiteCookieRequired
  340. *
  341. * Get an image
  342. *
  343. * @param string $key Key of the image
  344. * @param bool $useSvg Return image as SVG
  345. * @return FileDisplayResponse<Http::STATUS_OK, array{}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
  346. * @throws NotPermittedException
  347. *
  348. * 200: Image returned
  349. * 404: Image not found
  350. */
  351. public function getImage(string $key, bool $useSvg = true) {
  352. try {
  353. $file = $this->imageManager->getImage($key, $useSvg);
  354. } catch (NotFoundException $e) {
  355. return new NotFoundResponse();
  356. }
  357. $response = new FileDisplayResponse($file);
  358. $csp = new Http\ContentSecurityPolicy();
  359. $csp->allowInlineStyle();
  360. $response->setContentSecurityPolicy($csp);
  361. $response->cacheFor(3600);
  362. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  363. $response->addHeader('Content-Disposition', 'attachment; filename="' . $key . '"');
  364. if (!$useSvg) {
  365. $response->addHeader('Content-Type', 'image/png');
  366. } else {
  367. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  368. }
  369. return $response;
  370. }
  371. /**
  372. * @NoCSRFRequired
  373. * @PublicPage
  374. * @NoSameSiteCookieRequired
  375. * @NoTwoFactorRequired
  376. *
  377. * Get the CSS stylesheet for a theme
  378. *
  379. * @param string $themeId ID of the theme
  380. * @param bool $plain Let the browser decide the CSS priority
  381. * @param bool $withCustomCss Include custom CSS
  382. * @return DataDisplayResponse<Http::STATUS_OK, array{Content-Type: 'text/css'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
  383. *
  384. * 200: Stylesheet returned
  385. * 404: Theme not found
  386. */
  387. public function getThemeStylesheet(string $themeId, bool $plain = false, bool $withCustomCss = false) {
  388. $themes = $this->themesService->getThemes();
  389. if (!in_array($themeId, array_keys($themes))) {
  390. return new NotFoundResponse();
  391. }
  392. $theme = $themes[$themeId];
  393. $customCss = $theme->getCustomCss();
  394. // Generate variables
  395. $variables = '';
  396. foreach ($theme->getCSSVariables() as $variable => $value) {
  397. $variables .= "$variable:$value; ";
  398. };
  399. // If plain is set, the browser decides of the css priority
  400. if ($plain) {
  401. $css = ":root { $variables } " . $customCss;
  402. } else {
  403. // If not set, we'll rely on the body class
  404. $compiler = new Compiler();
  405. $compiledCss = $compiler->compileString("[data-theme-$themeId] { $variables $customCss }");
  406. $css = $compiledCss->getCss();;
  407. }
  408. try {
  409. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  410. $response->cacheFor(86400);
  411. return $response;
  412. } catch (NotFoundException $e) {
  413. return new NotFoundResponse();
  414. }
  415. }
  416. /**
  417. * @NoCSRFRequired
  418. * @PublicPage
  419. *
  420. * Get the manifest for an app
  421. *
  422. * @param string $app ID of the app
  423. * @psalm-suppress LessSpecificReturnStatement The content of the Manifest doesn't need to be described in the return type
  424. * @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{}>
  425. *
  426. * 200: Manifest returned
  427. */
  428. public function getManifest(string $app) {
  429. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  430. if ($app === 'core' || $app === 'settings') {
  431. $name = $this->themingDefaults->getName();
  432. $shortName = $this->themingDefaults->getName();
  433. $startUrl = $this->urlGenerator->getBaseUrl();
  434. $description = $this->themingDefaults->getSlogan();
  435. } else {
  436. $info = $this->appManager->getAppInfo($app, false, $this->l10n->getLanguageCode());
  437. $name = $info['name'] . ' - ' . $this->themingDefaults->getName();
  438. $shortName = $info['name'];
  439. if (str_contains($this->request->getRequestUri(), '/index.php/')) {
  440. $startUrl = $this->urlGenerator->getBaseUrl() . '/index.php/apps/' . $app . '/';
  441. } else {
  442. $startUrl = $this->urlGenerator->getBaseUrl() . '/apps/' . $app . '/';
  443. }
  444. $description = $info['summary'] ?? '';
  445. }
  446. /**
  447. * @var string $description
  448. * @var string $shortName
  449. */
  450. $responseJS = [
  451. 'name' => $name,
  452. 'short_name' => $shortName,
  453. 'start_url' => $startUrl,
  454. 'theme_color' => $this->themingDefaults->getColorPrimary(),
  455. 'background_color' => $this->themingDefaults->getColorPrimary(),
  456. 'description' => $description,
  457. 'icons' =>
  458. [
  459. [
  460. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon',
  461. ['app' => $app]) . '?v=' . $cacheBusterValue,
  462. 'type' => 'image/png',
  463. 'sizes' => '512x512'
  464. ],
  465. [
  466. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getFavicon',
  467. ['app' => $app]) . '?v=' . $cacheBusterValue,
  468. 'type' => 'image/svg+xml',
  469. 'sizes' => '16x16'
  470. ]
  471. ],
  472. 'display' => 'standalone'
  473. ];
  474. $response = new JSONResponse($responseJS);
  475. $response->cacheFor(3600);
  476. return $response;
  477. }
  478. }