Merge branch 'wip-MDL-61814-master' of git://github.com/abgreeve/moodle
[moodle.git] / theme / image.php
blobe9cc853f81de6d671510e865915e2bf1e652c214
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 theme and plugin images.
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
26 // disable moodle specific debug messages and any errors in output,
27 // comment out when debugging or better look into error log!
28 define('NO_DEBUG_DISPLAY', true);
30 // we need just the values from config.php and minlib.php
31 define('ABORT_AFTER_CONFIG', true);
32 require('../config.php'); // this stops immediately at the beginning of lib/setup.php
34 if ($slashargument = min_get_slash_argument()) {
35 $slashargument = ltrim($slashargument, '/');
36 if (substr_count($slashargument, '/') < 3) {
37 image_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;
46 // image must be last because it may contain "/"
47 list($themename, $component, $rev, $image) = explode('/', $slashargument, 4);
48 $themename = min_clean_param($themename, 'SAFEDIR');
49 $component = min_clean_param($component, 'SAFEDIR');
50 $rev = min_clean_param($rev, 'INT');
51 $image = min_clean_param($image, 'SAFEPATH');
53 } else {
54 $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
55 $component = min_optional_param('component', 'core', 'SAFEDIR');
56 $rev = min_optional_param('rev', -1, 'INT');
57 $image = min_optional_param('image', '', 'SAFEPATH');
58 $usesvg = (bool)min_optional_param('svg', '1', 'INT');
61 if (empty($component) or $component === 'moodle' or $component === 'core') {
62 $component = 'core';
65 if (empty($image)) {
66 image_not_found();
69 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
70 // exists
71 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
72 // exists
73 } else {
74 image_not_found();
77 $candidatelocation = "$CFG->localcachedir/theme/$rev/$themename/pix/$component";
78 $etag = sha1("$rev/$themename/$component/$image");
80 if ($rev > 0) {
81 if (file_exists("$candidatelocation/$image.error")) {
82 // This is a major speedup if there are multiple missing images,
83 // the only problem is that random requests may pollute our cache.
84 image_not_found();
86 $cacheimage = false;
87 if ($usesvg && file_exists("$candidatelocation/$image.svg")) {
88 $cacheimage = "$candidatelocation/$image.svg";
89 $ext = 'svg';
90 } else if (file_exists("$candidatelocation/$image.png")) {
91 $cacheimage = "$candidatelocation/$image.png";
92 $ext = 'png';
93 } else if (file_exists("$candidatelocation/$image.gif")) {
94 $cacheimage = "$candidatelocation/$image.gif";
95 $ext = 'gif';
96 } else if (file_exists("$candidatelocation/$image.jpg")) {
97 $cacheimage = "$candidatelocation/$image.jpg";
98 $ext = 'jpg';
99 } else if (file_exists("$candidatelocation/$image.jpeg")) {
100 $cacheimage = "$candidatelocation/$image.jpeg";
101 $ext = 'jpeg';
102 } else if (file_exists("$candidatelocation/$image.ico")) {
103 $cacheimage = "$candidatelocation/$image.ico";
104 $ext = 'ico';
106 if ($cacheimage) {
107 if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
108 // We do not actually need to verify the etag value because our files
109 // never change in cache because we increment the rev parameter.
110 // 90 days only - based on Moodle point release cadence being every 3 months.
111 $lifetime = 60 * 60 * 24 * 90;
112 $mimetype = get_contenttype_from_ext($ext);
113 header('HTTP/1.1 304 Not Modified');
114 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
115 header('Cache-Control: public, max-age='.$lifetime.', no-transform');
116 header('Content-Type: '.$mimetype);
117 header('Etag: "'.$etag.'"');
118 die;
120 send_cached_image($cacheimage, $etag);
124 //=================================================================================
125 // ok, now we need to start normal moodle script, we need to load all libs and $DB
126 define('ABORT_AFTER_CONFIG_CANCEL', true);
128 define('NO_MOODLE_COOKIES', true); // Session not used here
129 define('NO_UPGRADE_CHECK', true); // Ignore upgrade check
131 require("$CFG->dirroot/lib/setup.php");
133 $theme = theme_config::load($themename);
134 $themerev = theme_get_revision();
136 if ($themerev <= 0 or $rev != $themerev) {
137 // Do not send caching headers if they do not request current revision,
138 // we do not want to pollute browser caches with outdated images.
139 $imagefile = $theme->resolve_image_location($image, $component, $usesvg);
140 if (empty($imagefile) or !is_readable($imagefile)) {
141 image_not_found();
143 send_uncached_image($imagefile);
146 make_localcache_directory('theme', false);
148 // At this stage caching is enabled, and either:
149 // * we have no cached copy of the image in any format (either SVG, or non-SVG); or
150 // * we have a cached copy of the SVG, but the non-SVG was requested by the browser.
152 // Because of the way in which the cache return code works above:
153 // * if we are allowed to return SVG, we do not need to cache the non-SVG version; however
154 // * if the browser has requested the non-SVG version, we *must* cache _both_ the SVG, and the non-SVG versions.
156 // First get all copies - including, potentially, the SVG version.
157 $imagefile = $theme->resolve_image_location($image, $component, true);
159 if (empty($imagefile) || !is_readable($imagefile)) {
160 // Unable to find a copy of the image file in any format.
161 // We write a .error file for the image now - this will be used above when searching for cached copies to prevent
162 // trying to find the image in the future.
163 if (!file_exists($candidatelocation)) {
164 @mkdir($candidatelocation, $CFG->directorypermissions, true);
166 // Make note we can not find this file.
167 $cacheimage = "$candidatelocation/$image.error";
168 $fp = fopen($cacheimage, 'w');
169 fclose($fp);
170 image_not_found();
173 // The image was found, and it is readable.
174 $pathinfo = pathinfo($imagefile);
176 // Attempt to cache it if necessary.
177 // We don't really want to overwrite any existing cache items just for the sake of it.
178 $cacheimage = "$candidatelocation/$image.{$pathinfo['extension']}";
179 if (!file_exists($cacheimage)) {
180 // We don't already hold a cached copy of this image. Cache it now.
181 $cacheimage = cache_image($image, $imagefile, $candidatelocation);
184 if (!$usesvg && $pathinfo['extension'] === 'svg') {
185 // The browser has requested that a non-SVG version be returned.
186 // The version found so far is the SVG version - try and find the non-SVG version.
187 $imagefile = $theme->resolve_image_location($image, $component, false);
188 if (empty($imagefile) || !is_readable($imagefile)) {
189 // A non-SVG file could not be found at all.
190 // The browser has requested a non-SVG version, so we must return image_not_found().
191 // We must *not* write an .error file because the SVG is available.
192 image_not_found();
195 // An non-SVG version of image was found - cache it.
196 // This will be used below in the image serving code.
197 $cacheimage = cache_image($image, $imagefile, $candidatelocation);
200 if (connection_aborted()) {
201 // Request was cancelled - do not send anything.
202 die;
205 // Make sure nothing failed.
206 clearstatcache();
207 if (file_exists($cacheimage)) {
208 // The cached copy was found, and is accessible. Serve it.
209 send_cached_image($cacheimage, $etag);
212 send_uncached_image($imagefile);
214 //=================================================================================
215 //=== utility functions ==
216 // we are not using filelib because we need to fine tune all header
217 // parameters to get the best performance.
219 function send_cached_image($imagepath, $etag) {
220 global $CFG;
221 require("$CFG->dirroot/lib/xsendfilelib.php");
223 // 90 days only - based on Moodle point release cadence being every 3 months.
224 $lifetime = 60 * 60 * 24 * 90;
225 $pathinfo = pathinfo($imagepath);
226 $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
228 $mimetype = get_contenttype_from_ext($pathinfo['extension']);
230 header('Etag: "'.$etag.'"');
231 header('Content-Disposition: inline; filename="'.$imagename.'"');
232 header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($imagepath)) .' GMT');
233 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
234 header('Pragma: ');
235 header('Cache-Control: public, max-age='.$lifetime.', no-transform, immutable');
236 header('Accept-Ranges: none');
237 header('Content-Type: '.$mimetype);
239 if (xsendfile($imagepath)) {
240 die;
243 if ($mimetype === 'image/svg+xml') {
244 // SVG format is a text file. So we can compress SVG files.
245 if (!min_enable_zlib_compression()) {
246 header('Content-Length: '.filesize($imagepath));
248 } else {
249 // No need to compress other image formats.
250 header('Content-Length: '.filesize($imagepath));
253 readfile($imagepath);
254 die;
257 function send_uncached_image($imagepath) {
258 $pathinfo = pathinfo($imagepath);
259 $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
261 $mimetype = get_contenttype_from_ext($pathinfo['extension']);
263 header('Content-Disposition: inline; filename="'.$imagename.'"');
264 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
265 header('Expires: '. gmdate('D, d M Y H:i:s', time() + 15) .' GMT');
266 header('Pragma: ');
267 header('Accept-Ranges: none');
268 header('Content-Type: '.$mimetype);
269 header('Content-Length: '.filesize($imagepath));
271 readfile($imagepath);
272 die;
275 function image_not_found() {
276 header('HTTP/1.0 404 not found');
277 die('Image was not found, sorry.');
280 function get_contenttype_from_ext($ext) {
281 switch ($ext) {
282 case 'svg':
283 return 'image/svg+xml';
284 case 'png':
285 return 'image/png';
286 case 'gif':
287 return 'image/gif';
288 case 'jpg':
289 case 'jpeg':
290 return 'image/jpeg';
291 case 'ico':
292 return 'image/vnd.microsoft.icon';
294 return 'document/unknown';
298 * Caches a given image file.
300 * @param string $image The name of the image that was requested.
301 * @param string $imagefile The location of the image file we want to cache.
302 * @param string $candidatelocation The location to cache it in.
303 * @return string The path to the cached image.
305 function cache_image($image, $imagefile, $candidatelocation) {
306 global $CFG;
307 $pathinfo = pathinfo($imagefile);
308 $cacheimage = "$candidatelocation/$image.".$pathinfo['extension'];
310 clearstatcache();
311 if (!file_exists(dirname($cacheimage))) {
312 @mkdir(dirname($cacheimage), $CFG->directorypermissions, true);
315 // Prevent serving of incomplete file from concurrent request,
316 // the rename() should be more atomic than copy().
317 ignore_user_abort(true);
318 if (@copy($imagefile, $cacheimage.'.tmp')) {
319 rename($cacheimage.'.tmp', $cacheimage);
320 @chmod($cacheimage, $CFG->filepermissions);
321 @unlink($cacheimage.'.tmp'); // just in case anything fails
323 return $cacheimage;