MDL-42387 standardise file lifetime handling
[moodle.git] / mod / resource / lib.php
blobf2f86be7957eb19795b3f59b7047fb30c7e5cf2c
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package mod
20 * @subpackage resource
21 * @copyright 2009 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die;
27 /**
28 * List of features supported in Resource module
29 * @param string $feature FEATURE_xx constant for requested feature
30 * @return mixed True if module supports feature, false if not, null if doesn't know
32 function resource_supports($feature) {
33 switch($feature) {
34 case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE;
35 case FEATURE_GROUPS: return false;
36 case FEATURE_GROUPINGS: return false;
37 case FEATURE_GROUPMEMBERSONLY: return true;
38 case FEATURE_MOD_INTRO: return true;
39 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
40 case FEATURE_GRADE_HAS_GRADE: return false;
41 case FEATURE_GRADE_OUTCOMES: return false;
42 case FEATURE_BACKUP_MOODLE2: return true;
43 case FEATURE_SHOW_DESCRIPTION: return true;
45 default: return null;
49 /**
50 * Returns all other caps used in module
51 * @return array
53 function resource_get_extra_capabilities() {
54 return array('moodle/site:accessallgroups');
57 /**
58 * This function is used by the reset_course_userdata function in moodlelib.
59 * @param $data the data submitted from the reset course.
60 * @return array status array
62 function resource_reset_userdata($data) {
63 return array();
66 /**
67 * List of view style log actions
68 * @return array
70 function resource_get_view_actions() {
71 return array('view','view all');
74 /**
75 * List of update style log actions
76 * @return array
78 function resource_get_post_actions() {
79 return array('update', 'add');
82 /**
83 * Add resource instance.
84 * @param object $data
85 * @param object $mform
86 * @return int new resource instance id
88 function resource_add_instance($data, $mform) {
89 global $CFG, $DB;
90 require_once("$CFG->libdir/resourcelib.php");
91 require_once("$CFG->dirroot/mod/resource/locallib.php");
92 $cmid = $data->coursemodule;
93 $data->timemodified = time();
95 resource_set_display_options($data);
97 $data->id = $DB->insert_record('resource', $data);
99 // we need to use context now, so we need to make sure all needed info is already in db
100 $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
101 resource_set_mainfile($data);
102 return $data->id;
106 * Update resource instance.
107 * @param object $data
108 * @param object $mform
109 * @return bool true
111 function resource_update_instance($data, $mform) {
112 global $CFG, $DB;
113 require_once("$CFG->libdir/resourcelib.php");
114 $data->timemodified = time();
115 $data->id = $data->instance;
116 $data->revision++;
118 resource_set_display_options($data);
120 $DB->update_record('resource', $data);
121 resource_set_mainfile($data);
122 return true;
126 * Updates display options based on form input.
128 * Shared code used by resource_add_instance and resource_update_instance.
130 * @param object $data Data object
132 function resource_set_display_options($data) {
133 $displayoptions = array();
134 if ($data->display == RESOURCELIB_DISPLAY_POPUP) {
135 $displayoptions['popupwidth'] = $data->popupwidth;
136 $displayoptions['popupheight'] = $data->popupheight;
138 if (in_array($data->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) {
139 $displayoptions['printintro'] = (int)!empty($data->printintro);
141 if (!empty($data->showsize)) {
142 $displayoptions['showsize'] = 1;
144 if (!empty($data->showtype)) {
145 $displayoptions['showtype'] = 1;
147 $data->displayoptions = serialize($displayoptions);
151 * Delete resource instance.
152 * @param int $id
153 * @return bool true
155 function resource_delete_instance($id) {
156 global $DB;
158 if (!$resource = $DB->get_record('resource', array('id'=>$id))) {
159 return false;
162 // note: all context files are deleted automatically
164 $DB->delete_records('resource', array('id'=>$resource->id));
166 return true;
170 * Return use outline
171 * @param object $course
172 * @param object $user
173 * @param object $mod
174 * @param object $resource
175 * @return object|null
177 function resource_user_outline($course, $user, $mod, $resource) {
178 global $DB;
180 if ($logs = $DB->get_records('log', array('userid'=>$user->id, 'module'=>'resource',
181 'action'=>'view', 'info'=>$resource->id), 'time ASC')) {
183 $numviews = count($logs);
184 $lastlog = array_pop($logs);
186 $result = new stdClass();
187 $result->info = get_string('numviews', '', $numviews);
188 $result->time = $lastlog->time;
190 return $result;
192 return NULL;
196 * Return use complete
197 * @param object $course
198 * @param object $user
199 * @param object $mod
200 * @param object $resource
202 function resource_user_complete($course, $user, $mod, $resource) {
203 global $CFG, $DB;
205 if ($logs = $DB->get_records('log', array('userid'=>$user->id, 'module'=>'resource',
206 'action'=>'view', 'info'=>$resource->id), 'time ASC')) {
207 $numviews = count($logs);
208 $lastlog = array_pop($logs);
210 $strmostrecently = get_string('mostrecently');
211 $strnumviews = get_string('numviews', '', $numviews);
213 echo "$strnumviews - $strmostrecently ".userdate($lastlog->time);
215 } else {
216 print_string('neverseen', 'resource');
221 * Given a course_module object, this function returns any
222 * "extra" information that may be needed when printing
223 * this activity in a course listing.
225 * See {@link get_array_of_activities()} in course/lib.php
227 * @param stdClass $coursemodule
228 * @return cached_cm_info info
230 function resource_get_coursemodule_info($coursemodule) {
231 global $CFG, $DB;
232 require_once("$CFG->libdir/filelib.php");
233 require_once("$CFG->dirroot/mod/resource/locallib.php");
234 require_once($CFG->libdir.'/completionlib.php');
236 $context = context_module::instance($coursemodule->id);
238 if (!$resource = $DB->get_record('resource', array('id'=>$coursemodule->instance),
239 'id, name, display, displayoptions, tobemigrated, revision, intro, introformat')) {
240 return NULL;
243 $info = new cached_cm_info();
244 $info->name = $resource->name;
245 if ($coursemodule->showdescription) {
246 // Convert intro to html. Do not filter cached version, filters run at display time.
247 $info->content = format_module_intro('resource', $resource, $coursemodule->id, false);
250 if ($resource->tobemigrated) {
251 $info->icon ='i/invalid';
252 return $info;
254 $fs = get_file_storage();
255 $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false); // TODO: this is not very efficient!!
256 if (count($files) >= 1) {
257 $mainfile = reset($files);
258 $info->icon = file_file_icon($mainfile, 24);
259 $resource->mainfile = $mainfile->get_filename();
262 $display = resource_get_final_display_type($resource);
264 if ($display == RESOURCELIB_DISPLAY_POPUP) {
265 $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
266 $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions);
267 $width = empty($options['popupwidth']) ? 620 : $options['popupwidth'];
268 $height = empty($options['popupheight']) ? 450 : $options['popupheight'];
269 $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes";
270 $info->onclick = "window.open('$fullurl', '', '$wh'); return false;";
272 } else if ($display == RESOURCELIB_DISPLAY_NEW) {
273 $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
274 $info->onclick = "window.open('$fullurl'); return false;";
278 // If any optional extra details are turned on, store in custom data
279 $info->customdata = resource_get_optional_details($resource, $coursemodule);
281 return $info;
285 * Called when viewing course page. Shows extra details after the link if
286 * enabled.
288 * @param cm_info $cm Course module information
290 function resource_cm_info_view(cm_info $cm) {
291 $details = $cm->get_custom_data();
292 if ($details) {
293 $cm->set_after_link(' ' . html_writer::tag('span', $details,
294 array('class' => 'resourcelinkdetails')));
299 * Lists all browsable file areas
301 * @package mod_resource
302 * @category files
303 * @param stdClass $course course object
304 * @param stdClass $cm course module object
305 * @param stdClass $context context object
306 * @return array
308 function resource_get_file_areas($course, $cm, $context) {
309 $areas = array();
310 $areas['content'] = get_string('resourcecontent', 'resource');
311 return $areas;
315 * File browsing support for resource module content area.
317 * @package mod_resource
318 * @category files
319 * @param stdClass $browser file browser instance
320 * @param stdClass $areas file areas
321 * @param stdClass $course course object
322 * @param stdClass $cm course module object
323 * @param stdClass $context context object
324 * @param string $filearea file area
325 * @param int $itemid item ID
326 * @param string $filepath file path
327 * @param string $filename file name
328 * @return file_info instance or null if not found
330 function resource_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
331 global $CFG;
333 if (!has_capability('moodle/course:managefiles', $context)) {
334 // students can not peak here!
335 return null;
338 $fs = get_file_storage();
340 if ($filearea === 'content') {
341 $filepath = is_null($filepath) ? '/' : $filepath;
342 $filename = is_null($filename) ? '.' : $filename;
344 $urlbase = $CFG->wwwroot.'/pluginfile.php';
345 if (!$storedfile = $fs->get_file($context->id, 'mod_resource', 'content', 0, $filepath, $filename)) {
346 if ($filepath === '/' and $filename === '.') {
347 $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0);
348 } else {
349 // not found
350 return null;
353 require_once("$CFG->dirroot/mod/resource/locallib.php");
354 return new resource_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, true, false);
357 // note: resource_intro handled in file_browser automatically
359 return null;
363 * Serves the resource files.
365 * @package mod_resource
366 * @category files
367 * @param stdClass $course course object
368 * @param stdClass $cm course module object
369 * @param stdClass $context context object
370 * @param string $filearea file area
371 * @param array $args extra arguments
372 * @param bool $forcedownload whether or not force download
373 * @param array $options additional options affecting the file serving
374 * @return bool false if file not found, does not return if found - just send the file
376 function resource_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
377 global $CFG, $DB;
378 require_once("$CFG->libdir/resourcelib.php");
380 if ($context->contextlevel != CONTEXT_MODULE) {
381 return false;
384 require_course_login($course, true, $cm);
385 if (!has_capability('mod/resource:view', $context)) {
386 return false;
389 if ($filearea !== 'content') {
390 // intro is handled automatically in pluginfile.php
391 return false;
394 array_shift($args); // ignore revision - designed to prevent caching problems only
396 $fs = get_file_storage();
397 $relativepath = implode('/', $args);
398 $fullpath = rtrim("/$context->id/mod_resource/$filearea/0/$relativepath", '/');
399 do {
400 if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
401 if ($fs->get_file_by_hash(sha1("$fullpath/."))) {
402 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.htm"))) {
403 break;
405 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.html"))) {
406 break;
408 if ($file = $fs->get_file_by_hash(sha1("$fullpath/Default.htm"))) {
409 break;
412 $resource = $DB->get_record('resource', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
413 if ($resource->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
414 return false;
416 if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_resource', 'content', 0)) {
417 return false;
419 // file migrate - update flag
420 $resource->legacyfileslast = time();
421 $DB->update_record('resource', $resource);
423 } while (false);
425 // should we apply filters?
426 $mimetype = $file->get_mimetype();
427 if ($mimetype === 'text/html' or $mimetype === 'text/plain') {
428 $filter = $DB->get_field('resource', 'filterfiles', array('id'=>$cm->instance));
429 $CFG->embeddedsoforcelinktarget = true;
430 } else {
431 $filter = 0;
434 // finally send the file
435 send_stored_file($file, null, $filter, $forcedownload, $options);
439 * Return a list of page types
440 * @param string $pagetype current page type
441 * @param stdClass $parentcontext Block's parent context
442 * @param stdClass $currentcontext Current context of block
444 function resource_page_type_list($pagetype, $parentcontext, $currentcontext) {
445 $module_pagetype = array('mod-resource-*'=>get_string('page-mod-resource-x', 'resource'));
446 return $module_pagetype;
450 * Export file resource contents
452 * @return array of file content
454 function resource_export_contents($cm, $baseurl) {
455 global $CFG, $DB;
456 $contents = array();
457 $context = context_module::instance($cm->id);
458 $resource = $DB->get_record('resource', array('id'=>$cm->instance), '*', MUST_EXIST);
460 $fs = get_file_storage();
461 $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false);
463 foreach ($files as $fileinfo) {
464 $file = array();
465 $file['type'] = 'file';
466 $file['filename'] = $fileinfo->get_filename();
467 $file['filepath'] = $fileinfo->get_filepath();
468 $file['filesize'] = $fileinfo->get_filesize();
469 $file['fileurl'] = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_resource/content/'.$resource->revision.$fileinfo->get_filepath().$fileinfo->get_filename(), true);
470 $file['timecreated'] = $fileinfo->get_timecreated();
471 $file['timemodified'] = $fileinfo->get_timemodified();
472 $file['sortorder'] = $fileinfo->get_sortorder();
473 $file['userid'] = $fileinfo->get_userid();
474 $file['author'] = $fileinfo->get_author();
475 $file['license'] = $fileinfo->get_license();
476 $contents[] = $file;
479 return $contents;
483 * Register the ability to handle drag and drop file uploads
484 * @return array containing details of the files / types the mod can handle
486 function resource_dndupload_register() {
487 return array('files' => array(
488 array('extension' => '*', 'message' => get_string('dnduploadresource', 'mod_resource'))
493 * Handle a file that has been uploaded
494 * @param object $uploadinfo details of the file / content that has been uploaded
495 * @return int instance id of the newly created mod
497 function resource_dndupload_handle($uploadinfo) {
498 // Gather the required info.
499 $data = new stdClass();
500 $data->course = $uploadinfo->course->id;
501 $data->name = $uploadinfo->displayname;
502 $data->intro = '';
503 $data->introformat = FORMAT_HTML;
504 $data->coursemodule = $uploadinfo->coursemodule;
505 $data->files = $uploadinfo->draftitemid;
507 // Set the display options to the site defaults.
508 $config = get_config('resource');
509 $data->display = $config->display;
510 $data->popupheight = $config->popupheight;
511 $data->popupwidth = $config->popupwidth;
512 $data->printintro = $config->printintro;
513 $data->showsize = (isset($config->showsize)) ? $config->showsize : 0;
514 $data->showtype = (isset($config->showtype)) ? $config->showtype : 0;
515 $data->filterfiles = $config->filterfiles;
517 return resource_add_instance($data, null);