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