3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Mandatory public API of folder module
22 * @copyright 2009 Petr Skoda {@link http://skodak.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /** Display folder contents on a separate page */
29 define('FOLDER_DISPLAY_PAGE', 0);
30 /** Display folder contents inline in a course */
31 define('FOLDER_DISPLAY_INLINE', 1);
34 * List of features supported in Folder module
35 * @param string $feature FEATURE_xx constant for requested feature
36 * @return mixed True if module supports feature, false if not, null if doesn't know
38 function folder_supports($feature) {
40 case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE;
41 case FEATURE_GROUPS: return false;
42 case FEATURE_GROUPINGS: return false;
43 case FEATURE_MOD_INTRO: return true;
44 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
45 case FEATURE_GRADE_HAS_GRADE: return false;
46 case FEATURE_GRADE_OUTCOMES: return false;
47 case FEATURE_BACKUP_MOODLE2: return true;
48 case FEATURE_SHOW_DESCRIPTION: return true;
55 * Returns all other caps used in module
58 function folder_get_extra_capabilities() {
59 return array('moodle/site:accessallgroups');
63 * This function is used by the reset_course_userdata function in moodlelib.
64 * @param $data the data submitted from the reset course.
65 * @return array status array
67 function folder_reset_userdata($data) {
72 * List the actions that correspond to a view of this module.
73 * This is used by the participation report.
75 * Note: This is not used by new logging system. Event with
76 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
77 * be considered as view action.
81 function folder_get_view_actions() {
82 return array('view', 'view all');
86 * List the actions that correspond to a post of this module.
87 * This is used by the participation report.
89 * Note: This is not used by new logging system. Event with
90 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
91 * will be considered as post action.
95 function folder_get_post_actions() {
96 return array('update', 'add');
100 * Add folder instance.
101 * @param object $data
102 * @param object $mform
103 * @return int new folder instance id
105 function folder_add_instance($data, $mform) {
108 $cmid = $data->coursemodule;
109 $draftitemid = $data->files;
111 $data->timemodified = time();
112 $data->id = $DB->insert_record('folder', $data);
114 // we need to use context now, so we need to make sure all needed info is already in db
115 $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
116 $context = context_module::instance($cmid);
119 file_save_draft_area_files($draftitemid, $context->id, 'mod_folder', 'content', 0, array('subdirs'=>true));
122 $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
123 \core_completion\api::update_completion_date_event($data->coursemodule, 'folder', $data->id, $completiontimeexpected);
129 * Update folder instance.
130 * @param object $data
131 * @param object $mform
134 function folder_update_instance($data, $mform) {
137 $cmid = $data->coursemodule;
138 $draftitemid = $data->files;
140 $data->timemodified = time();
141 $data->id = $data->instance;
144 $DB->update_record('folder', $data);
146 $context = context_module::instance($cmid);
147 if ($draftitemid = file_get_submitted_draft_itemid('files')) {
148 file_save_draft_area_files($draftitemid, $context->id, 'mod_folder', 'content', 0, array('subdirs'=>true));
151 $completiontimeexpected = !empty($data->completionexpected) ? $data->completionexpected : null;
152 \core_completion\api::update_completion_date_event($data->coursemodule, 'folder', $data->id, $completiontimeexpected);
158 * Delete folder instance.
162 function folder_delete_instance($id) {
165 if (!$folder = $DB->get_record('folder', array('id'=>$id))) {
169 $cm = get_coursemodule_from_instance('folder', $id);
170 \core_completion\api::update_completion_date_event($cm->id, 'folder', $folder->id, null);
172 // note: all context files are deleted automatically
174 $DB->delete_records('folder', array('id'=>$folder->id));
180 * Lists all browsable file areas
182 * @package mod_folder
184 * @param stdClass $course course object
185 * @param stdClass $cm course module object
186 * @param stdClass $context context object
189 function folder_get_file_areas($course, $cm, $context) {
191 $areas['content'] = get_string('foldercontent', 'folder');
197 * File browsing support for folder module content area.
199 * @package mod_folder
201 * @param file_browser $browser file browser instance
202 * @param array $areas file areas
203 * @param stdClass $course course object
204 * @param stdClass $cm course module object
205 * @param stdClass $context context object
206 * @param string $filearea file area
207 * @param int $itemid item ID
208 * @param string $filepath file path
209 * @param string $filename file name
210 * @return file_info instance or null if not found
212 function folder_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
216 if ($filearea === 'content') {
217 if (!has_capability('mod/folder:view', $context)) {
220 $fs = get_file_storage();
222 $filepath = is_null($filepath) ? '/' : $filepath;
223 $filename = is_null($filename) ? '.' : $filename;
224 if (!$storedfile = $fs->get_file($context->id, 'mod_folder', 'content', 0, $filepath, $filename)) {
225 if ($filepath === '/' and $filename === '.') {
226 $storedfile = new virtual_root_file($context->id, 'mod_folder', 'content', 0);
233 require_once("$CFG->dirroot/mod/folder/locallib.php");
234 $urlbase = $CFG->wwwroot.'/pluginfile.php';
236 // students may read files here
237 $canwrite = has_capability('mod/folder:managefiles', $context);
238 return new folder_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, $canwrite, false);
241 // note: folder_intro handled in file_browser automatically
247 * Serves the folder files.
249 * @package mod_folder
251 * @param stdClass $course course object
252 * @param stdClass $cm course module
253 * @param stdClass $context context object
254 * @param string $filearea file area
255 * @param array $args extra arguments
256 * @param bool $forcedownload whether or not force download
257 * @param array $options additional options affecting the file serving
258 * @return bool false if file not found, does not return if found - just send the file
260 function folder_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
263 if ($context->contextlevel != CONTEXT_MODULE) {
267 require_course_login($course, true, $cm);
268 if (!has_capability('mod/folder:view', $context)) {
272 if ($filearea !== 'content') {
273 // intro is handled automatically in pluginfile.php
277 array_shift($args); // ignore revision - designed to prevent caching problems only
279 $fs = get_file_storage();
280 $relativepath = implode('/', $args);
281 $fullpath = "/$context->id/mod_folder/content/0/$relativepath";
282 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
286 // finally send the file
287 // for folder module, we force download file all the time
288 send_stored_file($file, 0, 0, true, $options);
292 * Return a list of page types
293 * @param string $pagetype current page type
294 * @param stdClass $parentcontext Block's parent context
295 * @param stdClass $currentcontext Current context of block
297 function folder_page_type_list($pagetype, $parentcontext, $currentcontext) {
298 $module_pagetype = array('mod-folder-*'=>get_string('page-mod-folder-x', 'folder'));
299 return $module_pagetype;
303 * Export folder resource contents
305 * @return array of file content
307 function folder_export_contents($cm, $baseurl) {
310 $context = context_module::instance($cm->id);
311 $folder = $DB->get_record('folder', array('id'=>$cm->instance), '*', MUST_EXIST);
313 $fs = get_file_storage();
314 $files = $fs->get_area_files($context->id, 'mod_folder', 'content', 0, 'sortorder DESC, id ASC', false);
316 foreach ($files as $fileinfo) {
318 $file['type'] = 'file';
319 $file['filename'] = $fileinfo->get_filename();
320 $file['filepath'] = $fileinfo->get_filepath();
321 $file['filesize'] = $fileinfo->get_filesize();
322 $file['fileurl'] = file_encode_url("$CFG->wwwroot/" . $baseurl, '/'.$context->id.'/mod_folder/content/'.$folder->revision.$fileinfo->get_filepath().$fileinfo->get_filename(), true);
323 $file['timecreated'] = $fileinfo->get_timecreated();
324 $file['timemodified'] = $fileinfo->get_timemodified();
325 $file['sortorder'] = $fileinfo->get_sortorder();
326 $file['userid'] = $fileinfo->get_userid();
327 $file['author'] = $fileinfo->get_author();
328 $file['license'] = $fileinfo->get_license();
336 * Register the ability to handle drag and drop file uploads
337 * @return array containing details of the files / types the mod can handle
339 function folder_dndupload_register() {
340 return array('files' => array(
341 array('extension' => 'zip', 'message' => get_string('dnduploadmakefolder', 'mod_folder'))
346 * Handle a file that has been uploaded
347 * @param object $uploadinfo details of the file / content that has been uploaded
348 * @return int instance id of the newly created mod
350 function folder_dndupload_handle($uploadinfo) {
353 // Gather the required info.
354 $data = new stdClass();
355 $data->course = $uploadinfo->course->id;
356 $data->name = $uploadinfo->displayname;
357 $data->intro = '<p>'.$uploadinfo->displayname.'</p>';
358 $data->introformat = FORMAT_HTML;
359 $data->coursemodule = $uploadinfo->coursemodule;
360 $data->files = null; // We will unzip the file and sort out the contents below.
362 $data->id = folder_add_instance($data, null);
364 // Retrieve the file from the draft file area.
365 $context = context_module::instance($uploadinfo->coursemodule);
366 file_save_draft_area_files($uploadinfo->draftitemid, $context->id, 'mod_folder', 'temp', 0, array('subdirs'=>true));
367 $fs = get_file_storage();
368 $files = $fs->get_area_files($context->id, 'mod_folder', 'temp', 0, 'sortorder', false);
369 // Only ever one file - extract the contents.
370 $file = reset($files);
372 $success = $file->extract_to_storage(new zip_packer(), $context->id, 'mod_folder', 'content', 0, '/', $USER->id);
373 $fs->delete_area_files($context->id, 'mod_folder', 'temp', 0);
379 $DB->delete_records('folder', array('id' => $data->id));
384 * Given a coursemodule object, this function returns the extra
385 * information needed to print this activity in various places.
387 * If folder needs to be displayed inline we store additional information
388 * in customdata, so functions {@link folder_cm_info_dynamic()} and
389 * {@link folder_cm_info_view()} do not need to do DB queries
392 * @return cached_cm_info info
394 function folder_get_coursemodule_info($cm) {
396 if (!($folder = $DB->get_record('folder', array('id' => $cm->instance),
397 'id, name, display, showexpanded, showdownloadfolder, intro, introformat'))) {
400 $cminfo = new cached_cm_info();
401 $cminfo->name = $folder->name;
402 if ($folder->display == FOLDER_DISPLAY_INLINE) {
403 // prepare folder object to store in customdata
404 $fdata = new stdClass();
405 $fdata->showexpanded = $folder->showexpanded;
406 $fdata->showdownloadfolder = $folder->showdownloadfolder;
407 if ($cm->showdescription && strlen(trim($folder->intro))) {
408 $fdata->intro = $folder->intro;
409 if ($folder->introformat != FORMAT_MOODLE) {
410 $fdata->introformat = $folder->introformat;
413 $cminfo->customdata = $fdata;
415 if ($cm->showdescription) {
416 // Convert intro to html. Do not filter cached version, filters run at display time.
417 $cminfo->content = format_module_intro('folder', $folder, $cm->id, false);
424 * Sets dynamic information about a course module
426 * This function is called from cm_info when displaying the module
427 * mod_folder can be displayed inline on course page and therefore have no course link
431 function folder_cm_info_dynamic(cm_info $cm) {
432 if ($cm->customdata) {
433 // the field 'customdata' is not empty IF AND ONLY IF we display contens inline
434 $cm->set_no_view_link();
439 * Overwrites the content in the course-module object with the folder files list
440 * if folder.display == FOLDER_DISPLAY_INLINE
444 function folder_cm_info_view(cm_info $cm) {
446 if ($cm->uservisible && $cm->customdata &&
447 has_capability('mod/folder:view', $cm->context)) {
448 // Restore folder object from customdata.
449 // Note the field 'customdata' is not empty IF AND ONLY IF we display contens inline.
450 // Otherwise the content is default.
451 $folder = $cm->customdata;
452 $folder->id = (int)$cm->instance;
453 $folder->course = (int)$cm->course;
454 $folder->display = FOLDER_DISPLAY_INLINE;
455 $folder->name = $cm->name;
456 if (empty($folder->intro)) {
459 if (empty($folder->introformat)) {
460 $folder->introformat = FORMAT_MOODLE;
463 $renderer = $PAGE->get_renderer('mod_folder');
464 $cm->set_content($renderer->display_folder($folder));
469 * Mark the activity completed (if required) and trigger the course_module_viewed event.
471 * @param stdClass $folder folder object
472 * @param stdClass $course course object
473 * @param stdClass $cm course module object
474 * @param stdClass $context context object
477 function folder_view($folder, $course, $cm, $context) {
479 // Trigger course_module_viewed event.
481 'context' => $context,
482 'objectid' => $folder->id
485 $event = \mod_folder\event\course_module_viewed::create($params);
486 $event->add_record_snapshot('course_modules', $cm);
487 $event->add_record_snapshot('course', $course);
488 $event->add_record_snapshot('folder', $folder);
492 $completion = new completion_info($course);
493 $completion->set_module_viewed($cm);
497 * Check if the folder can be zipped and downloaded.
498 * @param stdClass $folder
499 * @param context_module $cm
500 * @return bool True if the folder can be zipped and downloaded.
501 * @throws \dml_exception
503 function folder_archive_available($folder, $cm) {
504 if (!$folder->showdownloadfolder) {
508 $context = context_module::instance($cm->id);
509 $fs = get_file_storage();
510 $dir = $fs->get_area_tree($context->id, 'mod_folder', 'content', 0);
512 $size = folder_get_directory_size($dir);
513 $maxsize = get_config('folder', 'maxsizetodownload') * 1024 * 1024;
519 if (!empty($maxsize) && $size > $maxsize) {
527 * Recursively measure the size of the files in a directory.
528 * @param array $directory
529 * @return int size of directory contents in bytes
531 function folder_get_directory_size($directory) {
534 foreach ($directory['files'] as $file) {
535 $size += $file->get_filesize();
538 foreach ($directory['subdirs'] as $subdirectory) {
539 $size += folder_get_directory_size($subdirectory);
546 * Mark the activity completed (if required) and trigger the all_files_downloaded event.
548 * @param stdClass $folder folder object
549 * @param stdClass $course course object
550 * @param stdClass $cm course module object
551 * @param stdClass $context context object
554 function folder_downloaded($folder, $course, $cm, $context) {
556 'context' => $context,
557 'objectid' => $folder->id
559 $event = \mod_folder\event\all_files_downloaded::create($params);
560 $event->add_record_snapshot('course_modules', $cm);
561 $event->add_record_snapshot('course', $course);
562 $event->add_record_snapshot('folder', $folder);
566 $completion = new completion_info($course);
567 $completion->set_module_viewed($cm);
571 * Returns all uploads since a given time in specified folder.
573 * @param array $activities
575 * @param int $timestart
576 * @param int $courseid
579 * @param int $groupid not used, but required for compatibilty with other modules
581 function folder_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
582 global $COURSE, $DB, $OUTPUT;
584 if ($COURSE->id == $courseid) {
587 $course = $DB->get_record('course', array('id' => $courseid));
590 $modinfo = get_fast_modinfo($course);
591 $cm = $modinfo->cms[$cmid];
593 $context = context_module::instance($cm->id);
594 if (!has_capability('mod/folder:view', $context)) {
597 $files = folder_get_recent_activity($context, $timestart, $userid);
599 foreach ($files as $file) {
600 $tmpactivity = new stdClass();
602 $tmpactivity->type = 'folder';
603 $tmpactivity->cmid = $cm->id;
604 $tmpactivity->sectionnum = $cm->sectionnum;
605 $tmpactivity->timestamp = $file->get_timemodified();
606 $tmpactivity->user = core_user::get_user($file->get_userid());
608 $tmpactivity->content = new stdClass();
609 $tmpactivity->content->url = moodle_url::make_pluginfile_url($file->get_contextid(), 'mod_folder', 'content',
610 $file->get_itemid(), $file->get_filepath(), $file->get_filename());
612 if (file_extension_in_typegroup($file->get_filename(), 'web_image')) {
613 $image = $tmpactivity->content->url->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
614 $image = html_writer::empty_tag('img', array('src' => $image));
616 $image = $OUTPUT->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
619 $tmpactivity->content->image = $image;
620 $tmpactivity->content->filename = $file->get_filename();
622 $activities[$index++] = $tmpactivity;
628 * Outputs the folder uploads indicated by $activity.
630 * @param object $activity the activity object the folder resides in
631 * @param int $courseid the id of the course the folder resides in
632 * @param bool $detail not used, but required for compatibilty with other modules
633 * @param int $modnames not used, but required for compatibilty with other modules
634 * @param bool $viewfullnames not used, but required for compatibilty with other modules
636 function folder_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
639 $content = $activity->content;
642 'cellpadding' => '3',
645 $output = html_writer::start_tag('table', $tableoptions);
646 $output .= html_writer::start_tag('tr');
647 $output .= html_writer::tag('td', $content->image, ['class' => 'fp-icon', 'valign' => 'top']);
648 $output .= html_writer::start_tag('td');
649 $output .= html_writer::start_div('fp-filename');
650 $output .= html_writer::link($content->url, $content->filename);
651 $output .= html_writer::end_div();
653 // Show the uploader.
654 $fullname = fullname($activity->user, $viewfullnames);
655 $userurl = new moodle_url('/user/view.php');
656 $userurl->params(['id' => $activity->user->id, 'course' => $courseid]);
657 $by = new stdClass();
658 $by->name = html_writer::link($userurl, $fullname);
659 $by->date = userdate($activity->timestamp);
660 $authornamedate = get_string('bynameondate', 'folder', $by);
661 $output .= html_writer::div($authornamedate, 'user');
663 // Finish up the table.
664 $output .= html_writer::end_tag('tr');
665 $output .= html_writer::end_tag('table');
671 * Gets recent file uploads in a given folder. Does not perform security checks.
673 * @param object $context
674 * @param int $timestart
679 function folder_get_recent_activity($context, $timestart, $userid=0) {
681 $fs = get_file_storage();
682 $files = $fs->get_area_files($context->id, 'mod_folder', 'content');
683 foreach ($files as $file) {
684 if ($file->get_timemodified() <= $timestart) {
687 if ($file->get_filename() === '.') {
690 if (!empty($userid) && $userid !== $file->get_userid()) {
699 * Given a course and a date, prints a summary of all the new
700 * files posted in folder resources since that date
702 * @uses CONTEXT_MODULE
703 * @param object $course
704 * @param bool $viewfullnames capability
705 * @param int $timestart
706 * @return bool success
708 function folder_print_recent_activity($course, $viewfullnames, $timestart) {
711 $folders = get_all_instances_in_course('folder', $course);
713 if (empty($folders)) {
719 $modinfo = get_fast_modinfo($course);
720 foreach ($folders as $folder) {
721 // Skip resources if the user can't view them.
722 $cm = $modinfo->cms[$folder->coursemodule];
723 $context = context_module::instance($cm->id);
724 if (!has_capability('mod/folder:view', $context)) {
728 // Get the files uploaded in the current time frame.
729 $newfiles = array_merge($newfiles, folder_get_recent_activity($context, $timestart));
732 if (empty($newfiles)) {
736 // Build list of files.
737 echo $OUTPUT->heading(get_string('newfoldercontent', 'folder').':', 3);
738 $list = html_writer::start_tag('ul', ['class' => 'unlist']);
739 foreach ($newfiles as $file) {
740 $filename = $file->get_filename();
741 $url = moodle_url::make_pluginfile_url($file->get_contextid(), 'mod_folder', 'content',
742 $file->get_itemid(), $file->get_filepath(), $filename);
744 $list .= html_writer::start_tag('li');
745 $list .= html_writer::start_div('head');
746 $list .= html_writer::div(userdate($file->get_timemodified(), get_string('strftimerecent')), 'date');
747 $list .= html_writer::div($file->get_author(), 'name');
748 $list .= html_writer::end_div(); // Head.
750 $list .= html_writer::start_div('info');
751 $list .= html_writer::link($url, $filename);
752 $list .= html_writer::end_div(); // Info.
753 $list .= html_writer::end_tag('li');
755 $list .= html_writer::end_tag('ul');
761 * Check if the module has any update that affects the current user since a given time.
763 * @param cm_info $cm course module data
764 * @param int $from the time to check updates from
765 * @param array $filter if we need to check only specific updates
766 * @return stdClass an object with the different type of areas indicating if they were updated or not
769 function folder_check_updates_since(cm_info $cm, $from, $filter = array()) {
770 $updates = course_check_module_updates_since($cm, $from, array('content'), $filter);
775 * Handles creating actions for events.
777 * @param calendar_event $event
778 * @param \core_calendar\action_factory $factory
779 * @return \core_calendar\local\event\value_objects\action|\core_calendar\local\interfaces\action_interface|null
781 function mod_folder_core_calendar_provide_event_action(calendar_event $event,
782 \core_calendar\action_factory $factory) {
783 $cm = get_fast_modinfo($event->courseid)->instances['folder'][$event->instance];
785 $course = new stdClass();
786 $course->id = $event->courseid;
787 $completion = new \completion_info($course);
789 $completiondata = $completion->get_data($cm, false);
791 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
795 return $factory->create_instance(
797 new \moodle_url('/mod/folder/view.php', ['id' => $cm->id]),