Merge branch 'wip-MDL-61814-master' of git://github.com/abgreeve/moodle
[moodle.git] / theme / styles.php
blob6a4aa9b9d60bf35ce8164b61f470d334c53d71d9
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.
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/>.
17 /**
18 * This file is responsible for serving the one huge CSS of each theme.
20 * @package core
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) {
40 // Can't use SVG.
41 $slashargument = substr($slashargument, 3);
42 $usesvg = false;
43 } else {
44 $usesvg = true;
47 $chunk = null;
48 if (preg_match('#/(chunk(\d+)(/|$))#', $slashargument, $matches)) {
49 $chunk = (int)$matches[2];
50 $slashargument = str_replace($matches[1], '', $slashargument);
53 list($themename, $rev, $type) = explode('/', $slashargument, 3);
54 $themename = min_clean_param($themename, 'SAFEDIR');
55 $rev = min_clean_param($rev, 'RAW');
56 $type = min_clean_param($type, 'SAFEDIR');
58 } else {
59 $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
60 $rev = min_optional_param('rev', 0, 'RAW');
61 $type = min_optional_param('type', 'all', 'SAFEDIR');
62 $chunk = min_optional_param('chunk', null, 'INT');
63 $usesvg = (bool)min_optional_param('svg', '1', 'INT');
66 // Check if we received a theme sub revision which allows us
67 // to handle local caching on a per theme basis.
68 $values = explode('_', $rev);
69 $rev = min_clean_param(array_shift($values), 'INT');
70 $themesubrev = array_shift($values);
72 if (!is_null($themesubrev)) {
73 $themesubrev = min_clean_param($themesubrev, 'INT');
76 // Check that type fits into the expected values.
77 if ($type === 'editor') {
78 // The editor CSS is never chunked.
79 $chunk = null;
80 } else if ($type === 'all' || $type === 'all-rtl') {
81 // We're fine.
82 } else {
83 css_send_css_not_found();
86 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
87 // The theme exists in standard location - ok.
88 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
89 // Alternative theme location contains this theme - ok.
90 } else {
91 header('HTTP/1.0 404 not found');
92 die('Theme was not found, sorry.');
95 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
96 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
97 $chunkedcandidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg, $chunk);
98 $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk);
100 if (file_exists($chunkedcandidatesheet)) {
101 if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
102 // We do not actually need to verify the etag value because our files
103 // never change in cache because we increment the rev counter.
104 css_send_unmodified(filemtime($chunkedcandidatesheet), $etag);
106 css_send_cached_css($chunkedcandidatesheet, $etag);
109 // Ok, now we need to start normal moodle script, we need to load all libs and $DB.
110 define('ABORT_AFTER_CONFIG_CANCEL', true);
112 define('NO_MOODLE_COOKIES', true); // Session not used here.
113 define('NO_UPGRADE_CHECK', true); // Ignore upgrade check.
115 require("$CFG->dirroot/lib/setup.php");
117 $theme = theme_config::load($themename);
118 $theme->force_svg_use($usesvg);
119 $theme->set_rtl_mode($type === 'all-rtl' ? true : false);
121 $themerev = theme_get_revision();
122 $currentthemesubrev = theme_get_sub_revision_for_theme($themename);
124 $cache = true;
125 // If the client is requesting a revision that doesn't match both
126 // the global theme revision and the theme specific revision then
127 // tell the browser not to cache this style sheet because it's
128 // likely being regenerated.
129 if ($themerev <= 0 or $themerev != $rev or $themesubrev != $currentthemesubrev) {
130 $rev = $themerev;
131 $cache = false;
133 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
134 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
135 $chunkedcandidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg, $chunk);
136 $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk);
139 make_localcache_directory('theme', false);
141 if ($type === 'editor') {
142 $csscontent = $theme->get_css_content_editor();
144 if ($cache) {
145 css_store_css($theme, $candidatesheet, $csscontent, false);
146 css_send_cached_css($candidatesheet, $etag);
147 } else {
148 css_send_uncached_css($csscontent);
153 if (($fallbacksheet = theme_styles_fallback_content($theme)) && !$theme->has_css_cached_content()) {
154 // The theme is not yet available and a fallback is available.
155 // Return the fallback immediately, specifying the Content-Length, then generate in the background.
156 $css = file_get_contents($fallbacksheet);
157 css_send_temporary_css($css);
159 // The fallback content has now been sent.
160 // There will be an attempt to generate the content, but it should not be served.
161 // The Content-Length above means that the client will disregard it anyway.
162 $sendaftergeneration = false;
164 // There may be another client currently holding a lock and generating the stylesheet.
165 // Use a very low lock timeout as the connection will be ended immediately afterwards.
166 $locktimeout = 1;
167 } else {
168 // There is no fallback content to be issued here, therefore the generated content must be output.
169 $sendaftergeneration = true;
171 // Use a realistic lock timeout as the intention is to avoid lock contention.
172 $locktimeout = rand(90, 120);
175 // Attempt to fetch the lock.
176 $lockfactory = \core\lock\lock_config::get_lock_factory('core_theme_get_css_content');
177 $lock = $lockfactory->get_lock($themename, $locktimeout);
179 if ($sendaftergeneration || $lock) {
180 // Either the lock was successful, or the lock was unsuccessful but the content *must* be sent.
181 if (!file_exists($chunkedcandidatesheet)) {
182 // The content does not exist locally.
183 // Generate and save it.
184 $candidatesheet = theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir);
187 if ($lock) {
188 $lock->release();
191 if ($sendaftergeneration) {
192 if (!$cache) {
193 // Do not pollute browser caches if invalid revision requested,
194 // let's ignore legacy IE breakage here too.
195 css_send_uncached_css(file_get_contents($candidatesheet));
197 } else if ($chunk !== null and file_exists($chunkedcandidatesheet)) {
198 // Greetings stupid legacy IEs!
199 css_send_cached_css($chunkedcandidatesheet, $etag);
201 } else {
202 // Real browsers - this is the expected result!
203 css_send_cached_css($candidatesheet, $etag);
209 * Generate the theme CSS and store it.
211 * @param theme_config $theme The theme to be generated
212 * @param int $rev The theme revision
213 * @param int $themesubrev The theme sub-revision
214 * @param string $candidatedir The directory that it should be stored in
215 * @return string The path that the primary (non-chunked) CSS was written to
217 function theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir) {
218 global $CFG;
220 // Generate the content first.
221 if (!$csscontent = $theme->get_css_cached_content()) {
222 $csscontent = $theme->get_css_content();
223 $theme->set_css_content_cache($csscontent);
226 if ($theme->get_rtl_mode()) {
227 $type = "all-rtl";
228 } else {
229 $type = "all";
232 // Determine the candidatesheet path.
233 // Note: Do not pass any value for chunking as this is calcualted during css storage.
234 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $theme->use_svg_icons());
236 // Determine the chunking URL.
237 // Note, this will be removed when support for IE9 is removed.
238 $relroot = preg_replace('|^http.?://[^/]+|', '', $CFG->wwwroot);
239 if (!empty(min_get_slash_argument())) {
240 if ($theme->use_svg_icons()) {
241 $chunkurl = "{$relroot}/theme/styles.php/{$theme->name}/{$rev}/$type";
242 } else {
243 $chunkurl = "{$relroot}/theme/styles.php/_s/{$theme->name}/{$rev}/$type";
245 } else {
246 if ($theme->use_svg_icons()) {
247 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type";
248 } else {
249 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type&svg=0";
253 // Store the CSS.
254 css_store_css($theme, $candidatesheet, $csscontent, true, $chunkurl);
256 // Store the fallback CSS in the temp directory.
257 // This file is used as a fallback when waiting for a theme to compile and is not versioned in any way.
258 $fallbacksheet = make_temp_directory("theme/{$theme->name}")
259 . "/"
260 . theme_styles_get_filename($type, 0, $theme->use_svg_icons());
261 css_store_css($theme, $fallbacksheet, $csscontent, true, $chunkurl);
263 return $candidatesheet;
267 * Fetch the preferred fallback content location if available.
269 * @param theme_config $theme The theme to be generated
270 * @return string The path to the fallback sheet on disk
272 function theme_styles_fallback_content($theme) {
273 global $CFG;
275 if (!$theme->usefallback) {
276 // This theme does not support fallbacks.
277 return false;
280 $type = $theme->get_rtl_mode() ? 'all-rtl' : 'all';
281 $filename = theme_styles_get_filename($type);
283 $fallbacksheet = "{$CFG->tempdir}/theme/{$theme->name}/{$filename}";
284 if (file_exists($fallbacksheet)) {
285 return $fallbacksheet;
288 return false;
292 * Get the filename for the specified configuration.
294 * @param string $type The requested sheet type
295 * @param int $themesubrev The theme sub-revision
296 * @param bool $usesvg Whether SVGs are allowed
297 * @param int $chunk The chunk number if specified
298 * @return string The filename for this sheet
300 function theme_styles_get_filename($type, $themesubrev = 0, $usesvg = true, $chunk = null) {
301 $filename = $type;
302 $filename .= ($themesubrev > 0) ? "_{$themesubrev}" : '';
303 $filename .= $usesvg ? '' : '-nosvg';
304 $filename .= $chunk ? ".{$chunk}" : '';
306 return "{$filename}.css";
310 * Determine the correct etag for the specified configuration.
312 * @param string $themename The name of the theme
313 * @param int $rev The revision number
314 * @param string $type The requested sheet type
315 * @param int $themesubrev The theme sub-revision
316 * @param bool $usesvg Whether SVGs are allowed
317 * @param int $chunk The chunk number if specified
318 * @return string The etag to use for this request
320 function theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk) {
321 $etag = [$rev, $themename, $type, $themesubrev];
323 if (!$usesvg) {
324 $etag[] = 'nosvg';
327 if ($chunk) {
328 $etag[] = "chunk{$chunk}";
331 return sha1(implode('/', $etag));