Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/lib/ -> filelib.php (source)

Differences Between: [Versions 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   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   * Functions for file handling.
  19   *
  20   * @package   core_files
  21   * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
  22   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  /**
  28   * BYTESERVING_BOUNDARY - string unique string constant.
  29   */
  30  define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
  31  
  32  
  33  /**
  34   * Do not process file merging when working with draft area files.
  35   */
  36  define('IGNORE_FILE_MERGE', -1);
  37  
  38  /**
  39   * Unlimited area size constant
  40   */
  41  define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
  42  
  43  /**
  44   * Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  45   */
  46  define('DRAFT_AREA_BUCKET_CAPACITY', 50);
  47  
  48  /**
  49   * Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  50   */
  51  define('DRAFT_AREA_BUCKET_LEAK', 0.2);
  52  
  53  require_once("$CFG->libdir/filestorage/file_exceptions.php");
  54  require_once("$CFG->libdir/filestorage/file_storage.php");
  55  require_once("$CFG->libdir/filestorage/zip_packer.php");
  56  require_once("$CFG->libdir/filebrowser/file_browser.php");
  57  
  58  /**
  59   * Encodes file serving url
  60   *
  61   * @deprecated use moodle_url factory methods instead
  62   *
  63   * @todo MDL-31071 deprecate this function
  64   * @global stdClass $CFG
  65   * @param string $urlbase
  66   * @param string $path /filearea/itemid/dir/dir/file.exe
  67   * @param bool $forcedownload
  68   * @param bool $https https url required
  69   * @return string encoded file url
  70   */
  71  function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
  72      global $CFG;
  73  
  74  //TODO: deprecate this
  75  
  76      if ($CFG->slasharguments) {
  77          $parts = explode('/', $path);
  78          $parts = array_map('rawurlencode', $parts);
  79          $path  = implode('/', $parts);
  80          $return = $urlbase.$path;
  81          if ($forcedownload) {
  82              $return .= '?forcedownload=1';
  83          }
  84      } else {
  85          $path = rawurlencode($path);
  86          $return = $urlbase.'?file='.$path;
  87          if ($forcedownload) {
  88              $return .= '&amp;forcedownload=1';
  89          }
  90      }
  91  
  92      if ($https) {
  93          $return = str_replace('http://', 'https://', $return);
  94      }
  95  
  96      return $return;
  97  }
  98  
  99  /**
 100   * Detects if area contains subdirs,
 101   * this is intended for file areas that are attached to content
 102   * migrated from 1.x where subdirs were allowed everywhere.
 103   *
 104   * @param context $context
 105   * @param string $component
 106   * @param string $filearea
 107   * @param string $itemid
 108   * @return bool
 109   */
 110  function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
 111      global $DB;
 112  
 113      if (!isset($itemid)) {
 114          // Not initialised yet.
 115          return false;
 116      }
 117  
 118      // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
 119      $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
 120      $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
 121      return $DB->record_exists_select('files', $select, $params);
 122  }
 123  
 124  /**
 125   * Prepares 'editor' formslib element from data in database
 126   *
 127   * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
 128   * function then copies the embedded files into draft area (assigning itemids automatically),
 129   * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
 130   * displayed.
 131   * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
 132   * your mform's set_data() supplying the object returned by this function.
 133   *
 134   * @category files
 135   * @param stdClass $data database field that holds the html text with embedded media
 136   * @param string $field the name of the database field that holds the html text with embedded media
 137   * @param array $options editor options (like maxifiles, maxbytes etc.)
 138   * @param stdClass $context context of the editor
 139   * @param string $component
 140   * @param string $filearea file area name
 141   * @param int $itemid item id, required if item exists
 142   * @return stdClass modified data object
 143   */
 144  function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
 145      $options = (array)$options;
 146      if (!isset($options['trusttext'])) {
 147          $options['trusttext'] = false;
 148      }
 149      if (!isset($options['forcehttps'])) {
 150          $options['forcehttps'] = false;
 151      }
 152      if (!isset($options['subdirs'])) {
 153          $options['subdirs'] = false;
 154      }
 155      if (!isset($options['maxfiles'])) {
 156          $options['maxfiles'] = 0; // no files by default
 157      }
 158      if (!isset($options['noclean'])) {
 159          $options['noclean'] = false;
 160      }
 161  
 162      //sanity check for passed context. This function doesn't expect $option['context'] to be set
 163      //But this function is called before creating editor hence, this is one of the best places to check
 164      //if context is used properly. This check notify developer that they missed passing context to editor.
 165      if (isset($context) && !isset($options['context'])) {
 166          //if $context is not null then make sure $option['context'] is also set.
 167          debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
 168      } else if (isset($options['context']) && isset($context)) {
 169          //If both are passed then they should be equal.
 170          if ($options['context']->id != $context->id) {
 171              $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
 172              throw new coding_exception($exceptionmsg);
 173          }
 174      }
 175  
 176      if (is_null($itemid) or is_null($context)) {
 177          $contextid = null;
 178          $itemid = null;
 179          if (!isset($data)) {
 180              $data = new stdClass();
 181          }
 182          if (!isset($data->{$field})) {
 183              $data->{$field} = '';
 184          }
 185          if (!isset($data->{$field.'format'})) {
 186              $data->{$field.'format'} = editors_get_preferred_format();
 187          }
 188          if (!$options['noclean']) {
 189              $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
 190          }
 191  
 192      } else {
 193          if ($options['trusttext']) {
 194              // noclean ignored if trusttext enabled
 195              if (!isset($data->{$field.'trust'})) {
 196                  $data->{$field.'trust'} = 0;
 197              }
 198              $data = trusttext_pre_edit($data, $field, $context);
 199          } else {
 200              if (!$options['noclean']) {
 201                  $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
 202              }
 203          }
 204          $contextid = $context->id;
 205      }
 206  
 207      if ($options['maxfiles'] != 0) {
 208          $draftid_editor = file_get_submitted_draft_itemid($field);
 209          $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
 210          $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
 211      } else {
 212          $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
 213      }
 214  
 215      return $data;
 216  }
 217  
 218  /**
 219   * Prepares the content of the 'editor' form element with embedded media files to be saved in database
 220   *
 221   * This function moves files from draft area to the destination area and
 222   * encodes URLs to the draft files so they can be safely saved into DB. The
 223   * form has to contain the 'editor' element named foobar_editor, where 'foobar'
 224   * is the name of the database field to hold the wysiwyg editor content. The
 225   * editor data comes as an array with text, format and itemid properties. This
 226   * function automatically adds $data properties foobar, foobarformat and
 227   * foobartrust, where foobar has URL to embedded files encoded.
 228   *
 229   * @category files
 230   * @param stdClass $data raw data submitted by the form
 231   * @param string $field name of the database field containing the html with embedded media files
 232   * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
 233   * @param stdClass $context context, required for existing data
 234   * @param string $component file component
 235   * @param string $filearea file area name
 236   * @param int $itemid item id, required if item exists
 237   * @return stdClass modified data object
 238   */
 239  function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
 240      $options = (array)$options;
 241      if (!isset($options['trusttext'])) {
 242          $options['trusttext'] = false;
 243      }
 244      if (!isset($options['forcehttps'])) {
 245          $options['forcehttps'] = false;
 246      }
 247      if (!isset($options['subdirs'])) {
 248          $options['subdirs'] = false;
 249      }
 250      if (!isset($options['maxfiles'])) {
 251          $options['maxfiles'] = 0; // no files by default
 252      }
 253      if (!isset($options['maxbytes'])) {
 254          $options['maxbytes'] = 0; // unlimited
 255      }
 256      if (!isset($options['removeorphaneddrafts'])) {
 257          $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
 258      }
 259  
 260      if ($options['trusttext']) {
 261          $data->{$field.'trust'} = trusttext_trusted($context);
 262      } else {
 263          $data->{$field.'trust'} = 0;
 264      }
 265  
 266      $editor = $data->{$field.'_editor'};
 267  
 268      if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
 269          $data->{$field} = $editor['text'];
 270      } else {
 271          // Clean the user drafts area of any files not referenced in the editor text.
 272          if ($options['removeorphaneddrafts']) {
 273              file_remove_editor_orphaned_files($editor);
 274          }
 275          $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
 276      }
 277      $data->{$field.'format'} = $editor['format'];
 278  
 279      return $data;
 280  }
 281  
 282  /**
 283   * Saves text and files modified by Editor formslib element
 284   *
 285   * @category files
 286   * @param stdClass $data $database entry field
 287   * @param string $field name of data field
 288   * @param array $options various options
 289   * @param stdClass $context context - must already exist
 290   * @param string $component
 291   * @param string $filearea file area name
 292   * @param int $itemid must already exist, usually means data is in db
 293   * @return stdClass modified data obejct
 294   */
 295  function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
 296      $options = (array)$options;
 297      if (!isset($options['subdirs'])) {
 298          $options['subdirs'] = false;
 299      }
 300      if (is_null($itemid) or is_null($context)) {
 301          $itemid = null;
 302          $contextid = null;
 303      } else {
 304          $contextid = $context->id;
 305      }
 306  
 307      $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
 308      file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
 309      $data->{$field.'_filemanager'} = $draftid_editor;
 310  
 311      return $data;
 312  }
 313  
 314  /**
 315   * Saves files modified by File manager formslib element
 316   *
 317   * @todo MDL-31073 review this function
 318   * @category files
 319   * @param stdClass $data $database entry field
 320   * @param string $field name of data field
 321   * @param array $options various options
 322   * @param stdClass $context context - must already exist
 323   * @param string $component
 324   * @param string $filearea file area name
 325   * @param int $itemid must already exist, usually means data is in db
 326   * @return stdClass modified data obejct
 327   */
 328  function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
 329      $options = (array)$options;
 330      if (!isset($options['subdirs'])) {
 331          $options['subdirs'] = false;
 332      }
 333      if (!isset($options['maxfiles'])) {
 334          $options['maxfiles'] = -1; // unlimited
 335      }
 336      if (!isset($options['maxbytes'])) {
 337          $options['maxbytes'] = 0; // unlimited
 338      }
 339  
 340      if (empty($data->{$field.'_filemanager'})) {
 341          $data->$field = '';
 342  
 343      } else {
 344          file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
 345          $fs = get_file_storage();
 346  
 347          if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
 348              $data->$field = '1'; // TODO: this is an ugly hack (skodak)
 349          } else {
 350              $data->$field = '';
 351          }
 352      }
 353  
 354      return $data;
 355  }
 356  
 357  /**
 358   * Generate a draft itemid
 359   *
 360   * @category files
 361   * @global moodle_database $DB
 362   * @global stdClass $USER
 363   * @return int a random but available draft itemid that can be used to create a new draft
 364   * file area.
 365   */
 366  function file_get_unused_draft_itemid() {
 367      global $DB, $USER;
 368  
 369      if (isguestuser() or !isloggedin()) {
 370          // guests and not-logged-in users can not be allowed to upload anything!!!!!!
 371          print_error('noguest');
 372      }
 373  
 374      $contextid = context_user::instance($USER->id)->id;
 375  
 376      $fs = get_file_storage();
 377      $draftitemid = rand(1, 999999999);
 378      while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
 379          $draftitemid = rand(1, 999999999);
 380      }
 381  
 382      return $draftitemid;
 383  }
 384  
 385  /**
 386   * Initialise a draft file area from a real one by copying the files. A draft
 387   * area will be created if one does not already exist. Normally you should
 388   * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
 389   *
 390   * @category files
 391   * @global stdClass $CFG
 392   * @global stdClass $USER
 393   * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
 394   * @param int $contextid This parameter and the next two identify the file area to copy files from.
 395   * @param string $component
 396   * @param string $filearea helps indentify the file area.
 397   * @param int $itemid helps identify the file area. Can be null if there are no files yet.
 398   * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
 399   * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
 400   * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
 401   */
 402  function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
 403      global $CFG, $USER;
 404  
 405      $options = (array)$options;
 406      if (!isset($options['subdirs'])) {
 407          $options['subdirs'] = false;
 408      }
 409      if (!isset($options['forcehttps'])) {
 410          $options['forcehttps'] = false;
 411      }
 412  
 413      $usercontext = context_user::instance($USER->id);
 414      $fs = get_file_storage();
 415  
 416      if (empty($draftitemid)) {
 417          // create a new area and copy existing files into
 418          $draftitemid = file_get_unused_draft_itemid();
 419          $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
 420          if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
 421              foreach ($files as $file) {
 422                  if ($file->is_directory() and $file->get_filepath() === '/') {
 423                      // we need a way to mark the age of each draft area,
 424                      // by not copying the root dir we force it to be created automatically with current timestamp
 425                      continue;
 426                  }
 427                  if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
 428                      continue;
 429                  }
 430                  $draftfile = $fs->create_file_from_storedfile($file_record, $file);
 431                  // XXX: This is a hack for file manager (MDL-28666)
 432                  // File manager needs to know the original file information before copying
 433                  // to draft area, so we append these information in mdl_files.source field
 434                  // {@link file_storage::search_references()}
 435                  // {@link file_storage::search_references_count()}
 436                  $sourcefield = $file->get_source();
 437                  $newsourcefield = new stdClass;
 438                  $newsourcefield->source = $sourcefield;
 439                  $original = new stdClass;
 440                  $original->contextid = $contextid;
 441                  $original->component = $component;
 442                  $original->filearea  = $filearea;
 443                  $original->itemid    = $itemid;
 444                  $original->filename  = $file->get_filename();
 445                  $original->filepath  = $file->get_filepath();
 446                  $newsourcefield->original = file_storage::pack_reference($original);
 447                  $draftfile->set_source(serialize($newsourcefield));
 448                  // End of file manager hack
 449              }
 450          }
 451          if (!is_null($text)) {
 452              // at this point there should not be any draftfile links yet,
 453              // because this is a new text from database that should still contain the @@pluginfile@@ links
 454              // this happens when developers forget to post process the text
 455              $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
 456          }
 457      } else {
 458          // nothing to do
 459      }
 460  
 461      if (is_null($text)) {
 462          return null;
 463      }
 464  
 465      // relink embedded files - editor can not handle @@PLUGINFILE@@ !
 466      return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
 467  }
 468  
 469  /**
 470   * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
 471   * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
 472   * in the @@PLUGINFILE@@ form.
 473   *
 474   * @param   string  $text The content that may contain ULRs in need of rewriting.
 475   * @param   string  $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
 476   * @param   int     $contextid This parameter and the next two identify the file area to use.
 477   * @param   string  $component
 478   * @param   string  $filearea helps identify the file area.
 479   * @param   int     $itemid helps identify the file area.
 480   * @param   array   $options
 481   *          bool    $options.forcehttps Force the user of https
 482   *          bool    $options.reverse Reverse the behaviour of the function
 483   *          mixed   $options.includetoken Use a token for authentication. True for current user, int value for other user id.
 484   *          string  The processed text.
 485   */
 486  function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
 487      global $CFG, $USER;
 488  
 489      $options = (array)$options;
 490      if (!isset($options['forcehttps'])) {
 491          $options['forcehttps'] = false;
 492      }
 493  
 494      $baseurl = "{$CFG->wwwroot}/{$file}";
 495      if (!empty($options['includetoken'])) {
 496          $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
 497          $token = get_user_key('core_files', $userid);
 498          $finalfile = basename($file);
 499          $tokenfile = "token{$finalfile}";
 500          $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
 501          $baseurl = "{$CFG->wwwroot}/{$file}";
 502  
 503          if (!$CFG->slasharguments) {
 504              $baseurl .= "?token={$token}&file=";
 505          } else {
 506              $baseurl .= "/{$token}";
 507          }
 508      }
 509  
 510      $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
 511  
 512      if ($itemid !== null) {
 513          $baseurl .= "$itemid/";
 514      }
 515  
 516      if ($options['forcehttps']) {
 517          $baseurl = str_replace('http://', 'https://', $baseurl);
 518      }
 519  
 520      if (!empty($options['reverse'])) {
 521          return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
 522      } else {
 523          return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
 524      }
 525  }
 526  
 527  /**
 528   * Returns information about files in a draft area.
 529   *
 530   * @global stdClass $CFG
 531   * @global stdClass $USER
 532   * @param int $draftitemid the draft area item id.
 533   * @param string $filepath path to the directory from which the information have to be retrieved.
 534   * @return array with the following entries:
 535   *      'filecount' => number of files in the draft area.
 536   *      'filesize' => total size of the files in the draft area.
 537   *      'foldercount' => number of folders in the draft area.
 538   *      'filesize_without_references' => total size of the area excluding file references.
 539   * (more information will be added as needed).
 540   */
 541  function file_get_draft_area_info($draftitemid, $filepath = '/') {
 542      global $USER;
 543  
 544      $usercontext = context_user::instance($USER->id);
 545      return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
 546  }
 547  
 548  /**
 549   * Returns information about files in an area.
 550   *
 551   * @param int $contextid context id
 552   * @param string $component component
 553   * @param string $filearea file area name
 554   * @param int $itemid item id or all files if not specified
 555   * @param string $filepath path to the directory from which the information have to be retrieved.
 556   * @return array with the following entries:
 557   *      'filecount' => number of files in the area.
 558   *      'filesize' => total size of the files in the area.
 559   *      'foldercount' => number of folders in the area.
 560   *      'filesize_without_references' => total size of the area excluding file references.
 561   * @since Moodle 3.4
 562   */
 563  function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
 564  
 565      $fs = get_file_storage();
 566  
 567      $results = array(
 568          'filecount' => 0,
 569          'foldercount' => 0,
 570          'filesize' => 0,
 571          'filesize_without_references' => 0
 572      );
 573  
 574      $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
 575  
 576      foreach ($draftfiles as $file) {
 577          if ($file->is_directory()) {
 578              $results['foldercount'] += 1;
 579          } else {
 580              $results['filecount'] += 1;
 581          }
 582  
 583          $filesize = $file->get_filesize();
 584          $results['filesize'] += $filesize;
 585          if (!$file->is_external_file()) {
 586              $results['filesize_without_references'] += $filesize;
 587          }
 588      }
 589  
 590      return $results;
 591  }
 592  
 593  /**
 594   * Returns whether a draft area has exceeded/will exceed its size limit.
 595   *
 596   * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
 597   *
 598   * @param int $draftitemid the draft area item id.
 599   * @param int $areamaxbytes the maximum size allowed in this draft area.
 600   * @param int $newfilesize the size that would be added to the current area.
 601   * @param bool $includereferences true to include the size of the references in the area size.
 602   * @return bool true if the area will/has exceeded its limit.
 603   * @since Moodle 2.4
 604   */
 605  function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
 606      if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
 607          $draftinfo = file_get_draft_area_info($draftitemid);
 608          $areasize = $draftinfo['filesize_without_references'];
 609          if ($includereferences) {
 610              $areasize = $draftinfo['filesize'];
 611          }
 612          if ($areasize + $newfilesize > $areamaxbytes) {
 613              return true;
 614          }
 615      }
 616      return false;
 617  }
 618  
 619  /**
 620   * Returns whether a user has reached their draft area upload rate.
 621   *
 622   * @param int $userid The user id
 623   * @return bool
 624   */
 625  function file_is_draft_areas_limit_reached(int $userid): bool {
 626      global $CFG;
 627  
 628      $capacity = $CFG->draft_area_bucket_capacity ?? DRAFT_AREA_BUCKET_CAPACITY;
 629      $leak = $CFG->draft_area_bucket_leak ?? DRAFT_AREA_BUCKET_LEAK;
 630  
 631      $since = time() - floor($capacity / $leak); // The items that were in the bucket before this time are already leaked by now.
 632                                                  // We are going to be a bit generous to the user when using the leaky bucket
 633                                                  // algorithm below. We are going to assume that the bucket is empty at $since.
 634                                                  // We have to do an assumption here unless we really want to get ALL user's draft
 635                                                  // items without any limit and put all of them in the leaking bucket.
 636                                                  // I decided to favour performance over accuracy here.
 637  
 638      $fs = get_file_storage();
 639      $items = $fs->get_user_draft_items($userid, $since);
 640      $items = array_reverse($items); // So that the items are sorted based on time in the ascending direction.
 641  
 642      // We only need to store the time that each element in the bucket is going to leak. So $bucket is array of leaking times.
 643      $bucket = [];
 644      foreach ($items as $item) {
 645          $now = $item->timemodified;
 646          // First let's see if items can be dropped from the bucket as a result of leakage.
 647          while (!empty($bucket) && ($now >= $bucket[0])) {
 648              array_shift($bucket);
 649          }
 650  
 651          // Calculate the time that the new item we put into the bucket will be leaked from it, and store it into the bucket.
 652          if ($bucket) {
 653              $bucket[] = max($bucket[count($bucket) - 1], $now) + (1 / $leak);
 654          } else {
 655              $bucket[] = $now + (1 / $leak);
 656          }
 657      }
 658  
 659      // Recalculate the bucket's content based on the leakage until now.
 660      $now = time();
 661      while (!empty($bucket) && ($now >= $bucket[0])) {
 662          array_shift($bucket);
 663      }
 664  
 665      return count($bucket) >= $capacity;
 666  }
 667  
 668  /**
 669   * Get used space of files
 670   * @global moodle_database $DB
 671   * @global stdClass $USER
 672   * @return int total bytes
 673   */
 674  function file_get_user_used_space() {
 675      global $DB, $USER;
 676  
 677      $usercontext = context_user::instance($USER->id);
 678      $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
 679              JOIN (SELECT contenthash, filename, MAX(id) AS id
 680              FROM {files}
 681              WHERE contextid = ? AND component = ? AND filearea != ?
 682              GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
 683      $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
 684      $record = $DB->get_record_sql($sql, $params);
 685      return (int)$record->totalbytes;
 686  }
 687  
 688  /**
 689   * Convert any string to a valid filepath
 690   * @todo review this function
 691   * @param string $str
 692   * @return string path
 693   */
 694  function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
 695      if ($str == '/' or empty($str)) {
 696          return '/';
 697      } else {
 698          return '/'.trim($str, '/').'/';
 699      }
 700  }
 701  
 702  /**
 703   * Generate a folder tree of draft area of current USER recursively
 704   *
 705   * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
 706   * @param int $draftitemid
 707   * @param string $filepath
 708   * @param mixed $data
 709   */
 710  function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
 711      global $USER, $OUTPUT, $CFG;
 712      $data->children = array();
 713      $context = context_user::instance($USER->id);
 714      $fs = get_file_storage();
 715      if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
 716          foreach ($files as $file) {
 717              if ($file->is_directory()) {
 718                  $item = new stdClass();
 719                  $item->sortorder = $file->get_sortorder();
 720                  $item->filepath = $file->get_filepath();
 721  
 722                  $foldername = explode('/', trim($item->filepath, '/'));
 723                  $item->fullname = trim(array_pop($foldername), '/');
 724  
 725                  $item->id = uniqid();
 726                  file_get_drafarea_folders($draftitemid, $item->filepath, $item);
 727                  $data->children[] = $item;
 728              } else {
 729                  continue;
 730              }
 731          }
 732      }
 733  }
 734  
 735  /**
 736   * Listing all files (including folders) in current path (draft area)
 737   * used by file manager
 738   * @param int $draftitemid
 739   * @param string $filepath
 740   * @return stdClass
 741   */
 742  function file_get_drafarea_files($draftitemid, $filepath = '/') {
 743      global $USER, $OUTPUT, $CFG;
 744  
 745      $context = context_user::instance($USER->id);
 746      $fs = get_file_storage();
 747  
 748      $data = new stdClass();
 749      $data->path = array();
 750      $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
 751  
 752      // will be used to build breadcrumb
 753      $trail = '/';
 754      if ($filepath !== '/') {
 755          $filepath = file_correct_filepath($filepath);
 756          $parts = explode('/', $filepath);
 757          foreach ($parts as $part) {
 758              if ($part != '' && $part != null) {
 759                  $trail .= ($part.'/');
 760                  $data->path[] = array('name'=>$part, 'path'=>$trail);
 761              }
 762          }
 763      }
 764  
 765      $list = array();
 766      $maxlength = 12;
 767      if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
 768          foreach ($files as $file) {
 769              $item = new stdClass();
 770              $item->filename = $file->get_filename();
 771              $item->filepath = $file->get_filepath();
 772              $item->fullname = trim($item->filename, '/');
 773              $filesize = $file->get_filesize();
 774              $item->size = $filesize ? $filesize : null;
 775              $item->filesize = $filesize ? display_size($filesize) : '';
 776  
 777              $item->sortorder = $file->get_sortorder();
 778              $item->author = $file->get_author();
 779              $item->license = $file->get_license();
 780              $item->datemodified = $file->get_timemodified();
 781              $item->datecreated = $file->get_timecreated();
 782              $item->isref = $file->is_external_file();
 783              if ($item->isref && $file->get_status() == 666) {
 784                  $item->originalmissing = true;
 785              }
 786              // find the file this draft file was created from and count all references in local
 787              // system pointing to that file
 788              $source = @unserialize($file->get_source());
 789              if (isset($source->original)) {
 790                  $item->refcount = $fs->search_references_count($source->original);
 791              }
 792  
 793              if ($file->is_directory()) {
 794                  $item->filesize = 0;
 795                  $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
 796                  $item->type = 'folder';
 797                  $foldername = explode('/', trim($item->filepath, '/'));
 798                  $item->fullname = trim(array_pop($foldername), '/');
 799                  $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
 800              } else {
 801                  // do NOT use file browser here!
 802                  $item->mimetype = get_mimetype_description($file);
 803                  if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
 804                      $item->type = 'zip';
 805                  } else {
 806                      $item->type = 'file';
 807                  }
 808                  $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
 809                  $item->url = $itemurl->out();
 810                  $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
 811                  $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
 812  
 813                  // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
 814                  // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
 815                  // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
 816                  // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
 817                  // used by the widget to display a warning about the problem files.
 818                  // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
 819                  $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
 820                  if ($item->status == 0) {
 821                      if ($imageinfo = $file->get_imageinfo()) {
 822                          $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
 823                              'oid' => $file->get_timemodified()));
 824                          $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
 825                          $item->image_width = $imageinfo['width'];
 826                          $item->image_height = $imageinfo['height'];
 827                      }
 828                  }
 829              }
 830              $list[] = $item;
 831          }
 832      }
 833      $data->itemid = $draftitemid;
 834      $data->list = $list;
 835      return $data;
 836  }
 837  
 838  /**
 839   * Returns all of the files in the draftarea.
 840   *
 841   * @param  int $draftitemid The draft item ID
 842   * @param  string $filepath path for the uploaded files.
 843   * @return array An array of files associated with this draft item id.
 844   */
 845  function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
 846      $files = [];
 847      $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
 848      file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
 849  
 850      if (!empty($draftfiles)) {
 851          foreach ($draftfiles->list as $draftfile) {
 852              if ($draftfile->type == 'file') {
 853                  $files[] = $draftfile;
 854              }
 855          }
 856  
 857          if (isset($draftfiles->children)) {
 858              foreach ($draftfiles->children as $draftfile) {
 859                  $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
 860              }
 861          }
 862      }
 863      return $files;
 864  }
 865  
 866  /**
 867   * Returns draft area itemid for a given element.
 868   *
 869   * @category files
 870   * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
 871   * @return int the itemid, or 0 if there is not one yet.
 872   */
 873  function file_get_submitted_draft_itemid($elname) {
 874      // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
 875      if (!isset($_REQUEST[$elname])) {
 876          return 0;
 877      }
 878      if (is_array($_REQUEST[$elname])) {
 879          $param = optional_param_array($elname, 0, PARAM_INT);
 880          if (!empty($param['itemid'])) {
 881              $param = $param['itemid'];
 882          } else {
 883              debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
 884              return false;
 885          }
 886  
 887      } else {
 888          $param = optional_param($elname, 0, PARAM_INT);
 889      }
 890  
 891      if ($param) {
 892          require_sesskey();
 893      }
 894  
 895      return $param;
 896  }
 897  
 898  /**
 899   * Restore the original source field from draft files
 900   *
 901   * Do not use this function because it makes field files.source inconsistent
 902   * for draft area files. This function will be deprecated in 2.6
 903   *
 904   * @param stored_file $storedfile This only works with draft files
 905   * @return stored_file
 906   */
 907  function file_restore_source_field_from_draft_file($storedfile) {
 908      $source = @unserialize($storedfile->get_source());
 909      if (!empty($source)) {
 910          if (is_object($source)) {
 911              $restoredsource = $source->source;
 912              $storedfile->set_source($restoredsource);
 913          } else {
 914              throw new moodle_exception('invalidsourcefield', 'error');
 915          }
 916      }
 917      return $storedfile;
 918  }
 919  
 920  /**
 921   * Removes those files from the user drafts filearea which are not referenced in the editor text.
 922   *
 923   * @param stdClass $editor The online text editor element from the submitted form data.
 924   */
 925  function file_remove_editor_orphaned_files($editor) {
 926      global $CFG, $USER;
 927  
 928      // Find those draft files included in the text, and generate their hashes.
 929      $context = context_user::instance($USER->id);
 930      $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
 931      $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
 932      preg_match_all($pattern, $editor['text'], $matches);
 933      $usedfilehashes = [];
 934      foreach ($matches[1] as $matchedfilename) {
 935          $matchedfilename = urldecode($matchedfilename);
 936          $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
 937                                                               $matchedfilename);
 938      }
 939  
 940      // Now, compare the hashes of all draft files, and remove those which don't match used files.
 941      $fs = get_file_storage();
 942      $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
 943      foreach ($files as $file) {
 944          $tmphash = $file->get_pathnamehash();
 945          if (!in_array($tmphash, $usedfilehashes)) {
 946              $file->delete();
 947          }
 948      }
 949  }
 950  
 951  /**
 952   * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
 953   * content from another draft area it's possible for a single textarea to reference multiple draft areas.
 954   *
 955   * @category files
 956   * @param int $draftitemid the id of the primary draft area.
 957   *            When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
 958   * @param int $usercontextid the user's context id.
 959   * @param string $text some html content that needs to have files copied to the correct draft area.
 960   * @param bool $forcehttps force https urls.
 961   *
 962   * @return string $text html content modified with new draft links
 963   */
 964  function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
 965      if (is_null($text)) {
 966          return null;
 967      }
 968  
 969      // Do not merge files, leave it as it was.
 970      if ($draftitemid === IGNORE_FILE_MERGE) {
 971          return null;
 972      }
 973  
 974      $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
 975  
 976      // No draft areas to rewrite.
 977      if (empty($urls)) {
 978          return $text;
 979      }
 980  
 981      foreach ($urls as $url) {
 982          // Do not process the "home" draft area.
 983          if ($url['itemid'] == $draftitemid) {
 984              continue;
 985          }
 986  
 987          // Decode the filename.
 988          $filename = urldecode($url['filename']);
 989  
 990          // Copy the file.
 991          file_copy_file_to_file_area($url, $filename, $draftitemid);
 992  
 993          // Rewrite draft area.
 994          $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
 995      }
 996      return $text;
 997  }
 998  
 999  /**
1000   * Rewrites a file area in arbitrary text.
1001   *
1002   * @param array $file General information about the file.
1003   * @param int $newid The new file area itemid.
1004   * @param string $text The text to rewrite.
1005   * @param bool $forcehttps force https urls.
1006   * @return string The rewritten text.
1007   */
1008  function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
1009      global $CFG;
1010  
1011      $wwwroot = $CFG->wwwroot;
1012      if ($forcehttps) {
1013          $wwwroot = str_replace('http://', 'https://', $wwwroot);
1014      }
1015  
1016      $search = [
1017          $wwwroot,
1018          $file['urlbase'],
1019          $file['contextid'],
1020          $file['component'],
1021          $file['filearea'],
1022          $file['itemid'],
1023          $file['filename']
1024      ];
1025      $replace = [
1026          $wwwroot,
1027          $file['urlbase'],
1028          $file['contextid'],
1029          $file['component'],
1030          $file['filearea'],
1031          $newid,
1032          $file['filename']
1033      ];
1034  
1035      $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
1036      return $text;
1037  }
1038  
1039  /**
1040   * Copies a file from one file area to another.
1041   *
1042   * @param array $file Information about the file to be copied.
1043   * @param string $filename The filename.
1044   * @param int $itemid The new file area.
1045   */
1046  function file_copy_file_to_file_area($file, $filename, $itemid) {
1047      $fs = get_file_storage();
1048  
1049      // Load the current file in the old draft area.
1050      $fileinfo = array(
1051          'component' => $file['component'],
1052          'filearea' => $file['filearea'],
1053          'itemid' => $file['itemid'],
1054          'contextid' => $file['contextid'],
1055          'filepath' => '/',
1056          'filename' => $filename
1057      );
1058      $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
1059          $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
1060      $newfileinfo = array(
1061          'component' => $file['component'],
1062          'filearea' => $file['filearea'],
1063          'itemid' => $itemid,
1064          'contextid' => $file['contextid'],
1065          'filepath' => '/',
1066          'filename' => $filename
1067      );
1068  
1069      $newcontextid = $newfileinfo['contextid'];
1070      $newcomponent = $newfileinfo['component'];
1071      $newfilearea = $newfileinfo['filearea'];
1072      $newitemid = $newfileinfo['itemid'];
1073      $newfilepath = $newfileinfo['filepath'];
1074      $newfilename = $newfileinfo['filename'];
1075  
1076      // Check if the file exists.
1077      if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
1078          $fs->create_file_from_storedfile($newfileinfo, $oldfile);
1079      }
1080  }
1081  
1082  /**
1083   * Saves files from a draft file area to a real one (merging the list of files).
1084   * Can rewrite URLs in some content at the same time if desired.
1085   *
1086   * @category files
1087   * @global stdClass $USER
1088   * @param int $draftitemid the id of the draft area to use. Normally obtained
1089   *      from file_get_submitted_draft_itemid('elementname') or similar.
1090   *      When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
1091   * @param int $contextid This parameter and the next two identify the file area to save to.
1092   * @param string $component
1093   * @param string $filearea indentifies the file area.
1094   * @param int $itemid helps identifies the file area.
1095   * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
1096   * @param string $text some html content that needs to have embedded links rewritten
1097   *      to the @@PLUGINFILE@@ form for saving in the database.
1098   * @param bool $forcehttps force https urls.
1099   * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
1100   */
1101  function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
1102      global $USER;
1103  
1104      // Do not merge files, leave it as it was.
1105      if ($draftitemid === IGNORE_FILE_MERGE) {
1106          // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
1107          return $text;
1108      }
1109  
1110      $usercontext = context_user::instance($USER->id);
1111      $fs = get_file_storage();
1112  
1113      $options = (array)$options;
1114      if (!isset($options['subdirs'])) {
1115          $options['subdirs'] = false;
1116      }
1117      if (!isset($options['maxfiles'])) {
1118          $options['maxfiles'] = -1; // unlimited
1119      }
1120      if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
1121          $options['maxbytes'] = 0; // unlimited
1122      }
1123      if (!isset($options['areamaxbytes'])) {
1124          $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
1125      }
1126      $allowreferences = true;
1127      if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
1128          // we assume that if $options['return_types'] is NOT specified, we DO allow references.
1129          // this is not exactly right. BUT there are many places in code where filemanager options
1130          // are not passed to file_save_draft_area_files()
1131          $allowreferences = false;
1132      }
1133  
1134      // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
1135      // areas and need to be copied into the current draft area.
1136      $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
1137  
1138      // Check if the draft area has exceeded the authorised limit. This should never happen as validation
1139      // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
1140      // anything at all in the next area.
1141      if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
1142          return null;
1143      }
1144  
1145      $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
1146      $oldfiles   = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
1147  
1148      // One file in filearea means it is empty (it has only top-level directory '.').
1149      if (count($draftfiles) > 1 || count($oldfiles) > 1) {
1150          // we have to merge old and new files - we want to keep file ids for files that were not changed
1151          // we change time modified for all new and changed files, we keep time created as is
1152  
1153          $newhashes = array();
1154          $filecount = 0;
1155          $context = context::instance_by_id($contextid, MUST_EXIST);
1156          foreach ($draftfiles as $file) {
1157              if (!$options['subdirs'] && $file->get_filepath() !== '/') {
1158                  continue;
1159              }
1160              if (!$allowreferences && $file->is_external_file()) {
1161                  continue;
1162              }
1163              if (!$file->is_directory()) {
1164                  // Check to see if this file was uploaded by someone who can ignore the file size limits.
1165                  $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
1166                  if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
1167                          && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
1168                      // Oversized file.
1169                      continue;
1170                  }
1171                  if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
1172                      // more files - should not get here at all
1173                      continue;
1174                  }
1175                  $filecount++;
1176              }
1177              $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
1178              $newhashes[$newhash] = $file;
1179          }
1180  
1181          // Loop through oldfiles and decide which we need to delete and which to update.
1182          // After this cycle the array $newhashes will only contain the files that need to be added.
1183          foreach ($oldfiles as $oldfile) {
1184              $oldhash = $oldfile->get_pathnamehash();
1185              if (!isset($newhashes[$oldhash])) {
1186                  // delete files not needed any more - deleted by user
1187                  $oldfile->delete();
1188                  continue;
1189              }
1190  
1191              $newfile = $newhashes[$oldhash];
1192              // Now we know that we have $oldfile and $newfile for the same path.
1193              // Let's check if we can update this file or we need to delete and create.
1194              if ($newfile->is_directory()) {
1195                  // Directories are always ok to just update.
1196              } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
1197                  // File has the 'original' - we need to update the file (it may even have not been changed at all).
1198                  $original = file_storage::unpack_reference($source->original);
1199                  if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
1200                      // Very odd, original points to another file. Delete and create file.
1201                      $oldfile->delete();
1202                      continue;
1203                  }
1204              } else {
1205                  // The same file name but absence of 'original' means that file was deteled and uploaded again.
1206                  // By deleting and creating new file we properly manage all existing references.
1207                  $oldfile->delete();
1208                  continue;
1209              }
1210  
1211              // status changed, we delete old file, and create a new one
1212              if ($oldfile->get_status() != $newfile->get_status()) {
1213                  // file was changed, use updated with new timemodified data
1214                  $oldfile->delete();
1215                  // This file will be added later
1216                  continue;
1217              }
1218  
1219              // Updated author
1220              if ($oldfile->get_author() != $newfile->get_author()) {
1221                  $oldfile->set_author($newfile->get_author());
1222              }
1223              // Updated license
1224              if ($oldfile->get_license() != $newfile->get_license()) {
1225                  $oldfile->set_license($newfile->get_license());
1226              }
1227  
1228              // Updated file source
1229              // Field files.source for draftarea files contains serialised object with source and original information.
1230              // We only store the source part of it for non-draft file area.
1231              $newsource = $newfile->get_source();
1232              if ($source = @unserialize($newfile->get_source())) {
1233                  $newsource = $source->source;
1234              }
1235              if ($oldfile->get_source() !== $newsource) {
1236                  $oldfile->set_source($newsource);
1237              }
1238  
1239              // Updated sort order
1240              if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
1241                  $oldfile->set_sortorder($newfile->get_sortorder());
1242              }
1243  
1244              // Update file timemodified
1245              if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
1246                  $oldfile->set_timemodified($newfile->get_timemodified());
1247              }
1248  
1249              // Replaced file content
1250              if (!$oldfile->is_directory() &&
1251                      ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
1252                      $oldfile->get_filesize() != $newfile->get_filesize() ||
1253                      $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
1254                      $oldfile->get_userid() != $newfile->get_userid())) {
1255                  $oldfile->replace_file_with($newfile);
1256              }
1257  
1258              // unchanged file or directory - we keep it as is
1259              unset($newhashes[$oldhash]);
1260          }
1261  
1262          // Add fresh file or the file which has changed status
1263          // the size and subdirectory tests are extra safety only, the UI should prevent it
1264          foreach ($newhashes as $file) {
1265              $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
1266              if ($source = @unserialize($file->get_source())) {
1267                  // Field files.source for draftarea files contains serialised object with source and original information.
1268                  // We only store the source part of it for non-draft file area.
1269                  $file_record['source'] = $source->source;
1270              }
1271  
1272              if ($file->is_external_file()) {
1273                  $repoid = $file->get_repository_id();
1274                  if (!empty($repoid)) {
1275                      $context = context::instance_by_id($contextid, MUST_EXIST);
1276                      $repo = repository::get_repository_by_id($repoid, $context);
1277                      if (!empty($options)) {
1278                          $repo->options = $options;
1279                      }
1280                      $file_record['repositoryid'] = $repoid;
1281                      // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
1282                      // to the file store. E.g. transfer ownership of the file to a system account etc.
1283                      $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
1284  
1285                      $file_record['reference'] = $reference;
1286                  }
1287              }
1288  
1289              $fs->create_file_from_storedfile($file_record, $file);
1290          }
1291      }
1292  
1293      // note: do not purge the draft area - we clean up areas later in cron,
1294      //       the reason is that user might press submit twice and they would loose the files,
1295      //       also sometimes we might want to use hacks that save files into two different areas
1296  
1297      if (is_null($text)) {
1298          return null;
1299      } else {
1300          return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
1301      }
1302  }
1303  
1304  /**
1305   * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
1306   * ready to be saved in the database. Normally, this is done automatically by
1307   * {@link file_save_draft_area_files()}.
1308   *
1309   * @category files
1310   * @param string $text the content to process.
1311   * @param int $draftitemid the draft file area the content was using.
1312   * @param bool $forcehttps whether the content contains https URLs. Default false.
1313   * @return string the processed content.
1314   */
1315  function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
1316      global $CFG, $USER;
1317  
1318      $usercontext = context_user::instance($USER->id);
1319  
1320      $wwwroot = $CFG->wwwroot;
1321      if ($forcehttps) {
1322          $wwwroot = str_replace('http://', 'https://', $wwwroot);
1323      }
1324  
1325      // relink embedded files if text submitted - no absolute links allowed in database!
1326      $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1327  
1328      if (strpos($text, 'draftfile.php?file=') !== false) {
1329          $matches = array();
1330          preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
1331          if ($matches) {
1332              foreach ($matches[0] as $match) {
1333                  $replace = str_ireplace('%2F', '/', $match);
1334                  $text = str_replace($match, $replace, $text);
1335              }
1336          }
1337          $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
1338      }
1339  
1340      return $text;
1341  }
1342  
1343  /**
1344   * Set file sort order
1345   *
1346   * @global moodle_database $DB
1347   * @param int $contextid the context id
1348   * @param string $component file component
1349   * @param string $filearea file area.
1350   * @param int $itemid itemid.
1351   * @param string $filepath file path.
1352   * @param string $filename file name.
1353   * @param int $sortorder the sort order of file.
1354   * @return bool
1355   */
1356  function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
1357      global $DB;
1358      $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
1359      if ($file_record = $DB->get_record('files', $conditions)) {
1360          $sortorder = (int)$sortorder;
1361          $file_record->sortorder = $sortorder;
1362          $DB->update_record('files', $file_record);
1363          return true;
1364      }
1365      return false;
1366  }
1367  
1368  /**
1369   * reset file sort order number to 0
1370   * @global moodle_database $DB
1371   * @param int $contextid the context id
1372   * @param string $component
1373   * @param string $filearea file area.
1374   * @param int|bool $itemid itemid.
1375   * @return bool
1376   */
1377  function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
1378      global $DB;
1379  
1380      $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
1381      if ($itemid !== false) {
1382          $conditions['itemid'] = $itemid;
1383      }
1384  
1385      $file_records = $DB->get_records('files', $conditions);
1386      foreach ($file_records as $file_record) {
1387          $file_record->sortorder = 0;
1388          $DB->update_record('files', $file_record);
1389      }
1390      return true;
1391  }
1392  
1393  /**
1394   * Returns description of upload error
1395   *
1396   * @param int $errorcode found in $_FILES['filename.ext']['error']
1397   * @return string error description string, '' if ok
1398   */
1399  function file_get_upload_error($errorcode) {
1400  
1401      switch ($errorcode) {
1402      case 0: // UPLOAD_ERR_OK - no error
1403          $errmessage = '';
1404          break;
1405  
1406      case 1: // UPLOAD_ERR_INI_SIZE
1407          $errmessage = get_string('uploadserverlimit');
1408          break;
1409  
1410      case 2: // UPLOAD_ERR_FORM_SIZE
1411          $errmessage = get_string('uploadformlimit');
1412          break;
1413  
1414      case 3: // UPLOAD_ERR_PARTIAL
1415          $errmessage = get_string('uploadpartialfile');
1416          break;
1417  
1418      case 4: // UPLOAD_ERR_NO_FILE
1419          $errmessage = get_string('uploadnofilefound');
1420          break;
1421  
1422      // Note: there is no error with a value of 5
1423  
1424      case 6: // UPLOAD_ERR_NO_TMP_DIR
1425          $errmessage = get_string('uploadnotempdir');
1426          break;
1427  
1428      case 7: // UPLOAD_ERR_CANT_WRITE
1429          $errmessage = get_string('uploadcantwrite');
1430          break;
1431  
1432      case 8: // UPLOAD_ERR_EXTENSION
1433          $errmessage = get_string('uploadextension');
1434          break;
1435  
1436      default:
1437          $errmessage = get_string('uploadproblem');
1438      }
1439  
1440      return $errmessage;
1441  }
1442  
1443  /**
1444   * Recursive function formating an array in POST parameter
1445   * @param array $arraydata - the array that we are going to format and add into &$data array
1446   * @param string $currentdata - a row of the final postdata array at instant T
1447   *                when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
1448   * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
1449   */
1450  function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
1451          foreach ($arraydata as $k=>$v) {
1452              $newcurrentdata = $currentdata;
1453              if (is_array($v)) { //the value is an array, call the function recursively
1454                  $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
1455                  format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
1456              }  else { //add the POST parameter to the $data array
1457                  $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
1458              }
1459          }
1460  }
1461  
1462  /**
1463   * Transform a PHP array into POST parameter
1464   * (see the recursive function format_array_postdata_for_curlcall)
1465   * @param array $postdata
1466   * @return array containing all POST parameters  (1 row = 1 POST parameter)
1467   */
1468  function format_postdata_for_curlcall($postdata) {
1469          $data = array();
1470          foreach ($postdata as $k=>$v) {
1471              if (is_array($v)) {
1472                  $currentdata = urlencode($k);
1473                  format_array_postdata_for_curlcall($v, $currentdata, $data);
1474              }  else {
1475                  $data[] = urlencode($k).'='.urlencode($v);
1476              }
1477          }
1478          $convertedpostdata = implode('&', $data);
1479          return $convertedpostdata;
1480  }
1481  
1482  /**
1483   * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
1484   * Due to security concerns only downloads from http(s) sources are supported.
1485   *
1486   * @category files
1487   * @param string $url file url starting with http(s)://
1488   * @param array $headers http headers, null if none. If set, should be an
1489   *   associative array of header name => value pairs.
1490   * @param array $postdata array means use POST request with given parameters
1491   * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
1492   *   (if false, just returns content)
1493   * @param int $timeout timeout for complete download process including all file transfer
1494   *   (default 5 minutes)
1495   * @param int $connecttimeout timeout for connection to server; this is the timeout that
1496   *   usually happens if the remote server is completely down (default 20 seconds);
1497   *   may not work when using proxy
1498   * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
1499   *   Only use this when already in a trusted location.
1500   * @param string $tofile store the downloaded content to file instead of returning it.
1501   * @param bool $calctimeout false by default, true enables an extra head request to try and determine
1502   *   filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
1503   * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
1504   *   if file downloaded into $tofile successfully or the file content as a string.
1505   */
1506  function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
1507      global $CFG;
1508  
1509      // Only http and https links supported.
1510      if (!preg_match('|^https?://|i', $url)) {
1511          if ($fullresponse) {
1512              $response = new stdClass();
1513              $response->status        = 0;
1514              $response->headers       = array();
1515              $response->response_code = 'Invalid protocol specified in url';
1516              $response->results       = '';
1517              $response->error         = 'Invalid protocol specified in url';
1518              return $response;
1519          } else {
1520              return false;
1521          }
1522      }
1523  
1524      $options = array();
1525  
1526      $headers2 = array();
1527      if (is_array($headers)) {
1528          foreach ($headers as $key => $value) {
1529              if (is_numeric($key)) {
1530                  $headers2[] = $value;
1531              } else {
1532                  $headers2[] = "$key: $value";
1533              }
1534          }
1535      }
1536  
1537      if ($skipcertverify) {
1538          $options['CURLOPT_SSL_VERIFYPEER'] = false;
1539      } else {
1540          $options['CURLOPT_SSL_VERIFYPEER'] = true;
1541      }
1542  
1543      $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
1544  
1545      $options['CURLOPT_FOLLOWLOCATION'] = 1;
1546      $options['CURLOPT_MAXREDIRS'] = 5;
1547  
1548      // Use POST if requested.
1549      if (is_array($postdata)) {
1550          $postdata = format_postdata_for_curlcall($postdata);
1551      } else if (empty($postdata)) {
1552          $postdata = null;
1553      }
1554  
1555      // Optionally attempt to get more correct timeout by fetching the file size.
1556      if (!isset($CFG->curltimeoutkbitrate)) {
1557          // Use very slow rate of 56kbps as a timeout speed when not set.
1558          $bitrate = 56;
1559      } else {
1560          $bitrate = $CFG->curltimeoutkbitrate;
1561      }
1562      if ($calctimeout and !isset($postdata)) {
1563          $curl = new curl();
1564          $curl->setHeader($headers2);
1565  
1566          $curl->head($url, $postdata, $options);
1567  
1568          $info = $curl->get_info();
1569          $error_no = $curl->get_errno();
1570          if (!$error_no && $info['download_content_length'] > 0) {
1571              // No curl errors - adjust for large files only - take max timeout.
1572              $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
1573          }
1574      }
1575  
1576      $curl = new curl();
1577      $curl->setHeader($headers2);
1578  
1579      $options['CURLOPT_RETURNTRANSFER'] = true;
1580      $options['CURLOPT_NOBODY'] = false;
1581      $options['CURLOPT_TIMEOUT'] = $timeout;
1582  
1583      if ($tofile) {
1584          $fh = fopen($tofile, 'w');
1585          if (!$fh) {
1586              if ($fullresponse) {
1587                  $response = new stdClass();
1588                  $response->status        = 0;
1589                  $response->headers       = array();
1590                  $response->response_code = 'Can not write to file';
1591                  $response->results       = false;
1592                  $response->error         = 'Can not write to file';
1593                  return $response;
1594              } else {
1595                  return false;
1596              }
1597          }
1598          $options['CURLOPT_FILE'] = $fh;
1599      }
1600  
1601      if (isset($postdata)) {
1602          $content = $curl->post($url, $postdata, $options);
1603      } else {
1604          $content = $curl->get($url, null, $options);
1605      }
1606  
1607      if ($tofile) {
1608          fclose($fh);
1609          @chmod($tofile, $CFG->filepermissions);
1610      }
1611  
1612  /*
1613      // Try to detect encoding problems.
1614      if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
1615          curl_setopt($ch, CURLOPT_ENCODING, 'none');
1616          $result = curl_exec($ch);
1617      }
1618  */
1619  
1620      $info       = $curl->get_info();
1621      $error_no   = $curl->get_errno();
1622      $rawheaders = $curl->get_raw_response();
1623  
1624      if ($error_no) {
1625          $error = $content;
1626          if (!$fullresponse) {
1627              debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
1628              return false;
1629          }
1630  
1631          $response = new stdClass();
1632          if ($error_no == 28) {
1633              $response->status    = '-100'; // Mimic snoopy.
1634          } else {
1635              $response->status    = '0';
1636          }
1637          $response->headers       = array();
1638          $response->response_code = $error;
1639          $response->results       = false;
1640          $response->error         = $error;
1641          return $response;
1642      }
1643  
1644      if ($tofile) {
1645          $content = true;
1646      }
1647  
1648      if (empty($info['http_code'])) {
1649          // For security reasons we support only true http connections (Location: file:// exploit prevention).
1650          $response = new stdClass();
1651          $response->status        = '0';
1652          $response->headers       = array();
1653          $response->response_code = 'Unknown cURL error';
1654          $response->results       = false; // do NOT change this, we really want to ignore the result!
1655          $response->error         = 'Unknown cURL error';
1656  
1657      } else {
1658          $response = new stdClass();
1659          $response->status        = (string)$info['http_code'];
1660          $response->headers       = $rawheaders;
1661          $response->results       = $content;
1662          $response->error         = '';
1663  
1664          // There might be multiple headers on redirect, find the status of the last one.
1665          $firstline = true;
1666          foreach ($rawheaders as $line) {
1667              if ($firstline) {
1668                  $response->response_code = $line;
1669                  $firstline = false;
1670              }
1671              if (trim($line, "\r\n") === '') {
1672                  $firstline = true;
1673              }
1674          }
1675      }
1676  
1677      if ($fullresponse) {
1678          return $response;
1679      }
1680  
1681      if ($info['http_code'] != 200) {
1682          debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
1683          return false;
1684      }
1685      return $response->results;
1686  }
1687  
1688  /**
1689   * Returns a list of information about file types based on extensions.
1690   *
1691   * The following elements expected in value array for each extension:
1692   * 'type' - mimetype
1693   * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
1694   *     or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
1695   *     also files with bigger sizes under names
1696   *     FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
1697   * 'groups' (optional) - array of filetype groups this filetype extension is part of;
1698   *     commonly used in moodle the following groups:
1699   *       - web_image - image that can be included as <img> in HTML
1700   *       - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
1701   *       - optimised_image - image that will be processed and optimised
1702   *       - video - file that can be imported as video in text editor
1703   *       - audio - file that can be imported as audio in text editor
1704   *       - archive - we can extract files from this archive
1705   *       - spreadsheet - used for portfolio format
1706   *       - document - used for portfolio format
1707   *       - presentation - used for portfolio format
1708   * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
1709   *     human-readable description for this filetype;
1710   *     Function {@link get_mimetype_description()} first looks at the presence of string for
1711   *     particular mimetype (value of 'type'), if not found looks for string specified in 'string'
1712   *     attribute, if not found returns the value of 'type';
1713   * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
1714   *     an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
1715   *     this function will return first found icon; Especially usefull for types such as 'text/plain'
1716   *
1717   * @category files
1718   * @return array List of information about file types based on extensions.
1719   *   Associative array of extension (lower-case) to associative array
1720   *   from 'element name' to data. Current element names are 'type' and 'icon'.
1721   *   Unknown types should use the 'xxx' entry which includes defaults.
1722   */
1723  function &get_mimetypes_array() {
1724      // Get types from the core_filetypes function, which includes caching.
1725      return core_filetypes::get_types();
1726  }
1727  
1728  /**
1729   * Determine a file's MIME type based on the given filename using the function mimeinfo.
1730   *
1731   * This function retrieves a file's MIME type for a file that will be sent to the user.
1732   * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
1733   * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
1734   * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
1735   *
1736   * @param string $filename The file's filename.
1737   * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
1738   */
1739  function get_mimetype_for_sending($filename = '') {
1740      // Guess the file's MIME type using mimeinfo.
1741      $mimetype = mimeinfo('type', $filename);
1742  
1743      // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
1744      if (!$mimetype || $mimetype === 'document/unknown') {
1745          $mimetype = 'application/octet-stream';
1746      }
1747  
1748      return $mimetype;
1749  }
1750  
1751  /**
1752   * Obtains information about a filetype based on its extension. Will
1753   * use a default if no information is present about that particular
1754   * extension.
1755   *
1756   * @category files
1757   * @param string $element Desired information (usually 'icon'
1758   *   for icon filename or 'type' for MIME type. Can also be
1759   *   'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
1760   * @param string $filename Filename we're looking up
1761   * @return string Requested piece of information from array
1762   */
1763  function mimeinfo($element, $filename) {
1764      global $CFG;
1765      $mimeinfo = & get_mimetypes_array();
1766      static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1767  
1768      $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1769      if (empty($filetype)) {
1770          $filetype = 'xxx'; // file without extension
1771      }
1772      if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
1773          $iconsize = max(array(16, (int)$iconsizematch[1]));
1774          $filenames = array($mimeinfo['xxx']['icon']);
1775          if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
1776              array_unshift($filenames, $mimeinfo[$filetype]['icon']);
1777          }
1778          // find the file with the closest size, first search for specific icon then for default icon
1779          foreach ($filenames as $filename) {
1780              foreach ($iconpostfixes as $size => $postfix) {
1781                  $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
1782                  if ($iconsize >= $size &&
1783                          (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1784                      return $filename.$postfix;
1785                  }
1786              }
1787          }
1788      } else if (isset($mimeinfo[$filetype][$element])) {
1789          return $mimeinfo[$filetype][$element];
1790      } else if (isset($mimeinfo['xxx'][$element])) {
1791          return $mimeinfo['xxx'][$element];   // By default
1792      } else {
1793          return null;
1794      }
1795  }
1796  
1797  /**
1798   * Obtains information about a filetype based on the MIME type rather than
1799   * the other way around.
1800   *
1801   * @category files
1802   * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
1803   * @param string $mimetype MIME type we're looking up
1804   * @return string Requested piece of information from array
1805   */
1806  function mimeinfo_from_type($element, $mimetype) {
1807      /* array of cached mimetype->extension associations */
1808      static $cached = array();
1809      $mimeinfo = & get_mimetypes_array();
1810  
1811      if (!array_key_exists($mimetype, $cached)) {
1812          $cached[$mimetype] = null;
1813          foreach($mimeinfo as $filetype => $values) {
1814              if ($values['type'] == $mimetype) {
1815                  if ($cached[$mimetype] === null) {
1816                      $cached[$mimetype] = '.'.$filetype;
1817                  }
1818                  if (!empty($values['defaulticon'])) {
1819                      $cached[$mimetype] = '.'.$filetype;
1820                      break;
1821                  }
1822              }
1823          }
1824          if (empty($cached[$mimetype])) {
1825              $cached[$mimetype] = '.xxx';
1826          }
1827      }
1828      if ($element === 'extension') {
1829          return $cached[$mimetype];
1830      } else {
1831          return mimeinfo($element, $cached[$mimetype]);
1832      }
1833  }
1834  
1835  /**
1836   * Return the relative icon path for a given file
1837   *
1838   * Usage:
1839   * <code>
1840   * // $file - instance of stored_file or file_info
1841   * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
1842   * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
1843   * </code>
1844   * or
1845   * <code>
1846   * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
1847   * </code>
1848   *
1849   * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
1850   *     and $file->mimetype are expected)
1851   * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1852   * @return string
1853   */
1854  function file_file_icon($file, $size = null) {
1855      if (!is_object($file)) {
1856          $file = (object)$file;
1857      }
1858      if (isset($file->filename)) {
1859          $filename = $file->filename;
1860      } else if (method_exists($file, 'get_filename')) {
1861          $filename = $file->get_filename();
1862      } else if (method_exists($file, 'get_visible_name')) {
1863          $filename = $file->get_visible_name();
1864      } else {
1865          $filename = '';
1866      }
1867      if (isset($file->mimetype)) {
1868          $mimetype = $file->mimetype;
1869      } else if (method_exists($file, 'get_mimetype')) {
1870          $mimetype = $file->get_mimetype();
1871      } else {
1872          $mimetype = '';
1873      }
1874      $mimetypes = &get_mimetypes_array();
1875      if ($filename) {
1876          $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
1877          if ($extension && !empty($mimetypes[$extension])) {
1878              // if file name has known extension, return icon for this extension
1879              return file_extension_icon($filename, $size);
1880          }
1881      }
1882      return file_mimetype_icon($mimetype, $size);
1883  }
1884  
1885  /**
1886   * Return the relative icon path for a folder image
1887   *
1888   * Usage:
1889   * <code>
1890   * $icon = $OUTPUT->image_url(file_folder_icon())->out();
1891   * echo html_writer::empty_tag('img', array('src' => $icon));
1892   * </code>
1893   * or
1894   * <code>
1895   * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
1896   * </code>
1897   *
1898   * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
1899   * @return string
1900   */
1901  function file_folder_icon($iconsize = null) {
1902      global $CFG;
1903      static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
1904      static $cached = array();
1905      $iconsize = max(array(16, (int)$iconsize));
1906      if (!array_key_exists($iconsize, $cached)) {
1907          foreach ($iconpostfixes as $size => $postfix) {
1908              $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
1909              if ($iconsize >= $size &&
1910                      (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
1911                  $cached[$iconsize] = 'f/folder'.$postfix;
1912                  break;
1913              }
1914          }
1915      }
1916      return $cached[$iconsize];
1917  }
1918  
1919  /**
1920   * Returns the relative icon path for a given mime type
1921   *
1922   * This function should be used in conjunction with $OUTPUT->image_url to produce
1923   * a return the full path to an icon.
1924   *
1925   * <code>
1926   * $mimetype = 'image/jpg';
1927   * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
1928   * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
1929   * </code>
1930   *
1931   * @category files
1932   * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1933   * to conform with that.
1934   * @param string $mimetype The mimetype to fetch an icon for
1935   * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1936   * @return string The relative path to the icon
1937   */
1938  function file_mimetype_icon($mimetype, $size = NULL) {
1939      return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
1940  }
1941  
1942  /**
1943   * Returns the relative icon path for a given file name
1944   *
1945   * This function should be used in conjunction with $OUTPUT->image_url to produce
1946   * a return the full path to an icon.
1947   *
1948   * <code>
1949   * $filename = '.jpg';
1950   * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
1951   * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
1952   * </code>
1953   *
1954   * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
1955   * to conform with that.
1956   * @todo MDL-31074 Implement $size
1957   * @category files
1958   * @param string $filename The filename to get the icon for
1959   * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
1960   * @return string
1961   */
1962  function file_extension_icon($filename, $size = NULL) {
1963      return 'f/'.mimeinfo('icon'.$size, $filename);
1964  }
1965  
1966  /**
1967   * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
1968   * mimetypes.php language file.
1969   *
1970   * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
1971   *   'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
1972   *   have filename); In case of array/stdClass the field 'mimetype' is optional.
1973   * @param bool $capitalise If true, capitalises first character of result
1974   * @return string Text description
1975   */
1976  function get_mimetype_description($obj, $capitalise=false) {
1977      $filename = $mimetype = '';
1978      if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
1979          // this is an instance of stored_file
1980          $mimetype = $obj->get_mimetype();
1981          $filename = $obj->get_filename();
1982      } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
1983          // this is an instance of file_info
1984          $mimetype = $obj->get_mimetype();
1985          $filename = $obj->get_visible_name();
1986      } else if (is_array($obj) || is_object ($obj)) {
1987          $obj = (array)$obj;
1988          if (!empty($obj['filename'])) {
1989              $filename = $obj['filename'];
1990          }
1991          if (!empty($obj['mimetype'])) {
1992              $mimetype = $obj['mimetype'];
1993          }
1994      } else {
1995          $mimetype = $obj;
1996      }
1997      $mimetypefromext = mimeinfo('type', $filename);
1998      if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
1999          // if file has a known extension, overwrite the specified mimetype
2000          $mimetype = $mimetypefromext;
2001      }
2002      $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
2003      if (empty($extension)) {
2004          $mimetypestr = mimeinfo_from_type('string', $mimetype);
2005          $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
2006      } else {
2007          $mimetypestr = mimeinfo('string', $filename);
2008      }
2009      $chunks = explode('/', $mimetype, 2);
2010      $chunks[] = '';
2011      $attr = array(
2012          'mimetype' => $mimetype,
2013          'ext' => $extension,
2014          'mimetype1' => $chunks[0],
2015          'mimetype2' => $chunks[1],
2016      );
2017      $a = array();
2018      foreach ($attr as $key => $value) {
2019          $a[$key] = $value;
2020          $a[strtoupper($key)] = strtoupper($value);
2021          $a[ucfirst($key)] = ucfirst($value);
2022      }
2023  
2024      // MIME types may include + symbol but this is not permitted in string ids.
2025      $safemimetype = str_replace('+', '_', $mimetype);
2026      $safemimetypestr = str_replace('+', '_', $mimetypestr);
2027      $customdescription = mimeinfo('customdescription', $filename);
2028      if ($customdescription) {
2029          // Call format_string on the custom description so that multilang
2030          // filter can be used (if enabled on system context). We use system
2031          // context because it is possible that the page context might not have
2032          // been defined yet.
2033          $result = format_string($customdescription, true,
2034                  array('context' => context_system::instance()));
2035      } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
2036          $result = get_string($safemimetype, 'mimetypes', (object)$a);
2037      } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
2038          $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
2039      } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
2040          $result = get_string('default', 'mimetypes', (object)$a);
2041      } else {
2042          $result = $mimetype;
2043      }
2044      if ($capitalise) {
2045          $result=ucfirst($result);
2046      }
2047      return $result;
2048  }
2049  
2050  /**
2051   * Returns array of elements of type $element in type group(s)
2052   *
2053   * @param string $element name of the element we are interested in, usually 'type' or 'extension'
2054   * @param string|array $groups one group or array of groups/extensions/mimetypes
2055   * @return array
2056   */
2057  function file_get_typegroup($element, $groups) {
2058      static $cached = array();
2059      if (!is_array($groups)) {
2060          $groups = array($groups);
2061      }
2062      if (!array_key_exists($element, $cached)) {
2063          $cached[$element] = array();
2064      }
2065      $result = array();
2066      foreach ($groups as $group) {
2067          if (!array_key_exists($group, $cached[$element])) {
2068              // retrieive and cache all elements of type $element for group $group
2069              $mimeinfo = & get_mimetypes_array();
2070              $cached[$element][$group] = array();
2071              foreach ($mimeinfo as $extension => $value) {
2072                  $value['extension'] = '.'.$extension;
2073                  if (empty($value[$element])) {
2074                      continue;
2075                  }
2076                  if (($group === '.'.$extension || $group === $value['type'] ||
2077                          (!empty($value['groups']) && in_array($group, $value['groups']))) &&
2078                          !in_array($value[$element], $cached[$element][$group])) {
2079                      $cached[$element][$group][] = $value[$element];
2080                  }
2081              }
2082          }
2083          $result = array_merge($result, $cached[$element][$group]);
2084      }
2085      return array_values(array_unique($result));
2086  }
2087  
2088  /**
2089   * Checks if file with name $filename has one of the extensions in groups $groups
2090   *
2091   * @see get_mimetypes_array()
2092   * @param string $filename name of the file to check
2093   * @param string|array $groups one group or array of groups to check
2094   * @param bool $checktype if true and extension check fails, find the mimetype and check if
2095   * file mimetype is in mimetypes in groups $groups
2096   * @return bool
2097   */
2098  function file_extension_in_typegroup($filename, $groups, $checktype = false) {
2099      $extension = pathinfo($filename, PATHINFO_EXTENSION);
2100      if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
2101          return true;
2102      }
2103      return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
2104  }
2105  
2106  /**
2107   * Checks if mimetype $mimetype belongs to one of the groups $groups
2108   *
2109   * @see get_mimetypes_array()
2110   * @param string $mimetype
2111   * @param string|array $groups one group or array of groups to check
2112   * @return bool
2113   */
2114  function file_mimetype_in_typegroup($mimetype, $groups) {
2115      return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
2116  }
2117  
2118  /**
2119   * Requested file is not found or not accessible, does not return, terminates script
2120   *
2121   * @global stdClass $CFG
2122   * @global stdClass $COURSE
2123   */
2124  function send_file_not_found() {
2125      global $CFG, $COURSE;
2126  
2127      // Allow cross-origin requests only for Web Services.
2128      // This allow to receive requests done by Web Workers or webapps in different domains.
2129      if (WS_SERVER) {
2130          header('Access-Control-Allow-Origin: *');
2131      }
2132  
2133      send_header_404();
2134      print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
2135  }
2136  /**
2137   * Helper function to send correct 404 for server.
2138   */
2139  function send_header_404() {
2140      if (substr(php_sapi_name(), 0, 3) == 'cgi') {
2141          header("Status: 404 Not Found");
2142      } else {
2143          header('HTTP/1.0 404 not found');
2144      }
2145  }
2146  
2147  /**
2148   * The readfile function can fail when files are larger than 2GB (even on 64-bit
2149   * platforms). This wrapper uses readfile for small files and custom code for
2150   * large ones.
2151   *
2152   * @param string $path Path to file
2153   * @param int $filesize Size of file (if left out, will get it automatically)
2154   * @return int|bool Size read (will always be $filesize) or false if failed
2155   */
2156  function readfile_allow_large($path, $filesize = -1) {
2157      // Automatically get size if not specified.
2158      if ($filesize === -1) {
2159          $filesize = filesize($path);
2160      }
2161      if ($filesize <= 2147483647) {
2162          // If the file is up to 2^31 - 1, send it normally using readfile.
2163          return readfile($path);
2164      } else {
2165          // For large files, read and output in 64KB chunks.
2166          $handle = fopen($path, 'r');
2167          if ($handle === false) {
2168              return false;
2169          }
2170          $left = $filesize;
2171          while ($left > 0) {
2172              $size = min($left, 65536);
2173              $buffer = fread($handle, $size);
2174              if ($buffer === false) {
2175                  return false;
2176              }
2177              echo $buffer;
2178              $left -= $size;
2179          }
2180          return $filesize;
2181      }
2182  }
2183  
2184  /**
2185   * Enhanced readfile() with optional acceleration.
2186   * @param string|stored_file $file
2187   * @param string $mimetype
2188   * @param bool $accelerate
2189   * @return void
2190   */
2191  function readfile_accel($file, $mimetype, $accelerate) {
2192      global $CFG;
2193  
2194      if ($mimetype === 'text/plain') {
2195          // there is no encoding specified in text files, we need something consistent
2196          header('Content-Type: text/plain; charset=utf-8');
2197      } else {
2198          header('Content-Type: '.$mimetype);
2199      }
2200  
2201      $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
2202      header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2203  
2204      if (is_object($file)) {
2205          header('Etag: "' . $file->get_contenthash() . '"');
2206          if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
2207              header('HTTP/1.1 304 Not Modified');
2208              return;
2209          }
2210      }
2211  
2212      // if etag present for stored file rely on it exclusively
2213      if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
2214          // get unixtime of request header; clip extra junk off first
2215          $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
2216          if ($since && $since >= $lastmodified) {
2217              header('HTTP/1.1 304 Not Modified');
2218              return;
2219          }
2220      }
2221  
2222      if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2223          header('Accept-Ranges: bytes');
2224      } else {
2225          header('Accept-Ranges: none');
2226      }
2227  
2228      if ($accelerate) {
2229          if (is_object($file)) {
2230              $fs = get_file_storage();
2231              if ($fs->supports_xsendfile()) {
2232                  if ($fs->xsendfile_file($file)) {
2233                      return;
2234                  }
2235              }
2236          } else {
2237              if (!empty($CFG->xsendfile)) {
2238                  require_once("$CFG->libdir/xsendfilelib.php");
2239                  if (xsendfile($file)) {
2240                      return;
2241                  }
2242              }
2243          }
2244      }
2245  
2246      $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
2247  
2248      header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
2249  
2250      if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
2251  
2252          if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
2253              // byteserving stuff - for acrobat reader and download accelerators
2254              // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
2255              // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
2256              $ranges = false;
2257              if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
2258                  foreach ($ranges as $key=>$value) {
2259                      if ($ranges[$key][1] == '') {
2260                          //suffix case
2261                          $ranges[$key][1] = $filesize - $ranges[$key][2];
2262                          $ranges[$key][2] = $filesize - 1;
2263                      } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
2264                          //fix range length
2265                          $ranges[$key][2] = $filesize - 1;
2266                      }
2267                      if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
2268                          //invalid byte-range ==> ignore header
2269                          $ranges = false;
2270                          break;
2271                      }
2272                      //prepare multipart header
2273                      $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
2274                      $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
2275                  }
2276              } else {
2277                  $ranges = false;
2278              }
2279              if ($ranges) {
2280                  if (is_object($file)) {
2281                      $handle = $file->get_content_file_handle();
2282                      if ($handle === false) {
2283                          throw new file_exception('storedfilecannotreadfile', $file->get_filename());
2284                      }
2285                  } else {
2286                      $handle = fopen($file, 'rb');
2287                      if ($handle === false) {
2288                          throw new file_exception('cannotopenfile', $file);
2289                      }
2290                  }
2291                  byteserving_send_file($handle, $mimetype, $ranges, $filesize);
2292              }
2293          }
2294      }
2295  
2296      header('Content-Length: ' . $filesize);
2297  
2298      if (!empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] === 'HEAD') {
2299          exit;
2300      }
2301  
2302      while (ob_get_level()) {
2303          $handlerstack = ob_list_handlers();
2304          $activehandler = array_pop($handlerstack);
2305          if ($activehandler === 'default output handler') {
2306              // We do not expect any content in the buffer when we are serving files.
2307              $buffercontents = ob_get_clean();
2308              if ($buffercontents !== '') {
2309                  error_log('Non-empty default output handler buffer detected while serving the file ' . $file);
2310              }
2311          } else {
2312              // Some handlers such as zlib output compression may have file signature buffered - flush it.
2313              ob_end_flush();
2314          }
2315      }
2316  
2317      // send the whole file content
2318      if (is_object($file)) {
2319          $file->readfile();
2320      } else {
2321          if (readfile_allow_large($file, $filesize) === false) {
2322              throw new file_exception('cannotopenfile', $file);
2323          }
2324      }
2325  }
2326  
2327  /**
2328   * Similar to readfile_accel() but designed for strings.
2329   * @param string $string
2330   * @param string $mimetype
2331   * @param bool $accelerate Ignored
2332   * @return void
2333   */
2334  function readstring_accel($string, $mimetype, $accelerate = false) {
2335      global $CFG;
2336  
2337      if ($mimetype === 'text/plain') {
2338          // there is no encoding specified in text files, we need something consistent
2339          header('Content-Type: text/plain; charset=utf-8');
2340      } else {
2341          header('Content-Type: '.$mimetype);
2342      }
2343      header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
2344      header('Accept-Ranges: none');
2345      header('Content-Length: '.strlen($string));
2346      echo $string;
2347  }
2348  
2349  /**
2350   * Handles the sending of temporary file to user, download is forced.
2351   * File is deleted after abort or successful sending, does not return, script terminated
2352   *
2353   * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
2354   * @param string $filename proposed file name when saving file
2355   * @param bool $pathisstring If the path is string
2356   */
2357  function send_temp_file($path, $filename, $pathisstring=false) {
2358      global $CFG;
2359  
2360      // Guess the file's MIME type.
2361      $mimetype = get_mimetype_for_sending($filename);
2362  
2363      // close session - not needed anymore
2364      \core\session\manager::write_close();
2365  
2366      if (!$pathisstring) {
2367          if (!file_exists($path)) {
2368              send_header_404();
2369              print_error('filenotfound', 'error', $CFG->wwwroot.'/');
2370          }
2371          // executed after normal finish or abort
2372          core_shutdown_manager::register_function('send_temp_file_finished', array($path));
2373      }
2374  
2375      // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2376      if (core_useragent::is_ie() || core_useragent::is_edge()) {
2377          $filename = urlencode($filename);
2378      }
2379  
2380      // If this file was requested from a form, then mark download as complete.
2381      \core_form\util::form_download_complete();
2382  
2383      header('Content-Disposition: attachment; filename="'.$filename.'"');
2384      if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2385          header('Cache-Control: private, max-age=10, no-transform');
2386          header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2387          header('Pragma: ');
2388      } else { //normal http - prevent caching at all cost
2389          header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2390          header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2391          header('Pragma: no-cache');
2392      }
2393  
2394      // send the contents - we can not accelerate this because the file will be deleted asap
2395      if ($pathisstring) {
2396          readstring_accel($path, $mimetype);
2397      } else {
2398          readfile_accel($path, $mimetype, false);
2399          @unlink($path);
2400      }
2401  
2402      die; //no more chars to output
2403  }
2404  
2405  /**
2406   * Internal callback function used by send_temp_file()
2407   *
2408   * @param string $path
2409   */
2410  function send_temp_file_finished($path) {
2411      if (file_exists($path)) {
2412          @unlink($path);
2413      }
2414  }
2415  
2416  /**
2417   * Serve content which is not meant to be cached.
2418   *
2419   * This is only intended to be used for volatile public files, for instance
2420   * when development is enabled, or when caching is not required on a public resource.
2421   *
2422   * @param string $content Raw content.
2423   * @param string $filename The file name.
2424   * @return void
2425   */
2426  function send_content_uncached($content, $filename) {
2427      $mimetype = mimeinfo('type', $filename);
2428      $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
2429  
2430      header('Content-Disposition: inline; filename="' . $filename . '"');
2431      header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
2432      header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
2433      header('Pragma: ');
2434      header('Accept-Ranges: none');
2435      header('Content-Type: ' . $mimetype . $charset);
2436      header('Content-Length: ' . strlen($content));
2437  
2438      echo $content;
2439      die();
2440  }
2441  
2442  /**
2443   * Safely save content to a certain path.
2444   *
2445   * This function tries hard to be atomic by first copying the content
2446   * to a separate file, and then moving the file across. It also prevents
2447   * the user to abort a request to prevent half-safed files.
2448   *
2449   * This function is intended to be used when saving some content to cache like
2450   * $CFG->localcachedir. If you're not caching a file you should use the File API.
2451   *
2452   * @param string $content The file content.
2453   * @param string $destination The absolute path of the final file.
2454   * @return void
2455   */
2456  function file_safe_save_content($content, $destination) {
2457      global $CFG;
2458  
2459      clearstatcache();
2460      if (!file_exists(dirname($destination))) {
2461          @mkdir(dirname($destination), $CFG->directorypermissions, true);
2462      }
2463  
2464      // Prevent serving of incomplete file from concurrent request,
2465      // the rename() should be more atomic than fwrite().
2466      ignore_user_abort(true);
2467      if ($fp = fopen($destination . '.tmp', 'xb')) {
2468          fwrite($fp, $content);
2469          fclose($fp);
2470          rename($destination . '.tmp', $destination);
2471          @chmod($destination, $CFG->filepermissions);
2472          @unlink($destination . '.tmp'); // Just in case anything fails.
2473      }
2474      ignore_user_abort(false);
2475      if (connection_aborted()) {
2476          die();
2477      }
2478  }
2479  
2480  /**
2481   * Handles the sending of file data to the user's browser, including support for
2482   * byteranges etc.
2483   *
2484   * @category files
2485   * @param string|stored_file $path Path of file on disk (including real filename),
2486   *                                 or actual content of file as string,
2487   *                                 or stored_file object
2488   * @param string $filename Filename to send
2489   * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2490   * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2491   * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
2492   *                           Forced to false when $path is a stored_file object.
2493   * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2494   * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
2495   * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2496   *                        if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2497   *                        you must detect this case when control is returned using connection_aborted. Please not that session is closed
2498   *                        and should not be reopened.
2499   * @param array $options An array of options, currently accepts:
2500   *                       - (string) cacheability: public, or private.
2501   *                       - (string|null) immutable
2502   * @return null script execution stopped unless $dontdie is true
2503   */
2504  function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
2505                     $dontdie=false, array $options = array()) {
2506      global $CFG, $COURSE;
2507  
2508      if ($dontdie) {
2509          ignore_user_abort(true);
2510      }
2511  
2512      if ($lifetime === 'default' or is_null($lifetime)) {
2513          $lifetime = $CFG->filelifetime;
2514      }
2515  
2516      if (is_object($path)) {
2517          $pathisstring = false;
2518      }
2519  
2520      \core\session\manager::write_close(); // Unlock session during file serving.
2521  
2522      // Use given MIME type if specified, otherwise guess it.
2523      if (!$mimetype || $mimetype === 'document/unknown') {
2524          $mimetype = get_mimetype_for_sending($filename);
2525      }
2526  
2527      // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
2528      if (core_useragent::is_ie() || core_useragent::is_edge()) {
2529          $filename = rawurlencode($filename);
2530      }
2531  
2532      if ($forcedownload) {
2533          header('Content-Disposition: attachment; filename="'.$filename.'"');
2534  
2535          // If this file was requested from a form, then mark download as complete.
2536          \core_form\util::form_download_complete();
2537      } else if ($mimetype !== 'application/x-shockwave-flash') {
2538          // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
2539          // as an upload and enforces security that may prevent the file from being loaded.
2540  
2541          header('Content-Disposition: inline; filename="'.$filename.'"');
2542      }
2543  
2544      if ($lifetime > 0) {
2545          $immutable = '';
2546          if (!empty($options['immutable'])) {
2547              $immutable = ', immutable';
2548              // Overwrite lifetime accordingly:
2549              // 90 days only - based on Moodle point release cadence being every 3 months.
2550              $lifetimemin = 60 * 60 * 24 * 90;
2551              $lifetime = max($lifetime, $lifetimemin);
2552          }
2553          $cacheability = ' public,';
2554          if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
2555              // This file must be cache-able by both browsers and proxies.
2556              $cacheability = ' public,';
2557          } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
2558              // This file must be cache-able only by browsers.
2559              $cacheability = ' private,';
2560          } else if (isloggedin() and !isguestuser()) {
2561              // By default, under the conditions above, this file must be cache-able only by browsers.
2562              $cacheability = ' private,';
2563          }
2564          $nobyteserving = false;
2565          header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
2566          header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
2567          header('Pragma: ');
2568  
2569      } else { // Do not cache files in proxies and browsers
2570          $nobyteserving = true;
2571          if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
2572              header('Cache-Control: private, max-age=10, no-transform');
2573              header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2574              header('Pragma: ');
2575          } else { //normal http - prevent caching at all cost
2576              header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
2577              header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
2578              header('Pragma: no-cache');
2579          }
2580      }
2581  
2582      if (empty($filter)) {
2583          // send the contents
2584          if ($pathisstring) {
2585              readstring_accel($path, $mimetype);
2586          } else {
2587              readfile_accel($path, $mimetype, !$dontdie);
2588          }
2589  
2590      } else {
2591          // Try to put the file through filters
2592          if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml') {
2593              $options = new stdClass();
2594              $options->noclean = true;
2595              $options->nocache = true; // temporary workaround for MDL-5136
2596              if (is_object($path)) {
2597                  $text = $path->get_content();
2598              } else if ($pathisstring) {
2599                  $text = $path;
2600              } else {
2601                  $text = implode('', file($path));
2602              }
2603              $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
2604  
2605              readstring_accel($output, $mimetype);
2606  
2607          } else if (($mimetype == 'text/plain') and ($filter == 1)) {
2608              // only filter text if filter all files is selected
2609              $options = new stdClass();
2610              $options->newlines = false;
2611              $options->noclean = true;
2612              if (is_object($path)) {
2613                  $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
2614              } else if ($pathisstring) {
2615                  $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
2616              } else {
2617                  $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
2618              }
2619              $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
2620  
2621              readstring_accel($output, $mimetype);
2622  
2623          } else {
2624              // send the contents
2625              if ($pathisstring) {
2626                  readstring_accel($path, $mimetype);
2627              } else {
2628                  readfile_accel($path, $mimetype, !$dontdie);
2629              }
2630          }
2631      }
2632      if ($dontdie) {
2633          return;
2634      }
2635      die; //no more chars to output!!!
2636  }
2637  
2638  /**
2639   * Handles the sending of file data to the user's browser, including support for
2640   * byteranges etc.
2641   *
2642   * The $options parameter supports the following keys:
2643   *  (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
2644   *  (string|null) filename - overrides the implicit filename
2645   *  (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
2646   *      if this is passed as true, ignore_user_abort is called.  if you don't want your processing to continue on cancel,
2647   *      you must detect this case when control is returned using connection_aborted. Please not that session is closed
2648   *      and should not be reopened
2649   *  (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
2650   *      when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
2651   *      defaults to "public".
2652   *  (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
2653   *      Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
2654   *
2655   * @category files
2656   * @param stored_file $stored_file local file object
2657   * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
2658   * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
2659   * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
2660   * @param array $options additional options affecting the file serving
2661   * @return null script execution stopped unless $options['dontdie'] is true
2662   */
2663  function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
2664      global $CFG, $COURSE;
2665  
2666      if (empty($options['filename'])) {
2667          $filename = null;
2668      } else {
2669          $filename = $options['filename'];
2670      }
2671  
2672      if (empty($options['dontdie'])) {
2673          $dontdie = false;
2674      } else {
2675          $dontdie = true;
2676      }
2677  
2678      if ($lifetime === 'default' or is_null($lifetime)) {
2679          $lifetime = $CFG->filelifetime;
2680      }
2681  
2682      if (!empty($options['preview'])) {
2683          // replace the file with its preview
2684          $fs = get_file_storage();
2685          $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
2686          if (!$preview_file) {
2687              // unable to create a preview of the file, send its default mime icon instead
2688              if ($options['preview'] === 'tinyicon') {
2689                  $size = 24;
2690              } else if ($options['preview'] === 'thumb') {
2691                  $size = 90;
2692              } else {
2693                  $size = 256;
2694              }
2695              $fileicon = file_file_icon($stored_file, $size);
2696              send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
2697          } else {
2698              // preview images have fixed cache lifetime and they ignore forced download
2699              // (they are generated by GD and therefore they are considered reasonably safe).
2700              $stored_file = $preview_file;
2701              $lifetime = DAYSECS;
2702              $filter = 0;
2703              $forcedownload = false;
2704          }
2705      }
2706  
2707      // handle external resource
2708      if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
2709          $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
2710          die;
2711      }
2712  
2713      if (!$stored_file or $stored_file->is_directory()) {
2714          // nothing to serve
2715          if ($dontdie) {
2716              return;
2717          }
2718          die;
2719      }
2720  
2721      $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
2722  
2723      // Use given MIME type if specified.
2724      $mimetype = $stored_file->get_mimetype();
2725  
2726      // Allow cross-origin requests only for Web Services.
2727      // This allow to receive requests done by Web Workers or webapps in different domains.
2728      if (WS_SERVER) {
2729          header('Access-Control-Allow-Origin: *');
2730      }
2731  
2732      send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
2733  }
2734  
2735  /**
2736   * Recursively delete the file or folder with path $location. That is,
2737   * if it is a file delete it. If it is a folder, delete all its content
2738   * then delete it. If $location does not exist to start, that is not
2739   * considered an error.
2740   *
2741   * @param string $location the path to remove.
2742   * @return bool
2743   */
2744  function fulldelete($location) {
2745      if (empty($location)) {
2746          // extra safety against wrong param
2747          return false;
2748      }
2749      if (is_dir($location)) {
2750          if (!$currdir = opendir($location)) {
2751              return false;
2752          }
2753          while (false !== ($file = readdir($currdir))) {
2754              if ($file <> ".." && $file <> ".") {
2755                  $fullfile = $location."/".$file;
2756                  if (is_dir($fullfile)) {
2757                      if (!fulldelete($fullfile)) {
2758                          return false;
2759                      }
2760                  } else {
2761                      if (!unlink($fullfile)) {
2762                          return false;
2763                      }
2764                  }
2765              }
2766          }
2767          closedir($currdir);
2768          if (! rmdir($location)) {
2769              return false;
2770          }
2771  
2772      } else if (file_exists($location)) {
2773          if (!unlink($location)) {
2774              return false;
2775          }
2776      }
2777      return true;
2778  }
2779  
2780  /**
2781   * Send requested byterange of file.
2782   *
2783   * @param resource $handle A file handle
2784   * @param string $mimetype The mimetype for the output
2785   * @param array $ranges An array of ranges to send
2786   * @param string $filesize The size of the content if only one range is used
2787   */
2788  function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
2789      // better turn off any kind of compression and buffering
2790      ini_set('zlib.output_compression', 'Off');
2791  
2792      $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
2793      if ($handle === false) {
2794          die;
2795      }
2796      if (count($ranges) == 1) { //only one range requested
2797          $length = $ranges[0][2] - $ranges[0][1] + 1;
2798          header('HTTP/1.1 206 Partial content');
2799          header('Content-Length: '.$length);
2800          header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
2801          header('Content-Type: '.$mimetype);
2802  
2803          while(@ob_get_level()) {
2804              if (!@ob_end_flush()) {
2805                  break;
2806              }
2807          }
2808  
2809          fseek($handle, $ranges[0][1]);
2810          while (!feof($handle) && $length > 0) {
2811              core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2812              $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2813              echo $buffer;
2814              flush();
2815              $length -= strlen($buffer);
2816          }
2817          fclose($handle);
2818          die;
2819      } else { // multiple ranges requested - not tested much
2820          $totallength = 0;
2821          foreach($ranges as $range) {
2822              $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
2823          }
2824          $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
2825          header('HTTP/1.1 206 Partial content');
2826          header('Content-Length: '.$totallength);
2827          header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2828  
2829          while(@ob_get_level()) {
2830              if (!@ob_end_flush()) {
2831                  break;
2832              }
2833          }
2834  
2835          foreach($ranges as $range) {
2836              $length = $range[2] - $range[1] + 1;
2837              echo $range[0];
2838              fseek($handle, $range[1]);
2839              while (!feof($handle) && $length > 0) {
2840                  core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
2841                  $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2842                  echo $buffer;
2843                  flush();
2844                  $length -= strlen($buffer);
2845              }
2846          }
2847          echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2848          fclose($handle);
2849          die;
2850      }
2851  }
2852  
2853  /**
2854   * Tells whether the filename is executable.
2855   *
2856   * @link http://php.net/manual/en/function.is-executable.php
2857   * @link https://bugs.php.net/bug.php?id=41062
2858   * @param string $filename Path to the file.
2859   * @return bool True if the filename exists and is executable; otherwise, false.
2860   */
2861  function file_is_executable($filename) {
2862      if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2863          if (is_executable($filename)) {
2864              return true;
2865          } else {
2866              $fileext = strrchr($filename, '.');
2867              // If we have an extension we can check if it is listed as executable.
2868              if ($fileext && file_exists($filename) && !is_dir($filename)) {
2869                  $winpathext = strtolower(getenv('PATHEXT'));
2870                  $winpathexts = explode(';', $winpathext);
2871  
2872                  return in_array(strtolower($fileext), $winpathexts);
2873              }
2874  
2875              return false;
2876          }
2877      } else {
2878          return is_executable($filename);
2879      }
2880  }
2881  
2882  /**
2883   * Overwrite an existing file in a draft area.
2884   *
2885   * @param  stored_file $newfile      the new file with the new content and meta-data
2886   * @param  stored_file $existingfile the file that will be overwritten
2887   * @throws moodle_exception
2888   * @since Moodle 3.2
2889   */
2890  function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
2891      if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
2892          throw new coding_exception('The file to overwrite is not in a draft area.');
2893      }
2894  
2895      $fs = get_file_storage();
2896      // Remember original file source field.
2897      $source = @unserialize($existingfile->get_source());
2898      // Remember the original sortorder.
2899      $sortorder = $existingfile->get_sortorder();
2900      if ($newfile->is_external_file()) {
2901          // New file is a reference. Check that existing file does not have any other files referencing to it
2902          if (isset($source->original) && $fs->search_references_count($source->original)) {
2903              throw new moodle_exception('errordoublereference', 'repository');
2904          }
2905      }
2906  
2907      // Delete existing file to release filename.
2908      $newfilerecord = array(
2909          'contextid' => $existingfile->get_contextid(),
2910          'component' => 'user',
2911          'filearea' => 'draft',
2912          'itemid' => $existingfile->get_itemid(),
2913          'timemodified' => time()
2914      );
2915      $existingfile->delete();
2916  
2917      // Create new file.
2918      $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
2919      // Preserve original file location (stored in source field) for handling references.
2920      if (isset($source->original)) {
2921          if (!($newfilesource = @unserialize($newfile->get_source()))) {
2922              $newfilesource = new stdClass();
2923          }
2924          $newfilesource->original = $source->original;
2925          $newfile->set_source(serialize($newfilesource));
2926      }
2927      $newfile->set_sortorder($sortorder);
2928  }
2929  
2930  /**
2931   * Add files from a draft area into a final area.
2932   *
2933   * Most of the time you do not want to use this. It is intended to be used
2934   * by asynchronous services which cannot direcly manipulate a final
2935   * area through a draft area. Instead they add files to a new draft
2936   * area and merge that new draft into the final area when ready.
2937   *
2938   * @param int $draftitemid the id of the draft area to use.
2939   * @param int $contextid this parameter and the next two identify the file area to save to.
2940   * @param string $component component name
2941   * @param string $filearea indentifies the file area
2942   * @param int $itemid identifies the item id or false for all items in the file area
2943   * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
2944   * @see file_save_draft_area_files
2945   * @since Moodle 3.2
2946   */
2947  function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
2948                                                          array $options = null) {
2949      // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
2950      $finaldraftid = 0;
2951      file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2952      file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
2953      file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
2954  }
2955  
2956  /**
2957   * Merge files from two draftarea areas.
2958   *
2959   * This does not handle conflict resolution, files in the destination area which appear
2960   * to be more recent will be kept disregarding the intended ones.
2961   *
2962   * @param int $getfromdraftid the id of the draft area where are the files to merge.
2963   * @param int $mergeintodraftid the id of the draft area where new files will be merged.
2964   * @throws coding_exception
2965   * @since Moodle 3.2
2966   */
2967  function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
2968      global $USER;
2969  
2970      $fs = get_file_storage();
2971      $contextid = context_user::instance($USER->id)->id;
2972  
2973      if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
2974          throw new coding_exception('Nothing to merge or area does not belong to current user');
2975      }
2976  
2977      $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
2978  
2979      // Get hashes of the files to merge.
2980      $newhashes = array();
2981      foreach ($filestomerge as $filetomerge) {
2982          $filepath = $filetomerge->get_filepath();
2983          $filename = $filetomerge->get_filename();
2984  
2985          $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
2986          $newhashes[$newhash] = $filetomerge;
2987      }
2988  
2989      // Calculate wich files must be added.
2990      foreach ($currentfiles as $file) {
2991          $filehash = $file->get_pathnamehash();
2992          // One file to be merged already exists.
2993          if (isset($newhashes[$filehash])) {
2994              $updatedfile = $newhashes[$filehash];
2995  
2996              // Avoid race conditions.
2997              if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
2998                  // The existing file is more recent, do not copy the suposedly "new" one.
2999                  unset($newhashes[$filehash]);
3000                  continue;
3001              }
3002              // Update existing file (not only content, meta-data too).
3003              file_overwrite_existing_draftfile($updatedfile, $file);
3004              unset($newhashes[$filehash]);
3005          }
3006      }
3007  
3008      foreach ($newhashes as $newfile) {
3009          $newfilerecord = array(
3010              'contextid' => $contextid,
3011              'component' => 'user',
3012              'filearea' => 'draft',
3013              'itemid' => $mergeintodraftid,
3014              'timemodified' => time()
3015          );
3016  
3017          $fs->create_file_from_storedfile($newfilerecord, $newfile);
3018      }
3019  }
3020  
3021  /**
3022   * RESTful cURL class
3023   *
3024   * This is a wrapper class for curl, it is quite easy to use:
3025   * <code>
3026   * $c = new curl;
3027   * // enable cache
3028   * $c = new curl(array('cache'=>true));
3029   * // enable cookie
3030   * $c = new curl(array('cookie'=>true));
3031   * // enable proxy
3032   * $c = new curl(array('proxy'=>true));
3033   *
3034   * // HTTP GET Method
3035   * $html = $c->get('http://example.com');
3036   * // HTTP POST Method
3037   * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
3038   * // HTTP PUT Method
3039   * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
3040   * </code>
3041   *
3042   * @package   core_files
3043   * @category files
3044   * @copyright Dongsheng Cai <dongsheng@moodle.com>
3045   * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
3046   */
3047  class curl {
3048      /** @var bool Caches http request contents */
3049      public  $cache    = false;
3050      /** @var bool Uses proxy, null means automatic based on URL */
3051      public  $proxy    = null;
3052      /** @var string library version */
3053      public  $version  = '0.4 dev';
3054      /** @var array http's response */
3055      public  $response = array();
3056      /** @var array Raw response headers, needed for BC in download_file_content(). */
3057      public $rawresponse = array();
3058      /** @var array http header */
3059      public  $header   = array();
3060      /** @var string cURL information */
3061      public  $info;
3062      /** @var string error */
3063      public  $error;
3064      /** @var int error code */
3065      public  $errno;
3066      /** @var bool Perform redirects at PHP level instead of relying on native cURL functionality. Always true now. */
3067      public $emulateredirects = null;
3068  
3069      /** @var array cURL options */
3070      private $options;
3071  
3072      /** @var string Proxy host */
3073      private $proxy_host = '';
3074      /** @var string Proxy auth */
3075      private $proxy_auth = '';
3076      /** @var string Proxy type */
3077      private $proxy_type = '';
3078      /** @var bool Debug mode on */
3079      private $debug    = false;
3080      /** @var bool|string Path to cookie file */
3081      private $cookie   = false;
3082      /** @var bool tracks multiple headers in response - redirect detection */
3083      private $responsefinished = false;
3084      /** @var security helper class, responsible for checking host/ports against blacklist/whitelist entries.*/
3085      private $securityhelper;
3086      /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
3087      private $ignoresecurity;
3088      /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
3089      private static $mockresponses = [];
3090  
3091      /**
3092       * Curl constructor.
3093       *
3094       * Allowed settings are:
3095       *  proxy: (bool) use proxy server, null means autodetect non-local from url
3096       *  debug: (bool) use debug output
3097       *  cookie: (string) path to cookie file, false if none
3098       *  cache: (bool) use cache
3099       *  module_cache: (string) type of cache
3100       *  securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
3101       *  ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
3102       *
3103       * @param array $settings
3104       */
3105      public function __construct($settings = array()) {
3106          global $CFG;
3107          if (!function_exists('curl_init')) {
3108              $this->error = 'cURL module must be enabled!';
3109              trigger_error($this->error, E_USER_ERROR);
3110              return false;
3111          }
3112  
3113          // All settings of this class should be init here.
3114          $this->resetopt();
3115          if (!empty($settings['debug'])) {
3116              $this->debug = true;
3117          }
3118          if (!empty($settings['cookie'])) {
3119              if($settings['cookie'] === true) {
3120                  $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
3121              } else {
3122                  $this->cookie = $settings['cookie'];
3123              }
3124          }
3125          if (!empty($settings['cache'])) {
3126              if (class_exists('curl_cache')) {
3127                  if (!empty($settings['module_cache'])) {
3128                      $this->cache = new curl_cache($settings['module_cache']);
3129                  } else {
3130                      $this->cache = new curl_cache('misc');
3131                  }
3132              }
3133          }
3134          if (!empty($CFG->proxyhost)) {
3135              if (empty($CFG->proxyport)) {
3136                  $this->proxy_host = $CFG->proxyhost;
3137              } else {
3138                  $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
3139              }
3140              if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
3141                  $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
3142                  $this->setopt(array(
3143                              'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
3144                              'proxyuserpwd'=>$this->proxy_auth));
3145              }
3146              if (!empty($CFG->proxytype)) {
3147                  if ($CFG->proxytype == 'SOCKS5') {
3148                      $this->proxy_type = CURLPROXY_SOCKS5;
3149                  } else {
3150                      $this->proxy_type = CURLPROXY_HTTP;
3151                      $this->setopt(array('httpproxytunnel'=>false));
3152                  }
3153                  $this->setopt(array('proxytype'=>$this->proxy_type));
3154              }
3155  
3156              if (isset($settings['proxy'])) {
3157                  $this->proxy = $settings['proxy'];
3158              }
3159          } else {
3160              $this->proxy = false;
3161          }
3162  
3163          // All redirects are performed at PHP level now and each one is checked against blocked URLs rules. We do not
3164          // want to let cURL naively follow the redirect chain and visit every URL for security reasons. Even when the
3165          // caller explicitly wants to ignore the security checks, we would need to fall back to the original
3166          // implementation and use emulated redirects if open_basedir is in effect to avoid the PHP warning
3167          // "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir". So it is better to simply
3168          // ignore this property and always handle redirects at this PHP wrapper level and not inside the native cURL.
3169          $this->emulateredirects = true;
3170  
3171          // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
3172          if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
3173              $this->set_security($settings['securityhelper']);
3174          } else {
3175              $this->set_security(new \core\files\curl_security_helper());
3176          }
3177          $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
3178      }
3179  
3180      /**
3181       * Resets the CURL options that have already been set
3182       */
3183      public function resetopt() {
3184          $this->options = array();
3185          $this->options['CURLOPT_USERAGENT']         = \core_useragent::get_moodlebot_useragent();
3186          // True to include the header in the output
3187          $this->options['CURLOPT_HEADER']            = 0;
3188          // True to Exclude the body from the output
3189          $this->options['CURLOPT_NOBODY']            = 0;
3190          // Redirect ny default.
3191          $this->options['CURLOPT_FOLLOWLOCATION']    = 1;
3192          $this->options['CURLOPT_MAXREDIRS']         = 10;
3193          $this->options['CURLOPT_ENCODING']          = '';
3194          // TRUE to return the transfer as a string of the return
3195          // value of curl_exec() instead of outputting it out directly.
3196          $this->options['CURLOPT_RETURNTRANSFER']    = 1;
3197          $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
3198          $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
3199          $this->options['CURLOPT_CONNECTTIMEOUT']    = 30;
3200  
3201          if ($cacert = self::get_cacert()) {
3202              $this->options['CURLOPT_CAINFO'] = $cacert;
3203          }
3204      }
3205  
3206      /**
3207       * Get the location of ca certificates.
3208       * @return string absolute file path or empty if default used
3209       */
3210      public static function get_cacert() {
3211          global $CFG;
3212  
3213          // Bundle in dataroot always wins.
3214          if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
3215              return realpath("$CFG->dataroot/moodleorgca.crt");
3216          }
3217  
3218          // Next comes the default from php.ini
3219          $cacert = ini_get('curl.cainfo');
3220          if (!empty($cacert) and is_readable($cacert)) {
3221              return realpath($cacert);
3222          }
3223  
3224          // Windows PHP does not have any certs, we need to use something.
3225          if ($CFG->ostype === 'WINDOWS') {
3226              if (is_readable("$CFG->libdir/cacert.pem")) {
3227                  return realpath("$CFG->libdir/cacert.pem");
3228              }
3229          }
3230  
3231          // Use default, this should work fine on all properly configured *nix systems.
3232          return null;
3233      }
3234  
3235      /**
3236       * Reset Cookie
3237       */
3238      public function resetcookie() {
3239          if (!empty($this->cookie)) {
3240              if (is_file($this->cookie)) {
3241                  $fp = fopen($this->cookie, 'w');
3242                  if (!empty($fp)) {
3243                      fwrite($fp, '');
3244                      fclose($fp);
3245                  }
3246              }
3247          }
3248      }
3249  
3250      /**
3251       * Set curl options.
3252       *
3253       * Do not use the curl constants to define the options, pass a string
3254       * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
3255       * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
3256       *
3257       * @param array $options If array is null, this function will reset the options to default value.
3258       * @return void
3259       * @throws coding_exception If an option uses constant value instead of option name.
3260       */
3261      public function setopt($options = array()) {
3262          if (is_array($options)) {
3263              foreach ($options as $name => $val) {
3264                  if (!is_string($name)) {
3265                      throw new coding_exception('Curl options should be defined using strings, not constant values.');
3266                  }
3267                  if (stripos($name, 'CURLOPT_') === false) {
3268                      // Only prefix with CURLOPT_ if the option doesn't contain CURLINFO_,
3269                      // which is a valid prefix for at least one option CURLINFO_HEADER_OUT.
3270                      if (stripos($name, 'CURLINFO_') === false) {
3271                          $name = strtoupper('CURLOPT_'.$name);
3272                      }
3273                  } else {
3274                      $name = strtoupper($name);
3275                  }
3276                  $this->options[$name] = $val;
3277              }
3278          }
3279      }
3280  
3281      /**
3282       * Reset http method
3283       */
3284      public function cleanopt() {
3285          unset($this->options['CURLOPT_HTTPGET']);
3286          unset($this->options['CURLOPT_POST']);
3287          unset($this->options['CURLOPT_POSTFIELDS']);
3288          unset($this->options['CURLOPT_PUT']);
3289          unset($this->options['CURLOPT_INFILE']);
3290          unset($this->options['CURLOPT_INFILESIZE']);
3291          unset($this->options['CURLOPT_CUSTOMREQUEST']);
3292          unset($this->options['CURLOPT_FILE']);
3293      }
3294  
3295      /**
3296       * Resets the HTTP Request headers (to prepare for the new request)
3297       */
3298      public function resetHeader() {
3299          $this->header = array();
3300      }
3301  
3302      /**
3303       * Set HTTP Request Header
3304       *
3305       * @param array $header
3306       */
3307      public function setHeader($header) {
3308          if (is_array($header)) {
3309              foreach ($header as $v) {
3310                  $this->setHeader($v);
3311              }
3312          } else {
3313              // Remove newlines, they are not allowed in headers.
3314              $newvalue = preg_replace('/[\r\n]/', '', $header);
3315              if (!in_array($newvalue, $this->header)) {
3316                  $this->header[] = $newvalue;
3317              }
3318          }
3319      }
3320  
3321      /**
3322       * Get HTTP Response Headers
3323       * @return array of arrays
3324       */
3325      public function getResponse() {
3326          return $this->response;
3327      }
3328  
3329      /**
3330       * Get raw HTTP Response Headers
3331       * @return array of strings
3332       */
3333      public function get_raw_response() {
3334          return $this->rawresponse;
3335      }
3336  
3337      /**
3338       * private callback function
3339       * Formatting HTTP Response Header
3340       *
3341       * We only keep the last headers returned. For example during a redirect the
3342       * redirect headers will not appear in {@link self::getResponse()}, if you need
3343       * to use those headers, refer to {@link self::get_raw_response()}.
3344       *
3345       * @param resource $ch Apparently not used
3346       * @param string $header
3347       * @return int The strlen of the header
3348       */
3349      private function formatHeader($ch, $header) {
3350          $this->rawresponse[] = $header;
3351  
3352          if (trim($header, "\r\n") === '') {
3353              // This must be the last header.
3354              $this->responsefinished = true;
3355          }
3356  
3357          if (strlen($header) > 2) {
3358              if ($this->responsefinished) {
3359                  // We still have headers after the supposedly last header, we must be
3360                  // in a redirect so let's empty the response to keep the last headers.
3361                  $this->responsefinished = false;
3362                  $this->response = array();
3363              }
3364              $parts = explode(" ", rtrim($header, "\r\n"), 2);
3365              $key = rtrim($parts[0], ':');
3366              $value = isset($parts[1]) ? $parts[1] : null;
3367              if (!empty($this->response[$key])) {
3368                  if (is_array($this->response[$key])) {
3369                      $this->response[$key][] = $value;
3370                  } else {
3371                      $tmp = $this->response[$key];
3372                      $this->response[$key] = array();
3373                      $this->response[$key][] = $tmp;
3374                      $this->response[$key][] = $value;
3375  
3376                  }
3377              } else {
3378                  $this->response[$key] = $value;
3379              }
3380          }
3381          return strlen($header);
3382      }
3383  
3384      /**
3385       * Set options for individual curl instance
3386       *
3387       * @param resource $curl A curl handle
3388       * @param array $options
3389       * @return resource The curl handle
3390       */
3391      private function apply_opt($curl, $options) {
3392          // Clean up
3393          $this->cleanopt();
3394          // set cookie
3395          if (!empty($this->cookie) || !empty($options['cookie'])) {
3396              $this->setopt(array('cookiejar'=>$this->cookie,
3397                              'cookiefile'=>$this->cookie
3398                               ));
3399          }
3400  
3401          // Bypass proxy if required.
3402          if ($this->proxy === null) {
3403              if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
3404                  $proxy = false;
3405              } else {
3406                  $proxy = true;
3407              }
3408          } else {
3409              $proxy = (bool)$this->proxy;
3410          }
3411  
3412          // Set proxy.
3413          if ($proxy) {
3414              $options['CURLOPT_PROXY'] = $this->proxy_host;
3415          } else {
3416              unset($this->options['CURLOPT_PROXY']);
3417          }
3418  
3419          $this->setopt($options);
3420  
3421          // Reset before set options.
3422          curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
3423  
3424          // Setting the User-Agent based on options provided.
3425          $useragent = '';
3426  
3427          if (!empty($options['CURLOPT_USERAGENT'])) {
3428              $useragent = $options['CURLOPT_USERAGENT'];
3429          } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
3430              $useragent = $this->options['CURLOPT_USERAGENT'];
3431          } else {
3432              $useragent = \core_useragent::get_moodlebot_useragent();
3433          }
3434  
3435          // Set headers.
3436          if (empty($this->header)) {
3437              $this->setHeader(array(
3438                  'User-Agent: ' . $useragent,
3439                  'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
3440                  'Connection: keep-alive'
3441                  ));
3442          } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
3443              // Remove old User-Agent if one existed.
3444              // We have to partial search since we don't know what the original User-Agent is.
3445              if ($match = preg_grep('/User-Agent.*/', $this->header)) {
3446                  $key = array_keys($match)[0];
3447                  unset($this->header[$key]);
3448              }
3449              $this->setHeader(array('User-Agent: ' . $useragent));
3450          }
3451          curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
3452  
3453          if ($this->debug) {
3454              echo '<h1>Options</h1>';
3455              var_dump($this->options);
3456              echo '<h1>Header</h1>';
3457              var_dump($this->header);
3458          }
3459  
3460          // Do not allow infinite redirects.
3461          if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
3462              $this->options['CURLOPT_MAXREDIRS'] = 0;
3463          } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
3464              $this->options['CURLOPT_MAXREDIRS'] = 100;
3465          } else {
3466              $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
3467          }
3468  
3469          // Make sure we always know if redirects expected.
3470          if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
3471              $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
3472          }
3473  
3474          // Limit the protocols to HTTP and HTTPS.
3475          if (defined('CURLOPT_PROTOCOLS')) {
3476              $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3477              $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
3478          }
3479  
3480          // Set options.
3481          foreach($this->options as $name => $val) {
3482              if ($name === 'CURLOPT_FOLLOWLOCATION') {
3483                  // All the redirects are emulated at PHP level.
3484                  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
3485                  continue;
3486              }
3487              $name = constant($name);
3488              curl_setopt($curl, $name, $val);
3489          }
3490  
3491          return $curl;
3492      }
3493  
3494      /**
3495       * Download multiple files in parallel
3496       *
3497       * Calls {@link multi()} with specific download headers
3498       *
3499       * <code>
3500       * $c = new curl();
3501       * $file1 = fopen('a', 'wb');
3502       * $file2 = fopen('b', 'wb');
3503       * $c->download(array(
3504       *     array('url'=>'http://localhost/', 'file'=>$file1),
3505       *     array('url'=>'http://localhost/20/', 'file'=>$file2)
3506       * ));
3507       * fclose($file1);
3508       * fclose($file2);
3509       * </code>
3510       *
3511       * or
3512       *
3513       * <code>
3514       * $c = new curl();
3515       * $c->download(array(
3516       *              array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
3517       *              array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
3518       *              ));
3519       * </code>
3520       *
3521       * @param array $requests An array of files to request {
3522       *                  url => url to download the file [required]
3523       *                  file => file handler, or
3524       *                  filepath => file path
3525       * }
3526       * If 'file' and 'filepath' parameters are both specified in one request, the
3527       * open file handle in the 'file' parameter will take precedence and 'filepath'
3528       * will be ignored.
3529       *
3530       * @param array $options An array of options to set
3531       * @return array An array of results
3532       */
3533      public function download($requests, $options = array()) {
3534          $options['RETURNTRANSFER'] = false;
3535          return $this->multi($requests, $options);
3536      }
3537  
3538      /**
3539       * Returns the current curl security helper.
3540       *
3541       * @return \core\files\curl_security_helper instance.
3542       */
3543      public function get_security() {
3544          return $this->securityhelper;
3545      }
3546  
3547      /**
3548       * Sets the curl security helper.
3549       *
3550       * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
3551       * @return bool true if the security helper could be set, false otherwise.
3552       */
3553      public function set_security($securityobject) {
3554          if ($securityobject instanceof \core\files\curl_security_helper) {
3555              $this->securityhelper = $securityobject;
3556              return true;
3557          }
3558          return false;
3559      }
3560  
3561      /**
3562       * Multi HTTP Requests
3563       * This function could run multi-requests in parallel.
3564       *
3565       * @param array $requests An array of files to request
3566       * @param array $options An array of options to set
3567       * @return array An array of results
3568       */
3569      protected function multi($requests, $options = array()) {
3570          $count   = count($requests);
3571          $handles = array();
3572          $results = array();
3573          $main    = curl_multi_init();
3574          for ($i = 0; $i < $count; $i++) {
3575              if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
3576                  // open file
3577                  $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
3578                  $requests[$i]['auto-handle'] = true;
3579              }
3580              foreach($requests[$i] as $n=>$v) {
3581                  $options[$n] = $v;
3582              }
3583              $handles[$i] = curl_init($requests[$i]['url']);
3584              $this->apply_opt($handles[$i], $options);
3585              curl_multi_add_handle($main, $handles[$i]);
3586          }
3587          $running = 0;
3588          do {
3589              curl_multi_exec($main, $running);
3590          } while($running > 0);
3591          for ($i = 0; $i < $count; $i++) {
3592              if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
3593                  $results[] = true;
3594              } else {
3595                  $results[] = curl_multi_getcontent($handles[$i]);
3596              }
3597              curl_multi_remove_handle($main, $handles[$i]);
3598          }
3599          curl_multi_close($main);
3600  
3601          for ($i = 0; $i < $count; $i++) {
3602              if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
3603                  // close file handler if file is opened in this function
3604                  fclose($requests[$i]['file']);
3605              }
3606          }
3607          return $results;
3608      }
3609  
3610      /**
3611       * Helper function to reset the request state vars.
3612       *
3613       * @return void.
3614       */
3615      protected function reset_request_state_vars() {
3616          $this->info             = array();
3617          $this->error            = '';
3618          $this->errno            = 0;
3619          $this->response         = array();
3620          $this->rawresponse      = array();
3621          $this->responsefinished = false;
3622      }
3623  
3624      /**
3625       * For use only in unit tests - we can pre-set the next curl response.
3626       * This is useful for unit testing APIs that call external systems.
3627       * @param string $response
3628       */
3629      public static function mock_response($response) {
3630          if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3631              array_push(self::$mockresponses, $response);
3632          } else {
3633              throw new coding_exception('mock_response function is only available for unit tests.');
3634          }
3635      }
3636  
3637      /**
3638       * Single HTTP Request
3639       *
3640       * @param string $url The URL to request
3641       * @param array $options
3642       * @return bool
3643       */
3644      protected function request($url, $options = array()) {
3645          // Reset here so that the data is valid when result returned from cache, or if we return due to a blacklist hit.
3646          $this->reset_request_state_vars();
3647  
3648          if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
3649              if ($mockresponse = array_pop(self::$mockresponses)) {
3650                  $this->info = [ 'http_code' => 200 ];
3651                  return $mockresponse;
3652              }
3653          }
3654  
3655          if (empty($this->emulateredirects)) {
3656              // Just in case someone had tried to explicitly disable emulated redirects in legacy code.
3657              debugging('Attempting to disable emulated redirects has no effect any more!', DEBUG_DEVELOPER);
3658          }
3659  
3660          // If curl security is enabled, check the URL against the list of blocked URLs before calling the first curl_exec.
3661          if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($url)) {
3662              $this->error = $this->securityhelper->get_blocked_url_string();
3663              return $this->error;
3664          }
3665  
3666          // Set the URL as a curl option.
3667          $this->setopt(array('CURLOPT_URL' => $url));
3668  
3669          // Create curl instance.
3670          $curl = curl_init();
3671  
3672          $this->apply_opt($curl, $options);
3673          if ($this->cache && $ret = $this->cache->get($this->options)) {
3674              return $ret;
3675          }
3676  
3677          $ret = curl_exec($curl);
3678          $this->info  = curl_getinfo($curl);
3679          $this->error = curl_error($curl);
3680          $this->errno = curl_errno($curl);
3681          // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
3682  
3683          if (intval($this->info['redirect_count']) > 0) {
3684              // For security reasons we do not allow the cURL handle to follow redirects on its own.
3685              // See setting CURLOPT_FOLLOWLOCATION in {@see self::apply_opt()} method.
3686              throw new coding_exception('Internal cURL handle should never follow redirects on its own!',
3687                  'Reported number of redirects: ' . $this->info['redirect_count']);
3688          }
3689  
3690          if ($this->options['CURLOPT_FOLLOWLOCATION'] && $this->info['http_code'] != 200) {
3691              $redirects = 0;
3692  
3693              while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
3694  
3695                  if ($this->info['http_code'] == 301) {
3696                      // Moved Permanently - repeat the same request on new URL.
3697  
3698                  } else if ($this->info['http_code'] == 302) {
3699                      // Found - the standard redirect - repeat the same request on new URL.
3700  
3701                  } else if ($this->info['http_code'] == 303) {
3702                      // 303 See Other - repeat only if GET, do not bother with POSTs.
3703                      if (empty($this->options['CURLOPT_HTTPGET'])) {
3704                          break;
3705                      }
3706  
3707                  } else if ($this->info['http_code'] == 307) {
3708                      // Temporary Redirect - must repeat using the same request type.
3709  
3710                  } else if ($this->info['http_code'] == 308) {
3711                      // Permanent Redirect - must repeat using the same request type.
3712  
3713                  } else {
3714                      // Some other http code means do not retry!
3715                      break;
3716                  }
3717  
3718                  $redirects++;
3719  
3720                  $redirecturl = null;
3721                  if (isset($this->info['redirect_url'])) {
3722                      if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
3723                          $redirecturl = $this->info['redirect_url'];
3724                      } else {
3725                          // Emulate CURLOPT_REDIR_PROTOCOLS behaviour which we have set to (CURLPROTO_HTTP | CURLPROTO_HTTPS) only.
3726                          $this->errno = CURLE_UNSUPPORTED_PROTOCOL;
3727                          $this->error = 'Redirect to a URL with unsuported protocol: ' . $this->info['redirect_url'];
3728                          curl_close($curl);
3729                          return $this->error;
3730                      }
3731                  }
3732                  if (!$redirecturl) {
3733                      foreach ($this->response as $k => $v) {
3734                          if (strtolower($k) === 'location') {
3735                              $redirecturl = $v;
3736                              break;
3737                          }
3738                      }
3739                      if (preg_match('|^https?://|i', $redirecturl)) {
3740                          // Great, this is the correct location format!
3741  
3742                      } else if ($redirecturl) {
3743                          $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
3744                          if (strpos($redirecturl, '/') === 0) {
3745                              // Relative to server root - just guess.
3746                              $pos = strpos('/', $current, 8);
3747                              if ($pos === false) {
3748                                  $redirecturl = $current.$redirecturl;
3749                              } else {
3750                                  $redirecturl = substr($current, 0, $pos).$redirecturl;
3751                              }
3752                          } else {
3753                              // Relative to current script.
3754                              $redirecturl = dirname($current).'/'.$redirecturl;
3755                          }
3756                      }
3757                  }
3758  
3759                  if (!$this->ignoresecurity && $this->securityhelper->url_is_blocked($redirecturl)) {
3760                      $this->reset_request_state_vars();
3761                      $this->error = $this->securityhelper->get_blocked_url_string();
3762                      curl_close($curl);
3763                      return $this->error;
3764                  }
3765  
3766                  // If the response body is written to a seekable stream resource, reset the stream pointer to avoid
3767                  // appending multiple response bodies to the same resource.
3768                  if (!empty($this->options['CURLOPT_FILE'])) {
3769                      $streammetadata = stream_get_meta_data($this->options['CURLOPT_FILE']);
3770                      if ($streammetadata['seekable']) {
3771                          ftruncate($this->options['CURLOPT_FILE'], 0);
3772                          rewind($this->options['CURLOPT_FILE']);
3773                      }
3774                  }
3775  
3776                  curl_setopt($curl, CURLOPT_URL, $redirecturl);
3777                  $ret = curl_exec($curl);
3778  
3779                  $this->info  = curl_getinfo($curl);
3780                  $this->error = curl_error($curl);
3781                  $this->errno = curl_errno($curl);
3782  
3783                  $this->info['redirect_count'] = $redirects;
3784  
3785                  if ($this->info['http_code'] === 200) {
3786                      // Finally this is what we wanted.
3787                      break;
3788                  }
3789                  if ($this->errno != CURLE_OK) {
3790                      // Something wrong is going on.
3791                      break;
3792                  }
3793              }
3794              if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
3795                  $this->errno = CURLE_TOO_MANY_REDIRECTS;
3796                  $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
3797              }
3798          }
3799  
3800          if ($this->cache) {
3801              $this->cache->set($this->options, $ret);
3802          }
3803  
3804          if ($this->debug) {
3805              echo '<h1>Return Data</h1>';
3806              var_dump($ret);
3807              echo '<h1>Info</h1>';
3808              var_dump($this->info);
3809              echo '<h1>Error</h1>';
3810              var_dump($this->error);
3811          }
3812  
3813          curl_close($curl);
3814  
3815          if (empty($this->error)) {
3816              return $ret;
3817          } else {
3818              return $this->error;
3819              // exception is not ajax friendly
3820              //throw new moodle_exception($this->error, 'curl');
3821          }
3822      }
3823  
3824      /**
3825       * HTTP HEAD method
3826       *
3827       * @see request()
3828       *
3829       * @param string $url
3830       * @param array $options
3831       * @return bool
3832       */
3833      public function head($url, $options = array()) {
3834          $options['CURLOPT_HTTPGET'] = 0;
3835          $options['CURLOPT_HEADER']  = 1;
3836          $options['CURLOPT_NOBODY']  = 1;
3837          return $this->request($url, $options);
3838      }
3839  
3840      /**
3841       * HTTP PATCH method
3842       *
3843       * @param string $url
3844       * @param array|string $params
3845       * @param array $options
3846       * @return bool
3847       */
3848      public function patch($url, $params = '', $options = array()) {
3849          $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
3850          if (is_array($params)) {
3851              $this->_tmp_file_post_params = array();
3852              foreach ($params as $key => $value) {
3853                  if ($value instanceof stored_file) {
3854                      $value->add_to_curl_request($this, $key);
3855                  } else {
3856                      $this->_tmp_file_post_params[$key] = $value;
3857                  }
3858              }
3859              $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3860              unset($this->_tmp_file_post_params);
3861          } else {
3862              // The variable $params is the raw post data.
3863              $options['CURLOPT_POSTFIELDS'] = $params;
3864          }
3865          return $this->request($url, $options);
3866      }
3867  
3868      /**
3869       * HTTP POST method
3870       *
3871       * @param string $url
3872       * @param array|string $params
3873       * @param array $options
3874       * @return bool
3875       */
3876      public function post($url, $params = '', $options = array()) {
3877          $options['CURLOPT_POST']       = 1;
3878          if (is_array($params)) {
3879              $this->_tmp_file_post_params = array();
3880              foreach ($params as $key => $value) {
3881                  if ($value instanceof stored_file) {
3882                      $value->add_to_curl_request($this, $key);
3883                  } else {
3884                      $this->_tmp_file_post_params[$key] = $value;
3885                  }
3886              }
3887              $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
3888              unset($this->_tmp_file_post_params);
3889          } else {
3890              // $params is the raw post data
3891              $options['CURLOPT_POSTFIELDS'] = $params;
3892          }
3893          return $this->request($url, $options);
3894      }
3895  
3896      /**
3897       * HTTP GET method
3898       *
3899       * @param string $url
3900       * @param array $params
3901       * @param array $options
3902       * @return bool
3903       */
3904      public function get($url, $params = array(), $options = array()) {
3905          $options['CURLOPT_HTTPGET'] = 1;
3906  
3907          if (!empty($params)) {
3908              $url .= (stripos($url, '?') !== false) ? '&' : '?';
3909              $url .= http_build_query($params, '', '&');
3910          }
3911          return $this->request($url, $options);
3912      }
3913  
3914      /**
3915       * Downloads one file and writes it to the specified file handler
3916       *
3917       * <code>
3918       * $c = new curl();
3919       * $file = fopen('savepath', 'w');
3920       * $result = $c->download_one('http://localhost/', null,
3921       *   array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3922       * fclose($file);
3923       * $download_info = $c->get_info();
3924       * if ($result === true) {
3925       *   // file downloaded successfully
3926       * } else {
3927       *   $error_text = $result;
3928       *   $error_code = $c->get_errno();
3929       * }
3930       * </code>
3931       *
3932       * <code>
3933       * $c = new curl();
3934       * $result = $c->download_one('http://localhost/', null,
3935       *   array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
3936       * // ... see above, no need to close handle and remove file if unsuccessful
3937       * </code>
3938       *
3939       * @param string $url
3940       * @param array|null $params key-value pairs to be added to $url as query string
3941       * @param array $options request options. Must include either 'file' or 'filepath'
3942       * @return bool|string true on success or error string on failure
3943       */
3944      public function download_one($url, $params, $options = array()) {
3945          $options['CURLOPT_HTTPGET'] = 1;
3946          if (!empty($params)) {
3947              $url .= (stripos($url, '?') !== false) ? '&' : '?';
3948              $url .= http_build_query($params, '', '&');
3949          }
3950          if (!empty($options['filepath']) && empty($options['file'])) {
3951              // open file
3952              if (!($options['file'] = fopen($options['filepath'], 'w'))) {
3953                  $this->errno = 100;
3954                  return get_string('cannotwritefile', 'error', $options['filepath']);
3955              }
3956              $filepath = $options['filepath'];
3957          }
3958          unset($options['filepath']);
3959          $result = $this->request($url, $options);
3960          if (isset($filepath)) {
3961              fclose($options['file']);
3962              if ($result !== true) {
3963                  unlink($filepath);
3964              }
3965          }
3966          return $result;
3967      }
3968  
3969      /**
3970       * HTTP PUT method
3971       *
3972       * @param string $url
3973       * @param array $params
3974       * @param array $options
3975       * @return bool
3976       */
3977      public function put($url, $params = array(), $options = array()) {
3978          $file = '';
3979          $fp = false;
3980          if (isset($params['file'])) {
3981              $file = $params['file'];
3982              if (is_file($file)) {
3983                  $fp   = fopen($file, 'r');
3984                  $size = filesize($file);
3985                  $options['CURLOPT_PUT']        = 1;
3986                  $options['CURLOPT_INFILESIZE'] = $size;
3987                  $options['CURLOPT_INFILE']     = $fp;
3988              } else {
3989                  return null;
3990              }
3991              if (!isset($this->options['CURLOPT_USERPWD'])) {
3992                  $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
3993              }
3994          } else {
3995              $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
3996              $options['CURLOPT_POSTFIELDS'] = $params;
3997          }
3998  
3999          $ret = $this->request($url, $options);
4000          if ($fp !== false) {
4001              fclose($fp);
4002          }
4003          return $ret;
4004      }
4005  
4006      /**
4007       * HTTP DELETE method
4008       *
4009       * @param string $url
4010       * @param array $param
4011       * @param array $options
4012       * @return bool
4013       */
4014      public function delete($url, $param = array(), $options = array()) {
4015          $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
4016          if (!isset($options['CURLOPT_USERPWD'])) {
4017              $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
4018          }
4019          $ret = $this->request($url, $options);
4020          return $ret;
4021      }
4022  
4023      /**
4024       * HTTP TRACE method
4025       *
4026       * @param string $url
4027       * @param array $options
4028       * @return bool
4029       */
4030      public function trace($url, $options = array()) {
4031          $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
4032          $ret = $this->request($url, $options);
4033          return $ret;
4034      }
4035  
4036      /**
4037       * HTTP OPTIONS method
4038       *
4039       * @param string $url
4040       * @param array $options
4041       * @return bool
4042       */
4043      public function options($url, $options = array()) {
4044          $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
4045          $ret = $this->request($url, $options);
4046          return $ret;
4047      }
4048  
4049      /**
4050       * Get curl information
4051       *
4052       * @return string
4053       */
4054      public function get_info() {
4055          return $this->info;
4056      }
4057  
4058      /**
4059       * Get curl error code
4060       *
4061       * @return int
4062       */
4063      public function get_errno() {
4064          return $this->errno;
4065      }
4066  
4067      /**
4068       * When using a proxy, an additional HTTP response code may appear at
4069       * the start of the header. For example, when using https over a proxy
4070       * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
4071       * also possible and some may come with their own headers.
4072       *
4073       * If using the return value containing all headers, this function can be
4074       * called to remove unwanted doubles.
4075       *
4076       * Note that it is not possible to distinguish this situation from valid
4077       * data unless you know the actual response part (below the headers)
4078       * will not be included in this string, or else will not 'look like' HTTP
4079       * headers. As a result it is not safe to call this function for general
4080       * data.
4081       *
4082       * @param string $input Input HTTP response
4083       * @return string HTTP response with additional headers stripped if any
4084       */
4085      public static function strip_double_headers($input) {
4086          // I have tried to make this regular expression as specific as possible
4087          // to avoid any case where it does weird stuff if you happen to put
4088          // HTTP/1.1 200 at the start of any line in your RSS file. This should
4089          // also make it faster because it can abandon regex processing as soon
4090          // as it hits something that doesn't look like an http header. The
4091          // header definition is taken from RFC 822, except I didn't support
4092          // folding which is never used in practice.
4093          $crlf = "\r\n";
4094          return preg_replace(
4095                  // HTTP version and status code (ignore value of code).
4096                  '~^HTTP/1\..*' . $crlf .
4097                  // Header name: character between 33 and 126 decimal, except colon.
4098                  // Colon. Header value: any character except \r and \n. CRLF.
4099                  '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
4100                  // Headers are terminated by another CRLF (blank line).
4101                  $crlf .
4102                  // Second HTTP status code, this time must be 200.
4103                  '(HTTP/1.[01] 200 )~', '$1', $input);
4104      }
4105  }
4106  
4107  /**
4108   * This class is used by cURL class, use case:
4109   *
4110   * <code>
4111   * $CFG->repositorycacheexpire = 120;
4112   * $CFG->curlcache = 120;
4113   *
4114   * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
4115   * $ret = $c->get('http://www.google.com');
4116   * </code>
4117   *
4118   * @package   core_files
4119   * @copyright Dongsheng Cai <dongsheng@moodle.com>
4120   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4121   */
4122  class curl_cache {
4123      /** @var string Path to cache directory */
4124      public $dir = '';
4125  
4126      /**
4127       * Constructor
4128       *
4129       * @global stdClass $CFG
4130       * @param string $module which module is using curl_cache
4131       */
4132      public function __construct($module = 'repository') {
4133          global $CFG;
4134          if (!empty($module)) {
4135              $this->dir = $CFG->cachedir.'/'.$module.'/';
4136          } else {
4137              $this->dir = $CFG->cachedir.'/misc/';
4138          }
4139          if (!file_exists($this->dir)) {
4140              mkdir($this->dir, $CFG->directorypermissions, true);
4141          }
4142          if ($module == 'repository') {
4143              if (empty($CFG->repositorycacheexpire)) {
4144                  $CFG->repositorycacheexpire = 120;
4145              }
4146              $this->ttl = $CFG->repositorycacheexpire;
4147          } else {
4148              if (empty($CFG->curlcache)) {
4149                  $CFG->curlcache = 120;
4150              }
4151              $this->ttl = $CFG->curlcache;
4152          }
4153      }
4154  
4155      /**
4156       * Get cached value
4157       *
4158       * @global stdClass $CFG
4159       * @global stdClass $USER
4160       * @param mixed $param
4161       * @return bool|string
4162       */
4163      public function get($param) {
4164          global $CFG, $USER;
4165          $this->cleanup($this->ttl);
4166          $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4167          if(file_exists($this->dir.$filename)) {
4168              $lasttime = filemtime($this->dir.$filename);
4169              if (time()-$lasttime > $this->ttl) {
4170                  return false;
4171              } else {
4172                  $fp = fopen($this->dir.$filename, 'r');
4173                  $size = filesize($this->dir.$filename);
4174                  $content = fread($fp, $size);
4175                  return unserialize($content);
4176              }
4177          }
4178          return false;
4179      }
4180  
4181      /**
4182       * Set cache value
4183       *
4184       * @global object $CFG
4185       * @global object $USER
4186       * @param mixed $param
4187       * @param mixed $val
4188       */
4189      public function set($param, $val) {
4190          global $CFG, $USER;
4191          $filename = 'u'.$USER->id.'_'.md5(serialize($param));
4192          $fp = fopen($this->dir.$filename, 'w');
4193          fwrite($fp, serialize($val));
4194          fclose($fp);
4195          @chmod($this->dir.$filename, $CFG->filepermissions);
4196      }
4197  
4198      /**
4199       * Remove cache files
4200       *
4201       * @param int $expire The number of seconds before expiry
4202       */
4203      public function cleanup($expire) {
4204          if ($dir = opendir($this->dir)) {
4205              while (false !== ($file = readdir($dir))) {
4206                  if(!is_dir($file) && $file != '.' && $file != '..') {
4207                      $lasttime = @filemtime($this->dir.$file);
4208                      if (time() - $lasttime > $expire) {
4209                          @unlink($this->dir.$file);
4210                      }
4211                  }
4212              }
4213              closedir($dir);
4214          }
4215      }
4216      /**
4217       * delete current user's cache file
4218       *
4219       * @global object $CFG
4220       * @global object $USER
4221       */
4222      public function refresh() {
4223          global $CFG, $USER;
4224          if ($dir = opendir($this->dir)) {
4225              while (false !== ($file = readdir($dir))) {
4226                  if (!is_dir($file) && $file != '.' && $file != '..') {
4227                      if (strpos($file, 'u'.$USER->id.'_') !== false) {
4228                          @unlink($this->dir.$file);
4229                      }
4230                  }
4231              }
4232          }
4233      }
4234  }
4235  
4236  /**
4237   * This function delegates file serving to individual plugins
4238   *
4239   * @param string $relativepath
4240   * @param bool $forcedownload
4241   * @param null|string $preview the preview mode, defaults to serving the original file
4242   * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
4243   *                         offline (e.g. mobile app).
4244   * @param bool $embed Whether this file will be served embed into an iframe.
4245   * @todo MDL-31088 file serving improments
4246   */
4247  function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
4248      global $DB, $CFG, $USER;
4249      // relative path must start with '/'
4250      if (!$relativepath) {
4251          print_error('invalidargorconf');
4252      } else if ($relativepath[0] != '/') {
4253          print_error('pathdoesnotstartslash');
4254      }
4255  
4256      // extract relative path components
4257      $args = explode('/', ltrim($relativepath, '/'));
4258  
4259      if (count($args) < 3) { // always at least context, component and filearea
4260          print_error('invalidarguments');
4261      }
4262  
4263      $contextid = (int)array_shift($args);
4264      $component = clean_param(array_shift($args), PARAM_COMPONENT);
4265      $filearea  = clean_param(array_shift($args), PARAM_AREA);
4266  
4267      list($context, $course, $cm) = get_context_info_array($contextid);
4268  
4269      $fs = get_file_storage();
4270  
4271      $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
4272  
4273      // ========================================================================================================================
4274      if ($component === 'blog') {
4275          // Blog file serving
4276          if ($context->contextlevel != CONTEXT_SYSTEM) {
4277              send_file_not_found();
4278          }
4279          if ($filearea !== 'attachment' and $filearea !== 'post') {
4280              send_file_not_found();
4281          }
4282  
4283          if (empty($CFG->enableblogs)) {
4284              print_error('siteblogdisable', 'blog');
4285          }
4286  
4287          $entryid = (int)array_shift($args);
4288          if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
4289              send_file_not_found();
4290          }
4291          if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
4292              require_login();
4293              if (isguestuser()) {
4294                  print_error('noguest');
4295              }
4296              if ($CFG->bloglevel == BLOG_USER_LEVEL) {
4297                  if ($USER->id != $entry->userid) {
4298                      send_file_not_found();
4299                  }
4300              }
4301          }
4302  
4303          if ($entry->publishstate === 'public') {
4304              if ($CFG->forcelogin) {
4305                  require_login();
4306              }
4307  
4308          } else if ($entry->publishstate === 'site') {
4309              require_login();
4310              //ok
4311          } else if ($entry->publishstate === 'draft') {
4312              require_login();
4313              if ($USER->id != $entry->userid) {
4314                  send_file_not_found();
4315              }
4316          }
4317  
4318          $filename = array_pop($args);
4319          $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4320  
4321          if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
4322              send_file_not_found();
4323          }
4324  
4325          send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
4326  
4327      // ========================================================================================================================
4328      } else if ($component === 'grade') {
4329  
4330          require_once($CFG->libdir . '/grade/constants.php');
4331  
4332          if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
4333              // Global gradebook files
4334              if ($CFG->forcelogin) {
4335                  require_login();
4336              }
4337  
4338              $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
4339  
4340              if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4341                  send_file_not_found();
4342              }
4343  
4344              \core\session\manager::write_close(); // Unlock session during file serving.
4345              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4346  
4347          } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4348              if ($context->contextlevel != CONTEXT_MODULE) {
4349                  send_file_not_found();
4350              }
4351  
4352              require_login($course, false);
4353  
4354              $gradeid = (int) array_shift($args);
4355              $filename = array_pop($args);
4356              if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
4357                  $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
4358              } else {
4359                  $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
4360              }
4361  
4362              if (!$grade) {
4363                  send_file_not_found();
4364              }
4365  
4366              $iscurrentuser = $USER->id == $grade->userid;
4367  
4368              if (!$iscurrentuser) {
4369                  $coursecontext = context_course::instance($course->id);
4370                  if (!has_capability('moodle/grade:viewall', $coursecontext)) {
4371                      send_file_not_found();
4372                  }
4373              }
4374  
4375              $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
4376  
4377              if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4378                  send_file_not_found();
4379              }
4380  
4381              \core\session\manager::write_close(); // Unlock session during file serving.
4382              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4383          } else {
4384              send_file_not_found();
4385          }
4386  
4387      // ========================================================================================================================
4388      } else if ($component === 'tag') {
4389          if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
4390  
4391              // All tag descriptions are going to be public but we still need to respect forcelogin
4392              if ($CFG->forcelogin) {
4393                  require_login();
4394              }
4395  
4396              $fullpath = "/$context->id/tag/description/".implode('/', $args);
4397  
4398              if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
4399                  send_file_not_found();
4400              }
4401  
4402              \core\session\manager::write_close(); // Unlock session during file serving.
4403              send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4404  
4405          } else {
4406              send_file_not_found();
4407          }
4408      // ========================================================================================================================
4409      } else if ($component === 'badges') {
4410          require_once($CFG->libdir . '/badgeslib.php');
4411  
4412          $badgeid = (int)array_shift($args);
4413          $badge = new badge($badgeid);
4414          $filename = array_pop($args);
4415  
4416          if ($filearea === 'badgeimage') {
4417              if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
4418                  send_file_not_found();
4419              }
4420              if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
4421                  send_file_not_found();
4422              }
4423  
4424              \core\session\manager::write_close();
4425              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4426          } else if ($filearea === 'userbadge'  and $context->contextlevel == CONTEXT_USER) {
4427              if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
4428                  send_file_not_found();
4429              }
4430  
4431              \core\session\manager::write_close();
4432              send_stored_file($file, 60*60, 0, true, $sendfileoptions);
4433          }
4434      // ========================================================================================================================
4435      } else if ($component === 'calendar') {
4436          if ($filearea === 'event_description'  and $context->contextlevel == CONTEXT_SYSTEM) {
4437  
4438              // All events here are public the one requirement is that we respect forcelogin
4439              if ($CFG->forcelogin) {
4440                  require_login();
4441              }
4442  
4443              // Get the event if from the args array
4444              $eventid = array_shift($args);
4445  
4446              // Load the event from the database
4447              if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
4448                  send_file_not_found();
4449              }
4450  
4451              // Get the file and serve if successful
4452              $filename = array_pop($args);
4453              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4454              if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4455                  send_file_not_found();
4456              }
4457  
4458              \core\session\manager::write_close(); // Unlock session during file serving.
4459              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4460  
4461          } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
4462  
4463              // Must be logged in, if they are not then they obviously can't be this user
4464              require_login();
4465  
4466              // Don't want guests here, potentially saves a DB call
4467              if (isguestuser()) {
4468                  send_file_not_found();
4469              }
4470  
4471              // Get the event if from the args array
4472              $eventid = array_shift($args);
4473  
4474              // Load the event from the database - user id must match
4475              if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
4476                  send_file_not_found();
4477              }
4478  
4479              // Get the file and serve if successful
4480              $filename = array_pop($args);
4481              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4482              if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4483                  send_file_not_found();
4484              }
4485  
4486              \core\session\manager::write_close(); // Unlock session during file serving.
4487              send_stored_file($file, 0, 0, true, $sendfileoptions);
4488  
4489          } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
4490  
4491              // Respect forcelogin and require login unless this is the site.... it probably
4492              // should NEVER be the site
4493              if ($CFG->forcelogin || $course->id != SITEID) {
4494                  require_login($course);
4495              }
4496  
4497              // Must be able to at least view the course. This does not apply to the front page.
4498              if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
4499                  //TODO: hmm, do we really want to block guests here?
4500                  send_file_not_found();
4501              }
4502  
4503              // Get the event id
4504              $eventid = array_shift($args);
4505  
4506              // Load the event from the database we need to check whether it is
4507              // a) valid course event
4508              // b) a group event
4509              // Group events use the course context (there is no group context)
4510              if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
4511                  send_file_not_found();
4512              }
4513  
4514              // If its a group event require either membership of view all groups capability
4515              if ($event->eventtype === 'group') {
4516                  if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
4517                      send_file_not_found();
4518                  }
4519              } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
4520                  // Ok. Please note that the event type 'site' still uses a course context.
4521              } else {
4522                  // Some other type.
4523                  send_file_not_found();
4524              }
4525  
4526              // If we get this far we can serve the file
4527              $filename = array_pop($args);
4528              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4529              if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
4530                  send_file_not_found();
4531              }
4532  
4533              \core\session\manager::write_close(); // Unlock session during file serving.
4534              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4535  
4536          } else {
4537              send_file_not_found();
4538          }
4539  
4540      // ========================================================================================================================
4541      } else if ($component === 'user') {
4542          if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
4543              if (count($args) == 1) {
4544                  $themename = theme_config::DEFAULT_THEME;
4545                  $filename = array_shift($args);
4546              } else {
4547                  $themename = array_shift($args);
4548                  $filename = array_shift($args);
4549              }
4550  
4551              // fix file name automatically
4552              if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
4553                  $filename = 'f1';
4554              }
4555  
4556              if ((!empty($CFG->forcelogin) and !isloggedin()) ||
4557                      (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
4558                  // protect images if login required and not logged in;
4559                  // also if login is required for profile images and is not logged in or guest
4560                  // do not use require_login() because it is expensive and not suitable here anyway
4561                  $theme = theme_config::load($themename);
4562                  redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
4563              }
4564  
4565              if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
4566                  if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
4567                      if ($filename === 'f3') {
4568                          // f3 512x512px was introduced in 2.3, there might be only the smaller version.
4569                          if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
4570                              $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
4571                          }
4572                      }
4573                  }
4574              }
4575              if (!$file) {
4576                  // bad reference - try to prevent future retries as hard as possible!
4577                  if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
4578                      if ($user->picture > 0) {
4579                          $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
4580                      }
4581                  }
4582                  // no redirect here because it is not cached
4583                  $theme = theme_config::load($themename);
4584                  $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
4585                  send_file($imagefile, basename($imagefile), 60*60*24*14);
4586              }
4587  
4588              $options = $sendfileoptions;
4589              if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
4590                  // Profile images should be cache-able by both browsers and proxies according
4591                  // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
4592                  $options['cacheability'] = 'public';
4593              }
4594              send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
4595  
4596          } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
4597              require_login();
4598  
4599              if (isguestuser()) {
4600                  send_file_not_found();
4601              }
4602  
4603              if ($USER->id !== $context->instanceid) {
4604                  send_file_not_found();
4605              }
4606  
4607              $filename = array_pop($args);
4608              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4609              if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4610                  send_file_not_found();
4611              }
4612  
4613              \core\session\manager::write_close(); // Unlock session during file serving.
4614              send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4615  
4616          } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
4617  
4618              if ($CFG->forcelogin) {
4619                  require_login();
4620              }
4621  
4622              $userid = $context->instanceid;
4623  
4624              if ($USER->id == $userid) {
4625                  // always can access own
4626  
4627              } else if (!empty($CFG->forceloginforprofiles)) {
4628                  require_login();
4629  
4630                  if (isguestuser()) {
4631                      send_file_not_found();
4632                  }
4633  
4634                  // we allow access to site profile of all course contacts (usually teachers)
4635                  if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
4636                      send_file_not_found();
4637                  }
4638  
4639                  $canview = false;
4640                  if (has_capability('moodle/user:viewdetails', $context)) {
4641                      $canview = true;
4642                  } else {
4643                      $courses = enrol_get_my_courses();
4644                  }
4645  
4646                  while (!$canview && count($courses) > 0) {
4647                      $course = array_shift($courses);
4648                      if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
4649                          $canview = true;
4650                      }
4651                  }
4652              }
4653  
4654              $filename = array_pop($args);
4655              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4656              if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4657                  send_file_not_found();
4658              }
4659  
4660              \core\session\manager::write_close(); // Unlock session during file serving.
4661              send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4662  
4663          } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
4664              $userid = (int)array_shift($args);
4665              $usercontext = context_user::instance($userid);
4666  
4667              if ($CFG->forcelogin) {
4668                  require_login();
4669              }
4670  
4671              if (!empty($CFG->forceloginforprofiles)) {
4672                  require_login();
4673                  if (isguestuser()) {
4674                      print_error('noguest');
4675                  }
4676  
4677                  //TODO: review this logic of user profile access prevention
4678                  if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
4679                      print_error('usernotavailable');
4680                  }
4681                  if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
4682                      print_error('cannotviewprofile');
4683                  }
4684                  if (!is_enrolled($context, $userid)) {
4685                      print_error('notenrolledprofile');
4686                  }
4687                  if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
4688                      print_error('groupnotamember');
4689                  }
4690              }
4691  
4692              $filename = array_pop($args);
4693              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4694              if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
4695                  send_file_not_found();
4696              }
4697  
4698              \core\session\manager::write_close(); // Unlock session during file serving.
4699              send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4700  
4701          } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
4702              require_login();
4703  
4704              if (isguestuser()) {
4705                  send_file_not_found();
4706              }
4707              $userid = $context->instanceid;
4708  
4709              if ($USER->id != $userid) {
4710                  send_file_not_found();
4711              }
4712  
4713              $filename = array_pop($args);
4714              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4715              if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
4716                  send_file_not_found();
4717              }
4718  
4719              \core\session\manager::write_close(); // Unlock session during file serving.
4720              send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
4721  
4722          } else {
4723              send_file_not_found();
4724          }
4725  
4726      // ========================================================================================================================
4727      } else if ($component === 'coursecat') {
4728          if ($context->contextlevel != CONTEXT_COURSECAT) {
4729              send_file_not_found();
4730          }
4731  
4732          if ($filearea === 'description') {
4733              if ($CFG->forcelogin) {
4734                  // no login necessary - unless login forced everywhere
4735                  require_login();
4736              }
4737  
4738              // Check if user can view this category.
4739              if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
4740                  send_file_not_found();
4741              }
4742  
4743              $filename = array_pop($args);
4744              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4745              if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
4746                  send_file_not_found();
4747              }
4748  
4749              \core\session\manager::write_close(); // Unlock session during file serving.
4750              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4751          } else {
4752              send_file_not_found();
4753          }
4754  
4755      // ========================================================================================================================
4756      } else if ($component === 'course') {
4757          if ($context->contextlevel != CONTEXT_COURSE) {
4758              send_file_not_found();
4759          }
4760  
4761          if ($filearea === 'summary' || $filearea === 'overviewfiles') {
4762              if ($CFG->forcelogin) {
4763                  require_login();
4764              }
4765  
4766              $filename = array_pop($args);
4767              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4768              if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
4769                  send_file_not_found();
4770              }
4771  
4772              \core\session\manager::write_close(); // Unlock session during file serving.
4773              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4774  
4775          } else if ($filearea === 'section') {
4776              if ($CFG->forcelogin) {
4777                  require_login($course);
4778              } else if ($course->id != SITEID) {
4779                  require_login($course);
4780              }
4781  
4782              $sectionid = (int)array_shift($args);
4783  
4784              if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
4785                  send_file_not_found();
4786              }
4787  
4788              $filename = array_pop($args);
4789              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4790              if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4791                  send_file_not_found();
4792              }
4793  
4794              \core\session\manager::write_close(); // Unlock session during file serving.
4795              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4796  
4797          } else {
4798              send_file_not_found();
4799          }
4800  
4801      } else if ($component === 'cohort') {
4802  
4803          $cohortid = (int)array_shift($args);
4804          $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
4805          $cohortcontext = context::instance_by_id($cohort->contextid);
4806  
4807          // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
4808          if ($context->id != $cohort->contextid &&
4809              ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
4810              send_file_not_found();
4811          }
4812  
4813          // User is able to access cohort if they have view cap on cohort level or
4814          // the cohort is visible and they have view cap on course level.
4815          $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
4816                  ($cohort->visible && has_capability('moodle/cohort:view', $context));
4817  
4818          if ($filearea === 'description' && $canview) {
4819              $filename = array_pop($args);
4820              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4821              if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
4822                      && !$file->is_directory()) {
4823                  \core\session\manager::write_close(); // Unlock session during file serving.
4824                  send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
4825              }
4826          }
4827  
4828          send_file_not_found();
4829  
4830      } else if ($component === 'group') {
4831          if ($context->contextlevel != CONTEXT_COURSE) {
4832              send_file_not_found();
4833          }
4834  
4835          require_course_login($course, true, null, false);
4836  
4837          $groupid = (int)array_shift($args);
4838  
4839          $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
4840          if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
4841              // do not allow access to separate group info if not member or teacher
4842              send_file_not_found();
4843          }
4844  
4845          if ($filearea === 'description') {
4846  
4847              require_login($course);
4848  
4849              $filename = array_pop($args);
4850              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4851              if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
4852                  send_file_not_found();
4853              }
4854  
4855              \core\session\manager::write_close(); // Unlock session during file serving.
4856              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4857  
4858          } else if ($filearea === 'icon') {
4859              $filename = array_pop($args);
4860  
4861              if ($filename !== 'f1' and $filename !== 'f2') {
4862                  send_file_not_found();
4863              }
4864              if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
4865                  if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
4866                      send_file_not_found();
4867                  }
4868              }
4869  
4870              \core\session\manager::write_close(); // Unlock session during file serving.
4871              send_stored_file($file, 60*60, 0, false, $sendfileoptions);
4872  
4873          } else {
4874              send_file_not_found();
4875          }
4876  
4877      } else if ($component === 'grouping') {
4878          if ($context->contextlevel != CONTEXT_COURSE) {
4879              send_file_not_found();
4880          }
4881  
4882          require_login($course);
4883  
4884          $groupingid = (int)array_shift($args);
4885  
4886          // note: everybody has access to grouping desc images for now
4887          if ($filearea === 'description') {
4888  
4889              $filename = array_pop($args);
4890              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4891              if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
4892                  send_file_not_found();
4893              }
4894  
4895              \core\session\manager::write_close(); // Unlock session during file serving.
4896              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4897  
4898          } else {
4899              send_file_not_found();
4900          }
4901  
4902      // ========================================================================================================================
4903      } else if ($component === 'backup') {
4904          if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
4905              require_login($course);
4906              require_capability('moodle/backup:downloadfile', $context);
4907  
4908              $filename = array_pop($args);
4909              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4910              if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
4911                  send_file_not_found();
4912              }
4913  
4914              \core\session\manager::write_close(); // Unlock session during file serving.
4915              send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4916  
4917          } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
4918              require_login($course);
4919              require_capability('moodle/backup:downloadfile', $context);
4920  
4921              $sectionid = (int)array_shift($args);
4922  
4923              $filename = array_pop($args);
4924              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4925              if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
4926                  send_file_not_found();
4927              }
4928  
4929              \core\session\manager::write_close();
4930              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4931  
4932          } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
4933              require_login($course, false, $cm);
4934              require_capability('moodle/backup:downloadfile', $context);
4935  
4936              $filename = array_pop($args);
4937              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4938              if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
4939                  send_file_not_found();
4940              }
4941  
4942              \core\session\manager::write_close();
4943              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
4944  
4945          } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
4946              // Backup files that were generated by the automated backup systems.
4947  
4948              require_login($course);
4949              require_capability('moodle/backup:downloadfile', $context);
4950              require_capability('moodle/restore:userinfo', $context);
4951  
4952              $filename = array_pop($args);
4953              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
4954              if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
4955                  send_file_not_found();
4956              }
4957  
4958              \core\session\manager::write_close(); // Unlock session during file serving.
4959              send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
4960  
4961          } else {
4962              send_file_not_found();
4963          }
4964  
4965      // ========================================================================================================================
4966      } else if ($component === 'question') {
4967          require_once($CFG->libdir . '/questionlib.php');
4968          question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
4969          send_file_not_found();
4970  
4971      // ========================================================================================================================
4972      } else if ($component === 'grading') {
4973          if ($filearea === 'description') {
4974              // files embedded into the form definition description
4975  
4976              if ($context->contextlevel == CONTEXT_SYSTEM) {
4977                  require_login();
4978  
4979              } else if ($context->contextlevel >= CONTEXT_COURSE) {
4980                  require_login($course, false, $cm);
4981  
4982              } else {
4983                  send_file_not_found();
4984              }
4985  
4986              $formid = (int)array_shift($args);
4987  
4988              $sql = "SELECT ga.id
4989                  FROM {grading_areas} ga
4990                  JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
4991                  WHERE gd.id = ? AND ga.contextid = ?";
4992              $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
4993  
4994              if (!$areaid) {
4995                  send_file_not_found();
4996              }
4997  
4998              $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
4999  
5000              if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
5001                  send_file_not_found();
5002              }
5003  
5004              \core\session\manager::write_close(); // Unlock session during file serving.
5005              send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
5006          }
5007      } else if ($component === 'contentbank') {
5008          if ($filearea != 'public' || isguestuser()) {
5009              send_file_not_found();
5010          }
5011  
5012          if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
5013              require_login();
5014          } else if ($context->contextlevel == CONTEXT_COURSE) {
5015              require_login($course);
5016          } else {
5017              send_file_not_found();
5018          }
5019  
5020          $itemid = (int)array_shift($args);
5021          $filename = array_pop($args);
5022          $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5023          if (!$file = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename) or
5024              $file->is_directory()) {
5025              send_file_not_found();
5026          }
5027  
5028          \core\session\manager::write_close(); // Unlock session during file serving.
5029          send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
5030      } else if (strpos($component, 'mod_') === 0) {
5031          $modname = substr($component, 4);
5032          if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
5033              send_file_not_found();
5034          }
5035          require_once("$CFG->dirroot/mod/$modname/lib.php");
5036  
5037          if ($context->contextlevel == CONTEXT_MODULE) {
5038              if ($cm->modname !== $modname) {
5039                  // somebody tries to gain illegal access, cm type must match the component!
5040                  send_file_not_found();
5041              }
5042          }
5043  
5044          if ($filearea === 'intro') {
5045              if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
5046                  send_file_not_found();
5047              }
5048  
5049              // Require login to the course first (without login to the module).
5050              require_course_login($course, true);
5051  
5052              // Now check if module is available OR it is restricted but the intro is shown on the course page.
5053              $cminfo = cm_info::create($cm);
5054              if (!$cminfo->uservisible) {
5055                  if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
5056                      // Module intro is not visible on the course page and module is not available, show access error.
5057                      require_course_login($course, true, $cminfo);
5058                  }
5059              }
5060  
5061              // all users may access it
5062              $filename = array_pop($args);
5063              $filepath = $args ? '/'.implode('/', $args).'/' : '/';
5064              if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
5065                  send_file_not_found();
5066              }
5067  
5068              // finally send the file
5069              send_stored_file($file, null, 0, false, $sendfileoptions);
5070          }
5071  
5072          $filefunction = $component.'_pluginfile';
5073          $filefunctionold = $modname.'_pluginfile';
5074          if (function_exists($filefunction)) {
5075              // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5076              $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5077          } else if (function_exists($filefunctionold)) {
5078              // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5079              $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5080          }
5081  
5082          send_file_not_found();
5083  
5084      // ========================================================================================================================
5085      } else if (strpos($component, 'block_') === 0) {
5086          $blockname = substr($component, 6);
5087          // note: no more class methods in blocks please, that is ....
5088          if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
5089              send_file_not_found();
5090          }
5091          require_once("$CFG->dirroot/blocks/$blockname/lib.php");
5092  
5093          if ($context->contextlevel == CONTEXT_BLOCK) {
5094              $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
5095              if ($birecord->blockname !== $blockname) {
5096                  // somebody tries to gain illegal access, cm type must match the component!
5097                  send_file_not_found();
5098              }
5099  
5100              if ($context->get_course_context(false)) {
5101                  // If block is in course context, then check if user has capability to access course.
5102                  require_course_login($course);
5103              } else if ($CFG->forcelogin) {
5104                  // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
5105                  require_login();
5106              }
5107  
5108              $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
5109              // User can't access file, if block is hidden or doesn't have block:view capability
5110              if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
5111                   send_file_not_found();
5112              }
5113          } else {
5114              $birecord = null;
5115          }
5116  
5117          $filefunction = $component.'_pluginfile';
5118          if (function_exists($filefunction)) {
5119              // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5120              $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5121          }
5122  
5123          send_file_not_found();
5124  
5125      // ========================================================================================================================
5126      } else if (strpos($component, '_') === false) {
5127          // all core subsystems have to be specified above, no more guessing here!
5128          send_file_not_found();
5129  
5130      } else {
5131          // try to serve general plugin file in arbitrary context
5132          $dir = core_component::get_component_directory($component);
5133          if (!file_exists("$dir/lib.php")) {
5134              send_file_not_found();
5135          }
5136          include_once("$dir/lib.php");
5137  
5138          $filefunction = $component.'_pluginfile';
5139          if (function_exists($filefunction)) {
5140              // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
5141              $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
5142          }
5143  
5144          send_file_not_found();
5145      }
5146  
5147  }