Merge branch 'MDL-36056-master-enrolkeywhitespace' of git://github.com/mudrd8mz/moodle
[moodle.git] / lib / filestorage / stored_file.php
blob36f186f918d4cd89baea5b6acef0038b5ccf7270
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/>.
18 /**
19 * Definition of a class stored_file.
21 * @package core_files
22 * @copyright 2008 Petr Skoda {@link http://skodak.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->dirroot . '/lib/filestorage/file_progress.php');
29 require_once($CFG->dirroot . '/lib/filestorage/file_system.php');
31 /**
32 * Class representing local files stored in a sha1 file pool.
34 * Since Moodle 2.0 file contents are stored in sha1 pool and
35 * all other file information is stored in new "files" database table.
37 * @package core_files
38 * @category files
39 * @copyright 2008 Petr Skoda {@link http://skodak.org}
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 * @since Moodle 2.0
43 class stored_file {
44 /** @var file_storage file storage pool instance */
45 private $fs;
46 /** @var stdClass record from the files table left join files_reference table */
47 private $file_record;
48 /** @var repository repository plugin instance */
49 private $repository;
50 /** @var file_system filesystem instance */
51 private $filesystem;
53 /**
54 * @var int Indicates a file handle of the type returned by fopen.
56 const FILE_HANDLE_FOPEN = 0;
58 /**
59 * @var int Indicates a file handle of the type returned by gzopen.
61 const FILE_HANDLE_GZOPEN = 1;
64 /**
65 * Constructor, this constructor should be called ONLY from the file_storage class!
67 * @param file_storage $fs file storage instance
68 * @param stdClass $file_record description of file
69 * @param string $deprecated
71 public function __construct(file_storage $fs, stdClass $file_record, $deprecated = null) {
72 global $DB, $CFG;
73 $this->fs = $fs;
74 $this->file_record = clone($file_record); // prevent modifications
76 if (!empty($file_record->repositoryid)) {
77 require_once("$CFG->dirroot/repository/lib.php");
78 $this->repository = repository::get_repository_by_id($file_record->repositoryid, SYSCONTEXTID);
79 if ($this->repository->supported_returntypes() & FILE_REFERENCE != FILE_REFERENCE) {
80 // Repository cannot do file reference.
81 throw new moodle_exception('error');
83 } else {
84 $this->repository = null;
86 // make sure all reference fields exist in file_record even when it is not a reference
87 foreach (array('referencelastsync', 'referencefileid', 'reference', 'repositoryid') as $key) {
88 if (empty($this->file_record->$key)) {
89 $this->file_record->$key = null;
93 $this->filesystem = $fs->get_file_system();
96 /**
97 * Magic method, called during serialization.
99 * @return array
101 public function __sleep() {
102 // We only ever want the file_record saved, not the file_storage object.
103 return ['file_record'];
107 * Magic method, called during unserialization.
109 public function __wakeup() {
110 // Recreate our stored_file based on the file_record, and using file storage retrieved the correct way.
111 $this->__construct(get_file_storage(), $this->file_record);
115 * Whether or not this is a external resource
117 * @return bool
119 public function is_external_file() {
120 return !empty($this->repository);
124 * Whether or not this is a controlled link. Note that repositories cannot support FILE_REFERENCE and FILE_CONTROLLED_LINK.
126 * @return bool
128 public function is_controlled_link() {
129 return $this->is_external_file() && $this->repository->supported_returntypes() & FILE_CONTROLLED_LINK;
133 * Update some file record fields
134 * NOTE: Must remain protected
136 * @param stdClass $dataobject
138 protected function update($dataobject) {
139 global $DB;
140 $updatereferencesneeded = false;
141 $updatemimetype = false;
142 $keys = array_keys((array)$this->file_record);
143 $filepreupdate = clone($this->file_record);
144 foreach ($dataobject as $field => $value) {
145 if (in_array($field, $keys)) {
146 if ($field == 'contextid' and (!is_number($value) or $value < 1)) {
147 throw new file_exception('storedfileproblem', 'Invalid contextid');
150 if ($field == 'component') {
151 $value = clean_param($value, PARAM_COMPONENT);
152 if (empty($value)) {
153 throw new file_exception('storedfileproblem', 'Invalid component');
157 if ($field == 'filearea') {
158 $value = clean_param($value, PARAM_AREA);
159 if (empty($value)) {
160 throw new file_exception('storedfileproblem', 'Invalid filearea');
164 if ($field == 'itemid' and (!is_number($value) or $value < 0)) {
165 throw new file_exception('storedfileproblem', 'Invalid itemid');
169 if ($field == 'filepath') {
170 $value = clean_param($value, PARAM_PATH);
171 if (strpos($value, '/') !== 0 or strrpos($value, '/') !== strlen($value)-1) {
172 // path must start and end with '/'
173 throw new file_exception('storedfileproblem', 'Invalid file path');
177 if ($field == 'filename') {
178 // folder has filename == '.', so we pass this
179 if ($value != '.') {
180 $value = clean_param($value, PARAM_FILE);
182 if ($value === '') {
183 throw new file_exception('storedfileproblem', 'Invalid file name');
187 if ($field === 'timecreated' or $field === 'timemodified') {
188 if (!is_number($value)) {
189 throw new file_exception('storedfileproblem', 'Invalid timestamp');
191 if ($value < 0) {
192 $value = 0;
196 if ($field === 'referencefileid') {
197 if (!is_null($value) and !is_number($value)) {
198 throw new file_exception('storedfileproblem', 'Invalid reference info');
202 if (($field == 'contenthash' || $field == 'filesize') && $this->file_record->$field != $value) {
203 $updatereferencesneeded = true;
206 if ($updatereferencesneeded || ($field === 'filename' && $this->file_record->filename != $value)) {
207 $updatemimetype = true;
210 // adding the field
211 $this->file_record->$field = $value;
212 } else {
213 throw new coding_exception("Invalid field name, $field doesn't exist in file record");
216 // Validate mimetype field
217 if ($updatemimetype) {
218 $mimetype = $this->filesystem->mimetype_from_storedfile($this);
219 $this->file_record->mimetype = $mimetype;
222 $DB->update_record('files', $this->file_record);
223 if ($updatereferencesneeded) {
224 // Either filesize or contenthash of this file have changed. Update all files that reference to it.
225 $this->fs->update_references_to_storedfile($this);
228 // Callback for file update.
229 if (!$this->is_directory()) {
230 if ($pluginsfunction = get_plugins_with_function('after_file_updated')) {
231 foreach ($pluginsfunction as $plugintype => $plugins) {
232 foreach ($plugins as $pluginfunction) {
233 $pluginfunction($this->file_record, $filepreupdate);
241 * Rename filename
243 * @param string $filepath file path
244 * @param string $filename file name
246 public function rename($filepath, $filename) {
247 if ($this->fs->file_exists($this->get_contextid(), $this->get_component(), $this->get_filearea(), $this->get_itemid(), $filepath, $filename)) {
248 $a = new stdClass();
249 $a->contextid = $this->get_contextid();
250 $a->component = $this->get_component();
251 $a->filearea = $this->get_filearea();
252 $a->itemid = $this->get_itemid();
253 $a->filepath = $filepath;
254 $a->filename = $filename;
255 throw new file_exception('storedfilenotcreated', $a, 'file exists, cannot rename');
257 $filerecord = new stdClass;
258 $filerecord->filepath = $filepath;
259 $filerecord->filename = $filename;
260 // populate the pathname hash
261 $filerecord->pathnamehash = $this->fs->get_pathname_hash($this->file_record->contextid, $this->file_record->component, $this->file_record->filearea, $this->file_record->itemid, $filepath, $filename);
262 $this->update($filerecord);
266 * Function stored_file::replace_content_with() is deprecated. Please use stored_file::replace_file_with()
268 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
269 * @see stored_file::replace_file_with()
271 public function replace_content_with(stored_file $storedfile) {
272 throw new coding_exception('Function stored_file::replace_content_with() can not be used any more . ' .
273 'Please use stored_file::replace_file_with()');
277 * Replaces the fields that might have changed when file was overriden in filepicker:
278 * reference, contenthash, filesize, userid
280 * Note that field 'source' must be updated separately because
281 * it has different format for draft and non-draft areas and
282 * this function will usually be used to replace non-draft area
283 * file with draft area file.
285 * @param stored_file $newfile
286 * @throws coding_exception
288 public function replace_file_with(stored_file $newfile) {
289 if ($newfile->get_referencefileid() &&
290 $this->fs->get_references_count_by_storedfile($this)) {
291 // The new file is a reference.
292 // The current file has other local files referencing to it.
293 // Double reference is not allowed.
294 throw new moodle_exception('errordoublereference', 'repository');
297 $filerecord = new stdClass;
298 if ($this->filesystem->is_file_readable_remotely_by_storedfile($newfile)) {
299 $contenthash = $newfile->get_contenthash();
300 $filerecord->contenthash = $contenthash;
301 } else {
302 throw new file_exception('storedfileproblem', 'Invalid contenthash, content must be already in filepool', $contenthash);
304 $filerecord->filesize = $newfile->get_filesize();
305 $filerecord->referencefileid = $newfile->get_referencefileid();
306 $filerecord->userid = $newfile->get_userid();
307 $this->update($filerecord);
311 * Unlink the stored file from the referenced file
313 * This methods destroys the link to the record in files_reference table. This effectively
314 * turns the stored file from being an alias to a plain copy. However, the caller has
315 * to make sure that the actual file's content has beed synced prior to calling this method.
317 public function delete_reference() {
318 global $DB;
320 if (!$this->is_external_file()) {
321 throw new coding_exception('An attempt to unlink a non-reference file.');
324 $transaction = $DB->start_delegated_transaction();
326 // Are we the only one referring to the original file? If so, delete the
327 // referenced file record. Note we do not use file_storage::search_references_count()
328 // here because we want to count draft files too and we are at a bit lower access level here.
329 $countlinks = $DB->count_records('files',
330 array('referencefileid' => $this->file_record->referencefileid));
331 if ($countlinks == 1) {
332 $DB->delete_records('files_reference', array('id' => $this->file_record->referencefileid));
335 // Update the underlying record in the database.
336 $update = new stdClass();
337 $update->referencefileid = null;
338 $this->update($update);
340 $transaction->allow_commit();
342 // Update our properties and the record in the memory.
343 $this->repository = null;
344 $this->file_record->repositoryid = null;
345 $this->file_record->reference = null;
346 $this->file_record->referencefileid = null;
347 $this->file_record->referencelastsync = null;
351 * Is this a directory?
353 * Directories are only emulated, internally they are stored as empty
354 * files with a "." instead of name - this means empty directory contains
355 * exactly one empty file with name dot.
357 * @return bool true means directory, false means file
359 public function is_directory() {
360 return ($this->file_record->filename === '.');
364 * Delete file from files table.
366 * The content of files stored in sha1 pool is reclaimed
367 * later - the occupied disk space is reclaimed much later.
369 * @return bool always true or exception if error occurred
371 public function delete() {
372 global $DB;
374 if ($this->is_directory()) {
375 // Directories can not be referenced, just delete the record.
376 $DB->delete_records('files', array('id'=>$this->file_record->id));
378 } else {
379 $transaction = $DB->start_delegated_transaction();
381 // If there are other files referring to this file, convert them to copies.
382 if ($files = $this->fs->get_references_by_storedfile($this)) {
383 foreach ($files as $file) {
384 $this->fs->import_external_file($file);
388 // If this file is a reference (alias) to another file, unlink it first.
389 if ($this->is_external_file()) {
390 $this->delete_reference();
393 // Now delete the file record.
394 $DB->delete_records('files', array('id'=>$this->file_record->id));
396 $transaction->allow_commit();
398 if (!$this->is_directory()) {
399 // Callback for file deletion.
400 if ($pluginsfunction = get_plugins_with_function('after_file_deleted')) {
401 foreach ($pluginsfunction as $plugintype => $plugins) {
402 foreach ($plugins as $pluginfunction) {
403 $pluginfunction($this->file_record);
410 // Move pool file to trash if content not needed any more.
411 $this->filesystem->remove_file($this->file_record->contenthash);
412 return true; // BC only
416 * adds this file path to a curl request (POST only)
418 * @param curl $curlrequest the curl request object
419 * @param string $key what key to use in the POST request
420 * @return void
422 public function add_to_curl_request(&$curlrequest, $key) {
423 return $this->filesystem->add_to_curl_request($this, $curlrequest, $key);
427 * Returns file handle - read only mode, no writing allowed into pool files!
429 * When you want to modify a file, create a new file and delete the old one.
431 * @param int $type Type of file handle (FILE_HANDLE_xx constant)
432 * @return resource file handle
434 public function get_content_file_handle($type = self::FILE_HANDLE_FOPEN) {
435 return $this->filesystem->get_content_file_handle($this, $type);
439 * Dumps file content to page.
441 public function readfile() {
442 return $this->filesystem->readfile($this);
446 * Returns file content as string.
448 * @return string content
450 public function get_content() {
451 return $this->filesystem->get_content($this);
455 * Copy content of file to given pathname.
457 * @param string $pathname real path to the new file
458 * @return bool success
460 public function copy_content_to($pathname) {
461 return $this->filesystem->copy_content_from_storedfile($this, $pathname);
465 * Copy content of file to temporary folder and returns file path
467 * @param string $dir name of the temporary directory
468 * @param string $fileprefix prefix of temporary file.
469 * @return string|bool path of temporary file or false.
471 public function copy_content_to_temp($dir = 'files', $fileprefix = 'tempup_') {
472 $tempfile = false;
473 if (!$dir = make_temp_directory($dir)) {
474 return false;
476 if (!$tempfile = tempnam($dir, $fileprefix)) {
477 return false;
479 if (!$this->copy_content_to($tempfile)) {
480 // something went wrong
481 @unlink($tempfile);
482 return false;
484 return $tempfile;
488 * List contents of archive.
490 * @param file_packer $packer file packer instance
491 * @return array of file infos
493 public function list_files(file_packer $packer) {
494 return $this->filesystem->list_files($this, $packer);
498 * Extract file to given file path (real OS filesystem), existing files are overwritten.
500 * @param file_packer $packer file packer instance
501 * @param string $pathname target directory
502 * @param file_progress $progress Progress indicator callback or null if not required
503 * @return array|bool list of processed files; false if error
505 public function extract_to_pathname(file_packer $packer, $pathname,
506 file_progress $progress = null) {
507 return $this->filesystem->extract_to_pathname($this, $packer, $pathname, $progress);
511 * Extract file to given file path (real OS filesystem), existing files are overwritten.
513 * @param file_packer $packer file packer instance
514 * @param int $contextid context ID
515 * @param string $component component
516 * @param string $filearea file area
517 * @param int $itemid item ID
518 * @param string $pathbase path base
519 * @param int $userid user ID
520 * @param file_progress $progress Progress indicator callback or null if not required
521 * @return array|bool list of processed files; false if error
523 public function extract_to_storage(file_packer $packer, $contextid,
524 $component, $filearea, $itemid, $pathbase, $userid = null, file_progress $progress = null) {
526 return $this->filesystem->extract_to_storage($this, $packer, $contextid, $component, $filearea,
527 $itemid, $pathbase, $userid, $progress);
531 * Add file/directory into archive.
533 * @param file_archive $filearch file archive instance
534 * @param string $archivepath pathname in archive
535 * @return bool success
537 public function archive_file(file_archive $filearch, $archivepath) {
538 return $this->filesystem->add_storedfile_to_archive($this, $filearch, $archivepath);
542 * Returns information about image,
543 * information is determined from the file content
545 * @return mixed array with width, height and mimetype; false if not an image
547 public function get_imageinfo() {
548 return $this->filesystem->get_imageinfo($this);
552 * Verifies the file is a valid web image - gif, png and jpeg only.
554 * It should be ok to serve this image from server without any other security workarounds.
556 * @return bool true if file ok
558 public function is_valid_image() {
559 $mimetype = $this->get_mimetype();
560 if (!file_mimetype_in_typegroup($mimetype, 'web_image')) {
561 return false;
563 if (!$info = $this->get_imageinfo()) {
564 return false;
566 if ($info['mimetype'] !== $mimetype) {
567 return false;
569 // ok, GD likes this image
570 return true;
574 * Returns parent directory, creates missing parents if needed.
576 * @return stored_file
578 public function get_parent_directory() {
579 if ($this->file_record->filepath === '/' and $this->file_record->filename === '.') {
580 //root dir does not have parent
581 return null;
584 if ($this->file_record->filename !== '.') {
585 return $this->fs->create_directory($this->file_record->contextid, $this->file_record->component, $this->file_record->filearea, $this->file_record->itemid, $this->file_record->filepath);
588 $filepath = $this->file_record->filepath;
589 $filepath = trim($filepath, '/');
590 $dirs = explode('/', $filepath);
591 array_pop($dirs);
592 $filepath = implode('/', $dirs);
593 $filepath = ($filepath === '') ? '/' : "/$filepath/";
595 return $this->fs->create_directory($this->file_record->contextid, $this->file_record->component, $this->file_record->filearea, $this->file_record->itemid, $filepath);
599 * Set synchronised content from file.
601 * @param string $path Path to the file.
603 public function set_synchronised_content_from_file($path) {
604 $this->fs->synchronise_stored_file_from_file($this, $path, $this->file_record);
608 * Set synchronised content from content.
610 * @param string $content File content.
612 public function set_synchronised_content_from_string($content) {
613 $this->fs->synchronise_stored_file_from_string($this, $content, $this->file_record);
617 * Synchronize file if it is a reference and needs synchronizing
619 * Updates contenthash and filesize
621 public function sync_external_file() {
622 if (!empty($this->repository)) {
623 $this->repository->sync_reference($this);
628 * Returns context id of the file
630 * @return int context id
632 public function get_contextid() {
633 return $this->file_record->contextid;
637 * Returns component name - this is the owner of the areas,
638 * nothing else is allowed to read or modify the files directly!!
640 * @return string
642 public function get_component() {
643 return $this->file_record->component;
647 * Returns file area name, this divides files of one component into groups with different access control.
648 * All files in one area have the same access control.
650 * @return string
652 public function get_filearea() {
653 return $this->file_record->filearea;
657 * Returns returns item id of file.
659 * @return int
661 public function get_itemid() {
662 return $this->file_record->itemid;
666 * Returns file path - starts and ends with /, \ are not allowed.
668 * @return string
670 public function get_filepath() {
671 return $this->file_record->filepath;
675 * Returns file name or '.' in case of directories.
677 * @return string
679 public function get_filename() {
680 return $this->file_record->filename;
684 * Returns id of user who created the file.
686 * @return int
688 public function get_userid() {
689 return $this->file_record->userid;
693 * Returns the size of file in bytes.
695 * @return int bytes
697 public function get_filesize() {
698 $this->sync_external_file();
699 return $this->file_record->filesize;
703 * Function stored_file::set_filesize() is deprecated. Please use stored_file::replace_file_with
705 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
706 * @see stored_file::replace_file_with()
708 public function set_filesize($filesize) {
709 throw new coding_exception('Function stored_file::set_filesize() can not be used any more. ' .
710 'Please use stored_file::replace_file_with()');
714 * Returns mime type of file.
716 * @return string
718 public function get_mimetype() {
719 return $this->file_record->mimetype;
723 * Returns unix timestamp of file creation date.
725 * @return int
727 public function get_timecreated() {
728 return $this->file_record->timecreated;
732 * Returns unix timestamp of last file modification.
734 * @return int
736 public function get_timemodified() {
737 $this->sync_external_file();
738 return $this->file_record->timemodified;
742 * set timemodified
744 * @param int $timemodified
746 public function set_timemodified($timemodified) {
747 $filerecord = new stdClass;
748 $filerecord->timemodified = $timemodified;
749 $this->update($filerecord);
753 * Returns file status flag.
755 * @return int 0 means file OK, anything else is a problem and file can not be used
757 public function get_status() {
758 return $this->file_record->status;
762 * Returns file id.
764 * @return int
766 public function get_id() {
767 return $this->file_record->id;
771 * Returns sha1 hash of file content.
773 * @return string
775 public function get_contenthash() {
776 $this->sync_external_file();
777 return $this->file_record->contenthash;
781 * Returns sha1 hash of all file path components sha1("contextid/component/filearea/itemid/dir/dir/filename.ext").
783 * @return string
785 public function get_pathnamehash() {
786 return $this->file_record->pathnamehash;
790 * Returns the license type of the file, it is a short name referred from license table.
792 * @return string
794 public function get_license() {
795 return $this->file_record->license;
799 * Set license
801 * @param string $license license
803 public function set_license($license) {
804 $filerecord = new stdClass;
805 $filerecord->license = $license;
806 $this->update($filerecord);
810 * Returns the author name of the file.
812 * @return string
814 public function get_author() {
815 return $this->file_record->author;
819 * Set author
821 * @param string $author
823 public function set_author($author) {
824 $filerecord = new stdClass;
825 $filerecord->author = $author;
826 $this->update($filerecord);
830 * Returns the source of the file, usually it is a url.
832 * @return string
834 public function get_source() {
835 return $this->file_record->source;
839 * Set license
841 * @param string $license license
843 public function set_source($source) {
844 $filerecord = new stdClass;
845 $filerecord->source = $source;
846 $this->update($filerecord);
851 * Returns the sort order of file
853 * @return int
855 public function get_sortorder() {
856 return $this->file_record->sortorder;
860 * Set file sort order
862 * @param int $sortorder
863 * @return int
865 public function set_sortorder($sortorder) {
866 $oldorder = $this->file_record->sortorder;
867 $filerecord = new stdClass;
868 $filerecord->sortorder = $sortorder;
869 $this->update($filerecord);
870 if (!$this->is_directory()) {
871 // Callback for file sort order change.
872 if ($pluginsfunction = get_plugins_with_function('after_file_sorted')) {
873 foreach ($pluginsfunction as $plugintype => $plugins) {
874 foreach ($plugins as $pluginfunction) {
875 $pluginfunction($this->file_record, $oldorder, $sortorder);
883 * Returns repository id
885 * @return int|null
887 public function get_repository_id() {
888 if (!empty($this->repository)) {
889 return $this->repository->id;
890 } else {
891 return null;
896 * Returns repository type.
898 * @return mixed str|null the repository type or null if is not an external file
899 * @since Moodle 3.3
901 public function get_repository_type() {
903 if (!empty($this->repository)) {
904 return $this->repository->get_typename();
905 } else {
906 return null;
912 * get reference file id
913 * @return int
915 public function get_referencefileid() {
916 return $this->file_record->referencefileid;
920 * Get reference last sync time
921 * @return int
923 public function get_referencelastsync() {
924 return $this->file_record->referencelastsync;
928 * Function stored_file::get_referencelifetime() is deprecated as reference
929 * life time is no longer stored in DB or returned by repository. Each
930 * repository should decide by itself when to synchronise the references.
932 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
933 * @see repository::sync_reference()
935 public function get_referencelifetime() {
936 throw new coding_exception('Function stored_file::get_referencelifetime() can not be used any more. ' .
937 'See repository::sync_reference().');
940 * Returns file reference
942 * @return string
944 public function get_reference() {
945 return $this->file_record->reference;
949 * Get human readable file reference information
951 * @return string
953 public function get_reference_details() {
954 return $this->repository->get_reference_details($this->get_reference(), $this->get_status());
958 * Called after reference-file has been synchronized with the repository
960 * We update contenthash, filesize and status in files table if changed
961 * and we always update lastsync in files_reference table
963 * @param null|string $contenthash if set to null contenthash is not changed
964 * @param int $filesize new size of the file
965 * @param int $status new status of the file (0 means OK, 666 - source missing)
966 * @param int $timemodified last time modified of the source, if known
968 public function set_synchronized($contenthash, $filesize, $status = 0, $timemodified = null) {
969 if (!$this->is_external_file()) {
970 return;
972 $now = time();
973 if ($contenthash === null) {
974 $contenthash = $this->file_record->contenthash;
976 if ($contenthash != $this->file_record->contenthash) {
977 $oldcontenthash = $this->file_record->contenthash;
979 // this will update all entries in {files} that have the same filereference id
980 $this->fs->update_references($this->file_record->referencefileid, $now, null, $contenthash, $filesize, $status, $timemodified);
981 // we don't need to call update() for this object, just set the values of changed fields
982 $this->file_record->contenthash = $contenthash;
983 $this->file_record->filesize = $filesize;
984 $this->file_record->status = $status;
985 $this->file_record->referencelastsync = $now;
986 if ($timemodified) {
987 $this->file_record->timemodified = $timemodified;
989 if (isset($oldcontenthash)) {
990 $this->filesystem->remove_file($oldcontenthash);
995 * Sets the error status for a file that could not be synchronised
997 public function set_missingsource() {
998 $this->set_synchronized($this->file_record->contenthash, $this->file_record->filesize, 666);
1002 * Send file references
1004 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1005 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1006 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1007 * @param array $options additional options affecting the file serving
1009 public function send_file($lifetime, $filter, $forcedownload, $options) {
1010 $this->repository->send_file($this, $lifetime, $filter, $forcedownload, $options);
1014 * Imports the contents of an external file into moodle filepool.
1016 * @throws moodle_exception if file could not be downloaded or is too big
1017 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1019 public function import_external_file_contents($maxbytes = 0) {
1020 if ($this->repository) {
1021 $this->repository->import_external_file_contents($this, $maxbytes);
1026 * Gets a file relative to this file in the repository and sends it to the browser.
1027 * Checks the function repository::supports_relative_file() to make sure it can be used.
1029 * @param string $relativepath the relative path to the file we are trying to access
1031 public function send_relative_file($relativepath) {
1032 if ($this->repository && $this->repository->supports_relative_file()) {
1033 $relativepath = clean_param($relativepath, PARAM_PATH);
1034 $this->repository->send_relative_file($this, $relativepath);
1035 } else {
1036 send_file_not_found();
1041 * Generates a thumbnail for this stored_file.
1043 * If the GD library has at least version 2 and PNG support is available, the returned data
1044 * is the content of a transparent PNG file containing the thumbnail. Otherwise, the function
1045 * returns contents of a JPEG file with black background containing the thumbnail.
1047 * @param int $width the width of the requested thumbnail
1048 * @param int $height the height of the requested thumbnail
1049 * @return string|bool false if a problem occurs, the thumbnail image data otherwise
1051 public function generate_image_thumbnail($width, $height) {
1052 if (empty($width) or empty($height)) {
1053 return false;
1056 $content = $this->get_content();
1058 // Fetch the image information for this image.
1059 $imageinfo = @getimagesizefromstring($content);
1060 if (empty($imageinfo)) {
1061 return false;
1064 // Create a new image from the file.
1065 $original = @imagecreatefromstring($content);
1067 // Generate the thumbnail.
1068 return generate_image_thumbnail_from_image($original, $imageinfo, $width, $height);
1072 * Generate a resized image for this stored_file.
1074 * @param int|null $width The desired width, or null to only use the height.
1075 * @param int|null $height The desired height, or null to only use the width.
1076 * @return string|false False when a problem occurs, else the image data.
1078 public function resize_image($width, $height) {
1079 global $CFG;
1080 require_once($CFG->libdir . '/gdlib.php');
1082 $content = $this->get_content();
1084 // Fetch the image information for this image.
1085 $imageinfo = @getimagesizefromstring($content);
1086 if (empty($imageinfo)) {
1087 return false;
1090 // Create a new image from the file.
1091 $original = @imagecreatefromstring($content);
1093 // Generate the resized image.
1094 return resize_image_from_image($original, $imageinfo, $width, $height);
1098 * Check whether the supplied file is the same as this file.
1100 * @param string $path The path to the file on disk
1101 * @return boolean
1103 public function compare_to_path($path) {
1104 return $this->get_contenthash() === file_storage::hash_from_path($path);
1108 * Check whether the supplied content is the same as this file.
1110 * @param string $content The file content
1111 * @return boolean
1113 public function compare_to_string($content) {
1114 return $this->get_contenthash() === file_storage::hash_from_string($content);