/lib/filelib.php
PHP | 5175 lines | 3252 code | 534 blank | 1389 comment | 885 complexity | 2ae9b18013aff8782c4384398f6b4271 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * Functions for file handling.
- *
- * @package core_files
- * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- defined('MOODLE_INTERNAL') || die();
- /**
- * BYTESERVING_BOUNDARY - string unique string constant.
- */
- define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
- /**
- * Do not process file merging when working with draft area files.
- */
- define('IGNORE_FILE_MERGE', -1);
- /**
- * Unlimited area size constant
- */
- define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
- /**
- * Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
- */
- define('DRAFT_AREA_BUCKET_CAPACITY', 50);
- /**
- * Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
- */
- define('DRAFT_AREA_BUCKET_LEAK', 0.2);
- require_once("$CFG->libdir/filestorage/file_exceptions.php");
- require_once("$CFG->libdir/filestorage/file_storage.php");
- require_once("$CFG->libdir/filestorage/zip_packer.php");
- require_once("$CFG->libdir/filebrowser/file_browser.php");
- /**
- * Encodes file serving url
- *
- * @deprecated use moodle_url factory methods instead
- *
- * @todo MDL-31071 deprecate this function
- * @global stdClass $CFG
- * @param string $urlbase
- * @param string $path /filearea/itemid/dir/dir/file.exe
- * @param bool $forcedownload
- * @param bool $https https url required
- * @return string encoded file url
- */
- function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
- global $CFG;
- //TODO: deprecate this
- if ($CFG->slasharguments) {
- $parts = explode('/', $path);
- $parts = array_map('rawurlencode', $parts);
- $path = implode('/', $parts);
- $return = $urlbase.$path;
- if ($forcedownload) {
- $return .= '?forcedownload=1';
- }
- } else {
- $path = rawurlencode($path);
- $return = $urlbase.'?file='.$path;
- if ($forcedownload) {
- $return .= '&forcedownload=1';
- }
- }
- if ($https) {
- $return = str_replace('http://', 'https://', $return);
- }
- return $return;
- }
- /**
- * Detects if area contains subdirs,
- * this is intended for file areas that are attached to content
- * migrated from 1.x where subdirs were allowed everywhere.
- *
- * @param context $context
- * @param string $component
- * @param string $filearea
- * @param string $itemid
- * @return bool
- */
- function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
- global $DB;
- if (!isset($itemid)) {
- // Not initialised yet.
- return false;
- }
- // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
- $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
- $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
- return $DB->record_exists_select('files', $select, $params);
- }
- /**
- * Prepares 'editor' formslib element from data in database
- *
- * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
- * function then copies the embedded files into draft area (assigning itemids automatically),
- * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
- * displayed.
- * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
- * your mform's set_data() supplying the object returned by this function.
- *
- * @category files
- * @param stdClass $data database field that holds the html text with embedded media
- * @param string $field the name of the database field that holds the html text with embedded media
- * @param array $options editor options (like maxifiles, maxbytes etc.)
- * @param stdClass $context context of the editor
- * @param string $component
- * @param string $filearea file area name
- * @param int $itemid item id, required if item exists
- * @return stdClass modified data object
- */
- function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
- $options = (array)$options;
- if (!isset($options['trusttext'])) {
- $options['trusttext'] = false;
- }
- if (!isset($options['forcehttps'])) {
- $options['forcehttps'] = false;
- }
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (!isset($options['maxfiles'])) {
- $options['maxfiles'] = 0; // no files by default
- }
- if (!isset($options['noclean'])) {
- $options['noclean'] = false;
- }
- //sanity check for passed context. This function doesn't expect $option['context'] to be set
- //But this function is called before creating editor hence, this is one of the best places to check
- //if context is used properly. This check notify developer that they missed passing context to editor.
- if (isset($context) && !isset($options['context'])) {
- //if $context is not null then make sure $option['context'] is also set.
- debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
- } else if (isset($options['context']) && isset($context)) {
- //If both are passed then they should be equal.
- if ($options['context']->id != $context->id) {
- $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
- throw new coding_exception($exceptionmsg);
- }
- }
- if (is_null($itemid) or is_null($context)) {
- $contextid = null;
- $itemid = null;
- if (!isset($data)) {
- $data = new stdClass();
- }
- if (!isset($data->{$field})) {
- $data->{$field} = '';
- }
- if (!isset($data->{$field.'format'})) {
- $data->{$field.'format'} = editors_get_preferred_format();
- }
- if (!$options['noclean']) {
- $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
- }
- } else {
- if ($options['trusttext']) {
- // noclean ignored if trusttext enabled
- if (!isset($data->{$field.'trust'})) {
- $data->{$field.'trust'} = 0;
- }
- $data = trusttext_pre_edit($data, $field, $context);
- } else {
- if (!$options['noclean']) {
- $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
- }
- }
- $contextid = $context->id;
- }
- if ($options['maxfiles'] != 0) {
- $draftid_editor = file_get_submitted_draft_itemid($field);
- $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
- $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
- } else {
- $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
- }
- return $data;
- }
- /**
- * Prepares the content of the 'editor' form element with embedded media files to be saved in database
- *
- * This function moves files from draft area to the destination area and
- * encodes URLs to the draft files so they can be safely saved into DB. The
- * form has to contain the 'editor' element named foobar_editor, where 'foobar'
- * is the name of the database field to hold the wysiwyg editor content. The
- * editor data comes as an array with text, format and itemid properties. This
- * function automatically adds $data properties foobar, foobarformat and
- * foobartrust, where foobar has URL to embedded files encoded.
- *
- * @category files
- * @param stdClass $data raw data submitted by the form
- * @param string $field name of the database field containing the html with embedded media files
- * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
- * @param stdClass $context context, required for existing data
- * @param string $component file component
- * @param string $filearea file area name
- * @param int $itemid item id, required if item exists
- * @return stdClass modified data object
- */
- function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
- $options = (array)$options;
- if (!isset($options['trusttext'])) {
- $options['trusttext'] = false;
- }
- if (!isset($options['forcehttps'])) {
- $options['forcehttps'] = false;
- }
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (!isset($options['maxfiles'])) {
- $options['maxfiles'] = 0; // no files by default
- }
- if (!isset($options['maxbytes'])) {
- $options['maxbytes'] = 0; // unlimited
- }
- if (!isset($options['removeorphaneddrafts'])) {
- $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
- }
- if ($options['trusttext']) {
- $data->{$field.'trust'} = trusttext_trusted($context);
- } else {
- $data->{$field.'trust'} = 0;
- }
- $editor = $data->{$field.'_editor'};
- if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
- $data->{$field} = $editor['text'];
- } else {
- // Clean the user drafts area of any files not referenced in the editor text.
- if ($options['removeorphaneddrafts']) {
- file_remove_editor_orphaned_files($editor);
- }
- $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
- }
- $data->{$field.'format'} = $editor['format'];
- return $data;
- }
- /**
- * Saves text and files modified by Editor formslib element
- *
- * @category files
- * @param stdClass $data $database entry field
- * @param string $field name of data field
- * @param array $options various options
- * @param stdClass $context context - must already exist
- * @param string $component
- * @param string $filearea file area name
- * @param int $itemid must already exist, usually means data is in db
- * @return stdClass modified data obejct
- */
- function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
- $options = (array)$options;
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (is_null($itemid) or is_null($context)) {
- $itemid = null;
- $contextid = null;
- } else {
- $contextid = $context->id;
- }
- $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
- file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
- $data->{$field.'_filemanager'} = $draftid_editor;
- return $data;
- }
- /**
- * Saves files modified by File manager formslib element
- *
- * @todo MDL-31073 review this function
- * @category files
- * @param stdClass $data $database entry field
- * @param string $field name of data field
- * @param array $options various options
- * @param stdClass $context context - must already exist
- * @param string $component
- * @param string $filearea file area name
- * @param int $itemid must already exist, usually means data is in db
- * @return stdClass modified data obejct
- */
- function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
- $options = (array)$options;
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (!isset($options['maxfiles'])) {
- $options['maxfiles'] = -1; // unlimited
- }
- if (!isset($options['maxbytes'])) {
- $options['maxbytes'] = 0; // unlimited
- }
- if (empty($data->{$field.'_filemanager'})) {
- $data->$field = '';
- } else {
- file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
- $fs = get_file_storage();
- if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
- $data->$field = '1'; // TODO: this is an ugly hack (skodak)
- } else {
- $data->$field = '';
- }
- }
- return $data;
- }
- /**
- * Generate a draft itemid
- *
- * @category files
- * @global moodle_database $DB
- * @global stdClass $USER
- * @return int a random but available draft itemid that can be used to create a new draft
- * file area.
- */
- function file_get_unused_draft_itemid() {
- global $DB, $USER;
- if (isguestuser() or !isloggedin()) {
- // guests and not-logged-in users can not be allowed to upload anything!!!!!!
- print_error('noguest');
- }
- $contextid = context_user::instance($USER->id)->id;
- $fs = get_file_storage();
- $draftitemid = rand(1, 999999999);
- while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
- $draftitemid = rand(1, 999999999);
- }
- return $draftitemid;
- }
- /**
- * Initialise a draft file area from a real one by copying the files. A draft
- * area will be created if one does not already exist. Normally you should
- * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
- *
- * @category files
- * @global stdClass $CFG
- * @global stdClass $USER
- * @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.
- * @param int $contextid This parameter and the next two identify the file area to copy files from.
- * @param string $component
- * @param string $filearea helps indentify the file area.
- * @param int $itemid helps identify the file area. Can be null if there are no files yet.
- * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
- * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
- * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
- */
- function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
- global $CFG, $USER;
- $options = (array)$options;
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (!isset($options['forcehttps'])) {
- $options['forcehttps'] = false;
- }
- $usercontext = context_user::instance($USER->id);
- $fs = get_file_storage();
- if (empty($draftitemid)) {
- // create a new area and copy existing files into
- $draftitemid = file_get_unused_draft_itemid();
- $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
- if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
- foreach ($files as $file) {
- if ($file->is_directory() and $file->get_filepath() === '/') {
- // we need a way to mark the age of each draft area,
- // by not copying the root dir we force it to be created automatically with current timestamp
- continue;
- }
- if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
- continue;
- }
- $draftfile = $fs->create_file_from_storedfile($file_record, $file);
- // XXX: This is a hack for file manager (MDL-28666)
- // File manager needs to know the original file information before copying
- // to draft area, so we append these information in mdl_files.source field
- // {@link file_storage::search_references()}
- // {@link file_storage::search_references_count()}
- $sourcefield = $file->get_source();
- $newsourcefield = new stdClass;
- $newsourcefield->source = $sourcefield;
- $original = new stdClass;
- $original->contextid = $contextid;
- $original->component = $component;
- $original->filearea = $filearea;
- $original->itemid = $itemid;
- $original->filename = $file->get_filename();
- $original->filepath = $file->get_filepath();
- $newsourcefield->original = file_storage::pack_reference($original);
- $draftfile->set_source(serialize($newsourcefield));
- // End of file manager hack
- }
- }
- if (!is_null($text)) {
- // at this point there should not be any draftfile links yet,
- // because this is a new text from database that should still contain the @@pluginfile@@ links
- // this happens when developers forget to post process the text
- $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
- }
- } else {
- // nothing to do
- }
- if (is_null($text)) {
- return null;
- }
- // relink embedded files - editor can not handle @@PLUGINFILE@@ !
- return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
- }
- /**
- * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
- * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
- * in the @@PLUGINFILE@@ form.
- *
- * @param string $text The content that may contain ULRs in need of rewriting.
- * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
- * @param int $contextid This parameter and the next two identify the file area to use.
- * @param string $component
- * @param string $filearea helps identify the file area.
- * @param int $itemid helps identify the file area.
- * @param array $options
- * bool $options.forcehttps Force the user of https
- * bool $options.reverse Reverse the behaviour of the function
- * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
- * string The processed text.
- */
- function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
- global $CFG, $USER;
- $options = (array)$options;
- if (!isset($options['forcehttps'])) {
- $options['forcehttps'] = false;
- }
- $baseurl = "{$CFG->wwwroot}/{$file}";
- if (!empty($options['includetoken'])) {
- $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
- $token = get_user_key('core_files', $userid);
- $finalfile = basename($file);
- $tokenfile = "token{$finalfile}";
- $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
- $baseurl = "{$CFG->wwwroot}/{$file}";
- if (!$CFG->slasharguments) {
- $baseurl .= "?token={$token}&file=";
- } else {
- $baseurl .= "/{$token}";
- }
- }
- $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
- if ($itemid !== null) {
- $baseurl .= "$itemid/";
- }
- if ($options['forcehttps']) {
- $baseurl = str_replace('http://', 'https://', $baseurl);
- }
- if (!empty($options['reverse'])) {
- return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
- } else {
- return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
- }
- }
- /**
- * Returns information about files in a draft area.
- *
- * @global stdClass $CFG
- * @global stdClass $USER
- * @param int $draftitemid the draft area item id.
- * @param string $filepath path to the directory from which the information have to be retrieved.
- * @return array with the following entries:
- * 'filecount' => number of files in the draft area.
- * 'filesize' => total size of the files in the draft area.
- * 'foldercount' => number of folders in the draft area.
- * 'filesize_without_references' => total size of the area excluding file references.
- * (more information will be added as needed).
- */
- function file_get_draft_area_info($draftitemid, $filepath = '/') {
- global $USER;
- $usercontext = context_user::instance($USER->id);
- return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
- }
- /**
- * Returns information about files in an area.
- *
- * @param int $contextid context id
- * @param string $component component
- * @param string $filearea file area name
- * @param int $itemid item id or all files if not specified
- * @param string $filepath path to the directory from which the information have to be retrieved.
- * @return array with the following entries:
- * 'filecount' => number of files in the area.
- * 'filesize' => total size of the files in the area.
- * 'foldercount' => number of folders in the area.
- * 'filesize_without_references' => total size of the area excluding file references.
- * @since Moodle 3.4
- */
- function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
- $fs = get_file_storage();
- $results = array(
- 'filecount' => 0,
- 'foldercount' => 0,
- 'filesize' => 0,
- 'filesize_without_references' => 0
- );
- $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
- foreach ($draftfiles as $file) {
- if ($file->is_directory()) {
- $results['foldercount'] += 1;
- } else {
- $results['filecount'] += 1;
- }
- $filesize = $file->get_filesize();
- $results['filesize'] += $filesize;
- if (!$file->is_external_file()) {
- $results['filesize_without_references'] += $filesize;
- }
- }
- return $results;
- }
- /**
- * Returns whether a draft area has exceeded/will exceed its size limit.
- *
- * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
- *
- * @param int $draftitemid the draft area item id.
- * @param int $areamaxbytes the maximum size allowed in this draft area.
- * @param int $newfilesize the size that would be added to the current area.
- * @param bool $includereferences true to include the size of the references in the area size.
- * @return bool true if the area will/has exceeded its limit.
- * @since Moodle 2.4
- */
- function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
- if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
- $draftinfo = file_get_draft_area_info($draftitemid);
- $areasize = $draftinfo['filesize_without_references'];
- if ($includereferences) {
- $areasize = $draftinfo['filesize'];
- }
- if ($areasize + $newfilesize > $areamaxbytes) {
- return true;
- }
- }
- return false;
- }
- /**
- * Returns whether a user has reached their draft area upload rate.
- *
- * @param int $userid The user id
- * @return bool
- */
- function file_is_draft_areas_limit_reached(int $userid): bool {
- global $CFG;
- $capacity = $CFG->draft_area_bucket_capacity ?? DRAFT_AREA_BUCKET_CAPACITY;
- $leak = $CFG->draft_area_bucket_leak ?? DRAFT_AREA_BUCKET_LEAK;
- $since = time() - floor($capacity / $leak); // The items that were in the bucket before this time are already leaked by now.
- // We are going to be a bit generous to the user when using the leaky bucket
- // algorithm below. We are going to assume that the bucket is empty at $since.
- // We have to do an assumption here unless we really want to get ALL user's draft
- // items without any limit and put all of them in the leaking bucket.
- // I decided to favour performance over accuracy here.
- $fs = get_file_storage();
- $items = $fs->get_user_draft_items($userid, $since);
- $items = array_reverse($items); // So that the items are sorted based on time in the ascending direction.
- // We only need to store the time that each element in the bucket is going to leak. So $bucket is array of leaking times.
- $bucket = [];
- foreach ($items as $item) {
- $now = $item->timemodified;
- // First let's see if items can be dropped from the bucket as a result of leakage.
- while (!empty($bucket) && ($now >= $bucket[0])) {
- array_shift($bucket);
- }
- // Calculate the time that the new item we put into the bucket will be leaked from it, and store it into the bucket.
- if ($bucket) {
- $bucket[] = max($bucket[count($bucket) - 1], $now) + (1 / $leak);
- } else {
- $bucket[] = $now + (1 / $leak);
- }
- }
- // Recalculate the bucket's content based on the leakage until now.
- $now = time();
- while (!empty($bucket) && ($now >= $bucket[0])) {
- array_shift($bucket);
- }
- return count($bucket) >= $capacity;
- }
- /**
- * Get used space of files
- * @global moodle_database $DB
- * @global stdClass $USER
- * @return int total bytes
- */
- function file_get_user_used_space() {
- global $DB, $USER;
- $usercontext = context_user::instance($USER->id);
- $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
- JOIN (SELECT contenthash, filename, MAX(id) AS id
- FROM {files}
- WHERE contextid = ? AND component = ? AND filearea != ?
- GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
- $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
- $record = $DB->get_record_sql($sql, $params);
- return (int)$record->totalbytes;
- }
- /**
- * Convert any string to a valid filepath
- * @todo review this function
- * @param string $str
- * @return string path
- */
- function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
- if ($str == '/' or empty($str)) {
- return '/';
- } else {
- return '/'.trim($str, '/').'/';
- }
- }
- /**
- * Generate a folder tree of draft area of current USER recursively
- *
- * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
- * @param int $draftitemid
- * @param string $filepath
- * @param mixed $data
- */
- function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
- global $USER, $OUTPUT, $CFG;
- $data->children = array();
- $context = context_user::instance($USER->id);
- $fs = get_file_storage();
- if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
- foreach ($files as $file) {
- if ($file->is_directory()) {
- $item = new stdClass();
- $item->sortorder = $file->get_sortorder();
- $item->filepath = $file->get_filepath();
- $foldername = explode('/', trim($item->filepath, '/'));
- $item->fullname = trim(array_pop($foldername), '/');
- $item->id = uniqid();
- file_get_drafarea_folders($draftitemid, $item->filepath, $item);
- $data->children[] = $item;
- } else {
- continue;
- }
- }
- }
- }
- /**
- * Listing all files (including folders) in current path (draft area)
- * used by file manager
- * @param int $draftitemid
- * @param string $filepath
- * @return stdClass
- */
- function file_get_drafarea_files($draftitemid, $filepath = '/') {
- global $USER, $OUTPUT, $CFG;
- $context = context_user::instance($USER->id);
- $fs = get_file_storage();
- $data = new stdClass();
- $data->path = array();
- $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
- // will be used to build breadcrumb
- $trail = '/';
- if ($filepath !== '/') {
- $filepath = file_correct_filepath($filepath);
- $parts = explode('/', $filepath);
- foreach ($parts as $part) {
- if ($part != '' && $part != null) {
- $trail .= ($part.'/');
- $data->path[] = array('name'=>$part, 'path'=>$trail);
- }
- }
- }
- $list = array();
- $maxlength = 12;
- if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
- foreach ($files as $file) {
- $item = new stdClass();
- $item->filename = $file->get_filename();
- $item->filepath = $file->get_filepath();
- $item->fullname = trim($item->filename, '/');
- $filesize = $file->get_filesize();
- $item->size = $filesize ? $filesize : null;
- $item->filesize = $filesize ? display_size($filesize) : '';
- $item->sortorder = $file->get_sortorder();
- $item->author = $file->get_author();
- $item->license = $file->get_license();
- $item->datemodified = $file->get_timemodified();
- $item->datecreated = $file->get_timecreated();
- $item->isref = $file->is_external_file();
- if ($item->isref && $file->get_status() == 666) {
- $item->originalmissing = true;
- }
- // find the file this draft file was created from and count all references in local
- // system pointing to that file
- $source = @unserialize($file->get_source());
- if (isset($source->original)) {
- $item->refcount = $fs->search_references_count($source->original);
- }
- if ($file->is_directory()) {
- $item->filesize = 0;
- $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
- $item->type = 'folder';
- $foldername = explode('/', trim($item->filepath, '/'));
- $item->fullname = trim(array_pop($foldername), '/');
- $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
- } else {
- // do NOT use file browser here!
- $item->mimetype = get_mimetype_description($file);
- if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
- $item->type = 'zip';
- } else {
- $item->type = 'file';
- }
- $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
- $item->url = $itemurl->out();
- $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
- $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
- // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
- // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
- // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
- // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
- // used by the widget to display a warning about the problem files.
- // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
- $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
- if ($item->status == 0) {
- if ($imageinfo = $file->get_imageinfo()) {
- $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
- 'oid' => $file->get_timemodified()));
- $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
- $item->image_width = $imageinfo['width'];
- $item->image_height = $imageinfo['height'];
- }
- }
- }
- $list[] = $item;
- }
- }
- $data->itemid = $draftitemid;
- $data->list = $list;
- return $data;
- }
- /**
- * Returns all of the files in the draftarea.
- *
- * @param int $draftitemid The draft item ID
- * @param string $filepath path for the uploaded files.
- * @return array An array of files associated with this draft item id.
- */
- function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
- $files = [];
- $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
- file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
- if (!empty($draftfiles)) {
- foreach ($draftfiles->list as $draftfile) {
- if ($draftfile->type == 'file') {
- $files[] = $draftfile;
- }
- }
- if (isset($draftfiles->children)) {
- foreach ($draftfiles->children as $draftfile) {
- $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
- }
- }
- }
- return $files;
- }
- /**
- * Returns draft area itemid for a given element.
- *
- * @category files
- * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
- * @return int the itemid, or 0 if there is not one yet.
- */
- function file_get_submitted_draft_itemid($elname) {
- // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
- if (!isset($_REQUEST[$elname])) {
- return 0;
- }
- if (is_array($_REQUEST[$elname])) {
- $param = optional_param_array($elname, 0, PARAM_INT);
- if (!empty($param['itemid'])) {
- $param = $param['itemid'];
- } else {
- debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
- return false;
- }
- } else {
- $param = optional_param($elname, 0, PARAM_INT);
- }
- if ($param) {
- require_sesskey();
- }
- return $param;
- }
- /**
- * Restore the original source field from draft files
- *
- * Do not use this function because it makes field files.source inconsistent
- * for draft area files. This function will be deprecated in 2.6
- *
- * @param stored_file $storedfile This only works with draft files
- * @return stored_file
- */
- function file_restore_source_field_from_draft_file($storedfile) {
- $source = @unserialize($storedfile->get_source());
- if (!empty($source)) {
- if (is_object($source)) {
- $restoredsource = $source->source;
- $storedfile->set_source($restoredsource);
- } else {
- throw new moodle_exception('invalidsourcefield', 'error');
- }
- }
- return $storedfile;
- }
- /**
- * Removes those files from the user drafts filearea which are not referenced in the editor text.
- *
- * @param stdClass $editor The online text editor element from the submitted form data.
- */
- function file_remove_editor_orphaned_files($editor) {
- global $CFG, $USER;
- // Find those draft files included in the text, and generate their hashes.
- $context = context_user::instance($USER->id);
- $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
- $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
- preg_match_all($pattern, $editor['text'], $matches);
- $usedfilehashes = [];
- foreach ($matches[1] as $matchedfilename) {
- $matchedfilename = urldecode($matchedfilename);
- $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
- $matchedfilename);
- }
- // Now, compare the hashes of all draft files, and remove those which don't match used files.
- $fs = get_file_storage();
- $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
- foreach ($files as $file) {
- $tmphash = $file->get_pathnamehash();
- if (!in_array($tmphash, $usedfilehashes)) {
- $file->delete();
- }
- }
- }
- /**
- * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
- * content from another draft area it's possible for a single textarea to reference multiple draft areas.
- *
- * @category files
- * @param int $draftitemid the id of the primary draft area.
- * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
- * @param int $usercontextid the user's context id.
- * @param string $text some html content that needs to have files copied to the correct draft area.
- * @param bool $forcehttps force https urls.
- *
- * @return string $text html content modified with new draft links
- */
- function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
- if (is_null($text)) {
- return null;
- }
- // Do not merge files, leave it as it was.
- if ($draftitemid === IGNORE_FILE_MERGE) {
- return null;
- }
- $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
- // No draft areas to rewrite.
- if (empty($urls)) {
- return $text;
- }
- foreach ($urls as $url) {
- // Do not process the "home" draft area.
- if ($url['itemid'] == $draftitemid) {
- continue;
- }
- // Decode the filename.
- $filename = urldecode($url['filename']);
- // Copy the file.
- file_copy_file_to_file_area($url, $filename, $draftitemid);
- // Rewrite draft area.
- $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
- }
- return $text;
- }
- /**
- * Rewrites a file area in arbitrary text.
- *
- * @param array $file General information about the file.
- * @param int $newid The new file area itemid.
- * @param string $text The text to rewrite.
- * @param bool $forcehttps force https urls.
- * @return string The rewritten text.
- */
- function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
- global $CFG;
- $wwwroot = $CFG->wwwroot;
- if ($forcehttps) {
- $wwwroot = str_replace('http://', 'https://', $wwwroot);
- }
- $search = [
- $wwwroot,
- $file['urlbase'],
- $file['contextid'],
- $file['component'],
- $file['filearea'],
- $file['itemid'],
- $file['filename']
- ];
- $replace = [
- $wwwroot,
- $file['urlbase'],
- $file['contextid'],
- $file['component'],
- $file['filearea'],
- $newid,
- $file['filename']
- ];
- $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
- return $text;
- }
- /**
- * Copies a file from one file area to another.
- *
- * @param array $file Information about the file to be copied.
- * @param string $filename The filename.
- * @param int $itemid The new file area.
- */
- function file_copy_file_to_file_area($file, $filename, $itemid) {
- $fs = get_file_storage();
- // Load the current file in the old draft area.
- $fileinfo = array(
- 'component' => $file['component'],
- 'filearea' => $file['filearea'],
- 'itemid' => $file['itemid'],
- 'contextid' => $file['contextid'],
- 'filepath' => '/',
- 'filename' => $filename
- );
- $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
- $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
- $newfileinfo = array(
- 'component' => $file['component'],
- 'filearea' => $file['filearea'],
- 'itemid' => $itemid,
- 'contextid' => $file['contextid'],
- 'filepath' => '/',
- 'filename' => $filename
- );
- $newcontextid = $newfileinfo['contextid'];
- $newcomponent = $newfileinfo['component'];
- $newfilearea = $newfileinfo['filearea'];
- $newitemid = $newfileinfo['itemid'];
- $newfilepath = $newfileinfo['filepath'];
- $newfilename = $newfileinfo['filename'];
- // Check if the file exists.
- if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
- $fs->create_file_from_storedfile($newfileinfo, $oldfile);
- }
- }
- /**
- * Saves files from a draft file area to a real one (merging the list of files).
- * Can rewrite URLs in some content at the same time if desired.
- *
- * @category files
- * @global stdClass $USER
- * @param int $draftitemid the id of the draft area to use. Normally obtained
- * from file_get_submitted_draft_itemid('elementname') or similar.
- * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
- * @param int $contextid This parameter and the next two identify the file area to save to.
- * @param string $component
- * @param string $filearea indentifies the file area.
- * @param int $itemid helps identifies the file area.
- * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
- * @param string $text some html content that needs to have embedded links rewritten
- * to the @@PLUGINFILE@@ form for saving in the database.
- * @param bool $forcehttps force https urls.
- * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
- */
- function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
- global $USER;
- // Do not merge files, leave it as it was.
- if ($draftitemid === IGNORE_FILE_MERGE) {
- // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
- return $text;
- }
- if ($itemid === false) {
- // Catch a potentially dangerous coding error.
- throw new coding_exception('file_save_draft_area_files was called with $itemid false. ' .
- "This suggests a bug, because it would wipe all ($contextid, $component, $filearea) files.");
- }
- $usercontext = context_user::instance($USER->id);
- $fs = get_file_storage();
- $options = (array)$options;
- if (!isset($options['subdirs'])) {
- $options['subdirs'] = false;
- }
- if (!isset($options['maxfiles'])) {
- $options['maxfiles'] = -1; // unlimited
- }
- if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
- $options['maxbytes'] = 0; // unlimited
- }
- if (!isset($options['areamaxbytes'])) {
- $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
- }
- $allowreferences = true;
- if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
- // we assume that if $options['return_types'] is NOT specified, we DO allow references.
- // this is not exactly right. BUT there are many places in code where filemanager options
- // are not passed to file_save_draft_area_files()
- $allowreferences = false;
- }
- // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
- // areas and need to be copied into the current draft area.
- $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
- // Check if the draft area has exceeded the authorised limit. This should never happen as validation
- // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
- // anything at all in the next area.
- if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
- return null;
- }
- $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
- $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
- // One file in filearea means it is empty (it has only top-level directory '.').
- if (count($draftfiles) > 1 || count($oldfiles) > 1) {
- // we have to merge old and new files - we want to keep file ids for files that were not changed
- // we change time modified for all new and changed files, we keep time created as is
- $newhashes = array();
- $filecount = 0;
- $context = context::instance_by_id($contextid, MUST_EXIST);
- foreach ($draftfiles as $file) {
- if (!$options['subdirs'] && $file->get_filepath() !== '/') {
- continue;
- }
- if (!$allowreferences && $file->is_external_file()) {
- continue;
- }
- if (!$file->is_directory()) {
- // Check to see if this file was uploaded by someone who can ignore the file size limits.
- $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
- if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
- && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
- // Oversized file.
- continue;
- }
- if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
- // more files - should not get here at all
- continue;
- }
- $filecount++;
- }
- $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
- $newhashes[$newhash] = $file;
- }
- // Loop through oldfiles and decide which we need to delete and which to update.
- // After this cycle the array $newhashes will only contain the files that need to be added.
- foreach ($oldfiles as $oldfile) {
- $oldhash = $oldfile->get_pathnamehash();
- if (!isset($newhashes[$oldhash])) {
- // delete files not needed any more - deleted by user
- $oldfile->delete();
- continue;
- }
- $newfile = $newhashes[$oldhash];
- // Now we know that we have $oldfile and $newfile for the same path.
- // Let's check if we can update this file or we need to delete and create.
- if ($newfile->is_directory()) {
- // Directories are always ok to just update.
- } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
- // File has the 'original' - we need to update the file (it may even have not been changed at all).
- $original = file_storage::unpack_reference($source->original);
- if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
- // Very odd, original points to another file. Delete and create file.
- $oldfile->delete();
- continue;
- }
- } else {
- // The same file name but absence of 'original' means that file was deteled and uploaded again.
- // By deleting and creating new file we properly manage all existing references.
- $oldfile->delete();
- continue;
- }
- // status changed, we delete old file, and create a new one
- if ($oldfile->get_status() != $newfile->get_status()) {
- // file was changed, use updated with new timemodified data
- $oldfile->delete();
- // This file will be added later
- continue;
- }
- // Updated author
- if ($oldfile->get_author() != $newfile->get_author()) {
- $oldfile->set_author($newfile->get_author());
- }
- // Updated license
- if ($oldfile->get_license() != $newfile->get_license()) {
- $oldfile->set_license($newfile->get_license());
- }
- // Updated file source
- // Field files.source for draftarea files contains serialised object with source and original information.
- // We only store the source part of it for non-draft file area.
- $newsource = $newfile->get_source();
- if ($source = @unserialize($newfile->get_source())) {
- $newsource = $source->source;
- }
- if ($oldfile->get_source() !== $newsource) {
- $oldfile->set_source($newsource);
- }
- // Updated sort order
- if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
- $oldfile->set_sortorder($newfile->get_sortorder());
- }
- // Update file timemodified
- if ($oldfile->get_…
Large files files are truncated, but you can click here to view the full file