AccessibilityController.php 7.5 KB

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