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.

AccessibilityController.php 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  5. * @copyright Copyright (c) 2019 Janis Köhr <janiskoehr@icloud.com>
  6. *
  7. * @author Alexey Pyltsyn <lex61rus@gmail.com>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Janis Köhr <janis.koehr@novatec-gmbh.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  12. * @author Julius Härtl <jus@bitgrid.net>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Thomas Citharel <nextcloud@tcit.fr>
  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\Accessibility\Controller;
  33. use OC\Template\IconsCacher;
  34. use OCP\App\IAppManager;
  35. use OCP\AppFramework\Controller;
  36. use OCP\AppFramework\Http;
  37. use OCP\AppFramework\Http\DataDisplayResponse;
  38. use OCP\AppFramework\Http\DataDownloadResponse;
  39. use OCP\AppFramework\Utility\ITimeFactory;
  40. use OCP\IConfig;
  41. use OCP\ILogger;
  42. use OCP\IRequest;
  43. use OCP\IURLGenerator;
  44. use OCP\IUserManager;
  45. use OCP\IUserSession;
  46. use ScssPhp\ScssPhp\Compiler;
  47. use ScssPhp\ScssPhp\Exception\ParserException;
  48. use ScssPhp\ScssPhp\Formatter\Crunched;
  49. class AccessibilityController extends Controller {
  50. /** @var string */
  51. protected $appName;
  52. /** @var string */
  53. protected $serverRoot;
  54. /** @var IConfig */
  55. private $config;
  56. /** @var IUserManager */
  57. private $userManager;
  58. /** @var ILogger */
  59. private $logger;
  60. /** @var IURLGenerator */
  61. private $urlGenerator;
  62. /** @var ITimeFactory */
  63. protected $timeFactory;
  64. /** @var IUserSession */
  65. private $userSession;
  66. /** @var IAppManager */
  67. private $appManager;
  68. /** @var IconsCacher */
  69. protected $iconsCacher;
  70. /** @var \OC_Defaults */
  71. private $defaults;
  72. /** @var null|string */
  73. private $injectedVariables;
  74. /**
  75. * Account constructor.
  76. *
  77. * @param string $appName
  78. * @param IRequest $request
  79. * @param IConfig $config
  80. * @param IUserManager $userManager
  81. * @param ILogger $logger
  82. * @param IURLGenerator $urlGenerator
  83. * @param ITimeFactory $timeFactory
  84. * @param IUserSession $userSession
  85. * @param IAppManager $appManager
  86. * @param \OC_Defaults $defaults
  87. */
  88. public function __construct(string $appName,
  89. IRequest $request,
  90. IConfig $config,
  91. IUserManager $userManager,
  92. ILogger $logger,
  93. IURLGenerator $urlGenerator,
  94. ITimeFactory $timeFactory,
  95. IUserSession $userSession,
  96. IAppManager $appManager,
  97. IconsCacher $iconsCacher,
  98. \OC_Defaults $defaults) {
  99. parent::__construct($appName, $request);
  100. $this->appName = $appName;
  101. $this->config = $config;
  102. $this->userManager = $userManager;
  103. $this->logger = $logger;
  104. $this->urlGenerator = $urlGenerator;
  105. $this->timeFactory = $timeFactory;
  106. $this->userSession = $userSession;
  107. $this->appManager = $appManager;
  108. $this->iconsCacher = $iconsCacher;
  109. $this->defaults = $defaults;
  110. $this->serverRoot = \OC::$SERVERROOT;
  111. $this->appRoot = $this->appManager->getAppPath($this->appName);
  112. }
  113. /**
  114. * @NoAdminRequired
  115. * @NoCSRFRequired
  116. * @NoSameSiteCookieRequired
  117. *
  118. * @return DataDisplayResponse
  119. */
  120. public function getCss(): DataDisplayResponse {
  121. $css = '';
  122. $imports = '';
  123. $userValues = $this->getUserValues();
  124. foreach ($userValues as $key => $scssFile) {
  125. if ($scssFile !== false) {
  126. if ($scssFile === 'highcontrast' && in_array('dark', $userValues)) {
  127. $scssFile .= 'dark';
  128. }
  129. $imports .= '@import "' . $scssFile . '";';
  130. }
  131. }
  132. if ($imports !== '') {
  133. $scss = new Compiler();
  134. $scss->setImportPaths([
  135. $this->appRoot . '/css/',
  136. $this->serverRoot . '/core/css/'
  137. ]);
  138. // Continue after throw
  139. $scss->setIgnoreErrors(true);
  140. $scss->setFormatter(Crunched::class);
  141. // Import theme, variables and compile css4 variables
  142. try {
  143. $css .= $scss->compile(
  144. $imports .
  145. $this->getInjectedVariables() .
  146. '@import "variables.scss";' .
  147. '@import "css-variables.scss";'
  148. );
  149. } catch (ParserException $e) {
  150. $this->logger->error($e->getMessage(), ['app' => 'core']);
  151. }
  152. }
  153. // We don't want to override vars with url since path is different
  154. $css = $this->filterOutRule('/--[a-z-:]+url\([^;]+\)/mi', $css);
  155. // Rebase all urls
  156. $appWebRoot = substr($this->appRoot, strlen($this->serverRoot) - strlen(\OC::$WEBROOT));
  157. $css = $this->rebaseUrls($css, $appWebRoot . '/css');
  158. if (in_array('dark', $userValues) && $this->iconsCacher->getCachedList() && $this->iconsCacher->getCachedList()->getSize() > 0) {
  159. $iconsCss = $this->invertSvgIconsColor($this->iconsCacher->getCachedList()->getContent());
  160. $css = $css . $iconsCss;
  161. }
  162. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  163. // Set cache control
  164. $ttl = 31536000;
  165. $response->addHeader('Cache-Control', 'max-age=' . $ttl . ', immutable');
  166. $expires = new \DateTime();
  167. $expires->setTimestamp($this->timeFactory->getTime());
  168. $expires->add(new \DateInterval('PT' . $ttl . 'S'));
  169. $response->addHeader('Expires', $expires->format(\DateTime::RFC1123));
  170. $response->addHeader('Pragma', 'cache');
  171. // store current cache hash
  172. $this->config->setUserValue($this->userSession->getUser()->getUID(), $this->appName, 'icons-css', md5($css));
  173. return $response;
  174. }
  175. /**
  176. * @NoCSRFRequired
  177. * @PublicPage
  178. * @NoSameSiteCookieRequired
  179. *
  180. * @return DataDownloadResponse
  181. */
  182. public function getJavascript(): DataDownloadResponse {
  183. $user = $this->userSession->getUser();
  184. if ($user === null) {
  185. $theme = false;
  186. $highcontrast = false;
  187. } else {
  188. $theme = $this->config->getUserValue($user->getUID(), $this->appName, 'theme', false);
  189. $highcontrast = $this->config->getUserValue($user->getUID(), $this->appName, 'highcontrast', false) !== false;
  190. }
  191. if ($theme !== false) {
  192. $responseJS = '(function() {
  193. OCA.Accessibility = {
  194. highcontrast: ' . json_encode($highcontrast) . ',
  195. theme: ' . json_encode($theme) . ',
  196. };
  197. document.body.classList.add(' . json_encode($theme) . ');
  198. })();';
  199. } else {
  200. $responseJS = '(function() {
  201. OCA.Accessibility = {
  202. highcontrast: ' . json_encode($highcontrast) . ',
  203. theme: ' . json_encode($theme) . ',
  204. };
  205. })();';
  206. }
  207. $response = new DataDownloadResponse($responseJS, 'javascript', 'text/javascript');
  208. $response->cacheFor(3600);
  209. return $response;
  210. }
  211. /**
  212. * Return an array with the user theme & font settings
  213. *
  214. * @return array
  215. */
  216. private function getUserValues(): array{
  217. $userTheme = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'theme', false);
  218. $userFont = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'font', false);
  219. $userHighContrast = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'highcontrast', false);
  220. return [$userTheme, $userHighContrast, $userFont];
  221. }
  222. /**
  223. * Remove all matches from the $rule regex
  224. *
  225. * @param string $rule regex to match
  226. * @param string $css string to parse
  227. * @return string
  228. */
  229. private function filterOutRule(string $rule, string $css): string {
  230. return preg_replace($rule, '', $css);
  231. }
  232. /**
  233. * Add the correct uri prefix to make uri valid again
  234. *
  235. * @param string $css
  236. * @param string $webDir
  237. * @return string
  238. */
  239. private function rebaseUrls(string $css, string $webDir): string {
  240. $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
  241. $subst = 'url(\'' . $webDir . '/$1\')';
  242. return preg_replace($re, $subst, $css);
  243. }
  244. /**
  245. * Remove all matches from the $rule regex
  246. *
  247. * @param string $css string to parse
  248. * @return string
  249. */
  250. private function invertSvgIconsColor(string $css) {
  251. return str_replace(
  252. ['color=000&', 'color=fff&', 'color=***&'],
  253. ['color=***&', 'color=000&', 'color=fff&'],
  254. str_replace(
  255. ['color=000000&', 'color=ffffff&', 'color=******&'],
  256. ['color=******&', 'color=000000&', 'color=ffffff&'],
  257. $css
  258. )
  259. );
  260. }
  261. /**
  262. * @return string SCSS code for variables from OC_Defaults
  263. */
  264. private function getInjectedVariables(): string {
  265. if ($this->injectedVariables !== null) {
  266. return $this->injectedVariables;
  267. }
  268. $variables = '';
  269. foreach ($this->defaults->getScssVariables() as $key => $value) {
  270. $variables .= '$' . $key . ': ' . $value . ';';
  271. }
  272. // check for valid variables / otherwise fall back to defaults
  273. try {
  274. $scss = new Compiler();
  275. $scss->compile($variables);
  276. $this->injectedVariables = $variables;
  277. } catch (ParserException $e) {
  278. $this->logger->logException($e, ['app' => 'core']);
  279. }
  280. return $variables;
  281. }
  282. }