PageRenderTime 27ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/theme/styles.php

https://github.com/mackensen/moodle
PHP | 312 lines | 147 code | 50 blank | 115 comment | 35 complexity | 826be079c3421f0415036ba3cd49e02a MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This file is responsible for serving the one huge CSS of each theme.
  18. *
  19. * @package core
  20. * @copyright 2009 Petr Skoda (skodak) {@link http://skodak.org}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. // Disable moodle specific debug messages and any errors in output,
  24. // comment out when debugging or better look into error log!
  25. define('NO_DEBUG_DISPLAY', true);
  26. define('ABORT_AFTER_CONFIG', true);
  27. require('../config.php');
  28. require_once($CFG->dirroot.'/lib/csslib.php');
  29. if ($slashargument = min_get_slash_argument()) {
  30. $slashargument = ltrim($slashargument, '/');
  31. if (substr_count($slashargument, '/') < 2) {
  32. css_send_css_not_found();
  33. }
  34. if (strpos($slashargument, '_s/') === 0) {
  35. // Can't use SVG.
  36. $slashargument = substr($slashargument, 3);
  37. $usesvg = false;
  38. } else {
  39. $usesvg = true;
  40. }
  41. list($themename, $rev, $type) = explode('/', $slashargument, 3);
  42. $themename = min_clean_param($themename, 'SAFEDIR');
  43. $rev = min_clean_param($rev, 'RAW');
  44. $type = min_clean_param($type, 'SAFEDIR');
  45. } else {
  46. $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
  47. $rev = min_optional_param('rev', 0, 'RAW');
  48. $type = min_optional_param('type', 'all', 'SAFEDIR');
  49. $usesvg = (bool)min_optional_param('svg', '1', 'INT');
  50. }
  51. // Check if we received a theme sub revision which allows us
  52. // to handle local caching on a per theme basis.
  53. $values = explode('_', $rev);
  54. $rev = min_clean_param(array_shift($values), 'INT');
  55. $themesubrev = array_shift($values);
  56. if (!is_null($themesubrev)) {
  57. $themesubrev = min_clean_param($themesubrev, 'INT');
  58. }
  59. // Check that type fits into the expected values.
  60. if (!in_array($type, ['all', 'all-rtl', 'editor'])) {
  61. css_send_css_not_found();
  62. }
  63. if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
  64. // The theme exists in standard location - ok.
  65. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
  66. // Alternative theme location contains this theme - ok.
  67. } else {
  68. header('HTTP/1.0 404 not found');
  69. die('Theme was not found, sorry.');
  70. }
  71. $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
  72. $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
  73. $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg);
  74. if (file_exists($candidatesheet)) {
  75. if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  76. // We do not actually need to verify the etag value because our files
  77. // never change in cache because we increment the rev counter.
  78. css_send_unmodified(filemtime($candidatesheet), $etag);
  79. }
  80. css_send_cached_css($candidatesheet, $etag);
  81. }
  82. // Ok, now we need to start normal moodle script, we need to load all libs and $DB.
  83. define('ABORT_AFTER_CONFIG_CANCEL', true);
  84. define('NO_MOODLE_COOKIES', true); // Session not used here.
  85. define('NO_UPGRADE_CHECK', true); // Ignore upgrade check.
  86. require("$CFG->dirroot/lib/setup.php");
  87. $theme = theme_config::load($themename);
  88. $theme->force_svg_use($usesvg);
  89. $theme->set_rtl_mode($type === 'all-rtl' ? true : false);
  90. $themerev = theme_get_revision();
  91. $currentthemesubrev = theme_get_sub_revision_for_theme($themename);
  92. $cache = true;
  93. // If the client is requesting a revision that doesn't match both
  94. // the global theme revision and the theme specific revision then
  95. // tell the browser not to cache this style sheet because it's
  96. // likely being regenerated.
  97. if ($themerev <= 0 or $themerev != $rev or $themesubrev != $currentthemesubrev) {
  98. $rev = $themerev;
  99. $themesubrev = $currentthemesubrev;
  100. $cache = false;
  101. $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
  102. $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
  103. $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg);
  104. }
  105. make_localcache_directory('theme', false);
  106. if ($type === 'editor') {
  107. $csscontent = $theme->get_css_content_editor();
  108. if ($cache) {
  109. css_store_css($theme, $candidatesheet, $csscontent);
  110. css_send_cached_css($candidatesheet, $etag);
  111. } else {
  112. css_send_uncached_css($csscontent);
  113. }
  114. }
  115. if (($fallbacksheet = theme_styles_fallback_content($theme)) && !$theme->has_css_cached_content()) {
  116. // The theme is not yet available and a fallback is available.
  117. // Return the fallback immediately, specifying the Content-Length, then generate in the background.
  118. $css = file_get_contents($fallbacksheet);
  119. css_send_temporary_css($css);
  120. // The fallback content has now been sent.
  121. // There will be an attempt to generate the content, but it should not be served.
  122. // The Content-Length above means that the client will disregard it anyway.
  123. $sendaftergeneration = false;
  124. // There may be another client currently holding a lock and generating the stylesheet.
  125. // Use a very low lock timeout as the connection will be ended immediately afterwards.
  126. $locktimeout = 1;
  127. } else {
  128. // There is no fallback content to be issued here, therefore the generated content must be output.
  129. $sendaftergeneration = true;
  130. // Use a realistic lock timeout as the intention is to avoid lock contention.
  131. $locktimeout = rand(90, 120);
  132. }
  133. // Attempt to fetch the lock.
  134. $lockfactory = \core\lock\lock_config::get_lock_factory('core_theme_get_css_content');
  135. $lock = $lockfactory->get_lock($themename, $locktimeout);
  136. if ($sendaftergeneration || $lock) {
  137. // Either the lock was successful, or the lock was unsuccessful but the content *must* be sent.
  138. // The content does not exist locally.
  139. // Generate and save it.
  140. $candidatesheet = theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir);
  141. if ($lock) {
  142. $lock->release();
  143. }
  144. if ($sendaftergeneration) {
  145. if (!$cache) {
  146. // Do not pollute browser caches if invalid revision requested,
  147. // let's ignore legacy IE breakage here too.
  148. css_send_uncached_css(file_get_contents($candidatesheet));
  149. } else {
  150. // Real browsers - this is the expected result!
  151. css_send_cached_css($candidatesheet, $etag);
  152. }
  153. }
  154. }
  155. /**
  156. * Generate the theme CSS and store it.
  157. *
  158. * @param theme_config $theme The theme to be generated
  159. * @param int $rev The theme revision
  160. * @param int $themesubrev The theme sub-revision
  161. * @param string $candidatedir The directory that it should be stored in
  162. * @return string The path that the primary CSS was written to
  163. */
  164. function theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir) {
  165. global $CFG;
  166. require_once("{$CFG->libdir}/filelib.php");
  167. // Generate the content first.
  168. if (!$csscontent = $theme->get_css_cached_content()) {
  169. $csscontent = $theme->get_css_content();
  170. $theme->set_css_content_cache($csscontent);
  171. }
  172. if ($theme->get_rtl_mode()) {
  173. $type = "all-rtl";
  174. } else {
  175. $type = "all";
  176. }
  177. // Determine the candidatesheet path.
  178. $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $theme->use_svg_icons());
  179. // Store the CSS.
  180. css_store_css($theme, $candidatesheet, $csscontent);
  181. // Store the fallback CSS in the temp directory.
  182. // This file is used as a fallback when waiting for a theme to compile and is not versioned in any way.
  183. $fallbacksheet = make_temp_directory("theme/{$theme->name}")
  184. . "/"
  185. . theme_styles_get_filename($type, 0, $theme->use_svg_icons());
  186. css_store_css($theme, $fallbacksheet, $csscontent);
  187. // Delete older revisions from localcache.
  188. $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR);
  189. foreach ($themecachedirs as $localcachedir) {
  190. $cachedrev = [];
  191. preg_match("/\/theme\/([0-9]+)$/", $localcachedir, $cachedrev);
  192. $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
  193. if ($cachedrev > 0 && $cachedrev < $rev) {
  194. fulldelete($localcachedir);
  195. }
  196. }
  197. // Delete older theme subrevision CSS from localcache.
  198. $subrevfiles = glob("{$CFG->localcachedir}/theme/{$rev}/{$theme->name}/css/*.css");
  199. foreach ($subrevfiles as $subrevfile) {
  200. $cachedsubrev = [];
  201. preg_match("/_([0-9]+)\.([0-9]+\.)?css$/", $subrevfile, $cachedsubrev);
  202. $cachedsubrev = isset($cachedsubrev[1]) ? intval($cachedsubrev[1]) : 0;
  203. if ($cachedsubrev > 0 && $cachedsubrev < $themesubrev) {
  204. fulldelete($subrevfile);
  205. }
  206. }
  207. return $candidatesheet;
  208. }
  209. /**
  210. * Fetch the preferred fallback content location if available.
  211. *
  212. * @param theme_config $theme The theme to be generated
  213. * @return string The path to the fallback sheet on disk
  214. */
  215. function theme_styles_fallback_content($theme) {
  216. global $CFG;
  217. if (!$theme->usefallback) {
  218. // This theme does not support fallbacks.
  219. return false;
  220. }
  221. $type = $theme->get_rtl_mode() ? 'all-rtl' : 'all';
  222. $filename = theme_styles_get_filename($type);
  223. $fallbacksheet = "{$CFG->tempdir}/theme/{$theme->name}/{$filename}";
  224. if (file_exists($fallbacksheet)) {
  225. return $fallbacksheet;
  226. }
  227. return false;
  228. }
  229. /**
  230. * Get the filename for the specified configuration.
  231. *
  232. * @param string $type The requested sheet type
  233. * @param int $themesubrev The theme sub-revision
  234. * @param bool $usesvg Whether SVGs are allowed
  235. * @return string The filename for this sheet
  236. */
  237. function theme_styles_get_filename($type, $themesubrev = 0, $usesvg = true) {
  238. $filename = $type;
  239. $filename .= ($themesubrev > 0) ? "_{$themesubrev}" : '';
  240. $filename .= $usesvg ? '' : '-nosvg';
  241. return "{$filename}.css";
  242. }
  243. /**
  244. * Determine the correct etag for the specified configuration.
  245. *
  246. * @param string $themename The name of the theme
  247. * @param int $rev The revision number
  248. * @param string $type The requested sheet type
  249. * @param int $themesubrev The theme sub-revision
  250. * @param bool $usesvg Whether SVGs are allowed
  251. * @return string The etag to use for this request
  252. */
  253. function theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg) {
  254. $etag = [$rev, $themename, $type, $themesubrev];
  255. if (!$usesvg) {
  256. $etag[] = 'nosvg';
  257. }
  258. return sha1(implode('/', $etag));
  259. }