Merge branch 'MDL-65744' of git://github.com/Chocolate-lightning/moodle
[moodle.git] / lib / filestorage / file_storage.php
blobb297159ab64a5ffcb6c21c0b7b34ee05bff139f2
1 <?php
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.
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/>.
18 /**
19 * Core file storage class definition.
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
26 defined('MOODLE_INTERNAL') || die();
28 require_once("$CFG->libdir/filestorage/stored_file.php");
30 /**
31 * File storage class used for low level access to stored files.
33 * Only owner of file area may use this class to access own files,
34 * for example only code in mod/assignment/* may access assignment
35 * attachments. When some other part of moodle needs to access
36 * files of modules it has to use file_browser class instead or there
37 * has to be some callback API.
39 * @package core_files
40 * @category files
41 * @copyright 2008 Petr Skoda {@link http://skodak.org}
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 * @since Moodle 2.0
45 class file_storage {
47 /** @var string tempdir */
48 private $tempdir;
50 /** @var file_system filesystem */
51 private $filesystem;
53 /**
54 * Constructor - do not use directly use {@link get_file_storage()} call instead.
56 public function __construct() {
57 // The tempdir must always remain on disk, but shared between all ndoes in a cluster. Its content is not subject
58 // to the file_system abstraction.
59 $this->tempdir = make_temp_directory('filestorage');
61 $this->setup_file_system();
64 /**
65 * Complete setup procedure for the file_system component.
67 * @return file_system
69 public function setup_file_system() {
70 global $CFG;
71 if ($this->filesystem === null) {
72 require_once($CFG->libdir . '/filestorage/file_system.php');
73 if (!empty($CFG->alternative_file_system_class)) {
74 $class = $CFG->alternative_file_system_class;
75 } else {
76 // The default file_system is the filedir.
77 require_once($CFG->libdir . '/filestorage/file_system_filedir.php');
78 $class = file_system_filedir::class;
80 $this->filesystem = new $class();
83 return $this->filesystem;
86 /**
87 * Return the file system instance.
89 * @return file_system
91 public function get_file_system() {
92 return $this->filesystem;
95 /**
96 * Calculates sha1 hash of unique full path name information.
98 * This hash is a unique file identifier - it is used to improve
99 * performance and overcome db index size limits.
101 * @param int $contextid context ID
102 * @param string $component component
103 * @param string $filearea file area
104 * @param int $itemid item ID
105 * @param string $filepath file path
106 * @param string $filename file name
107 * @return string sha1 hash
109 public static function get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename) {
110 return sha1("/$contextid/$component/$filearea/$itemid".$filepath.$filename);
114 * Does this file exist?
116 * @param int $contextid context ID
117 * @param string $component component
118 * @param string $filearea file area
119 * @param int $itemid item ID
120 * @param string $filepath file path
121 * @param string $filename file name
122 * @return bool
124 public function file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename) {
125 $filepath = clean_param($filepath, PARAM_PATH);
126 $filename = clean_param($filename, PARAM_FILE);
128 if ($filename === '') {
129 $filename = '.';
132 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
133 return $this->file_exists_by_hash($pathnamehash);
137 * Whether or not the file exist
139 * @param string $pathnamehash path name hash
140 * @return bool
142 public function file_exists_by_hash($pathnamehash) {
143 global $DB;
145 return $DB->record_exists('files', array('pathnamehash'=>$pathnamehash));
149 * Create instance of file class from database record.
151 * @param stdClass $filerecord record from the files table left join files_reference table
152 * @return stored_file instance of file abstraction class
154 public function get_file_instance(stdClass $filerecord) {
155 $storedfile = new stored_file($this, $filerecord);
156 return $storedfile;
160 * Get converted document.
162 * Get an alternate version of the specified document, if it is possible to convert.
164 * @param stored_file $file the file we want to preview
165 * @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
166 * @param boolean $forcerefresh If true, the file will be converted every time (not cached).
167 * @return stored_file|bool false if unable to create the conversion, stored file otherwise
169 public function get_converted_document(stored_file $file, $format, $forcerefresh = false) {
170 debugging('The get_converted_document function has been deprecated and the unoconv functions been removed. '
171 . 'The file has not been converted. '
172 . 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
174 return false;
178 * Verify the format is supported.
180 * @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
181 * @return bool - True if the format is supported for input.
183 protected function is_format_supported_by_unoconv($format) {
184 debugging('The is_format_supported_by_unoconv function has been deprecated and the unoconv functions been removed. '
185 . 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
187 return false;
191 * Check if the installed version of unoconv is supported.
193 * @return bool true if the present version is supported, false otherwise.
195 public static function can_convert_documents() {
196 debugging('The can_convert_documents function has been deprecated and the unoconv functions been removed. '
197 . 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
199 return false;
203 * Regenerate the test pdf and send it direct to the browser.
205 public static function send_test_pdf() {
206 debugging('The send_test_pdf function has been deprecated and the unoconv functions been removed. '
207 . 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
209 return false;
213 * Check if unoconv configured path is correct and working.
215 * @return \stdClass an object with the test status and the UNOCONVPATH_ constant message.
217 public static function test_unoconv_path() {
218 debugging('The test_unoconv_path function has been deprecated and the unoconv functions been removed. '
219 . 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
221 return false;
225 * Returns an image file that represent the given stored file as a preview
227 * At the moment, only GIF, JPEG and PNG files are supported to have previews. In the
228 * future, the support for other mimetypes can be added, too (eg. generate an image
229 * preview of PDF, text documents etc).
231 * @param stored_file $file the file we want to preview
232 * @param string $mode preview mode, eg. 'thumb'
233 * @return stored_file|bool false if unable to create the preview, stored file otherwise
235 public function get_file_preview(stored_file $file, $mode) {
237 $context = context_system::instance();
238 $path = '/' . trim($mode, '/') . '/';
239 $preview = $this->get_file($context->id, 'core', 'preview', 0, $path, $file->get_contenthash());
241 if (!$preview) {
242 $preview = $this->create_file_preview($file, $mode);
243 if (!$preview) {
244 return false;
248 return $preview;
252 * Return an available file name.
254 * This will return the next available file name in the area, adding/incrementing a suffix
255 * of the file, ie: file.txt > file (1).txt > file (2).txt > etc...
257 * If the file name passed is available without modification, it is returned as is.
259 * @param int $contextid context ID.
260 * @param string $component component.
261 * @param string $filearea file area.
262 * @param int $itemid area item ID.
263 * @param string $filepath the file path.
264 * @param string $filename the file name.
265 * @return string available file name.
266 * @throws coding_exception if the file name is invalid.
267 * @since Moodle 2.5
269 public function get_unused_filename($contextid, $component, $filearea, $itemid, $filepath, $filename) {
270 global $DB;
272 // Do not accept '.' or an empty file name (zero is acceptable).
273 if ($filename == '.' || (empty($filename) && !is_numeric($filename))) {
274 throw new coding_exception('Invalid file name passed', $filename);
277 // The file does not exist, we return the same file name.
278 if (!$this->file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
279 return $filename;
282 // Trying to locate a file name using the used pattern. We remove the used pattern from the file name first.
283 $pathinfo = pathinfo($filename);
284 $basename = $pathinfo['filename'];
285 $matches = array();
286 if (preg_match('~^(.+) \(([0-9]+)\)$~', $basename, $matches)) {
287 $basename = $matches[1];
290 $filenamelike = $DB->sql_like_escape($basename) . ' (%)';
291 if (isset($pathinfo['extension'])) {
292 $filenamelike .= '.' . $DB->sql_like_escape($pathinfo['extension']);
295 $filenamelikesql = $DB->sql_like('f.filename', ':filenamelike');
296 $filenamelen = $DB->sql_length('f.filename');
297 $sql = "SELECT filename
298 FROM {files} f
299 WHERE
300 f.contextid = :contextid AND
301 f.component = :component AND
302 f.filearea = :filearea AND
303 f.itemid = :itemid AND
304 f.filepath = :filepath AND
305 $filenamelikesql
306 ORDER BY
307 $filenamelen DESC,
308 f.filename DESC";
309 $params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid,
310 'filepath' => $filepath, 'filenamelike' => $filenamelike);
311 $results = $DB->get_fieldset_sql($sql, $params, IGNORE_MULTIPLE);
313 // Loop over the results to make sure we are working on a valid file name. Because 'file (1).txt' and 'file (copy).txt'
314 // would both be returned, but only the one only containing digits should be used.
315 $number = 1;
316 foreach ($results as $result) {
317 $resultbasename = pathinfo($result, PATHINFO_FILENAME);
318 $matches = array();
319 if (preg_match('~^(.+) \(([0-9]+)\)$~', $resultbasename, $matches)) {
320 $number = $matches[2] + 1;
321 break;
325 // Constructing the new filename.
326 $newfilename = $basename . ' (' . $number . ')';
327 if (isset($pathinfo['extension'])) {
328 $newfilename .= '.' . $pathinfo['extension'];
331 return $newfilename;
335 * Return an available directory name.
337 * This will return the next available directory name in the area, adding/incrementing a suffix
338 * of the last portion of path, ie: /path/ > /path (1)/ > /path (2)/ > etc...
340 * If the file path passed is available without modification, it is returned as is.
342 * @param int $contextid context ID.
343 * @param string $component component.
344 * @param string $filearea file area.
345 * @param int $itemid area item ID.
346 * @param string $suggestedpath the suggested file path.
347 * @return string available file path
348 * @since Moodle 2.5
350 public function get_unused_dirname($contextid, $component, $filearea, $itemid, $suggestedpath) {
351 global $DB;
353 // Ensure suggestedpath has trailing '/'
354 $suggestedpath = rtrim($suggestedpath, '/'). '/';
356 // The directory does not exist, we return the same file path.
357 if (!$this->file_exists($contextid, $component, $filearea, $itemid, $suggestedpath, '.')) {
358 return $suggestedpath;
361 // Trying to locate a file path using the used pattern. We remove the used pattern from the path first.
362 if (preg_match('~^(/.+) \(([0-9]+)\)/$~', $suggestedpath, $matches)) {
363 $suggestedpath = $matches[1]. '/';
366 $filepathlike = $DB->sql_like_escape(rtrim($suggestedpath, '/')) . ' (%)/';
368 $filepathlikesql = $DB->sql_like('f.filepath', ':filepathlike');
369 $filepathlen = $DB->sql_length('f.filepath');
370 $sql = "SELECT filepath
371 FROM {files} f
372 WHERE
373 f.contextid = :contextid AND
374 f.component = :component AND
375 f.filearea = :filearea AND
376 f.itemid = :itemid AND
377 f.filename = :filename AND
378 $filepathlikesql
379 ORDER BY
380 $filepathlen DESC,
381 f.filepath DESC";
382 $params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid,
383 'filename' => '.', 'filepathlike' => $filepathlike);
384 $results = $DB->get_fieldset_sql($sql, $params, IGNORE_MULTIPLE);
386 // Loop over the results to make sure we are working on a valid file path. Because '/path (1)/' and '/path (copy)/'
387 // would both be returned, but only the one only containing digits should be used.
388 $number = 1;
389 foreach ($results as $result) {
390 if (preg_match('~ \(([0-9]+)\)/$~', $result, $matches)) {
391 $number = (int)($matches[1]) + 1;
392 break;
396 return rtrim($suggestedpath, '/'). ' (' . $number . ')/';
400 * Generates a preview image for the stored file
402 * @param stored_file $file the file we want to preview
403 * @param string $mode preview mode, eg. 'thumb'
404 * @return stored_file|bool the newly created preview file or false
406 protected function create_file_preview(stored_file $file, $mode) {
408 $mimetype = $file->get_mimetype();
410 if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
411 // make a preview of the image
412 $data = $this->create_imagefile_preview($file, $mode);
414 } else {
415 // unable to create the preview of this mimetype yet
416 return false;
419 if (empty($data)) {
420 return false;
423 $context = context_system::instance();
424 $record = array(
425 'contextid' => $context->id,
426 'component' => 'core',
427 'filearea' => 'preview',
428 'itemid' => 0,
429 'filepath' => '/' . trim($mode, '/') . '/',
430 'filename' => $file->get_contenthash(),
433 $imageinfo = getimagesizefromstring($data);
434 if ($imageinfo) {
435 $record['mimetype'] = $imageinfo['mime'];
438 return $this->create_file_from_string($record, $data);
442 * Generates a preview for the stored image file
444 * @param stored_file $file the image we want to preview
445 * @param string $mode preview mode, eg. 'thumb'
446 * @return string|bool false if a problem occurs, the thumbnail image data otherwise
448 protected function create_imagefile_preview(stored_file $file, $mode) {
449 global $CFG;
450 require_once($CFG->libdir.'/gdlib.php');
452 if ($mode === 'tinyicon') {
453 $data = $file->generate_image_thumbnail(24, 24);
455 } else if ($mode === 'thumb') {
456 $data = $file->generate_image_thumbnail(90, 90);
458 } else if ($mode === 'bigthumb') {
459 $data = $file->generate_image_thumbnail(250, 250);
461 } else {
462 throw new file_exception('storedfileproblem', 'Invalid preview mode requested');
465 return $data;
469 * Fetch file using local file id.
471 * Please do not rely on file ids, it is usually easier to use
472 * pathname hashes instead.
474 * @param int $fileid file ID
475 * @return stored_file|bool stored_file instance if exists, false if not
477 public function get_file_by_id($fileid) {
478 global $DB;
480 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
481 FROM {files} f
482 LEFT JOIN {files_reference} r
483 ON f.referencefileid = r.id
484 WHERE f.id = ?";
485 if ($filerecord = $DB->get_record_sql($sql, array($fileid))) {
486 return $this->get_file_instance($filerecord);
487 } else {
488 return false;
493 * Fetch file using local file full pathname hash
495 * @param string $pathnamehash path name hash
496 * @return stored_file|bool stored_file instance if exists, false if not
498 public function get_file_by_hash($pathnamehash) {
499 global $DB;
501 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
502 FROM {files} f
503 LEFT JOIN {files_reference} r
504 ON f.referencefileid = r.id
505 WHERE f.pathnamehash = ?";
506 if ($filerecord = $DB->get_record_sql($sql, array($pathnamehash))) {
507 return $this->get_file_instance($filerecord);
508 } else {
509 return false;
514 * Fetch locally stored file.
516 * @param int $contextid context ID
517 * @param string $component component
518 * @param string $filearea file area
519 * @param int $itemid item ID
520 * @param string $filepath file path
521 * @param string $filename file name
522 * @return stored_file|bool stored_file instance if exists, false if not
524 public function get_file($contextid, $component, $filearea, $itemid, $filepath, $filename) {
525 $filepath = clean_param($filepath, PARAM_PATH);
526 $filename = clean_param($filename, PARAM_FILE);
528 if ($filename === '') {
529 $filename = '.';
532 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
533 return $this->get_file_by_hash($pathnamehash);
537 * Are there any files (or directories)
539 * @param int $contextid context ID
540 * @param string $component component
541 * @param string $filearea file area
542 * @param bool|int $itemid item id or false if all items
543 * @param bool $ignoredirs whether or not ignore directories
544 * @return bool empty
546 public function is_area_empty($contextid, $component, $filearea, $itemid = false, $ignoredirs = true) {
547 global $DB;
549 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
550 $where = "contextid = :contextid AND component = :component AND filearea = :filearea";
552 if ($itemid !== false) {
553 $params['itemid'] = $itemid;
554 $where .= " AND itemid = :itemid";
557 if ($ignoredirs) {
558 $sql = "SELECT 'x'
559 FROM {files}
560 WHERE $where AND filename <> '.'";
561 } else {
562 $sql = "SELECT 'x'
563 FROM {files}
564 WHERE $where AND (filename <> '.' OR filepath <> '/')";
567 return !$DB->record_exists_sql($sql, $params);
571 * Returns all files belonging to given repository
573 * @param int $repositoryid
574 * @param string $sort A fragment of SQL to use for sorting
576 public function get_external_files($repositoryid, $sort = '') {
577 global $DB;
578 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
579 FROM {files} f
580 LEFT JOIN {files_reference} r
581 ON f.referencefileid = r.id
582 WHERE r.repositoryid = ?";
583 if (!empty($sort)) {
584 $sql .= " ORDER BY {$sort}";
587 $result = array();
588 $filerecords = $DB->get_records_sql($sql, array($repositoryid));
589 foreach ($filerecords as $filerecord) {
590 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
592 return $result;
596 * Returns all area files (optionally limited by itemid)
598 * @param int $contextid context ID
599 * @param string $component component
600 * @param mixed $filearea file area/s, you cannot specify multiple fileareas as well as an itemid
601 * @param int|int[]|false $itemid item ID(s) or all files if not specified
602 * @param string $sort A fragment of SQL to use for sorting
603 * @param bool $includedirs whether or not include directories
604 * @param int $updatedsince return files updated since this time
605 * @param int $limitfrom return a subset of records, starting at this point (optional).
606 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
607 * @return stored_file[] array of stored_files indexed by pathanmehash
609 public function get_area_files($contextid, $component, $filearea, $itemid = false, $sort = "itemid, filepath, filename",
610 $includedirs = true, $updatedsince = 0, $limitfrom = 0, $limitnum = 0) {
611 global $DB;
613 list($areasql, $conditions) = $DB->get_in_or_equal($filearea, SQL_PARAMS_NAMED);
614 $conditions['contextid'] = $contextid;
615 $conditions['component'] = $component;
617 if ($itemid !== false && is_array($filearea)) {
618 throw new coding_exception('You cannot specify multiple fileareas as well as an itemid.');
619 } else if ($itemid !== false) {
620 $itemids = is_array($itemid) ? $itemid : [$itemid];
621 list($itemidinorequalsql, $itemidconditions) = $DB->get_in_or_equal($itemids, SQL_PARAMS_NAMED);
622 $itemidsql = " AND f.itemid {$itemidinorequalsql}";
623 $conditions = array_merge($conditions, $itemidconditions);
624 } else {
625 $itemidsql = '';
628 $updatedsincesql = '';
629 if (!empty($updatedsince)) {
630 $conditions['time'] = $updatedsince;
631 $updatedsincesql = 'AND f.timemodified > :time';
634 $includedirssql = '';
635 if (!$includedirs) {
636 $includedirssql = 'AND f.filename != :dot';
637 $conditions['dot'] = '.';
640 if ($limitfrom && !$limitnum) {
641 throw new coding_exception('If specifying $limitfrom you must also specify $limitnum');
644 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
645 FROM {files} f
646 LEFT JOIN {files_reference} r
647 ON f.referencefileid = r.id
648 WHERE f.contextid = :contextid
649 AND f.component = :component
650 AND f.filearea $areasql
651 $includedirssql
652 $updatedsincesql
653 $itemidsql";
654 if (!empty($sort)) {
655 $sql .= " ORDER BY {$sort}";
658 $result = array();
659 $filerecords = $DB->get_records_sql($sql, $conditions, $limitfrom, $limitnum);
660 foreach ($filerecords as $filerecord) {
661 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
663 return $result;
667 * Returns array based tree structure of area files
669 * @param int $contextid context ID
670 * @param string $component component
671 * @param string $filearea file area
672 * @param int $itemid item ID
673 * @return array each dir represented by dirname, subdirs, files and dirfile array elements
675 public function get_area_tree($contextid, $component, $filearea, $itemid) {
676 $result = array('dirname'=>'', 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
677 $files = $this->get_area_files($contextid, $component, $filearea, $itemid, '', true);
678 // first create directory structure
679 foreach ($files as $hash=>$dir) {
680 if (!$dir->is_directory()) {
681 continue;
683 unset($files[$hash]);
684 if ($dir->get_filepath() === '/') {
685 $result['dirfile'] = $dir;
686 continue;
688 $parts = explode('/', trim($dir->get_filepath(),'/'));
689 $pointer =& $result;
690 foreach ($parts as $part) {
691 if ($part === '') {
692 continue;
694 if (!isset($pointer['subdirs'][$part])) {
695 $pointer['subdirs'][$part] = array('dirname'=>$part, 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
697 $pointer =& $pointer['subdirs'][$part];
699 $pointer['dirfile'] = $dir;
700 unset($pointer);
702 foreach ($files as $hash=>$file) {
703 $parts = explode('/', trim($file->get_filepath(),'/'));
704 $pointer =& $result;
705 foreach ($parts as $part) {
706 if ($part === '') {
707 continue;
709 $pointer =& $pointer['subdirs'][$part];
711 $pointer['files'][$file->get_filename()] = $file;
712 unset($pointer);
714 $result = $this->sort_area_tree($result);
715 return $result;
719 * Sorts the result of {@link file_storage::get_area_tree()}.
721 * @param array $tree Array of results provided by {@link file_storage::get_area_tree()}
722 * @return array of sorted results
724 protected function sort_area_tree($tree) {
725 foreach ($tree as $key => &$value) {
726 if ($key == 'subdirs') {
727 core_collator::ksort($value, core_collator::SORT_NATURAL);
728 foreach ($value as $subdirname => &$subtree) {
729 $subtree = $this->sort_area_tree($subtree);
731 } else if ($key == 'files') {
732 core_collator::ksort($value, core_collator::SORT_NATURAL);
735 return $tree;
739 * Returns all files and optionally directories
741 * @param int $contextid context ID
742 * @param string $component component
743 * @param string $filearea file area
744 * @param int $itemid item ID
745 * @param int $filepath directory path
746 * @param bool $recursive include all subdirectories
747 * @param bool $includedirs include files and directories
748 * @param string $sort A fragment of SQL to use for sorting
749 * @return array of stored_files indexed by pathanmehash
751 public function get_directory_files($contextid, $component, $filearea, $itemid, $filepath, $recursive = false, $includedirs = true, $sort = "filepath, filename") {
752 global $DB;
754 if (!$directory = $this->get_file($contextid, $component, $filearea, $itemid, $filepath, '.')) {
755 return array();
758 $orderby = (!empty($sort)) ? " ORDER BY {$sort}" : '';
760 if ($recursive) {
762 $dirs = $includedirs ? "" : "AND filename <> '.'";
763 $length = core_text::strlen($filepath);
765 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
766 FROM {files} f
767 LEFT JOIN {files_reference} r
768 ON f.referencefileid = r.id
769 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
770 AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
771 AND f.id <> :dirid
772 $dirs
773 $orderby";
774 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
776 $files = array();
777 $dirs = array();
778 $filerecords = $DB->get_records_sql($sql, $params);
779 foreach ($filerecords as $filerecord) {
780 if ($filerecord->filename == '.') {
781 $dirs[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
782 } else {
783 $files[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
786 $result = array_merge($dirs, $files);
788 } else {
789 $result = array();
790 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
792 $length = core_text::strlen($filepath);
794 if ($includedirs) {
795 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
796 FROM {files} f
797 LEFT JOIN {files_reference} r
798 ON f.referencefileid = r.id
799 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea
800 AND f.itemid = :itemid AND f.filename = '.'
801 AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
802 AND f.id <> :dirid
803 $orderby";
804 $reqlevel = substr_count($filepath, '/') + 1;
805 $filerecords = $DB->get_records_sql($sql, $params);
806 foreach ($filerecords as $filerecord) {
807 if (substr_count($filerecord->filepath, '/') !== $reqlevel) {
808 continue;
810 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
814 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
815 FROM {files} f
816 LEFT JOIN {files_reference} r
817 ON f.referencefileid = r.id
818 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
819 AND f.filepath = :filepath AND f.filename <> '.'
820 $orderby";
822 $filerecords = $DB->get_records_sql($sql, $params);
823 foreach ($filerecords as $filerecord) {
824 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
828 return $result;
832 * Delete all area files (optionally limited by itemid).
834 * @param int $contextid context ID
835 * @param string $component component
836 * @param string $filearea file area or all areas in context if not specified
837 * @param int $itemid item ID or all files if not specified
838 * @return bool success
840 public function delete_area_files($contextid, $component = false, $filearea = false, $itemid = false) {
841 global $DB;
843 $conditions = array('contextid'=>$contextid);
844 if ($component !== false) {
845 $conditions['component'] = $component;
847 if ($filearea !== false) {
848 $conditions['filearea'] = $filearea;
850 if ($itemid !== false) {
851 $conditions['itemid'] = $itemid;
854 $filerecords = $DB->get_records('files', $conditions);
855 foreach ($filerecords as $filerecord) {
856 $this->get_file_instance($filerecord)->delete();
859 return true; // BC only
863 * Delete all the files from certain areas where itemid is limited by an
864 * arbitrary bit of SQL.
866 * @param int $contextid the id of the context the files belong to. Must be given.
867 * @param string $component the owning component. Must be given.
868 * @param string $filearea the file area name. Must be given.
869 * @param string $itemidstest an SQL fragment that the itemid must match. Used
870 * in the query like WHERE itemid $itemidstest. Must used named parameters,
871 * and may not used named parameters called contextid, component or filearea.
872 * @param array $params any query params used by $itemidstest.
874 public function delete_area_files_select($contextid, $component,
875 $filearea, $itemidstest, array $params = null) {
876 global $DB;
878 $where = "contextid = :contextid
879 AND component = :component
880 AND filearea = :filearea
881 AND itemid $itemidstest";
882 $params['contextid'] = $contextid;
883 $params['component'] = $component;
884 $params['filearea'] = $filearea;
886 $filerecords = $DB->get_recordset_select('files', $where, $params);
887 foreach ($filerecords as $filerecord) {
888 $this->get_file_instance($filerecord)->delete();
890 $filerecords->close();
894 * Delete all files associated with the given component.
896 * @param string $component the component owning the file
898 public function delete_component_files($component) {
899 global $DB;
901 $filerecords = $DB->get_recordset('files', array('component' => $component));
902 foreach ($filerecords as $filerecord) {
903 $this->get_file_instance($filerecord)->delete();
905 $filerecords->close();
909 * Move all the files in a file area from one context to another.
911 * @param int $oldcontextid the context the files are being moved from.
912 * @param int $newcontextid the context the files are being moved to.
913 * @param string $component the plugin that these files belong to.
914 * @param string $filearea the name of the file area.
915 * @param int $itemid file item ID
916 * @return int the number of files moved, for information.
918 public function move_area_files_to_new_context($oldcontextid, $newcontextid, $component, $filearea, $itemid = false) {
919 // Note, this code is based on some code that Petr wrote in
920 // forum_move_attachments in mod/forum/lib.php. I moved it here because
921 // I needed it in the question code too.
922 $count = 0;
924 $oldfiles = $this->get_area_files($oldcontextid, $component, $filearea, $itemid, 'id', false);
925 foreach ($oldfiles as $oldfile) {
926 $filerecord = new stdClass();
927 $filerecord->contextid = $newcontextid;
928 $this->create_file_from_storedfile($filerecord, $oldfile);
929 $count += 1;
932 if ($count) {
933 $this->delete_area_files($oldcontextid, $component, $filearea, $itemid);
936 return $count;
940 * Recursively creates directory.
942 * @param int $contextid context ID
943 * @param string $component component
944 * @param string $filearea file area
945 * @param int $itemid item ID
946 * @param string $filepath file path
947 * @param int $userid the user ID
948 * @return bool success
950 public function create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid = null) {
951 global $DB;
953 // validate all parameters, we do not want any rubbish stored in database, right?
954 if (!is_number($contextid) or $contextid < 1) {
955 throw new file_exception('storedfileproblem', 'Invalid contextid');
958 $component = clean_param($component, PARAM_COMPONENT);
959 if (empty($component)) {
960 throw new file_exception('storedfileproblem', 'Invalid component');
963 $filearea = clean_param($filearea, PARAM_AREA);
964 if (empty($filearea)) {
965 throw new file_exception('storedfileproblem', 'Invalid filearea');
968 if (!is_number($itemid) or $itemid < 0) {
969 throw new file_exception('storedfileproblem', 'Invalid itemid');
972 $filepath = clean_param($filepath, PARAM_PATH);
973 if (strpos($filepath, '/') !== 0 or strrpos($filepath, '/') !== strlen($filepath)-1) {
974 // path must start and end with '/'
975 throw new file_exception('storedfileproblem', 'Invalid file path');
978 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, '.');
980 if ($dir_info = $this->get_file_by_hash($pathnamehash)) {
981 return $dir_info;
984 static $contenthash = null;
985 if (!$contenthash) {
986 $this->add_string_to_pool('');
987 $contenthash = self::hash_from_string('');
990 $now = time();
992 $dir_record = new stdClass();
993 $dir_record->contextid = $contextid;
994 $dir_record->component = $component;
995 $dir_record->filearea = $filearea;
996 $dir_record->itemid = $itemid;
997 $dir_record->filepath = $filepath;
998 $dir_record->filename = '.';
999 $dir_record->contenthash = $contenthash;
1000 $dir_record->filesize = 0;
1002 $dir_record->timecreated = $now;
1003 $dir_record->timemodified = $now;
1004 $dir_record->mimetype = null;
1005 $dir_record->userid = $userid;
1007 $dir_record->pathnamehash = $pathnamehash;
1009 $DB->insert_record('files', $dir_record);
1010 $dir_info = $this->get_file_by_hash($pathnamehash);
1012 if ($filepath !== '/') {
1013 //recurse to parent dirs
1014 $filepath = trim($filepath, '/');
1015 $filepath = explode('/', $filepath);
1016 array_pop($filepath);
1017 $filepath = implode('/', $filepath);
1018 $filepath = ($filepath === '') ? '/' : "/$filepath/";
1019 $this->create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid);
1022 return $dir_info;
1026 * Add new file record to database and handle callbacks.
1028 * @param stdClass $newrecord
1030 protected function create_file($newrecord) {
1031 global $DB;
1032 $newrecord->id = $DB->insert_record('files', $newrecord);
1034 if ($newrecord->filename !== '.') {
1035 // Callback for file created.
1036 if ($pluginsfunction = get_plugins_with_function('after_file_created')) {
1037 foreach ($pluginsfunction as $plugintype => $plugins) {
1038 foreach ($plugins as $pluginfunction) {
1039 $pluginfunction($newrecord);
1047 * Add new local file based on existing local file.
1049 * @param stdClass|array $filerecord object or array describing changes
1050 * @param stored_file|int $fileorid id or stored_file instance of the existing local file
1051 * @return stored_file instance of newly created file
1053 public function create_file_from_storedfile($filerecord, $fileorid) {
1054 global $DB;
1056 if ($fileorid instanceof stored_file) {
1057 $fid = $fileorid->get_id();
1058 } else {
1059 $fid = $fileorid;
1062 $filerecord = (array)$filerecord; // We support arrays too, do not modify the submitted record!
1064 unset($filerecord['id']);
1065 unset($filerecord['filesize']);
1066 unset($filerecord['contenthash']);
1067 unset($filerecord['pathnamehash']);
1069 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
1070 FROM {files} f
1071 LEFT JOIN {files_reference} r
1072 ON f.referencefileid = r.id
1073 WHERE f.id = ?";
1075 if (!$newrecord = $DB->get_record_sql($sql, array($fid))) {
1076 throw new file_exception('storedfileproblem', 'File does not exist');
1079 unset($newrecord->id);
1081 foreach ($filerecord as $key => $value) {
1082 // validate all parameters, we do not want any rubbish stored in database, right?
1083 if ($key == 'contextid' and (!is_number($value) or $value < 1)) {
1084 throw new file_exception('storedfileproblem', 'Invalid contextid');
1087 if ($key == 'component') {
1088 $value = clean_param($value, PARAM_COMPONENT);
1089 if (empty($value)) {
1090 throw new file_exception('storedfileproblem', 'Invalid component');
1094 if ($key == 'filearea') {
1095 $value = clean_param($value, PARAM_AREA);
1096 if (empty($value)) {
1097 throw new file_exception('storedfileproblem', 'Invalid filearea');
1101 if ($key == 'itemid' and (!is_number($value) or $value < 0)) {
1102 throw new file_exception('storedfileproblem', 'Invalid itemid');
1106 if ($key == 'filepath') {
1107 $value = clean_param($value, PARAM_PATH);
1108 if (strpos($value, '/') !== 0 or strrpos($value, '/') !== strlen($value)-1) {
1109 // path must start and end with '/'
1110 throw new file_exception('storedfileproblem', 'Invalid file path');
1114 if ($key == 'filename') {
1115 $value = clean_param($value, PARAM_FILE);
1116 if ($value === '') {
1117 // path must start and end with '/'
1118 throw new file_exception('storedfileproblem', 'Invalid file name');
1122 if ($key === 'timecreated' or $key === 'timemodified') {
1123 if (!is_number($value)) {
1124 throw new file_exception('storedfileproblem', 'Invalid file '.$key);
1126 if ($value < 0) {
1127 //NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1128 $value = 0;
1132 if ($key == 'referencefileid' or $key == 'referencelastsync') {
1133 $value = clean_param($value, PARAM_INT);
1136 $newrecord->$key = $value;
1139 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
1141 if ($newrecord->filename === '.') {
1142 // special case - only this function supports directories ;-)
1143 $directory = $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
1144 // update the existing directory with the new data
1145 $newrecord->id = $directory->get_id();
1146 $DB->update_record('files', $newrecord);
1147 return $this->get_file_instance($newrecord);
1150 // note: referencefileid is copied from the original file so that
1151 // creating a new file from an existing alias creates new alias implicitly.
1152 // here we just check the database consistency.
1153 if (!empty($newrecord->repositoryid)) {
1154 // It is OK if the current reference does not exist. It may have been altered by a repository plugin when the files
1155 // where saved from a draft area.
1156 $newrecord->referencefileid = $this->get_or_create_referencefileid($newrecord->repositoryid, $newrecord->reference);
1159 try {
1160 $this->create_file($newrecord);
1161 } catch (dml_exception $e) {
1162 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
1163 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
1167 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
1169 return $this->get_file_instance($newrecord);
1173 * Add new local file.
1175 * @param stdClass|array $filerecord object or array describing file
1176 * @param string $url the URL to the file
1177 * @param array $options {@link download_file_content()} options
1178 * @param bool $usetempfile use temporary file for download, may prevent out of memory problems
1179 * @return stored_file
1181 public function create_file_from_url($filerecord, $url, array $options = null, $usetempfile = false) {
1183 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1184 $filerecord = (object)$filerecord; // We support arrays too.
1186 $headers = isset($options['headers']) ? $options['headers'] : null;
1187 $postdata = isset($options['postdata']) ? $options['postdata'] : null;
1188 $fullresponse = isset($options['fullresponse']) ? $options['fullresponse'] : false;
1189 $timeout = isset($options['timeout']) ? $options['timeout'] : 300;
1190 $connecttimeout = isset($options['connecttimeout']) ? $options['connecttimeout'] : 20;
1191 $skipcertverify = isset($options['skipcertverify']) ? $options['skipcertverify'] : false;
1192 $calctimeout = isset($options['calctimeout']) ? $options['calctimeout'] : false;
1194 if (!isset($filerecord->filename)) {
1195 $parts = explode('/', $url);
1196 $filename = array_pop($parts);
1197 $filerecord->filename = clean_param($filename, PARAM_FILE);
1199 $source = !empty($filerecord->source) ? $filerecord->source : $url;
1200 $filerecord->source = clean_param($source, PARAM_URL);
1202 if ($usetempfile) {
1203 check_dir_exists($this->tempdir);
1204 $tmpfile = tempnam($this->tempdir, 'newfromurl');
1205 $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, $tmpfile, $calctimeout);
1206 if ($content === false) {
1207 throw new file_exception('storedfileproblem', 'Can not fetch file form URL');
1209 try {
1210 $newfile = $this->create_file_from_pathname($filerecord, $tmpfile);
1211 @unlink($tmpfile);
1212 return $newfile;
1213 } catch (Exception $e) {
1214 @unlink($tmpfile);
1215 throw $e;
1218 } else {
1219 $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, NULL, $calctimeout);
1220 if ($content === false) {
1221 throw new file_exception('storedfileproblem', 'Can not fetch file form URL');
1223 return $this->create_file_from_string($filerecord, $content);
1228 * Add new local file.
1230 * @param stdClass|array $filerecord object or array describing file
1231 * @param string $pathname path to file or content of file
1232 * @return stored_file
1234 public function create_file_from_pathname($filerecord, $pathname) {
1235 global $DB;
1237 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1238 $filerecord = (object)$filerecord; // We support arrays too.
1240 // validate all parameters, we do not want any rubbish stored in database, right?
1241 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
1242 throw new file_exception('storedfileproblem', 'Invalid contextid');
1245 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
1246 if (empty($filerecord->component)) {
1247 throw new file_exception('storedfileproblem', 'Invalid component');
1250 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
1251 if (empty($filerecord->filearea)) {
1252 throw new file_exception('storedfileproblem', 'Invalid filearea');
1255 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
1256 throw new file_exception('storedfileproblem', 'Invalid itemid');
1259 if (!empty($filerecord->sortorder)) {
1260 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
1261 $filerecord->sortorder = 0;
1263 } else {
1264 $filerecord->sortorder = 0;
1267 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
1268 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
1269 // path must start and end with '/'
1270 throw new file_exception('storedfileproblem', 'Invalid file path');
1273 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
1274 if ($filerecord->filename === '') {
1275 // filename must not be empty
1276 throw new file_exception('storedfileproblem', 'Invalid file name');
1279 $now = time();
1280 if (isset($filerecord->timecreated)) {
1281 if (!is_number($filerecord->timecreated)) {
1282 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1284 if ($filerecord->timecreated < 0) {
1285 //NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1286 $filerecord->timecreated = 0;
1288 } else {
1289 $filerecord->timecreated = $now;
1292 if (isset($filerecord->timemodified)) {
1293 if (!is_number($filerecord->timemodified)) {
1294 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1296 if ($filerecord->timemodified < 0) {
1297 //NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1298 $filerecord->timemodified = 0;
1300 } else {
1301 $filerecord->timemodified = $now;
1304 $newrecord = new stdClass();
1306 $newrecord->contextid = $filerecord->contextid;
1307 $newrecord->component = $filerecord->component;
1308 $newrecord->filearea = $filerecord->filearea;
1309 $newrecord->itemid = $filerecord->itemid;
1310 $newrecord->filepath = $filerecord->filepath;
1311 $newrecord->filename = $filerecord->filename;
1313 $newrecord->timecreated = $filerecord->timecreated;
1314 $newrecord->timemodified = $filerecord->timemodified;
1315 $newrecord->mimetype = empty($filerecord->mimetype) ? $this->mimetype($pathname, $filerecord->filename) : $filerecord->mimetype;
1316 $newrecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1317 $newrecord->source = empty($filerecord->source) ? null : $filerecord->source;
1318 $newrecord->author = empty($filerecord->author) ? null : $filerecord->author;
1319 $newrecord->license = empty($filerecord->license) ? null : $filerecord->license;
1320 $newrecord->status = empty($filerecord->status) ? 0 : $filerecord->status;
1321 $newrecord->sortorder = $filerecord->sortorder;
1323 list($newrecord->contenthash, $newrecord->filesize, $newfile) = $this->add_file_to_pool($pathname, null, $newrecord);
1325 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
1327 try {
1328 $this->create_file($newrecord);
1329 } catch (dml_exception $e) {
1330 if ($newfile) {
1331 $this->filesystem->remove_file($newrecord->contenthash);
1333 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
1334 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
1337 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
1339 return $this->get_file_instance($newrecord);
1343 * Add new local file.
1345 * @param stdClass|array $filerecord object or array describing file
1346 * @param string $content content of file
1347 * @return stored_file
1349 public function create_file_from_string($filerecord, $content) {
1350 global $DB;
1352 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1353 $filerecord = (object)$filerecord; // We support arrays too.
1355 // validate all parameters, we do not want any rubbish stored in database, right?
1356 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
1357 throw new file_exception('storedfileproblem', 'Invalid contextid');
1360 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
1361 if (empty($filerecord->component)) {
1362 throw new file_exception('storedfileproblem', 'Invalid component');
1365 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
1366 if (empty($filerecord->filearea)) {
1367 throw new file_exception('storedfileproblem', 'Invalid filearea');
1370 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
1371 throw new file_exception('storedfileproblem', 'Invalid itemid');
1374 if (!empty($filerecord->sortorder)) {
1375 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
1376 $filerecord->sortorder = 0;
1378 } else {
1379 $filerecord->sortorder = 0;
1382 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
1383 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
1384 // path must start and end with '/'
1385 throw new file_exception('storedfileproblem', 'Invalid file path');
1388 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
1389 if ($filerecord->filename === '') {
1390 // path must start and end with '/'
1391 throw new file_exception('storedfileproblem', 'Invalid file name');
1394 $now = time();
1395 if (isset($filerecord->timecreated)) {
1396 if (!is_number($filerecord->timecreated)) {
1397 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1399 if ($filerecord->timecreated < 0) {
1400 //NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1401 $filerecord->timecreated = 0;
1403 } else {
1404 $filerecord->timecreated = $now;
1407 if (isset($filerecord->timemodified)) {
1408 if (!is_number($filerecord->timemodified)) {
1409 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1411 if ($filerecord->timemodified < 0) {
1412 //NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1413 $filerecord->timemodified = 0;
1415 } else {
1416 $filerecord->timemodified = $now;
1419 $newrecord = new stdClass();
1421 $newrecord->contextid = $filerecord->contextid;
1422 $newrecord->component = $filerecord->component;
1423 $newrecord->filearea = $filerecord->filearea;
1424 $newrecord->itemid = $filerecord->itemid;
1425 $newrecord->filepath = $filerecord->filepath;
1426 $newrecord->filename = $filerecord->filename;
1428 $newrecord->timecreated = $filerecord->timecreated;
1429 $newrecord->timemodified = $filerecord->timemodified;
1430 $newrecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1431 $newrecord->source = empty($filerecord->source) ? null : $filerecord->source;
1432 $newrecord->author = empty($filerecord->author) ? null : $filerecord->author;
1433 $newrecord->license = empty($filerecord->license) ? null : $filerecord->license;
1434 $newrecord->status = empty($filerecord->status) ? 0 : $filerecord->status;
1435 $newrecord->sortorder = $filerecord->sortorder;
1437 list($newrecord->contenthash, $newrecord->filesize, $newfile) = $this->add_string_to_pool($content, $newrecord);
1438 if (empty($filerecord->mimetype)) {
1439 $newrecord->mimetype = $this->filesystem->mimetype_from_hash($newrecord->contenthash, $newrecord->filename);
1440 } else {
1441 $newrecord->mimetype = $filerecord->mimetype;
1444 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
1446 try {
1447 $this->create_file($newrecord);
1448 } catch (dml_exception $e) {
1449 if ($newfile) {
1450 $this->filesystem->remove_file($newrecord->contenthash);
1452 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
1453 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
1456 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
1458 return $this->get_file_instance($newrecord);
1462 * Synchronise stored file from file.
1464 * @param stored_file $file Stored file to synchronise.
1465 * @param string $path Path to the file to synchronise from.
1466 * @param stdClass $filerecord The file record from the database.
1468 public function synchronise_stored_file_from_file(stored_file $file, $path, $filerecord) {
1469 list($contenthash, $filesize) = $this->add_file_to_pool($path, null, $filerecord);
1470 $file->set_synchronized($contenthash, $filesize);
1474 * Synchronise stored file from string.
1476 * @param stored_file $file Stored file to synchronise.
1477 * @param string $content File content.
1478 * @param stdClass $filerecord The file record from the database.
1480 public function synchronise_stored_file_from_string(stored_file $file, $content, $filerecord) {
1481 list($contenthash, $filesize) = $this->add_string_to_pool($content, $filerecord);
1482 $file->set_synchronized($contenthash, $filesize);
1486 * Create a new alias/shortcut file from file reference information
1488 * @param stdClass|array $filerecord object or array describing the new file
1489 * @param int $repositoryid the id of the repository that provides the original file
1490 * @param string $reference the information required by the repository to locate the original file
1491 * @param array $options options for creating the new file
1492 * @return stored_file
1494 public function create_file_from_reference($filerecord, $repositoryid, $reference, $options = array()) {
1495 global $DB;
1497 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1498 $filerecord = (object)$filerecord; // We support arrays too.
1500 // validate all parameters, we do not want any rubbish stored in database, right?
1501 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
1502 throw new file_exception('storedfileproblem', 'Invalid contextid');
1505 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
1506 if (empty($filerecord->component)) {
1507 throw new file_exception('storedfileproblem', 'Invalid component');
1510 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
1511 if (empty($filerecord->filearea)) {
1512 throw new file_exception('storedfileproblem', 'Invalid filearea');
1515 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
1516 throw new file_exception('storedfileproblem', 'Invalid itemid');
1519 if (!empty($filerecord->sortorder)) {
1520 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
1521 $filerecord->sortorder = 0;
1523 } else {
1524 $filerecord->sortorder = 0;
1527 $filerecord->mimetype = empty($filerecord->mimetype) ? $this->mimetype($filerecord->filename) : $filerecord->mimetype;
1528 $filerecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1529 $filerecord->source = empty($filerecord->source) ? null : $filerecord->source;
1530 $filerecord->author = empty($filerecord->author) ? null : $filerecord->author;
1531 $filerecord->license = empty($filerecord->license) ? null : $filerecord->license;
1532 $filerecord->status = empty($filerecord->status) ? 0 : $filerecord->status;
1533 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
1534 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
1535 // Path must start and end with '/'.
1536 throw new file_exception('storedfileproblem', 'Invalid file path');
1539 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
1540 if ($filerecord->filename === '') {
1541 // Path must start and end with '/'.
1542 throw new file_exception('storedfileproblem', 'Invalid file name');
1545 $now = time();
1546 if (isset($filerecord->timecreated)) {
1547 if (!is_number($filerecord->timecreated)) {
1548 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1550 if ($filerecord->timecreated < 0) {
1551 // NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1552 $filerecord->timecreated = 0;
1554 } else {
1555 $filerecord->timecreated = $now;
1558 if (isset($filerecord->timemodified)) {
1559 if (!is_number($filerecord->timemodified)) {
1560 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1562 if ($filerecord->timemodified < 0) {
1563 // NOTE: unfortunately I make a mistake when creating the "files" table, we can not have negative numbers there, on the other hand no file should be older than 1970, right? (skodak)
1564 $filerecord->timemodified = 0;
1566 } else {
1567 $filerecord->timemodified = $now;
1570 $transaction = $DB->start_delegated_transaction();
1572 try {
1573 $filerecord->referencefileid = $this->get_or_create_referencefileid($repositoryid, $reference);
1574 } catch (Exception $e) {
1575 throw new file_reference_exception($repositoryid, $reference, null, null, $e->getMessage());
1578 $existingfile = null;
1579 if (isset($filerecord->contenthash)) {
1580 $existingfile = $DB->get_record('files', array('contenthash' => $filerecord->contenthash), '*', IGNORE_MULTIPLE);
1582 if (!empty($existingfile)) {
1583 // There is an existing file already available.
1584 if (empty($filerecord->filesize)) {
1585 $filerecord->filesize = $existingfile->filesize;
1586 } else {
1587 $filerecord->filesize = clean_param($filerecord->filesize, PARAM_INT);
1589 } else {
1590 // Attempt to get the result of last synchronisation for this reference.
1591 $lastcontent = $DB->get_record('files', array('referencefileid' => $filerecord->referencefileid),
1592 'id, contenthash, filesize', IGNORE_MULTIPLE);
1593 if ($lastcontent) {
1594 $filerecord->contenthash = $lastcontent->contenthash;
1595 $filerecord->filesize = $lastcontent->filesize;
1596 } else {
1597 // External file doesn't have content in moodle.
1598 // So we create an empty file for it.
1599 list($filerecord->contenthash, $filerecord->filesize, $newfile) = $this->add_string_to_pool(null, $filerecord);
1603 $filerecord->pathnamehash = $this->get_pathname_hash($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid, $filerecord->filepath, $filerecord->filename);
1605 try {
1606 $filerecord->id = $DB->insert_record('files', $filerecord);
1607 } catch (dml_exception $e) {
1608 if (!empty($newfile)) {
1609 $this->filesystem->remove_file($filerecord->contenthash);
1611 throw new stored_file_creation_exception($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid,
1612 $filerecord->filepath, $filerecord->filename, $e->debuginfo);
1615 $this->create_directory($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid, $filerecord->filepath, $filerecord->userid);
1617 $transaction->allow_commit();
1619 // this will retrieve all reference information from DB as well
1620 return $this->get_file_by_id($filerecord->id);
1624 * Creates new image file from existing.
1626 * @param stdClass|array $filerecord object or array describing new file
1627 * @param int|stored_file $fid file id or stored file object
1628 * @param int $newwidth in pixels
1629 * @param int $newheight in pixels
1630 * @param bool $keepaspectratio whether or not keep aspect ratio
1631 * @param int $quality depending on image type 0-100 for jpeg, 0-9 (0 means no compression) for png
1632 * @return stored_file
1634 public function convert_image($filerecord, $fid, $newwidth = null, $newheight = null, $keepaspectratio = true, $quality = null) {
1635 if (!function_exists('imagecreatefromstring')) {
1636 //Most likely the GD php extension isn't installed
1637 //image conversion cannot succeed
1638 throw new file_exception('storedfileproblem', 'imagecreatefromstring() doesnt exist. The PHP extension "GD" must be installed for image conversion.');
1641 if ($fid instanceof stored_file) {
1642 $fid = $fid->get_id();
1645 $filerecord = (array)$filerecord; // We support arrays too, do not modify the submitted record!
1647 if (!$file = $this->get_file_by_id($fid)) { // Make sure file really exists and we we correct data.
1648 throw new file_exception('storedfileproblem', 'File does not exist');
1651 if (!$imageinfo = $file->get_imageinfo()) {
1652 throw new file_exception('storedfileproblem', 'File is not an image');
1655 if (!isset($filerecord['filename'])) {
1656 $filerecord['filename'] = $file->get_filename();
1659 if (!isset($filerecord['mimetype'])) {
1660 $filerecord['mimetype'] = $imageinfo['mimetype'];
1663 $width = $imageinfo['width'];
1664 $height = $imageinfo['height'];
1666 if ($keepaspectratio) {
1667 if (0 >= $newwidth and 0 >= $newheight) {
1668 // no sizes specified
1669 $newwidth = $width;
1670 $newheight = $height;
1672 } else if (0 < $newwidth and 0 < $newheight) {
1673 $xheight = ($newwidth*($height/$width));
1674 if ($xheight < $newheight) {
1675 $newheight = (int)$xheight;
1676 } else {
1677 $newwidth = (int)($newheight*($width/$height));
1680 } else if (0 < $newwidth) {
1681 $newheight = (int)($newwidth*($height/$width));
1683 } else { //0 < $newheight
1684 $newwidth = (int)($newheight*($width/$height));
1687 } else {
1688 if (0 >= $newwidth) {
1689 $newwidth = $width;
1691 if (0 >= $newheight) {
1692 $newheight = $height;
1696 // The original image.
1697 $img = imagecreatefromstring($file->get_content());
1699 // A new true color image where we will copy our original image.
1700 $newimg = imagecreatetruecolor($newwidth, $newheight);
1702 // Determine if the file supports transparency.
1703 $hasalpha = $filerecord['mimetype'] == 'image/png' || $filerecord['mimetype'] == 'image/gif';
1705 // Maintain transparency.
1706 if ($hasalpha) {
1707 imagealphablending($newimg, true);
1709 // Get the current transparent index for the original image.
1710 $colour = imagecolortransparent($img);
1711 if ($colour == -1) {
1712 // Set a transparent colour index if there's none.
1713 $colour = imagecolorallocatealpha($newimg, 255, 255, 255, 127);
1714 // Save full alpha channel.
1715 imagesavealpha($newimg, true);
1717 imagecolortransparent($newimg, $colour);
1718 imagefill($newimg, 0, 0, $colour);
1721 // Process the image to be output.
1722 if ($height != $newheight or $width != $newwidth) {
1723 // Resample if the dimensions differ from the original.
1724 if (!imagecopyresampled($newimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height)) {
1725 // weird
1726 throw new file_exception('storedfileproblem', 'Can not resize image');
1728 imagedestroy($img);
1729 $img = $newimg;
1731 } else if ($hasalpha) {
1732 // Just copy to the new image with the alpha channel.
1733 if (!imagecopy($newimg, $img, 0, 0, 0, 0, $width, $height)) {
1734 // Weird.
1735 throw new file_exception('storedfileproblem', 'Can not copy image');
1737 imagedestroy($img);
1738 $img = $newimg;
1740 } else {
1741 // No particular processing needed for the original image.
1742 imagedestroy($newimg);
1745 ob_start();
1746 switch ($filerecord['mimetype']) {
1747 case 'image/gif':
1748 imagegif($img);
1749 break;
1751 case 'image/jpeg':
1752 if (is_null($quality)) {
1753 imagejpeg($img);
1754 } else {
1755 imagejpeg($img, NULL, $quality);
1757 break;
1759 case 'image/png':
1760 $quality = (int)$quality;
1762 // Woah nelly! Because PNG quality is in the range 0 - 9 compared to JPEG quality,
1763 // the latter of which can go to 100, we need to make sure that quality here is
1764 // in a safe range or PHP WILL CRASH AND DIE. You have been warned.
1765 $quality = $quality > 9 ? (int)(max(1.0, (float)$quality / 100.0) * 9.0) : $quality;
1766 imagepng($img, NULL, $quality, NULL);
1767 break;
1769 default:
1770 throw new file_exception('storedfileproblem', 'Unsupported mime type');
1773 $content = ob_get_contents();
1774 ob_end_clean();
1775 imagedestroy($img);
1777 if (!$content) {
1778 throw new file_exception('storedfileproblem', 'Can not convert image');
1781 return $this->create_file_from_string($filerecord, $content);
1785 * Add file content to sha1 pool.
1787 * @param string $pathname path to file
1788 * @param string|null $contenthash sha1 hash of content if known (performance only)
1789 * @param stdClass|null $newrecord New file record
1790 * @return array (contenthash, filesize, newfile)
1792 public function add_file_to_pool($pathname, $contenthash = null, $newrecord = null) {
1793 $this->call_before_file_created_plugin_functions($newrecord, $pathname);
1794 return $this->filesystem->add_file_from_path($pathname, $contenthash);
1798 * Add string content to sha1 pool.
1800 * @param string $content file content - binary string
1801 * @return array (contenthash, filesize, newfile)
1803 public function add_string_to_pool($content, $newrecord = null) {
1804 $this->call_before_file_created_plugin_functions($newrecord, null, $content);
1805 return $this->filesystem->add_file_from_string($content);
1809 * before_file_created hook.
1811 * @param stdClass|null $newrecord New file record.
1812 * @param string|null $pathname Path to file.
1813 * @param string|null $content File content.
1815 protected function call_before_file_created_plugin_functions($newrecord, $pathname = null, $content = null) {
1816 $pluginsfunction = get_plugins_with_function('before_file_created');
1817 foreach ($pluginsfunction as $plugintype => $plugins) {
1818 foreach ($plugins as $pluginfunction) {
1819 $pluginfunction($newrecord, ['pathname' => $pathname, 'content' => $content]);
1825 * Serve file content using X-Sendfile header.
1826 * Please make sure that all headers are already sent
1827 * and the all access control checks passed.
1829 * @param string $contenthash sah1 hash of the file content to be served
1830 * @return bool success
1832 public function xsendfile($contenthash) {
1833 return $this->filesystem->xsendfile($contenthash);
1837 * Content exists
1839 * @param string $contenthash
1840 * @return bool
1841 * @deprecated since 3.3
1843 public function content_exists($contenthash) {
1844 debugging('The content_exists function has been deprecated and should no longer be used.', DEBUG_DEVELOPER);
1846 return false;
1850 * Tries to recover missing content of file from trash.
1852 * @param stored_file $file stored_file instance
1853 * @return bool success
1854 * @deprecated since 3.3
1856 public function try_content_recovery($file) {
1857 debugging('The try_content_recovery function has been deprecated and should no longer be used.', DEBUG_DEVELOPER);
1859 return false;
1863 * When user referring to a moodle file, we build the reference field
1865 * @param array $params
1866 * @return string
1868 public static function pack_reference($params) {
1869 $params = (array)$params;
1870 $reference = array();
1871 $reference['contextid'] = is_null($params['contextid']) ? null : clean_param($params['contextid'], PARAM_INT);
1872 $reference['component'] = is_null($params['component']) ? null : clean_param($params['component'], PARAM_COMPONENT);
1873 $reference['itemid'] = is_null($params['itemid']) ? null : clean_param($params['itemid'], PARAM_INT);
1874 $reference['filearea'] = is_null($params['filearea']) ? null : clean_param($params['filearea'], PARAM_AREA);
1875 $reference['filepath'] = is_null($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH);
1876 $reference['filename'] = is_null($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE);
1877 return base64_encode(serialize($reference));
1881 * Unpack reference field
1883 * @param string $str
1884 * @param bool $cleanparams if set to true, array elements will be passed through {@link clean_param()}
1885 * @throws file_reference_exception if the $str does not have the expected format
1886 * @return array
1888 public static function unpack_reference($str, $cleanparams = false) {
1889 $decoded = base64_decode($str, true);
1890 if ($decoded === false) {
1891 throw new file_reference_exception(null, $str, null, null, 'Invalid base64 format');
1893 $params = @unserialize($decoded); // hide E_NOTICE
1894 if ($params === false) {
1895 throw new file_reference_exception(null, $decoded, null, null, 'Not an unserializeable value');
1897 if (is_array($params) && $cleanparams) {
1898 $params = array(
1899 'component' => is_null($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
1900 'filearea' => is_null($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
1901 'itemid' => is_null($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
1902 'filename' => is_null($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
1903 'filepath' => is_null($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
1904 'contextid' => is_null($params['contextid']) ? null : clean_param($params['contextid'], PARAM_INT)
1907 return $params;
1911 * Search through the server files.
1913 * The query parameter will be used in conjuction with the SQL directive
1914 * LIKE, so include '%' in it if you need to. This search will always ignore
1915 * user files and directories. Note that the search is case insensitive.
1917 * This query can quickly become inefficient so use it sparignly.
1919 * @param string $query The string used with SQL LIKE.
1920 * @param integer $from The offset to start the search at.
1921 * @param integer $limit The maximum number of results.
1922 * @param boolean $count When true this methods returns the number of results availabe,
1923 * disregarding the parameters $from and $limit.
1924 * @return int|array Integer when count, otherwise array of stored_file objects.
1926 public function search_server_files($query, $from = 0, $limit = 20, $count = false) {
1927 global $DB;
1928 $params = array(
1929 'contextlevel' => CONTEXT_USER,
1930 'directory' => '.',
1931 'query' => $query
1934 if ($count) {
1935 $select = 'COUNT(1)';
1936 } else {
1937 $select = self::instance_sql_fields('f', 'r');
1939 $like = $DB->sql_like('f.filename', ':query', false);
1941 $sql = "SELECT $select
1942 FROM {files} f
1943 LEFT JOIN {files_reference} r
1944 ON f.referencefileid = r.id
1945 JOIN {context} c
1946 ON f.contextid = c.id
1947 WHERE c.contextlevel <> :contextlevel
1948 AND f.filename <> :directory
1949 AND " . $like . "";
1951 if ($count) {
1952 return $DB->count_records_sql($sql, $params);
1955 $sql .= " ORDER BY f.filename";
1957 $result = array();
1958 $filerecords = $DB->get_recordset_sql($sql, $params, $from, $limit);
1959 foreach ($filerecords as $filerecord) {
1960 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
1962 $filerecords->close();
1964 return $result;
1968 * Returns all aliases that refer to some stored_file via the given reference
1970 * All repositories that provide access to a stored_file are expected to use
1971 * {@link self::pack_reference()}. This method can't be used if the given reference
1972 * does not use this format or if you are looking for references to an external file
1973 * (for example it can't be used to search for all aliases that refer to a given
1974 * Dropbox or Box.net file).
1976 * Aliases in user draft areas are excluded from the returned list.
1978 * @param string $reference identification of the referenced file
1979 * @return array of stored_file indexed by its pathnamehash
1981 public function search_references($reference) {
1982 global $DB;
1984 if (is_null($reference)) {
1985 throw new coding_exception('NULL is not a valid reference to an external file');
1988 // Give {@link self::unpack_reference()} a chance to throw exception if the
1989 // reference is not in a valid format.
1990 self::unpack_reference($reference);
1992 $referencehash = sha1($reference);
1994 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
1995 FROM {files} f
1996 JOIN {files_reference} r ON f.referencefileid = r.id
1997 JOIN {repository_instances} ri ON r.repositoryid = ri.id
1998 WHERE r.referencehash = ?
1999 AND (f.component <> ? OR f.filearea <> ?)";
2001 $rs = $DB->get_recordset_sql($sql, array($referencehash, 'user', 'draft'));
2002 $files = array();
2003 foreach ($rs as $filerecord) {
2004 $files[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
2006 $rs->close();
2008 return $files;
2012 * Returns the number of aliases that refer to some stored_file via the given reference
2014 * All repositories that provide access to a stored_file are expected to use
2015 * {@link self::pack_reference()}. This method can't be used if the given reference
2016 * does not use this format or if you are looking for references to an external file
2017 * (for example it can't be used to count aliases that refer to a given Dropbox or
2018 * Box.net file).
2020 * Aliases in user draft areas are not counted.
2022 * @param string $reference identification of the referenced file
2023 * @return int
2025 public function search_references_count($reference) {
2026 global $DB;
2028 if (is_null($reference)) {
2029 throw new coding_exception('NULL is not a valid reference to an external file');
2032 // Give {@link self::unpack_reference()} a chance to throw exception if the
2033 // reference is not in a valid format.
2034 self::unpack_reference($reference);
2036 $referencehash = sha1($reference);
2038 $sql = "SELECT COUNT(f.id)
2039 FROM {files} f
2040 JOIN {files_reference} r ON f.referencefileid = r.id
2041 JOIN {repository_instances} ri ON r.repositoryid = ri.id
2042 WHERE r.referencehash = ?
2043 AND (f.component <> ? OR f.filearea <> ?)";
2045 return (int)$DB->count_records_sql($sql, array($referencehash, 'user', 'draft'));
2049 * Returns all aliases that link to the given stored_file
2051 * Aliases in user draft areas are excluded from the returned list.
2053 * @param stored_file $storedfile
2054 * @return array of stored_file
2056 public function get_references_by_storedfile(stored_file $storedfile) {
2057 global $DB;
2059 $params = array();
2060 $params['contextid'] = $storedfile->get_contextid();
2061 $params['component'] = $storedfile->get_component();
2062 $params['filearea'] = $storedfile->get_filearea();
2063 $params['itemid'] = $storedfile->get_itemid();
2064 $params['filename'] = $storedfile->get_filename();
2065 $params['filepath'] = $storedfile->get_filepath();
2067 return $this->search_references(self::pack_reference($params));
2071 * Returns the number of aliases that link to the given stored_file
2073 * Aliases in user draft areas are not counted.
2075 * @param stored_file $storedfile
2076 * @return int
2078 public function get_references_count_by_storedfile(stored_file $storedfile) {
2079 global $DB;
2081 $params = array();
2082 $params['contextid'] = $storedfile->get_contextid();
2083 $params['component'] = $storedfile->get_component();
2084 $params['filearea'] = $storedfile->get_filearea();
2085 $params['itemid'] = $storedfile->get_itemid();
2086 $params['filename'] = $storedfile->get_filename();
2087 $params['filepath'] = $storedfile->get_filepath();
2089 return $this->search_references_count(self::pack_reference($params));
2093 * Updates all files that are referencing this file with the new contenthash
2094 * and filesize
2096 * @param stored_file $storedfile
2098 public function update_references_to_storedfile(stored_file $storedfile) {
2099 global $CFG, $DB;
2100 $params = array();
2101 $params['contextid'] = $storedfile->get_contextid();
2102 $params['component'] = $storedfile->get_component();
2103 $params['filearea'] = $storedfile->get_filearea();
2104 $params['itemid'] = $storedfile->get_itemid();
2105 $params['filename'] = $storedfile->get_filename();
2106 $params['filepath'] = $storedfile->get_filepath();
2107 $reference = self::pack_reference($params);
2108 $referencehash = sha1($reference);
2110 $sql = "SELECT repositoryid, id FROM {files_reference}
2111 WHERE referencehash = ?";
2112 $rs = $DB->get_recordset_sql($sql, array($referencehash));
2114 $now = time();
2115 foreach ($rs as $record) {
2116 $this->update_references($record->id, $now, null,
2117 $storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
2119 $rs->close();
2123 * Convert file alias to local file
2125 * @throws moodle_exception if file could not be downloaded
2127 * @param stored_file $storedfile a stored_file instances
2128 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
2129 * @return stored_file stored_file
2131 public function import_external_file(stored_file $storedfile, $maxbytes = 0) {
2132 global $CFG;
2133 $storedfile->import_external_file_contents($maxbytes);
2134 $storedfile->delete_reference();
2135 return $storedfile;
2139 * Return mimetype by given file pathname.
2141 * If file has a known extension, we return the mimetype based on extension.
2142 * Otherwise (when possible) we try to get the mimetype from file contents.
2144 * @param string $fullpath Full path to the file on disk
2145 * @param string $filename Correct file name with extension, if omitted will be taken from $path
2146 * @return string
2148 public static function mimetype($fullpath, $filename = null) {
2149 if (empty($filename)) {
2150 $filename = $fullpath;
2153 // The mimeinfo function determines the mimetype purely based on the file extension.
2154 $type = mimeinfo('type', $filename);
2156 if ($type === 'document/unknown') {
2157 // The type is unknown. Inspect the file now.
2158 $type = self::mimetype_from_file($fullpath);
2160 return $type;
2164 * Inspect a file on disk for it's mimetype.
2166 * @param string $fullpath Path to file on disk
2167 * @return string The mimetype
2169 public static function mimetype_from_file($fullpath) {
2170 if (file_exists($fullpath)) {
2171 // The type is unknown. Attempt to look up the file type now.
2172 $finfo = new finfo(FILEINFO_MIME_TYPE);
2173 return mimeinfo_from_type('type', $finfo->file($fullpath));
2176 return 'document/unknown';
2180 * Cron cleanup job.
2182 public function cron() {
2183 global $CFG, $DB;
2184 require_once($CFG->libdir.'/cronlib.php');
2186 // find out all stale draft areas (older than 4 days) and purge them
2187 // those are identified by time stamp of the /. root dir
2188 mtrace('Deleting old draft files... ', '');
2189 cron_trace_time_and_memory();
2190 $old = time() - 60*60*24*4;
2191 $sql = "SELECT *
2192 FROM {files}
2193 WHERE component = 'user' AND filearea = 'draft' AND filepath = '/' AND filename = '.'
2194 AND timecreated < :old";
2195 $rs = $DB->get_recordset_sql($sql, array('old'=>$old));
2196 foreach ($rs as $dir) {
2197 $this->delete_area_files($dir->contextid, $dir->component, $dir->filearea, $dir->itemid);
2199 $rs->close();
2200 mtrace('done.');
2202 // remove orphaned preview files (that is files in the core preview filearea without
2203 // the existing original file)
2204 mtrace('Deleting orphaned preview files... ', '');
2205 cron_trace_time_and_memory();
2206 $sql = "SELECT p.*
2207 FROM {files} p
2208 LEFT JOIN {files} o ON (p.filename = o.contenthash)
2209 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'preview' AND p.itemid = 0
2210 AND o.id IS NULL";
2211 $syscontext = context_system::instance();
2212 $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
2213 foreach ($rs as $orphan) {
2214 $file = $this->get_file_instance($orphan);
2215 if (!$file->is_directory()) {
2216 $file->delete();
2219 $rs->close();
2220 mtrace('done.');
2222 // Remove orphaned converted files (that is files in the core documentconversion filearea without
2223 // the existing original file).
2224 mtrace('Deleting orphaned document conversion files... ', '');
2225 cron_trace_time_and_memory();
2226 $sql = "SELECT p.*
2227 FROM {files} p
2228 LEFT JOIN {files} o ON (p.filename = o.contenthash)
2229 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'documentconversion' AND p.itemid = 0
2230 AND o.id IS NULL";
2231 $syscontext = context_system::instance();
2232 $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
2233 foreach ($rs as $orphan) {
2234 $file = $this->get_file_instance($orphan);
2235 if (!$file->is_directory()) {
2236 $file->delete();
2239 $rs->close();
2240 mtrace('done.');
2242 // remove trash pool files once a day
2243 // if you want to disable purging of trash put $CFG->fileslastcleanup=time(); into config.php
2244 if (empty($CFG->fileslastcleanup) or $CFG->fileslastcleanup < time() - 60*60*24) {
2245 require_once($CFG->libdir.'/filelib.php');
2246 // Delete files that are associated with a context that no longer exists.
2247 mtrace('Cleaning up files from deleted contexts... ', '');
2248 cron_trace_time_and_memory();
2249 $sql = "SELECT DISTINCT f.contextid
2250 FROM {files} f
2251 LEFT OUTER JOIN {context} c ON f.contextid = c.id
2252 WHERE c.id IS NULL";
2253 $rs = $DB->get_recordset_sql($sql);
2254 if ($rs->valid()) {
2255 $fs = get_file_storage();
2256 foreach ($rs as $ctx) {
2257 $fs->delete_area_files($ctx->contextid);
2260 $rs->close();
2261 mtrace('done.');
2263 mtrace('Call filesystem cron tasks.', '');
2264 cron_trace_time_and_memory();
2265 $this->filesystem->cron();
2266 mtrace('done.');
2271 * Get the sql formated fields for a file instance to be created from a
2272 * {files} and {files_refernece} join.
2274 * @param string $filesprefix the table prefix for the {files} table
2275 * @param string $filesreferenceprefix the table prefix for the {files_reference} table
2276 * @return string the sql to go after a SELECT
2278 private static function instance_sql_fields($filesprefix, $filesreferenceprefix) {
2279 // Note, these fieldnames MUST NOT overlap between the two tables,
2280 // else problems like MDL-33172 occur.
2281 $filefields = array('contenthash', 'pathnamehash', 'contextid', 'component', 'filearea',
2282 'itemid', 'filepath', 'filename', 'userid', 'filesize', 'mimetype', 'status', 'source',
2283 'author', 'license', 'timecreated', 'timemodified', 'sortorder', 'referencefileid');
2285 $referencefields = array('repositoryid' => 'repositoryid',
2286 'reference' => 'reference',
2287 'lastsync' => 'referencelastsync');
2289 // id is specifically named to prevent overlaping between the two tables.
2290 $fields = array();
2291 $fields[] = $filesprefix.'.id AS id';
2292 foreach ($filefields as $field) {
2293 $fields[] = "{$filesprefix}.{$field}";
2296 foreach ($referencefields as $field => $alias) {
2297 $fields[] = "{$filesreferenceprefix}.{$field} AS {$alias}";
2300 return implode(', ', $fields);
2304 * Returns the id of the record in {files_reference} that matches the passed repositoryid and reference
2306 * If the record already exists, its id is returned. If there is no such record yet,
2307 * new one is created (using the lastsync provided, too) and its id is returned.
2309 * @param int $repositoryid
2310 * @param string $reference
2311 * @param int $lastsync
2312 * @param int $lifetime argument not used any more
2313 * @return int
2315 private function get_or_create_referencefileid($repositoryid, $reference, $lastsync = null, $lifetime = null) {
2316 global $DB;
2318 $id = $this->get_referencefileid($repositoryid, $reference, IGNORE_MISSING);
2320 if ($id !== false) {
2321 // bah, that was easy
2322 return $id;
2325 // no such record yet, create one
2326 try {
2327 $id = $DB->insert_record('files_reference', array(
2328 'repositoryid' => $repositoryid,
2329 'reference' => $reference,
2330 'referencehash' => sha1($reference),
2331 'lastsync' => $lastsync));
2332 } catch (dml_exception $e) {
2333 // if inserting the new record failed, chances are that the race condition has just
2334 // occured and the unique index did not allow to create the second record with the same
2335 // repositoryid + reference combo
2336 $id = $this->get_referencefileid($repositoryid, $reference, MUST_EXIST);
2339 return $id;
2343 * Returns the id of the record in {files_reference} that matches the passed parameters
2345 * Depending on the required strictness, false can be returned. The behaviour is consistent
2346 * with standard DML methods.
2348 * @param int $repositoryid
2349 * @param string $reference
2350 * @param int $strictness either {@link IGNORE_MISSING}, {@link IGNORE_MULTIPLE} or {@link MUST_EXIST}
2351 * @return int|bool
2353 private function get_referencefileid($repositoryid, $reference, $strictness) {
2354 global $DB;
2356 return $DB->get_field('files_reference', 'id',
2357 array('repositoryid' => $repositoryid, 'referencehash' => sha1($reference)), $strictness);
2361 * Updates a reference to the external resource and all files that use it
2363 * This function is called after synchronisation of an external file and updates the
2364 * contenthash, filesize and status of all files that reference this external file
2365 * as well as time last synchronised.
2367 * @param int $referencefileid
2368 * @param int $lastsync
2369 * @param int $lifetime argument not used any more, liefetime is returned by repository
2370 * @param string $contenthash
2371 * @param int $filesize
2372 * @param int $status 0 if ok or 666 if source is missing
2373 * @param int $timemodified last time modified of the source, if known
2375 public function update_references($referencefileid, $lastsync, $lifetime, $contenthash, $filesize, $status, $timemodified = null) {
2376 global $DB;
2377 $referencefileid = clean_param($referencefileid, PARAM_INT);
2378 $lastsync = clean_param($lastsync, PARAM_INT);
2379 validate_param($contenthash, PARAM_TEXT, NULL_NOT_ALLOWED);
2380 $filesize = clean_param($filesize, PARAM_INT);
2381 $status = clean_param($status, PARAM_INT);
2382 $params = array('contenthash' => $contenthash,
2383 'filesize' => $filesize,
2384 'status' => $status,
2385 'referencefileid' => $referencefileid,
2386 'timemodified' => $timemodified);
2387 $DB->execute('UPDATE {files} SET contenthash = :contenthash, filesize = :filesize,
2388 status = :status ' . ($timemodified ? ', timemodified = :timemodified' : '') . '
2389 WHERE referencefileid = :referencefileid', $params);
2390 $data = array('id' => $referencefileid, 'lastsync' => $lastsync);
2391 $DB->update_record('files_reference', (object)$data);
2395 * Calculate and return the contenthash of the supplied file.
2397 * @param string $filepath The path to the file on disk
2398 * @return string The file's content hash
2400 public static function hash_from_path($filepath) {
2401 return sha1_file($filepath);
2405 * Calculate and return the contenthash of the supplied content.
2407 * @param string $content The file content
2408 * @return string The file's content hash
2410 public static function hash_from_string($content) {
2411 return sha1($content);