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