MDL-62801 themes: Added missing filelib include
[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
PS
130 $rev = $themerev;
131 $cache = false;
132
98245a84 133 $candidatedir = "$CFG->localcachedir/theme/$rev/$themename/css";
0e9911e1
AN
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);
383b89a1 137}
ef201c96 138
cb8108dd 139make_localcache_directory('theme', false);
2c61e7cc 140
78946b9b 141if ($type === 'editor') {
98245a84 142 $csscontent = $theme->get_css_content_editor();
ef201c96 143
0e9911e1 144 if ($cache) {
bb8bb8e4 145 css_store_css($theme, $candidatesheet, $csscontent, false);
0e9911e1
AN
146 css_send_cached_css($candidatesheet, $etag);
147 } else {
bb8bb8e4 148 css_send_uncached_css($csscontent);
0e9911e1
AN
149 }
150
151}
152
153if (($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);
158
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;
163
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;
78946b9b 167} else {
0e9911e1
AN
168 // There is no fallback content to be issued here, therefore the generated content must be output.
169 $sendaftergeneration = true;
170
171 // Use a realistic lock timeout as the intention is to avoid lock contention.
172 $locktimeout = rand(90, 120);
173}
174
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);
d433cf37 178
0e9911e1
AN
179if ($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);
185 }
186
187 if ($lock) {
188 $lock->release();
189 }
190
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));
196
197 } else if ($chunk !== null and file_exists($chunkedcandidatesheet)) {
198 // Greetings stupid legacy IEs!
3b9b4731 199 css_send_cached_css($chunkedcandidatesheet, $etag);
0e9911e1 200
d0f6660b 201 } else {
0e9911e1
AN
202 // Real browsers - this is the expected result!
203 css_send_cached_css($candidatesheet, $etag);
d433cf37
FM
204 }
205 }
0e9911e1
AN
206}
207
208/**
209 * Generate the theme CSS and store it.
210 *
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
216 */
217function theme_styles_generate_and_store($theme, $rev, $themesubrev, $candidatedir) {
218 global $CFG;
d433cf37 219
0e9911e1 220 // Generate the content first.
4cc2f33b
SL
221 if (!$csscontent = $theme->get_css_cached_content()) {
222 $csscontent = $theme->get_css_content();
223 $theme->set_css_content_cache($csscontent);
224 }
98245a84 225
0e9911e1
AN
226 if ($theme->get_rtl_mode()) {
227 $type = "all-rtl";
228 } else {
229 $type = "all";
230 }
231
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());
235
236 // Determine the chunking URL.
237 // Note, this will be removed when support for IE9 is removed.
e1075027 238 $relroot = preg_replace('|^http.?://[^/]+|', '', $CFG->wwwroot);
0e9911e1
AN
239 if (!empty(min_get_slash_argument())) {
240 if ($theme->use_svg_icons()) {
241 $chunkurl = "{$relroot}/theme/styles.php/{$theme->name}/{$rev}/$type";
e1075027 242 } else {
0e9911e1 243 $chunkurl = "{$relroot}/theme/styles.php/_s/{$theme->name}/{$rev}/$type";
1eb2b517
SH
244 }
245 } else {
0e9911e1
AN
246 if ($theme->use_svg_icons()) {
247 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type";
1eb2b517 248 } else {
0e9911e1 249 $chunkurl = "{$relroot}/theme/styles.php?theme={$theme->name}&rev={$rev}&type=$type&svg=0";
e1075027 250 }
1eb2b517 251 }
0e9911e1
AN
252
253 // Store the CSS.
3b9b4731 254 css_store_css($theme, $candidatesheet, $csscontent, true, $chunkurl);
d433cf37 255
0e9911e1
AN
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);
262
263 return $candidatesheet;
264}
265
266/**
267 * Fetch the preferred fallback content location if available.
268 *
269 * @param theme_config $theme The theme to be generated
270 * @return string The path to the fallback sheet on disk
271 */
272function theme_styles_fallback_content($theme) {
273 global $CFG;
274
275 if (!$theme->usefallback) {
276 // This theme does not support fallbacks.
277 return false;
278 }
279
280 $type = $theme->get_rtl_mode() ? 'all-rtl' : 'all';
281 $filename = theme_styles_get_filename($type);
282
283 $fallbacksheet = "{$CFG->tempdir}/theme/{$theme->name}/{$filename}";
284 if (file_exists($fallbacksheet)) {
285 return $fallbacksheet;
d433cf37 286 }
0e9911e1
AN
287
288 return false;
045f492c 289}
979d3207 290
0e9911e1
AN
291/**
292 * Get the filename for the specified configuration.
293 *
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
299 */
300function 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}" : '';
ef201c96 305
0e9911e1
AN
306 return "{$filename}.css";
307}
979d3207 308
0e9911e1
AN
309/**
310 * Determine the correct etag for the specified configuration.
311 *
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
319 */
320function theme_styles_get_etag($themename, $rev, $type, $themesubrev, $usesvg, $chunk) {
321 $etag = [$rev, $themename, $type, $themesubrev];
322
323 if (!$usesvg) {
324 $etag[] = 'nosvg';
325 }
326
327 if ($chunk) {
328 $etag[] = "chunk{$chunk}";
329 }
330
331 return sha1(implode('/', $etag));
ef201c96 332}