ThemingController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 Daniel Calviño Sánchez <danxuliu@gmail.com>
  9. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Haertl <jus@bitgrid.net>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. *
  16. * @license GNU AGPL version 3 or any later version
  17. *
  18. * This program is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License as
  20. * published by the Free Software Foundation, either version 3 of the
  21. * License, or (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU Affero General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU Affero General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. *
  31. */
  32. namespace OCA\Theming\Controller;
  33. use OC\Template\SCSSCacher;
  34. use OCA\Theming\ImageManager;
  35. use OCA\Theming\ThemingDefaults;
  36. use OCP\AppFramework\Controller;
  37. use OCP\AppFramework\Http;
  38. use OCP\AppFramework\Http\DataDownloadResponse;
  39. use OCP\AppFramework\Http\FileDisplayResponse;
  40. use OCP\AppFramework\Http\DataResponse;
  41. use OCP\AppFramework\Http\NotFoundResponse;
  42. use OCP\AppFramework\Utility\ITimeFactory;
  43. use OCP\Files\File;
  44. use OCP\Files\IAppData;
  45. use OCP\Files\NotFoundException;
  46. use OCP\Files\NotPermittedException;
  47. use OCP\IConfig;
  48. use OCP\IL10N;
  49. use OCP\IRequest;
  50. use OCA\Theming\Util;
  51. use OCP\ITempManager;
  52. use OCP\IURLGenerator;
  53. use OCP\App\IAppManager;
  54. /**
  55. * Class ThemingController
  56. *
  57. * handle ajax requests to update the theme
  58. *
  59. * @package OCA\Theming\Controller
  60. */
  61. class ThemingController extends Controller {
  62. /** @var ThemingDefaults */
  63. private $themingDefaults;
  64. /** @var Util */
  65. private $util;
  66. /** @var IL10N */
  67. private $l10n;
  68. /** @var IConfig */
  69. private $config;
  70. /** @var ITempManager */
  71. private $tempManager;
  72. /** @var IAppData */
  73. private $appData;
  74. /** @var SCSSCacher */
  75. private $scssCacher;
  76. /** @var IURLGenerator */
  77. private $urlGenerator;
  78. /** @var IAppManager */
  79. private $appManager;
  80. /** @var ImageManager */
  81. private $imageManager;
  82. /**
  83. * ThemingController constructor.
  84. *
  85. * @param string $appName
  86. * @param IRequest $request
  87. * @param IConfig $config
  88. * @param ThemingDefaults $themingDefaults
  89. * @param Util $util
  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. Util $util,
  104. IL10N $l,
  105. ITempManager $tempManager,
  106. IAppData $appData,
  107. SCSSCacher $scssCacher,
  108. IURLGenerator $urlGenerator,
  109. IAppManager $appManager,
  110. ImageManager $imageManager
  111. ) {
  112. parent::__construct($appName, $request);
  113. $this->themingDefaults = $themingDefaults;
  114. $this->util = $util;
  115. $this->l10n = $l;
  116. $this->config = $config;
  117. $this->tempManager = $tempManager;
  118. $this->appData = $appData;
  119. $this->scssCacher = $scssCacher;
  120. $this->urlGenerator = $urlGenerator;
  121. $this->appManager = $appManager;
  122. $this->imageManager = $imageManager;
  123. }
  124. /**
  125. * @param string $setting
  126. * @param string $value
  127. * @return DataResponse
  128. * @throws NotPermittedException
  129. */
  130. public function updateStylesheet($setting, $value) {
  131. $value = trim($value);
  132. switch ($setting) {
  133. case 'name':
  134. if (strlen($value) > 250) {
  135. return new DataResponse([
  136. 'data' => [
  137. 'message' => $this->l10n->t('The given name is too long'),
  138. ],
  139. 'status' => 'error'
  140. ]);
  141. }
  142. break;
  143. case 'url':
  144. if (strlen($value) > 500) {
  145. return new DataResponse([
  146. 'data' => [
  147. 'message' => $this->l10n->t('The given web address is too long'),
  148. ],
  149. 'status' => 'error'
  150. ]);
  151. }
  152. break;
  153. case 'imprintUrl':
  154. if (strlen($value) > 500) {
  155. return new DataResponse([
  156. 'data' => [
  157. 'message' => $this->l10n->t('The given legal notice address is too long'),
  158. ],
  159. 'status' => 'error'
  160. ]);
  161. }
  162. break;
  163. case 'privacyUrl':
  164. if (strlen($value) > 500) {
  165. return new DataResponse([
  166. 'data' => [
  167. 'message' => $this->l10n->t('The given privacy policy address is too long'),
  168. ],
  169. 'status' => 'error'
  170. ]);
  171. }
  172. break;
  173. case 'slogan':
  174. if (strlen($value) > 500) {
  175. return new DataResponse([
  176. 'data' => [
  177. 'message' => $this->l10n->t('The given slogan is too long'),
  178. ],
  179. 'status' => 'error'
  180. ]);
  181. }
  182. break;
  183. case 'color':
  184. if (!preg_match('/^\#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value)) {
  185. return new DataResponse([
  186. 'data' => [
  187. 'message' => $this->l10n->t('The given color is invalid'),
  188. ],
  189. 'status' => 'error'
  190. ]);
  191. }
  192. break;
  193. }
  194. $this->themingDefaults->set($setting, $value);
  195. // reprocess server scss for preview
  196. $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core');
  197. return new DataResponse(
  198. [
  199. 'data' =>
  200. [
  201. 'message' => $this->l10n->t('Saved'),
  202. 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss'))
  203. ],
  204. 'status' => 'success'
  205. ]
  206. );
  207. }
  208. /**
  209. * @return DataResponse
  210. * @throws NotPermittedException
  211. */
  212. public function uploadImage(): DataResponse {
  213. // logo / background
  214. // new: favicon logo-header
  215. //
  216. $key = $this->request->getParam('key');
  217. $image = $this->request->getUploadedFile('image');
  218. $error = null;
  219. $phpFileUploadErrors = [
  220. UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
  221. UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
  222. UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
  223. UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
  224. UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
  225. UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
  226. UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
  227. UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
  228. ];
  229. if (empty($image)) {
  230. $error = $this->l10n->t('No file uploaded');
  231. }
  232. if (!empty($image) && array_key_exists('error', $image) && $image['error'] !== UPLOAD_ERR_OK) {
  233. $error = $phpFileUploadErrors[$image['error']];
  234. }
  235. if ($error !== null) {
  236. return new DataResponse(
  237. [
  238. 'data' => [
  239. 'message' => $error
  240. ],
  241. 'status' => 'failure',
  242. ],
  243. Http::STATUS_UNPROCESSABLE_ENTITY
  244. );
  245. }
  246. $name = '';
  247. try {
  248. $folder = $this->appData->getFolder('images');
  249. } catch (NotFoundException $e) {
  250. $folder = $this->appData->newFolder('images');
  251. }
  252. $this->imageManager->delete($key);
  253. $target = $folder->newFile($key);
  254. $supportedFormats = $this->getSupportedUploadImageFormats($key);
  255. $detectedMimeType = mime_content_type($image['tmp_name']);
  256. if (!in_array($image['type'], $supportedFormats) || !in_array($detectedMimeType, $supportedFormats)) {
  257. return new DataResponse(
  258. [
  259. 'data' => [
  260. 'message' => $this->l10n->t('Unsupported image type'),
  261. ],
  262. 'status' => 'failure',
  263. ],
  264. Http::STATUS_UNPROCESSABLE_ENTITY
  265. );
  266. }
  267. $resizeKeys = ['background'];
  268. if (in_array($key, $resizeKeys, true)) {
  269. // Optimize the image since some people may upload images that will be
  270. // either to big or are not progressive rendering.
  271. $newImage = @imagecreatefromstring(file_get_contents($image['tmp_name'], 'r'));
  272. $tmpFile = $this->tempManager->getTemporaryFile();
  273. $newWidth = imagesx($newImage) < 4096 ? imagesx($newImage) : 4096;
  274. $newHeight = imagesy($newImage) / (imagesx($newImage) / $newWidth);
  275. $outputImage = imagescale($newImage, $newWidth, $newHeight);
  276. imageinterlace($outputImage, 1);
  277. imagejpeg($outputImage, $tmpFile, 75);
  278. imagedestroy($outputImage);
  279. $target->putContent(file_get_contents($tmpFile, 'r'));
  280. } else {
  281. $target->putContent(file_get_contents($image['tmp_name'], 'r'));
  282. }
  283. $name = $image['name'];
  284. $this->themingDefaults->set($key.'Mime', $image['type']);
  285. $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core');
  286. return new DataResponse(
  287. [
  288. 'data' =>
  289. [
  290. 'name' => $name,
  291. 'url' => $this->imageManager->getImageUrl($key),
  292. 'message' => $this->l10n->t('Saved'),
  293. 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss'))
  294. ],
  295. 'status' => 'success'
  296. ]
  297. );
  298. }
  299. /**
  300. * Returns a list of supported mime types for image uploads.
  301. * "favicon" images are only allowed to be SVG when imagemagick with SVG support is available.
  302. *
  303. * @param string $key The image key, e.g. "favicon"
  304. * @return array
  305. */
  306. private function getSupportedUploadImageFormats(string $key): array {
  307. $supportedFormats = ['image/jpeg', 'image/png', 'image/gif',];
  308. if ($key !== 'favicon' || $this->imageManager->shouldReplaceIcons() === true) {
  309. $supportedFormats[] = 'image/svg+xml';
  310. $supportedFormats[] = 'image/svg';
  311. }
  312. return $supportedFormats;
  313. }
  314. /**
  315. * Revert setting to default value
  316. *
  317. * @param string $setting setting which should be reverted
  318. * @return DataResponse
  319. * @throws NotPermittedException
  320. */
  321. public function undo(string $setting): DataResponse {
  322. $value = $this->themingDefaults->undo($setting);
  323. // reprocess server scss for preview
  324. $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core');
  325. if (strpos($setting, 'Mime') !== -1) {
  326. $imageKey = str_replace('Mime', '', $setting);
  327. $this->imageManager->delete($imageKey);
  328. }
  329. return new DataResponse(
  330. [
  331. 'data' =>
  332. [
  333. 'value' => $value,
  334. 'message' => $this->l10n->t('Saved'),
  335. 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss'))
  336. ],
  337. 'status' => 'success'
  338. ]
  339. );
  340. }
  341. /**
  342. * @PublicPage
  343. * @NoCSRFRequired
  344. *
  345. * @param string $key
  346. * @param bool $useSvg
  347. * @return FileDisplayResponse|NotFoundResponse
  348. * @throws NotPermittedException
  349. */
  350. public function getImage(string $key, bool $useSvg = true) {
  351. try {
  352. $file = $this->imageManager->getImage($key, $useSvg);
  353. } catch (NotFoundException $e) {
  354. return new NotFoundResponse();
  355. }
  356. $response = new FileDisplayResponse($file);
  357. $response->cacheFor(3600);
  358. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  359. $response->addHeader('Content-Disposition', 'attachment; filename="' . $key . '"');
  360. if (!$useSvg) {
  361. $response->addHeader('Content-Type', 'image/png');
  362. } else {
  363. $response->addHeader('Content-Type', $this->config->getAppValue($this->appName, $key . 'Mime', ''));
  364. }
  365. return $response;
  366. }
  367. /**
  368. * @NoCSRFRequired
  369. * @PublicPage
  370. * @NoSameSiteCookieRequired
  371. *
  372. * @return FileDisplayResponse|NotFoundResponse
  373. * @throws NotPermittedException
  374. * @throws \Exception
  375. * @throws \OCP\App\AppPathNotFoundException
  376. */
  377. public function getStylesheet() {
  378. $appPath = $this->appManager->getAppPath('theming');
  379. /* SCSSCacher is required here
  380. * We cannot rely on automatic caching done by \OC_Util::addStyle,
  381. * since we need to add the cacheBuster value to the url
  382. */
  383. $cssCached = $this->scssCacher->process($appPath, 'css/theming.scss', 'theming');
  384. if(!$cssCached) {
  385. return new NotFoundResponse();
  386. }
  387. try {
  388. $cssFile = $this->scssCacher->getCachedCSS('theming', 'theming.css');
  389. $response = new FileDisplayResponse($cssFile, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  390. $response->cacheFor(86400);
  391. return $response;
  392. } catch (NotFoundException $e) {
  393. return new NotFoundResponse();
  394. }
  395. }
  396. /**
  397. * @NoCSRFRequired
  398. * @PublicPage
  399. * @NoSameSiteCookieRequired
  400. *
  401. * @return DataDownloadResponse
  402. */
  403. public function getJavascript() {
  404. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  405. $responseJS = '(function() {
  406. OCA.Theming = {
  407. name: ' . json_encode($this->themingDefaults->getName()) . ',
  408. url: ' . json_encode($this->themingDefaults->getBaseUrl()) . ',
  409. slogan: ' . json_encode($this->themingDefaults->getSlogan()) . ',
  410. color: ' . json_encode($this->themingDefaults->getColorPrimary()) . ',
  411. imprintUrl: ' . json_encode($this->themingDefaults->getImprintUrl()) . ',
  412. privacyUrl: ' . json_encode($this->themingDefaults->getPrivacyUrl()) . ',
  413. inverted: ' . json_encode($this->util->invertTextColor($this->themingDefaults->getColorPrimary())) . ',
  414. cacheBuster: ' . json_encode($cacheBusterValue) . '
  415. };
  416. })();';
  417. $response = new DataDownloadResponse($responseJS, 'javascript', 'text/javascript');
  418. $response->cacheFor(3600);
  419. return $response;
  420. }
  421. /**
  422. * @NoCSRFRequired
  423. * @PublicPage
  424. *
  425. * @return Http\JSONResponse
  426. */
  427. public function getManifest($app) {
  428. $cacheBusterValue = $this->config->getAppValue('theming', 'cachebuster', '0');
  429. $responseJS = [
  430. 'name' => $this->themingDefaults->getName(),
  431. 'start_url' => $this->urlGenerator->getBaseUrl(),
  432. 'icons' =>
  433. [
  434. [
  435. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getTouchIcon',
  436. ['app' => $app]) . '?v=' . $cacheBusterValue,
  437. 'type'=> 'image/png',
  438. 'sizes'=> '128x128'
  439. ],
  440. [
  441. 'src' => $this->urlGenerator->linkToRoute('theming.Icon.getFavicon',
  442. ['app' => $app]) . '?v=' . $cacheBusterValue,
  443. 'type' => 'image/svg+xml',
  444. 'sizes' => '16x16'
  445. ]
  446. ],
  447. 'display' => 'standalone'
  448. ];
  449. $response = new Http\JSONResponse($responseJS);
  450. $response->cacheFor(3600);
  451. return $response;
  452. }
  453. }