Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/theme/ -> image.php (source)

Differences Between: [Versions 310 and 401]

   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  /**
  18   * This file is responsible for serving the one theme and plugin images.
  19   *
  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
  23   */
  24  
  25  
  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);
  29  
  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
  33  
  34  if ($slashargument = min_get_slash_argument()) {
  35      $slashargument = ltrim($slashargument, '/');
  36      if (substr_count($slashargument, '/') < 3) {
  37          image_not_found();
  38      }
  39      if (strpos($slashargument, '_s/') === 0) {
  40          // Can't use SVG
  41          $slashargument = substr($slashargument, 3);
  42          $usesvg = false;
  43      } else {
  44          $usesvg = true;
  45      }
  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');
  52  
  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');
  59  }
  60  
  61  if (!min_is_revision_valid_and_current($rev)) {
  62      // If the rev is invalid, normalise it to -1 to disable all caching.
  63      $rev = -1;
  64  }
  65  
  66  if (empty($component) or $component === 'moodle' or $component === 'core') {
  67      $component = 'core';
  68  }
  69  
  70  if (empty($image)) {
  71      image_not_found();
  72  }
  73  
  74  if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
  75      // exists
  76  } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) {
  77      // exists
  78  } else {
  79      image_not_found();
  80  }
  81  
  82  $candidatelocation = "$CFG->localcachedir/theme/$rev/$themename/pix/$component";
  83  $etag = sha1("$rev/$themename/$component/$image");
  84  
  85  if ($rev > 0) {
  86      if (file_exists("$candidatelocation/$image.error")) {
  87          // This is a major speedup if there are multiple missing images,
  88          // the only problem is that random requests may pollute our cache.
  89          image_not_found();
  90      }
  91      $cacheimage = false;
  92      if ($usesvg && file_exists("$candidatelocation/$image.svg")) {
  93          $cacheimage = "$candidatelocation/$image.svg";
  94          $ext = 'svg';
  95      } else if (file_exists("$candidatelocation/$image.png")) {
  96          $cacheimage = "$candidatelocation/$image.png";
  97          $ext = 'png';
  98      } else if (file_exists("$candidatelocation/$image.gif")) {
  99          $cacheimage = "$candidatelocation/$image.gif";
 100          $ext = 'gif';
 101      } else if (file_exists("$candidatelocation/$image.jpg")) {
 102          $cacheimage = "$candidatelocation/$image.jpg";
 103          $ext = 'jpg';
 104      } else if (file_exists("$candidatelocation/$image.jpeg")) {
 105          $cacheimage = "$candidatelocation/$image.jpeg";
 106          $ext = 'jpeg';
 107      } else if (file_exists("$candidatelocation/$image.ico")) {
 108          $cacheimage = "$candidatelocation/$image.ico";
 109          $ext = 'ico';
 110      }
 111      if ($cacheimage) {
 112          if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
 113              // We do not actually need to verify the etag value because our files
 114              // never change in cache because we increment the rev parameter.
 115              // 90 days only - based on Moodle point release cadence being every 3 months.
 116              $lifetime = 60 * 60 * 24 * 90;
 117              $mimetype = get_contenttype_from_ext($ext);
 118              header('HTTP/1.1 304 Not Modified');
 119              header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
 120              header('Cache-Control: public, max-age='.$lifetime.', no-transform');
 121              header('Content-Type: '.$mimetype);
 122              header('Etag: "'.$etag.'"');
 123              die;
 124          }
 125          send_cached_image($cacheimage, $etag);
 126      }
 127  }
 128  
 129  //=================================================================================
 130  // ok, now we need to start normal moodle script, we need to load all libs and $DB
 131  define('ABORT_AFTER_CONFIG_CANCEL', true);
 132  
 133  define('NO_MOODLE_COOKIES', true); // Session not used here
 134  define('NO_UPGRADE_CHECK', true);  // Ignore upgrade check
 135  
 136  require("$CFG->dirroot/lib/setup.php");
 137  
 138  $theme = theme_config::load($themename);
 139  $themerev = theme_get_revision();
 140  
 141  if ($themerev <= 0 or $rev != $themerev) {
 142      // Do not send caching headers if they do not request current revision,
 143      // we do not want to pollute browser caches with outdated images.
 144      $imagefile = $theme->resolve_image_location($image, $component, $usesvg);
 145      if (empty($imagefile) or !is_readable($imagefile)) {
 146          image_not_found();
 147      }
 148      send_uncached_image($imagefile);
 149  }
 150  
 151  make_localcache_directory('theme', false);
 152  
 153  // At this stage caching is enabled, and either:
 154  // * we have no cached copy of the image in any format (either SVG, or non-SVG); or
 155  // * we have a cached copy of the SVG, but the non-SVG was requested by the browser.
 156  //
 157  // Because of the way in which the cache return code works above:
 158  // * if we are allowed to return SVG, we do not need to cache the non-SVG version; however
 159  // * if the browser has requested the non-SVG version, we *must* cache _both_ the SVG, and the non-SVG versions.
 160  
 161  // First get all copies - including, potentially, the SVG version.
 162  $imagefile = $theme->resolve_image_location($image, $component, true);
 163  
 164  if (empty($imagefile) || !is_readable($imagefile)) {
 165      // Unable to find a copy of the image file in any format.
 166      // We write a .error file for the image now - this will be used above when searching for cached copies to prevent
 167      // trying to find the image in the future.
 168      if (!file_exists($candidatelocation)) {
 169          @mkdir($candidatelocation, $CFG->directorypermissions, true);
 170      }
 171      // Make note we can not find this file.
 172      $cacheimage = "$candidatelocation/$image.error";
 173      $fp = fopen($cacheimage, 'w');
 174      fclose($fp);
 175      image_not_found();
 176  }
 177  
 178  // The image was found, and it is readable.
 179  $pathinfo = pathinfo($imagefile);
 180  
 181  // Attempt to cache it if necessary.
 182  // We don't really want to overwrite any existing cache items just for the sake of it.
 183  $cacheimage = "$candidatelocation/$image.{$pathinfo['extension']}";
 184  if (!file_exists($cacheimage)) {
 185      // We don't already hold a cached copy of this image. Cache it now.
 186      $cacheimage = cache_image($image, $imagefile, $candidatelocation);
 187  }
 188  
 189  if (!$usesvg && $pathinfo['extension'] === 'svg') {
 190      // The browser has requested that a non-SVG version be returned.
 191      // The version found so far is the SVG version - try and find the non-SVG version.
 192      $imagefile = $theme->resolve_image_location($image, $component, false);
 193      if (empty($imagefile) || !is_readable($imagefile)) {
 194          // A non-SVG file could not be found at all.
 195          // The browser has requested a non-SVG version, so we must return image_not_found().
 196          // We must *not* write an .error file because the SVG is available.
 197          image_not_found();
 198      }
 199  
 200      // An non-SVG version of image was found - cache it.
 201      // This will be used below in the image serving code.
 202      $cacheimage = cache_image($image, $imagefile, $candidatelocation);
 203  }
 204  
 205  if (connection_aborted()) {
 206      // Request was cancelled - do not send anything.
 207      die;
 208  }
 209  
 210  // Make sure nothing failed.
 211  clearstatcache();
 212  if (file_exists($cacheimage)) {
 213      // The cached copy was found, and is accessible. Serve it.
 214      send_cached_image($cacheimage, $etag);
 215  }
 216  
 217  send_uncached_image($imagefile);
 218  
 219  //=================================================================================
 220  //=== utility functions ==
 221  // we are not using filelib because we need to fine tune all header
 222  // parameters to get the best performance.
 223  
 224  function send_cached_image($imagepath, $etag) {
 225      global $CFG;
 226      require("$CFG->dirroot/lib/xsendfilelib.php");
 227  
 228      // 90 days only - based on Moodle point release cadence being every 3 months.
 229      $lifetime = 60 * 60 * 24 * 90;
 230      $pathinfo = pathinfo($imagepath);
 231      $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
 232  
 233      $mimetype = get_contenttype_from_ext($pathinfo['extension']);
 234  
 235      header('Etag: "'.$etag.'"');
 236      header('Content-Disposition: inline; filename="'.$imagename.'"');
 237      header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($imagepath)) .' GMT');
 238      header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
 239      header('Pragma: ');
 240      header('Cache-Control: public, max-age='.$lifetime.', no-transform, immutable');
 241      header('Accept-Ranges: none');
 242      header('Content-Type: '.$mimetype);
 243  
 244      if (xsendfile($imagepath)) {
 245          die;
 246      }
 247  
 248      if ($mimetype === 'image/svg+xml') {
 249          // SVG format is a text file. So we can compress SVG files.
 250          if (!min_enable_zlib_compression()) {
 251              header('Content-Length: '.filesize($imagepath));
 252          }
 253      } else {
 254          // No need to compress other image formats.
 255          header('Content-Length: '.filesize($imagepath));
 256      }
 257  
 258      readfile($imagepath);
 259      die;
 260  }
 261  
 262  function send_uncached_image($imagepath) {
 263      $pathinfo = pathinfo($imagepath);
 264      $imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
 265  
 266      $mimetype = get_contenttype_from_ext($pathinfo['extension']);
 267  
 268      header('Content-Disposition: inline; filename="'.$imagename.'"');
 269      header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
 270      header('Expires: '. gmdate('D, d M Y H:i:s', time() + 15) .' GMT');
 271      header('Pragma: ');
 272      header('Accept-Ranges: none');
 273      header('Content-Type: '.$mimetype);
 274      header('Content-Length: '.filesize($imagepath));
 275  
 276      readfile($imagepath);
 277      die;
 278  }
 279  
 280  function image_not_found() {
 281      header('HTTP/1.0 404 not found');
 282      die('Image was not found, sorry.');
 283  }
 284  
 285  function get_contenttype_from_ext($ext) {
 286      switch ($ext) {
 287          case 'svg':
 288              return 'image/svg+xml';
 289          case 'png':
 290              return 'image/png';
 291          case 'gif':
 292              return 'image/gif';
 293          case 'jpg':
 294          case 'jpeg':
 295              return 'image/jpeg';
 296          case 'ico':
 297              return 'image/vnd.microsoft.icon';
 298      }
 299      return 'document/unknown';
 300  }
 301  
 302  /**
 303   * Caches a given image file.
 304   *
 305   * @param string $image The name of the image that was requested.
 306   * @param string $imagefile The location of the image file we want to cache.
 307   * @param string $candidatelocation The location to cache it in.
 308   * @return string The path to the cached image.
 309   */
 310  function cache_image($image, $imagefile, $candidatelocation) {
 311      global $CFG;
 312      $pathinfo = pathinfo($imagefile);
 313      $cacheimage = "$candidatelocation/$image.".$pathinfo['extension'];
 314  
 315      clearstatcache();
 316      if (!file_exists(dirname($cacheimage))) {
 317          @mkdir(dirname($cacheimage), $CFG->directorypermissions, true);
 318      }
 319  
 320      // Prevent serving of incomplete file from concurrent request,
 321      // the rename() should be more atomic than copy().
 322      ignore_user_abort(true);
 323      if (@copy($imagefile, $cacheimage.'.tmp')) {
 324          rename($cacheimage.'.tmp', $cacheimage);
 325          @chmod($cacheimage, $CFG->filepermissions);
 326          @unlink($cacheimage.'.tmp'); // just in case anything fails
 327      }
 328      return $cacheimage;
 329  }