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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 OCA\Theming\ImageManager;
  41. use OCA\Theming\Service\ThemesService;
  42. use OCA\Theming\ThemingDefaults;
  43. use OCP\App\IAppManager;
  44. use OCP\AppFramework\Controller;
  45. use OCP\AppFramework\Http;
  46. use OCP\AppFramework\Http\DataDisplayResponse;
  47. use OCP\AppFramework\Http\DataResponse;
  48. use OCP\AppFramework\Http\FileDisplayResponse;
  49. use OCP\AppFramework\Http\JSONResponse;
  50. use OCP\AppFramework\Http\NotFoundResponse;
  51. use OCP\Files\IAppData;
  52. use OCP\Files\NotFoundException;
  53. use OCP\Files\NotPermittedException;
  54. use OCP\IConfig;
  55. use OCP\IL10N;
  56. use OCP\IRequest;
  57. use OCP\ITempManager;
  58. use OCP\IURLGenerator;
  59. use ScssPhp\ScssPhp\Compiler;
  60. /**
  61. * Class ThemingController
  62. *
  63. * handle ajax requests to update the theme
  64. *
  65. * @package OCA\Theming\Controller
  66. */
  67. class ThemingController extends Controller {
  68. const VALID_UPLOAD_KEYS = ['header', 'logo', 'logoheader', 'background', 'favicon'];
  69. private ThemingDefaults $themingDefaults;
  70. private IL10N $l10n;
  71. private IConfig $config;
  72. private ITempManager $tempManager;
  73. private IAppData $appData;
  74. private IURLGenerator $urlGenerator;
  75. private IAppManager $appManager;
  76. private ImageManager $imageManager;
  77. private ThemesService $themesService;
  78. public function __construct(
  79. $appName,
  80. IRequest $request,
  81. IConfig $config,
  82. ThemingDefaults $themingDefaults,
  83. IL10N $l,
  84. ITempManager $tempManager,
  85. IAppData $appData,
  86. IURLGenerator $urlGenerator,
  87. IAppManager $appManager,
  88. ImageManager $imageManager,
  89. ThemesService $themesService
  90. ) {
  91. parent::__construct($appName, $request);
  92. $this->themingDefaults = $themingDefaults;
  93. $this->l10n = $l;
  94. $this->config = $config;
  95. $this->tempManager = $tempManager;
  96. $this->appData = $appData;
  97. $this->urlGenerator = $urlGenerator;
  98. $this->appManager = $appManager;
  99. $this->imageManager = $imageManager;
  100. $this->themesService = $themesService;
  101. }
  102. /**
  103. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  104. * @param string $setting
  105. * @param string $value
  106. * @return DataResponse
  107. * @throws NotPermittedException
  108. */
  109. public function updateStylesheet($setting, $value) {
  110. $value = trim($value);
  111. $error = null;
  112. switch ($setting) {
  113. case 'name':
  114. if (strlen($value) > 250) {
  115. $error = $this->l10n->t('The given name is too long');
  116. }
  117. break;
  118. case 'url':
  119. if (strlen($value) > 500) {
  120. $error = $this->l10n->t('The given web address is too long');
  121. }
  122. if (!$this->isValidUrl($value)) {
  123. $error = $this->l10n->t('The given web address is not a valid URL');
  124. }
  125. break;
  126. case 'imprintUrl':
  127. if (strlen($value) > 500) {
  128. $error = $this->l10n->t('The given legal notice address is too long');
  129. }
  130. if (!$this->isValidUrl($value)) {
  131. $error = $this->l10n->t('The given legal notice address is not a valid URL');
  132. }
  133. break;
  134. case 'privacyUrl':
  135. if (strlen($value) > 500) {
  136. $error = $this->l10n->t('The given privacy policy address is too long');
  137. }
  138. if (!$this->isValidUrl($value)) {
  139. $error = $this->l10n->t('The given privacy policy address is not a valid URL');
  140. }
  141. break;
  142. case 'slogan':
  143. if (strlen($value) > 500) {
  144. $error = $this->l10n->t('The given slogan is too long');
  145. }
  146. break;
  147. case 'color':
  148. if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
  149. $error = $this->l10n->t('The given color is invalid');
  150. }
  151. break;
  152. case 'disable-user-theming':
  153. if ($value !== "yes" && $value !== "no") {
  154. $error = $this->l10n->t('Disable-user-theming should be true or false');
  155. }
  156. break;
  157. }
  158. if ($error !== null) {
  159. return new DataResponse([
  160. 'data' => [
  161. 'message' => $error,
  162. ],
  163. 'status' => 'error'
  164. ], Http::STATUS_BAD_REQUEST);
  165. }
  166. $this->themingDefaults->set($setting, $value);
  167. return new DataResponse([
  168. 'data' => [
  169. 'message' => $this->l10n->t('Saved'),
  170. ],
  171. 'status' => 'success'
  172. ]);
  173. }
  174. /**
  175. * Check that a string is a valid http/https url
  176. */
  177. private function isValidUrl(string $url): bool {
  178. return ((str_starts_with($url, 'http://') || str_starts_with($url, 'https://')) &&
  179. filter_var($url, FILTER_VALIDATE_URL) !== false);
  180. }
  181. /**
  182. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  183. * @return DataResponse
  184. * @throws NotPermittedException
  185. */
  186. public function uploadImage(): DataResponse {
  187. $key = $this->request->getParam('key');
  188. if (!in_array($key, self::VALID_UPLOAD_KEYS, true)) {
  189. return new DataResponse(
  190. [
  191. 'data' => [
  192. 'message' => 'Invalid key'
  193. ],
  194. 'status' => 'failure',
  195. ],
  196. Http::STATUS_BAD_REQUEST
  197. );
  198. }
  199. $image = $this->request->getUploadedFile('image');
  200. $error = null;
  201. $phpFileUploadErrors = [
  202. UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
  203. UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  204. UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  205. UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
  206. UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
  207. UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
  208. UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
  209. UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
  210. ];
  211. if (empty($image)) {
  212. $error = $this->l10n->t('No file uploaded');
  213. }
  214. if (!empty($image) && array_key_exists('error', $image) && $image['error'] !== UPLOAD_ERR_OK) {
  215. $error = $phpFileUploadErrors[$image['error']];
  216. }
  217. if ($error !== null) {
  218. return new DataResponse(
  219. [
  220. 'data' => [
  221. 'message' => $error
  222. ],
  223. 'status' => 'failure',
  224. ],
  225. Http::STATUS_UNPROCESSABLE_ENTITY
  226. );
  227. }
  228. try {
  229. $mime = $this->imageManager->updateImage($key, $image['tmp_name']);
  230. $this->themingDefaults->set($key . 'Mime', $mime);
  231. } catch (\Exception $e) {
  232. return new DataResponse(
  233. [
  234. 'data' => [
  235. 'message' => $e->getMessage()
  236. ],
  237. 'status' => 'failure',
  238. ],
  239. Http::STATUS_UNPROCESSABLE_ENTITY
  240. );
  241. }
  242. $name = $image['name'];
  243. return new DataResponse(
  244. [
  245. 'data' =>
  246. [
  247. 'name' => $name,
  248. 'url' => $this->imageManager->getImageUrl($key),
  249. 'message' => $this->l10n->t('Saved'),
  250. ],
  251. 'status' => 'success'
  252. ]
  253. );
  254. }
  255. /**
  256. * Revert setting to default value
  257. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  258. *
  259. * @param string $setting setting which should be reverted
  260. * @return DataResponse
  261. * @throws NotPermittedException
  262. */
  263. public function undo(string $setting): DataResponse {
  264. $value = $this->themingDefaults->undo($setting);
  265. return new DataResponse(
  266. [
  267. 'data' =>
  268. [
  269. 'value' => $value,
  270. 'message' => $this->l10n->t('Saved'),
  271. ],
  272. 'status' => 'success'
  273. ]
  274. );
  275. }
  276. /**
  277. * Revert all theming settings to their default values
  278. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  279. *
  280. * @return DataResponse
  281. * @throws NotPermittedException
  282. */
  283. public function undoAll(): DataResponse {
  284. $this->themingDefaults->undoAll();
  285. return new DataResponse(
  286. [
  287. 'data' =>
  288. [
  289. 'message' => $this->l10n->t('Saved'),
  290. ],
  291. 'status' => 'success'
  292. ]
  293. );
  294. }
  295. /**
  296. * @PublicPage
  297. * @NoCSRFRequired
  298. * @NoSameSiteCookieRequired
  299. *
  300. * Get an image
  301. *
  302. * @param string $key Key of the image
  303. * @param bool $useSvg Return image as SVG
  304. * @return FileDisplayResponse<Http::STATUS_OK, array{}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
  305. * @throws NotPermittedException
  306. *
  307. * 200: Image returned
  308. * 404: Image not found
  309. */
  310. public function getImage(string $key, bool $useSvg = true) {
  311. try {
  312. $file = $this->imageManager->getImage($key, $useSvg);
  313. } catch (NotFoundException $e) {
  314. return new NotFoundResponse();
  315. }
  316. $response = new FileDisplayResponse($file);
  317. $csp = new Http\ContentSecurityPolicy();
  318. $csp->allowInlineStyle();
  319. $response->setContentSecurityPolicy($csp);
  320. $response->cacheFor(3600);
  321. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  322. $response->addHeader('Content-Disposition', 'attachment; filename="' . $key . '"');
  323. if (!$useSvg) {
  324. $response->addHeader('Content-Type', 'image/png');
  325. } else {
  326. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  327. }
  328. return $response;
  329. }
  330. /**
  331. * @NoCSRFRequired
  332. * @PublicPage
  333. * @NoSameSiteCookieRequired
  334. * @NoTwoFactorRequired
  335. *
  336. * Get the CSS stylesheet for a theme
  337. *
  338. * @param string $themeId ID of the theme
  339. * @param bool $plain Let the browser decide the CSS priority
  340. * @param bool $withCustomCss Include custom CSS
  341. * @return DataDisplayResponse<Http::STATUS_OK, array{Content-Type: 'text/css'}>|NotFoundResponse<Http::STATUS_NOT_FOUND, array{}>
  342. *
  343. * 200: Stylesheet returned
  344. * 404: Theme not found
  345. */
  346. public function getThemeStylesheet(string $themeId, bool $plain = false, bool $withCustomCss = false) {
  347. $themes = $this->themesService->getThemes();
  348. if (!in_array($themeId, array_keys($themes))) {
  349. return new NotFoundResponse();
  350. }
  351. $theme = $themes[$themeId];
  352. $customCss = $theme->getCustomCss();
  353. // Generate variables
  354. $variables = '';
  355. foreach ($theme->getCSSVariables() as $variable => $value) {
  356. $variables .= "$variable:$value; ";
  357. };
  358. // If plain is set, the browser decides of the css priority
  359. if ($plain) {
  360. $css = ":root { $variables } " . $customCss;
  361. } else {
  362. // If not set, we'll rely on the body class
  363. $compiler = new Compiler();
  364. $compiledCss = $compiler->compileString("[data-theme-$themeId] { $variables $customCss }");
  365. $css = $compiledCss->getCss();;
  366. }
  367. try {
  368. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  369. $response->cacheFor(86400);
  370. return $response;
  371. } catch (NotFoundException $e) {
  372. return new NotFoundResponse();
  373. }
  374. }
  375. /**
  376. * @NoCSRFRequired
  377. * @PublicPage
  378. *
  379. * Get the manifest for an app
  380. *
  381. * @param string $app ID of the app
  382. * @psalm-suppress LessSpecificReturnStatement The content of the Manifest doesn't need to be described in the return type
  383. * @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{}>
  384. *
  385. * 200: Manifest returned
  386. */
  387. public function getManifest(string $app) {
  388. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  389. if ($app === 'core' || $app === 'settings') {
  390. $name = $this->themingDefaults->getName();
  391. $shortName = $this->themingDefaults->getName();
  392. $startUrl = $this->urlGenerator->getBaseUrl();
  393. $description = $this->themingDefaults->getSlogan();
  394. } else {
  395. $info = $this->appManager->getAppInfo($app, false, $this->l10n->getLanguageCode());
  396. $name = $info['name'] . ' - ' . $this->themingDefaults->getName();
  397. $shortName = $info['name'];
  398. if (str_contains($this->request->getRequestUri(), '/index.php/')) {
  399. $startUrl = $this->urlGenerator->getBaseUrl() . '/index.php/apps/' . $app . '/';
  400. } else {
  401. $startUrl = $this->urlGenerator->getBaseUrl() . '/apps/' . $app . '/';
  402. }
  403. $description = $info['summary'] ?? '';
  404. }
  405. /**
  406. * @var string $description
  407. * @var string $shortName
  408. */
  409. $responseJS = [
  410. 'name' => $name,
  411. 'short_name' => $shortName,
  412. 'start_url' => $startUrl,
  413. 'theme_color' => $this->themingDefaults->getColorPrimary(),
  414. 'background_color' => $this->themingDefaults->getColorPrimary(),
  415. 'description' => $description,
  416. 'icons' =>
  417. [
  418. [
  419. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon',
  420. ['app' => $app]) . '?v=' . $cacheBusterValue,
  421. 'type' => 'image/png',
  422. 'sizes' => '512x512'
  423. ],
  424. [
  425. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getFavicon',
  426. ['app' => $app]) . '?v=' . $cacheBusterValue,
  427. 'type' => 'image/svg+xml',
  428. 'sizes' => '16x16'
  429. ]
  430. ],
  431. 'display' => 'standalone'
  432. ];
  433. $response = new JSONResponse($responseJS);
  434. $response->cacheFor(3600);
  435. return $response;
  436. }
  437. }