Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.6.x will end 11 November 2019 (12 months).
  • Bug fixes for security issues in 3.6.x will end 11 May 2020 (18 months) - Support has ended.
  • minimum PHP 7.0.0 Note: minimum PHP version has increased since Moodle 3.3. PHP 7.1.x and 7.2.x are supported too. PHP 7.3.x support is being implemented (@ MDL-63420) and not ready for production with this release.
  • /lib/ -> filelib.php (source)

    Differences Between: [Versions 35 and 36] [Versions 36 and 310] [Versions 36 and 311] [Versions 36 and 37] [Versions 36 and 38] [Versions 36 and 39]

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