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