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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. /** @var string */
  47. protected $appName;
  48. /** @var string */
  49. protected $serverRoot;
  50. /** @var IConfig */
  51. private $config;
  52. /** @var LoggerInterface */
  53. private $logger;
  54. /** @var ITimeFactory */
  55. protected $timeFactory;
  56. /** @var IUserSession */
  57. private $userSession;
  58. /** @var IconsCacher */
  59. protected $iconsCacher;
  60. /** @var \OC_Defaults */
  61. private $defaults;
  62. /** @var null|string */
  63. private $injectedVariables;
  64. /** @var string */
  65. private $appRoot;
  66. public function __construct(string $appName,
  67. IRequest $request,
  68. IConfig $config,
  69. LoggerInterface $logger,
  70. ITimeFactory $timeFactory,
  71. IUserSession $userSession,
  72. IAppManager $appManager,
  73. IconsCacher $iconsCacher,
  74. \OC_Defaults $defaults) {
  75. parent::__construct($appName, $request);
  76. $this->appName = $appName;
  77. $this->config = $config;
  78. $this->logger = $logger;
  79. $this->timeFactory = $timeFactory;
  80. $this->userSession = $userSession;
  81. $this->iconsCacher = $iconsCacher;
  82. $this->defaults = $defaults;
  83. $this->serverRoot = \OC::$SERVERROOT;
  84. $this->appRoot = $appManager->getAppPath($this->appName);
  85. }
  86. /**
  87. * @PublicPage
  88. * @NoCSRFRequired
  89. * @NoSameSiteCookieRequired
  90. *
  91. * @return DataDisplayResponse
  92. */
  93. public function getCss(): DataDisplayResponse {
  94. $css = '';
  95. $imports = '';
  96. if ($this->userSession->isLoggedIn()) {
  97. $userValues = $this->getUserValues();
  98. } else {
  99. $userValues = ['dark'];
  100. }
  101. foreach ($userValues as $key => $scssFile) {
  102. if ($scssFile !== false) {
  103. if ($scssFile === 'highcontrast' && in_array('dark', $userValues)) {
  104. $scssFile .= 'dark';
  105. }
  106. $imports .= '@import "' . $scssFile . '";';
  107. }
  108. }
  109. if ($imports !== '') {
  110. $scss = new Compiler();
  111. $scss->setImportPaths([
  112. $this->appRoot . '/css/',
  113. $this->serverRoot . '/core/css/'
  114. ]);
  115. // Continue after throw
  116. $scss->setOutputStyle(OutputStyle::COMPRESSED);
  117. // Import theme, variables and compile css4 variables
  118. try {
  119. $css .= $scss->compile(
  120. $imports .
  121. $this->getInjectedVariables() .
  122. '@import "variables.scss";' .
  123. '@import "css-variables.scss";'
  124. );
  125. } catch (ParserException $e) {
  126. $this->logger->error($e->getMessage(),
  127. [
  128. 'app' => 'core',
  129. 'exception' => $e,
  130. ]
  131. );
  132. }
  133. }
  134. // We don't want to override vars with url since path is different
  135. $css = $this->filterOutRule('/--[a-z-:]+url\([^;]+\)/mi', $css);
  136. // Rebase all urls
  137. $appWebRoot = substr($this->appRoot, strlen($this->serverRoot) - strlen(\OC::$WEBROOT));
  138. $css = $this->rebaseUrls($css, $appWebRoot . '/css');
  139. if (in_array('dark', $userValues) && $this->iconsCacher->getCachedList() && $this->iconsCacher->getCachedList()->getSize() > 0) {
  140. $iconsCss = $this->invertSvgIconsColor($this->iconsCacher->getCachedList()->getContent());
  141. $css = $css . $iconsCss;
  142. }
  143. $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']);
  144. // Set cache control
  145. $ttl = 31536000;
  146. $response->addHeader('Cache-Control', 'max-age=' . $ttl . ', immutable');
  147. $expires = new \DateTime();
  148. $expires->setTimestamp($this->timeFactory->getTime());
  149. $expires->add(new \DateInterval('PT' . $ttl . 'S'));
  150. $response->addHeader('Expires', $expires->format(\DateTime::RFC1123));
  151. $response->addHeader('Pragma', 'cache');
  152. // store current cache hash
  153. if ($this->userSession->isLoggedIn()) {
  154. $this->config->setUserValue($this->userSession->getUser()->getUID(), $this->appName, 'icons-css', md5($css));
  155. }
  156. return $response;
  157. }
  158. /**
  159. * Return an array with the user theme & font settings
  160. *
  161. * @return array
  162. */
  163. private function getUserValues(): array {
  164. $userTheme = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'theme', false);
  165. $userFont = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'font', false);
  166. $userHighContrast = $this->config->getUserValue($this->userSession->getUser()->getUID(), $this->appName, 'highcontrast', false);
  167. return [$userTheme, $userHighContrast, $userFont];
  168. }
  169. /**
  170. * Remove all matches from the $rule regex
  171. *
  172. * @param string $rule regex to match
  173. * @param string $css string to parse
  174. * @return string
  175. */
  176. private function filterOutRule(string $rule, string $css): string {
  177. return preg_replace($rule, '', $css);
  178. }
  179. /**
  180. * Add the correct uri prefix to make uri valid again
  181. *
  182. * @param string $css
  183. * @param string $webDir
  184. * @return string
  185. */
  186. private function rebaseUrls(string $css, string $webDir): string {
  187. $re = '/url\([\'"]([^\/][\.\w?=\/-]*)[\'"]\)/x';
  188. $subst = 'url(\'' . $webDir . '/$1\')';
  189. return preg_replace($re, $subst, $css);
  190. }
  191. /**
  192. * Remove all matches from the $rule regex
  193. *
  194. * @param string $css string to parse
  195. * @return string
  196. */
  197. private function invertSvgIconsColor(string $css) {
  198. return str_replace(
  199. ['color=000&', 'color=fff&', 'color=***&'],
  200. ['color=***&', 'color=000&', 'color=fff&'],
  201. str_replace(
  202. ['color=000000&', 'color=ffffff&', 'color=******&'],
  203. ['color=******&', 'color=000000&', 'color=ffffff&'],
  204. $css
  205. )
  206. );
  207. }
  208. /**
  209. * @return string SCSS code for variables from OC_Defaults
  210. */
  211. private function getInjectedVariables(): string {
  212. if ($this->injectedVariables !== null) {
  213. return $this->injectedVariables;
  214. }
  215. $variables = '';
  216. foreach ($this->defaults->getScssVariables() as $key => $value) {
  217. $variables .= '$' . $key . ': ' . $value . ';';
  218. }
  219. // check for valid variables / otherwise fall back to defaults
  220. try {
  221. $scss = new Compiler();
  222. $scss->compile($variables);
  223. $this->injectedVariables = $variables;
  224. } catch (ParserException $e) {
  225. $this->logger->error($e->getMessage(),
  226. [
  227. 'app' => 'core',
  228. 'exception' => $e,
  229. ]
  230. );
  231. }
  232. return $variables;
  233. }
  234. }