Moodle PHP Documentation 4.3
Moodle 4.3.5 (Build: 20240610) (7dcfaa79f78)
core_files

Namespaces

namespace  core
  
 
namespace  core_files
  
 
namespace  core_files\external
  
 
namespace  core_files\external\delete
  
 
namespace  core_files\external\get
  
 
namespace  core_files\local\archive_writer
  
 
namespace  core_files\privacy
  
 
namespace  core_files\reportbuilder\datasource
  
 
namespace  core_files\reportbuilder\local\entities
  
 
namespace  core_files\task
  
 

Classes

class  core\content
 The Content API allows all parts of Moodle to determine details about content within a component, or plugintype. More...
 
class  core_files\archive_writer
 Each file archive type must extend this class. More...
 
class  core_files\conversion
 Class representing a conversion currently in progress. More...
 
class  core_files\converter
 Class for converting files between different formats using unoconv. More...
 
interface  core_files\converter_interface
 Class for converting files between different file formats. More...
 
class  core_files\external\delete\draft
 This is the external method for deleting draft files. More...
 
class  core_files\external\get\unused_draft
 Generate a new draft itemid for the current user. More...
 
class  core_files\external\stored_file_exporter
 
interface  core_files\local\archive_writer\file_writer_interface
 Interface used by archives that write to files. More...
 
interface  core_files\local\archive_writer\stream_writer_interface
 Interface used by archives that write to streams. More...
 
class  core_files\local\archive_writer\zip_writer
 Class used for creating ZIP archives. More...
 
class  core_files\privacy\provider
 Data provider class. More...
 
class  core_files\reportbuilder\datasource\files
 
class  core_files\reportbuilder\local\entities\file
 
class  core_files\task\conversion_cleanup_task
 A scheduled task to clear up old conversion records. More...
 
class  core_files_external
 Files external functions. More...
 
class  core_form\privacy\provider
 Implements the privacy API for the core_form subsystem. More...
 
class  curl
 RESTful cURL class. More...
 
class  curl_cache
 This class is used by cURL class, use case: More...
 
class  file_access_exception
 No file access exception. More...
 
class  file_archive
 Each file archive type must extend this class. More...
 
class  file_browser
 This class provides the main entry point for other code wishing to get information about files. More...
 
class  file_exception
 Basic file related exception class. More...
 
class  file_info
 Base class for things in the tree navigated by file_browser. More...
 
class  file_info_area_backup_section
 Implementation of course section backup area. More...
 
class  file_info_area_course_legacy
 Subclass of file_info_stored for files in the course files area. More...
 
class  file_info_area_course_section
 Represents a course category context in the tree navigated by file_browser. More...
 
class  file_info_context_course
 Represents a course context in the tree navigated by file_browser. More...
 
class  file_info_context_coursecat
 Represents a course category context in the tree navigated by file_browser. More...
 
class  file_info_context_module
 Represents a module context in the tree navigated by file_browser. More...
 
class  file_info_context_system
 Represents the system context in the tree navigated by file_browser. More...
 
class  file_info_context_user
 Represents a user context in the tree navigated by file_browser. More...
 
class  file_info_stored
 Represents an actual file or folder - a row in the file table in the tree navigated by file_browser. More...
 
class  file_packer
 Abstract class for archiving of files. More...
 
class  file_pool_content_exception
 Hash file content problem exception. More...
 
interface  file_progress
 
class  file_reference_exception
 Problem with records in the {files_reference} table. More...
 
class  file_storage
 File storage class used for low level access to stored files. More...
 
class  file_system
 
class  file_system_filedir
 File system class used for low level access to real files in filedir. More...
 
class  mbz_packer
 Utility class - handles all packing/unpacking of .mbz files. More...
 
class  stored_file
 Class representing local files stored in a sha1 file pool. More...
 
class  stored_file_creation_exception
 Cannot create file exception. More...
 
class  tgz_extractor
 Extracts .tar.gz files (POSIX format). More...
 
interface  tgz_extractor_handler
 Interface for callback from tgz_extractor\extract. More...
 
class  tgz_packer
 Utility class - handles all packing/unpacking of .tar.gz files. More...
 
class  tgz_packer_extract_to_pathname
 Handles extraction to pathname. More...
 
class  tgz_packer_extract_to_storage
 Handles extraction to file storage. More...
 
class  virtual_root_file
 Represents the root directory of an empty file area in the tree navigated by file_browser. More...
 
class  zip_archive
 Zip file archive class. More...
 
class  zip_packer
 Utility class - handles all zipping and unzipping operations. More...
 

Functions

 byteserving_send_file ($handle, $mimetype, $ranges, $filesize)
 Send requested byterange of file.
 
 download_file_content ($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false)
 Fetches content of file from Internet (using proxy if defined).
 
 file_area_contains_subdirs (context $context, $component, $filearea, $itemid)
 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.
 
 file_copy_file_to_file_area ($file, $filename, $itemid)
 Copies a file from one file area to another.
 
 file_correct_filepath ($str)
 Convert any string to a valid filepath.
 
stdClass file_encode_url ($urlbase, $path, $forcedownload=false, $https=false)
 Encodes file serving url.
 
 file_extension_icon ($filename, $unused=null)
 Returns the relative icon path for a given file name.
 
 file_extension_in_typegroup ($filename, $groups, $checktype=false)
 Checks if file with name $filename has one of the extensions in groups $groups.
 
 file_file_icon ($file, $unused=null)
 Return the relative icon path for a given file.
 
 file_folder_icon ($unused=null)
 Return the relative icon path for a folder image.
 
 file_get_all_files_in_draftarea (int $draftitemid, string $filepath='/')
 Returns all of the files in the draftarea.
 
 file_get_drafarea_files ($draftitemid, $filepath='/')
 Listing all files (including folders) in current path (draft area) used by file manager.
 
 file_get_drafarea_folders ($draftitemid, $filepath, &$data)
 Generate a folder tree of draft area of current USER recursively.
 
stdClass file_get_draft_area_info ($draftitemid, $filepath='/')
 Returns information about files in a draft area.
 
 file_get_file_area_info ($contextid, $component, $filearea, $itemid=0, $filepath='/')
 Returns information about files in an area.
 
 file_get_submitted_draft_itemid ($elname)
 Returns draft area itemid for a given element.
 
 file_get_typegroup ($element, $groups)
 Returns array of elements of type $element in type group(s)
 
moodle_database file_get_unused_draft_itemid ()
 Generate a draft itemid.
 
 file_get_upload_error ($errorcode)
 Returns description of upload error.
 
moodle_database file_get_user_used_space ()
 Get used space of files $DB @global stdClass $USER.
 
 file_is_draft_area_limit_reached ($draftitemid, $areamaxbytes, $newfilesize=0, $includereferences=false)
 Returns whether a draft area has exceeded/will exceed its size limit.
 
 file_is_draft_areas_limit_reached (int $userid)
 Returns whether a user has reached their draft area upload rate.
 
 file_is_executable ($filename)
 Tells whether the filename is executable.
 
 file_is_svg_image_from_mimetype (string $mimetype)
 Attempt to determine whether the specified mime-type is an SVG image or not.
 
 file_merge_draft_area_into_draft_area ($getfromdraftid, $mergeintodraftid)
 Merge files from two draftarea areas.
 
 file_merge_draft_areas ($draftitemid, $usercontextid, $text, $forcehttps=false)
 Finds all draft areas used in a textarea and copies the files into the primary textarea.
 
 file_merge_files_from_draft_area_into_filearea ($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null)
 Add files from a draft area into a final area.
 
 file_mimetype_icon ($mimetype, $unused=null)
 Returns the relative icon path for a given mime type.
 
 file_mimetype_in_typegroup ($mimetype, $groups)
 Checks if mimetype $mimetype belongs to one of the groups $groups.
 
 file_overwrite_existing_draftfile (stored_file $newfile, stored_file $existingfile)
 Overwrite an existing file in a draft area.
 
 file_pluginfile ($relativepath, $forcedownload, $preview=null, $offline=false, $embed=false)
 This function delegates file serving to individual plugins.
 
 file_postupdate_standard_editor ($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null)
 Prepares the content of the 'editor' form element with embedded media files to be saved in database.
 
 file_postupdate_standard_filemanager ($data, $field, array $options, $context, $component, $filearea, $itemid)
 Saves files modified by File manager formslib element.
 
stdClass file_prepare_draft_area (&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null)
 Initialise a draft file area from a real one by copying the files.
 
 file_prepare_standard_editor ($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null)
 Prepares 'editor' formslib element from data in database.
 
 file_prepare_standard_filemanager ($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null)
 Saves text and files modified by Editor formslib element.
 
 file_remove_editor_orphaned_files ($editor)
 Removes those files from the user drafts filearea which are not referenced in the editor text.
 
 file_replace_file_area_in_text ($file, $newid, $text, $forcehttps=false)
 Rewrites a file area in arbitrary text.
 
moodle_database file_reset_sortorder ($contextid, $component, $filearea, $itemid=false)
 reset file sort order number to 0 $DB
 
 file_restore_source_field_from_draft_file ($storedfile)
 Restore the original source field from draft files.
 
 file_rewrite_pluginfile_urls ($text, $file, $contextid, $component, $filearea, $itemid, array $options=null)
 Convert encoded URLs in $text from the @PLUGINFILE@/... form to an actual URL.
 
 file_rewrite_urls_to_pluginfile ($text, $draftitemid, $forcehttps=false)
 Convert the draft file area URLs in some content to @PLUGINFILE@ tokens ready to be saved in the database.
 
 file_safe_save_content ($content, $destination)
 Safely save content to a certain path.
 
stdClass file_save_draft_area_files ($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false)
 Saves files from a draft file area to a real one (merging the list of files).
 
moodle_database file_set_sortorder ($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder)
 Set file sort order.
 
 format_array_postdata_for_curlcall ($arraydata, $currentdata, &$data)
 Recursive function formating an array in POST parameter.
 
 format_postdata_for_curlcall ($postdata)
 Transform a PHP array into POST parameter (see the recursive function format_array_postdata_for_curlcall)
 
 fulldelete ($location)
 Recursively delete the file or folder with path $location.
 
 get_mimetype_description ($obj, $capitalise=false)
 Obtains descriptions for file types (e.g.
 
 get_mimetype_for_sending ($filename='')
 Determine a file's MIME type based on the given filename using the function mimeinfo.
 
get_mimetypes_array ()
 Returns a list of information about file types based on extensions.
 
 get_moodle_proxy_url ()
 Returns the moodle proxy configuration as a formatted url.
 
 mimeinfo ($element, $filename)
 Obtains information about a filetype based on its extension.
 
 mimeinfo_from_type ($element, $mimetype)
 Obtains information about a filetype based on the MIME type rather than the other way around.
 
 readfile_accel ($file, $mimetype, $accelerate)
 Enhanced readfile() with optional acceleration.
 
 readfile_allow_large ($path, $filesize=-1)
 The readfile function can fail when files are larger than 2GB (even on 64-bit platforms).
 
 readstring_accel ($string, $mimetype, $accelerate=false)
 Similar to readfile_accel() but designed for strings.
 
 send_content_uncached ($content, $filename)
 Serve content which is not meant to be cached.
 
 send_file ($path, $filename, $lifetime=null, $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false, array $options=array())
 Handles the sending of file data to the user's browser, including support for byteranges etc.
 
stdClass send_file_not_found ()
 Requested file is not found or not accessible, does not return, terminates script.
 
 send_header_404 ()
 Helper function to send correct 404 for server.
 
 send_stored_file ($storedfile, $lifetime=null, $filter=0, $forcedownload=false, array $options=array())
 Handles the sending of file data to the user's browser, including support for byteranges etc.
 
 send_temp_file ($path, $filename, $pathisstring=false)
 Handles the sending of temporary file to user, download is forced.
 
 send_temp_file_finished ($path)
 Internal callback function used by send_temp_file()
 
 xsendfile ($filepath)
 Serve file using X-Sendfile header, this needs special server module or configuration.
 

Variables

global core_files\external\delete::$CFG
 
global core_files\external\get::$CFG
 
const BYTESERVING_BOUNDARY 's1k2o3d4a5k6s7'
 BYTESERVING_BOUNDARY - string unique string constant.
 
const DRAFT_AREA_BUCKET_CAPACITY 50
 Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
 
const DRAFT_AREA_BUCKET_LEAK 0.2
 Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
 
const FILE_AREA_MAX_BYTES_UNLIMITED -1
 Unlimited area size constant.
 
const IGNORE_FILE_MERGE -1
 Do not process file merging when working with draft area files.
 

Detailed Description

Function Documentation

◆ byteserving_send_file()

byteserving_send_file ( $handle,
$mimetype,
$ranges,
$filesize )

Send requested byterange of file.

Parameters
resource$handleA file handle
string$mimetypeThe mimetype for the output
array$rangesAn array of ranges to send
string$filesizeThe size of the content if only one range is used

◆ download_file_content()

download_file_content ( $url,
$headers = null,
$postdata = null,
$fullresponse = false,
$timeout = 300,
$connecttimeout = 20,
$skipcertverify = false,
$tofile = NULL,
$calctimeout = false )

Fetches content of file from Internet (using proxy if defined).

Uses cURL extension if present. Due to security concerns only downloads from http(s) sources are supported.

Parameters
string$urlfile url starting with http(s)://
array$headershttp headers, null if none. If set, should be an associative array of header name => value pairs.
array$postdataarray means use POST request with given parameters
bool$fullresponsereturn headers, responses, etc in a similar way snoopy does (if false, just returns content)
int$timeouttimeout for complete download process including all file transfer (default 5 minutes)
int$connecttimeouttimeout for connection to server; this is the timeout that usually happens if the remote server is completely down (default 20 seconds); may not work when using proxy
bool$skipcertverifyIf true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
string$tofilestore the downloaded content to file instead of returning it.
bool$calctimeoutfalse by default, true enables an extra head request to try and determine filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
Return values
stdClass|string|boolstdClass object if $fullresponse is true, false if request failed, true if file downloaded into $tofile successfully or the file content as a string.

◆ file_area_contains_subdirs()

file_area_contains_subdirs ( context $context,
$component,
$filearea,
$itemid )

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.

Parameters
context$context
string$component
string$filearea
string$itemid
Return values
bool

◆ file_copy_file_to_file_area()

file_copy_file_to_file_area ( $file,
$filename,
$itemid )

Copies a file from one file area to another.

Parameters
array$fileInformation about the file to be copied.
string$filenameThe filename.
int$itemidThe new file area.

◆ file_correct_filepath()

file_correct_filepath ( $str)

Convert any string to a valid filepath.

Todo
review this function
Parameters
string$str
Return values
stringpath

◆ file_encode_url()

stdClass file_encode_url ( $urlbase,
$path,
$forcedownload = false,
$https = false )

Encodes file serving url.

Deprecated
use moodle_url factory methods instead
Todo
MDL-31071 deprecate this function $CFG
Parameters
string$urlbase
string$path/filearea/itemid/dir/dir/file.exe
bool$forcedownload
bool$httpshttps url required
Return values
stringencoded file url

◆ file_extension_icon()

file_extension_icon ( $filename,
$unused = null )

Returns the relative icon path for a given file name.

This function should be used in conjunction with $OUTPUT->image_url to produce a return the full path to an icon.

$filename = '.jpg'; $icon = $OUTPUT->image_url(file_extension_icon($filename))->out(); echo html_writer\empty_tag('img', array('src' => $icon, 'alt' => '...'));

Todo

MDL-31074 When an $OUTPUT->icon method is available this function should be altered to conform with that.

MDL-31074 Implement $size

Parameters
string$filenameThe filename to get the icon for
null$unusedThis parameter has been deprecated since 4.3 and should not be used anymore.
Return values
string

◆ file_extension_in_typegroup()

file_extension_in_typegroup ( $filename,
$groups,
$checktype = false )

Checks if file with name $filename has one of the extensions in groups $groups.

See also
get_mimetypes_array()
Parameters
string$filenamename of the file to check
string | array$groupsone group or array of groups to check
bool$checktypeif true and extension check fails, find the mimetype and check if file mimetype is in mimetypes in groups $groups
Return values
bool

◆ file_file_icon()

file_file_icon ( $file,
$unused = null )

Return the relative icon path for a given file.

Usage: // $file - instance of stored_file or file_info $icon = $OUTPUT->image_url(file_file_icon($file))->out(); echo html_writer\empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file))); or echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));

Parameters
stored_file | file_info | stdClass | array$file(in case of object attributes $file->filename and $file->mimetype are expected)
null$unusedThis parameter has been deprecated since 4.3 and should not be used anymore.
Return values
string

◆ file_folder_icon()

file_folder_icon ( $unused = null)

Return the relative icon path for a folder image.

Usage: $icon = $OUTPUT->image_url(file_folder_icon())->out(); echo html_writer\empty_tag('img', array('src' => $icon)); or echo $OUTPUT->pix_icon(file_folder_icon(), '');

Parameters
null$unusedThis parameter has been deprecated since 4.3 and should not be used anymore.
Return values
string

◆ file_get_all_files_in_draftarea()

file_get_all_files_in_draftarea ( int $draftitemid,
string $filepath = '/' )

Returns all of the files in the draftarea.

Parameters
int$draftitemidThe draft item ID
string$filepathpath for the uploaded files.
Return values
arrayAn array of files associated with this draft item id.

◆ file_get_drafarea_files()

file_get_drafarea_files ( $draftitemid,
$filepath = '/' )

Listing all files (including folders) in current path (draft area) used by file manager.

Parameters
int$draftitemid
string$filepath
Return values
stdClass

◆ file_get_drafarea_folders()

file_get_drafarea_folders ( $draftitemid,
$filepath,
& $data )

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)
Parameters
int$draftitemid
string$filepath
mixed$data

◆ file_get_draft_area_info()

stdClass file_get_draft_area_info ( $draftitemid,
$filepath = '/' )

Returns information about files in a draft area.

$CFG @global stdClass $USER

Parameters
int$draftitemidthe draft area item id.
string$filepathpath to the directory from which the information have to be retrieved.
Return values
arraywith 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).

◆ file_get_file_area_info()

file_get_file_area_info ( $contextid,
$component,
$filearea,
$itemid = 0,
$filepath = '/' )

Returns information about files in an area.

Parameters
int$contextidcontext id
string$componentcomponent
string$fileareafile area name
int$itemiditem id or all files if not specified
string$filepathpath to the directory from which the information have to be retrieved.
Return values
arraywith 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

◆ file_get_submitted_draft_itemid()

file_get_submitted_draft_itemid ( $elname)

Returns draft area itemid for a given element.

Parameters
string$elnamename of formlib editor element, or a hidden form field that stores the draft area item id, etc.
Return values
intthe itemid, or 0 if there is not one yet.

◆ file_get_typegroup()

file_get_typegroup ( $element,
$groups )

Returns array of elements of type $element in type group(s)

Parameters
string$elementname of the element we are interested in, usually 'type' or 'extension'
string | array$groupsone group or array of groups/extensions/mimetypes
Return values
array

◆ file_get_unused_draft_itemid()

moodle_database file_get_unused_draft_itemid ( )

Generate a draft itemid.

$DB @global stdClass $USER

Return values
inta random but available draft itemid that can be used to create a new draft file area.

◆ file_get_upload_error()

file_get_upload_error ( $errorcode)

Returns description of upload error.

Parameters
int$errorcodefound in $_FILES['filename.ext']['error']
Return values
stringerror description string, '' if ok

◆ file_get_user_used_space()

moodle_database file_get_user_used_space ( )

Get used space of files $DB @global stdClass $USER.

Return values
inttotal bytes

◆ file_is_draft_area_limit_reached()

file_is_draft_area_limit_reached ( $draftitemid,
$areamaxbytes,
$newfilesize = 0,
$includereferences = false )

Returns whether a draft area has exceeded/will exceed its size limit.

Please note that the unlimited value for $areamaxbytes is -1 FILE_AREA_MAX_BYTES_UNLIMITED, not 0.

Parameters
int$draftitemidthe draft area item id.
int$areamaxbytesthe maximum size allowed in this draft area.
int$newfilesizethe size that would be added to the current area.
bool$includereferencestrue to include the size of the references in the area size.
Return values
booltrue if the area will/has exceeded its limit.
Since
Moodle 2.4

◆ file_is_draft_areas_limit_reached()

file_is_draft_areas_limit_reached ( int $userid)

Returns whether a user has reached their draft area upload rate.

Parameters
int$useridThe user id
Return values
bool

◆ file_is_executable()

file_is_executable ( $filename)

Tells whether the filename is executable.

@externalurl http://php.net/manual/en/function.is-executable.php @externalurl https://bugs.php.net/bug.php?id=41062

Parameters
string$filenamePath to the file.
Return values
boolTrue if the filename exists and is executable; otherwise, false.

◆ file_is_svg_image_from_mimetype()

file_is_svg_image_from_mimetype ( string $mimetype)

Attempt to determine whether the specified mime-type is an SVG image or not.

Parameters
string$mimetypeMime-type
Return values
boolTrue if it is an SVG file

◆ file_merge_draft_area_into_draft_area()

file_merge_draft_area_into_draft_area ( $getfromdraftid,
$mergeintodraftid )

Merge files from two draftarea areas.

This does not handle conflict resolution, files in the destination area which appear to be more recent will be kept disregarding the intended ones.

Parameters
int$getfromdraftidthe id of the draft area where are the files to merge.
int$mergeintodraftidthe id of the draft area where new files will be merged.
Exceptions
coding_exception
Since
Moodle 3.2

◆ file_merge_draft_areas()

file_merge_draft_areas ( $draftitemid,
$usercontextid,
$text,
$forcehttps = false )

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.

Parameters
int$draftitemidthe 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.
int$usercontextidthe user's context id.
string$textsome html content that needs to have files copied to the correct draft area.
bool$forcehttpsforce https urls.
Return values
string\$texthtml content modified with new draft links

◆ file_merge_files_from_draft_area_into_filearea()

file_merge_files_from_draft_area_into_filearea ( $draftitemid,
$contextid,
$component,
$filearea,
$itemid,
array $options = null )

Add files from a draft area into a final area.

Most of the time you do not want to use this. It is intended to be used by asynchronous services which cannot direcly manipulate a final area through a draft area. Instead they add files to a new draft area and merge that new draft into the final area when ready.

Parameters
int$draftitemidthe id of the draft area to use.
int$contextidthis parameter and the next two identify the file area to save to.
string$componentcomponent name
string$fileareaindentifies the file area
int$itemididentifies the item id or false for all items in the file area
array$optionsarea options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
See also
file_save_draft_area_files
Since
Moodle 3.2

◆ file_mimetype_icon()

file_mimetype_icon ( $mimetype,
$unused = null )

Returns the relative icon path for a given mime type.

This function should be used in conjunction with $OUTPUT->image_url to produce a return the full path to an icon.

$mimetype = 'image/jpg'; $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out(); echo html_writer\empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));

Todo
MDL-31074 When an $OUTPUT->icon method is available this function should be altered to conform with that.
Parameters
string$mimetypeThe mimetype to fetch an icon for
null$unusedThis parameter has been deprecated since 4.3 and should not be used anymore.
Return values
stringThe relative path to the icon

◆ file_mimetype_in_typegroup()

file_mimetype_in_typegroup ( $mimetype,
$groups )

Checks if mimetype $mimetype belongs to one of the groups $groups.

See also
get_mimetypes_array()
Parameters
string$mimetype
string | array$groupsone group or array of groups to check
Return values
bool

◆ file_overwrite_existing_draftfile()

file_overwrite_existing_draftfile ( stored_file $newfile,
stored_file $existingfile )

Overwrite an existing file in a draft area.

Parameters
stored_file$newfilethe new file with the new content and meta-data
stored_file$existingfilethe file that will be overwritten
Exceptions
moodle_exception
Since
Moodle 3.2

◆ file_pluginfile()

file_pluginfile ( $relativepath,
$forcedownload,
$preview = null,
$offline = false,
$embed = false )

This function delegates file serving to individual plugins.

Parameters
string$relativepath
bool$forcedownload
null | string$previewthe preview mode, defaults to serving the original file
boolean$offlineIf offline is requested - don't serve a redirect to an external file, return a file suitable for viewing offline (e.g. mobile app).
bool$embedWhether this file will be served embed into an iframe.
Todo
MDL-31088 file serving improments

◆ file_postupdate_standard_editor()

file_postupdate_standard_editor ( $data,
$field,
array $options,
$context,
$component = null,
$filearea = null,
$itemid = null )

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.

Parameters
stdClass$dataraw data submitted by the form
string$fieldname of the database field containing the html with embedded media files
array$optionseditor options (trusttext, subdirs, maxfiles, maxbytes etc.)
stdClass$contextcontext, required for existing data
string$componentfile component
string$fileareafile area name
int$itemiditem id, required if item exists
Return values
stdClassmodified data object

◆ file_postupdate_standard_filemanager()

file_postupdate_standard_filemanager ( $data,
$field,
array $options,
$context,
$component,
$filearea,
$itemid )

Saves files modified by File manager formslib element.

Todo
MDL-31073 review this function
Parameters
stdClass$data$database entry field
string$fieldname of data field
array$optionsvarious options
stdClass$contextcontext - must already exist
string$component
string$fileareafile area name
int$itemidmust already exist, usually means data is in db
Return values
stdClassmodified data obejct

◆ file_prepare_draft_area()

stdClass file_prepare_draft_area ( & $draftitemid,
$contextid,
$component,
$filearea,
$itemid,
array $options = null,
$text = null )

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');

$CFG @global stdClass $USER

Parameters
int$draftitemidthe id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
int$contextidThis parameter and the next two identify the file area to copy files from.
string$component
string$fileareahelps indentify the file area.
int$itemidhelps identify the file area. Can be null if there are no files yet.
array$optionstext and file options ('subdirs'=>false, 'forcehttps'=>false)
string$textsome html content that needs to have embedded links rewritten to point to the draft area.
Return values
string|nullreturns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.

◆ file_prepare_standard_editor()

file_prepare_standard_editor ( $data,
$field,
array $options,
$context = null,
$component = null,
$filearea = null,
$itemid = null )

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.

Parameters
stdClass$datadatabase field that holds the html text with embedded media
string$fieldthe name of the database field that holds the html text with embedded media
array$optionseditor options (like maxifiles, maxbytes etc.)
stdClass$contextcontext of the editor
string$component
string$fileareafile area name
int$itemiditem id, required if item exists
Return values
stdClassmodified data object

◆ file_prepare_standard_filemanager()

file_prepare_standard_filemanager ( $data,
$field,
array $options,
$context = null,
$component = null,
$filearea = null,
$itemid = null )

Saves text and files modified by Editor formslib element.

Parameters
stdClass$data$database entry field
string$fieldname of data field
array$optionsvarious options
stdClass$contextcontext - must already exist
string$component
string$fileareafile area name
int$itemidmust already exist, usually means data is in db
Return values
stdClassmodified data obejct

◆ file_remove_editor_orphaned_files()

file_remove_editor_orphaned_files ( $editor)

Removes those files from the user drafts filearea which are not referenced in the editor text.

Parameters
stdClass$editorThe online text editor element from the submitted form data.

◆ file_replace_file_area_in_text()

file_replace_file_area_in_text ( $file,
$newid,
$text,
$forcehttps = false )

Rewrites a file area in arbitrary text.

Parameters
array$fileGeneral information about the file.
int$newidThe new file area itemid.
string$textThe text to rewrite.
bool$forcehttpsforce https urls.
Return values
stringThe rewritten text.

◆ file_reset_sortorder()

moodle_database file_reset_sortorder ( $contextid,
$component,
$filearea,
$itemid = false )

reset file sort order number to 0 $DB

Parameters
int$contextidthe context id
string$component
string$fileareafile area.
int | bool$itemiditemid.
Return values
bool

◆ file_restore_source_field_from_draft_file()

file_restore_source_field_from_draft_file ( $storedfile)

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

Parameters
stored_file$storedfileThis only works with draft files
Return values
stored_file

◆ file_rewrite_pluginfile_urls()

file_rewrite_pluginfile_urls ( $text,
$file,
$contextid,
$component,
$filearea,
$itemid,
array $options = null )

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.

Parameters
string$textThe content that may contain ULRs in need of rewriting.
string$fileThe script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
int$contextidThis parameter and the next two identify the file area to use.
string$component
string$fileareahelps identify the file area.
int$itemidhelps identify the file area.
array$optionsbool $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.

◆ file_rewrite_urls_to_pluginfile()

file_rewrite_urls_to_pluginfile ( $text,
$draftitemid,
$forcehttps = false )

Convert the draft file area URLs in some content to @PLUGINFILE@ tokens ready to be saved in the database.

Normally, this is done automatically by file_save_draft_area_files().

Parameters
string$textthe content to process.
int$draftitemidthe draft file area the content was using.
bool$forcehttpswhether the content contains https URLs. Default false.
Return values
stringthe processed content.

◆ file_safe_save_content()

file_safe_save_content ( $content,
$destination )

Safely save content to a certain path.

This function tries hard to be atomic by first copying the content to a separate file, and then moving the file across. It also prevents the user to abort a request to prevent half-safed files.

This function is intended to be used when saving some content to cache like $CFG->localcachedir. If you're not caching a file you should use the File API.

Parameters
string$contentThe file content.
string$destinationThe absolute path of the final file.
Return values
void

◆ file_save_draft_area_files()

stdClass file_save_draft_area_files ( $draftitemid,
$contextid,
$component,
$filearea,
$itemid,
array $options = null,
$text = null,
$forcehttps = false )

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.

$USER

Parameters
int$draftitemidthe 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.
int$contextidThis parameter and the next two identify the file area to save to.
string$component
string$fileareaindentifies the file area.
int$itemidhelps identifies the file area.
array$optionsarea options (subdirs=>false, maxfiles=-1, maxbytes=0)
string$textsome html content that needs to have embedded links rewritten to the @PLUGINFILE@ form for saving in the database.
bool$forcehttpsforce https urls.
Return values
string|nullif $text was passed in, the rewritten $text is returned. Otherwise NULL.

◆ file_set_sortorder()

moodle_database file_set_sortorder ( $contextid,
$component,
$filearea,
$itemid,
$filepath,
$filename,
$sortorder )

Set file sort order.

$DB

Parameters
int$contextidthe context id
string$componentfile component
string$fileareafile area.
int$itemiditemid.
string$filepathfile path.
string$filenamefile name.
int$sortorderthe sort order of file.
Return values
bool

◆ format_array_postdata_for_curlcall()

format_array_postdata_for_curlcall ( $arraydata,
$currentdata,
& $data )

Recursive function formating an array in POST parameter.

Parameters
array$arraydata- the array that we are going to format and add into &$data array
string$currentdata- a row of the final postdata array at instant T when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
array$data- the final data array containing all POST parameters : 1 row = 1 parameter

◆ format_postdata_for_curlcall()

format_postdata_for_curlcall ( $postdata)

Transform a PHP array into POST parameter (see the recursive function format_array_postdata_for_curlcall)

Parameters
array$postdata
Return values
arraycontaining all POST parameters (1 row = 1 POST parameter)

◆ fulldelete()

fulldelete ( $location)

Recursively delete the file or folder with path $location.

That is, if it is a file delete it. If it is a folder, delete all its content then delete it. If $location does not exist to start, that is not considered an error.

Parameters
string$locationthe path to remove.
Return values
bool

◆ get_mimetype_description()

get_mimetype_description ( $obj,
$capitalise = false )

Obtains descriptions for file types (e.g.

'Microsoft Word document') from the mimetypes.php language file.

Parameters
mixed$obj- instance of stored_file or file_info or array/stdClass with field 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to have filename); In case of array/stdClass the field 'mimetype' is optional.
bool$capitaliseIf true, capitalises first character of result
Return values
stringText description

◆ get_mimetype_for_sending()

get_mimetype_for_sending ( $filename = '')

Determine a file's MIME type based on the given filename using the function mimeinfo.

This function retrieves a file's MIME type for a file that will be sent to the user. This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file. Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default MIME type which should tell the browser "I don't know what type of file this is, so just download it.".

Parameters
string$filenameThe file's filename.
Return values
stringThe file's MIME type or 'application/octet-stream' if it cannot be determined.

◆ get_mimetypes_array()

& get_mimetypes_array ( )

Returns a list of information about file types based on extensions.

The following elements expected in value array for each extension: 'type' - mimetype 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon; also files with bigger sizes under names FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended. 'groups' (optional) - array of filetype groups this filetype extension is part of; commonly used in moodle the following groups:

  • web_image - image that can be included as in HTML
  • image - image that we can parse using GD to find it's dimensions, also used for portfolio format
  • optimised_image - image that will be processed and optimised
  • video - file that can be imported as video in text editor
  • audio - file that can be imported as audio in text editor
  • archive - we can extract files from this archive
  • spreadsheet - used for portfolio format
  • document - used for portfolio format
  • presentation - used for portfolio format 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays human-readable description for this filetype; Function get_mimetype_description() first looks at the presence of string for particular mimetype (value of 'type'), if not found looks for string specified in 'string' attribute, if not found returns the value of 'type'; 'defaulticon' (boolean, optional) - used by function file_mimetype_icon() to find an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype, this function will return first found icon; Especially usefull for types such as 'text/plain'
Return values
arrayList of information about file types based on extensions. Associative array of extension (lower-case) to associative array from 'element name' to data. Current element names are 'type' and 'icon'. Unknown types should use the 'xxx' entry which includes defaults.

◆ get_moodle_proxy_url()

get_moodle_proxy_url ( )

Returns the moodle proxy configuration as a formatted url.

Return values
stringthe string to use for proxy settings.

◆ mimeinfo()

mimeinfo ( $element,
$filename )

Obtains information about a filetype based on its extension.

Will use a default if no information is present about that particular extension.

Parameters
string$elementDesired information (usually 'icon' for icon filename or 'type' for MIME type. Can also be 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
string$filenameFilename we're looking up
Return values
stringRequested piece of information from array

◆ mimeinfo_from_type()

mimeinfo_from_type ( $element,
$mimetype )

Obtains information about a filetype based on the MIME type rather than the other way around.

Parameters
string$elementDesired information ('extension', 'icon', etc.)
string$mimetypeMIME type we're looking up
Return values
stringRequested piece of information from array

◆ readfile_accel()

readfile_accel ( $file,
$mimetype,
$accelerate )

Enhanced readfile() with optional acceleration.

Parameters
string | stored_file$file
string$mimetype
bool$accelerate
Return values
void

◆ readfile_allow_large()

readfile_allow_large ( $path,
$filesize = -1 )

The readfile function can fail when files are larger than 2GB (even on 64-bit platforms).

This wrapper uses readfile for small files and custom code for large ones.

Parameters
string$pathPath to file
int$filesizeSize of file (if left out, will get it automatically)
Return values
int|boolSize read (will always be $filesize) or false if failed

◆ readstring_accel()

readstring_accel ( $string,
$mimetype,
$accelerate = false )

Similar to readfile_accel() but designed for strings.

Parameters
string$string
string$mimetype
bool$accelerateIgnored
Return values
void

◆ send_content_uncached()

send_content_uncached ( $content,
$filename )

Serve content which is not meant to be cached.

This is only intended to be used for volatile public files, for instance when development is enabled, or when caching is not required on a public resource.

Parameters
string$contentRaw content.
string$filenameThe file name.
Return values
void

◆ send_file()

send_file ( $path,
$filename,
$lifetime = null,
$filter = 0,
$pathisstring = false,
$forcedownload = false,
$mimetype = '',
$dontdie = false,
array $options = array() )

Handles the sending of file data to the user's browser, including support for byteranges etc.

Parameters
string | stored_file$pathPath of file on disk (including real filename), or actual content of file as string, or stored_file object
string$filenameFilename to send
int$lifetimeNumber of seconds before the file should expire from caches (null means $CFG->filelifetime)
int$filter0 (default)=no filtering, 1=all files, 2=html files only
bool$pathisstringIf true (default false), $path is the content to send and not the pathname. Forced to false when $path is a stored_file object.
bool$forcedownloadIf true (default false), forces download of file rather than view in browser/plugin
string$mimetypeInclude to specify the MIME type; leave blank to have it guess the type from $filename
bool$dontdie- return control to caller afterwards. this is not recommended and only used for cleanup tasks. if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel, you must detect this case when control is returned using connection_aborted. Please not that session is closed and should not be reopened.
array$optionsAn array of options, currently accepts:
  • (string) cacheability: public, or private.
  • (string|null) immutable
  • (bool) dontforcesvgdownload: true if force download should be disabled on SVGs. Note: This overrides a security feature, so should only be applied to "trusted" content (eg module content that is created using an XSS risk flagged capability, such as SCORM).
Return values
nullscript execution stopped unless $dontdie is true

◆ send_file_not_found()

stdClass send_file_not_found ( )

Requested file is not found or not accessible, does not return, terminates script.

$CFG @global stdClass $COURSE

◆ send_stored_file()

send_stored_file ( $storedfile,
$lifetime = null,
$filter = 0,
$forcedownload = false,
array $options = array() )

Handles the sending of file data to the user's browser, including support for byteranges etc.

The $options parameter supports the following keys: (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail) (string|null) filename - overrides the implicit filename (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks. if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel, you must detect this case when control is returned using connection_aborted. Please not that session is closed and should not be reopened (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public", when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise, defaults to "public". (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS. Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.

Parameters
stored_file$storedfilelocal file object
int$lifetimeNumber of seconds before the file should expire from caches (null means $CFG->filelifetime)
int$filter0 (default)=no filtering, 1=all files, 2=html files only
bool$forcedownloadIf true (default false), forces download of file rather than view in browser/plugin
array$optionsadditional options affecting the file serving
Return values
nullscript execution stopped unless $options['dontdie'] is true

◆ send_temp_file()

send_temp_file ( $path,
$filename,
$pathisstring = false )

Handles the sending of temporary file to user, download is forced.

File is deleted after abort or successful sending, does not return, script terminated

Parameters
string$pathpath to file, preferably from moodledata/temp/something; or content of file itself
string$filenameproposed file name when saving file
bool$pathisstringIf the path is string

◆ send_temp_file_finished()

send_temp_file_finished ( $path)

Internal callback function used by send_temp_file()

Parameters
string$path

◆ xsendfile()

xsendfile ( $filepath)

Serve file using X-Sendfile header, this needs special server module or configuration.

Please make sure that all headers are already sent and the all access control checks passed.

Parameters
string$filepath
Return values
boolsuccess