2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * This file is responsible for serving the one huge CSS of each theme.
21 * @copyright 2009 Petr Skoda (skodak) {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 // Disable moodle specific debug messages and any errors in output,
26 // comment out when debugging or better look into error log!
27 define('NO_DEBUG_DISPLAY', true);
29 define('ABORT_AFTER_CONFIG', true);
30 require('../config.php');
31 require_once($CFG->dirroot
.'/lib/csslib.php');
33 if ($slashargument = min_get_slash_argument()) {
34 $slashargument = ltrim($slashargument, '/');
35 if (substr_count($slashargument, '/') < 2) {
36 css_send_css_not_found();
39 if (strpos($slashargument, '_s/') === 0) {
41 $slashargument = substr($slashargument, 3);
47 list($themename, $rev, $type) = explode('/', $slashargument, 3);
48 $themename = min_clean_param($themename, 'SAFEDIR');
49 $rev = min_clean_param($rev, 'RAW');
50 $type = min_clean_param($type, 'SAFEDIR');
53 $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
54 $rev = min_optional_param('rev', 0, 'RAW');
55 $type = min_optional_param('type', 'all', 'SAFEDIR');
56 $usesvg = (bool)min_optional_param('svg', '1', 'INT');
59 // Check if we received a theme sub revision which allows us
60 // to handle local caching on a per theme basis.
61 $values = explode('_', $rev);
62 $rev = min_clean_param(array_shift($values), 'INT');
63 $themesubrev = array_shift($values);
65 if (!is_null($themesubrev)) {
66 $themesubrev = min_clean_param($themesubrev, 'INT');
69 // Check that type fits into the expected values.
70 if (!in_array($type, ['all', 'all-rtl', 'editor'])) {
71 css_send_css_not_found();
74 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
75 // The theme exists in standard location - ok.
76 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$themename/config.php")) {
77 // Alternative theme location contains this theme - ok.
79 header('HTTP/1.0 404 not found');
80 die('Theme was not found, sorry.');
83 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
84 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
85 $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg);
87 // Ok, now we need to start normal moodle script, we need to load all libs and $DB.
88 define('ABORT_AFTER_CONFIG_CANCEL', true);
90 define('NO_MOODLE_COOKIES', true); // Session not used here.
91 define('NO_UPGRADE_CHECK', true); // Ignore upgrade check.
93 require("$CFG->dirroot/lib/setup.php");
95 $theme = theme_config
::load($themename);
96 $theme->force_svg_use($usesvg);
97 $theme->set_rtl_mode($type === 'all-rtl' ?
true : false);
99 $themerev = theme_get_revision();
100 $currentthemesubrev = theme_get_sub_revision_for_theme($themename);
103 // If the client is requesting a revision that doesn't match both
104 // the global theme revision and the theme specific revision then
105 // tell the browser not to cache this style sheet because it's
106 // likely being regenerated.
107 if ($themerev <= 0 or $themerev != $rev or $themesubrev != $currentthemesubrev) {
109 $themesubrev = $currentthemesubrev;
112 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
113 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
114 $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg);
117 make_localcache_directory('theme', false);
119 if ($type === 'editor') {
120 $csscontent = $theme->get_css_content_editor();
123 css_store_css($theme, $candidatesheet, $csscontent);
124 css_send_cached_css($candidatesheet, $etag);
126 css_send_uncached_css($csscontent);
131 if (($fallbacksheet = theme_styles_fallback_content($theme)) && !$theme->has_css_cached_content()) {
132 // The theme is not yet available and a fallback is available.
133 // Return the fallback immediately, specifying the Content-Length, then generate in the background.
134 $css = file_get_contents($fallbacksheet);
135 css_send_temporary_css($css);
137 // The fallback content has now been sent.
138 // There will be an attempt to generate the content, but it should not be served.
139 // The Content-Length above means that the client will disregard it anyway.
140 $sendaftergeneration = false;
142 // There may be another client currently holding a lock and generating the stylesheet.
143 // Use a very low lock timeout as the connection will be ended immediately afterwards.
146 // There is no fallback content to be issued here, therefore the generated content must be output.
147 $sendaftergeneration = true;
149 // Use a realistic lock timeout as the intention is to avoid lock contention.
150 $locktimeout = rand(90, 120);
153 // Attempt to fetch the lock.
154 $lockfactory = \core\lock\lock_config
::get_lock_factory('core_theme_get_css_content');
155 $lock = $lockfactory->get_lock($themename, $locktimeout);
157 if ($sendaftergeneration ||
$lock) {
158 // Either the lock was successful, or the lock was unsuccessful but the content *must* be sent.
160 // The content does not exist locally.
161 // Generate and save it.
162 $candidatesheet = theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir);
168 if ($sendaftergeneration) {
170 // Do not pollute browser caches if invalid revision requested,
171 // let's ignore legacy IE breakage here too.
172 css_send_uncached_css(file_get_contents($candidatesheet));
175 // Real browsers - this is the expected result!
176 css_send_cached_css($candidatesheet, $etag);
182 * Generate the theme CSS and store it.
184 * @param theme_config $theme The theme to be generated
185 * @param int $rev The theme revision
186 * @param int $themesubrev The theme sub-revision
187 * @param string $candidatedir The directory that it should be stored in
188 * @return string The path that the primary CSS was written to
190 function theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir) {
192 require_once("{$CFG->libdir}/filelib.php");
194 // Generate the content first.
195 if (!$csscontent = $theme->get_css_cached_content()) {
196 $csscontent = $theme->get_css_content();
197 $theme->set_css_content_cache($csscontent);
200 if ($theme->get_rtl_mode()) {
206 // Determine the candidatesheet path.
207 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $theme->use_svg_icons());
210 css_store_css($theme, $candidatesheet, $csscontent);
212 // Store the fallback CSS in the temp directory.
213 // This file is used as a fallback when waiting for a theme to compile and is not versioned in any way.
214 $fallbacksheet = make_temp_directory("theme/{$theme->name}")
216 . theme_styles_get_filename($type, 0, $theme->use_svg_icons());
217 css_store_css($theme, $fallbacksheet, $csscontent);
219 // Delete older revisions from localcache.
220 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR
);
221 foreach ($themecachedirs as $localcachedir) {
223 preg_match("/\/theme\/([0-9]+)$/", $localcachedir, $cachedrev);
224 $cachedrev = isset($cachedrev[1]) ?
intval($cachedrev[1]) : 0;
225 if ($cachedrev > 0 && $cachedrev < $rev) {
226 fulldelete($localcachedir);
230 // Delete older theme subrevision CSS from localcache.
231 $subrevfiles = glob("{$CFG->localcachedir}/theme/{$rev}/{$theme->name}/css/*.css");
232 foreach ($subrevfiles as $subrevfile) {
234 preg_match("/_([0-9]+)\.([0-9]+\.)?css$/", $subrevfile, $cachedsubrev);
235 $cachedsubrev = isset($cachedsubrev[1]) ?
intval($cachedsubrev[1]) : 0;
236 if ($cachedsubrev > 0 && $cachedsubrev < $themesubrev) {
237 fulldelete($subrevfile);
241 return $candidatesheet;
245 * Fetch the preferred fallback content location if available.
247 * @param theme_config $theme The theme to be generated
248 * @return string The path to the fallback sheet on disk
250 function theme_styles_fallback_content($theme) {
253 if (!$theme->usefallback
) {
254 // This theme does not support fallbacks.
258 $type = $theme->get_rtl_mode() ?
'all-rtl' : 'all';
259 $filename = theme_styles_get_filename($type);
261 $fallbacksheet = "{$CFG->tempdir}/theme/{$theme->name}/{$filename}";
262 if (file_exists($fallbacksheet)) {
263 return $fallbacksheet;
270 * Get the filename for the specified configuration.
272 * @param string $type The requested sheet type
273 * @param int $themesubrev The theme sub-revision
274 * @param bool $usesvg Whether SVGs are allowed
275 * @return string The filename for this sheet
277 function theme_styles_get_filename($type, $themesubrev = 0, $usesvg = true) {
279 $filename .= ($themesubrev > 0) ?
"_{$themesubrev}" : '';
280 $filename .= $usesvg ?
'' : '-nosvg';
282 return "{$filename}.css";
286 * Determine the correct etag for the specified configuration.
288 * @param string $themename The name of the theme
289 * @param int $rev The revision number
290 * @param string $type The requested sheet type
291 * @param int $themesubrev The theme sub-revision
292 * @param bool $usesvg Whether SVGs are allowed
293 * @return string The etag to use for this request
295 function theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg) {
296 $etag = [$rev, $themename, $type, $themesubrev];
302 return sha1(implode('/', $etag));