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 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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) <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\ILogger;
  40. use OCP\IRequest;
  41. use OCP\IURLGenerator;
  42. use OCP\IUserManager;
  43. use OCP\IUserSession;
  44. use ScssPhp\ScssPhp\Compiler;
  45. use ScssPhp\ScssPhp\Exception\ParserException;
  46. use ScssPhp\ScssPhp\Formatter\Crunched;
  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. * @PublicPage
  113. * @NoCSRFRequired
  114. * @NoSameSiteCookieRequired
  115. *
  116. * @return DataDisplayResponse
  117. */
  118. public function getCss(): DataDisplayResponse {
  119. $css = '';
  120. $imports = '';
  121. if ($this->userSession->isLoggedIn()) {
  122. $userValues = $this->getUserValues();
  123. } else {
  124. $userValues = ['dark'];
  125. }
  126. foreach ($userValues as $key => $scssFile) {
  127. if ($scssFile !== false) {
  128. if ($scssFile === 'highcontrast' && in_array('dark', $userValues)) {
  129. $scssFile .= 'dark';
  130. }
  131. $imports .= '@import "' . $scssFile . '";';
  132. }
  133. }
  134. if ($imports !== '') {
  135. $scss = new Compiler();
  136. $scss->setImportPaths([
  137. $this->appRoot . '/css/',
  138. $this->serverRoot . '/core/css/'
  139. ]);
  140. // Continue after throw
  141. $scss->setIgnoreErrors(true);
  142. $scss->setFormatter(Crunched::class);
  143. // Import theme, variables and compile css4 variables
  144. try {
  145. $css .= $scss->compile(
  146. $imports .
  147. $this->getInjectedVariables() .
  148. '@import "variables.scss";' .
  149. '@import "css-variables.scss";'
  150. );
  151. } catch (ParserException $e) {
  152. $this->logger->error($e->getMessage(), ['app' => 'core']);
  153. }
  154. }
  155. // We don't want to override vars with url since path is different
  156. $css = $this->filterOutRule('/--[a-z-:]+url\([^;]+\)/mi', $css);
  157. // Rebase all urls
  158. $appWebRoot = substr($this->appRoot, strlen($this->serverRoot) - strlen(\OC::$WEBROOT));
  159. $css = $this->rebaseUrls($css, $appWebRoot . '/css');
  160. if (in_array('dark', $userValues) && $this->iconsCacher->getCachedList() && $this->iconsCacher->getCachedList()->getSize() > 0) {
  161. $iconsCss = $this->invertSvgIconsColor($this->iconsCacher->getCachedList()->getContent());
  162. $css = $css . $iconsCss;
  163. }
  164. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  165. // Set cache control
  166. $ttl = 31536000;
  167. $response->addHeader('Cache-Control', 'max-age=' . $ttl . ', immutable');
  168. $expires = new \DateTime();
  169. $expires->setTimestamp($this->timeFactory->getTime());
  170. $expires->add(new \DateInterval('PT' . $ttl . 'S'));
  171. $response->addHeader('Expires', $expires->format(\DateTime::RFC1123));
  172. $response->addHeader('Pragma', 'cache');
  173. // store current cache hash
  174. if ($this->userSession->isLoggedIn()) {
  175. $this->config->setUserValue($this->userSession->getUser()->getUID(), $this->appName, 'icons-css', md5($css));
  176. }
  177. return $response;
  178. }
  179. /**
  180. * Return an array with the user theme & font settings
  181. *
  182. * @return array
  183. */
  184. private function getUserValues(): array {
  185. $userTheme = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'theme', false);
  186. $userFont = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'font', false);
  187. $userHighContrast = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'highcontrast', false);
  188. return [$userTheme, $userHighContrast, $userFont];
  189. }
  190. /**
  191. * Remove all matches from the $rule regex
  192. *
  193. * @param string $rule regex to match
  194. * @param string $css string to parse
  195. * @return string
  196. */
  197. private function filterOutRule(string $rule, string $css): string {
  198. return preg_replace($rule, '', $css);
  199. }
  200. /**
  201. * Add the correct uri prefix to make uri valid again
  202. *
  203. * @param string $css
  204. * @param string $webDir
  205. * @return string
  206. */
  207. private function rebaseUrls(string $css, string $webDir): string {
  208. $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
  209. $subst = 'url(\'' . $webDir . '/$1\')';
  210. return preg_replace($re, $subst, $css);
  211. }
  212. /**
  213. * Remove all matches from the $rule regex
  214. *
  215. * @param string $css string to parse
  216. * @return string
  217. */
  218. private function invertSvgIconsColor(string $css) {
  219. return str_replace(
  220. ['color=000&', 'color=fff&', 'color=***&'],
  221. ['color=***&', 'color=000&', 'color=fff&'],
  222. str_replace(
  223. ['color=000000&', 'color=ffffff&', 'color=******&'],
  224. ['color=******&', 'color=000000&', 'color=ffffff&'],
  225. $css
  226. )
  227. );
  228. }
  229. /**
  230. * @return string SCSS code for variables from OC_Defaults
  231. */
  232. private function getInjectedVariables(): string {
  233. if ($this->injectedVariables !== null) {
  234. return $this->injectedVariables;
  235. }
  236. $variables = '';
  237. foreach ($this->defaults->getScssVariables() as $key => $value) {
  238. $variables .= '$' . $key . ': ' . $value . ';';
  239. }
  240. // check for valid variables / otherwise fall back to defaults
  241. try {
  242. $scss = new Compiler();
  243. $scss->compile($variables);
  244. $this->injectedVariables = $variables;
  245. } catch (ParserException $e) {
  246. $this->logger->logException($e, ['app' => 'core']);
  247. }
  248. return $variables;
  249. }
  250. }