f1e6c248825c01392d4734ad2bf6180e25438671
[moodle.git] / lib / filestorage / stored_file.php
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.
13 //
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.
20  *
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
24  */
26 defined('MOODLE_INTERNAL') || die();
28 require_once($CFG->dirroot . '/lib/filestorage/file_progress.php');
30 /**
31  * Class representing local files stored in a sha1 file pool.
32  *
33  * Since Moodle 2.0 file contents are stored in sha1 pool and
34  * all other file information is stored in new "files" database table.
35  *
36  * @package   core_files
37  * @category  files
38  * @copyright 2008 Petr Skoda {@link http://skodak.org}
39  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40  * @since     Moodle 2.0
41  */
42 class stored_file {
43     /** @var file_storage file storage pool instance */
44     private $fs;
45     /** @var stdClass record from the files table left join files_reference table */
46     private $file_record;
47     /** @var string location of content files */
48     private $filedir;
49     /** @var repository repository plugin instance */
50     private $repository;
52     /**
53      * Constructor, this constructor should be called ONLY from the file_storage class!
54      *
55      * @param file_storage $fs file  storage instance
56      * @param stdClass $file_record description of file
57      * @param string $filedir location of file directory with sh1 named content files
58      */
59     public function __construct(file_storage $fs, stdClass $file_record, $filedir) {
60         global $DB, $CFG;
61         $this->fs          = $fs;
62         $this->file_record = clone($file_record); // prevent modifications
63         $this->filedir     = $filedir; // keep secret, do not expose!
65         if (!empty($file_record->repositoryid)) {
66             require_once("$CFG->dirroot/repository/lib.php");
67             $this->repository = repository::get_repository_by_id($file_record->repositoryid, SYSCONTEXTID);
68             if ($this->repository->supported_returntypes() & FILE_REFERENCE != FILE_REFERENCE) {
69                 // Repository cannot do file reference.
70                 throw new moodle_exception('error');
71             }
72         } else {
73             $this->repository = null;
74         }
75         // make sure all reference fields exist in file_record even when it is not a reference
76         foreach (array('referencelastsync', 'referencelifetime', 'referencefileid', 'reference', 'repositoryid') as $key) {
77             if (empty($this->file_record->$key)) {
78                 $this->file_record->$key = null;
79             }
80         }
81     }
83     /**
84      * Whether or not this is a external resource
85      *
86      * @return bool
87      */
88     public function is_external_file() {
89         return !empty($this->repository);
90     }
92     /**
93      * Update some file record fields
94      * NOTE: Must remain protected
95      *
96      * @param stdClass $dataobject
97      */
98     protected function update($dataobject) {
99         global $DB;
100         $keys = array_keys((array)$this->file_record);
101         foreach ($dataobject as $field => $value) {
102             if (in_array($field, $keys)) {
103                 if ($field == 'contextid' and (!is_number($value) or $value < 1)) {
104                     throw new file_exception('storedfileproblem', 'Invalid contextid');
105                 }
107                 if ($field == 'component') {
108                     $value = clean_param($value, PARAM_COMPONENT);
109                     if (empty($value)) {
110                         throw new file_exception('storedfileproblem', 'Invalid component');
111                     }
112                 }
114                 if ($field == 'filearea') {
115                     $value = clean_param($value, PARAM_AREA);
116                     if (empty($value)) {
117                         throw new file_exception('storedfileproblem', 'Invalid filearea');
118                     }
119                 }
121                 if ($field == 'itemid' and (!is_number($value) or $value < 0)) {
122                     throw new file_exception('storedfileproblem', 'Invalid itemid');
123                 }
126                 if ($field == 'filepath') {
127                     $value = clean_param($value, PARAM_PATH);
128                     if (strpos($value, '/') !== 0 or strrpos($value, '/') !== strlen($value)-1) {
129                         // path must start and end with '/'
130                         throw new file_exception('storedfileproblem', 'Invalid file path');
131                     }
132                 }
134                 if ($field == 'filename') {
135                     // folder has filename == '.', so we pass this
136                     if ($value != '.') {
137                         $value = clean_param($value, PARAM_FILE);
138                     }
139                     if ($value === '') {
140                         throw new file_exception('storedfileproblem', 'Invalid file name');
141                     }
142                 }
144                 if ($field === 'timecreated' or $field === 'timemodified') {
145                     if (!is_number($value)) {
146                         throw new file_exception('storedfileproblem', 'Invalid timestamp');
147                     }
148                     if ($value < 0) {
149                         $value = 0;
150                     }
151                 }
153                 if ($field === 'referencefileid') {
154                     if (!is_null($value) and !is_number($value)) {
155                         throw new file_exception('storedfileproblem', 'Invalid reference info');
156                     }
157                 }
159                 if ($field === 'referencelastsync' or $field === 'referencelifetime') {
160                     // do not update those fields
161                     // TODO MDL-33416 [2.4] fields referencelastsync and referencelifetime to be removed from {files} table completely
162                     continue;
163                 }
165                 // adding the field
166                 $this->file_record->$field = $value;
167             } else {
168                 throw new coding_exception("Invalid field name, $field doesn't exist in file record");
169             }
170         }
171         // Validate mimetype field
172         // we don't use {@link stored_file::get_content_file_location()} here becaues it will try to update file_record
173         $pathname = $this->get_pathname_by_contenthash();
174         // try to recover the content from trash
175         if (!is_readable($pathname)) {
176             if (!$this->fs->try_content_recovery($this) or !is_readable($pathname)) {
177                 throw new file_exception('storedfilecannotread', '', $pathname);
178             }
179         }
180         $mimetype = $this->fs->mimetype($pathname, $this->file_record->filename);
181         $this->file_record->mimetype = $mimetype;
183         $DB->update_record('files', $this->file_record);
184     }
186     /**
187      * Rename filename
188      *
189      * @param string $filepath file path
190      * @param string $filename file name
191      */
192     public function rename($filepath, $filename) {
193         if ($this->fs->file_exists($this->get_contextid(), $this->get_component(), $this->get_filearea(), $this->get_itemid(), $filepath, $filename)) {
194             throw new file_exception('storedfilenotcreated', '', 'file exists, cannot rename');
195         }
196         $filerecord = new stdClass;
197         $filerecord->filepath = $filepath;
198         $filerecord->filename = $filename;
199         // populate the pathname hash
200         $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);
201         $this->update($filerecord);
202     }
204     /**
205      * Replace the content by providing another stored_file instance
206      *
207      * @param stored_file $storedfile
208      */
209     public function replace_content_with(stored_file $storedfile) {
210         $contenthash = $storedfile->get_contenthash();
211         $this->set_contenthash($contenthash);
212         $this->set_filesize($storedfile->get_filesize());
213     }
215     /**
216      * Replaces the fields that might have changed when file was overriden in filepicker:
217      * reference, contenthash, filesize, userid
218      *
219      * Note that field 'source' must be updated separately because
220      * it has different format for draft and non-draft areas and
221      * this function will usually be used to replace non-draft area
222      * file with draft area file.
223      *
224      * @param stored_file $newfile
225      * @throws coding_exception
226      */
227     public function replace_file_with(stored_file $newfile) {
228         if ($newfile->get_referencefileid() &&
229                 $this->fs->get_references_count_by_storedfile($this)) {
230             // The new file is a reference.
231             // The current file has other local files referencing to it.
232             // Double reference is not allowed.
233             throw new moodle_exception('errordoublereference', 'repository');
234         }
236         $filerecord = new stdClass;
237         $contenthash = $newfile->get_contenthash();
238         if ($this->fs->content_exists($contenthash)) {
239             $filerecord->contenthash = $contenthash;
240         } else {
241             throw new file_exception('storedfileproblem', 'Invalid contenthash, content must be already in filepool', $contenthash);
242         }
243         $filerecord->filesize = $newfile->get_filesize();
244         $filerecord->referencefileid = $newfile->get_referencefileid();
245         $filerecord->userid = $newfile->get_userid();
246         $this->update($filerecord);
247     }
249     /**
250      * Unlink the stored file from the referenced file
251      *
252      * This methods destroys the link to the record in files_reference table. This effectively
253      * turns the stored file from being an alias to a plain copy. However, the caller has
254      * to make sure that the actual file's content has beed synced prior to calling this method.
255      */
256     public function delete_reference() {
257         global $DB;
259         if (!$this->is_external_file()) {
260             throw new coding_exception('An attempt to unlink a non-reference file.');
261         }
263         $transaction = $DB->start_delegated_transaction();
265         // Are we the only one referring to the original file? If so, delete the
266         // referenced file record. Note we do not use file_storage::search_references_count()
267         // here because we want to count draft files too and we are at a bit lower access level here.
268         $countlinks = $DB->count_records('files',
269             array('referencefileid' => $this->file_record->referencefileid));
270         if ($countlinks == 1) {
271             $DB->delete_records('files_reference', array('id' => $this->file_record->referencefileid));
272         }
274         // Update the underlying record in the database.
275         $update = new stdClass();
276         $update->referencefileid = null;
277         $this->update($update);
279         $transaction->allow_commit();
281         // Update our properties and the record in the memory.
282         $this->repository = null;
283         $this->file_record->repositoryid = null;
284         $this->file_record->reference = null;
285         $this->file_record->referencefileid = null;
286         $this->file_record->referencelastsync = null;
287         $this->file_record->referencelifetime = null;
288     }
290     /**
291      * Is this a directory?
292      *
293      * Directories are only emulated, internally they are stored as empty
294      * files with a "." instead of name - this means empty directory contains
295      * exactly one empty file with name dot.
296      *
297      * @return bool true means directory, false means file
298      */
299     public function is_directory() {
300         return ($this->file_record->filename === '.');
301     }
303     /**
304      * Delete file from files table.
305      *
306      * The content of files stored in sha1 pool is reclaimed
307      * later - the occupied disk space is reclaimed much later.
308      *
309      * @return bool always true or exception if error occurred
310      */
311     public function delete() {
312         global $DB;
314         if ($this->is_directory()) {
315             // Directories can not be referenced, just delete the record.
316             $DB->delete_records('files', array('id'=>$this->file_record->id));
318         } else {
319             $transaction = $DB->start_delegated_transaction();
321             // If there are other files referring to this file, convert them to copies.
322             if ($files = $this->fs->get_references_by_storedfile($this)) {
323                 foreach ($files as $file) {
324                     $this->fs->import_external_file($file);
325                 }
326             }
328             // If this file is a reference (alias) to another file, unlink it first.
329             if ($this->is_external_file()) {
330                 $this->delete_reference();
331             }
333             // Now delete the file record.
334             $DB->delete_records('files', array('id'=>$this->file_record->id));
336             $transaction->allow_commit();
337         }
339         // Move pool file to trash if content not needed any more.
340         $this->fs->deleted_file_cleanup($this->file_record->contenthash);
341         return true; // BC only
342     }
344     /**
345      * Get file pathname by contenthash
346      *
347      * NOTE, this function is not calling sync_external_file, it assume the contenthash is current
348      * Protected - developers must not gain direct access to this function.
349      *
350      * @return string full path to pool file with file content
351      */
352     protected function get_pathname_by_contenthash() {
353         // Detect is local file or not.
354         $contenthash = $this->file_record->contenthash;
355         $l1 = $contenthash[0].$contenthash[1];
356         $l2 = $contenthash[2].$contenthash[3];
357         return "$this->filedir/$l1/$l2/$contenthash";
358     }
360     /**
361      * Get file pathname by given contenthash, this method will try to sync files
362      *
363      * Protected - developers must not gain direct access to this function.
364      *
365      * NOTE: do not make this public, we must not modify or delete the pool files directly! ;-)
366      *
367      * @return string full path to pool file with file content
368      **/
369     protected function get_content_file_location() {
370         $this->sync_external_file();
371         return $this->get_pathname_by_contenthash();
372     }
374     /**
375     * adds this file path to a curl request (POST only)
376     *
377     * @param curl $curlrequest the curl request object
378     * @param string $key what key to use in the POST request
379     * @return void
380     */
381     public function add_to_curl_request(&$curlrequest, $key) {
382         $curlrequest->_tmp_file_post_params[$key] = '@' . $this->get_content_file_location();
383     }
385     /**
386      * Returns file handle - read only mode, no writing allowed into pool files!
387      *
388      * When you want to modify a file, create a new file and delete the old one.
389      *
390      * @return resource file handle
391      */
392     public function get_content_file_handle() {
393         $path = $this->get_content_file_location();
394         if (!is_readable($path)) {
395             if (!$this->fs->try_content_recovery($this) or !is_readable($path)) {
396                 throw new file_exception('storedfilecannotread', '', $path);
397             }
398         }
399         return fopen($path, 'rb'); // Binary reading only!!
400     }
402     /**
403      * Dumps file content to page.
404      */
405     public function readfile() {
406         $path = $this->get_content_file_location();
407         if (!is_readable($path)) {
408             if (!$this->fs->try_content_recovery($this) or !is_readable($path)) {
409                 throw new file_exception('storedfilecannotread', '', $path);
410             }
411         }
412         readfile_allow_large($path, $this->get_filesize());
413     }
415     /**
416      * Returns file content as string.
417      *
418      * @return string content
419      */
420     public function get_content() {
421         $path = $this->get_content_file_location();
422         if (!is_readable($path)) {
423             if (!$this->fs->try_content_recovery($this) or !is_readable($path)) {
424                 throw new file_exception('storedfilecannotread', '', $path);
425             }
426         }
427         return file_get_contents($this->get_content_file_location());
428     }
430     /**
431      * Copy content of file to given pathname.
432      *
433      * @param string $pathname real path to the new file
434      * @return bool success
435      */
436     public function copy_content_to($pathname) {
437         $path = $this->get_content_file_location();
438         if (!is_readable($path)) {
439             if (!$this->fs->try_content_recovery($this) or !is_readable($path)) {
440                 throw new file_exception('storedfilecannotread', '', $path);
441             }
442         }
443         return copy($path, $pathname);
444     }
446     /**
447      * Copy content of file to temporary folder and returns file path
448      *
449      * @param string $dir name of the temporary directory
450      * @param string $fileprefix prefix of temporary file.
451      * @return string|bool path of temporary file or false.
452      */
453     public function copy_content_to_temp($dir = 'files', $fileprefix = 'tempup_') {
454         $tempfile = false;
455         if (!$dir = make_temp_directory($dir)) {
456             return false;
457         }
458         if (!$tempfile = tempnam($dir, $fileprefix)) {
459             return false;
460         }
461         if (!$this->copy_content_to($tempfile)) {
462             // something went wrong
463             @unlink($tempfile);
464             return false;
465         }
466         return $tempfile;
467     }
469     /**
470      * List contents of archive.
471      *
472      * @param file_packer $packer file packer instance
473      * @return array of file infos
474      */
475     public function list_files(file_packer $packer) {
476         $archivefile = $this->get_content_file_location();
477         return $packer->list_files($archivefile);
478     }
480     /**
481      * Extract file to given file path (real OS filesystem), existing files are overwritten.
482      *
483      * @param file_packer $packer file packer instance
484      * @param string $pathname target directory
485      * @param file_progress $progress Progress indicator callback or null if not required
486      * @return array|bool list of processed files; false if error
487      */
488     public function extract_to_pathname(file_packer $packer, $pathname,
489             file_progress $progress = null) {
490         $archivefile = $this->get_content_file_location();
491         return $packer->extract_to_pathname($archivefile, $pathname, null, $progress);
492     }
494     /**
495      * Extract file to given file path (real OS filesystem), existing files are overwritten.
496      *
497      * @param file_packer $packer file packer instance
498      * @param int $contextid context ID
499      * @param string $component component
500      * @param string $filearea file area
501      * @param int $itemid item ID
502      * @param string $pathbase path base
503      * @param int $userid user ID
504      * @param file_progress $progress Progress indicator callback or null if not required
505      * @return array|bool list of processed files; false if error
506      */
507     public function extract_to_storage(file_packer $packer, $contextid,
508             $component, $filearea, $itemid, $pathbase, $userid = null, file_progress $progress = null) {
509         $archivefile = $this->get_content_file_location();
510         return $packer->extract_to_storage($archivefile, $contextid,
511                 $component, $filearea, $itemid, $pathbase, $userid, $progress);
512     }
514     /**
515      * Add file/directory into archive.
516      *
517      * @param file_archive $filearch file archive instance
518      * @param string $archivepath pathname in archive
519      * @return bool success
520      */
521     public function archive_file(file_archive $filearch, $archivepath) {
522         if ($this->is_directory()) {
523             return $filearch->add_directory($archivepath);
524         } else {
525             $path = $this->get_content_file_location();
526             if (!is_readable($path)) {
527                 return false;
528             }
529             return $filearch->add_file_from_pathname($archivepath, $path);
530         }
531     }
533     /**
534      * Returns information about image,
535      * information is determined from the file content
536      *
537      * @return mixed array with width, height and mimetype; false if not an image
538      */
539     public function get_imageinfo() {
540         $path = $this->get_content_file_location();
541         if (!is_readable($path)) {
542             if (!$this->fs->try_content_recovery($this) or !is_readable($path)) {
543                 throw new file_exception('storedfilecannotread', '', $path);
544             }
545         }
546         $mimetype = $this->get_mimetype();
547         if (!preg_match('|^image/|', $mimetype) || !filesize($path) || !($imageinfo = getimagesize($path))) {
548             return false;
549         }
550         $image = array('width'=>$imageinfo[0], 'height'=>$imageinfo[1], 'mimetype'=>image_type_to_mime_type($imageinfo[2]));
551         if (empty($image['width']) or empty($image['height']) or empty($image['mimetype'])) {
552             // gd can not parse it, sorry
553             return false;
554         }
555         return $image;
556     }
558     /**
559      * Verifies the file is a valid web image - gif, png and jpeg only.
560      *
561      * It should be ok to serve this image from server without any other security workarounds.
562      *
563      * @return bool true if file ok
564      */
565     public function is_valid_image() {
566         $mimetype = $this->get_mimetype();
567         if (!file_mimetype_in_typegroup($mimetype, 'web_image')) {
568             return false;
569         }
570         if (!$info = $this->get_imageinfo()) {
571             return false;
572         }
573         if ($info['mimetype'] !== $mimetype) {
574             return false;
575         }
576         // ok, GD likes this image
577         return true;
578     }
580     /**
581      * Returns parent directory, creates missing parents if needed.
582      *
583      * @return stored_file
584      */
585     public function get_parent_directory() {
586         if ($this->file_record->filepath === '/' and $this->file_record->filename === '.') {
587             //root dir does not have parent
588             return null;
589         }
591         if ($this->file_record->filename !== '.') {
592             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);
593         }
595         $filepath = $this->file_record->filepath;
596         $filepath = trim($filepath, '/');
597         $dirs = explode('/', $filepath);
598         array_pop($dirs);
599         $filepath = implode('/', $dirs);
600         $filepath = ($filepath === '') ? '/' : "/$filepath/";
602         return $this->fs->create_directory($this->file_record->contextid, $this->file_record->component, $this->file_record->filearea, $this->file_record->itemid, $filepath);
603     }
605     /**
606      * Synchronize file if it is a reference and needs synchronizing
607      *
608      * Updates contenthash and filesize
609      */
610     public function sync_external_file() {
611         global $CFG;
612         if (!empty($this->file_record->referencefileid)) {
613             require_once($CFG->dirroot.'/repository/lib.php');
614             repository::sync_external_file($this);
615         }
616     }
618     /**
619      * Returns context id of the file
620      *
621      * @return int context id
622      */
623     public function get_contextid() {
624         return $this->file_record->contextid;
625     }
627     /**
628      * Returns component name - this is the owner of the areas,
629      * nothing else is allowed to read or modify the files directly!!
630      *
631      * @return string
632      */
633     public function get_component() {
634         return $this->file_record->component;
635     }
637     /**
638      * Returns file area name, this divides files of one component into groups with different access control.
639      * All files in one area have the same access control.
640      *
641      * @return string
642      */
643     public function get_filearea() {
644         return $this->file_record->filearea;
645     }
647     /**
648      * Returns returns item id of file.
649      *
650      * @return int
651      */
652     public function get_itemid() {
653         return $this->file_record->itemid;
654     }
656     /**
657      * Returns file path - starts and ends with /, \ are not allowed.
658      *
659      * @return string
660      */
661     public function get_filepath() {
662         return $this->file_record->filepath;
663     }
665     /**
666      * Returns file name or '.' in case of directories.
667      *
668      * @return string
669      */
670     public function get_filename() {
671         return $this->file_record->filename;
672     }
674     /**
675      * Returns id of user who created the file.
676      *
677      * @return int
678      */
679     public function get_userid() {
680         return $this->file_record->userid;
681     }
683     /**
684      * Returns the size of file in bytes.
685      *
686      * @return int bytes
687      */
688     public function get_filesize() {
689         $this->sync_external_file();
690         return $this->file_record->filesize;
691     }
693     /**
694      * Returns the size of file in bytes.
695      *
696      * @param int $filesize bytes
697      */
698     public function set_filesize($filesize) {
699         $filerecord = new stdClass;
700         $filerecord->filesize = $filesize;
701         $this->update($filerecord);
702     }
704     /**
705      * Returns mime type of file.
706      *
707      * @return string
708      */
709     public function get_mimetype() {
710         return $this->file_record->mimetype;
711     }
713     /**
714      * Returns unix timestamp of file creation date.
715      *
716      * @return int
717      */
718     public function get_timecreated() {
719         return $this->file_record->timecreated;
720     }
722     /**
723      * Returns unix timestamp of last file modification.
724      *
725      * @return int
726      */
727     public function get_timemodified() {
728         $this->sync_external_file();
729         return $this->file_record->timemodified;
730     }
732     /**
733      * set timemodified
734      *
735      * @param int $timemodified
736      */
737     public function set_timemodified($timemodified) {
738         $filerecord = new stdClass;
739         $filerecord->timemodified = $timemodified;
740         $this->update($filerecord);
741     }
743     /**
744      * Returns file status flag.
745      *
746      * @return int 0 means file OK, anything else is a problem and file can not be used
747      */
748     public function get_status() {
749         return $this->file_record->status;
750     }
752     /**
753      * Returns file id.
754      *
755      * @return int
756      */
757     public function get_id() {
758         return $this->file_record->id;
759     }
761     /**
762      * Returns sha1 hash of file content.
763      *
764      * @return string
765      */
766     public function get_contenthash() {
767         $this->sync_external_file();
768         return $this->file_record->contenthash;
769     }
771     /**
772      * Set contenthash
773      *
774      * @param string $contenthash
775      */
776     protected function set_contenthash($contenthash) {
777         // make sure the content exists in moodle file pool
778         if ($this->fs->content_exists($contenthash)) {
779             $filerecord = new stdClass;
780             $filerecord->contenthash = $contenthash;
781             $this->update($filerecord);
782         } else {
783             throw new file_exception('storedfileproblem', 'Invalid contenthash, content must be already in filepool', $contenthash);
784         }
785     }
787     /**
788      * Returns sha1 hash of all file path components sha1("contextid/component/filearea/itemid/dir/dir/filename.ext").
789      *
790      * @return string
791      */
792     public function get_pathnamehash() {
793         return $this->file_record->pathnamehash;
794     }
796     /**
797      * Returns the license type of the file, it is a short name referred from license table.
798      *
799      * @return string
800      */
801     public function get_license() {
802         return $this->file_record->license;
803     }
805     /**
806      * Set license
807      *
808      * @param string $license license
809      */
810     public function set_license($license) {
811         $filerecord = new stdClass;
812         $filerecord->license = $license;
813         $this->update($filerecord);
814     }
816     /**
817      * Returns the author name of the file.
818      *
819      * @return string
820      */
821     public function get_author() {
822         return $this->file_record->author;
823     }
825     /**
826      * Set author
827      *
828      * @param string $author
829      */
830     public function set_author($author) {
831         $filerecord = new stdClass;
832         $filerecord->author = $author;
833         $this->update($filerecord);
834     }
836     /**
837      * Returns the source of the file, usually it is a url.
838      *
839      * @return string
840      */
841     public function get_source() {
842         return $this->file_record->source;
843     }
845     /**
846      * Set license
847      *
848      * @param string $license license
849      */
850     public function set_source($source) {
851         $filerecord = new stdClass;
852         $filerecord->source = $source;
853         $this->update($filerecord);
854     }
857     /**
858      * Returns the sort order of file
859      *
860      * @return int
861      */
862     public function get_sortorder() {
863         return $this->file_record->sortorder;
864     }
866     /**
867      * Set file sort order
868      *
869      * @param int $sortorder
870      * @return int
871      */
872     public function set_sortorder($sortorder) {
873         $filerecord = new stdClass;
874         $filerecord->sortorder = $sortorder;
875         $this->update($filerecord);
876     }
878     /**
879      * Returns repository id
880      *
881      * @return int|null
882      */
883     public function get_repository_id() {
884         if (!empty($this->repository)) {
885             return $this->repository->id;
886         } else {
887             return null;
888         }
889     }
891     /**
892      * get reference file id
893      * @return int
894      */
895     public function get_referencefileid() {
896         return $this->file_record->referencefileid;
897     }
899     /**
900      * Get reference last sync time
901      * @return int
902      */
903     public function get_referencelastsync() {
904         return $this->file_record->referencelastsync;
905     }
907     /**
908      * Get reference last sync time
909      * @return int
910      */
911     public function get_referencelifetime() {
912         return $this->file_record->referencelifetime;
913     }
914     /**
915      * Returns file reference
916      *
917      * @return string
918      */
919     public function get_reference() {
920         return $this->file_record->reference;
921     }
923     /**
924      * Get human readable file reference information
925      *
926      * @return string
927      */
928     public function get_reference_details() {
929         return $this->repository->get_reference_details($this->get_reference(), $this->get_status());
930     }
932     /**
933      * Called after reference-file has been synchronized with the repository
934      *
935      * We update contenthash, filesize and status in files table if changed
936      * and we always update lastsync in files_reference table
937      *
938      * @param string $contenthash
939      * @param int $filesize
940      * @param int $status
941      * @param int $lifetime the life time of this synchronisation results
942      */
943     public function set_synchronized($contenthash, $filesize, $status = 0, $lifetime = null) {
944         global $DB;
945         if (!$this->is_external_file()) {
946             return;
947         }
948         $now = time();
949         if ($contenthash != $this->file_record->contenthash) {
950             $oldcontenthash = $this->file_record->contenthash;
951         }
952         if ($lifetime === null) {
953             $lifetime = $this->file_record->referencelifetime;
954         }
955         // this will update all entries in {files} that have the same filereference id
956         $this->fs->update_references($this->file_record->referencefileid, $now, $lifetime, $contenthash, $filesize, $status);
957         // we don't need to call update() for this object, just set the values of changed fields
958         $this->file_record->contenthash = $contenthash;
959         $this->file_record->filesize = $filesize;
960         $this->file_record->status = $status;
961         $this->file_record->referencelastsync = $now;
962         $this->file_record->referencelifetime = $lifetime;
963         if (isset($oldcontenthash)) {
964             $this->fs->deleted_file_cleanup($oldcontenthash);
965         }
966     }
968     /**
969      * Sets the error status for a file that could not be synchronised
970      *
971      * @param int $lifetime the life time of this synchronisation results
972      */
973     public function set_missingsource($lifetime = null) {
974         $this->set_synchronized($this->get_contenthash(), $this->get_filesize(), 666, $lifetime);
975     }
977     /**
978      * Send file references
979      *
980      * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
981      * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
982      * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
983      * @param array $options additional options affecting the file serving
984      */
985     public function send_file($lifetime, $filter, $forcedownload, $options) {
986         $this->repository->send_file($this, $lifetime, $filter, $forcedownload, $options);
987     }
989     /**
990      * Imports the contents of an external file into moodle filepool.
991      *
992      * @throws moodle_exception if file could not be downloaded or is too big
993      * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
994      */
995     public function import_external_file_contents($maxbytes = 0) {
996         if ($this->repository) {
997             $this->repository->import_external_file_contents($this, $maxbytes);
998         }
999     }