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