image.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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.
  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. * This file is responsible for serving the one theme and plugin images.
  18. *
  19. * @package core
  20. * @copyright 2009 Petr Skoda (skodak) {@link http://skodak.org}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. // disable moodle specific debug messages and any errors in output,
  24. // comment out when debugging or better look into error log!
  25. define('NO_DEBUG_DISPLAY', true);
  26. // we need just the values from config.php and minlib.php
  27. define('ABORT_AFTER_CONFIG', true);
  28. require('../config.php'); // this stops immediately at the beginning of lib/setup.php
  29. if ($slashargument = min_get_slash_argument()) {
  30. $slashargument = ltrim($slashargument, '/');
  31. if (substr_count($slashargument, '/') < 3) {
  32. image_not_found();
  33. }
  34. if (strpos($slashargument, '_s/') === 0) {
  35. // Can't use SVG
  36. $slashargument = substr($slashargument, 3);
  37. $usesvg = false;
  38. } else {
  39. $usesvg = true;
  40. }
  41. // image must be last because it may contain "/"
  42. list($themename, $component, $rev, $image) = explode('/', $slashargument, 4);
  43. $themename = min_clean_param($themename, 'SAFEDIR');
  44. $component = min_clean_param($component, 'SAFEDIR');
  45. $rev = min_clean_param($rev, 'INT');
  46. $image = min_clean_param($image, 'SAFEPATH');
  47. } else {
  48. $themename = min_optional_param('theme', 'standard', 'SAFEDIR');
  49. $component = min_optional_param('component', 'core', 'SAFEDIR');
  50. $rev = min_optional_param('rev', -1, 'INT');
  51. $image = min_optional_param('image', '', 'SAFEPATH');
  52. $usesvg = (bool)min_optional_param('svg', '1', 'INT');
  53. }
  54. if (empty($component) or $component === 'moodle' or $component === 'core') {
  55. $component = 'core';
  56. }
  57. if (empty($image)) {
  58. image_not_found();
  59. }
  60. if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
  61. // exists
  62. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
  63. // exists
  64. } else {
  65. image_not_found();
  66. }
  67. $candidatelocation = "$CFG->localcachedir/theme/$rev/$themename/pix/$component";
  68. $etag = sha1("$rev/$themename/$component/$image");
  69. if ($rev > 0) {
  70. if (file_exists("$candidatelocation/$image.error")) {
  71. // This is a major speedup if there are multiple missing images,
  72. // the only problem is that random requests may pollute our cache.
  73. image_not_found();
  74. }
  75. $cacheimage = false;
  76. if ($usesvg && file_exists("$candidatelocation/$image.svg")) {
  77. $cacheimage = "$candidatelocation/$image.svg";
  78. $ext = 'svg';
  79. } else if (file_exists("$candidatelocation/$image.png")) {
  80. $cacheimage = "$candidatelocation/$image.png";
  81. $ext = 'png';
  82. } else if (file_exists("$candidatelocation/$image.gif")) {
  83. $cacheimage = "$candidatelocation/$image.gif";
  84. $ext = 'gif';
  85. } else if (file_exists("$candidatelocation/$image.jpg")) {
  86. $cacheimage = "$candidatelocation/$image.jpg";
  87. $ext = 'jpg';
  88. } else if (file_exists("$candidatelocation/$image.jpeg")) {
  89. $cacheimage = "$candidatelocation/$image.jpeg";
  90. $ext = 'jpeg';
  91. } else if (file_exists("$candidatelocation/$image.ico")) {
  92. $cacheimage = "$candidatelocation/$image.ico";
  93. $ext = 'ico';
  94. }
  95. if ($cacheimage) {
  96. if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  97. // we do not actually need to verify the etag value because our files
  98. // never change in cache because we increment the rev parameter
  99. $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
  100. $mimetype = get_contenttype_from_ext($ext);
  101. header('HTTP/1.1 304 Not Modified');
  102. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  103. header('Cache-Control: public, max-age='.$lifetime.', no-transform');
  104. header('Content-Type: '.$mimetype);
  105. header('Etag: "'.$etag.'"');
  106. die;
  107. }
  108. send_cached_image($cacheimage, $etag);
  109. }
  110. }
  111. //=================================================================================
  112. // ok, now we need to start normal moodle script, we need to load all libs and $DB
  113. define('ABORT_AFTER_CONFIG_CANCEL', true);
  114. define('NO_MOODLE_COOKIES', true); // Session not used here
  115. define('NO_UPGRADE_CHECK', true); // Ignore upgrade check
  116. require("$CFG->dirroot/lib/setup.php");
  117. $theme = theme_config::load($themename);
  118. $themerev = theme_get_revision();
  119. if ($themerev <= 0 or $rev != $themerev) {
  120. // Do not send caching headers if they do not request current revision,
  121. // we do not want to pollute browser caches with outdated images.
  122. $imagefile = $theme->resolve_image_location($image, $component, $usesvg);
  123. if (empty($imagefile) or !is_readable($imagefile)) {
  124. image_not_found();
  125. }
  126. send_uncached_image($imagefile);
  127. }
  128. make_localcache_directory('theme', false);
  129. // At this stage caching is enabled, and either:
  130. // * we have no cached copy of the image in any format (either SVG, or non-SVG); or
  131. // * we have a cached copy of the SVG, but the non-SVG was requested by the browser.
  132. //
  133. // Because of the way in which the cache return code works above:
  134. // * if we are allowed to return SVG, we do not need to cache the non-SVG version; however
  135. // * if the browser has requested the non-SVG version, we *must* cache _both_ the SVG, and the non-SVG versions.
  136. // First get all copies - including, potentially, the SVG version.
  137. $imagefile = $theme->resolve_image_location($image, $component, true);
  138. if (empty($imagefile) || !is_readable($imagefile)) {
  139. // Unable to find a copy of the image file in any format.
  140. // We write a .error file for the image now - this will be used above when searching for cached copies to prevent
  141. // trying to find the image in the future.
  142. if (!file_exists($candidatelocation)) {
  143. @mkdir($candidatelocation, $CFG->directorypermissions, true);
  144. }
  145. // Make note we can not find this file.
  146. $cacheimage = "$candidatelocation/$image.error";
  147. $fp = fopen($cacheimage, 'w');
  148. fclose($fp);
  149. image_not_found();
  150. }
  151. // The image was found, and it is readable.
  152. $pathinfo = pathinfo($imagefile);
  153. // Attempt to cache it if necessary.
  154. // We don't really want to overwrite any existing cache items just for the sake of it.
  155. $cacheimage = "$candidatelocation/$image.{$pathinfo['extension']}";
  156. if (!file_exists($cacheimage)) {
  157. // We don't already hold a cached copy of this image. Cache it now.
  158. $cacheimage = cache_image($image, $imagefile, $candidatelocation);
  159. }
  160. if (!$usesvg && $pathinfo['extension'] === 'svg') {
  161. // The browser has requested that a non-SVG version be returned.
  162. // The version found so far is the SVG version - try and find the non-SVG version.
  163. $imagefile = $theme->resolve_image_location($image, $component, false);
  164. if (empty($imagefile) || !is_readable($imagefile)) {
  165. // A non-SVG file could not be found at all.
  166. // The browser has requested a non-SVG version, so we must return image_not_found().
  167. // We must *not* write an .error file because the SVG is available.
  168. image_not_found();
  169. }
  170. // An non-SVG version of image was found - cache it.
  171. // This will be used below in the image serving code.
  172. $cacheimage = cache_image($image, $imagefile, $candidatelocation);
  173. }
  174. if (connection_aborted()) {
  175. // Request was cancelled - do not send anything.
  176. die;
  177. }
  178. // Make sure nothing failed.
  179. clearstatcache();
  180. if (file_exists($cacheimage)) {
  181. // The cached copy was found, and is accessible. Serve it.
  182. send_cached_image($cacheimage, $etag);
  183. }
  184. send_uncached_image($imagefile);
  185. //=================================================================================
  186. //=== utility functions ==
  187. // we are not using filelib because we need to fine tune all header
  188. // parameters to get the best performance.
  189. function send_cached_image($imagepath, $etag) {
  190. global $CFG;
  191. require("$CFG->dirroot/lib/xsendfilelib.php");
  192. $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
  193. $pathinfo = pathinfo($imagepath);
  194. $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
  195. $mimetype = get_contenttype_from_ext($pathinfo['extension']);
  196. header('Etag: "'.$etag.'"');
  197. header('Content-Disposition: inline; filename="'.$imagename.'"');
  198. header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($imagepath)) .' GMT');
  199. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  200. header('Pragma: ');
  201. header('Cache-Control: public, max-age='.$lifetime.', no-transform');
  202. header('Accept-Ranges: none');
  203. header('Content-Type: '.$mimetype);
  204. header('Content-Length: '.filesize($imagepath));
  205. if (xsendfile($imagepath)) {
  206. die;
  207. }
  208. // no need to gzip already compressed images ;-)
  209. readfile($imagepath);
  210. die;
  211. }
  212. function send_uncached_image($imagepath) {
  213. $pathinfo = pathinfo($imagepath);
  214. $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
  215. $mimetype = get_contenttype_from_ext($pathinfo['extension']);
  216. header('Content-Disposition: inline; filename="'.$imagename.'"');
  217. header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
  218. header('Expires: '. gmdate('D, d M Y H:i:s', time() + 15) .' GMT');
  219. header('Pragma: ');
  220. header('Accept-Ranges: none');
  221. header('Content-Type: '.$mimetype);
  222. header('Content-Length: '.filesize($imagepath));
  223. readfile($imagepath);
  224. die;
  225. }
  226. function image_not_found() {
  227. header('HTTP/1.0 404 not found');
  228. die('Image was not found, sorry.');
  229. }
  230. function get_contenttype_from_ext($ext) {
  231. switch ($ext) {
  232. case 'svg':
  233. return 'image/svg+xml';
  234. case 'png':
  235. return 'image/png';
  236. case 'gif':
  237. return 'image/gif';
  238. case 'jpg':
  239. case 'jpeg':
  240. return 'image/jpeg';
  241. case 'ico':
  242. return 'image/vnd.microsoft.icon';
  243. }
  244. return 'document/unknown';
  245. }
  246. /**
  247. * Caches a given image file.
  248. *
  249. * @param string $image The name of the image that was requested.
  250. * @param string $imagefile The location of the image file we want to cache.
  251. * @param string $candidatelocation The location to cache it in.
  252. * @return string The path to the cached image.
  253. */
  254. function cache_image($image, $imagefile, $candidatelocation) {
  255. global $CFG;
  256. $pathinfo = pathinfo($imagefile);
  257. $cacheimage = "$candidatelocation/$image.".$pathinfo['extension'];
  258. clearstatcache();
  259. if (!file_exists(dirname($cacheimage))) {
  260. @mkdir(dirname($cacheimage), $CFG->directorypermissions, true);
  261. }
  262. // Prevent serving of incomplete file from concurrent request,
  263. // the rename() should be more atomic than copy().
  264. ignore_user_abort(true);
  265. if (@copy($imagefile, $cacheimage.'.tmp')) {
  266. rename($cacheimage.'.tmp', $cacheimage);
  267. @chmod($cacheimage, $CFG->filepermissions);
  268. @unlink($cacheimage.'.tmp'); // just in case anything fails
  269. }
  270. return $cacheimage;
  271. }