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