MDL-33330 introducing new file_reference_exception
[moodle.git] / lib / filestorage / file_storage.php
CommitLineData
25aebf09 1<?php
25aebf09 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/**
19 * Core file storage class definition.
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
25aebf09 24 */
172dd12c 25
64f93798
PS
26defined('MOODLE_INTERNAL') || die();
27
28require_once("$CFG->libdir/filestorage/stored_file.php");
172dd12c 29
25aebf09 30/**
31 * File storage class used for low level access to stored files.
bf9ffe27 32 *
25aebf09 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
bf9ffe27
PS
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.
38 *
d2b7803e
DC
39 * @package core_files
40 * @category files
bf9ffe27
PS
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
25aebf09 44 */
172dd12c 45class file_storage {
bf9ffe27 46 /** @var string Directory with file contents */
172dd12c 47 private $filedir;
bf9ffe27 48 /** @var string Contents of deleted files not needed any more */
1aa01caf 49 private $trashdir;
3a1055a5
PS
50 /** @var string tempdir */
51 private $tempdir;
bf9ffe27 52 /** @var int Permissions for new directories */
1aa01caf 53 private $dirpermissions;
bf9ffe27 54 /** @var int Permissions for new files */
1aa01caf 55 private $filepermissions;
bf9ffe27 56
172dd12c 57 /**
d2b7803e 58 * Constructor - do not use directly use {@link get_file_storage()} call instead.
bf9ffe27 59 *
172dd12c 60 * @param string $filedir full path to pool directory
bf9ffe27 61 * @param string $trashdir temporary storage of deleted area
3a1055a5 62 * @param string $tempdir temporary storage of various files
bf9ffe27
PS
63 * @param int $dirpermissions new directory permissions
64 * @param int $filepermissions new file permissions
172dd12c 65 */
3a1055a5 66 public function __construct($filedir, $trashdir, $tempdir, $dirpermissions, $filepermissions) {
1aa01caf 67 $this->filedir = $filedir;
68 $this->trashdir = $trashdir;
3a1055a5 69 $this->tempdir = $tempdir;
1aa01caf 70 $this->dirpermissions = $dirpermissions;
71 $this->filepermissions = $filepermissions;
172dd12c 72
73 // make sure the file pool directory exists
74 if (!is_dir($this->filedir)) {
1aa01caf 75 if (!mkdir($this->filedir, $this->dirpermissions, true)) {
145a0a31 76 throw new file_exception('storedfilecannotcreatefiledirs'); // permission trouble
172dd12c 77 }
78 // place warning file in file pool root
1aa01caf 79 if (!file_exists($this->filedir.'/warning.txt')) {
80 file_put_contents($this->filedir.'/warning.txt',
81 'This directory contains the content of uploaded files and is controlled by Moodle code. Do not manually move, change or rename any of the files and subdirectories here.');
82 }
83 }
84 // make sure the file pool directory exists
85 if (!is_dir($this->trashdir)) {
86 if (!mkdir($this->trashdir, $this->dirpermissions, true)) {
87 throw new file_exception('storedfilecannotcreatefiledirs'); // permission trouble
88 }
172dd12c 89 }
90 }
91
92 /**
bf9ffe27
PS
93 * Calculates sha1 hash of unique full path name information.
94 *
95 * This hash is a unique file identifier - it is used to improve
96 * performance and overcome db index size limits.
97 *
d2b7803e
DC
98 * @param int $contextid context ID
99 * @param string $component component
100 * @param string $filearea file area
101 * @param int $itemid item ID
102 * @param string $filepath file path
103 * @param string $filename file name
bf9ffe27 104 * @return string sha1 hash
172dd12c 105 */
64f93798
PS
106 public static function get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename) {
107 return sha1("/$contextid/$component/$filearea/$itemid".$filepath.$filename);
172dd12c 108 }
109
110 /**
111 * Does this file exist?
bf9ffe27 112 *
d2b7803e
DC
113 * @param int $contextid context ID
114 * @param string $component component
115 * @param string $filearea file area
116 * @param int $itemid item ID
117 * @param string $filepath file path
118 * @param string $filename file name
172dd12c 119 * @return bool
120 */
64f93798 121 public function file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename) {
172dd12c 122 $filepath = clean_param($filepath, PARAM_PATH);
123 $filename = clean_param($filename, PARAM_FILE);
124
125 if ($filename === '') {
126 $filename = '.';
127 }
128
64f93798 129 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
172dd12c 130 return $this->file_exists_by_hash($pathnamehash);
131 }
132
133 /**
d2b7803e 134 * Whether or not the file exist
bf9ffe27 135 *
d2b7803e 136 * @param string $pathnamehash path name hash
172dd12c 137 * @return bool
138 */
139 public function file_exists_by_hash($pathnamehash) {
140 global $DB;
141
142 return $DB->record_exists('files', array('pathnamehash'=>$pathnamehash));
143 }
144
693ef3a8
PS
145 /**
146 * Create instance of file class from database record.
147 *
04e3b007 148 * @param stdClass $filerecord record from the files table left join files_reference table
693ef3a8
PS
149 * @return stored_file instance of file abstraction class
150 */
67233725
DC
151 public function get_file_instance(stdClass $filerecord) {
152 $storedfile = new stored_file($this, $filerecord, $this->filedir);
153 return $storedfile;
693ef3a8
PS
154 }
155
c4d19c5a
DM
156 /**
157 * Returns an image file that represent the given stored file as a preview
158 *
159 * At the moment, only GIF, JPEG and PNG files are supported to have previews. In the
160 * future, the support for other mimetypes can be added, too (eg. generate an image
161 * preview of PDF, text documents etc).
162 *
163 * @param stored_file $file the file we want to preview
164 * @param string $mode preview mode, eg. 'thumb'
165 * @return stored_file|bool false if unable to create the preview, stored file otherwise
166 */
167 public function get_file_preview(stored_file $file, $mode) {
168
169 $context = context_system::instance();
170 $path = '/' . trim($mode, '/') . '/';
171 $preview = $this->get_file($context->id, 'core', 'preview', 0, $path, $file->get_contenthash());
172
173 if (!$preview) {
174 $preview = $this->create_file_preview($file, $mode);
175 if (!$preview) {
176 return false;
177 }
178 }
179
180 return $preview;
181 }
182
183 /**
184 * Generates a preview image for the stored file
185 *
186 * @param stored_file $file the file we want to preview
187 * @param string $mode preview mode, eg. 'thumb'
188 * @return stored_file|bool the newly created preview file or false
189 */
190 protected function create_file_preview(stored_file $file, $mode) {
191
192 $mimetype = $file->get_mimetype();
193
fe68aac7 194 if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
c4d19c5a
DM
195 // make a preview of the image
196 $data = $this->create_imagefile_preview($file, $mode);
197
198 } else {
199 // unable to create the preview of this mimetype yet
200 return false;
201 }
202
203 if (empty($data)) {
204 return false;
205 }
206
207 // getimagesizefromstring() is available from PHP 5.4 but we need to support
208 // lower versions, so...
209 $tmproot = make_temp_directory('thumbnails');
94d10417 210 $tmpfilepath = $tmproot.'/'.$file->get_contenthash().'_'.$mode;
c4d19c5a
DM
211 file_put_contents($tmpfilepath, $data);
212 $imageinfo = getimagesize($tmpfilepath);
213 unlink($tmpfilepath);
214
215 $context = context_system::instance();
216
217 $record = array(
218 'contextid' => $context->id,
219 'component' => 'core',
220 'filearea' => 'preview',
221 'itemid' => 0,
222 'filepath' => '/' . trim($mode, '/') . '/',
223 'filename' => $file->get_contenthash(),
224 );
225
226 if ($imageinfo) {
227 $record['mimetype'] = $imageinfo['mime'];
228 }
229
230 return $this->create_file_from_string($record, $data);
231 }
232
233 /**
234 * Generates a preview for the stored image file
235 *
236 * @param stored_file $file the image we want to preview
237 * @param string $mode preview mode, eg. 'thumb'
238 * @return string|bool false if a problem occurs, the thumbnail image data otherwise
239 */
240 protected function create_imagefile_preview(stored_file $file, $mode) {
241 global $CFG;
242 require_once($CFG->libdir.'/gdlib.php');
243
244 $tmproot = make_temp_directory('thumbnails');
245 $tmpfilepath = $tmproot.'/'.$file->get_contenthash();
246 $file->copy_content_to($tmpfilepath);
247
fe68aac7 248 if ($mode === 'tinyicon') {
10f0978b 249 $data = generate_image_thumbnail($tmpfilepath, 24, 24);
c4d19c5a 250
fe68aac7 251 } else if ($mode === 'thumb') {
c4d19c5a
DM
252 $data = generate_image_thumbnail($tmpfilepath, 90, 90);
253
254 } else {
255 throw new file_exception('storedfileproblem', 'Invalid preview mode requested');
256 }
257
258 unlink($tmpfilepath);
259
260 return $data;
261 }
262
172dd12c 263 /**
25aebf09 264 * Fetch file using local file id.
bf9ffe27 265 *
25aebf09 266 * Please do not rely on file ids, it is usually easier to use
267 * pathname hashes instead.
bf9ffe27 268 *
d2b7803e
DC
269 * @param int $fileid file ID
270 * @return stored_file|bool stored_file instance if exists, false if not
172dd12c 271 */
272 public function get_file_by_id($fileid) {
273 global $DB;
274
3447100c 275 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
276 FROM {files} f
277 LEFT JOIN {files_reference} r
278 ON f.referencefileid = r.id
279 WHERE f.id = ?";
280 if ($filerecord = $DB->get_record_sql($sql, array($fileid))) {
281 return $this->get_file_instance($filerecord);
172dd12c 282 } else {
283 return false;
284 }
285 }
286
287 /**
288 * Fetch file using local file full pathname hash
bf9ffe27 289 *
d2b7803e
DC
290 * @param string $pathnamehash path name hash
291 * @return stored_file|bool stored_file instance if exists, false if not
172dd12c 292 */
293 public function get_file_by_hash($pathnamehash) {
294 global $DB;
295
3447100c 296 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
297 FROM {files} f
298 LEFT JOIN {files_reference} r
299 ON f.referencefileid = r.id
300 WHERE f.pathnamehash = ?";
301 if ($filerecord = $DB->get_record_sql($sql, array($pathnamehash))) {
302 return $this->get_file_instance($filerecord);
172dd12c 303 } else {
304 return false;
305 }
306 }
307
308 /**
bf9ffe27
PS
309 * Fetch locally stored file.
310 *
d2b7803e
DC
311 * @param int $contextid context ID
312 * @param string $component component
313 * @param string $filearea file area
314 * @param int $itemid item ID
315 * @param string $filepath file path
316 * @param string $filename file name
317 * @return stored_file|bool stored_file instance if exists, false if not
172dd12c 318 */
64f93798 319 public function get_file($contextid, $component, $filearea, $itemid, $filepath, $filename) {
172dd12c 320 $filepath = clean_param($filepath, PARAM_PATH);
321 $filename = clean_param($filename, PARAM_FILE);
322
323 if ($filename === '') {
324 $filename = '.';
325 }
326
64f93798 327 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
172dd12c 328 return $this->get_file_by_hash($pathnamehash);
329 }
330
16741cac
PS
331 /**
332 * Are there any files (or directories)
d2b7803e
DC
333 *
334 * @param int $contextid context ID
335 * @param string $component component
336 * @param string $filearea file area
337 * @param bool|int $itemid item id or false if all items
338 * @param bool $ignoredirs whether or not ignore directories
16741cac
PS
339 * @return bool empty
340 */
341 public function is_area_empty($contextid, $component, $filearea, $itemid = false, $ignoredirs = true) {
342 global $DB;
343
344 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
345 $where = "contextid = :contextid AND component = :component AND filearea = :filearea";
346
347 if ($itemid !== false) {
348 $params['itemid'] = $itemid;
349 $where .= " AND itemid = :itemid";
350 }
351
352 if ($ignoredirs) {
353 $sql = "SELECT 'x'
354 FROM {files}
355 WHERE $where AND filename <> '.'";
356 } else {
357 $sql = "SELECT 'x'
358 FROM {files}
359 WHERE $where AND (filename <> '.' OR filepath <> '/')";
360 }
361
362 return !$DB->record_exists_sql($sql, $params);
363 }
364
67233725
DC
365 /**
366 * Returns all files belonging to given repository
367 *
368 * @param int $repositoryid
9f4789b8 369 * @param string $sort A fragment of SQL to use for sorting
67233725
DC
370 */
371 public function get_external_files($repositoryid, $sort = 'sortorder, itemid, filepath, filename') {
372 global $DB;
3447100c 373 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
374 FROM {files} f
375 LEFT JOIN {files_reference} r
376 ON f.referencefileid = r.id
9f4789b8
SH
377 WHERE r.repositoryid = ?";
378 if (!empty($sort)) {
379 $sql .= " ORDER BY {$sort}";
380 }
67233725
DC
381
382 $result = array();
383 $filerecords = $DB->get_records_sql($sql, array($repositoryid));
384 foreach ($filerecords as $filerecord) {
385 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
386 }
387 return $result;
388 }
389
172dd12c 390 /**
391 * Returns all area files (optionally limited by itemid)
bf9ffe27 392 *
d2b7803e
DC
393 * @param int $contextid context ID
394 * @param string $component component
395 * @param string $filearea file area
396 * @param int $itemid item ID or all files if not specified
9f4789b8 397 * @param string $sort A fragment of SQL to use for sorting
d2b7803e 398 * @param bool $includedirs whether or not include directories
cd5be217 399 * @return array of stored_files indexed by pathanmehash
172dd12c 400 */
9f4789b8 401 public function get_area_files($contextid, $component, $filearea, $itemid = false, $sort = "sortorder, itemid, filepath, filename", $includedirs = true) {
172dd12c 402 global $DB;
403
64f93798 404 $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
172dd12c 405 if ($itemid !== false) {
67233725 406 $itemidsql = ' AND f.itemid = :itemid ';
172dd12c 407 $conditions['itemid'] = $itemid;
67233725
DC
408 } else {
409 $itemidsql = '';
172dd12c 410 }
411
3447100c 412 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
413 FROM {files} f
414 LEFT JOIN {files_reference} r
415 ON f.referencefileid = r.id
416 WHERE f.contextid = :contextid
417 AND f.component = :component
418 AND f.filearea = :filearea
9f4789b8
SH
419 $itemidsql";
420 if (!empty($sort)) {
421 $sql .= " ORDER BY {$sort}";
422 }
67233725 423
172dd12c 424 $result = array();
67233725
DC
425 $filerecords = $DB->get_records_sql($sql, $conditions);
426 foreach ($filerecords as $filerecord) {
427 if (!$includedirs and $filerecord->filename === '.') {
172dd12c 428 continue;
429 }
67233725 430 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
172dd12c 431 }
432 return $result;
433 }
434
752b9f42 435 /**
436 * Returns array based tree structure of area files
bf9ffe27 437 *
d2b7803e
DC
438 * @param int $contextid context ID
439 * @param string $component component
440 * @param string $filearea file area
441 * @param int $itemid item ID
752b9f42 442 * @return array each dir represented by dirname, subdirs, files and dirfile array elements
443 */
64f93798 444 public function get_area_tree($contextid, $component, $filearea, $itemid) {
752b9f42 445 $result = array('dirname'=>'', 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
d3427cfe 446 $files = $this->get_area_files($contextid, $component, $filearea, $itemid, "sortorder, itemid, filepath, filename", true);
752b9f42 447 // first create directory structure
448 foreach ($files as $hash=>$dir) {
449 if (!$dir->is_directory()) {
450 continue;
451 }
452 unset($files[$hash]);
453 if ($dir->get_filepath() === '/') {
454 $result['dirfile'] = $dir;
455 continue;
456 }
457 $parts = explode('/', trim($dir->get_filepath(),'/'));
458 $pointer =& $result;
459 foreach ($parts as $part) {
3b607678 460 if ($part === '') {
461 continue;
462 }
752b9f42 463 if (!isset($pointer['subdirs'][$part])) {
464 $pointer['subdirs'][$part] = array('dirname'=>$part, 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
465 }
466 $pointer =& $pointer['subdirs'][$part];
467 }
468 $pointer['dirfile'] = $dir;
469 unset($pointer);
470 }
471 foreach ($files as $hash=>$file) {
472 $parts = explode('/', trim($file->get_filepath(),'/'));
473 $pointer =& $result;
474 foreach ($parts as $part) {
3b607678 475 if ($part === '') {
476 continue;
477 }
752b9f42 478 $pointer =& $pointer['subdirs'][$part];
479 }
480 $pointer['files'][$file->get_filename()] = $file;
481 unset($pointer);
482 }
483 return $result;
484 }
485
ee03a651 486 /**
bf9ffe27
PS
487 * Returns all files and optionally directories
488 *
d2b7803e
DC
489 * @param int $contextid context ID
490 * @param string $component component
491 * @param string $filearea file area
492 * @param int $itemid item ID
ee03a651 493 * @param int $filepath directory path
494 * @param bool $recursive include all subdirectories
46fcbcf4 495 * @param bool $includedirs include files and directories
9f4789b8 496 * @param string $sort A fragment of SQL to use for sorting
cd5be217 497 * @return array of stored_files indexed by pathanmehash
ee03a651 498 */
64f93798 499 public function get_directory_files($contextid, $component, $filearea, $itemid, $filepath, $recursive = false, $includedirs = true, $sort = "filepath, filename") {
ee03a651 500 global $DB;
501
64f93798 502 if (!$directory = $this->get_file($contextid, $component, $filearea, $itemid, $filepath, '.')) {
ee03a651 503 return array();
504 }
505
9f4789b8
SH
506 $orderby = (!empty($sort)) ? " ORDER BY {$sort}" : '';
507
ee03a651 508 if ($recursive) {
509
46fcbcf4 510 $dirs = $includedirs ? "" : "AND filename <> '.'";
f8311def 511 $length = textlib::strlen($filepath);
ee03a651 512
3447100c 513 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
462c4955
DC
514 FROM {files} f
515 LEFT JOIN {files_reference} r
516 ON f.referencefileid = r.id
517 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
518 AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
519 AND f.id <> :dirid
ee03a651 520 $dirs
9f4789b8 521 $orderby";
64f93798 522 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
ee03a651 523
524 $files = array();
525 $dirs = array();
67233725
DC
526 $filerecords = $DB->get_records_sql($sql, $params);
527 foreach ($filerecords as $filerecord) {
528 if ($filerecord->filename == '.') {
529 $dirs[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
ee03a651 530 } else {
67233725 531 $files[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
ee03a651 532 }
533 }
534 $result = array_merge($dirs, $files);
535
536 } else {
537 $result = array();
64f93798 538 $params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
ee03a651 539
f8311def 540 $length = textlib::strlen($filepath);
ee03a651 541
46fcbcf4 542 if ($includedirs) {
3447100c 543 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
462c4955
DC
544 FROM {files} f
545 LEFT JOIN {files_reference} r
546 ON f.referencefileid = r.id
547 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea
548 AND f.itemid = :itemid AND f.filename = '.'
549 AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
550 AND f.id <> :dirid
9f4789b8 551 $orderby";
ee03a651 552 $reqlevel = substr_count($filepath, '/') + 1;
67233725
DC
553 $filerecords = $DB->get_records_sql($sql, $params);
554 foreach ($filerecords as $filerecord) {
555 if (substr_count($filerecord->filepath, '/') !== $reqlevel) {
ee03a651 556 continue;
557 }
67233725 558 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
ee03a651 559 }
560 }
561
3447100c 562 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
462c4955
DC
563 FROM {files} f
564 LEFT JOIN {files_reference} r
565 ON f.referencefileid = r.id
566 WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
567 AND f.filepath = :filepath AND f.filename <> '.'
9f4789b8 568 $orderby";
ee03a651 569
67233725
DC
570 $filerecords = $DB->get_records_sql($sql, $params);
571 foreach ($filerecords as $filerecord) {
572 $result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
ee03a651 573 }
574 }
575
576 return $result;
577 }
578
172dd12c 579 /**
bf9ffe27
PS
580 * Delete all area files (optionally limited by itemid).
581 *
d2b7803e
DC
582 * @param int $contextid context ID
583 * @param string $component component
584 * @param string $filearea file area or all areas in context if not specified
585 * @param int $itemid item ID or all files if not specified
bf9ffe27 586 * @return bool success
172dd12c 587 */
64f93798 588 public function delete_area_files($contextid, $component = false, $filearea = false, $itemid = false) {
172dd12c 589 global $DB;
590
6311eb61 591 $conditions = array('contextid'=>$contextid);
64f93798
PS
592 if ($component !== false) {
593 $conditions['component'] = $component;
594 }
6311eb61 595 if ($filearea !== false) {
596 $conditions['filearea'] = $filearea;
597 }
172dd12c 598 if ($itemid !== false) {
599 $conditions['itemid'] = $itemid;
600 }
601
67233725
DC
602 $filerecords = $DB->get_records('files', $conditions);
603 foreach ($filerecords as $filerecord) {
604 $this->get_file_instance($filerecord)->delete();
172dd12c 605 }
606
bf9ffe27 607 return true; // BC only
172dd12c 608 }
609
af7b3673
TH
610 /**
611 * Delete all the files from certain areas where itemid is limited by an
612 * arbitrary bit of SQL.
613 *
614 * @param int $contextid the id of the context the files belong to. Must be given.
615 * @param string $component the owning component. Must be given.
616 * @param string $filearea the file area name. Must be given.
617 * @param string $itemidstest an SQL fragment that the itemid must match. Used
618 * in the query like WHERE itemid $itemidstest. Must used named parameters,
619 * and may not used named parameters called contextid, component or filearea.
620 * @param array $params any query params used by $itemidstest.
621 */
622 public function delete_area_files_select($contextid, $component,
623 $filearea, $itemidstest, array $params = null) {
624 global $DB;
625
626 $where = "contextid = :contextid
627 AND component = :component
628 AND filearea = :filearea
629 AND itemid $itemidstest";
630 $params['contextid'] = $contextid;
631 $params['component'] = $component;
632 $params['filearea'] = $filearea;
633
67233725
DC
634 $filerecords = $DB->get_recordset_select('files', $where, $params);
635 foreach ($filerecords as $filerecord) {
636 $this->get_file_instance($filerecord)->delete();
af7b3673 637 }
67233725 638 $filerecords->close();
af7b3673
TH
639 }
640
d2af1014
TH
641 /**
642 * Move all the files in a file area from one context to another.
d2b7803e
DC
643 *
644 * @param int $oldcontextid the context the files are being moved from.
645 * @param int $newcontextid the context the files are being moved to.
d2af1014
TH
646 * @param string $component the plugin that these files belong to.
647 * @param string $filearea the name of the file area.
d2b7803e
DC
648 * @param int $itemid file item ID
649 * @return int the number of files moved, for information.
d2af1014
TH
650 */
651 public function move_area_files_to_new_context($oldcontextid, $newcontextid, $component, $filearea, $itemid = false) {
652 // Note, this code is based on some code that Petr wrote in
653 // forum_move_attachments in mod/forum/lib.php. I moved it here because
654 // I needed it in the question code too.
655 $count = 0;
656
657 $oldfiles = $this->get_area_files($oldcontextid, $component, $filearea, $itemid, 'id', false);
658 foreach ($oldfiles as $oldfile) {
659 $filerecord = new stdClass();
660 $filerecord->contextid = $newcontextid;
661 $this->create_file_from_storedfile($filerecord, $oldfile);
662 $count += 1;
663 }
664
665 if ($count) {
666 $this->delete_area_files($oldcontextid, $component, $filearea, $itemid);
667 }
668
669 return $count;
670 }
671
172dd12c 672 /**
bf9ffe27
PS
673 * Recursively creates directory.
674 *
d2b7803e
DC
675 * @param int $contextid context ID
676 * @param string $component component
677 * @param string $filearea file area
678 * @param int $itemid item ID
679 * @param string $filepath file path
680 * @param int $userid the user ID
172dd12c 681 * @return bool success
682 */
64f93798 683 public function create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid = null) {
172dd12c 684 global $DB;
685
686 // validate all parameters, we do not want any rubbish stored in database, right?
687 if (!is_number($contextid) or $contextid < 1) {
145a0a31 688 throw new file_exception('storedfileproblem', 'Invalid contextid');
172dd12c 689 }
690
aff24313
PS
691 $component = clean_param($component, PARAM_COMPONENT);
692 if (empty($component)) {
64f93798
PS
693 throw new file_exception('storedfileproblem', 'Invalid component');
694 }
695
aff24313
PS
696 $filearea = clean_param($filearea, PARAM_AREA);
697 if (empty($filearea)) {
145a0a31 698 throw new file_exception('storedfileproblem', 'Invalid filearea');
172dd12c 699 }
700
701 if (!is_number($itemid) or $itemid < 0) {
145a0a31 702 throw new file_exception('storedfileproblem', 'Invalid itemid');
172dd12c 703 }
704
705 $filepath = clean_param($filepath, PARAM_PATH);
706 if (strpos($filepath, '/') !== 0 or strrpos($filepath, '/') !== strlen($filepath)-1) {
707 // path must start and end with '/'
145a0a31 708 throw new file_exception('storedfileproblem', 'Invalid file path');
172dd12c 709 }
710
64f93798 711 $pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, '.');
172dd12c 712
713 if ($dir_info = $this->get_file_by_hash($pathnamehash)) {
714 return $dir_info;
715 }
716
717 static $contenthash = null;
718 if (!$contenthash) {
b48f3e06 719 $this->add_string_to_pool('');
172dd12c 720 $contenthash = sha1('');
721 }
722
723 $now = time();
724
ac6f1a82 725 $dir_record = new stdClass();
172dd12c 726 $dir_record->contextid = $contextid;
64f93798 727 $dir_record->component = $component;
172dd12c 728 $dir_record->filearea = $filearea;
729 $dir_record->itemid = $itemid;
730 $dir_record->filepath = $filepath;
731 $dir_record->filename = '.';
732 $dir_record->contenthash = $contenthash;
733 $dir_record->filesize = 0;
734
735 $dir_record->timecreated = $now;
736 $dir_record->timemodified = $now;
737 $dir_record->mimetype = null;
738 $dir_record->userid = $userid;
739
740 $dir_record->pathnamehash = $pathnamehash;
741
742 $DB->insert_record('files', $dir_record);
743 $dir_info = $this->get_file_by_hash($pathnamehash);
744
745 if ($filepath !== '/') {
746 //recurse to parent dirs
747 $filepath = trim($filepath, '/');
748 $filepath = explode('/', $filepath);
749 array_pop($filepath);
750 $filepath = implode('/', $filepath);
751 $filepath = ($filepath === '') ? '/' : "/$filepath/";
64f93798 752 $this->create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid);
172dd12c 753 }
754
755 return $dir_info;
756 }
757
758 /**
bf9ffe27
PS
759 * Add new local file based on existing local file.
760 *
67233725 761 * @param stdClass|array $filerecord object or array describing changes
d2b7803e 762 * @param stored_file|int $fileorid id or stored_file instance of the existing local file
bf9ffe27 763 * @return stored_file instance of newly created file
172dd12c 764 */
67233725 765 public function create_file_from_storedfile($filerecord, $fileorid) {
4fb2306e 766 global $DB;
172dd12c 767
72d0aed6 768 if ($fileorid instanceof stored_file) {
769 $fid = $fileorid->get_id();
770 } else {
771 $fid = $fileorid;
8eb1e0a1 772 }
773
67233725 774 $filerecord = (array)$filerecord; // We support arrays too, do not modify the submitted record!
ec8b711f 775
67233725
DC
776 unset($filerecord['id']);
777 unset($filerecord['filesize']);
778 unset($filerecord['contenthash']);
779 unset($filerecord['pathnamehash']);
172dd12c 780
3447100c 781 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
782 FROM {files} f
783 LEFT JOIN {files_reference} r
784 ON f.referencefileid = r.id
785 WHERE f.id = ?";
786
787 if (!$newrecord = $DB->get_record_sql($sql, array($fid))) {
145a0a31 788 throw new file_exception('storedfileproblem', 'File does not exist');
172dd12c 789 }
790
791 unset($newrecord->id);
792
67233725 793 foreach ($filerecord as $key => $value) {
172dd12c 794 // validate all parameters, we do not want any rubbish stored in database, right?
795 if ($key == 'contextid' and (!is_number($value) or $value < 1)) {
145a0a31 796 throw new file_exception('storedfileproblem', 'Invalid contextid');
172dd12c 797 }
798
64f93798 799 if ($key == 'component') {
aff24313
PS
800 $value = clean_param($value, PARAM_COMPONENT);
801 if (empty($value)) {
64f93798
PS
802 throw new file_exception('storedfileproblem', 'Invalid component');
803 }
804 }
805
172dd12c 806 if ($key == 'filearea') {
aff24313
PS
807 $value = clean_param($value, PARAM_AREA);
808 if (empty($value)) {
145a0a31 809 throw new file_exception('storedfileproblem', 'Invalid filearea');
172dd12c 810 }
811 }
812
813 if ($key == 'itemid' and (!is_number($value) or $value < 0)) {
145a0a31 814 throw new file_exception('storedfileproblem', 'Invalid itemid');
172dd12c 815 }
816
817
818 if ($key == 'filepath') {
819 $value = clean_param($value, PARAM_PATH);
00c32c54 820 if (strpos($value, '/') !== 0 or strrpos($value, '/') !== strlen($value)-1) {
172dd12c 821 // path must start and end with '/'
145a0a31 822 throw new file_exception('storedfileproblem', 'Invalid file path');
172dd12c 823 }
824 }
825
826 if ($key == 'filename') {
827 $value = clean_param($value, PARAM_FILE);
828 if ($value === '') {
829 // path must start and end with '/'
145a0a31 830 throw new file_exception('storedfileproblem', 'Invalid file name');
172dd12c 831 }
832 }
833
260c4a5b
PS
834 if ($key === 'timecreated' or $key === 'timemodified') {
835 if (!is_number($value)) {
836 throw new file_exception('storedfileproblem', 'Invalid file '.$key);
837 }
838 if ($value < 0) {
839 //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)
840 $value = 0;
841 }
842 }
843
67233725
DC
844 if ($key == 'referencefileid' or $key == 'referencelastsync' or $key == 'referencelifetime') {
845 $value = clean_param($value, PARAM_INT);
846 }
847
172dd12c 848 $newrecord->$key = $value;
849 }
850
64f93798 851 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
172dd12c 852
cd5be217 853 if ($newrecord->filename === '.') {
854 // special case - only this function supports directories ;-)
64f93798 855 $directory = $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
cd5be217 856 // update the existing directory with the new data
857 $newrecord->id = $directory->get_id();
b8ac7ece 858 $DB->update_record('files', $newrecord);
693ef3a8 859 return $this->get_file_instance($newrecord);
cd5be217 860 }
861
67233725
DC
862 if (!empty($newrecord->repositoryid)) {
863 try {
864 $referencerecord = new stdClass;
865 $referencerecord->repositoryid = $newrecord->repositoryid;
866 $referencerecord->reference = $newrecord->reference;
867 $referencerecord->lastsync = $newrecord->referencelastsync;
868 $referencerecord->lifetime = $newrecord->referencelifetime;
869 $referencerecord->id = $DB->insert_record('files_reference', $referencerecord);
870 } catch (dml_exception $e) {
871 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
872 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
873 }
874 $newrecord->referencefileid = $referencerecord->id;
875 }
876
172dd12c 877 try {
878 $newrecord->id = $DB->insert_record('files', $newrecord);
8a680500 879 } catch (dml_exception $e) {
64f93798 880 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
694f3b74 881 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
172dd12c 882 }
883
67233725 884
64f93798 885 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
172dd12c 886
693ef3a8 887 return $this->get_file_instance($newrecord);
172dd12c 888 }
889
6e73ac42 890 /**
bf9ffe27
PS
891 * Add new local file.
892 *
67233725 893 * @param stdClass|array $filerecord object or array describing file
d2b7803e
DC
894 * @param string $url the URL to the file
895 * @param array $options {@link download_file_content()} options
3a1055a5 896 * @param bool $usetempfile use temporary file for download, may prevent out of memory problems
d2b7803e 897 * @return stored_file
6e73ac42 898 */
67233725 899 public function create_file_from_url($filerecord, $url, array $options = null, $usetempfile = false) {
ec8b711f 900
67233725
DC
901 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
902 $filerecord = (object)$filerecord; // We support arrays too.
6e73ac42 903
904 $headers = isset($options['headers']) ? $options['headers'] : null;
905 $postdata = isset($options['postdata']) ? $options['postdata'] : null;
906 $fullresponse = isset($options['fullresponse']) ? $options['fullresponse'] : false;
907 $timeout = isset($options['timeout']) ? $options['timeout'] : 300;
908 $connecttimeout = isset($options['connecttimeout']) ? $options['connecttimeout'] : 20;
909 $skipcertverify = isset($options['skipcertverify']) ? $options['skipcertverify'] : false;
5f1c825d 910 $calctimeout = isset($options['calctimeout']) ? $options['calctimeout'] : false;
6e73ac42 911
67233725 912 if (!isset($filerecord->filename)) {
6e73ac42 913 $parts = explode('/', $url);
914 $filename = array_pop($parts);
67233725 915 $filerecord->filename = clean_param($filename, PARAM_FILE);
6e73ac42 916 }
67233725
DC
917 $source = !empty($filerecord->source) ? $filerecord->source : $url;
918 $filerecord->source = clean_param($source, PARAM_URL);
6e73ac42 919
3a1055a5 920 if ($usetempfile) {
c426ef3a 921 check_dir_exists($this->tempdir);
3a1055a5 922 $tmpfile = tempnam($this->tempdir, 'newfromurl');
60b5a2fe 923 $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, $tmpfile, $calctimeout);
3a1055a5
PS
924 if ($content === false) {
925 throw new file_exception('storedfileproblem', 'Can not fetch file form URL');
926 }
927 try {
67233725 928 $newfile = $this->create_file_from_pathname($filerecord, $tmpfile);
3a1055a5
PS
929 @unlink($tmpfile);
930 return $newfile;
931 } catch (Exception $e) {
932 @unlink($tmpfile);
933 throw $e;
934 }
935
936 } else {
60b5a2fe 937 $content = download_file_content($url, $headers, $postdata, $fullresponse, $timeout, $connecttimeout, $skipcertverify, NULL, $calctimeout);
3a1055a5
PS
938 if ($content === false) {
939 throw new file_exception('storedfileproblem', 'Can not fetch file form URL');
940 }
67233725 941 return $this->create_file_from_string($filerecord, $content);
3a1055a5 942 }
6e73ac42 943 }
944
172dd12c 945 /**
bf9ffe27
PS
946 * Add new local file.
947 *
67233725 948 * @param stdClass|array $filerecord object or array describing file
d2b7803e
DC
949 * @param string $pathname path to file or content of file
950 * @return stored_file
172dd12c 951 */
67233725 952 public function create_file_from_pathname($filerecord, $pathname) {
4fb2306e 953 global $DB;
172dd12c 954
67233725
DC
955 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
956 $filerecord = (object)$filerecord; // We support arrays too.
172dd12c 957
958 // validate all parameters, we do not want any rubbish stored in database, right?
67233725 959 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
145a0a31 960 throw new file_exception('storedfileproblem', 'Invalid contextid');
172dd12c 961 }
962
67233725
DC
963 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
964 if (empty($filerecord->component)) {
64f93798
PS
965 throw new file_exception('storedfileproblem', 'Invalid component');
966 }
967
67233725
DC
968 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
969 if (empty($filerecord->filearea)) {
145a0a31 970 throw new file_exception('storedfileproblem', 'Invalid filearea');
172dd12c 971 }
972
67233725 973 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
145a0a31 974 throw new file_exception('storedfileproblem', 'Invalid itemid');
172dd12c 975 }
976
67233725
DC
977 if (!empty($filerecord->sortorder)) {
978 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
979 $filerecord->sortorder = 0;
f79321f1
DC
980 }
981 } else {
67233725 982 $filerecord->sortorder = 0;
f79321f1
DC
983 }
984
67233725
DC
985 $filerecord->referencefileid = !isset($filerecord->referencefileid) ? 0 : $filerecord->referencefileid;
986 $filerecord->referencelastsync = !isset($filerecord->referencelastsync) ? 0 : $filerecord->referencelastsync;
987 $filerecord->referencelifetime = !isset($filerecord->referencelifetime) ? 0 : $filerecord->referencelifetime;
988
989 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
990 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
172dd12c 991 // path must start and end with '/'
145a0a31 992 throw new file_exception('storedfileproblem', 'Invalid file path');
172dd12c 993 }
994
67233725
DC
995 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
996 if ($filerecord->filename === '') {
e1dcb950 997 // filename must not be empty
145a0a31 998 throw new file_exception('storedfileproblem', 'Invalid file name');
172dd12c 999 }
1000
1001 $now = time();
67233725
DC
1002 if (isset($filerecord->timecreated)) {
1003 if (!is_number($filerecord->timecreated)) {
260c4a5b
PS
1004 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1005 }
67233725 1006 if ($filerecord->timecreated < 0) {
260c4a5b 1007 //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)
67233725 1008 $filerecord->timecreated = 0;
260c4a5b
PS
1009 }
1010 } else {
67233725 1011 $filerecord->timecreated = $now;
260c4a5b
PS
1012 }
1013
67233725
DC
1014 if (isset($filerecord->timemodified)) {
1015 if (!is_number($filerecord->timemodified)) {
260c4a5b
PS
1016 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1017 }
67233725 1018 if ($filerecord->timemodified < 0) {
260c4a5b 1019 //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)
67233725 1020 $filerecord->timemodified = 0;
260c4a5b
PS
1021 }
1022 } else {
67233725 1023 $filerecord->timemodified = $now;
260c4a5b 1024 }
172dd12c 1025
ac6f1a82 1026 $newrecord = new stdClass();
172dd12c 1027
67233725
DC
1028 $newrecord->contextid = $filerecord->contextid;
1029 $newrecord->component = $filerecord->component;
1030 $newrecord->filearea = $filerecord->filearea;
1031 $newrecord->itemid = $filerecord->itemid;
1032 $newrecord->filepath = $filerecord->filepath;
1033 $newrecord->filename = $filerecord->filename;
1034
1035 $newrecord->timecreated = $filerecord->timecreated;
1036 $newrecord->timemodified = $filerecord->timemodified;
4c2fcbfc 1037 $newrecord->mimetype = empty($filerecord->mimetype) ? $this->mimetype($pathname, $filerecord->filename) : $filerecord->mimetype;
67233725
DC
1038 $newrecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1039 $newrecord->source = empty($filerecord->source) ? null : $filerecord->source;
1040 $newrecord->author = empty($filerecord->author) ? null : $filerecord->author;
1041 $newrecord->license = empty($filerecord->license) ? null : $filerecord->license;
1042 $newrecord->sortorder = $filerecord->sortorder;
172dd12c 1043
b48f3e06 1044 list($newrecord->contenthash, $newrecord->filesize, $newfile) = $this->add_file_to_pool($pathname);
172dd12c 1045
64f93798 1046 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
172dd12c 1047
1048 try {
1049 $newrecord->id = $DB->insert_record('files', $newrecord);
8a680500 1050 } catch (dml_exception $e) {
172dd12c 1051 if ($newfile) {
ead14290 1052 $this->deleted_file_cleanup($newrecord->contenthash);
172dd12c 1053 }
64f93798 1054 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
694f3b74 1055 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
172dd12c 1056 }
1057
64f93798 1058 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
172dd12c 1059
693ef3a8 1060 return $this->get_file_instance($newrecord);
172dd12c 1061 }
1062
1063 /**
bf9ffe27
PS
1064 * Add new local file.
1065 *
67233725 1066 * @param stdClass|array $filerecord object or array describing file
172dd12c 1067 * @param string $content content of file
d2b7803e 1068 * @return stored_file
172dd12c 1069 */
67233725 1070 public function create_file_from_string($filerecord, $content) {
4fb2306e 1071 global $DB;
172dd12c 1072
67233725
DC
1073 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1074 $filerecord = (object)$filerecord; // We support arrays too.
172dd12c 1075
1076 // validate all parameters, we do not want any rubbish stored in database, right?
67233725 1077 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
145a0a31 1078 throw new file_exception('storedfileproblem', 'Invalid contextid');
172dd12c 1079 }
1080
67233725
DC
1081 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
1082 if (empty($filerecord->component)) {
64f93798
PS
1083 throw new file_exception('storedfileproblem', 'Invalid component');
1084 }
1085
67233725
DC
1086 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
1087 if (empty($filerecord->filearea)) {
145a0a31 1088 throw new file_exception('storedfileproblem', 'Invalid filearea');
172dd12c 1089 }
1090
67233725 1091 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
145a0a31 1092 throw new file_exception('storedfileproblem', 'Invalid itemid');
172dd12c 1093 }
1094
67233725
DC
1095 if (!empty($filerecord->sortorder)) {
1096 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
1097 $filerecord->sortorder = 0;
f79321f1
DC
1098 }
1099 } else {
67233725 1100 $filerecord->sortorder = 0;
f79321f1 1101 }
67233725
DC
1102 $filerecord->referencefileid = !isset($filerecord->referencefileid) ? 0 : $filerecord->referencefileid;
1103 $filerecord->referencelastsync = !isset($filerecord->referencelastsync) ? 0 : $filerecord->referencelastsync;
1104 $filerecord->referencelifetime = !isset($filerecord->referencelifetime) ? 0 : $filerecord->referencelifetime;
f79321f1 1105
67233725
DC
1106 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
1107 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
172dd12c 1108 // path must start and end with '/'
145a0a31 1109 throw new file_exception('storedfileproblem', 'Invalid file path');
172dd12c 1110 }
1111
67233725
DC
1112 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
1113 if ($filerecord->filename === '') {
172dd12c 1114 // path must start and end with '/'
145a0a31 1115 throw new file_exception('storedfileproblem', 'Invalid file name');
172dd12c 1116 }
1117
1118 $now = time();
67233725
DC
1119 if (isset($filerecord->timecreated)) {
1120 if (!is_number($filerecord->timecreated)) {
260c4a5b
PS
1121 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1122 }
67233725 1123 if ($filerecord->timecreated < 0) {
260c4a5b 1124 //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)
67233725 1125 $filerecord->timecreated = 0;
260c4a5b
PS
1126 }
1127 } else {
67233725 1128 $filerecord->timecreated = $now;
260c4a5b
PS
1129 }
1130
67233725
DC
1131 if (isset($filerecord->timemodified)) {
1132 if (!is_number($filerecord->timemodified)) {
260c4a5b
PS
1133 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1134 }
67233725 1135 if ($filerecord->timemodified < 0) {
260c4a5b 1136 //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)
67233725 1137 $filerecord->timemodified = 0;
260c4a5b
PS
1138 }
1139 } else {
67233725 1140 $filerecord->timemodified = $now;
260c4a5b 1141 }
172dd12c 1142
ac6f1a82 1143 $newrecord = new stdClass();
172dd12c 1144
67233725
DC
1145 $newrecord->contextid = $filerecord->contextid;
1146 $newrecord->component = $filerecord->component;
1147 $newrecord->filearea = $filerecord->filearea;
1148 $newrecord->itemid = $filerecord->itemid;
1149 $newrecord->filepath = $filerecord->filepath;
1150 $newrecord->filename = $filerecord->filename;
1151
1152 $newrecord->timecreated = $filerecord->timecreated;
1153 $newrecord->timemodified = $filerecord->timemodified;
67233725
DC
1154 $newrecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1155 $newrecord->source = empty($filerecord->source) ? null : $filerecord->source;
1156 $newrecord->author = empty($filerecord->author) ? null : $filerecord->author;
1157 $newrecord->license = empty($filerecord->license) ? null : $filerecord->license;
1158 $newrecord->sortorder = $filerecord->sortorder;
1dce6261 1159
b48f3e06 1160 list($newrecord->contenthash, $newrecord->filesize, $newfile) = $this->add_string_to_pool($content);
8177b7b9
DC
1161 $filepathname = $this->path_from_hash($newrecord->contenthash) . '/' . $newrecord->contenthash;
1162 // get mimetype by magic bytes
4c2fcbfc 1163 $newrecord->mimetype = empty($filerecord->mimetype) ? $this->mimetype($filepathname, $filerecord->filename) : $filerecord->mimetype;
172dd12c 1164
64f93798 1165 $newrecord->pathnamehash = $this->get_pathname_hash($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->filename);
172dd12c 1166
1167 try {
1168 $newrecord->id = $DB->insert_record('files', $newrecord);
8a680500 1169 } catch (dml_exception $e) {
172dd12c 1170 if ($newfile) {
ead14290 1171 $this->deleted_file_cleanup($newrecord->contenthash);
172dd12c 1172 }
64f93798 1173 throw new stored_file_creation_exception($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid,
694f3b74 1174 $newrecord->filepath, $newrecord->filename, $e->debuginfo);
172dd12c 1175 }
1176
64f93798 1177 $this->create_directory($newrecord->contextid, $newrecord->component, $newrecord->filearea, $newrecord->itemid, $newrecord->filepath, $newrecord->userid);
172dd12c 1178
693ef3a8 1179 return $this->get_file_instance($newrecord);
172dd12c 1180 }
1181
67233725
DC
1182 /**
1183 * Create a moodle file from file reference information
1184 *
1185 * @param stdClass $filerecord
1186 * @param int $repositoryid
1187 * @param string $reference
1188 * @param array $options options for creating external file
1189 * @return stored_file
1190 */
1191 public function create_file_from_reference($filerecord, $repositoryid, $reference, $options = array()) {
1192 global $DB;
1193
1194 $filerecord = (array)$filerecord; // Do not modify the submitted record, this cast unlinks objects.
1195 $filerecord = (object)$filerecord; // We support arrays too.
1196
1197 // validate all parameters, we do not want any rubbish stored in database, right?
1198 if (!is_number($filerecord->contextid) or $filerecord->contextid < 1) {
1199 throw new file_exception('storedfileproblem', 'Invalid contextid');
1200 }
1201
1202 $filerecord->component = clean_param($filerecord->component, PARAM_COMPONENT);
1203 if (empty($filerecord->component)) {
1204 throw new file_exception('storedfileproblem', 'Invalid component');
1205 }
1206
1207 $filerecord->filearea = clean_param($filerecord->filearea, PARAM_AREA);
1208 if (empty($filerecord->filearea)) {
1209 throw new file_exception('storedfileproblem', 'Invalid filearea');
1210 }
1211
1212 if (!is_number($filerecord->itemid) or $filerecord->itemid < 0) {
1213 throw new file_exception('storedfileproblem', 'Invalid itemid');
1214 }
1215
1216 if (!empty($filerecord->sortorder)) {
1217 if (!is_number($filerecord->sortorder) or $filerecord->sortorder < 0) {
1218 $filerecord->sortorder = 0;
1219 }
1220 } else {
1221 $filerecord->sortorder = 0;
1222 }
1223
1224 $filerecord->referencefileid = empty($filerecord->referencefileid) ? 0 : $filerecord->referencefileid;
1225 $filerecord->referencelastsync = empty($filerecord->referencelastsync) ? 0 : $filerecord->referencelastsync;
1226 $filerecord->referencelifetime = empty($filerecord->referencelifetime) ? 0 : $filerecord->referencelifetime;
8177b7b9 1227 $filerecord->mimetype = empty($filerecord->mimetype) ? $this->mimetype($filerecord->filename) : $filerecord->mimetype;
67233725
DC
1228 $filerecord->userid = empty($filerecord->userid) ? null : $filerecord->userid;
1229 $filerecord->source = empty($filerecord->source) ? null : $filerecord->source;
1230 $filerecord->author = empty($filerecord->author) ? null : $filerecord->author;
1231 $filerecord->license = empty($filerecord->license) ? null : $filerecord->license;
1232 $filerecord->filepath = clean_param($filerecord->filepath, PARAM_PATH);
1233 if (strpos($filerecord->filepath, '/') !== 0 or strrpos($filerecord->filepath, '/') !== strlen($filerecord->filepath)-1) {
1234 // Path must start and end with '/'.
1235 throw new file_exception('storedfileproblem', 'Invalid file path');
1236 }
1237
1238 $filerecord->filename = clean_param($filerecord->filename, PARAM_FILE);
1239 if ($filerecord->filename === '') {
1240 // Path must start and end with '/'.
1241 throw new file_exception('storedfileproblem', 'Invalid file name');
1242 }
1243
1244 $now = time();
1245 if (isset($filerecord->timecreated)) {
1246 if (!is_number($filerecord->timecreated)) {
1247 throw new file_exception('storedfileproblem', 'Invalid file timecreated');
1248 }
1249 if ($filerecord->timecreated < 0) {
1250 // 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)
1251 $filerecord->timecreated = 0;
1252 }
1253 } else {
1254 $filerecord->timecreated = $now;
1255 }
1256
1257 if (isset($filerecord->timemodified)) {
1258 if (!is_number($filerecord->timemodified)) {
1259 throw new file_exception('storedfileproblem', 'Invalid file timemodified');
1260 }
1261 if ($filerecord->timemodified < 0) {
1262 // 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)
1263 $filerecord->timemodified = 0;
1264 }
1265 } else {
1266 $filerecord->timemodified = $now;
1267 }
1268
e3c02118
DC
1269 $transaction = $DB->start_delegated_transaction();
1270
67233725
DC
1271 // Insert file reference record.
1272 try {
1273 $referencerecord = new stdClass;
1274 $referencerecord->repositoryid = $repositoryid;
1275 $referencerecord->reference = $reference;
1276 $referencerecord->lastsync = $filerecord->referencelastsync;
1277 $referencerecord->lifetime = $filerecord->referencelifetime;
1278 $referencerecord->id = $DB->insert_record('files_reference', $referencerecord);
1279 } catch (dml_exception $e) {
1280 throw $e;
1281 }
1282
1283 $filerecord->referencefileid = $referencerecord->id;
1284
1285 // External file doesn't have content in moodle.
1286 // So we create an empty file for it.
1287 list($filerecord->contenthash, $filerecord->filesize, $newfile) = $this->add_string_to_pool(null);
1288
1289 $filerecord->pathnamehash = $this->get_pathname_hash($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid, $filerecord->filepath, $filerecord->filename);
1290
1291 try {
1292 $filerecord->id = $DB->insert_record('files', $filerecord);
1293 } catch (dml_exception $e) {
1294 if ($newfile) {
1295 $this->deleted_file_cleanup($filerecord->contenthash);
1296 }
1297 throw new stored_file_creation_exception($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid,
1298 $filerecord->filepath, $filerecord->filename, $e->debuginfo);
1299 }
1300
1301 $this->create_directory($filerecord->contextid, $filerecord->component, $filerecord->filearea, $filerecord->itemid, $filerecord->filepath, $filerecord->userid);
1302
e3c02118
DC
1303 $transaction->allow_commit();
1304
67233725
DC
1305 // Adding repositoryid and reference to file record to create stored_file instance
1306 $filerecord->repositoryid = $repositoryid;
1307 $filerecord->reference = $reference;
1308 return $this->get_file_instance($filerecord);
1309 }
1310
797f19e8 1311 /**
1312 * Creates new image file from existing.
bf9ffe27 1313 *
67233725 1314 * @param stdClass|array $filerecord object or array describing new file
d2b7803e 1315 * @param int|stored_file $fid file id or stored file object
797f19e8 1316 * @param int $newwidth in pixels
1317 * @param int $newheight in pixels
d2b7803e 1318 * @param bool $keepaspectratio whether or not keep aspect ratio
bf9ffe27 1319 * @param int $quality depending on image type 0-100 for jpeg, 0-9 (0 means no compression) for png
d2b7803e 1320 * @return stored_file
797f19e8 1321 */
67233725 1322 public function convert_image($filerecord, $fid, $newwidth = null, $newheight = null, $keepaspectratio = true, $quality = null) {
6b2f2184
AD
1323 if (!function_exists('imagecreatefromstring')) {
1324 //Most likely the GD php extension isn't installed
1325 //image conversion cannot succeed
1326 throw new file_exception('storedfileproblem', 'imagecreatefromstring() doesnt exist. The PHP extension "GD" must be installed for image conversion.');
1327 }
1328
797f19e8 1329 if ($fid instanceof stored_file) {
1330 $fid = $fid->get_id();
1331 }
1332
67233725 1333 $filerecord = (array)$filerecord; // We support arrays too, do not modify the submitted record!
797f19e8 1334
67233725 1335 if (!$file = $this->get_file_by_id($fid)) { // Make sure file really exists and we we correct data.
797f19e8 1336 throw new file_exception('storedfileproblem', 'File does not exist');
1337 }
1338
1339 if (!$imageinfo = $file->get_imageinfo()) {
1340 throw new file_exception('storedfileproblem', 'File is not an image');
1341 }
1342
67233725
DC
1343 if (!isset($filerecord['filename'])) {
1344 $filerecord['filename'] = $file->get_filename();
797f19e8 1345 }
1346
67233725 1347 if (!isset($filerecord['mimetype'])) {
8177b7b9 1348 $filerecord['mimetype'] = $imageinfo['mimetype'];
797f19e8 1349 }
1350
1351 $width = $imageinfo['width'];
1352 $height = $imageinfo['height'];
1353 $mimetype = $imageinfo['mimetype'];
1354
1355 if ($keepaspectratio) {
1356 if (0 >= $newwidth and 0 >= $newheight) {
1357 // no sizes specified
1358 $newwidth = $width;
1359 $newheight = $height;
1360
1361 } else if (0 < $newwidth and 0 < $newheight) {
1362 $xheight = ($newwidth*($height/$width));
1363 if ($xheight < $newheight) {
1364 $newheight = (int)$xheight;
1365 } else {
1366 $newwidth = (int)($newheight*($width/$height));
1367 }
1368
1369 } else if (0 < $newwidth) {
1370 $newheight = (int)($newwidth*($height/$width));
1371
1372 } else { //0 < $newheight
1373 $newwidth = (int)($newheight*($width/$height));
1374 }
1375
1376 } else {
1377 if (0 >= $newwidth) {
1378 $newwidth = $width;
1379 }
1380 if (0 >= $newheight) {
1381 $newheight = $height;
1382 }
1383 }
1384
1385 $img = imagecreatefromstring($file->get_content());
1386 if ($height != $newheight or $width != $newwidth) {
1387 $newimg = imagecreatetruecolor($newwidth, $newheight);
1388 if (!imagecopyresized($newimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height)) {
1389 // weird
1390 throw new file_exception('storedfileproblem', 'Can not resize image');
1391 }
1392 imagedestroy($img);
1393 $img = $newimg;
1394 }
1395
1396 ob_start();
67233725 1397 switch ($filerecord['mimetype']) {
797f19e8 1398 case 'image/gif':
1399 imagegif($img);
1400 break;
1401
1402 case 'image/jpeg':
1403 if (is_null($quality)) {
1404 imagejpeg($img);
1405 } else {
1406 imagejpeg($img, NULL, $quality);
1407 }
1408 break;
1409
1410 case 'image/png':
8bd49ec0 1411 $quality = (int)$quality;
797f19e8 1412 imagepng($img, NULL, $quality, NULL);
1413 break;
1414
1415 default:
1416 throw new file_exception('storedfileproblem', 'Unsupported mime type');
1417 }
1418
1419 $content = ob_get_contents();
1420 ob_end_clean();
1421 imagedestroy($img);
1422
1423 if (!$content) {
1424 throw new file_exception('storedfileproblem', 'Can not convert image');
1425 }
1426
67233725 1427 return $this->create_file_from_string($filerecord, $content);
797f19e8 1428 }
1429
172dd12c 1430 /**
bf9ffe27
PS
1431 * Add file content to sha1 pool.
1432 *
172dd12c 1433 * @param string $pathname path to file
bf9ffe27
PS
1434 * @param string $contenthash sha1 hash of content if known (performance only)
1435 * @return array (contenthash, filesize, newfile)
172dd12c 1436 */
bf9ffe27 1437 public function add_file_to_pool($pathname, $contenthash = NULL) {
172dd12c 1438 if (!is_readable($pathname)) {
d610cb89 1439 throw new file_exception('storedfilecannotread', '', $pathname);
172dd12c 1440 }
1441
1442 if (is_null($contenthash)) {
1443 $contenthash = sha1_file($pathname);
1444 }
1445
1446 $filesize = filesize($pathname);
1447
1448 $hashpath = $this->path_from_hash($contenthash);
1449 $hashfile = "$hashpath/$contenthash";
1450
1451 if (file_exists($hashfile)) {
1452 if (filesize($hashfile) !== $filesize) {
1453 throw new file_pool_content_exception($contenthash);
1454 }
1455 $newfile = false;
1456
1457 } else {
1aa01caf 1458 if (!is_dir($hashpath)) {
1459 if (!mkdir($hashpath, $this->dirpermissions, true)) {
1460 throw new file_exception('storedfilecannotcreatefiledirs'); // permission trouble
1461 }
172dd12c 1462 }
1463 $newfile = true;
1464
6c0e2d08 1465 if (!copy($pathname, $hashfile)) {
d610cb89 1466 throw new file_exception('storedfilecannotread', '', $pathname);
172dd12c 1467 }
172dd12c 1468
1469 if (filesize($hashfile) !== $filesize) {
1470 @unlink($hashfile);
1471 throw new file_pool_content_exception($contenthash);
1472 }
1aa01caf 1473 chmod($hashfile, $this->filepermissions); // fix permissions if needed
172dd12c 1474 }
1475
1476
1477 return array($contenthash, $filesize, $newfile);
1478 }
1479
1480 /**
bf9ffe27
PS
1481 * Add string content to sha1 pool.
1482 *
172dd12c 1483 * @param string $content file content - binary string
bf9ffe27 1484 * @return array (contenthash, filesize, newfile)
172dd12c 1485 */
b48f3e06 1486 public function add_string_to_pool($content) {
172dd12c 1487 $contenthash = sha1($content);
1488 $filesize = strlen($content); // binary length
1489
1490 $hashpath = $this->path_from_hash($contenthash);
1491 $hashfile = "$hashpath/$contenthash";
1492
1493
1494 if (file_exists($hashfile)) {
1495 if (filesize($hashfile) !== $filesize) {
1496 throw new file_pool_content_exception($contenthash);
1497 }
1498 $newfile = false;
1499
1500 } else {
1aa01caf 1501 if (!is_dir($hashpath)) {
1502 if (!mkdir($hashpath, $this->dirpermissions, true)) {
1503 throw new file_exception('storedfilecannotcreatefiledirs'); // permission trouble
1504 }
172dd12c 1505 }
1506 $newfile = true;
1507
6c0e2d08 1508 file_put_contents($hashfile, $content);
172dd12c 1509
1510 if (filesize($hashfile) !== $filesize) {
1511 @unlink($hashfile);
1512 throw new file_pool_content_exception($contenthash);
1513 }
1aa01caf 1514 chmod($hashfile, $this->filepermissions); // fix permissions if needed
172dd12c 1515 }
1516
1517 return array($contenthash, $filesize, $newfile);
1518 }
1519
d5dd0540
PS
1520 /**
1521 * Serve file content using X-Sendfile header.
1522 * Please make sure that all headers are already sent
1523 * and the all access control checks passed.
1524 *
1525 * @param string $contenthash sah1 hash of the file content to be served
1526 * @return bool success
1527 */
1528 public function xsendfile($contenthash) {
1529 global $CFG;
1530 require_once("$CFG->libdir/xsendfilelib.php");
1531
1532 $hashpath = $this->path_from_hash($contenthash);
1533 return xsendfile("$hashpath/$contenthash");
1534 }
1535
67233725
DC
1536 /**
1537 * Content exists
1538 *
1539 * @param string $contenthash
1540 * @return bool
1541 */
1542 public function content_exists($contenthash) {
1543 $dir = $this->path_from_hash($contenthash);
1544 $filepath = $dir . '/' . $contenthash;
1545 return file_exists($filepath);
1546 }
1547
172dd12c 1548 /**
bf9ffe27 1549 * Return path to file with given hash.
172dd12c 1550 *
17d9269f 1551 * NOTE: must not be public, files in pool must not be modified
172dd12c 1552 *
d2b7803e 1553 * @param string $contenthash content hash
172dd12c 1554 * @return string expected file location
1555 */
17d9269f 1556 protected function path_from_hash($contenthash) {
172dd12c 1557 $l1 = $contenthash[0].$contenthash[1];
1558 $l2 = $contenthash[2].$contenthash[3];
d0b6f92a 1559 return "$this->filedir/$l1/$l2";
172dd12c 1560 }
1561
1aa01caf 1562 /**
bf9ffe27 1563 * Return path to file with given hash.
1aa01caf 1564 *
1565 * NOTE: must not be public, files in pool must not be modified
1566 *
d2b7803e 1567 * @param string $contenthash content hash
1aa01caf 1568 * @return string expected file location
1569 */
1570 protected function trash_path_from_hash($contenthash) {
1571 $l1 = $contenthash[0].$contenthash[1];
1572 $l2 = $contenthash[2].$contenthash[3];
d0b6f92a 1573 return "$this->trashdir/$l1/$l2";
1aa01caf 1574 }
1575
1576 /**
bf9ffe27
PS
1577 * Tries to recover missing content of file from trash.
1578 *
d2b7803e 1579 * @param stored_file $file stored_file instance
1aa01caf 1580 * @return bool success
1581 */
1582 public function try_content_recovery($file) {
1583 $contenthash = $file->get_contenthash();
1584 $trashfile = $this->trash_path_from_hash($contenthash).'/'.$contenthash;
1585 if (!is_readable($trashfile)) {
1586 if (!is_readable($this->trashdir.'/'.$contenthash)) {
1587 return false;
1588 }
1589 // nice, at least alternative trash file in trash root exists
1590 $trashfile = $this->trashdir.'/'.$contenthash;
1591 }
1592 if (filesize($trashfile) != $file->get_filesize() or sha1_file($trashfile) != $contenthash) {
1593 //weird, better fail early
1594 return false;
1595 }
1596 $contentdir = $this->path_from_hash($contenthash);
1597 $contentfile = $contentdir.'/'.$contenthash;
1598 if (file_exists($contentfile)) {
1599 //strange, no need to recover anything
1600 return true;
1601 }
1602 if (!is_dir($contentdir)) {
1603 if (!mkdir($contentdir, $this->dirpermissions, true)) {
1604 return false;
1605 }
1606 }
1607 return rename($trashfile, $contentfile);
1608 }
1609
172dd12c 1610 /**
bf9ffe27
PS
1611 * Marks pool file as candidate for deleting.
1612 *
1613 * DO NOT call directly - reserved for core!!
1614 *
172dd12c 1615 * @param string $contenthash
1616 */
1aa01caf 1617 public function deleted_file_cleanup($contenthash) {
172dd12c 1618 global $DB;
1619
1aa01caf 1620 //Note: this section is critical - in theory file could be reused at the same
1621 // time, if this happens we can still recover the file from trash
1622 if ($DB->record_exists('files', array('contenthash'=>$contenthash))) {
1623 // file content is still used
1624 return;
1625 }
1626 //move content file to trash
1627 $contentfile = $this->path_from_hash($contenthash).'/'.$contenthash;
1628 if (!file_exists($contentfile)) {
1629 //weird, but no problem
172dd12c 1630 return;
1631 }
1aa01caf 1632 $trashpath = $this->trash_path_from_hash($contenthash);
1633 $trashfile = $trashpath.'/'.$contenthash;
1634 if (file_exists($trashfile)) {
1635 // we already have this content in trash, no need to move it there
1636 unlink($contentfile);
1637 return;
1638 }
1639 if (!is_dir($trashpath)) {
1640 mkdir($trashpath, $this->dirpermissions, true);
1641 }
1642 rename($contentfile, $trashfile);
1643 chmod($trashfile, $this->filepermissions); // fix permissions if needed
172dd12c 1644 }
1645
67233725
DC
1646 /**
1647 * When user referring to a moodle file, we build the reference field
1648 *
1649 * @param array $params
1650 * @return string
1651 */
1652 public static function pack_reference($params) {
1653 $params = (array)$params;
1654 $reference = array();
1655 $reference['contextid'] = is_null($params['contextid']) ? null : clean_param($params['contextid'], PARAM_INT);
1656 $reference['component'] = is_null($params['component']) ? null : clean_param($params['component'], PARAM_COMPONENT);
1657 $reference['itemid'] = is_null($params['itemid']) ? null : clean_param($params['itemid'], PARAM_INT);
1658 $reference['filearea'] = is_null($params['filearea']) ? null : clean_param($params['filearea'], PARAM_AREA);
1659 $reference['filepath'] = is_null($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH);;
1660 $reference['filename'] = is_null($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE);
1661 return base64_encode(serialize($reference));
1662 }
1663
1664 /**
1665 * Unpack reference field
1666 *
1667 * @param string $str
1668 * @return array
1669 */
1670 public static function unpack_reference($str) {
1671 return unserialize(base64_decode($str));
1672 }
1673
1674 /**
1675 * Search references by providing reference content
1676 *
1677 * @param string $str
1678 * @return array
1679 */
1680 public function search_references($str) {
1681 global $DB;
3447100c 1682 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
1683 FROM {files} f
1684 LEFT JOIN {files_reference} r
1685 ON f.referencefileid = r.id
3447100c
DP
1686 WHERE ".$DB->sql_compare_text('r.reference').' = '.$DB->sql_compare_text('?')."
1687 AND (f.component <> ? OR f.filearea <> ?)";
67233725 1688
7051415c 1689 $rs = $DB->get_recordset_sql($sql, array($str, 'user', 'draft'));
67233725
DC
1690 $files = array();
1691 foreach ($rs as $filerecord) {
1692 $file = $this->get_file_instance($filerecord);
1693 if ($file->is_external_file()) {
1694 $files[$filerecord->pathnamehash] = $file;
1695 }
1696 }
1697
1698 return $files;
1699 }
1700
1701 /**
1702 * Search references count by providing reference content
1703 *
1704 * @param string $str
1705 * @return int
1706 */
1707 public function search_references_count($str) {
1708 global $DB;
1709 $sql = "SELECT COUNT(f.id)
1710 FROM {files} f
1711 LEFT JOIN {files_reference} r
1712 ON f.referencefileid = r.id
3447100c
DP
1713 WHERE ".$DB->sql_compare_text('r.reference').' = '.$DB->sql_compare_text('?')."
1714 AND (f.component <> ? OR f.filearea <> ?)";
67233725 1715
7051415c 1716 $count = $DB->count_records_sql($sql, array($str, 'user', 'draft'));
67233725
DC
1717 return $count;
1718 }
1719
1720 /**
1721 * Return all files referring to provided stored_file instance
1722 * This won't work for draft files
1723 *
1724 * @param stored_file $storedfile
1725 * @return array
1726 */
1727 public function get_references_by_storedfile($storedfile) {
1728 global $DB;
1729
1730 $params = array();
1731 $params['contextid'] = $storedfile->get_contextid();
1732 $params['component'] = $storedfile->get_component();
1733 $params['filearea'] = $storedfile->get_filearea();
1734 $params['itemid'] = $storedfile->get_itemid();
1735 $params['filename'] = $storedfile->get_filename();
1736 $params['filepath'] = $storedfile->get_filepath();
1737 $params['userid'] = $storedfile->get_userid();
1738
1739 $reference = self::pack_reference($params);
1740
3447100c 1741 $sql = "SELECT ".self::instance_sql_fields('f', 'r')."
67233725
DC
1742 FROM {files} f
1743 LEFT JOIN {files_reference} r
1744 ON f.referencefileid = r.id
3447100c 1745 WHERE ".$DB->sql_compare_text('r.reference').' = '.$DB->sql_compare_text('?')."
6347a621 1746 AND (f.component <> ? OR f.filearea <> ?)";
67233725 1747
7051415c 1748 $rs = $DB->get_recordset_sql($sql, array($reference, 'user', 'draft'));
67233725
DC
1749 $files = array();
1750 foreach ($rs as $filerecord) {
1751 $file = $this->get_file_instance($filerecord);
1752 if ($file->is_external_file()) {
1753 $files[$filerecord->pathnamehash] = $file;
1754 }
1755 }
1756
1757 return $files;
1758 }
1759
1760 /**
1761 * Return the count files referring to provided stored_file instance
1762 * This won't work for draft files
1763 *
1764 * @param stored_file $storedfile
1765 * @return int
1766 */
1767 public function get_references_count_by_storedfile($storedfile) {
1768 global $DB;
1769
1770 $params = array();
1771 $params['contextid'] = $storedfile->get_contextid();
1772 $params['component'] = $storedfile->get_component();
1773 $params['filearea'] = $storedfile->get_filearea();
1774 $params['itemid'] = $storedfile->get_itemid();
1775 $params['filename'] = $storedfile->get_filename();
1776 $params['filepath'] = $storedfile->get_filepath();
1777 $params['userid'] = $storedfile->get_userid();
1778
1779 $reference = self::pack_reference($params);
1780
1781 $sql = "SELECT COUNT(f.id)
1782 FROM {files} f
1783 LEFT JOIN {files_reference} r
1784 ON f.referencefileid = r.id
3447100c
DP
1785 WHERE ".$DB->sql_compare_text('r.reference').' = '.$DB->sql_compare_text('?')."
1786 AND (f.component <> ? OR f.filearea <> ?)";
67233725 1787
7051415c 1788 $count = $DB->count_records_sql($sql, array($reference, 'user', 'draft'));
67233725
DC
1789 return $count;
1790 }
1791
1792 /**
1793 * Convert file alias to local file
1794 *
1795 * @param stored_file $storedfile a stored_file instances
fc4e8034 1796 * @return stored_file stored_file
67233725
DC
1797 */
1798 public function import_external_file($storedfile) {
1799 global $CFG;
1800 require_once($CFG->dirroot.'/repository/lib.php');
1801 // sync external file
fc4e8034
DC
1802 repository::sync_external_file($storedfile);
1803 // Remove file references
1804 $storedfile->delete_reference();
1805 return $storedfile;
67233725
DC
1806 }
1807
8177b7b9
DC
1808 /**
1809 * Return mimetype by given file pathname
1810 *
ae7f35b9
MG
1811 * If file has a known extension, we return the mimetype based on extension.
1812 * Otherwise (when possible) we try to get the mimetype from file contents.
8177b7b9 1813 *
4c2fcbfc
MG
1814 * @param string $pathname full path to the file
1815 * @param string $filename correct file name with extension, if omitted will be taken from $path
8177b7b9
DC
1816 * @return string
1817 */
4c2fcbfc
MG
1818 public static function mimetype($pathname, $filename = null) {
1819 if (empty($filename)) {
1820 $filename = $pathname;
1821 }
1822 $type = mimeinfo('type', $filename);
ae7f35b9 1823 if ($type === 'document/unknown' && class_exists('finfo') && file_exists($pathname)) {
8177b7b9 1824 $finfo = new finfo(FILEINFO_MIME_TYPE);
ae7f35b9 1825 $type = mimeinfo_from_type('type', $finfo->file($pathname));
8177b7b9 1826 }
ae7f35b9 1827 return $type;
8177b7b9
DC
1828 }
1829
172dd12c 1830 /**
1831 * Cron cleanup job.
1832 */
1833 public function cron() {
a881f970 1834 global $CFG, $DB;
64f93798 1835
2e69ea4a
PS
1836 // find out all stale draft areas (older than 4 days) and purge them
1837 // those are identified by time stamp of the /. root dir
1838 mtrace('Deleting old draft files... ', '');
1839 $old = time() - 60*60*24*4;
1840 $sql = "SELECT *
1841 FROM {files}
1842 WHERE component = 'user' AND filearea = 'draft' AND filepath = '/' AND filename = '.'
1843 AND timecreated < :old";
1844 $rs = $DB->get_recordset_sql($sql, array('old'=>$old));
1845 foreach ($rs as $dir) {
1846 $this->delete_area_files($dir->contextid, $dir->component, $dir->filearea, $dir->itemid);
1847 }
be981316 1848 $rs->close();
b5541735 1849 mtrace('done.');
64f93798 1850
9120a462
DM
1851 // remove orphaned preview files (that is files in the core preview filearea without
1852 // the existing original file)
1853 mtrace('Deleting orphaned preview files... ', '');
1854 $sql = "SELECT p.*
1855 FROM {files} p
1856 LEFT JOIN {files} o ON (p.filename = o.contenthash)
1857 WHERE p.contextid = ? AND p.component = 'core' AND p.filearea = 'preview' AND p.itemid = 0
f7eec6ce 1858 AND o.id IS NULL";
9120a462
DM
1859 $syscontext = context_system::instance();
1860 $rs = $DB->get_recordset_sql($sql, array($syscontext->id));
1861 foreach ($rs as $orphan) {
f7eec6ce
DM
1862 $file = $this->get_file_instance($orphan);
1863 if (!$file->is_directory()) {
1864 $file->delete();
1865 }
9120a462
DM
1866 }
1867 $rs->close();
1868 mtrace('done.');
1869
1aa01caf 1870 // remove trash pool files once a day
1871 // if you want to disable purging of trash put $CFG->fileslastcleanup=time(); into config.php
1872 if (empty($CFG->fileslastcleanup) or $CFG->fileslastcleanup < time() - 60*60*24) {
1873 require_once($CFG->libdir.'/filelib.php');
a881f970
SH
1874 // Delete files that are associated with a context that no longer exists.
1875 mtrace('Cleaning up files from deleted contexts... ', '');
1876 $sql = "SELECT DISTINCT f.contextid
1877 FROM {files} f
1878 LEFT OUTER JOIN {context} c ON f.contextid = c.id
1879 WHERE c.id IS NULL";
be981316
EL
1880 $rs = $DB->get_recordset_sql($sql);
1881 if ($rs->valid()) {
a881f970
SH
1882 $fs = get_file_storage();
1883 foreach ($rs as $ctx) {
1884 $fs->delete_area_files($ctx->contextid);
1885 }
1886 }
be981316 1887 $rs->close();
a881f970
SH
1888 mtrace('done.');
1889
1aa01caf 1890 mtrace('Deleting trash files... ', '');
1891 fulldelete($this->trashdir);
1892 set_config('fileslastcleanup', time());
1893 mtrace('done.');
172dd12c 1894 }
1895 }
3447100c
DP
1896
1897 /**
1898 * Get the sql formated fields for a file instance to be created from a
1899 * {files} and {files_refernece} join.
1900 *
1901 * @param string $filesprefix the table prefix for the {files} table
1902 * @param string $filesreferenceprefix the table prefix for the {files_reference} table
1903 * @return string the sql to go after a SELECT
1904 */
1905 private static function instance_sql_fields($filesprefix, $filesreferenceprefix) {
1906 // Note, these fieldnames MUST NOT overlap between the two tables,
1907 // else problems like MDL-33172 occur.
1908 $filefields = array('contenthash', 'pathnamehash', 'contextid', 'component', 'filearea',
1909 'itemid', 'filepath', 'filename', 'userid', 'filesize', 'mimetype', 'status', 'source',
1910 'author', 'license', 'timecreated', 'timemodified', 'sortorder', 'referencefileid',
1911 'referencelastsync', 'referencelifetime');
1912
1913 $referencefields = array('repositoryid', 'reference');
1914
1915 // id is specifically named to prevent overlaping between the two tables.
1916 $fields = array();
1917 $fields[] = $filesprefix.'.id AS id';
1918 foreach ($filefields as $field) {
1919 $fields[] = "{$filesprefix}.{$field}";
1920 }
1921
1922 foreach ($referencefields as $field) {
1923 $fields[] = "{$filesreferenceprefix}.{$field}";
1924 }
1925
1926 return implode(', ', $fields);
1927 }
172dd12c 1928}
bf9ffe27 1929