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.

425 lines
12 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  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. * Revert all theming settings to their default values
  264. * @AuthorizedAdminSetting(settings=OCA\Theming\Settings\Admin)
  265. *
  266. * @return DataResponse
  267. * @throws NotPermittedException
  268. */
  269. public function undoAll(): DataResponse {
  270. $this->themingDefaults->undoAll();
  271. return new DataResponse(
  272. [
  273. 'data' =>
  274. [
  275. 'message' => $this->l10n->t('Saved'),
  276. ],
  277. 'status' => 'success'
  278. ]
  279. );
  280. }
  281. /**
  282. * @PublicPage
  283. * @NoCSRFRequired
  284. * @NoSameSiteCookieRequired
  285. *
  286. * @param string $key
  287. * @param bool $useSvg
  288. * @return FileDisplayResponse|NotFoundResponse
  289. * @throws NotPermittedException
  290. */
  291. public function getImage(string $key, bool $useSvg = true) {
  292. try {
  293. $file = $this->imageManager->getImage($key, $useSvg);
  294. } catch (NotFoundException $e) {
  295. return new NotFoundResponse();
  296. }
  297. $response = new FileDisplayResponse($file);
  298. $csp = new Http\ContentSecurityPolicy();
  299. $csp->allowInlineStyle();
  300. $response->setContentSecurityPolicy($csp);
  301. $response->cacheFor(3600);
  302. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  303. $response->addHeader('Content-Disposition', 'attachment; filename="' . $key . '"');
  304. if (!$useSvg) {
  305. $response->addHeader('Content-Type', 'image/png');
  306. } else {
  307. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  308. }
  309. return $response;
  310. }
  311. /**
  312. * @NoCSRFRequired
  313. * @PublicPage
  314. * @NoSameSiteCookieRequired
  315. * @NoTwoFactorRequired
  316. *
  317. * @return DataDisplayResponse|NotFoundResponse
  318. */
  319. public function getThemeStylesheet(string $themeId, bool $plain = false, bool $withCustomCss = false) {
  320. $themes = $this->themesService->getThemes();
  321. if (!in_array($themeId, array_keys($themes))) {
  322. return new NotFoundResponse();
  323. }
  324. $theme = $themes[$themeId];
  325. $customCss = $theme->getCustomCss();
  326. // Generate variables
  327. $variables = '';
  328. foreach ($theme->getCSSVariables() as $variable => $value) {
  329. $variables .= "$variable:$value; ";
  330. };
  331. // If plain is set, the browser decides of the css priority
  332. if ($plain) {
  333. $css = ":root { $variables } " . $customCss;
  334. } else {
  335. // If not set, we'll rely on the body class
  336. $compiler = new Compiler();
  337. $compiledCss = $compiler->compileString("[data-theme-$themeId] { $variables $customCss }");
  338. $css = $compiledCss->getCss();;
  339. }
  340. try {
  341. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  342. $response->cacheFor(86400);
  343. return $response;
  344. } catch (NotFoundException $e) {
  345. return new NotFoundResponse();
  346. }
  347. }
  348. /**
  349. * @NoCSRFRequired
  350. * @PublicPage
  351. *
  352. * @return Http\JSONResponse
  353. */
  354. public function getManifest($app) {
  355. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  356. if ($app === 'core' || $app === 'settings') {
  357. $name = $this->themingDefaults->getName();
  358. $shortName = $this->themingDefaults->getName();
  359. $startUrl = $this->urlGenerator->getBaseUrl();
  360. $description = $this->themingDefaults->getSlogan();
  361. } else {
  362. $info = $this->appManager->getAppInfo($app, false, $this->l10n->getLanguageCode());
  363. $name = $info['name'] . ' - ' . $this->themingDefaults->getName();
  364. $shortName = $info['name'];
  365. if (strpos($this->request->getRequestUri(), '/index.php/') !== false) {
  366. $startUrl = $this->urlGenerator->getBaseUrl() . '/index.php/apps/' . $app . '/';
  367. } else {
  368. $startUrl = $this->urlGenerator->getBaseUrl() . '/apps/' . $app . '/';
  369. }
  370. $description = $info['summary'] ?? '';
  371. }
  372. $responseJS = [
  373. 'name' => $name,
  374. 'short_name' => $shortName,
  375. 'start_url' => $startUrl,
  376. 'theme_color' => $this->themingDefaults->getColorPrimary(),
  377. 'background_color' => $this->themingDefaults->getColorPrimary(),
  378. 'description' => $description,
  379. 'icons' =>
  380. [
  381. [
  382. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon',
  383. ['app' => $app]) . '?v=' . $cacheBusterValue,
  384. 'type' => 'image/png',
  385. 'sizes' => '512x512'
  386. ],
  387. [
  388. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getFavicon',
  389. ['app' => $app]) . '?v=' . $cacheBusterValue,
  390. 'type' => 'image/svg+xml',
  391. 'sizes' => '16x16'
  392. ]
  393. ],
  394. 'display' => 'standalone'
  395. ];
  396. $response = new Http\JSONResponse($responseJS);
  397. $response->cacheFor(3600);
  398. return $response;
  399. }
  400. }