weekly release 3.8dev
[moodle.git] / theme / styles.php
CommitLineData
b7009474 1<?php
b7009474 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/**
78946b9b 18 * This file is responsible for serving the one huge CSS of each theme.
b7009474 19 *
574909ef 20 * @package core
78946b9b 21 * @copyright 2009 Petr Skoda (skodak) {@link http://skodak.org}
b7009474 22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
98245a84 25// Disable moodle specific debug messages and any errors in output,
c198390a
PS
26// comment out when debugging or better look into error log!
27define('NO_DEBUG_DISPLAY', true);
28
78946b9b 29define('ABORT_AFTER_CONFIG', true);
98245a84 30require('../config.php');
0e641c74 31require_once($CFG->dirroot.'/lib/csslib.php');
b7009474 32
7070b7f2
PS
33if ($slashargument = min_get_slash_argument()) {
34 $slashargument = ltrim($slashargument, '/');
35 if (substr_count($slashargument, '/') < 2) {
e1075027 36 css_send_css_not_found();
7070b7f2 37 }
383b89a1
SH
38
39 if (strpos($slashargument, '_s/') === 0) {
98245a84 40 // Can't use SVG.
383b89a1
SH
41 $slashargument = substr($slashargument, 3);
42 $usesvg = false;
43 } else {
44 $usesvg = true;
45 }
46
e1075027
SH
47 $chunk = null;
48 if (preg_match('#/(chunk(\d+)(/|$))#', $slashargument, $matches)) {
49 $chunk = (int)$matches[2];
50 $slashargument = str_replace($matches[1], '', $slashargument);
51 }
52
7070b7f2
PS
53 list($themename, $rev, $type) = explode('/', $slashargument, 3);
54 $themename = min_clean_param($themename, 'SAFEDIR');
5dd40ec4 55 $rev = min_clean_param($rev, 'RAW');
7070b7f2
PS
56 $type = min_clean_param($type, 'SAFEDIR');
57
58} else {
59 $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
5dd40ec4 60 $rev = min_optional_param('rev', 0, 'RAW');
7070b7f2 61 $type = min_optional_param('type', 'all', 'SAFEDIR');
e1075027 62 $chunk = min_optional_param('chunk', null, 'INT');
383b89a1 63 $usesvg = (bool)min_optional_param('svg', '1', 'INT');
7070b7f2 64}
b7009474 65
5dd40ec4
RW
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);
71
bb8bb8e4 72if (!is_null($themesubrev)) {
5dd40ec4
RW
73 $themesubrev = min_clean_param($themesubrev, 'INT');
74}
75
0e9911e1 76// Check that type fits into the expected values.
1eb2b517
SH
77if ($type === 'editor') {
78 // The editor CSS is never chunked.
79 $chunk = null;
1d987cae 80} else if ($type === 'all' || $type === 'all-rtl') {
1eb2b517
SH
81 // We're fine.
82} else {
ef201c96 83 css_send_css_not_found();
b7009474 84}
85
73e504bc 86if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
98245a84 87 // The theme exists in standard location - ok.
73e504bc 88} else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
98245a84 89 // Alternative theme location contains this theme - ok.
73e504bc 90} else {
78946b9b
PS
91 header('HTTP/1.0 404 not found');
92 die('Theme was not found, sorry.');
93}
b7009474 94
cb8108dd 95$candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
0e9911e1
AN
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);
b7009474 99
3b9b4731 100if (file_exists($chunkedcandidatesheet)) {
aa603b14 101 if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
98245a84
PS
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.
3b9b4731 104 css_send_unmodified(filemtime($chunkedcandidatesheet), $etag);
78946b9b 105 }
3b9b4731 106 css_send_cached_css($chunkedcandidatesheet, $etag);
b7009474 107}
108
98245a84 109// Ok, now we need to start normal moodle script, we need to load all libs and $DB.
78946b9b 110define('ABORT_AFTER_CONFIG_CANCEL', true);
fdeb7fa1 111
98245a84
PS
112define('NO_MOODLE_COOKIES', true); // Session not used here.
113define('NO_UPGRADE_CHECK', true); // Ignore upgrade check.
fdeb7fa1 114
78946b9b 115require("$CFG->dirroot/lib/setup.php");
b7009474 116
78946b9b 117$theme = theme_config::load($themename);
383b89a1 118$theme->force_svg_use($usesvg);
1d987cae 119$theme->set_rtl_mode($type === 'all-rtl' ? true : false);
fdeb7fa1 120
ef201c96 121$themerev = theme_get_revision();
5dd40ec4 122$currentthemesubrev = theme_get_sub_revision_for_theme($themename);
383b89a1 123
ef201c96 124$cache = true;
5dd40ec4
RW
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
0e9911e1 128// likely being regenerated.
5dd40ec4 129if ($themerev <= 0 or $themerev != $rev or $themesubrev != $currentthemesubrev) {
ef201c96 130 $rev = $themerev;
a990e4fa 131 $themesubrev = $currentthemesubrev;
ef201c96
PS
132 $cache = false;
133
98245a84 134 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
0e9911e1
AN
135 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg);
136 $chunkedcandidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $usesvg, $chunk);
137 $etag = theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk);
383b89a1 138}
ef201c96 139
cb8108dd 140make_localcache_directory('theme', false);
2c61e7cc 141
78946b9b 142if ($type === 'editor') {
98245a84 143 $csscontent = $theme->get_css_content_editor();
ef201c96 144
0e9911e1 145 if ($cache) {
bb8bb8e4 146 css_store_css($theme, $candidatesheet, $csscontent, false);
0e9911e1
AN
147 css_send_cached_css($candidatesheet, $etag);
148 } else {
bb8bb8e4 149 css_send_uncached_css($csscontent);
0e9911e1
AN
150 }
151
152}
153
154if (($fallbacksheet = theme_styles_fallback_content($theme)) && !$theme->has_css_cached_content()) {
155 // The theme is not yet available and a fallback is available.
156 // Return the fallback immediately, specifying the Content-Length, then generate in the background.
157 $css = file_get_contents($fallbacksheet);
158 css_send_temporary_css($css);
159
160 // The fallback content has now been sent.
161 // There will be an attempt to generate the content, but it should not be served.
162 // The Content-Length above means that the client will disregard it anyway.
163 $sendaftergeneration = false;
164
165 // There may be another client currently holding a lock and generating the stylesheet.
166 // Use a very low lock timeout as the connection will be ended immediately afterwards.
167 $locktimeout = 1;
78946b9b 168} else {
0e9911e1
AN
169 // There is no fallback content to be issued here, therefore the generated content must be output.
170 $sendaftergeneration = true;
171
172 // Use a realistic lock timeout as the intention is to avoid lock contention.
173 $locktimeout = rand(90, 120);
174}
175
176// Attempt to fetch the lock.
177$lockfactory = \core\lock\lock_config::get_lock_factory('core_theme_get_css_content');
178$lock = $lockfactory->get_lock($themename, $locktimeout);
d433cf37 179
0e9911e1
AN
180if ($sendaftergeneration || $lock) {
181 // Either the lock was successful, or the lock was unsuccessful but the content *must* be sent.
182 if (!file_exists($chunkedcandidatesheet)) {
183 // The content does not exist locally.
184 // Generate and save it.
185 $candidatesheet = theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir);
186 }
187
188 if ($lock) {
189 $lock->release();
190 }
191
192 if ($sendaftergeneration) {
193 if (!$cache) {
194 // Do not pollute browser caches if invalid revision requested,
195 // let's ignore legacy IE breakage here too.
196 css_send_uncached_css(file_get_contents($candidatesheet));
197
198 } else if ($chunk !== null and file_exists($chunkedcandidatesheet)) {
199 // Greetings stupid legacy IEs!
3b9b4731 200 css_send_cached_css($chunkedcandidatesheet, $etag);
0e9911e1 201
d0f6660b 202 } else {
0e9911e1
AN
203 // Real browsers - this is the expected result!
204 css_send_cached_css($candidatesheet, $etag);
d433cf37
FM
205 }
206 }
0e9911e1
AN
207}
208
209/**
210 * Generate the theme CSS and store it.
211 *
212 * @param theme_config $theme The theme to be generated
213 * @param int $rev The theme revision
214 * @param int $themesubrev The theme sub-revision
215 * @param string $candidatedir The directory that it should be stored in
216 * @return string The path that the primary (non-chunked) CSS was written to
217 */
218function theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir) {
219 global $CFG;
a990e4fa 220 require_once("{$CFG->libdir}/filelib.php");
d433cf37 221
0e9911e1 222 // Generate the content first.
4cc2f33b
SL
223 if (!$csscontent = $theme->get_css_cached_content()) {
224 $csscontent = $theme->get_css_content();
225 $theme->set_css_content_cache($csscontent);
226 }
98245a84 227
0e9911e1
AN
228 if ($theme->get_rtl_mode()) {
229 $type = "all-rtl";
230 } else {
231 $type = "all";
232 }
233
234 // Determine the candidatesheet path.
235 // Note: Do not pass any value for chunking as this is calcualted during css storage.
236 $candidatesheet = "{$candidatedir}/" . theme_styles_get_filename($type, $themesubrev, $theme->use_svg_icons());
237
238 // Determine the chunking URL.
239 // Note, this will be removed when support for IE9 is removed.
e1075027 240 $relroot = preg_replace('|^http.?://[^/]+|', '', $CFG->wwwroot);
0e9911e1
AN
241 if (!empty(min_get_slash_argument())) {
242 if ($theme->use_svg_icons()) {
243 $chunkurl = "{$relroot}/theme/styles.php/{$theme->name}/{$rev}/$type";
e1075027 244 } else {
0e9911e1 245 $chunkurl = "{$relroot}/theme/styles.php/_s/{$theme->name}/{$rev}/$type";
1eb2b517
SH
246 }
247 } else {
0e9911e1
AN
248 if ($theme->use_svg_icons()) {
249 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type";
1eb2b517 250 } else {
0e9911e1 251 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type&svg=0";
e1075027 252 }
1eb2b517 253 }
0e9911e1
AN
254
255 // Store the CSS.
3b9b4731 256 css_store_css($theme, $candidatesheet, $csscontent, true, $chunkurl);
d433cf37 257
0e9911e1
AN
258 // Store the fallback CSS in the temp directory.
259 // This file is used as a fallback when waiting for a theme to compile and is not versioned in any way.
260 $fallbacksheet = make_temp_directory("theme/{$theme->name}")
261 . "/"
262 . theme_styles_get_filename($type, 0, $theme->use_svg_icons());
263 css_store_css($theme, $fallbacksheet, $csscontent, true, $chunkurl);
264
a990e4fa
MH
265 // Delete older revisions from localcache.
266 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR);
267 foreach ($themecachedirs as $localcachedir) {
268 $cachedrev = [];
269 preg_match("/\/theme\/([0-9]+)$/", $localcachedir, $cachedrev);
270 $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
271 if ($cachedrev > 0 && $cachedrev < $rev) {
272 fulldelete($localcachedir);
273 }
274 }
275
276 // Delete older theme subrevision CSS from localcache.
277 $subrevfiles = glob("{$CFG->localcachedir}/theme/{$rev}/{$theme->name}/css/*.css");
278 foreach ($subrevfiles as $subrevfile) {
279 $cachedsubrev = [];
280 preg_match("/_([0-9]+)\.([0-9]+\.)?css$/", $subrevfile, $cachedsubrev);
281 $cachedsubrev = isset($cachedsubrev[1]) ? intval($cachedsubrev[1]) : 0;
282 if ($cachedsubrev > 0 && $cachedsubrev < $themesubrev) {
283 fulldelete($subrevfile);
284 }
285 }
286
0e9911e1
AN
287 return $candidatesheet;
288}
289
290/**
291 * Fetch the preferred fallback content location if available.
292 *
293 * @param theme_config $theme The theme to be generated
294 * @return string The path to the fallback sheet on disk
295 */
296function theme_styles_fallback_content($theme) {
297 global $CFG;
298
299 if (!$theme->usefallback) {
300 // This theme does not support fallbacks.
301 return false;
302 }
303
304 $type = $theme->get_rtl_mode() ? 'all-rtl' : 'all';
305 $filename = theme_styles_get_filename($type);
306
307 $fallbacksheet = "{$CFG->tempdir}/theme/{$theme->name}/{$filename}";
308 if (file_exists($fallbacksheet)) {
309 return $fallbacksheet;
d433cf37 310 }
0e9911e1
AN
311
312 return false;
045f492c 313}
979d3207 314
0e9911e1
AN
315/**
316 * Get the filename for the specified configuration.
317 *
318 * @param string $type The requested sheet type
319 * @param int $themesubrev The theme sub-revision
320 * @param bool $usesvg Whether SVGs are allowed
321 * @param int $chunk The chunk number if specified
322 * @return string The filename for this sheet
323 */
324function theme_styles_get_filename($type, $themesubrev = 0, $usesvg = true, $chunk = null) {
325 $filename = $type;
326 $filename .= ($themesubrev > 0) ? "_{$themesubrev}" : '';
327 $filename .= $usesvg ? '' : '-nosvg';
328 $filename .= $chunk ? ".{$chunk}" : '';
ef201c96 329
0e9911e1
AN
330 return "{$filename}.css";
331}
979d3207 332
0e9911e1
AN
333/**
334 * Determine the correct etag for the specified configuration.
335 *
336 * @param string $themename The name of the theme
337 * @param int $rev The revision number
338 * @param string $type The requested sheet type
339 * @param int $themesubrev The theme sub-revision
340 * @param bool $usesvg Whether SVGs are allowed
341 * @param int $chunk The chunk number if specified
342 * @return string The etag to use for this request
343 */
344function theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk) {
345 $etag = [$rev, $themename, $type, $themesubrev];
346
347 if (!$usesvg) {
348 $etag[] = 'nosvg';
349 }
350
351 if ($chunk) {
352 $etag[] = "chunk{$chunk}";
353 }
354
355 return sha1(implode('/', $etag));
ef201c96 356}