Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/lib/ -> filelib.php (source)

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