MDL-59700 filestorage: Add before_file_created hook
[moodle.git] / lib / filestorage / stored_file.php
CommitLineData
16a95e8f 1<?php
16a95e8f 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/>.
16
17
18/**
8496fdac 19 * Definition of a class stored_file.
16a95e8f 20 *
d2b7803e
DC
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
16a95e8f 24 */
25
64f93798
PS
26defined('MOODLE_INTERNAL') || die();
27
71ab7e51 28require_once($CFG->dirroot . '/lib/filestorage/file_progress.php');
16a34ae1 29require_once($CFG->dirroot . '/lib/filestorage/file_system.php');
71ab7e51 30
172dd12c 31/**
8496fdac
PS
32 * Class representing local files stored in a sha1 file pool.
33 *
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.
36 *
d2b7803e
DC
37 * @package core_files
38 * @category files
8496fdac
PS
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
172dd12c 42 */
43class stored_file {
8496fdac 44 /** @var file_storage file storage pool instance */
172dd12c 45 private $fs;
04e3b007 46 /** @var stdClass record from the files table left join files_reference table */
172dd12c 47 private $file_record;
67233725 48 /** @var repository repository plugin instance */
291a3d1f 49 private $repository;
16a34ae1
AN
50 /** @var file_system filesystem instance */
51 private $filesystem;
172dd12c 52
c858655d 53 /**
54 * @var int Indicates a file handle of the type returned by fopen.
55 */
56 const FILE_HANDLE_FOPEN = 0;
57
58 /**
59 * @var int Indicates a file handle of the type returned by gzopen.
60 */
61 const FILE_HANDLE_GZOPEN = 1;
62
63
172dd12c 64 /**
8496fdac
PS
65 * Constructor, this constructor should be called ONLY from the file_storage class!
66 *
67 * @param file_storage $fs file storage instance
d2b7803e 68 * @param stdClass $file_record description of file
16a34ae1 69 * @param string $deprecated
172dd12c 70 */
16a34ae1 71 public function __construct(file_storage $fs, stdClass $file_record, $deprecated = null) {
67233725 72 global $DB, $CFG;
8496fdac
PS
73 $this->fs = $fs;
74 $this->file_record = clone($file_record); // prevent modifications
67233725
DC
75
76 if (!empty($file_record->repositoryid)) {
b99065be 77 require_once("$CFG->dirroot/repository/lib.php");
67233725
DC
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');
82 }
83 } else {
84 $this->repository = null;
85 }
42aa6e15 86 // make sure all reference fields exist in file_record even when it is not a reference
87355560 87 foreach (array('referencelastsync', 'referencefileid', 'reference', 'repositoryid') as $key) {
42aa6e15
MG
88 if (empty($this->file_record->$key)) {
89 $this->file_record->$key = null;
90 }
91 }
16a34ae1
AN
92
93 $this->filesystem = $fs->get_file_system();
67233725
DC
94 }
95
e927581a
JD
96 /**
97 * Magic method, called during serialization.
98 *
99 * @return array
100 */
101 public function __sleep() {
102 // We only ever want the file_record saved, not the file_storage object.
103 return ['file_record'];
104 }
105
106 /**
107 * Magic method, called during unserialization.
108 */
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);
112 }
113
67233725
DC
114 /**
115 * Whether or not this is a external resource
116 *
117 * @return bool
118 */
119 public function is_external_file() {
120 return !empty($this->repository);
121 }
122
151b0f94
DW
123 /**
124 * Whether or not this is a controlled link. Note that repositories cannot support FILE_REFERENCE and FILE_CONTROLLED_LINK.
125 *
126 * @return bool
127 */
128 public function is_controlled_link() {
129 return $this->is_external_file() && $this->repository->supported_returntypes() & FILE_CONTROLLED_LINK;
130 }
131
67233725
DC
132 /**
133 * Update some file record fields
134 * NOTE: Must remain protected
135 *
136 * @param stdClass $dataobject
137 */
138 protected function update($dataobject) {
139 global $DB;
2a68ee0e 140 $updatereferencesneeded = false;
67233725 141 $keys = array_keys((array)$this->file_record);
023037dc 142 $filepreupdate = clone($this->file_record);
67233725
DC
143 foreach ($dataobject as $field => $value) {
144 if (in_array($field, $keys)) {
145 if ($field == 'contextid' and (!is_number($value) or $value < 1)) {
146 throw new file_exception('storedfileproblem', 'Invalid contextid');
147 }
148
149 if ($field == 'component') {
150 $value = clean_param($value, PARAM_COMPONENT);
151 if (empty($value)) {
152 throw new file_exception('storedfileproblem', 'Invalid component');
153 }
154 }
155
156 if ($field == 'filearea') {
157 $value = clean_param($value, PARAM_AREA);
158 if (empty($value)) {
159 throw new file_exception('storedfileproblem', 'Invalid filearea');
160 }
161 }
162
163 if ($field == 'itemid' and (!is_number($value) or $value < 0)) {
164 throw new file_exception('storedfileproblem', 'Invalid itemid');
165 }
166
167
168 if ($field == 'filepath') {
169 $value = clean_param($value, PARAM_PATH);
170 if (strpos($value, '/') !== 0 or strrpos($value, '/') !== strlen($value)-1) {
171 // path must start and end with '/'
172 throw new file_exception('storedfileproblem', 'Invalid file path');
173 }
174 }
175
176 if ($field == 'filename') {
fc4e8034
DC
177 // folder has filename == '.', so we pass this
178 if ($value != '.') {
179 $value = clean_param($value, PARAM_FILE);
180 }
67233725
DC
181 if ($value === '') {
182 throw new file_exception('storedfileproblem', 'Invalid file name');
183 }
184 }
185
186 if ($field === 'timecreated' or $field === 'timemodified') {
187 if (!is_number($value)) {
188 throw new file_exception('storedfileproblem', 'Invalid timestamp');
189 }
190 if ($value < 0) {
191 $value = 0;
192 }
193 }
194
42aa6e15 195 if ($field === 'referencefileid') {
1c0da849
DM
196 if (!is_null($value) and !is_number($value)) {
197 throw new file_exception('storedfileproblem', 'Invalid reference info');
198 }
67233725
DC
199 }
200
2a68ee0e
MG
201 if (($field == 'contenthash' || $field == 'filesize') && $this->file_record->$field != $value) {
202 $updatereferencesneeded = true;
203 }
204
67233725
DC
205 // adding the field
206 $this->file_record->$field = $value;
207 } else {
208 throw new coding_exception("Invalid field name, $field doesn't exist in file record");
209 }
210 }
8177b7b9 211 // Validate mimetype field
16a34ae1 212 $mimetype = $this->filesystem->mimetype_from_storedfile($this);
8177b7b9
DC
213 $this->file_record->mimetype = $mimetype;
214
67233725 215 $DB->update_record('files', $this->file_record);
2a68ee0e
MG
216 if ($updatereferencesneeded) {
217 // Either filesize or contenthash of this file have changed. Update all files that reference to it.
218 $this->fs->update_references_to_storedfile($this);
219 }
023037dc 220
221 // Callback for file update.
222 if (!$this->is_directory()) {
223 if ($pluginsfunction = get_plugins_with_function('after_file_updated')) {
224 foreach ($pluginsfunction as $plugintype => $plugins) {
225 foreach ($plugins as $pluginfunction) {
226 $pluginfunction($this->file_record, $filepreupdate);
227 }
228 }
229 }
230 }
67233725
DC
231 }
232
233 /**
234 * Rename filename
235 *
236 * @param string $filepath file path
237 * @param string $filename file name
238 */
239 public function rename($filepath, $filename) {
7051415c 240 if ($this->fs->file_exists($this->get_contextid(), $this->get_component(), $this->get_filearea(), $this->get_itemid(), $filepath, $filename)) {
8436e859
MS
241 $a = new stdClass();
242 $a->contextid = $this->get_contextid();
243 $a->component = $this->get_component();
244 $a->filearea = $this->get_filearea();
245 $a->itemid = $this->get_itemid();
246 $a->filepath = $filepath;
247 $a->filename = $filename;
248 throw new file_exception('storedfilenotcreated', $a, 'file exists, cannot rename');
7051415c 249 }
67233725
DC
250 $filerecord = new stdClass;
251 $filerecord->filepath = $filepath;
252 $filerecord->filename = $filename;
253 // populate the pathname hash
254 $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);
255 $this->update($filerecord);
256 }
257
258 /**
e6904efc 259 * Function stored_file::replace_content_with() is deprecated. Please use stored_file::replace_file_with()
67233725 260 *
e6904efc 261 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
2a68ee0e 262 * @see stored_file::replace_file_with()
67233725
DC
263 */
264 public function replace_content_with(stored_file $storedfile) {
e6904efc
JO
265 throw new coding_exception('Function stored_file::replace_content_with() can not be used any more . ' .
266 'Please use stored_file::replace_file_with()');
67233725
DC
267 }
268
e9e32b1d
MG
269 /**
270 * Replaces the fields that might have changed when file was overriden in filepicker:
6dd92c02 271 * reference, contenthash, filesize, userid
e9e32b1d 272 *
935429af
MG
273 * Note that field 'source' must be updated separately because
274 * it has different format for draft and non-draft areas and
275 * this function will usually be used to replace non-draft area
276 * file with draft area file.
e9e32b1d
MG
277 *
278 * @param stored_file $newfile
279 * @throws coding_exception
280 */
281 public function replace_file_with(stored_file $newfile) {
282 if ($newfile->get_referencefileid() &&
283 $this->fs->get_references_count_by_storedfile($this)) {
284 // The new file is a reference.
285 // The current file has other local files referencing to it.
286 // Double reference is not allowed.
287 throw new moodle_exception('errordoublereference', 'repository');
288 }
289
290 $filerecord = new stdClass;
16a34ae1
AN
291 if ($this->filesystem->is_file_readable_remotely_by_storedfile($newfile)) {
292 $contenthash = $newfile->get_contenthash();
e9e32b1d
MG
293 $filerecord->contenthash = $contenthash;
294 } else {
295 throw new file_exception('storedfileproblem', 'Invalid contenthash, content must be already in filepool', $contenthash);
296 }
297 $filerecord->filesize = $newfile->get_filesize();
298 $filerecord->referencefileid = $newfile->get_referencefileid();
6dd92c02 299 $filerecord->userid = $newfile->get_userid();
e9e32b1d
MG
300 $this->update($filerecord);
301 }
302
67233725 303 /**
2fa8aea2 304 * Unlink the stored file from the referenced file
67233725 305 *
2fa8aea2
DM
306 * This methods destroys the link to the record in files_reference table. This effectively
307 * turns the stored file from being an alias to a plain copy. However, the caller has
308 * to make sure that the actual file's content has beed synced prior to calling this method.
67233725
DC
309 */
310 public function delete_reference() {
311 global $DB;
61506a0a 312
2fa8aea2
DM
313 if (!$this->is_external_file()) {
314 throw new coding_exception('An attempt to unlink a non-reference file.');
315 }
316
e3c02118
DC
317 $transaction = $DB->start_delegated_transaction();
318
1c0da849
DM
319 // Are we the only one referring to the original file? If so, delete the
320 // referenced file record. Note we do not use file_storage::search_references_count()
321 // here because we want to count draft files too and we are at a bit lower access level here.
322 $countlinks = $DB->count_records('files',
323 array('referencefileid' => $this->file_record->referencefileid));
324 if ($countlinks == 1) {
325 $DB->delete_records('files_reference', array('id' => $this->file_record->referencefileid));
326 }
61506a0a 327
1c0da849
DM
328 // Update the underlying record in the database.
329 $update = new stdClass();
330 $update->referencefileid = null;
1c0da849 331 $this->update($update);
61506a0a 332
e3c02118
DC
333 $transaction->allow_commit();
334
1c0da849
DM
335 // Update our properties and the record in the memory.
336 $this->repository = null;
337 $this->file_record->repositoryid = null;
338 $this->file_record->reference = null;
339 $this->file_record->referencefileid = null;
340 $this->file_record->referencelastsync = null;
172dd12c 341 }
342
343 /**
344 * Is this a directory?
8496fdac
PS
345 *
346 * Directories are only emulated, internally they are stored as empty
347 * files with a "." instead of name - this means empty directory contains
348 * exactly one empty file with name dot.
349 *
350 * @return bool true means directory, false means file
172dd12c 351 */
352 public function is_directory() {
8496fdac 353 return ($this->file_record->filename === '.');
172dd12c 354 }
355
356 /**
8496fdac
PS
357 * Delete file from files table.
358 *
359 * The content of files stored in sha1 pool is reclaimed
360 * later - the occupied disk space is reclaimed much later.
361 *
362 * @return bool always true or exception if error occurred
172dd12c 363 */
364 public function delete() {
365 global $DB;
e3c02118 366
e029dff4
PS
367 if ($this->is_directory()) {
368 // Directories can not be referenced, just delete the record.
369 $DB->delete_records('files', array('id'=>$this->file_record->id));
370
371 } else {
372 $transaction = $DB->start_delegated_transaction();
e3c02118 373
e029dff4
PS
374 // If there are other files referring to this file, convert them to copies.
375 if ($files = $this->fs->get_references_by_storedfile($this)) {
376 foreach ($files as $file) {
377 $this->fs->import_external_file($file);
378 }
67233725 379 }
3b2465fe 380
e029dff4
PS
381 // If this file is a reference (alias) to another file, unlink it first.
382 if ($this->is_external_file()) {
383 $this->delete_reference();
384 }
3b2465fe 385
e029dff4
PS
386 // Now delete the file record.
387 $DB->delete_records('files', array('id'=>$this->file_record->id));
e3c02118 388
e029dff4 389 $transaction->allow_commit();
023037dc 390
391 if (!$this->is_directory()) {
392 // Callback for file deletion.
393 if ($pluginsfunction = get_plugins_with_function('after_file_deleted')) {
394 foreach ($pluginsfunction as $plugintype => $plugins) {
395 foreach ($plugins as $pluginfunction) {
396 $pluginfunction($this->file_record);
397 }
398 }
399 }
400 }
e029dff4 401 }
e3c02118 402
e029dff4 403 // Move pool file to trash if content not needed any more.
16a34ae1 404 $this->filesystem->remove_file($this->file_record->contenthash);
8496fdac 405 return true; // BC only
172dd12c 406 }
407
5035a8b4 408 /**
409 * adds this file path to a curl request (POST only)
410 *
411 * @param curl $curlrequest the curl request object
412 * @param string $key what key to use in the POST request
8496fdac 413 * @return void
5035a8b4 414 */
415 public function add_to_curl_request(&$curlrequest, $key) {
16a34ae1 416 return $this->filesystem->add_to_curl_request($this, $curlrequest, $key);
5035a8b4 417 }
418
172dd12c 419 /**
420 * Returns file handle - read only mode, no writing allowed into pool files!
8496fdac
PS
421 *
422 * When you want to modify a file, create a new file and delete the old one.
423 *
c858655d 424 * @param int $type Type of file handle (FILE_HANDLE_xx constant)
8496fdac 425 * @return resource file handle
172dd12c 426 */
c858655d 427 public function get_content_file_handle($type = self::FILE_HANDLE_FOPEN) {
16a34ae1 428 return $this->filesystem->get_content_file_handle($this, $type);
172dd12c 429 }
430
431 /**
8496fdac 432 * Dumps file content to page.
172dd12c 433 */
434 public function readfile() {
16a34ae1 435 return $this->filesystem->readfile($this);
172dd12c 436 }
437
438 /**
8496fdac
PS
439 * Returns file content as string.
440 *
172dd12c 441 * @return string content
442 */
443 public function get_content() {
16a34ae1 444 return $this->filesystem->get_content($this);
172dd12c 445 }
446
6c0e2d08 447 /**
8496fdac
PS
448 * Copy content of file to given pathname.
449 *
450 * @param string $pathname real path to the new file
6c0e2d08 451 * @return bool success
452 */
453 public function copy_content_to($pathname) {
16a34ae1 454 return $this->filesystem->copy_content_from_storedfile($this, $pathname);
6c0e2d08 455 }
456
4e782b32
RT
457 /**
458 * Copy content of file to temporary folder and returns file path
459 *
460 * @param string $dir name of the temporary directory
461 * @param string $fileprefix prefix of temporary file.
462 * @return string|bool path of temporary file or false.
463 */
464 public function copy_content_to_temp($dir = 'files', $fileprefix = 'tempup_') {
465 $tempfile = false;
466 if (!$dir = make_temp_directory($dir)) {
467 return false;
468 }
469 if (!$tempfile = tempnam($dir, $fileprefix)) {
470 return false;
471 }
472 if (!$this->copy_content_to($tempfile)) {
473 // something went wrong
474 @unlink($tempfile);
475 return false;
476 }
477 return $tempfile;
478 }
479
17d9269f 480 /**
8496fdac
PS
481 * List contents of archive.
482 *
d2b7803e 483 * @param file_packer $packer file packer instance
c78a0558 484 * @return array of file infos
485 */
486 public function list_files(file_packer $packer) {
16a34ae1 487 return $this->filesystem->list_files($this, $packer);
c78a0558 488 }
489
490 /**
8496fdac
PS
491 * Extract file to given file path (real OS filesystem), existing files are overwritten.
492 *
d2b7803e 493 * @param file_packer $packer file packer instance
0b0bfa93 494 * @param string $pathname target directory
71ab7e51 495 * @param file_progress $progress Progress indicator callback or null if not required
8496fdac 496 * @return array|bool list of processed files; false if error
17d9269f 497 */
71ab7e51 498 public function extract_to_pathname(file_packer $packer, $pathname,
499 file_progress $progress = null) {
16a34ae1 500 return $this->filesystem->extract_to_pathname($this, $packer, $pathname, $progress);
17d9269f 501 }
502
503 /**
8496fdac
PS
504 * Extract file to given file path (real OS filesystem), existing files are overwritten.
505 *
d2b7803e
DC
506 * @param file_packer $packer file packer instance
507 * @param int $contextid context ID
508 * @param string $component component
509 * @param string $filearea file area
510 * @param int $itemid item ID
511 * @param string $pathbase path base
512 * @param int $userid user ID
71ab7e51 513 * @param file_progress $progress Progress indicator callback or null if not required
8496fdac 514 * @return array|bool list of processed files; false if error
17d9269f 515 */
71ab7e51 516 public function extract_to_storage(file_packer $packer, $contextid,
517 $component, $filearea, $itemid, $pathbase, $userid = null, file_progress $progress = null) {
16a34ae1
AN
518
519 return $this->filesystem->extract_to_storage($this, $packer, $contextid, $component, $filearea,
520 $itemid, $pathbase, $userid, $progress);
17d9269f 521 }
522
b1897a6d 523 /**
8496fdac
PS
524 * Add file/directory into archive.
525 *
d2b7803e 526 * @param file_archive $filearch file archive instance
c78a0558 527 * @param string $archivepath pathname in archive
b1897a6d 528 * @return bool success
529 */
0b0bfa93 530 public function archive_file(file_archive $filearch, $archivepath) {
16a34ae1 531 return $this->filesystem->add_storedfile_to_archive($this, $filearch, $archivepath);
b1897a6d 532 }
533
797f19e8 534 /**
535 * Returns information about image,
536 * information is determined from the file content
d2b7803e 537 *
797f19e8 538 * @return mixed array with width, height and mimetype; false if not an image
539 */
540 public function get_imageinfo() {
16a34ae1 541 return $this->filesystem->get_imageinfo($this);
797f19e8 542 }
543
544 /**
545 * Verifies the file is a valid web image - gif, png and jpeg only.
8496fdac 546 *
797f19e8 547 * It should be ok to serve this image from server without any other security workarounds.
8496fdac 548 *
797f19e8 549 * @return bool true if file ok
550 */
551 public function is_valid_image() {
552 $mimetype = $this->get_mimetype();
559276b1 553 if (!file_mimetype_in_typegroup($mimetype, 'web_image')) {
797f19e8 554 return false;
555 }
556 if (!$info = $this->get_imageinfo()) {
557 return false;
558 }
559 if ($info['mimetype'] !== $mimetype) {
560 return false;
561 }
562 // ok, GD likes this image
563 return true;
564 }
565
4b6b5ce7 566 /**
8496fdac
PS
567 * Returns parent directory, creates missing parents if needed.
568 *
569 * @return stored_file
4b6b5ce7 570 */
571 public function get_parent_directory() {
572 if ($this->file_record->filepath === '/' and $this->file_record->filename === '.') {
573 //root dir does not have parent
574 return null;
575 }
576
577 if ($this->file_record->filename !== '.') {
64f93798 578 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);
4b6b5ce7 579 }
580
581 $filepath = $this->file_record->filepath;
582 $filepath = trim($filepath, '/');
583 $dirs = explode('/', $filepath);
584 array_pop($dirs);
585 $filepath = implode('/', $dirs);
586 $filepath = ($filepath === '') ? '/' : "/$filepath/";
587
64f93798 588 return $this->fs->create_directory($this->file_record->contextid, $this->file_record->component, $this->file_record->filearea, $this->file_record->itemid, $filepath);
4b6b5ce7 589 }
590
16a95e8f 591 /**
0b2bfbd1 592 * Synchronize file if it is a reference and needs synchronizing
67233725 593 *
0b2bfbd1 594 * Updates contenthash and filesize
67233725
DC
595 */
596 public function sync_external_file() {
87355560
MG
597 if (!empty($this->repository)) {
598 $this->repository->sync_reference($this);
67233725 599 }
67233725
DC
600 }
601
602 /**
603 * Returns context id of the file
8496fdac 604 *
16a95e8f 605 * @return int context id
606 */
172dd12c 607 public function get_contextid() {
608 return $this->file_record->contextid;
609 }
610
16a95e8f 611 /**
64f93798
PS
612 * Returns component name - this is the owner of the areas,
613 * nothing else is allowed to read or modify the files directly!!
614 *
615 * @return string
616 */
617 public function get_component() {
618 return $this->file_record->component;
619 }
620
621 /**
622 * Returns file area name, this divides files of one component into groups with different access control.
623 * All files in one area have the same access control.
8496fdac 624 *
16a95e8f 625 * @return string
626 */
172dd12c 627 public function get_filearea() {
628 return $this->file_record->filearea;
629 }
630
16a95e8f 631 /**
8496fdac
PS
632 * Returns returns item id of file.
633 *
16a95e8f 634 * @return int
635 */
172dd12c 636 public function get_itemid() {
637 return $this->file_record->itemid;
638 }
639
16a95e8f 640 /**
641 * Returns file path - starts and ends with /, \ are not allowed.
8496fdac 642 *
16a95e8f 643 * @return string
644 */
172dd12c 645 public function get_filepath() {
646 return $this->file_record->filepath;
647 }
648
16a95e8f 649 /**
650 * Returns file name or '.' in case of directories.
8496fdac 651 *
16a95e8f 652 * @return string
653 */
172dd12c 654 public function get_filename() {
655 return $this->file_record->filename;
656 }
657
16a95e8f 658 /**
659 * Returns id of user who created the file.
8496fdac 660 *
16a95e8f 661 * @return int
662 */
172dd12c 663 public function get_userid() {
664 return $this->file_record->userid;
665 }
666
16a95e8f 667 /**
668 * Returns the size of file in bytes.
8496fdac 669 *
16a95e8f 670 * @return int bytes
671 */
172dd12c 672 public function get_filesize() {
67233725 673 $this->sync_external_file();
172dd12c 674 return $this->file_record->filesize;
675 }
676
2a68ee0e 677 /**
e6904efc 678 * Function stored_file::set_filesize() is deprecated. Please use stored_file::replace_file_with
61506a0a 679 *
e6904efc
JO
680 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
681 * @see stored_file::replace_file_with()
61506a0a
DC
682 */
683 public function set_filesize($filesize) {
e6904efc
JO
684 throw new coding_exception('Function stored_file::set_filesize() can not be used any more. ' .
685 'Please use stored_file::replace_file_with()');
61506a0a
DC
686 }
687
16a95e8f 688 /**
8496fdac
PS
689 * Returns mime type of file.
690 *
16a95e8f 691 * @return string
692 */
172dd12c 693 public function get_mimetype() {
694 return $this->file_record->mimetype;
695 }
696
16a95e8f 697 /**
8496fdac
PS
698 * Returns unix timestamp of file creation date.
699 *
16a95e8f 700 * @return int
701 */
172dd12c 702 public function get_timecreated() {
703 return $this->file_record->timecreated;
704 }
705
16a95e8f 706 /**
8496fdac
PS
707 * Returns unix timestamp of last file modification.
708 *
16a95e8f 709 * @return int
710 */
172dd12c 711 public function get_timemodified() {
67233725 712 $this->sync_external_file();
172dd12c 713 return $this->file_record->timemodified;
714 }
6c0e2d08 715
67233725
DC
716 /**
717 * set timemodified
718 *
719 * @param int $timemodified
720 */
721 public function set_timemodified($timemodified) {
722 $filerecord = new stdClass;
723 $filerecord->timemodified = $timemodified;
724 $this->update($filerecord);
725 }
726
16a95e8f 727 /**
8496fdac
PS
728 * Returns file status flag.
729 *
16a95e8f 730 * @return int 0 means file OK, anything else is a problem and file can not be used
731 */
6c0e2d08 732 public function get_status() {
733 return $this->file_record->status;
734 }
ee03a651 735
16a95e8f 736 /**
8496fdac
PS
737 * Returns file id.
738 *
16a95e8f 739 * @return int
740 */
ee03a651 741 public function get_id() {
742 return $this->file_record->id;
743 }
4284e1cc 744
16a95e8f 745 /**
8496fdac
PS
746 * Returns sha1 hash of file content.
747 *
16a95e8f 748 * @return string
749 */
4284e1cc 750 public function get_contenthash() {
67233725 751 $this->sync_external_file();
4284e1cc 752 return $this->file_record->contenthash;
753 }
6ed19c74 754
16a95e8f 755 /**
64f93798 756 * Returns sha1 hash of all file path components sha1("contextid/component/filearea/itemid/dir/dir/filename.ext").
8496fdac 757 *
16a95e8f 758 * @return string
759 */
6ed19c74 760 public function get_pathnamehash() {
761 return $this->file_record->pathnamehash;
762 }
1dce6261
DC
763
764 /**
8496fdac
PS
765 * Returns the license type of the file, it is a short name referred from license table.
766 *
1dce6261
DC
767 * @return string
768 */
769 public function get_license() {
770 return $this->file_record->license;
771 }
772
67233725
DC
773 /**
774 * Set license
775 *
776 * @param string $license license
777 */
778 public function set_license($license) {
779 $filerecord = new stdClass;
780 $filerecord->license = $license;
781 $this->update($filerecord);
782 }
783
1dce6261 784 /**
8496fdac
PS
785 * Returns the author name of the file.
786 *
1dce6261
DC
787 * @return string
788 */
789 public function get_author() {
31cd5fe8 790 return $this->file_record->author;
1dce6261
DC
791 }
792
67233725
DC
793 /**
794 * Set author
795 *
796 * @param string $author
797 */
798 public function set_author($author) {
799 $filerecord = new stdClass;
800 $filerecord->author = $author;
801 $this->update($filerecord);
802 }
803
1dce6261 804 /**
8496fdac
PS
805 * Returns the source of the file, usually it is a url.
806 *
1dce6261
DC
807 * @return string
808 */
809 public function get_source() {
810 return $this->file_record->source;
811 }
8496fdac 812
67233725
DC
813 /**
814 * Set license
815 *
816 * @param string $license license
817 */
818 public function set_source($source) {
819 $filerecord = new stdClass;
820 $filerecord->source = $source;
821 $this->update($filerecord);
822 }
823
824
f79321f1
DC
825 /**
826 * Returns the sort order of file
827 *
828 * @return int
829 */
830 public function get_sortorder() {
831 return $this->file_record->sortorder;
832 }
67233725
DC
833
834 /**
835 * Set file sort order
836 *
837 * @param int $sortorder
838 * @return int
839 */
840 public function set_sortorder($sortorder) {
023037dc 841 $oldorder = $this->file_record->sortorder;
67233725
DC
842 $filerecord = new stdClass;
843 $filerecord->sortorder = $sortorder;
844 $this->update($filerecord);
023037dc 845 if (!$this->is_directory()) {
846 // Callback for file sort order change.
847 if ($pluginsfunction = get_plugins_with_function('after_file_sorted')) {
848 foreach ($pluginsfunction as $plugintype => $plugins) {
849 foreach ($plugins as $pluginfunction) {
850 $pluginfunction($this->file_record, $oldorder, $sortorder);
851 }
852 }
853 }
854 }
67233725
DC
855 }
856
857 /**
858 * Returns repository id
859 *
860 * @return int|null
861 */
862 public function get_repository_id() {
863 if (!empty($this->repository)) {
864 return $this->repository->id;
865 } else {
866 return null;
867 }
868 }
869
1104a9fa
JL
870 /**
871 * Returns repository type.
872 *
873 * @return mixed str|null the repository type or null if is not an external file
874 * @since Moodle 3.3
875 */
876 public function get_repository_type() {
877
878 if (!empty($this->repository)) {
879 return $this->repository->get_typename();
880 } else {
881 return null;
882 }
883 }
884
885
67233725
DC
886 /**
887 * get reference file id
888 * @return int
889 */
890 public function get_referencefileid() {
891 return $this->file_record->referencefileid;
892 }
893
894 /**
895 * Get reference last sync time
896 * @return int
897 */
898 public function get_referencelastsync() {
899 return $this->file_record->referencelastsync;
900 }
901
902 /**
e6904efc
JO
903 * Function stored_file::get_referencelifetime() is deprecated as reference
904 * life time is no longer stored in DB or returned by repository. Each
87355560
MG
905 * repository should decide by itself when to synchronise the references.
906 *
e6904efc 907 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
87355560 908 * @see repository::sync_reference()
67233725
DC
909 */
910 public function get_referencelifetime() {
e6904efc
JO
911 throw new coding_exception('Function stored_file::get_referencelifetime() can not be used any more. ' .
912 'See repository::sync_reference().');
67233725
DC
913 }
914 /**
915 * Returns file reference
916 *
917 * @return string
918 */
919 public function get_reference() {
920 return $this->file_record->reference;
921 }
922
923 /**
924 * Get human readable file reference information
925 *
926 * @return string
927 */
928 public function get_reference_details() {
0b2bfbd1
MG
929 return $this->repository->get_reference_details($this->get_reference(), $this->get_status());
930 }
931
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 *
87355560
MG
938 * @param null|string $contenthash if set to null contenthash is not changed
939 * @param int $filesize new size of the file
940 * @param int $status new status of the file (0 means OK, 666 - source missing)
58e5ab1b 941 * @param int $timemodified last time modified of the source, if known
0b2bfbd1 942 */
58e5ab1b 943 public function set_synchronized($contenthash, $filesize, $status = 0, $timemodified = null) {
0b2bfbd1
MG
944 if (!$this->is_external_file()) {
945 return;
946 }
947 $now = time();
87355560
MG
948 if ($contenthash === null) {
949 $contenthash = $this->file_record->contenthash;
950 }
14b7e500
MG
951 if ($contenthash != $this->file_record->contenthash) {
952 $oldcontenthash = $this->file_record->contenthash;
0b2bfbd1 953 }
14b7e500 954 // this will update all entries in {files} that have the same filereference id
58e5ab1b 955 $this->fs->update_references($this->file_record->referencefileid, $now, null, $contenthash, $filesize, $status, $timemodified);
14b7e500
MG
956 // we don't need to call update() for this object, just set the values of changed fields
957 $this->file_record->contenthash = $contenthash;
958 $this->file_record->filesize = $filesize;
959 $this->file_record->status = $status;
960 $this->file_record->referencelastsync = $now;
58e5ab1b
MG
961 if ($timemodified) {
962 $this->file_record->timemodified = $timemodified;
963 }
14b7e500 964 if (isset($oldcontenthash)) {
16a34ae1 965 $this->filesystem->remove_file($oldcontenthash);
0b2bfbd1 966 }
0b2bfbd1
MG
967 }
968
14b7e500
MG
969 /**
970 * Sets the error status for a file that could not be synchronised
14b7e500 971 */
87355560
MG
972 public function set_missingsource() {
973 $this->set_synchronized($this->file_record->contenthash, $this->file_record->filesize, 666);
67233725
DC
974 }
975
976 /**
977 * Send file references
978 *
979 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
980 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
981 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
982 * @param array $options additional options affecting the file serving
983 */
984 public function send_file($lifetime, $filter, $forcedownload, $options) {
985 $this->repository->send_file($this, $lifetime, $filter, $forcedownload, $options);
986 }
bc6f241c
MG
987
988 /**
989 * Imports the contents of an external file into moodle filepool.
990 *
991 * @throws moodle_exception if file could not be downloaded or is too big
992 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
993 */
994 public function import_external_file_contents($maxbytes = 0) {
995 if ($this->repository) {
996 $this->repository->import_external_file_contents($this, $maxbytes);
997 }
998 }
361a47d4
DM
999
1000 /**
1001 * Gets a file relative to this file in the repository and sends it to the browser.
1002 * Checks the function repository::supports_relative_file() to make sure it can be used.
1003 *
1004 * @param string $relativepath the relative path to the file we are trying to access
1005 */
1006 public function send_relative_file($relativepath) {
1007 if ($this->repository && $this->repository->supports_relative_file()) {
1008 $relativepath = clean_param($relativepath, PARAM_PATH);
1009 $this->repository->send_relative_file($this, $relativepath);
1010 } else {
1011 send_file_not_found();
1012 }
1013 }
b7067f06
AN
1014
1015 /**
1016 * Generates a thumbnail for this stored_file.
1017 *
1018 * If the GD library has at least version 2 and PNG support is available, the returned data
1019 * is the content of a transparent PNG file containing the thumbnail. Otherwise, the function
1020 * returns contents of a JPEG file with black background containing the thumbnail.
1021 *
1022 * @param int $width the width of the requested thumbnail
1023 * @param int $height the height of the requested thumbnail
1024 * @return string|bool false if a problem occurs, the thumbnail image data otherwise
1025 */
1026 public function generate_image_thumbnail($width, $height) {
1027 if (empty($width) or empty($height)) {
1028 return false;
1029 }
1030
16a34ae1
AN
1031 $content = $this->get_content();
1032
b7067f06 1033 // Fetch the image information for this image.
16a34ae1 1034 $imageinfo = @getimagesizefromstring($content);
b7067f06
AN
1035 if (empty($imageinfo)) {
1036 return false;
1037 }
1038
1039 // Create a new image from the file.
16a34ae1 1040 $original = @imagecreatefromstring($content);
b7067f06
AN
1041
1042 // Generate the thumbnail.
1043 return generate_image_thumbnail_from_image($original, $imageinfo, $width, $height);
1044 }
92b9ef99
FM
1045
1046 /**
1047 * Generate a resized image for this stored_file.
1048 *
1049 * @param int|null $width The desired width, or null to only use the height.
1050 * @param int|null $height The desired height, or null to only use the width.
1051 * @return string|false False when a problem occurs, else the image data.
1052 */
1053 public function resize_image($width, $height) {
1054 global $CFG;
1055 require_once($CFG->libdir . '/gdlib.php');
1056
16a34ae1
AN
1057 $content = $this->get_content();
1058
92b9ef99 1059 // Fetch the image information for this image.
16a34ae1 1060 $imageinfo = @getimagesizefromstring($content);
92b9ef99
FM
1061 if (empty($imageinfo)) {
1062 return false;
1063 }
1064
1065 // Create a new image from the file.
16a34ae1 1066 $original = @imagecreatefromstring($content);
92b9ef99
FM
1067
1068 // Generate the resized image.
1069 return resize_image_from_image($original, $imageinfo, $width, $height);
1070 }
a30a04fa
AN
1071
1072 /**
1073 * Check whether the supplied file is the same as this file.
1074 *
1075 * @param string $path The path to the file on disk
1076 * @return boolean
1077 */
1078 public function compare_to_path($path) {
1079 return $this->get_contenthash() === file_storage::hash_from_path($path);
1080 }
1081
1082 /**
1083 * Check whether the supplied content is the same as this file.
1084 *
1085 * @param string $content The file content
1086 * @return boolean
1087 */
1088 public function compare_to_string($content) {
1089 return $this->get_contenthash() === file_storage::hash_from_string($content);
1090 }
f79321f1 1091}