MDL-71126 Quiz: Manual grading page size preference can get stuck at 0
[moodle.git] / lib / filestorage / file_system.php
blob2339c13bd80d44cd868c25e146633bbb3f5eb039
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Core file system class definition.
20 * @package core_files
21 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * File system class used for low level access to real files in filedir.
30 * @package core_files
31 * @category files
32 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 abstract class file_system {
37 /**
38 * Output the content of the specified stored file.
40 * Note, this is different to get_content() as it uses the built-in php
41 * readfile function which is more efficient.
43 * @param stored_file $file The file to serve.
44 * @return void
46 public function readfile(stored_file $file) {
47 if ($this->is_file_readable_locally_by_storedfile($file, false)) {
48 $path = $this->get_local_path_from_storedfile($file, false);
49 } else {
50 $path = $this->get_remote_path_from_storedfile($file);
52 if (readfile_allow_large($path, $file->get_filesize()) === false) {
53 throw new file_exception('storedfilecannotreadfile', $file->get_filename());
57 /**
58 * Get the full path on disk for the specified stored file.
60 * Note: This must return a consistent path for the file's contenthash
61 * and the path _will_ be in a standard local format.
62 * Streamable paths will not work.
63 * A local copy of the file _will_ be fetched if $fetchifnotfound is tree.
65 * The $fetchifnotfound allows you to determine the expected path of the file.
67 * @param stored_file $file The file to serve.
68 * @param bool $fetchifnotfound Whether to attempt to fetch from the remote path if not found.
69 * @return string full path to pool file with file content
71 public function get_local_path_from_storedfile(stored_file $file, $fetchifnotfound = false) {
72 return $this->get_local_path_from_hash($file->get_contenthash(), $fetchifnotfound);
75 /**
76 * Get a remote filepath for the specified stored file.
78 * This is typically either the same as the local filepath, or it is a streamable resource.
80 * See https://secure.php.net/manual/en/wrappers.php for further information on valid wrappers.
82 * @param stored_file $file The file to serve.
83 * @return string full path to pool file with file content
85 public function get_remote_path_from_storedfile(stored_file $file) {
86 return $this->get_remote_path_from_hash($file->get_contenthash(), false);
89 /**
90 * Get the full path for the specified hash, including the path to the filedir.
92 * Note: This must return a consistent path for the file's contenthash
93 * and the path _will_ be in a standard local format.
94 * Streamable paths will not work.
95 * A local copy of the file _will_ be fetched if $fetchifnotfound is tree.
97 * The $fetchifnotfound allows you to determine the expected path of the file.
99 * @param string $contenthash The content hash
100 * @param bool $fetchifnotfound Whether to attempt to fetch from the remote path if not found.
101 * @return string The full path to the content file
103 abstract protected function get_local_path_from_hash($contenthash, $fetchifnotfound = false);
106 * Get the full path for the specified hash, including the path to the filedir.
108 * This is typically either the same as the local filepath, or it is a streamable resource.
110 * See https://secure.php.net/manual/en/wrappers.php for further information on valid wrappers.
112 * @param string $contenthash The content hash
113 * @return string The full path to the content file
115 abstract protected function get_remote_path_from_hash($contenthash);
118 * Determine whether the file is present on the file system somewhere.
119 * A local copy of the file _will_ be fetched if $fetchifnotfound is tree.
121 * The $fetchifnotfound allows you to determine the expected path of the file.
123 * @param stored_file $file The file to ensure is available.
124 * @param bool $fetchifnotfound Whether to attempt to fetch from the remote path if not found.
125 * @return bool
127 public function is_file_readable_locally_by_storedfile(stored_file $file, $fetchifnotfound = false) {
128 if (!$file->get_filesize()) {
129 // Files with empty size are either directories or empty.
130 // We handle these virtually.
131 return true;
134 // Check to see if the file is currently readable.
135 $path = $this->get_local_path_from_storedfile($file, $fetchifnotfound);
136 if (is_readable($path)) {
137 return true;
140 return false;
144 * Determine whether the file is present on the local file system somewhere.
146 * @param stored_file $file The file to ensure is available.
147 * @return bool
149 public function is_file_readable_remotely_by_storedfile(stored_file $file) {
150 if (!$file->get_filesize()) {
151 // Files with empty size are either directories or empty.
152 // We handle these virtually.
153 return true;
156 $path = $this->get_remote_path_from_storedfile($file, false);
157 if (is_readable($path)) {
158 return true;
161 return false;
165 * Determine whether the file is present on the file system somewhere given
166 * the contenthash.
168 * @param string $contenthash The contenthash of the file to check.
169 * @param bool $fetchifnotfound Whether to attempt to fetch from the remote path if not found.
170 * @return bool
172 public function is_file_readable_locally_by_hash($contenthash, $fetchifnotfound = false) {
173 if ($contenthash === file_storage::hash_from_string('')) {
174 // Files with empty size are either directories or empty.
175 // We handle these virtually.
176 return true;
179 // This is called by file_storage::content_exists(), and in turn by the repository system.
180 $path = $this->get_local_path_from_hash($contenthash, $fetchifnotfound);
182 // Note - it is not possible to perform a content recovery safely from a hash alone.
183 return is_readable($path);
187 * Determine whether the file is present locally on the file system somewhere given
188 * the contenthash.
190 * @param string $contenthash The contenthash of the file to check.
191 * @return bool
193 public function is_file_readable_remotely_by_hash($contenthash) {
194 if ($contenthash === file_storage::hash_from_string('')) {
195 // Files with empty size are either directories or empty.
196 // We handle these virtually.
197 return true;
200 $path = $this->get_remote_path_from_hash($contenthash, false);
202 // Note - it is not possible to perform a content recovery safely from a hash alone.
203 return is_readable($path);
207 * Copy content of file to given pathname.
209 * @param stored_file $file The file to be copied
210 * @param string $target real path to the new file
211 * @return bool success
213 abstract public function copy_content_from_storedfile(stored_file $file, $target);
216 * Remove the file with the specified contenthash.
218 * Note, if overriding this function, you _must_ check that the file is
219 * no longer in use - see {check_file_usage}.
221 * DO NOT call directly - reserved for core!!
223 * @param string $contenthash
225 abstract public function remove_file($contenthash);
228 * Check whether a file is removable.
230 * This must be called prior to file removal.
232 * @param string $contenthash
233 * @return bool
235 protected static function is_file_removable($contenthash) {
236 global $DB;
238 if ($contenthash === file_storage::hash_from_string('')) {
239 // No need to delete files without content.
240 return false;
243 // Note: This section is critical - in theory file could be reused at the same time, if this
244 // happens we can still recover the file from trash.
245 // Technically this is the responsibility of the file_storage API, but as this method is public, we go belt-and-braces.
246 if ($DB->record_exists('files', array('contenthash' => $contenthash))) {
247 // File content is still used.
248 return false;
251 return true;
255 * Get the content of the specified stored file.
257 * Generally you will probably want to use readfile() to serve content,
258 * and where possible you should see if you can use
259 * get_content_file_handle and work with the file stream instead.
261 * @param stored_file $file The file to retrieve
262 * @return string The full file content
264 public function get_content(stored_file $file) {
265 if (!$file->get_filesize()) {
266 // Directories are empty. Empty files are not worth fetching.
267 return '';
270 $source = $this->get_remote_path_from_storedfile($file);
271 return file_get_contents($source);
275 * List contents of archive.
277 * @param stored_file $file The archive to inspect
278 * @param file_packer $packer file packer instance
279 * @return array of file infos
281 public function list_files($file, file_packer $packer) {
282 $archivefile = $this->get_local_path_from_storedfile($file, true);
283 return $packer->list_files($archivefile);
287 * Extract file to given file path (real OS filesystem), existing files are overwritten.
289 * @param stored_file $file The archive to inspect
290 * @param file_packer $packer File packer instance
291 * @param string $pathname Target directory
292 * @param file_progress $progress progress indicator callback or null if not required
293 * @return array|bool List of processed files; false if error
295 public function extract_to_pathname(stored_file $file, file_packer $packer, $pathname, file_progress $progress = null) {
296 $archivefile = $this->get_local_path_from_storedfile($file, true);
297 return $packer->extract_to_pathname($archivefile, $pathname, null, $progress);
301 * Extract file to given file path (real OS filesystem), existing files are overwritten.
303 * @param stored_file $file The archive to inspect
304 * @param file_packer $packer file packer instance
305 * @param int $contextid context ID
306 * @param string $component component
307 * @param string $filearea file area
308 * @param int $itemid item ID
309 * @param string $pathbase path base
310 * @param int $userid user ID
311 * @param file_progress $progress Progress indicator callback or null if not required
312 * @return array|bool list of processed files; false if error
314 public function extract_to_storage(stored_file $file, file_packer $packer, $contextid,
315 $component, $filearea, $itemid, $pathbase, $userid = null, file_progress $progress = null) {
317 // Since we do not know which extractor we have, and whether it supports remote paths, use a local path here.
318 $archivefile = $this->get_local_path_from_storedfile($file, true);
319 return $packer->extract_to_storage($archivefile, $contextid,
320 $component, $filearea, $itemid, $pathbase, $userid, $progress);
324 * Add file/directory into archive.
326 * @param stored_file $file The file to archive
327 * @param file_archive $filearch file archive instance
328 * @param string $archivepath pathname in archive
329 * @return bool success
331 public function add_storedfile_to_archive(stored_file $file, file_archive $filearch, $archivepath) {
332 if ($file->is_directory()) {
333 return $filearch->add_directory($archivepath);
334 } else {
335 // Since we do not know which extractor we have, and whether it supports remote paths, use a local path here.
336 return $filearch->add_file_from_pathname($archivepath, $this->get_local_path_from_storedfile($file, true));
341 * Adds this file path to a curl request (POST only).
343 * @param stored_file $file The file to add to the curl request
344 * @param curl $curlrequest The curl request object
345 * @param string $key What key to use in the POST request
346 * @return void
347 * This needs the fullpath for the storedfile :/
348 * Can this be achieved in some other fashion?
350 public function add_to_curl_request(stored_file $file, &$curlrequest, $key) {
351 // Note: curl_file_create does not work with remote paths.
352 $path = $this->get_local_path_from_storedfile($file, true);
353 $curlrequest->_tmp_file_post_params[$key] = curl_file_create($path, null, $file->get_filename());
357 * Returns information about image.
358 * Information is determined from the file content
360 * @param stored_file $file The file to inspect
361 * @return mixed array with width, height and mimetype; false if not an image
363 public function get_imageinfo(stored_file $file) {
364 if (!$this->is_image_from_storedfile($file)) {
365 return false;
368 // Whilst get_imageinfo_from_path can use remote paths, it must download the entire file first.
369 // It is more efficient to use a local file when possible.
370 return $this->get_imageinfo_from_path($this->get_local_path_from_storedfile($file, true));
374 * Attempt to determine whether the specified file is likely to be an
375 * image.
376 * Since this relies upon the mimetype stored in the files table, there
377 * may be times when this information is not 100% accurate.
379 * @param stored_file $file The file to check
380 * @return bool
382 public function is_image_from_storedfile(stored_file $file) {
383 if (!$file->get_filesize()) {
384 // An empty file cannot be an image.
385 return false;
388 $mimetype = $file->get_mimetype();
389 if (!preg_match('|^image/|', $mimetype)) {
390 // The mimetype does not include image.
391 return false;
394 // If it looks like an image, and it smells like an image, perhaps it's an image!
395 return true;
399 * Returns image information relating to the specified path or URL.
401 * @param string $path The path to pass to getimagesize.
402 * @return array Containing width, height, and mimetype.
404 protected function get_imageinfo_from_path($path) {
405 $imageinfo = getimagesize($path);
407 if (!is_array($imageinfo)) {
408 return false; // Nothing to process, the file was not recognised as image by GD.
411 $image = array(
412 'width' => $imageinfo[0],
413 'height' => $imageinfo[1],
414 'mimetype' => image_type_to_mime_type($imageinfo[2]),
417 if (empty($image['width']) or empty($image['height']) or empty($image['mimetype'])) {
418 // GD can not parse it, sorry.
419 return false;
421 return $image;
425 * Serve file content using X-Sendfile header.
426 * Please make sure that all headers are already sent and the all
427 * access control checks passed.
429 * This alternate method to xsendfile() allows an alternate file system
430 * to use the full file metadata and avoid extra lookups.
432 * @param stored_file $file The file to send
433 * @return bool success
435 public function xsendfile_file(stored_file $file): bool {
436 return $this->xsendfile($file->get_contenthash());
440 * Serve file content using X-Sendfile header.
441 * Please make sure that all headers are already sent and the all
442 * access control checks passed.
444 * @param string $contenthash The content hash of the file to be served
445 * @return bool success
447 public function xsendfile($contenthash) {
448 global $CFG;
449 require_once($CFG->libdir . "/xsendfilelib.php");
451 return xsendfile($this->get_remote_path_from_hash($contenthash));
455 * Returns true if filesystem is configured to support xsendfile.
457 * @return bool
459 public function supports_xsendfile() {
460 global $CFG;
461 return !empty($CFG->xsendfile);
465 * Validate that the content hash matches the content hash of the file on disk.
467 * @param string $contenthash The current content hash to validate
468 * @param string $pathname The path to the file on disk
469 * @return array The content hash (it might change) and file size
471 protected function validate_hash_and_file_size($contenthash, $pathname) {
472 global $CFG;
474 if (!is_readable($pathname)) {
475 throw new file_exception('storedfilecannotread', '', $pathname);
478 $filesize = filesize($pathname);
479 if ($filesize === false) {
480 throw new file_exception('storedfilecannotread', '', $pathname);
483 if (is_null($contenthash)) {
484 $contenthash = file_storage::hash_from_path($pathname);
485 } else if ($CFG->debugdeveloper) {
486 $filehash = file_storage::hash_from_path($pathname);
487 if ($filehash === false) {
488 throw new file_exception('storedfilecannotread', '', $pathname);
490 if ($filehash !== $contenthash) {
491 // Hopefully this never happens, if yes we need to fix calling code.
492 debugging("Invalid contenthash submitted for file $pathname", DEBUG_DEVELOPER);
493 $contenthash = $filehash;
496 if ($contenthash === false) {
497 throw new file_exception('storedfilecannotread', '', $pathname);
500 if ($filesize > 0 and $contenthash === file_storage::hash_from_string('')) {
501 // Did the file change or is file_storage::hash_from_path() borked for this file?
502 clearstatcache();
503 $contenthash = file_storage::hash_from_path($pathname);
504 $filesize = filesize($pathname);
506 if ($contenthash === false or $filesize === false) {
507 throw new file_exception('storedfilecannotread', '', $pathname);
509 if ($filesize > 0 and $contenthash === file_storage::hash_from_string('')) {
510 // This is very weird...
511 throw new file_exception('storedfilecannotread', '', $pathname);
515 return [$contenthash, $filesize];
519 * Add the supplied file to the file system.
521 * Note: If overriding this function, it is advisable to store the file
522 * in the path returned by get_local_path_from_hash as there may be
523 * subsequent uses of the file in the same request.
525 * @param string $pathname Path to file currently on disk
526 * @param string $contenthash SHA1 hash of content if known (performance only)
527 * @return array (contenthash, filesize, newfile)
529 abstract public function add_file_from_path($pathname, $contenthash = null);
532 * Add a file with the supplied content to the file system.
534 * Note: If overriding this function, it is advisable to store the file
535 * in the path returned by get_local_path_from_hash as there may be
536 * subsequent uses of the file in the same request.
538 * @param string $content file content - binary string
539 * @return array (contenthash, filesize, newfile)
541 abstract public function add_file_from_string($content);
544 * Returns file handle - read only mode, no writing allowed into pool files!
546 * When you want to modify a file, create a new file and delete the old one.
548 * @param stored_file $file The file to retrieve a handle for
549 * @param int $type Type of file handle (FILE_HANDLE_xx constant)
550 * @return resource file handle
552 public function get_content_file_handle(stored_file $file, $type = stored_file::FILE_HANDLE_FOPEN) {
553 if ($type === stored_file::FILE_HANDLE_GZOPEN) {
554 // Local file required for gzopen.
555 $path = $this->get_local_path_from_storedfile($file, true);
556 } else {
557 $path = $this->get_remote_path_from_storedfile($file);
560 return self::get_file_handle_for_path($path, $type);
564 * Return a file handle for the specified path.
566 * This abstraction should be used when overriding get_content_file_handle in a new file system.
568 * @param string $path The path to the file. This shoudl be any type of path that fopen and gzopen accept.
569 * @param int $type Type of file handle (FILE_HANDLE_xx constant)
570 * @return resource
571 * @throws coding_exception When an unexpected type of file handle is requested
573 protected static function get_file_handle_for_path($path, $type = stored_file::FILE_HANDLE_FOPEN) {
574 switch ($type) {
575 case stored_file::FILE_HANDLE_FOPEN:
576 // Binary reading.
577 return fopen($path, 'rb');
578 case stored_file::FILE_HANDLE_GZOPEN:
579 // Binary reading of file in gz format.
580 return gzopen($path, 'rb');
581 default:
582 throw new coding_exception('Unexpected file handle type');
587 * Retrieve the mime information for the specified stored file.
589 * @param string $contenthash
590 * @param string $filename
591 * @return string The MIME type.
593 public function mimetype_from_hash($contenthash, $filename) {
594 $pathname = $this->get_local_path_from_hash($contenthash);
595 $mimetype = file_storage::mimetype($pathname, $filename);
597 if ($mimetype === 'document/unknown' && !$this->is_file_readable_locally_by_hash($contenthash)) {
598 // The type is unknown, but the full checks weren't completed because the file isn't locally available.
599 // Ensure we have a local copy and try again.
600 $pathname = $this->get_local_path_from_hash($contenthash, true);
601 $mimetype = file_storage::mimetype_from_file($pathname);
604 return $mimetype;
608 * Retrieve the mime information for the specified stored file.
610 * @param stored_file $file The stored file to retrieve mime information for
611 * @return string The MIME type.
613 public function mimetype_from_storedfile($file) {
614 if (!$file->get_filesize()) {
615 // Files with an empty filesize are treated as directories and have no mimetype.
616 return null;
618 return $this->mimetype_from_hash($file->get_contenthash(), $file->get_filename());
622 * Run any periodic tasks which must be performed.
624 public function cron() {