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