Search moodle.org's
Developer Documentation

See Release Notes

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

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

Core file storage class definition.

Copyright: 2008 Petr Skoda {@link http://skodak.org}
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2472 lines (101 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

file_storage:: (67 methods):
  __construct()
  setup_file_system()
  get_file_system()
  get_pathname_hash()
  file_exists()
  file_exists_by_hash()
  get_file_instance()
  get_converted_document()
  is_format_supported_by_unoconv()
  can_convert_documents()
  send_test_pdf()
  test_unoconv_path()
  get_file_preview()
  get_unused_filename()
  get_unused_dirname()
  create_file_preview()
  create_imagefile_preview()
  get_file_by_id()
  get_file_by_hash()
  get_file()
  is_area_empty()
  get_external_files()
  get_area_files()
  get_user_draft_items()
  get_area_tree()
  sort_area_tree()
  get_directory_files()
  delete_area_files()
  delete_area_files_select()
  delete_component_files()
  move_area_files_to_new_context()
  create_directory()
  create_file()
  create_file_from_storedfile()
  create_file_from_url()
  create_file_from_pathname()
  create_file_from_string()
  synchronise_stored_file_from_file()
  synchronise_stored_file_from_string()
  create_file_from_reference()
  convert_image()
  add_file_to_pool()
  add_string_to_pool()
  call_before_file_created_plugin_functions()
  xsendfile_file()
  xsendfile()
  supports_xsendfile()
  content_exists()
  try_content_recovery()
  pack_reference()
  unpack_reference()
  search_server_files()
  search_references()
  search_references_count()
  get_references_by_storedfile()
  get_references_count_by_storedfile()
  update_references_to_storedfile()
  import_external_file()
  mimetype()
  mimetype_from_file()
  cron()
  instance_sql_fields()
  get_or_create_referencefileid()
  get_referencefileid()
  update_references()
  hash_from_path()
  hash_from_string()


Class: file_storage  - X-Ref

File storage class used for low level access to stored files.

Only owner of file area may use this class to access own files,
for example only code in mod/assignment/* may access assignment
attachments. When some other part of moodle needs to access
files of modules it has to use file_browser class instead or there
has to be some callback API.

__construct()   X-Ref
Constructor - do not use directly use {@link get_file_storage()} call instead.


setup_file_system()   X-Ref
Complete setup procedure for the file_system component.

return: file_system

get_file_system()   X-Ref
Return the file system instance.

return: file_system

get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename)   X-Ref
Calculates sha1 hash of unique full path name information.

This hash is a unique file identifier - it is used to improve
performance and overcome db index size limits.

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
param: string $filepath file path
param: string $filename file name
return: string sha1 hash

file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename)   X-Ref
Does this file exist?

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
param: string $filepath file path
param: string $filename file name
return: bool

file_exists_by_hash($pathnamehash)   X-Ref
Whether or not the file exist

param: string $pathnamehash path name hash
return: bool

get_file_instance(stdClass $filerecord)   X-Ref
Create instance of file class from database record.

param: stdClass $filerecord record from the files table left join files_reference table
return: stored_file instance of file abstraction class

get_converted_document(stored_file $file, $format, $forcerefresh = false)   X-Ref
Get converted document.

Get an alternate version of the specified document, if it is possible to convert.

param: stored_file $file the file we want to preview
param: string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
param: boolean $forcerefresh If true, the file will be converted every time (not cached).
return: stored_file|bool false if unable to create the conversion, stored file otherwise

is_format_supported_by_unoconv($format)   X-Ref
Verify the format is supported.

param: string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
return: bool - True if the format is supported for input.

can_convert_documents()   X-Ref
Check if the installed version of unoconv is supported.

return: bool true if the present version is supported, false otherwise.

send_test_pdf()   X-Ref
Regenerate the test pdf and send it direct to the browser.


test_unoconv_path()   X-Ref
Check if unoconv configured path is correct and working.

return: \stdClass an object with the test status and the UNOCONVPATH_ constant message.

get_file_preview(stored_file $file, $mode)   X-Ref
Returns an image file that represent the given stored file as a preview

At the moment, only GIF, JPEG, PNG and SVG files are supported to have previews. In the
future, the support for other mimetypes can be added, too (eg. generate an image
preview of PDF, text documents etc).

param: stored_file $file the file we want to preview
param: string $mode preview mode, eg. 'thumb'
return: stored_file|bool false if unable to create the preview, stored file otherwise

get_unused_filename($contextid, $component, $filearea, $itemid, $filepath, $filename)   X-Ref
Return an available file name.

This will return the next available file name in the area, adding/incrementing a suffix
of the file, ie: file.txt > file (1).txt > file (2).txt > etc...

If the file name passed is available without modification, it is returned as is.

param: int $contextid context ID.
param: string $component component.
param: string $filearea file area.
param: int $itemid area item ID.
param: string $filepath the file path.
param: string $filename the file name.
return: string available file name.

get_unused_dirname($contextid, $component, $filearea, $itemid, $suggestedpath)   X-Ref
Return an available directory name.

This will return the next available directory name in the area, adding/incrementing a suffix
of the last portion of path, ie: /path/ > /path (1)/ > /path (2)/ > etc...

If the file path passed is available without modification, it is returned as is.

param: int $contextid context ID.
param: string $component component.
param: string $filearea file area.
param: int $itemid area item ID.
param: string $suggestedpath the suggested file path.
return: string available file path

create_file_preview(stored_file $file, $mode)   X-Ref
Generates a preview image for the stored file

param: stored_file $file the file we want to preview
param: string $mode preview mode, eg. 'thumb'
return: stored_file|bool the newly created preview file or false

create_imagefile_preview(stored_file $file, $mode)   X-Ref
Generates a preview for the stored image file

param: stored_file $file the image we want to preview
param: string $mode preview mode, eg. 'thumb'
return: string|bool false if a problem occurs, the thumbnail image data otherwise

get_file_by_id($fileid)   X-Ref
Fetch file using local file id.

Please do not rely on file ids, it is usually easier to use
pathname hashes instead.

param: int $fileid file ID
return: stored_file|bool stored_file instance if exists, false if not

get_file_by_hash($pathnamehash)   X-Ref
Fetch file using local file full pathname hash

param: string $pathnamehash path name hash
return: stored_file|bool stored_file instance if exists, false if not

get_file($contextid, $component, $filearea, $itemid, $filepath, $filename)   X-Ref
Fetch locally stored file.

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
param: string $filepath file path
param: string $filename file name
return: stored_file|bool stored_file instance if exists, false if not

is_area_empty($contextid, $component, $filearea, $itemid = false, $ignoredirs = true)   X-Ref
Are there any files (or directories)

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: bool|int $itemid item id or false if all items
param: bool $ignoredirs whether or not ignore directories
return: bool empty

get_external_files($repositoryid, $sort = '')   X-Ref
Returns all files belonging to given repository

param: int $repositoryid
param: string $sort A fragment of SQL to use for sorting

get_area_files($contextid, $component, $filearea, $itemid = false, $sort = "itemid, filepath, filename",$includedirs = true, $updatedsince = 0, $limitfrom = 0, $limitnum = 0)   X-Ref
Returns all area files (optionally limited by itemid)

param: int $contextid context ID
param: string $component component
param: mixed $filearea file area/s, you cannot specify multiple fileareas as well as an itemid
param: int|int[]|false $itemid item ID(s) or all files if not specified
param: string $sort A fragment of SQL to use for sorting
param: bool $includedirs whether or not include directories
param: int $updatedsince return files updated since this time
param: int $limitfrom return a subset of records, starting at this point (optional).
param: int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
return: stored_file[] array of stored_files indexed by pathanmehash

get_user_draft_items(int $userid, int $updatedsince = 0, int $lastnum = 0)   X-Ref
Returns the file area item ids and their updatetime for a user's draft uploads, sorted by updatetime DESC.

param: int $userid user id
param: int $updatedsince only return draft areas updated since this time
param: int $lastnum only return the last specified numbers
return: array

get_area_tree($contextid, $component, $filearea, $itemid)   X-Ref
Returns array based tree structure of area files

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
return: array each dir represented by dirname, subdirs, files and dirfile array elements

sort_area_tree($tree)   X-Ref
Sorts the result of {@link file_storage::get_area_tree()}.

param: array $tree Array of results provided by {@link file_storage::get_area_tree()}
return: array of sorted results

get_directory_files($contextid, $component, $filearea, $itemid, $filepath, $recursive = false, $includedirs = true, $sort = "filepath, filename")   X-Ref
Returns all files and optionally directories

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
param: int $filepath directory path
param: bool $recursive include all subdirectories
param: bool $includedirs include files and directories
param: string $sort A fragment of SQL to use for sorting
return: array of stored_files indexed by pathanmehash

delete_area_files($contextid, $component = false, $filearea = false, $itemid = false)   X-Ref
Delete all area files (optionally limited by itemid).

param: int $contextid context ID
param: string $component component
param: string $filearea file area or all areas in context if not specified
param: int $itemid item ID or all files if not specified
return: bool success

delete_area_files_select($contextid, $component,$filearea, $itemidstest, array $params = null)   X-Ref
Delete all the files from certain areas where itemid is limited by an
arbitrary bit of SQL.

param: int $contextid the id of the context the files belong to. Must be given.
param: string $component the owning component. Must be given.
param: string $filearea the file area name. Must be given.
param: string $itemidstest an SQL fragment that the itemid must match. Used
param: array $params any query params used by $itemidstest.

delete_component_files($component)   X-Ref
Delete all files associated with the given component.

param: string $component the component owning the file

move_area_files_to_new_context($oldcontextid, $newcontextid, $component, $filearea, $itemid = false)   X-Ref
Move all the files in a file area from one context to another.

param: int $oldcontextid the context the files are being moved from.
param: int $newcontextid the context the files are being moved to.
param: string $component the plugin that these files belong to.
param: string $filearea the name of the file area.
param: int $itemid file item ID
return: int the number of files moved, for information.

create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid = null)   X-Ref
Recursively creates directory.

param: int $contextid context ID
param: string $component component
param: string $filearea file area
param: int $itemid item ID
param: string $filepath file path
param: int $userid the user ID
return: stored_file|false success

create_file($newrecord)   X-Ref
Add new file record to database and handle callbacks.

param: stdClass $newrecord

create_file_from_storedfile($filerecord, $fileorid)   X-Ref
Add new local file based on existing local file.

param: stdClass|array $filerecord object or array describing changes
param: stored_file|int $fileorid id or stored_file instance of the existing local file
return: stored_file instance of newly created file

create_file_from_url($filerecord, $url, array $options = null, $usetempfile = false)   X-Ref
Add new local file.

param: stdClass|array $filerecord object or array describing file
param: string $url the URL to the file
param: array $options {@link download_file_content()} options
param: bool $usetempfile use temporary file for download, may prevent out of memory problems
return: stored_file

create_file_from_pathname($filerecord, $pathname)   X-Ref
Add new local file.

param: stdClass|array $filerecord object or array describing file
param: string $pathname path to file or content of file
return: stored_file

create_file_from_string($filerecord, $content)   X-Ref
Add new local file.

param: stdClass|array $filerecord object or array describing file
param: string $content content of file
return: stored_file

synchronise_stored_file_from_file(stored_file $file, $path, $filerecord)   X-Ref
Synchronise stored file from file.

param: stored_file $file Stored file to synchronise.
param: string $path Path to the file to synchronise from.
param: stdClass $filerecord The file record from the database.

synchronise_stored_file_from_string(stored_file $file, $content, $filerecord)   X-Ref
Synchronise stored file from string.

param: stored_file $file Stored file to synchronise.
param: string $content File content.
param: stdClass $filerecord The file record from the database.

create_file_from_reference($filerecord, $repositoryid, $reference, $options = array()   X-Ref
Create a new alias/shortcut file from file reference information

param: stdClass|array $filerecord object or array describing the new file
param: int $repositoryid the id of the repository that provides the original file
param: string $reference the information required by the repository to locate the original file
param: array $options options for creating the new file
return: stored_file

convert_image($filerecord, $fid, $newwidth = null, $newheight = null, $keepaspectratio = true, $quality = null)   X-Ref
Creates new image file from existing.

param: stdClass|array $filerecord object or array describing new file
param: int|stored_file $fid file id or stored file object
param: int $newwidth in pixels
param: int $newheight in pixels
param: bool $keepaspectratio whether or not keep aspect ratio
param: int $quality depending on image type 0-100 for jpeg, 0-9 (0 means no compression) for png
return: stored_file

add_file_to_pool($pathname, $contenthash = null, $newrecord = null)   X-Ref
Add file content to sha1 pool.

param: string $pathname path to file
param: string|null $contenthash sha1 hash of content if known (performance only)
param: stdClass|null $newrecord New file record
return: array (contenthash, filesize, newfile)

add_string_to_pool($content, $newrecord = null)   X-Ref
Add string content to sha1 pool.

param: string $content file content - binary string
return: array (contenthash, filesize, newfile)

call_before_file_created_plugin_functions($newrecord, $pathname = null, $content = null)   X-Ref
before_file_created hook.

param: stdClass|null $newrecord New file record.
param: string|null $pathname Path to file.
param: string|null $content File content.

xsendfile_file(stored_file $file)   X-Ref
Serve file content using X-Sendfile header.
Please make sure that all headers are already sent and the all
access control checks passed.

This alternate method to xsendfile() allows an alternate file system
to use the full file metadata and avoid extra lookups.

param: stored_file $file The file to send
return: bool success

xsendfile($contenthash)   X-Ref
Serve file content using X-Sendfile header.
Please make sure that all headers are already sent
and the all access control checks passed.

param: string $contenthash sah1 hash of the file content to be served
return: bool success

supports_xsendfile()   X-Ref
Returns true if filesystem is configured to support xsendfile.

return: bool

content_exists($contenthash)   X-Ref
Content exists

param: string $contenthash
return: bool

try_content_recovery($file)   X-Ref
Tries to recover missing content of file from trash.

param: stored_file $file stored_file instance
return: bool success

pack_reference($params)   X-Ref
When user referring to a moodle file, we build the reference field

param: array $params
return: string

unpack_reference($str, $cleanparams = false)   X-Ref
Unpack reference field

param: string $str
param: bool $cleanparams if set to true, array elements will be passed through {@link clean_param()}
return: array

search_server_files($query, $from = 0, $limit = 20, $count = false)   X-Ref
Search through the server files.

The query parameter will be used in conjuction with the SQL directive
LIKE, so include '%' in it if you need to. This search will always ignore
user files and directories. Note that the search is case insensitive.

This query can quickly become inefficient so use it sparignly.

param: string  $query The string used with SQL LIKE.
param: integer $from  The offset to start the search at.
param: integer $limit The maximum number of results.
param: boolean $count When true this methods returns the number of results availabe,
return: int|array      Integer when count, otherwise array of stored_file objects.

search_references($reference)   X-Ref
Returns all aliases that refer to some stored_file via the given reference

All repositories that provide access to a stored_file are expected to use
{@link self::pack_reference()}. This method can't be used if the given reference
does not use this format or if you are looking for references to an external file
(for example it can't be used to search for all aliases that refer to a given
Dropbox or Box.net file).

Aliases in user draft areas are excluded from the returned list.

param: string $reference identification of the referenced file
return: array of stored_file indexed by its pathnamehash

search_references_count($reference)   X-Ref
Returns the number of aliases that refer to some stored_file via the given reference

All repositories that provide access to a stored_file are expected to use
{@link self::pack_reference()}. This method can't be used if the given reference
does not use this format or if you are looking for references to an external file
(for example it can't be used to count aliases that refer to a given Dropbox or
Box.net file).

Aliases in user draft areas are not counted.

param: string $reference identification of the referenced file
return: int

get_references_by_storedfile(stored_file $storedfile)   X-Ref
Returns all aliases that link to the given stored_file

Aliases in user draft areas are excluded from the returned list.

param: stored_file $storedfile
return: array of stored_file

get_references_count_by_storedfile(stored_file $storedfile)   X-Ref
Returns the number of aliases that link to the given stored_file

Aliases in user draft areas are not counted.

param: stored_file $storedfile
return: int

update_references_to_storedfile(stored_file $storedfile)   X-Ref
Updates all files that are referencing this file with the new contenthash
and filesize

param: stored_file $storedfile

import_external_file(stored_file $storedfile, $maxbytes = 0)   X-Ref
Convert file alias to local file

param: stored_file $storedfile a stored_file instances
param: int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
return: stored_file stored_file

mimetype($fullpath, $filename = null)   X-Ref
Return mimetype by given file pathname.

If file has a known extension, we return the mimetype based on extension.
Otherwise (when possible) we try to get the mimetype from file contents.

param: string $fullpath Full path to the file on disk
param: string $filename Correct file name with extension, if omitted will be taken from $path
return: string

mimetype_from_file($fullpath)   X-Ref
Inspect a file on disk for it's mimetype.

param: string $fullpath Path to file on disk
return: string The mimetype

cron()   X-Ref
Cron cleanup job.


instance_sql_fields($filesprefix, $filesreferenceprefix)   X-Ref
Get the sql formated fields for a file instance to be created from a
{files} and {files_refernece} join.

param: string $filesprefix the table prefix for the {files} table
param: string $filesreferenceprefix the table prefix for the {files_reference} table
return: string the sql to go after a SELECT

get_or_create_referencefileid($repositoryid, $reference, $lastsync = null, $lifetime = null)   X-Ref
Returns the id of the record in {files_reference} that matches the passed repositoryid and reference

If the record already exists, its id is returned. If there is no such record yet,
new one is created (using the lastsync provided, too) and its id is returned.

param: int $repositoryid
param: string $reference
param: int $lastsync
param: int $lifetime argument not used any more
return: int

get_referencefileid($repositoryid, $reference, $strictness)   X-Ref
Returns the id of the record in {files_reference} that matches the passed parameters

Depending on the required strictness, false can be returned. The behaviour is consistent
with standard DML methods.

param: int $repositoryid
param: string $reference
param: int $strictness either {@link IGNORE_MISSING}, {@link IGNORE_MULTIPLE} or {@link MUST_EXIST}
return: int|bool

update_references($referencefileid, $lastsync, $lifetime, $contenthash, $filesize, $status, $timemodified = null)   X-Ref
Updates a reference to the external resource and all files that use it

This function is called after synchronisation of an external file and updates the
contenthash, filesize and status of all files that reference this external file
as well as time last synchronised.

param: int $referencefileid
param: int $lastsync
param: int $lifetime argument not used any more, liefetime is returned by repository
param: string $contenthash
param: int $filesize
param: int $status 0 if ok or 666 if source is missing
param: int $timemodified last time modified of the source, if known

hash_from_path($filepath)   X-Ref
Calculate and return the contenthash of the supplied file.

param: string $filepath The path to the file on disk
return: string The file's content hash

hash_from_string($content)   X-Ref
Calculate and return the contenthash of the supplied content.

param: string $content The file content
return: string The file's content hash