ThemingController.php 13 KB

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