MDL-51888 mod_resource: cache file details for performance
[moodle.git] / mod / resource / lib.php
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.
14 //
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_resource
20  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
21  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22  */
24 defined('MOODLE_INTERNAL') || die;
26 /**
27  * List of features supported in Resource module
28  * @param string $feature FEATURE_xx constant for requested feature
29  * @return mixed True if module supports feature, false if not, null if doesn't know
30  */
31 function resource_supports($feature) {
32     switch($feature) {
33         case FEATURE_MOD_ARCHETYPE:           return MOD_ARCHETYPE_RESOURCE;
34         case FEATURE_GROUPS:                  return false;
35         case FEATURE_GROUPINGS:               return false;
36         case FEATURE_MOD_INTRO:               return true;
37         case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
38         case FEATURE_GRADE_HAS_GRADE:         return false;
39         case FEATURE_GRADE_OUTCOMES:          return false;
40         case FEATURE_BACKUP_MOODLE2:          return true;
41         case FEATURE_SHOW_DESCRIPTION:        return true;
43         default: return null;
44     }
45 }
47 /**
48  * Returns all other caps used in module
49  * @return array
50  */
51 function resource_get_extra_capabilities() {
52     return array('moodle/site:accessallgroups');
53 }
55 /**
56  * This function is used by the reset_course_userdata function in moodlelib.
57  * @param $data the data submitted from the reset course.
58  * @return array status array
59  */
60 function resource_reset_userdata($data) {
61     return array();
62 }
64 /**
65  * List the actions that correspond to a view of this module.
66  * This is used by the participation report.
67  *
68  * Note: This is not used by new logging system. Event with
69  *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
70  *       be considered as view action.
71  *
72  * @return array
73  */
74 function resource_get_view_actions() {
75     return array('view','view all');
76 }
78 /**
79  * List the actions that correspond to a post of this module.
80  * This is used by the participation report.
81  *
82  * Note: This is not used by new logging system. Event with
83  *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
84  *       will be considered as post action.
85  *
86  * @return array
87  */
88 function resource_get_post_actions() {
89     return array('update', 'add');
90 }
92 /**
93  * Add resource instance.
94  * @param object $data
95  * @param object $mform
96  * @return int new resource instance id
97  */
98 function resource_add_instance($data, $mform) {
99     global $CFG, $DB;
100     require_once("$CFG->libdir/resourcelib.php");
101     require_once("$CFG->dirroot/mod/resource/locallib.php");
102     $cmid = $data->coursemodule;
103     $data->timemodified = time();
105     resource_set_display_options($data);
107     $data->id = $DB->insert_record('resource', $data);
109     // we need to use context now, so we need to make sure all needed info is already in db
110     $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
111     resource_set_mainfile($data);
112     return $data->id;
115 /**
116  * Update resource instance.
117  * @param object $data
118  * @param object $mform
119  * @return bool true
120  */
121 function resource_update_instance($data, $mform) {
122     global $CFG, $DB;
123     require_once("$CFG->libdir/resourcelib.php");
124     $data->timemodified = time();
125     $data->id           = $data->instance;
126     $data->revision++;
128     resource_set_display_options($data);
130     $DB->update_record('resource', $data);
131     resource_set_mainfile($data);
132     return true;
135 /**
136  * Updates display options based on form input.
137  *
138  * Shared code used by resource_add_instance and resource_update_instance.
139  *
140  * @param object $data Data object
141  */
142 function resource_set_display_options($data) {
143     $displayoptions = array();
144     if ($data->display == RESOURCELIB_DISPLAY_POPUP) {
145         $displayoptions['popupwidth']  = $data->popupwidth;
146         $displayoptions['popupheight'] = $data->popupheight;
147     }
148     if (in_array($data->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) {
149         $displayoptions['printintro']   = (int)!empty($data->printintro);
150     }
151     if (!empty($data->showsize)) {
152         $displayoptions['showsize'] = 1;
153     }
154     if (!empty($data->showtype)) {
155         $displayoptions['showtype'] = 1;
156     }
157     if (!empty($data->showdate)) {
158         $displayoptions['showdate'] = 1;
159     }
160     $data->displayoptions = serialize($displayoptions);
163 /**
164  * Delete resource instance.
165  * @param int $id
166  * @return bool true
167  */
168 function resource_delete_instance($id) {
169     global $DB;
171     if (!$resource = $DB->get_record('resource', array('id'=>$id))) {
172         return false;
173     }
175     // note: all context files are deleted automatically
177     $DB->delete_records('resource', array('id'=>$resource->id));
179     return true;
182 /**
183  * Given a course_module object, this function returns any
184  * "extra" information that may be needed when printing
185  * this activity in a course listing.
186  *
187  * See {@link get_array_of_activities()} in course/lib.php
188  *
189  * @param stdClass $coursemodule
190  * @return cached_cm_info info
191  */
192 function resource_get_coursemodule_info($coursemodule) {
193     global $CFG, $DB;
194     require_once("$CFG->libdir/filelib.php");
195     require_once("$CFG->dirroot/mod/resource/locallib.php");
196     require_once($CFG->libdir.'/completionlib.php');
198     $context = context_module::instance($coursemodule->id);
200     if (!$resource = $DB->get_record('resource', array('id'=>$coursemodule->instance),
201             'id, name, display, displayoptions, tobemigrated, revision, intro, introformat')) {
202         return NULL;
203     }
205     $info = new cached_cm_info();
206     $info->name = $resource->name;
207     if ($coursemodule->showdescription) {
208         // Convert intro to html. Do not filter cached version, filters run at display time.
209         $info->content = format_module_intro('resource', $resource, $coursemodule->id, false);
210     }
212     if ($resource->tobemigrated) {
213         $info->icon ='i/invalid';
214         return $info;
215     }
216     $fs = get_file_storage();
217     $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false); // TODO: this is not very efficient!!
218     if (count($files) >= 1) {
219         $mainfile = reset($files);
220         $info->icon = file_file_icon($mainfile, 24);
221         $resource->mainfile = $mainfile->get_filename();
222     }
224     $display = resource_get_final_display_type($resource);
226     if ($display == RESOURCELIB_DISPLAY_POPUP) {
227         $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
228         $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions);
229         $width  = empty($options['popupwidth'])  ? 620 : $options['popupwidth'];
230         $height = empty($options['popupheight']) ? 450 : $options['popupheight'];
231         $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes";
232         $info->onclick = "window.open('$fullurl', '', '$wh'); return false;";
234     } else if ($display == RESOURCELIB_DISPLAY_NEW) {
235         $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&amp;redirect=1";
236         $info->onclick = "window.open('$fullurl'); return false;";
238     }
240     // If any optional extra details are turned on, store in custom data,
241     // add some file details as well to be used later by resource_get_optional_details() without retriving.
242     // Do not store filedetails if this is a reference - they will still need to be retrieved every time.
243     if (($filedetails = resource_get_file_details($resource, $coursemodule)) && empty($filedetails['isref'])) {
244         $displayoptions = @unserialize($resource->displayoptions);
245         $displayoptions['filedetails'] = $filedetails;
246         $info->customdata = serialize($displayoptions);
247     } else {
248         $info->customdata = $resource->displayoptions;
249     }
251     return $info;
254 /**
255  * Called when viewing course page. Shows extra details after the link if
256  * enabled.
257  *
258  * @param cm_info $cm Course module information
259  */
260 function resource_cm_info_view(cm_info $cm) {
261     global $CFG;
262     require_once($CFG->dirroot . '/mod/resource/locallib.php');
264     $resource = (object)array('displayoptions' => $cm->customdata);
265     $details = resource_get_optional_details($resource, $cm);
266     if ($details) {
267         $cm->set_after_link(' ' . html_writer::tag('span', $details,
268                 array('class' => 'resourcelinkdetails')));
269     }
272 /**
273  * Lists all browsable file areas
274  *
275  * @package  mod_resource
276  * @category files
277  * @param stdClass $course course object
278  * @param stdClass $cm course module object
279  * @param stdClass $context context object
280  * @return array
281  */
282 function resource_get_file_areas($course, $cm, $context) {
283     $areas = array();
284     $areas['content'] = get_string('resourcecontent', 'resource');
285     return $areas;
288 /**
289  * File browsing support for resource module content area.
290  *
291  * @package  mod_resource
292  * @category files
293  * @param stdClass $browser file browser instance
294  * @param stdClass $areas file areas
295  * @param stdClass $course course object
296  * @param stdClass $cm course module object
297  * @param stdClass $context context object
298  * @param string $filearea file area
299  * @param int $itemid item ID
300  * @param string $filepath file path
301  * @param string $filename file name
302  * @return file_info instance or null if not found
303  */
304 function resource_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
305     global $CFG;
307     if (!has_capability('moodle/course:managefiles', $context)) {
308         // students can not peak here!
309         return null;
310     }
312     $fs = get_file_storage();
314     if ($filearea === 'content') {
315         $filepath = is_null($filepath) ? '/' : $filepath;
316         $filename = is_null($filename) ? '.' : $filename;
318         $urlbase = $CFG->wwwroot.'/pluginfile.php';
319         if (!$storedfile = $fs->get_file($context->id, 'mod_resource', 'content', 0, $filepath, $filename)) {
320             if ($filepath === '/' and $filename === '.') {
321                 $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0);
322             } else {
323                 // not found
324                 return null;
325             }
326         }
327         require_once("$CFG->dirroot/mod/resource/locallib.php");
328         return new resource_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, true, false);
329     }
331     // note: resource_intro handled in file_browser automatically
333     return null;
336 /**
337  * Serves the resource files.
338  *
339  * @package  mod_resource
340  * @category files
341  * @param stdClass $course course object
342  * @param stdClass $cm course module object
343  * @param stdClass $context context object
344  * @param string $filearea file area
345  * @param array $args extra arguments
346  * @param bool $forcedownload whether or not force download
347  * @param array $options additional options affecting the file serving
348  * @return bool false if file not found, does not return if found - just send the file
349  */
350 function resource_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
351     global $CFG, $DB;
352     require_once("$CFG->libdir/resourcelib.php");
354     if ($context->contextlevel != CONTEXT_MODULE) {
355         return false;
356     }
358     require_course_login($course, true, $cm);
359     if (!has_capability('mod/resource:view', $context)) {
360         return false;
361     }
363     if ($filearea !== 'content') {
364         // intro is handled automatically in pluginfile.php
365         return false;
366     }
368     array_shift($args); // ignore revision - designed to prevent caching problems only
370     $fs = get_file_storage();
371     $relativepath = implode('/', $args);
372     $fullpath = rtrim("/$context->id/mod_resource/$filearea/0/$relativepath", '/');
373     do {
374         if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
375             if ($fs->get_file_by_hash(sha1("$fullpath/."))) {
376                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.htm"))) {
377                     break;
378                 }
379                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/index.html"))) {
380                     break;
381                 }
382                 if ($file = $fs->get_file_by_hash(sha1("$fullpath/Default.htm"))) {
383                     break;
384                 }
385             }
386             $resource = $DB->get_record('resource', array('id'=>$cm->instance), 'id, legacyfiles', MUST_EXIST);
387             if ($resource->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) {
388                 return false;
389             }
390             if (!$file = resourcelib_try_file_migration('/'.$relativepath, $cm->id, $cm->course, 'mod_resource', 'content', 0)) {
391                 return false;
392             }
393             // file migrate - update flag
394             $resource->legacyfileslast = time();
395             $DB->update_record('resource', $resource);
396         }
397     } while (false);
399     // should we apply filters?
400     $mimetype = $file->get_mimetype();
401     if ($mimetype === 'text/html' or $mimetype === 'text/plain' or $mimetype === 'application/xhtml+xml') {
402         $filter = $DB->get_field('resource', 'filterfiles', array('id'=>$cm->instance));
403         $CFG->embeddedsoforcelinktarget = true;
404     } else {
405         $filter = 0;
406     }
408     // finally send the file
409     send_stored_file($file, null, $filter, $forcedownload, $options);
412 /**
413  * Return a list of page types
414  * @param string $pagetype current page type
415  * @param stdClass $parentcontext Block's parent context
416  * @param stdClass $currentcontext Current context of block
417  */
418 function resource_page_type_list($pagetype, $parentcontext, $currentcontext) {
419     $module_pagetype = array('mod-resource-*'=>get_string('page-mod-resource-x', 'resource'));
420     return $module_pagetype;
423 /**
424  * Export file resource contents
425  *
426  * @return array of file content
427  */
428 function resource_export_contents($cm, $baseurl) {
429     global $CFG, $DB;
430     $contents = array();
431     $context = context_module::instance($cm->id);
432     $resource = $DB->get_record('resource', array('id'=>$cm->instance), '*', MUST_EXIST);
434     $fs = get_file_storage();
435     $files = $fs->get_area_files($context->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false);
437     foreach ($files as $fileinfo) {
438         $file = array();
439         $file['type'] = 'file';
440         $file['filename']     = $fileinfo->get_filename();
441         $file['filepath']     = $fileinfo->get_filepath();
442         $file['filesize']     = $fileinfo->get_filesize();
443         $file['fileurl']      = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_resource/content/'.$resource->revision.$fileinfo->get_filepath().$fileinfo->get_filename(), true);
444         $file['timecreated']  = $fileinfo->get_timecreated();
445         $file['timemodified'] = $fileinfo->get_timemodified();
446         $file['sortorder']    = $fileinfo->get_sortorder();
447         $file['userid']       = $fileinfo->get_userid();
448         $file['author']       = $fileinfo->get_author();
449         $file['license']      = $fileinfo->get_license();
450         $contents[] = $file;
451     }
453     return $contents;
456 /**
457  * Register the ability to handle drag and drop file uploads
458  * @return array containing details of the files / types the mod can handle
459  */
460 function resource_dndupload_register() {
461     return array('files' => array(
462                      array('extension' => '*', 'message' => get_string('dnduploadresource', 'mod_resource'))
463                  ));
466 /**
467  * Handle a file that has been uploaded
468  * @param object $uploadinfo details of the file / content that has been uploaded
469  * @return int instance id of the newly created mod
470  */
471 function resource_dndupload_handle($uploadinfo) {
472     // Gather the required info.
473     $data = new stdClass();
474     $data->course = $uploadinfo->course->id;
475     $data->name = $uploadinfo->displayname;
476     $data->intro = '';
477     $data->introformat = FORMAT_HTML;
478     $data->coursemodule = $uploadinfo->coursemodule;
479     $data->files = $uploadinfo->draftitemid;
481     // Set the display options to the site defaults.
482     $config = get_config('resource');
483     $data->display = $config->display;
484     $data->popupheight = $config->popupheight;
485     $data->popupwidth = $config->popupwidth;
486     $data->printintro = $config->printintro;
487     $data->showsize = (isset($config->showsize)) ? $config->showsize : 0;
488     $data->showtype = (isset($config->showtype)) ? $config->showtype : 0;
489     $data->showdate = (isset($config->showdate)) ? $config->showdate : 0;
490     $data->filterfiles = $config->filterfiles;
492     return resource_add_instance($data, null);
495 /**
496  * Mark the activity completed (if required) and trigger the course_module_viewed event.
497  *
498  * @param  stdClass $resource   resource object
499  * @param  stdClass $course     course object
500  * @param  stdClass $cm         course module object
501  * @param  stdClass $context    context object
502  * @since Moodle 3.0
503  */
504 function resource_view($resource, $course, $cm, $context) {
506     // Trigger course_module_viewed event.
507     $params = array(
508         'context' => $context,
509         'objectid' => $resource->id
510     );
512     $event = \mod_resource\event\course_module_viewed::create($params);
513     $event->add_record_snapshot('course_modules', $cm);
514     $event->add_record_snapshot('course', $course);
515     $event->add_record_snapshot('resource', $resource);
516     $event->trigger();
518     // Completion.
519     $completion = new completion_info($course);
520     $completion->set_module_viewed($cm);