ThemingController.php 13 KB

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