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