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

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