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.0KB

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