AccessibilityController.php 7.8 KB

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