MDL-80880 quiz: change display of previous attempts summary
[moodle.git] / mod / feedback / lib.php
blob8a351cf35eac24a1a1f3cc7ce283cbda3c6ed95e
1 <?php
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.
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/>.
17 /**
18 * Library of functions and constants for module feedback
19 * includes the main-part of feedback-functions
21 * @package mod_feedback
22 * @copyright Andreas Grabs
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 // Include forms lib.
29 require_once($CFG->libdir.'/formslib.php');
31 define('FEEDBACK_ANONYMOUS_YES', 1);
32 define('FEEDBACK_ANONYMOUS_NO', 2);
33 define('FEEDBACK_MIN_ANONYMOUS_COUNT_IN_GROUP', 2);
34 define('FEEDBACK_DECIMAL', '.');
35 define('FEEDBACK_THOUSAND', ',');
36 define('FEEDBACK_RESETFORM_RESET', 'feedback_reset_data_');
37 define('FEEDBACK_RESETFORM_DROP', 'feedback_drop_feedback_');
38 define('FEEDBACK_MAX_PIX_LENGTH', '400'); //max. Breite des grafischen Balkens in der Auswertung
39 define('FEEDBACK_DEFAULT_PAGE_COUNT', 20);
41 // Event types.
42 define('FEEDBACK_EVENT_TYPE_OPEN', 'open');
43 define('FEEDBACK_EVENT_TYPE_CLOSE', 'close');
45 require_once(__DIR__ . '/deprecatedlib.php');
47 /**
48 * @uses FEATURE_GROUPS
49 * @uses FEATURE_GROUPINGS
50 * @uses FEATURE_MOD_INTRO
51 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
52 * @uses FEATURE_GRADE_HAS_GRADE
53 * @uses FEATURE_GRADE_OUTCOMES
54 * @param string $feature FEATURE_xx constant for requested feature
55 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
57 function feedback_supports($feature) {
58 switch($feature) {
59 case FEATURE_GROUPS: return true;
60 case FEATURE_GROUPINGS: return true;
61 case FEATURE_MOD_INTRO: return true;
62 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
63 case FEATURE_COMPLETION_HAS_RULES: return true;
64 case FEATURE_GRADE_HAS_GRADE: return false;
65 case FEATURE_GRADE_OUTCOMES: return false;
66 case FEATURE_BACKUP_MOODLE2: return true;
67 case FEATURE_SHOW_DESCRIPTION: return true;
68 case FEATURE_MOD_PURPOSE: return MOD_PURPOSE_COMMUNICATION;
70 default: return null;
74 /**
75 * this will create a new instance and return the id number
76 * of the new instance.
78 * @global object
79 * @param object $feedback the object given by mod_feedback_mod_form
80 * @return int
82 function feedback_add_instance($feedback) {
83 global $DB;
85 $feedback->timemodified = time();
86 $feedback->id = '';
88 if (empty($feedback->site_after_submit)) {
89 $feedback->site_after_submit = '';
92 //saving the feedback in db
93 $feedbackid = $DB->insert_record("feedback", $feedback);
95 $feedback->id = $feedbackid;
97 feedback_set_events($feedback);
99 if (!isset($feedback->coursemodule)) {
100 $cm = get_coursemodule_from_id('feedback', $feedback->id);
101 $feedback->coursemodule = $cm->id;
103 $context = context_module::instance($feedback->coursemodule);
105 if (!empty($feedback->completionexpected)) {
106 \core_completion\api::update_completion_date_event($feedback->coursemodule, 'feedback', $feedback->id,
107 $feedback->completionexpected);
110 $editoroptions = feedback_get_editor_options();
112 // process the custom wysiwyg editor in page_after_submit
113 if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
114 $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
115 'mod_feedback', 'page_after_submit',
116 0, $editoroptions,
117 $feedback->page_after_submit_editor['text']);
119 $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
121 $DB->update_record('feedback', $feedback);
123 return $feedbackid;
127 * this will update a given instance
129 * @global object
130 * @param object $feedback the object given by mod_feedback_mod_form
131 * @return boolean
133 function feedback_update_instance($feedback) {
134 global $DB;
136 $feedback->timemodified = time();
137 $feedback->id = $feedback->instance;
139 if (empty($feedback->site_after_submit)) {
140 $feedback->site_after_submit = '';
143 //save the feedback into the db
144 $DB->update_record("feedback", $feedback);
146 //create or update the new events
147 feedback_set_events($feedback);
148 $completionexpected = (!empty($feedback->completionexpected)) ? $feedback->completionexpected : null;
149 \core_completion\api::update_completion_date_event($feedback->coursemodule, 'feedback', $feedback->id, $completionexpected);
151 $context = context_module::instance($feedback->coursemodule);
153 $editoroptions = feedback_get_editor_options();
155 // process the custom wysiwyg editor in page_after_submit
156 if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
157 $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
158 'mod_feedback', 'page_after_submit',
159 0, $editoroptions,
160 $feedback->page_after_submit_editor['text']);
162 $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
164 $DB->update_record('feedback', $feedback);
166 return true;
170 * Serves the files included in feedback items like label. Implements needed access control ;-)
172 * There are two situations in general where the files will be sent.
173 * 1) filearea = item, 2) filearea = template
175 * @package mod_feedback
176 * @category files
177 * @param stdClass $course course object
178 * @param stdClass $cm course module object
179 * @param stdClass $context context object
180 * @param string $filearea file area
181 * @param array $args extra arguments
182 * @param bool $forcedownload whether or not force download
183 * @param array $options additional options affecting the file serving
184 * @return bool false if file not found, does not return if found - justsend the file
186 function feedback_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
187 global $CFG, $DB;
189 if ($filearea === 'item' or $filearea === 'template') {
190 $itemid = (int)array_shift($args);
191 //get the item what includes the file
192 if (!$item = $DB->get_record('feedback_item', array('id'=>$itemid))) {
193 return false;
195 $feedbackid = $item->feedback;
196 $templateid = $item->template;
199 if ($filearea === 'page_after_submit' or $filearea === 'item') {
200 if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) {
201 return false;
204 $feedbackid = $feedback->id;
206 //if the filearea is "item" so we check the permissions like view/complete the feedback
207 $canload = false;
208 //first check whether the user has the complete capability
209 if (has_capability('mod/feedback:complete', $context)) {
210 $canload = true;
213 //now we check whether the user has the view capability
214 if (has_capability('mod/feedback:view', $context)) {
215 $canload = true;
218 //if the feedback is on frontpage and anonymous and the fullanonymous is allowed
219 //so the file can be loaded too.
220 if (isset($CFG->feedback_allowfullanonymous)
221 AND $CFG->feedback_allowfullanonymous
222 AND $course->id == SITEID
223 AND $feedback->anonymous == FEEDBACK_ANONYMOUS_YES ) {
224 $canload = true;
227 if (!$canload) {
228 return false;
230 } else if ($filearea === 'template') { //now we check files in templates
231 if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
232 return false;
235 //if the file is not public so the capability edititems has to be there
236 if (!$template->ispublic) {
237 if (!has_capability('mod/feedback:edititems', $context)) {
238 return false;
240 } else { //on public templates, at least the user has to be logged in
241 if (!isloggedin()) {
242 return false;
245 } else {
246 return false;
249 if ($context->contextlevel == CONTEXT_MODULE) {
250 if ($filearea !== 'item' and $filearea !== 'page_after_submit') {
251 return false;
255 if ($context->contextlevel == CONTEXT_COURSE || $context->contextlevel == CONTEXT_SYSTEM) {
256 if ($filearea !== 'template') {
257 return false;
261 $relativepath = implode('/', $args);
262 if ($filearea === 'page_after_submit') {
263 $fullpath = "/{$context->id}/mod_feedback/$filearea/$relativepath";
264 } else {
265 $fullpath = "/{$context->id}/mod_feedback/$filearea/{$item->id}/$relativepath";
268 $fs = get_file_storage();
270 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
271 return false;
274 // finally send the file
275 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
277 return false;
281 * this will delete a given instance.
282 * all referenced data also will be deleted
284 * @global object
285 * @param int $id the instanceid of feedback
286 * @return boolean
288 function feedback_delete_instance($id) {
289 global $DB;
291 //get all referenced items
292 $feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$id));
294 //deleting all referenced items and values
295 if (is_array($feedbackitems)) {
296 foreach ($feedbackitems as $feedbackitem) {
297 $DB->delete_records("feedback_value", array("item"=>$feedbackitem->id));
298 $DB->delete_records("feedback_valuetmp", array("item"=>$feedbackitem->id));
300 if ($delitems = $DB->get_records("feedback_item", array("feedback"=>$id))) {
301 foreach ($delitems as $delitem) {
302 feedback_delete_item($delitem->id, false);
307 //deleting the completeds
308 $DB->delete_records("feedback_completed", array("feedback"=>$id));
310 //deleting the unfinished completeds
311 $DB->delete_records("feedback_completedtmp", array("feedback"=>$id));
313 //deleting old events
314 $DB->delete_records('event', array('modulename'=>'feedback', 'instance'=>$id));
315 return $DB->delete_records("feedback", array("id"=>$id));
319 * Return a small object with summary information about what a
320 * user has done with a given particular instance of this module
321 * Used for user activity reports.
322 * $return->time = the time they did it
323 * $return->info = a short text description
325 * @param stdClass $course
326 * @param stdClass $user
327 * @param cm_info|stdClass $mod
328 * @param stdClass $feedback
329 * @return stdClass
331 function feedback_user_outline($course, $user, $mod, $feedback) {
332 global $DB;
333 $outline = (object)['info' => '', 'time' => 0];
334 if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
335 // Do not disclose any user info if feedback is anonymous.
336 return $outline;
338 $params = array('userid' => $user->id, 'feedback' => $feedback->id,
339 'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
340 $status = null;
341 $context = context_module::instance($mod->id);
342 if ($completed = $DB->get_record('feedback_completed', $params)) {
343 // User has completed feedback.
344 $outline->info = get_string('completed', 'feedback');
345 $outline->time = $completed->timemodified;
346 } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
347 // User has started but not completed feedback.
348 $outline->info = get_string('started', 'feedback');
349 $outline->time = $completedtmp->timemodified;
350 } else if (has_capability('mod/feedback:complete', $context, $user)) {
351 // User has not started feedback but has capability to do so.
352 $outline->info = get_string('not_started', 'feedback');
355 return $outline;
359 * Returns all users who has completed a specified feedback since a given time
360 * many thanks to Manolescu Dorel, who contributed these two functions
362 * @global object
363 * @global object
364 * @global object
365 * @global object
366 * @uses CONTEXT_MODULE
367 * @param array $activities Passed by reference
368 * @param int $index Passed by reference
369 * @param int $timemodified Timestamp
370 * @param int $courseid
371 * @param int $cmid
372 * @param int $userid
373 * @param int $groupid
374 * @return void
376 function feedback_get_recent_mod_activity(&$activities, &$index,
377 $timemodified, $courseid,
378 $cmid, $userid="", $groupid="") {
380 global $CFG, $COURSE, $USER, $DB;
382 if ($COURSE->id == $courseid) {
383 $course = $COURSE;
384 } else {
385 $course = $DB->get_record('course', array('id'=>$courseid));
388 $modinfo = get_fast_modinfo($course);
390 $cm = $modinfo->cms[$cmid];
392 $sqlargs = array();
394 $userfieldsapi = \core_user\fields::for_userpic();
395 $userfields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects;
396 $sql = " SELECT fk . * , fc . * , $userfields
397 FROM {feedback_completed} fc
398 JOIN {feedback} fk ON fk.id = fc.feedback
399 JOIN {user} u ON u.id = fc.userid ";
401 if ($groupid) {
402 $sql .= " JOIN {groups_members} gm ON gm.userid=u.id ";
405 $sql .= " WHERE fc.timemodified > ?
406 AND fk.id = ?
407 AND fc.anonymous_response = ?";
408 $sqlargs[] = $timemodified;
409 $sqlargs[] = $cm->instance;
410 $sqlargs[] = FEEDBACK_ANONYMOUS_NO;
412 if ($userid) {
413 $sql .= " AND u.id = ? ";
414 $sqlargs[] = $userid;
417 if ($groupid) {
418 $sql .= " AND gm.groupid = ? ";
419 $sqlargs[] = $groupid;
422 if (!$feedbackitems = $DB->get_records_sql($sql, $sqlargs)) {
423 return;
426 $cm_context = context_module::instance($cm->id);
428 if (!has_capability('mod/feedback:view', $cm_context)) {
429 return;
432 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
433 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
434 $groupmode = groups_get_activity_groupmode($cm, $course);
436 $aname = format_string($cm->name, true);
437 foreach ($feedbackitems as $feedbackitem) {
438 if ($feedbackitem->userid != $USER->id) {
440 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
441 $usersgroups = groups_get_all_groups($course->id,
442 $feedbackitem->userid,
443 $cm->groupingid);
444 if (!is_array($usersgroups)) {
445 continue;
447 $usersgroups = array_keys($usersgroups);
448 $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
449 if (empty($intersect)) {
450 continue;
455 $tmpactivity = new stdClass();
457 $tmpactivity->type = 'feedback';
458 $tmpactivity->cmid = $cm->id;
459 $tmpactivity->name = $aname;
460 $tmpactivity->sectionnum= $cm->sectionnum;
461 $tmpactivity->timestamp = $feedbackitem->timemodified;
463 $tmpactivity->content = new stdClass();
464 $tmpactivity->content->feedbackid = $feedbackitem->id;
465 $tmpactivity->content->feedbackuserid = $feedbackitem->userid;
467 $tmpactivity->user = user_picture::unalias($feedbackitem, null, 'useridagain');
468 $tmpactivity->user->fullname = fullname($feedbackitem, $viewfullnames);
470 $activities[$index++] = $tmpactivity;
473 return;
477 * Prints all users who has completed a specified feedback since a given time
478 * many thanks to Manolescu Dorel, who contributed these two functions
480 * @global object
481 * @param object $activity
482 * @param int $courseid
483 * @param string $detail
484 * @param array $modnames
485 * @return void Output is echo'd
487 function feedback_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
488 global $CFG, $OUTPUT;
490 echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
492 echo "<tr><td class=\"userpicture align-top\">";
493 echo $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid));
494 echo "</td><td>";
496 if ($detail) {
497 $modname = $modnames[$activity->type];
498 echo '<div class="title">';
499 echo $OUTPUT->image_icon('monologo', $modname, $activity->type);
500 echo "<a href=\"$CFG->wwwroot/mod/feedback/view.php?id={$activity->cmid}\">{$activity->name}</a>";
501 echo '</div>';
504 echo '<div class="title">';
505 echo '</div>';
507 echo '<div class="user">';
508 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
509 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
510 echo '</div>';
512 echo "</td></tr></table>";
514 return;
518 * Print a detailed representation of what a user has done with
519 * a given particular instance of this module, for user activity reports.
521 * @param stdClass $course
522 * @param stdClass $user
523 * @param cm_info|stdClass $mod
524 * @param stdClass $feedback
526 function feedback_user_complete($course, $user, $mod, $feedback) {
527 global $DB;
528 if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
529 // Do not disclose any user info if feedback is anonymous.
530 return;
532 $params = array('userid' => $user->id, 'feedback' => $feedback->id,
533 'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
534 $url = $status = null;
535 $context = context_module::instance($mod->id);
536 if ($completed = $DB->get_record('feedback_completed', $params)) {
537 // User has completed feedback.
538 if (has_capability('mod/feedback:viewreports', $context)) {
539 $url = new moodle_url('/mod/feedback/show_entries.php',
540 ['id' => $mod->id, 'userid' => $user->id,
541 'showcompleted' => $completed->id]);
543 $status = get_string('completedon', 'feedback', userdate($completed->timemodified));
544 } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
545 // User has started but not completed feedback.
546 $status = get_string('startedon', 'feedback', userdate($completedtmp->timemodified));
547 } else if (has_capability('mod/feedback:complete', $context, $user)) {
548 // User has not started feedback but has capability to do so.
549 $status = get_string('not_started', 'feedback');
552 if ($url && $status) {
553 echo html_writer::link($url, $status);
554 } else if ($status) {
555 echo html_writer::div($status);
560 * @return bool true
562 function feedback_cron () {
563 return true;
567 * @deprecated since Moodle 3.8
569 function feedback_scale_used() {
570 throw new coding_exception('feedback_scale_used() can not be used anymore. Plugins can implement ' .
571 '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
575 * Checks if scale is being used by any instance of feedback
577 * This is used to find out if scale used anywhere
578 * @param $scaleid int
579 * @return boolean True if the scale is used by any assignment
581 function feedback_scale_used_anywhere($scaleid) {
582 return false;
586 * List the actions that correspond to a view of this module.
587 * This is used by the participation report.
589 * Note: This is not used by new logging system. Event with
590 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
591 * be considered as view action.
593 * @return array
595 function feedback_get_view_actions() {
596 return array('view', 'view all');
600 * List the actions that correspond to a post of this module.
601 * This is used by the participation report.
603 * Note: This is not used by new logging system. Event with
604 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
605 * will be considered as post action.
607 * @return array
609 function feedback_get_post_actions() {
610 return array('submit');
614 * This function is used by the reset_course_userdata function in moodlelib.
615 * This function will remove all responses from the specified feedback
616 * and clean up any related data.
618 * @global object
619 * @global object
620 * @uses FEEDBACK_RESETFORM_RESET
621 * @uses FEEDBACK_RESETFORM_DROP
622 * @param object $data the data submitted from the reset course.
623 * @return array status array
625 function feedback_reset_userdata($data) {
626 global $CFG, $DB;
628 $resetfeedbacks = array();
629 $dropfeedbacks = array();
630 $status = array();
631 $componentstr = get_string('modulenameplural', 'feedback');
633 //get the relevant entries from $data
634 foreach ($data as $key => $value) {
635 switch(true) {
636 case substr($key, 0, strlen(FEEDBACK_RESETFORM_RESET)) == FEEDBACK_RESETFORM_RESET:
637 if ($value == 1) {
638 $templist = explode('_', $key);
639 if (isset($templist[3])) {
640 $resetfeedbacks[] = intval($templist[3]);
643 break;
644 case substr($key, 0, strlen(FEEDBACK_RESETFORM_DROP)) == FEEDBACK_RESETFORM_DROP:
645 if ($value == 1) {
646 $templist = explode('_', $key);
647 if (isset($templist[3])) {
648 $dropfeedbacks[] = intval($templist[3]);
651 break;
655 //reset the selected feedbacks
656 foreach ($resetfeedbacks as $id) {
657 $feedback = $DB->get_record('feedback', array('id'=>$id));
658 feedback_delete_all_completeds($feedback);
659 $status[] = array('component'=>$componentstr.':'.$feedback->name,
660 'item'=>get_string('resetting_data', 'feedback'),
661 'error'=>false);
664 // Updating dates - shift may be negative too.
665 if ($data->timeshift) {
666 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
667 // See MDL-9367.
668 $shifterror = !shift_course_mod_dates('feedback', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
669 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => $shifterror);
672 return $status;
676 * Called by course/reset.php
678 * @global object
679 * @uses FEEDBACK_RESETFORM_RESET
680 * @param MoodleQuickForm $mform form passed by reference
682 function feedback_reset_course_form_definition(&$mform) {
683 global $COURSE, $DB;
685 $mform->addElement('header', 'feedbackheader', get_string('modulenameplural', 'feedback'));
687 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$COURSE->id), 'name')) {
688 return;
691 $mform->addElement('static', 'hint', get_string('resetting_data', 'feedback'));
692 foreach ($feedbacks as $feedback) {
693 $mform->addElement('checkbox', FEEDBACK_RESETFORM_RESET.$feedback->id, $feedback->name);
698 * Course reset form defaults.
700 * @global object
701 * @uses FEEDBACK_RESETFORM_RESET
702 * @param object $course
704 function feedback_reset_course_form_defaults($course) {
705 global $DB;
707 $return = array();
708 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
709 return;
711 foreach ($feedbacks as $feedback) {
712 $return[FEEDBACK_RESETFORM_RESET.$feedback->id] = true;
714 return $return;
718 * Called by course/reset.php and shows the formdata by coursereset.
719 * it prints checkboxes for each feedback available at the given course
720 * there are two checkboxes:
721 * 1) delete userdata and keep the feedback
722 * 2) delete userdata and drop the feedback
724 * @global object
725 * @uses FEEDBACK_RESETFORM_RESET
726 * @uses FEEDBACK_RESETFORM_DROP
727 * @param object $course
728 * @return void
730 function feedback_reset_course_form($course) {
731 global $DB, $OUTPUT;
733 echo get_string('resetting_feedbacks', 'feedback'); echo ':<br />';
734 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
735 return;
738 foreach ($feedbacks as $feedback) {
739 echo '<p>';
740 echo get_string('name', 'feedback').': '.$feedback->name.'<br />';
741 echo html_writer::checkbox(FEEDBACK_RESETFORM_RESET.$feedback->id,
742 1, true,
743 get_string('resetting_data', 'feedback'));
744 echo '<br />';
745 echo html_writer::checkbox(FEEDBACK_RESETFORM_DROP.$feedback->id,
746 1, false,
747 get_string('drop_feedback', 'feedback'));
748 echo '</p>';
753 * This gets an array with default options for the editor
755 * @return array the options
757 function feedback_get_editor_options() {
758 return array('maxfiles' => EDITOR_UNLIMITED_FILES,
759 'trusttext'=>true);
763 * This creates new events given as timeopen and closeopen by $feedback.
765 * @global object
766 * @param object $feedback
767 * @return void
769 function feedback_set_events($feedback) {
770 global $DB, $CFG;
772 // Include calendar/lib.php.
773 require_once($CFG->dirroot.'/calendar/lib.php');
775 // Get CMID if not sent as part of $feedback.
776 if (!isset($feedback->coursemodule)) {
777 $cm = get_coursemodule_from_instance('feedback', $feedback->id, $feedback->course);
778 $feedback->coursemodule = $cm->id;
781 // Feedback start calendar events.
782 $eventid = $DB->get_field('event', 'id',
783 array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_OPEN));
785 if (isset($feedback->timeopen) && $feedback->timeopen > 0) {
786 $event = new stdClass();
787 $event->eventtype = FEEDBACK_EVENT_TYPE_OPEN;
788 $event->type = empty($feedback->timeclose) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
789 $event->name = get_string('calendarstart', 'feedback', $feedback->name);
790 $event->description = format_module_intro('feedback', $feedback, $feedback->coursemodule, false);
791 $event->format = FORMAT_HTML;
792 $event->timestart = $feedback->timeopen;
793 $event->timesort = $feedback->timeopen;
794 $event->visible = instance_is_visible('feedback', $feedback);
795 $event->timeduration = 0;
796 if ($eventid) {
797 // Calendar event exists so update it.
798 $event->id = $eventid;
799 $calendarevent = calendar_event::load($event->id);
800 $calendarevent->update($event, false);
801 } else {
802 // Event doesn't exist so create one.
803 $event->courseid = $feedback->course;
804 $event->groupid = 0;
805 $event->userid = 0;
806 $event->modulename = 'feedback';
807 $event->instance = $feedback->id;
808 $event->eventtype = FEEDBACK_EVENT_TYPE_OPEN;
809 calendar_event::create($event, false);
811 } else if ($eventid) {
812 // Calendar event is on longer needed.
813 $calendarevent = calendar_event::load($eventid);
814 $calendarevent->delete();
817 // Feedback close calendar events.
818 $eventid = $DB->get_field('event', 'id',
819 array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_CLOSE));
821 if (isset($feedback->timeclose) && $feedback->timeclose > 0) {
822 $event = new stdClass();
823 $event->type = CALENDAR_EVENT_TYPE_ACTION;
824 $event->eventtype = FEEDBACK_EVENT_TYPE_CLOSE;
825 $event->name = get_string('calendarend', 'feedback', $feedback->name);
826 $event->description = format_module_intro('feedback', $feedback, $feedback->coursemodule, false);
827 $event->format = FORMAT_HTML;
828 $event->timestart = $feedback->timeclose;
829 $event->timesort = $feedback->timeclose;
830 $event->visible = instance_is_visible('feedback', $feedback);
831 $event->timeduration = 0;
832 if ($eventid) {
833 // Calendar event exists so update it.
834 $event->id = $eventid;
835 $calendarevent = calendar_event::load($event->id);
836 $calendarevent->update($event, false);
837 } else {
838 // Event doesn't exist so create one.
839 $event->courseid = $feedback->course;
840 $event->groupid = 0;
841 $event->userid = 0;
842 $event->modulename = 'feedback';
843 $event->instance = $feedback->id;
844 calendar_event::create($event, false);
846 } else if ($eventid) {
847 // Calendar event is on longer needed.
848 $calendarevent = calendar_event::load($eventid);
849 $calendarevent->delete();
854 * This standard function will check all instances of this module
855 * and make sure there are up-to-date events created for each of them.
856 * If courseid = 0, then every feedback event in the site is checked, else
857 * only feedback events belonging to the course specified are checked.
858 * This function is used, in its new format, by restore_refresh_events()
860 * @param int $courseid
861 * @param int|stdClass $instance Feedback module instance or ID.
862 * @param int|stdClass $cm Course module object or ID (not used in this module).
863 * @return bool
865 function feedback_refresh_events($courseid = 0, $instance = null, $cm = null) {
866 global $DB;
868 // If we have instance information then we can just update the one event instead of updating all events.
869 if (isset($instance)) {
870 if (!is_object($instance)) {
871 $instance = $DB->get_record('feedback', array('id' => $instance), '*', MUST_EXIST);
873 feedback_set_events($instance);
874 return true;
877 if ($courseid) {
878 if (! $feedbacks = $DB->get_records("feedback", array("course" => $courseid))) {
879 return true;
881 } else {
882 if (! $feedbacks = $DB->get_records("feedback")) {
883 return true;
887 foreach ($feedbacks as $feedback) {
888 feedback_set_events($feedback);
890 return true;
894 * this function is called by {@link feedback_delete_userdata()}
895 * it drops the feedback-instance from the course_module table
897 * @global object
898 * @param int $id the id from the coursemodule
899 * @return boolean
901 function feedback_delete_course_module($id) {
902 global $DB;
904 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
905 return true;
907 return $DB->delete_records('course_modules', array('id'=>$cm->id));
912 ////////////////////////////////////////////////
913 //functions to handle capabilities
914 ////////////////////////////////////////////////
917 * @deprecated since 3.1
919 function feedback_get_context() {
920 throw new coding_exception('feedback_get_context() can not be used anymore.');
924 * returns true if the current role is faked by switching role feature
926 * @global object
927 * @return boolean
929 function feedback_check_is_switchrole() {
930 global $USER;
931 if (isset($USER->switchrole) AND
932 is_array($USER->switchrole) AND
933 count($USER->switchrole) > 0) {
935 return true;
937 return false;
941 * count users which have not completed the feedback
943 * @global object
944 * @uses CONTEXT_MODULE
945 * @param cm_info $cm Course-module object
946 * @param int $group single groupid
947 * @param string $sort
948 * @param int $startpage
949 * @param int $pagecount
950 * @param bool $includestatus to return if the user started or not the feedback among the complete user record
951 * @return array array of user ids or user objects when $includestatus set to true
953 function feedback_get_incomplete_users(cm_info $cm,
954 $group = false,
955 $sort = '',
956 $startpage = false,
957 $pagecount = false,
958 $includestatus = false) {
960 global $DB;
962 $context = context_module::instance($cm->id);
964 //first get all user who can complete this feedback
965 $cap = 'mod/feedback:complete';
966 $userfieldsapi = \core_user\fields::for_name();
967 $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
968 $fields = 'u.id, ' . $allnames . ', u.picture, u.email, u.imagealt';
969 if (!$allusers = get_users_by_capability($context,
970 $cap,
971 $fields,
972 $sort,
975 $group,
977 true)) {
978 return false;
980 // Filter users that are not in the correct group/grouping.
981 $info = new \core_availability\info_module($cm);
982 $allusersrecords = $info->filter_user_list($allusers);
984 $allusers = array_keys($allusersrecords);
986 //now get all completeds
987 $params = array('feedback'=>$cm->instance);
988 if ($completedusers = $DB->get_records_menu('feedback_completed', $params, '', 'id, userid')) {
989 // Now strike all completedusers from allusers.
990 $allusers = array_diff($allusers, $completedusers);
993 //for paging I use array_slice()
994 if ($startpage !== false AND $pagecount !== false) {
995 $allusers = array_slice($allusers, $startpage, $pagecount);
998 // Check if we should return the full users objects.
999 if ($includestatus) {
1000 $userrecords = [];
1001 $startedusers = $DB->get_records_menu('feedback_completedtmp', ['feedback' => $cm->instance], '', 'id, userid');
1002 $startedusers = array_flip($startedusers);
1003 foreach ($allusers as $userid) {
1004 $allusersrecords[$userid]->feedbackstarted = isset($startedusers[$userid]);
1005 $userrecords[] = $allusersrecords[$userid];
1007 return $userrecords;
1008 } else { // Return just user ids.
1009 return $allusers;
1014 * count users which have not completed the feedback
1016 * @global object
1017 * @param object $cm
1018 * @param int $group single groupid
1019 * @return int count of userrecords
1021 function feedback_count_incomplete_users($cm, $group = false) {
1022 if ($allusers = feedback_get_incomplete_users($cm, $group)) {
1023 return count($allusers);
1025 return 0;
1029 * count users which have completed a feedback
1031 * @global object
1032 * @uses FEEDBACK_ANONYMOUS_NO
1033 * @param object $cm
1034 * @param int $group single groupid
1035 * @return int count of userrecords
1037 function feedback_count_complete_users($cm, $group = false) {
1038 global $DB;
1040 $params = array(FEEDBACK_ANONYMOUS_NO, $cm->instance);
1042 $fromgroup = '';
1043 $wheregroup = '';
1044 if ($group) {
1045 $fromgroup = ', {groups_members} g';
1046 $wheregroup = ' AND g.groupid = ? AND g.userid = c.userid';
1047 $params[] = $group;
1050 $sql = 'SELECT COUNT(u.id) FROM {user} u, {feedback_completed} c'.$fromgroup.'
1051 WHERE anonymous_response = ? AND u.id = c.userid AND c.feedback = ?
1052 '.$wheregroup;
1054 return $DB->count_records_sql($sql, $params);
1059 * get users which have completed a feedback
1061 * @global object
1062 * @uses CONTEXT_MODULE
1063 * @uses FEEDBACK_ANONYMOUS_NO
1064 * @param object $cm
1065 * @param int $group single groupid
1066 * @param string $where a sql where condition (must end with " AND ")
1067 * @param array parameters used in $where
1068 * @param string $sort a table field
1069 * @param int $startpage
1070 * @param int $pagecount
1071 * @return object the userrecords
1073 function feedback_get_complete_users($cm,
1074 $group = false,
1075 $where = '',
1076 array $params = null,
1077 $sort = '',
1078 $startpage = false,
1079 $pagecount = false) {
1081 global $DB;
1083 $context = context_module::instance($cm->id);
1085 $params = (array)$params;
1087 $params['anon'] = FEEDBACK_ANONYMOUS_NO;
1088 $params['instance'] = $cm->instance;
1090 $fromgroup = '';
1091 $wheregroup = '';
1092 if ($group) {
1093 $fromgroup = ', {groups_members} g';
1094 $wheregroup = ' AND g.groupid = :group AND g.userid = c.userid';
1095 $params['group'] = $group;
1098 if ($sort) {
1099 $sortsql = ' ORDER BY '.$sort;
1100 } else {
1101 $sortsql = '';
1104 $userfieldsapi = \core_user\fields::for_userpic();
1105 $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1106 $sql = 'SELECT DISTINCT '.$ufields.', c.timemodified as completed_timemodified
1107 FROM {user} u, {feedback_completed} c '.$fromgroup.'
1108 WHERE '.$where.' anonymous_response = :anon
1109 AND u.id = c.userid
1110 AND c.feedback = :instance
1111 '.$wheregroup.$sortsql;
1113 if ($startpage === false OR $pagecount === false) {
1114 $startpage = false;
1115 $pagecount = false;
1117 return $DB->get_records_sql($sql, $params, $startpage, $pagecount);
1121 * get users which have the viewreports-capability
1123 * @uses CONTEXT_MODULE
1124 * @param int $cmid
1125 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1126 * @return object the userrecords
1128 function feedback_get_viewreports_users($cmid, $groups = false) {
1130 $context = context_module::instance($cmid);
1132 //description of the call below:
1133 //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1134 // $limitnum='', $groups='', $exceptions='', $doanything=true)
1135 return get_users_by_capability($context,
1136 'mod/feedback:viewreports',
1138 'lastname',
1141 $groups,
1143 false);
1147 * get users which have the receivemail-capability
1149 * @uses CONTEXT_MODULE
1150 * @param int $cmid
1151 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1152 * @return object the userrecords
1154 function feedback_get_receivemail_users($cmid, $groups = false) {
1156 $context = context_module::instance($cmid);
1158 //description of the call below:
1159 //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1160 // $limitnum='', $groups='', $exceptions='', $doanything=true)
1161 return get_users_by_capability($context,
1162 'mod/feedback:receivemail',
1164 'lastname',
1167 $groups,
1169 false);
1172 ////////////////////////////////////////////////
1173 //functions to handle the templates
1174 ////////////////////////////////////////////////
1175 ////////////////////////////////////////////////
1178 * creates a new template-record.
1180 * @global object
1181 * @param int $courseid
1182 * @param string $name the name of template shown in the templatelist
1183 * @param int $ispublic 0:privat 1:public
1184 * @return stdClass the new template
1186 function feedback_create_template($courseid, $name, $ispublic = 0) {
1187 global $DB;
1189 $templ = new stdClass();
1190 $templ->course = ($ispublic ? 0 : $courseid);
1191 $templ->name = $name;
1192 $templ->ispublic = $ispublic;
1194 $templid = $DB->insert_record('feedback_template', $templ);
1195 return $DB->get_record('feedback_template', array('id'=>$templid));
1199 * creates new template items.
1200 * all items will be copied and the attribute feedback will be set to 0
1201 * and the attribute template will be set to the new templateid
1203 * @global object
1204 * @uses CONTEXT_MODULE
1205 * @uses CONTEXT_COURSE
1206 * @param object $feedback
1207 * @param string $name the name of template shown in the templatelist
1208 * @param int $ispublic 0:privat 1:public
1209 * @return boolean
1211 function feedback_save_as_template($feedback, $name, $ispublic = 0) {
1212 global $DB;
1213 $fs = get_file_storage();
1215 if (!$feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1216 return false;
1219 if (!$newtempl = feedback_create_template($feedback->course, $name, $ispublic)) {
1220 return false;
1223 //files in the template_item are in the context of the current course or
1224 //if the template is public the files are in the system context
1225 //files in the feedback_item are in the feedback_context of the feedback
1226 if ($ispublic) {
1227 $s_context = context_system::instance();
1228 } else {
1229 $s_context = context_course::instance($newtempl->course);
1231 $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1232 $f_context = context_module::instance($cm->id);
1234 //create items of this new template
1235 //depend items we are storing temporary in an mapping list array(new id => dependitem)
1236 //we also store a mapping of all items array(oldid => newid)
1237 $dependitemsmap = array();
1238 $itembackup = array();
1239 foreach ($feedbackitems as $item) {
1241 $t_item = clone($item);
1243 unset($t_item->id);
1244 $t_item->feedback = 0;
1245 $t_item->template = $newtempl->id;
1246 $t_item->id = $DB->insert_record('feedback_item', $t_item);
1247 //copy all included files to the feedback_template filearea
1248 $itemfiles = $fs->get_area_files($f_context->id,
1249 'mod_feedback',
1250 'item',
1251 $item->id,
1252 "id",
1253 false);
1254 if ($itemfiles) {
1255 foreach ($itemfiles as $ifile) {
1256 $file_record = new stdClass();
1257 $file_record->contextid = $s_context->id;
1258 $file_record->component = 'mod_feedback';
1259 $file_record->filearea = 'template';
1260 $file_record->itemid = $t_item->id;
1261 $fs->create_file_from_storedfile($file_record, $ifile);
1265 $itembackup[$item->id] = $t_item->id;
1266 if ($t_item->dependitem) {
1267 $dependitemsmap[$t_item->id] = $t_item->dependitem;
1272 //remapping the dependency
1273 foreach ($dependitemsmap as $key => $dependitem) {
1274 $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1275 $newitem->dependitem = $itembackup[$newitem->dependitem];
1276 $DB->update_record('feedback_item', $newitem);
1279 return true;
1283 * deletes all feedback_items related to the given template id
1285 * @global object
1286 * @uses CONTEXT_COURSE
1287 * @param object $template the template
1288 * @return void
1290 function feedback_delete_template($template) {
1291 global $DB;
1293 //deleting the files from the item is done by feedback_delete_item
1294 if ($t_items = $DB->get_records("feedback_item", array("template"=>$template->id))) {
1295 foreach ($t_items as $t_item) {
1296 feedback_delete_item($t_item->id, false, $template);
1299 $DB->delete_records("feedback_template", array("id"=>$template->id));
1303 * creates new feedback_item-records from template.
1304 * if $deleteold is set true so the existing items of the given feedback will be deleted
1305 * if $deleteold is set false so the new items will be appanded to the old items
1307 * @global object
1308 * @uses CONTEXT_COURSE
1309 * @uses CONTEXT_MODULE
1310 * @param object $feedback
1311 * @param int $templateid
1312 * @param boolean $deleteold
1314 function feedback_items_from_template($feedback, $templateid, $deleteold = false) {
1315 global $DB, $CFG;
1317 require_once($CFG->libdir.'/completionlib.php');
1319 $fs = get_file_storage();
1321 if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
1322 return false;
1324 //get all templateitems
1325 if (!$templitems = $DB->get_records('feedback_item', array('template'=>$templateid))) {
1326 return false;
1329 //files in the template_item are in the context of the current course
1330 //files in the feedback_item are in the feedback_context of the feedback
1331 if ($template->ispublic) {
1332 $s_context = context_system::instance();
1333 } else {
1334 $s_context = context_course::instance($feedback->course);
1336 $course = $DB->get_record('course', array('id'=>$feedback->course));
1337 $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1338 $f_context = context_module::instance($cm->id);
1340 //if deleteold then delete all old items before
1341 //get all items
1342 if ($deleteold) {
1343 if ($feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1344 //delete all items of this feedback
1345 foreach ($feedbackitems as $item) {
1346 feedback_delete_item($item->id, false);
1349 $params = array('feedback'=>$feedback->id);
1350 if ($completeds = $DB->get_records('feedback_completed', $params)) {
1351 $completion = new completion_info($course);
1352 foreach ($completeds as $completed) {
1353 $DB->delete_records('feedback_completed', array('id' => $completed->id));
1354 // Update completion state
1355 if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC &&
1356 $feedback->completionsubmit) {
1357 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1361 $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedback->id));
1363 $positionoffset = 0;
1364 } else {
1365 //if the old items are kept the new items will be appended
1366 //therefor the new position has an offset
1367 $positionoffset = $DB->count_records('feedback_item', array('feedback'=>$feedback->id));
1370 //create items of this new template
1371 //depend items we are storing temporary in an mapping list array(new id => dependitem)
1372 //we also store a mapping of all items array(oldid => newid)
1373 $dependitemsmap = array();
1374 $itembackup = array();
1375 foreach ($templitems as $t_item) {
1376 $item = clone($t_item);
1377 unset($item->id);
1378 $item->feedback = $feedback->id;
1379 $item->template = 0;
1380 $item->position = $item->position + $positionoffset;
1382 $item->id = $DB->insert_record('feedback_item', $item);
1384 //moving the files to the new item
1385 $templatefiles = $fs->get_area_files($s_context->id,
1386 'mod_feedback',
1387 'template',
1388 $t_item->id,
1389 "id",
1390 false);
1391 if ($templatefiles) {
1392 foreach ($templatefiles as $tfile) {
1393 $file_record = new stdClass();
1394 $file_record->contextid = $f_context->id;
1395 $file_record->component = 'mod_feedback';
1396 $file_record->filearea = 'item';
1397 $file_record->itemid = $item->id;
1398 $fs->create_file_from_storedfile($file_record, $tfile);
1402 $itembackup[$t_item->id] = $item->id;
1403 if ($item->dependitem) {
1404 $dependitemsmap[$item->id] = $item->dependitem;
1408 //remapping the dependency
1409 foreach ($dependitemsmap as $key => $dependitem) {
1410 $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1411 $newitem->dependitem = $itembackup[$newitem->dependitem];
1412 $DB->update_record('feedback_item', $newitem);
1417 * get the list of available templates.
1418 * if the $onlyown param is set true so only templates from own course will be served
1419 * this is important for droping templates
1421 * @global object
1422 * @param object $course
1423 * @param string $onlyownorpublic
1424 * @return array the template recordsets
1426 function feedback_get_template_list($course, $onlyownorpublic = '') {
1427 global $DB, $CFG;
1429 switch($onlyownorpublic) {
1430 case '':
1431 $templates = $DB->get_records_select('feedback_template',
1432 'course = ? OR ispublic = 1',
1433 array($course->id),
1434 'name');
1435 break;
1436 case 'own':
1437 $templates = $DB->get_records('feedback_template',
1438 array('course'=>$course->id),
1439 'name');
1440 break;
1441 case 'public':
1442 $templates = $DB->get_records('feedback_template', array('ispublic'=>1), 'name');
1443 break;
1445 return $templates;
1448 ////////////////////////////////////////////////
1449 //Handling der Items
1450 ////////////////////////////////////////////////
1451 ////////////////////////////////////////////////
1454 * load the lib.php from item-plugin-dir and returns the instance of the itemclass
1456 * @param string $typ
1457 * @return feedback_item_base the instance of itemclass
1459 function feedback_get_item_class($typ) {
1460 global $CFG;
1462 require_once($CFG->dirroot.'/mod/feedback/item/feedback_item_class.php');
1464 //get the class of item-typ
1465 $itemclass = 'feedback_item_'.$typ;
1466 //get the instance of item-class
1467 if (!class_exists($itemclass)) {
1468 require_once($CFG->dirroot.'/mod/feedback/item/'.$typ.'/lib.php');
1470 return new $itemclass();
1474 * load the available item plugins from given subdirectory of $CFG->dirroot
1475 * the default is "mod/feedback/item"
1477 * @global object
1478 * @param string $dir the subdir
1479 * @return array pluginnames as string
1481 function feedback_load_feedback_items($dir = 'mod/feedback/item') {
1482 global $CFG;
1483 $names = get_list_of_plugins($dir);
1484 $ret_names = array();
1486 foreach ($names as $name) {
1487 require_once($CFG->dirroot.'/'.$dir.'/'.$name.'/lib.php');
1488 if (class_exists('feedback_item_'.$name)) {
1489 $ret_names[] = $name;
1492 return $ret_names;
1496 * load the available item plugins to use as dropdown-options
1498 * @global object
1499 * @return array pluginnames as string
1501 function feedback_load_feedback_items_options() {
1502 global $CFG;
1504 $feedback_options = array("pagebreak" => get_string('add_pagebreak', 'feedback'));
1506 if (!$feedback_names = feedback_load_feedback_items('mod/feedback/item')) {
1507 return array();
1510 foreach ($feedback_names as $fn) {
1511 $feedback_options[$fn] = get_string($fn, 'feedback');
1513 asort($feedback_options);
1514 return $feedback_options;
1518 * load the available items for the depend item dropdown list shown in the edit_item form
1520 * @global object
1521 * @param object $feedback
1522 * @param object $item the item of the edit_item form
1523 * @return array all items except the item $item, labels and pagebreaks
1525 function feedback_get_depend_candidates_for_item($feedback, $item) {
1526 global $DB;
1527 //all items for dependitem
1528 $where = "feedback = ? AND typ != 'pagebreak' AND hasvalue = 1";
1529 $params = array($feedback->id);
1530 if (isset($item->id) AND $item->id) {
1531 $where .= ' AND id != ?';
1532 $params[] = $item->id;
1534 $dependitems = array(0 => get_string('choose'));
1535 $feedbackitems = $DB->get_records_select_menu('feedback_item',
1536 $where,
1537 $params,
1538 'position',
1539 'id, label');
1541 if (!$feedbackitems) {
1542 return $dependitems;
1544 //adding the choose-option
1545 foreach ($feedbackitems as $key => $val) {
1546 if (trim(strval($val)) !== '') {
1547 $dependitems[$key] = format_string($val);
1550 return $dependitems;
1554 * @deprecated since 3.1
1556 function feedback_create_item() {
1557 throw new coding_exception('feedback_create_item() can not be used anymore.');
1561 * save the changes of a given item.
1563 * @global object
1564 * @param object $item
1565 * @return boolean
1567 function feedback_update_item($item) {
1568 global $DB;
1569 return $DB->update_record("feedback_item", $item);
1573 * deletes an item and also deletes all related values
1575 * @global object
1576 * @uses CONTEXT_MODULE
1577 * @param int $itemid
1578 * @param boolean $renumber should the kept items renumbered Yes/No
1579 * @param object $template if the template is given so the items are bound to it
1580 * @return void
1582 function feedback_delete_item($itemid, $renumber = true, $template = false) {
1583 global $DB;
1585 $item = $DB->get_record('feedback_item', array('id'=>$itemid));
1587 //deleting the files from the item
1588 $fs = get_file_storage();
1590 if ($template) {
1591 if ($template->ispublic) {
1592 $context = context_system::instance();
1593 } else {
1594 $context = context_course::instance($template->course);
1596 $templatefiles = $fs->get_area_files($context->id,
1597 'mod_feedback',
1598 'template',
1599 $item->id,
1600 "id",
1601 false);
1603 if ($templatefiles) {
1604 $fs->delete_area_files($context->id, 'mod_feedback', 'template', $item->id);
1606 } else {
1607 if (!$cm = get_coursemodule_from_instance('feedback', $item->feedback)) {
1608 return false;
1610 $context = context_module::instance($cm->id);
1612 $itemfiles = $fs->get_area_files($context->id,
1613 'mod_feedback',
1614 'item',
1615 $item->id,
1616 "id", false);
1618 if ($itemfiles) {
1619 $fs->delete_area_files($context->id, 'mod_feedback', 'item', $item->id);
1623 $DB->delete_records("feedback_value", array("item"=>$itemid));
1624 $DB->delete_records("feedback_valuetmp", array("item"=>$itemid));
1626 //remove all depends
1627 $DB->set_field('feedback_item', 'dependvalue', '', array('dependitem'=>$itemid));
1628 $DB->set_field('feedback_item', 'dependitem', 0, array('dependitem'=>$itemid));
1630 $DB->delete_records("feedback_item", array("id"=>$itemid));
1631 if ($renumber) {
1632 feedback_renumber_items($item->feedback);
1637 * deletes all items of the given feedbackid
1639 * @global object
1640 * @param int $feedbackid
1641 * @return void
1643 function feedback_delete_all_items($feedbackid) {
1644 global $DB, $CFG;
1645 require_once($CFG->libdir.'/completionlib.php');
1647 if (!$feedback = $DB->get_record('feedback', array('id'=>$feedbackid))) {
1648 return false;
1651 if (!$cm = get_coursemodule_from_instance('feedback', $feedback->id)) {
1652 return false;
1655 if (!$course = $DB->get_record('course', array('id'=>$feedback->course))) {
1656 return false;
1659 if (!$items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid))) {
1660 return;
1662 foreach ($items as $item) {
1663 feedback_delete_item($item->id, false);
1665 if ($completeds = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
1666 $completion = new completion_info($course);
1667 foreach ($completeds as $completed) {
1668 $DB->delete_records('feedback_completed', array('id' => $completed->id));
1669 // Update completion state
1670 if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC &&
1671 $feedback->completionsubmit) {
1672 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1677 $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedbackid));
1682 * this function toggled the item-attribute required (yes/no)
1684 * @global object
1685 * @param object $item
1686 * @return boolean
1688 function feedback_switch_item_required($item) {
1689 global $DB, $CFG;
1691 $itemobj = feedback_get_item_class($item->typ);
1693 if ($itemobj->can_switch_require()) {
1694 $new_require_val = (int)!(bool)$item->required;
1695 $params = array('id'=>$item->id);
1696 $DB->set_field('feedback_item', 'required', $new_require_val, $params);
1698 return true;
1702 * renumbers all items of the given feedbackid
1704 * @global object
1705 * @param int $feedbackid
1706 * @return void
1708 function feedback_renumber_items($feedbackid) {
1709 global $DB;
1711 $items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid), 'position');
1712 $pos = 1;
1713 if ($items) {
1714 foreach ($items as $item) {
1715 $DB->set_field('feedback_item', 'position', $pos, array('id'=>$item->id));
1716 $pos++;
1722 * this decreases the position of the given item
1724 * @global object
1725 * @param object $item
1726 * @return bool
1728 function feedback_moveup_item($item) {
1729 global $DB;
1731 if ($item->position == 1) {
1732 return true;
1735 $params = array('feedback'=>$item->feedback);
1736 if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1737 return false;
1740 $itembefore = null;
1741 foreach ($items as $i) {
1742 if ($i->id == $item->id) {
1743 if (is_null($itembefore)) {
1744 return true;
1746 $itembefore->position = $item->position;
1747 $item->position--;
1748 feedback_update_item($itembefore);
1749 feedback_update_item($item);
1750 feedback_renumber_items($item->feedback);
1751 return true;
1753 $itembefore = $i;
1755 return false;
1759 * this increased the position of the given item
1761 * @global object
1762 * @param object $item
1763 * @return bool
1765 function feedback_movedown_item($item) {
1766 global $DB;
1768 $params = array('feedback'=>$item->feedback);
1769 if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1770 return false;
1773 $movedownitem = null;
1774 foreach ($items as $i) {
1775 if (!is_null($movedownitem) AND $movedownitem->id == $item->id) {
1776 $movedownitem->position = $i->position;
1777 $i->position--;
1778 feedback_update_item($movedownitem);
1779 feedback_update_item($i);
1780 feedback_renumber_items($item->feedback);
1781 return true;
1783 $movedownitem = $i;
1785 return false;
1789 * here the position of the given item will be set to the value in $pos
1791 * @global object
1792 * @param object $moveitem
1793 * @param int $pos
1794 * @return boolean
1796 function feedback_move_item($moveitem, $pos) {
1797 global $DB;
1799 $params = array('feedback'=>$moveitem->feedback);
1800 if (!$allitems = $DB->get_records('feedback_item', $params, 'position')) {
1801 return false;
1803 if (is_array($allitems)) {
1804 $index = 1;
1805 foreach ($allitems as $item) {
1806 if ($index == $pos) {
1807 $index++;
1809 if ($item->id == $moveitem->id) {
1810 $moveitem->position = $pos;
1811 feedback_update_item($moveitem);
1812 continue;
1814 $item->position = $index;
1815 feedback_update_item($item);
1816 $index++;
1818 return true;
1820 return false;
1824 * @deprecated since Moodle 3.1
1826 function feedback_print_item_preview() {
1827 throw new coding_exception('feedback_print_item_preview() can not be used anymore. '
1828 . 'Items must implement complete_form_element().');
1832 * @deprecated since Moodle 3.1
1834 function feedback_print_item_complete() {
1835 throw new coding_exception('feedback_print_item_complete() can not be used anymore. '
1836 . 'Items must implement complete_form_element().');
1840 * @deprecated since Moodle 3.1
1842 function feedback_print_item_show_value() {
1843 throw new coding_exception('feedback_print_item_show_value() can not be used anymore. '
1844 . 'Items must implement complete_form_element().');
1848 * if the user completes a feedback and there is a pagebreak so the values are saved temporary.
1849 * the values are not saved permanently until the user click on save button
1851 * @global object
1852 * @param object $feedbackcompleted
1853 * @return object temporary saved completed-record
1855 function feedback_set_tmp_values($feedbackcompleted) {
1856 global $DB;
1858 //first we create a completedtmp
1859 $tmpcpl = new stdClass();
1860 foreach ($feedbackcompleted as $key => $value) {
1861 $tmpcpl->{$key} = $value;
1863 unset($tmpcpl->id);
1864 $tmpcpl->timemodified = time();
1865 $tmpcpl->id = $DB->insert_record('feedback_completedtmp', $tmpcpl);
1866 //get all values of original-completed
1867 if (!$values = $DB->get_records('feedback_value', array('completed'=>$feedbackcompleted->id))) {
1868 return;
1870 foreach ($values as $value) {
1871 unset($value->id);
1872 $value->completed = $tmpcpl->id;
1873 $DB->insert_record('feedback_valuetmp', $value);
1875 return $tmpcpl;
1879 * this saves the temporary saved values permanently
1881 * @global object
1882 * @param object $feedbackcompletedtmp the temporary completed
1883 * @param stdClass|null $feedbackcompleted the target completed
1884 * @return int the id of the completed
1886 function feedback_save_tmp_values($feedbackcompletedtmp, ?stdClass $feedbackcompleted = null) {
1887 global $DB;
1889 $tmpcplid = $feedbackcompletedtmp->id;
1890 if ($feedbackcompleted) {
1891 //first drop all existing values
1892 $DB->delete_records('feedback_value', array('completed'=>$feedbackcompleted->id));
1893 //update the current completed
1894 $feedbackcompleted->timemodified = time();
1895 $DB->update_record('feedback_completed', $feedbackcompleted);
1896 } else {
1897 $feedbackcompleted = clone($feedbackcompletedtmp);
1898 $feedbackcompleted->id = '';
1899 $feedbackcompleted->timemodified = time();
1900 $feedbackcompleted->id = $DB->insert_record('feedback_completed', $feedbackcompleted);
1903 $allitems = $DB->get_records('feedback_item', array('feedback' => $feedbackcompleted->feedback));
1905 //save all the new values from feedback_valuetmp
1906 //get all values of tmp-completed
1907 $params = array('completed'=>$feedbackcompletedtmp->id);
1908 $values = $DB->get_records('feedback_valuetmp', $params);
1909 foreach ($values as $value) {
1910 //check if there are depend items
1911 $item = $DB->get_record('feedback_item', array('id'=>$value->item));
1912 if ($item->dependitem > 0 && isset($allitems[$item->dependitem])) {
1913 $ditem = $allitems[$item->dependitem];
1914 while ($ditem !== null) {
1915 $check = feedback_compare_item_value($tmpcplid,
1916 $ditem,
1917 $item->dependvalue,
1918 true);
1919 if (!$check) {
1920 break;
1922 if ($ditem->dependitem > 0 && isset($allitems[$ditem->dependitem])) {
1923 $item = $ditem;
1924 $ditem = $allitems[$ditem->dependitem];
1925 } else {
1926 $ditem = null;
1930 } else {
1931 $check = true;
1933 if ($check) {
1934 unset($value->id);
1935 $value->completed = $feedbackcompleted->id;
1936 $DB->insert_record('feedback_value', $value);
1939 //drop all the tmpvalues
1940 $DB->delete_records('feedback_valuetmp', array('completed'=>$tmpcplid));
1941 $DB->delete_records('feedback_completedtmp', array('id'=>$tmpcplid));
1943 // Trigger event for the delete action we performed.
1944 $cm = get_coursemodule_from_instance('feedback', $feedbackcompleted->feedback);
1945 $event = \mod_feedback\event\response_submitted::create_from_record($feedbackcompleted, $cm);
1946 $event->trigger();
1947 return $feedbackcompleted->id;
1952 * @deprecated since Moodle 3.1
1954 function feedback_delete_completedtmp() {
1955 throw new coding_exception('feedback_delete_completedtmp() can not be used anymore.');
1959 ////////////////////////////////////////////////
1960 ////////////////////////////////////////////////
1961 ////////////////////////////////////////////////
1962 //functions to handle the pagebreaks
1963 ////////////////////////////////////////////////
1966 * this creates a pagebreak.
1967 * a pagebreak is a special kind of item
1969 * @global object
1970 * @param int $feedbackid
1971 * @return int|false false if there already is a pagebreak on last position or the id of the pagebreak-item
1973 function feedback_create_pagebreak($feedbackid) {
1974 global $DB;
1976 //check if there already is a pagebreak on the last position
1977 $lastposition = $DB->count_records('feedback_item', array('feedback'=>$feedbackid));
1978 if ($lastposition == feedback_get_last_break_position($feedbackid)) {
1979 return false;
1982 $item = new stdClass();
1983 $item->feedback = $feedbackid;
1985 $item->template=0;
1987 $item->name = '';
1989 $item->presentation = '';
1990 $item->hasvalue = 0;
1992 $item->typ = 'pagebreak';
1993 $item->position = $lastposition + 1;
1995 $item->required=0;
1997 return $DB->insert_record('feedback_item', $item);
2001 * get all positions of pagebreaks in the given feedback
2003 * @global object
2004 * @param int $feedbackid
2005 * @return array all ordered pagebreak positions
2007 function feedback_get_all_break_positions($feedbackid) {
2008 global $DB;
2010 $params = array('typ'=>'pagebreak', 'feedback'=>$feedbackid);
2011 $allbreaks = $DB->get_records_menu('feedback_item', $params, 'position', 'id, position');
2012 if (!$allbreaks) {
2013 return false;
2015 return array_values($allbreaks);
2019 * get the position of the last pagebreak
2021 * @param int $feedbackid
2022 * @return int the position of the last pagebreak
2024 function feedback_get_last_break_position($feedbackid) {
2025 if (!$allbreaks = feedback_get_all_break_positions($feedbackid)) {
2026 return false;
2028 return $allbreaks[count($allbreaks) - 1];
2032 * @deprecated since Moodle 3.1
2034 function feedback_get_page_to_continue() {
2035 throw new coding_exception('feedback_get_page_to_continue() can not be used anymore.');
2038 ////////////////////////////////////////////////
2039 ////////////////////////////////////////////////
2040 ////////////////////////////////////////////////
2041 //functions to handle the values
2042 ////////////////////////////////////////////////
2045 * @deprecated since Moodle 3.1
2047 function feedback_clean_input_value() {
2048 throw new coding_exception('feedback_clean_input_value() can not be used anymore. '
2049 . 'Items must implement complete_form_element().');
2054 * @deprecated since Moodle 3.1
2056 function feedback_save_values() {
2057 throw new coding_exception('feedback_save_values() can not be used anymore.');
2061 * @deprecated since Moodle 3.1
2063 function feedback_save_guest_values() {
2064 throw new coding_exception('feedback_save_guest_values() can not be used anymore.');
2068 * get the value from the given item related to the given completed.
2069 * the value can come as temporary or as permanently value. the deciding is done by $tmp
2071 * @global object
2072 * @param int $completeid
2073 * @param int $itemid
2074 * @param boolean $tmp
2075 * @return mixed the value, the type depends on plugin-definition
2077 function feedback_get_item_value($completedid, $itemid, $tmp = false) {
2078 global $DB;
2080 $tmpstr = $tmp ? 'tmp' : '';
2081 $params = array('completed'=>$completedid, 'item'=>$itemid);
2082 return $DB->get_field('feedback_value'.$tmpstr, 'value', $params);
2086 * compares the value of the itemid related to the completedid with the dependvalue.
2087 * this is used if a depend item is set.
2088 * the value can come as temporary or as permanently value. the deciding is done by $tmp.
2090 * @param int $completedid
2091 * @param stdClass|int $item
2092 * @param mixed $dependvalue
2093 * @param bool $tmp
2094 * @return bool
2096 function feedback_compare_item_value($completedid, $item, $dependvalue, $tmp = false) {
2097 global $DB;
2099 if (is_int($item)) {
2100 $item = $DB->get_record('feedback_item', array('id' => $item));
2103 $dbvalue = feedback_get_item_value($completedid, $item->id, $tmp);
2105 $itemobj = feedback_get_item_class($item->typ);
2106 return $itemobj->compare_value($item, $dbvalue, $dependvalue); //true or false
2110 * @deprecated since Moodle 3.1
2112 function feedback_check_values() {
2113 throw new coding_exception('feedback_check_values() can not be used anymore. '
2114 . 'Items must implement complete_form_element().');
2118 * @deprecated since Moodle 3.1
2120 function feedback_create_values() {
2121 throw new coding_exception('feedback_create_values() can not be used anymore.');
2125 * @deprecated since Moodle 3.1
2127 function feedback_update_values() {
2128 throw new coding_exception('feedback_update_values() can not be used anymore.');
2132 * get the values of an item depending on the given groupid.
2133 * if the feedback is anonymous so the values are shuffled
2135 * @global object
2136 * @global object
2137 * @param object $item
2138 * @param int $groupid
2139 * @param int $courseid
2140 * @param bool $ignore_empty if this is set true so empty values are not delivered
2141 * @return array the value-records
2143 function feedback_get_group_values($item,
2144 $groupid = false,
2145 $courseid = false,
2146 $ignore_empty = false) {
2148 global $CFG, $DB;
2150 //if the groupid is given?
2151 if (intval($groupid) > 0) {
2152 $params = array();
2153 if ($ignore_empty) {
2154 $value = $DB->sql_compare_text('fbv.value');
2155 $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2156 $params += array('emptyvalue' => '', 'zerovalue' => '0');
2157 } else {
2158 $ignore_empty_select = "";
2161 $query = 'SELECT fbv . *
2162 FROM {feedback_value} fbv, {feedback_completed} fbc, {groups_members} gm
2163 WHERE fbv.item = :itemid
2164 AND fbv.completed = fbc.id
2165 AND fbc.userid = gm.userid
2166 '.$ignore_empty_select.'
2167 AND gm.groupid = :groupid
2168 ORDER BY fbc.timemodified';
2169 $params += array('itemid' => $item->id, 'groupid' => $groupid);
2170 $values = $DB->get_records_sql($query, $params);
2172 } else {
2173 $params = array();
2174 if ($ignore_empty) {
2175 $value = $DB->sql_compare_text('value');
2176 $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2177 $params += array('emptyvalue' => '', 'zerovalue' => '0');
2178 } else {
2179 $ignore_empty_select = "";
2182 if ($courseid) {
2183 $select = "item = :itemid AND course_id = :courseid ".$ignore_empty_select;
2184 $params += array('itemid' => $item->id, 'courseid' => $courseid);
2185 $values = $DB->get_records_select('feedback_value', $select, $params);
2186 } else {
2187 $select = "item = :itemid ".$ignore_empty_select;
2188 $params += array('itemid' => $item->id);
2189 $values = $DB->get_records_select('feedback_value', $select, $params);
2192 $params = array('id'=>$item->feedback);
2193 if ($DB->get_field('feedback', 'anonymous', $params) == FEEDBACK_ANONYMOUS_YES) {
2194 if (is_array($values)) {
2195 shuffle($values);
2198 return $values;
2202 * check for multiple_submit = false.
2203 * if the feedback is global so the courseid must be given
2205 * @global object
2206 * @global object
2207 * @param int $feedbackid
2208 * @param int $courseid
2209 * @return boolean true if the feedback already is submitted otherwise false
2211 function feedback_is_already_submitted($feedbackid, $courseid = false) {
2212 global $USER, $DB;
2214 if (!isloggedin() || isguestuser()) {
2215 return false;
2218 $params = array('userid' => $USER->id, 'feedback' => $feedbackid);
2219 if ($courseid) {
2220 $params['courseid'] = $courseid;
2222 return $DB->record_exists('feedback_completed', $params);
2226 * @deprecated since Moodle 3.1. Use feedback_get_current_completed_tmp() or feedback_get_last_completed.
2228 function feedback_get_current_completed() {
2229 throw new coding_exception('feedback_get_current_completed() can not be used anymore. Please ' .
2230 'use either feedback_get_current_completed_tmp() or feedback_get_last_completed()');
2234 * get the completeds depending on the given groupid.
2236 * @global object
2237 * @global object
2238 * @param object $feedback
2239 * @param int $groupid
2240 * @param int $courseid
2241 * @return mixed array of found completeds otherwise false
2243 function feedback_get_completeds_group($feedback, $groupid = false, $courseid = false) {
2244 global $CFG, $DB;
2246 if (intval($groupid) > 0) {
2247 $query = "SELECT fbc.*
2248 FROM {feedback_completed} fbc, {groups_members} gm
2249 WHERE fbc.feedback = ?
2250 AND gm.groupid = ?
2251 AND fbc.userid = gm.userid";
2252 if ($values = $DB->get_records_sql($query, array($feedback->id, $groupid))) {
2253 return $values;
2254 } else {
2255 return false;
2257 } else {
2258 if ($courseid) {
2259 $query = "SELECT DISTINCT fbc.*
2260 FROM {feedback_completed} fbc, {feedback_value} fbv
2261 WHERE fbc.id = fbv.completed
2262 AND fbc.feedback = ?
2263 AND fbv.course_id = ?
2264 ORDER BY random_response";
2265 if ($values = $DB->get_records_sql($query, array($feedback->id, $courseid))) {
2266 return $values;
2267 } else {
2268 return false;
2270 } else {
2271 if ($values = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
2272 return $values;
2273 } else {
2274 return false;
2281 * get the count of completeds depending on the given groupid.
2283 * @global object
2284 * @global object
2285 * @param object $feedback
2286 * @param int $groupid
2287 * @param int $courseid
2288 * @return mixed count of completeds or false
2290 function feedback_get_completeds_group_count($feedback, $groupid = false, $courseid = false) {
2291 global $CFG, $DB;
2293 if ($courseid > 0 AND !$groupid <= 0) {
2294 $sql = "SELECT id, COUNT(item) AS ci
2295 FROM {feedback_value}
2296 WHERE course_id = ?
2297 GROUP BY item ORDER BY ci DESC";
2298 if ($foundrecs = $DB->get_records_sql($sql, array($courseid))) {
2299 $foundrecs = array_values($foundrecs);
2300 return $foundrecs[0]->ci;
2302 return false;
2304 if ($values = feedback_get_completeds_group($feedback, $groupid)) {
2305 return count($values);
2306 } else {
2307 return false;
2312 * deletes all completed-recordsets from a feedback.
2313 * all related data such as values also will be deleted
2315 * @param stdClass|int $feedback
2316 * @param stdClass|cm_info $cm
2317 * @param stdClass $course
2318 * @return void
2320 function feedback_delete_all_completeds($feedback, $cm = null, $course = null) {
2321 global $DB;
2323 if (is_int($feedback)) {
2324 $feedback = $DB->get_record('feedback', array('id' => $feedback));
2327 if (!$completeds = $DB->get_records('feedback_completed', array('feedback' => $feedback->id))) {
2328 return;
2331 if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2332 return false;
2335 if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2336 return false;
2339 foreach ($completeds as $completed) {
2340 feedback_delete_completed($completed, $feedback, $cm, $course);
2345 * deletes a completed given by completedid.
2346 * all related data such values or tracking data also will be deleted
2348 * @param int|stdClass $completed
2349 * @param stdClass $feedback
2350 * @param stdClass|cm_info $cm
2351 * @param stdClass $course
2352 * @return boolean
2354 function feedback_delete_completed($completed, $feedback = null, $cm = null, $course = null) {
2355 global $DB, $CFG;
2356 require_once($CFG->libdir.'/completionlib.php');
2358 if (!isset($completed->id)) {
2359 if (!$completed = $DB->get_record('feedback_completed', array('id' => $completed))) {
2360 return false;
2364 if (!$feedback && !($feedback = $DB->get_record('feedback', array('id' => $completed->feedback)))) {
2365 return false;
2368 if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2369 return false;
2372 if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2373 return false;
2376 //first we delete all related values
2377 $DB->delete_records('feedback_value', array('completed' => $completed->id));
2379 // Delete the completed record.
2380 $return = $DB->delete_records('feedback_completed', array('id' => $completed->id));
2382 // Update completion state
2383 $completion = new completion_info($course);
2384 if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC && $feedback->completionsubmit) {
2385 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
2387 // Trigger event for the delete action we performed.
2388 $event = \mod_feedback\event\response_deleted::create_from_record($completed, $cm, $feedback);
2389 $event->trigger();
2391 return $return;
2394 ////////////////////////////////////////////////
2395 ////////////////////////////////////////////////
2396 ////////////////////////////////////////////////
2397 //functions to handle sitecourse mapping
2398 ////////////////////////////////////////////////
2401 * @deprecated since 3.1
2403 function feedback_is_course_in_sitecourse_map() {
2404 throw new coding_exception('feedback_is_course_in_sitecourse_map() can not be used anymore.');
2408 * @deprecated since 3.1
2410 function feedback_is_feedback_in_sitecourse_map() {
2411 throw new coding_exception('feedback_is_feedback_in_sitecourse_map() can not be used anymore.');
2415 * gets the feedbacks from table feedback_sitecourse_map.
2416 * this is used to show the global feedbacks on the feedback block
2417 * all feedbacks with the following criteria will be selected:<br />
2419 * 1) all feedbacks which id are listed together with the courseid in sitecoursemap and<br />
2420 * 2) all feedbacks which not are listed in sitecoursemap
2422 * @global object
2423 * @param int $courseid
2424 * @return array the feedback-records
2426 function feedback_get_feedbacks_from_sitecourse_map($courseid) {
2427 global $DB;
2429 //first get all feedbacks listed in sitecourse_map with named courseid
2430 $sql = "SELECT f.id AS id,
2431 cm.id AS cmid,
2432 f.name AS name,
2433 f.timeopen AS timeopen,
2434 f.timeclose AS timeclose
2435 FROM {feedback} f, {course_modules} cm, {feedback_sitecourse_map} sm, {modules} m
2436 WHERE f.id = cm.instance
2437 AND f.course = '".SITEID."'
2438 AND m.id = cm.module
2439 AND m.name = 'feedback'
2440 AND sm.courseid = ?
2441 AND sm.feedbackid = f.id";
2443 if (!$feedbacks1 = $DB->get_records_sql($sql, array($courseid))) {
2444 $feedbacks1 = array();
2447 //second get all feedbacks not listed in sitecourse_map
2448 $feedbacks2 = array();
2449 $sql = "SELECT f.id AS id,
2450 cm.id AS cmid,
2451 f.name AS name,
2452 f.timeopen AS timeopen,
2453 f.timeclose AS timeclose
2454 FROM {feedback} f, {course_modules} cm, {modules} m
2455 WHERE f.id = cm.instance
2456 AND f.course = '".SITEID."'
2457 AND m.id = cm.module
2458 AND m.name = 'feedback'";
2459 if (!$allfeedbacks = $DB->get_records_sql($sql)) {
2460 $allfeedbacks = array();
2462 foreach ($allfeedbacks as $a) {
2463 if (!$DB->record_exists('feedback_sitecourse_map', array('feedbackid'=>$a->id))) {
2464 $feedbacks2[] = $a;
2468 $feedbacks = array_merge($feedbacks1, $feedbacks2);
2469 $modinfo = get_fast_modinfo(SITEID);
2470 return array_filter($feedbacks, function($f) use ($modinfo) {
2471 return ($cm = $modinfo->get_cm($f->cmid)) && $cm->uservisible;
2477 * Gets the courses from table feedback_sitecourse_map
2479 * @param int $feedbackid
2480 * @return array the course-records
2482 function feedback_get_courses_from_sitecourse_map($feedbackid) {
2483 global $DB;
2485 $sql = "SELECT c.id, c.fullname, c.shortname
2486 FROM {feedback_sitecourse_map} f, {course} c
2487 WHERE c.id = f.courseid
2488 AND f.feedbackid = ?
2489 ORDER BY c.fullname";
2491 return $DB->get_records_sql($sql, array($feedbackid));
2496 * Updates the course mapping for the feedback
2498 * @param stdClass $feedback
2499 * @param array $courses array of course ids
2501 function feedback_update_sitecourse_map($feedback, $courses) {
2502 global $DB;
2503 if (empty($courses)) {
2504 $courses = array();
2506 $currentmapping = $DB->get_fieldset_select('feedback_sitecourse_map', 'courseid', 'feedbackid=?', array($feedback->id));
2507 foreach (array_diff($courses, $currentmapping) as $courseid) {
2508 $DB->insert_record('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2510 foreach (array_diff($currentmapping, $courses) as $courseid) {
2511 $DB->delete_records('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2513 // TODO MDL-53574 add events.
2517 * @deprecated since 3.1
2519 function feedback_clean_up_sitecourse_map() {
2520 throw new coding_exception('feedback_clean_up_sitecourse_map() can not be used anymore.');
2523 ////////////////////////////////////////////////
2524 ////////////////////////////////////////////////
2525 ////////////////////////////////////////////////
2526 //not relatable functions
2527 ////////////////////////////////////////////////
2530 * @deprecated since 3.1
2532 function feedback_print_numeric_option_list() {
2533 throw new coding_exception('feedback_print_numeric_option_list() can not be used anymore.');
2537 * sends an email to the teachers of the course where the given feedback is placed.
2539 * @global object
2540 * @global object
2541 * @uses FEEDBACK_ANONYMOUS_NO
2542 * @uses FORMAT_PLAIN
2543 * @param object $cm the coursemodule-record
2544 * @param object $feedback
2545 * @param object $course
2546 * @param stdClass|int $user
2547 * @param stdClass $completed record from feedback_completed if known
2548 * @return void
2550 function feedback_send_email($cm, $feedback, $course, $user, $completed = null) {
2551 global $CFG, $DB, $PAGE;
2553 if ($feedback->email_notification == 0) { // No need to do anything
2554 return;
2557 if (!is_object($user)) {
2558 $user = $DB->get_record('user', array('id' => $user));
2561 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
2562 $groupmode = $cm->groupmode;
2563 } else {
2564 $groupmode = $course->groupmode;
2567 if ($groupmode == SEPARATEGROUPS) {
2568 $groups = $DB->get_records_sql_menu("SELECT g.name, g.id
2569 FROM {groups} g, {groups_members} m
2570 WHERE g.courseid = ?
2571 AND g.id = m.groupid
2572 AND m.userid = ?
2573 ORDER BY name ASC", array($course->id, $user->id));
2574 $groups = array_values($groups);
2576 $teachers = feedback_get_receivemail_users($cm->id, $groups);
2577 } else {
2578 $teachers = feedback_get_receivemail_users($cm->id);
2581 if ($teachers) {
2583 $strfeedbacks = get_string('modulenameplural', 'feedback');
2584 $strfeedback = get_string('modulename', 'feedback');
2586 if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
2587 $printusername = fullname($user);
2588 } else {
2589 $printusername = get_string('anonymous_user', 'feedback');
2592 foreach ($teachers as $teacher) {
2593 $info = new stdClass();
2594 $info->username = $printusername;
2595 $info->feedback = format_string($feedback->name, true);
2596 $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?'.
2597 'id='.$cm->id.'&'.
2598 'userid=' . $user->id;
2599 if ($completed) {
2600 $info->url .= '&showcompleted=' . $completed->id;
2601 if ($feedback->course == SITEID) {
2602 // Course where feedback was completed (for site feedbacks only).
2603 $info->url .= '&courseid=' . $completed->courseid;
2607 $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
2609 $postsubject = get_string('feedbackcompleted', 'feedback', $a);
2610 $posttext = feedback_send_email_text($info, $course);
2612 if ($teacher->mailformat == 1) {
2613 $posthtml = feedback_send_email_html($info, $course, $cm);
2614 } else {
2615 $posthtml = '';
2618 $customdata = [
2619 'cmid' => $cm->id,
2620 'instance' => $feedback->id,
2622 if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
2623 $eventdata = new \core\message\message();
2624 $eventdata->anonymous = false;
2625 $eventdata->courseid = $course->id;
2626 $eventdata->name = 'submission';
2627 $eventdata->component = 'mod_feedback';
2628 $eventdata->userfrom = $user;
2629 $eventdata->userto = $teacher;
2630 $eventdata->subject = $postsubject;
2631 $eventdata->fullmessage = $posttext;
2632 $eventdata->fullmessageformat = FORMAT_PLAIN;
2633 $eventdata->fullmessagehtml = $posthtml;
2634 $eventdata->smallmessage = '';
2635 $eventdata->courseid = $course->id;
2636 $eventdata->contexturl = $info->url;
2637 $eventdata->contexturlname = $info->feedback;
2638 // User image.
2639 $userpicture = new user_picture($user);
2640 $userpicture->size = 1; // Use f1 size.
2641 $userpicture->includetoken = $teacher->id; // Generate an out-of-session token for the user receiving the message.
2642 $customdata['notificationiconurl'] = $userpicture->get_url($PAGE)->out(false);
2643 $eventdata->customdata = $customdata;
2644 message_send($eventdata);
2645 } else {
2646 $eventdata = new \core\message\message();
2647 $eventdata->anonymous = true;
2648 $eventdata->courseid = $course->id;
2649 $eventdata->name = 'submission';
2650 $eventdata->component = 'mod_feedback';
2651 $eventdata->userfrom = $teacher;
2652 $eventdata->userto = $teacher;
2653 $eventdata->subject = $postsubject;
2654 $eventdata->fullmessage = $posttext;
2655 $eventdata->fullmessageformat = FORMAT_PLAIN;
2656 $eventdata->fullmessagehtml = $posthtml;
2657 $eventdata->smallmessage = '';
2658 $eventdata->courseid = $course->id;
2659 $eventdata->contexturl = $info->url;
2660 $eventdata->contexturlname = $info->feedback;
2661 // Feedback icon if can be easily reachable.
2662 $customdata['notificationiconurl'] = ($cm instanceof cm_info) ? $cm->get_icon_url()->out() : '';
2663 $eventdata->customdata = $customdata;
2664 message_send($eventdata);
2671 * sends an email to the teachers of the course where the given feedback is placed.
2673 * @global object
2674 * @uses FORMAT_PLAIN
2675 * @param object $cm the coursemodule-record
2676 * @param object $feedback
2677 * @param object $course
2678 * @return void
2680 function feedback_send_email_anonym($cm, $feedback, $course) {
2681 global $CFG;
2683 if ($feedback->email_notification == 0) { // No need to do anything
2684 return;
2687 $teachers = feedback_get_receivemail_users($cm->id);
2689 if ($teachers) {
2691 $strfeedbacks = get_string('modulenameplural', 'feedback');
2692 $strfeedback = get_string('modulename', 'feedback');
2693 $printusername = get_string('anonymous_user', 'feedback');
2695 foreach ($teachers as $teacher) {
2696 $info = new stdClass();
2697 $info->username = $printusername;
2698 $info->feedback = format_string($feedback->name, true);
2699 $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?id=' . $cm->id;
2701 $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
2703 $postsubject = get_string('feedbackcompleted', 'feedback', $a);
2704 $posttext = feedback_send_email_text($info, $course);
2706 if ($teacher->mailformat == 1) {
2707 $posthtml = feedback_send_email_html($info, $course, $cm);
2708 } else {
2709 $posthtml = '';
2712 $eventdata = new \core\message\message();
2713 $eventdata->anonymous = true;
2714 $eventdata->courseid = $course->id;
2715 $eventdata->name = 'submission';
2716 $eventdata->component = 'mod_feedback';
2717 $eventdata->userfrom = $teacher;
2718 $eventdata->userto = $teacher;
2719 $eventdata->subject = $postsubject;
2720 $eventdata->fullmessage = $posttext;
2721 $eventdata->fullmessageformat = FORMAT_PLAIN;
2722 $eventdata->fullmessagehtml = $posthtml;
2723 $eventdata->smallmessage = '';
2724 $eventdata->courseid = $course->id;
2725 $eventdata->contexturl = $info->url;
2726 $eventdata->contexturlname = $info->feedback;
2727 $eventdata->customdata = [
2728 'cmid' => $cm->id,
2729 'instance' => $feedback->id,
2730 'notificationiconurl' => ($cm instanceof cm_info) ? $cm->get_icon_url()->out() : '', // Performance wise.
2733 message_send($eventdata);
2739 * send the text-part of the email
2741 * @param object $info includes some infos about the feedback you want to send
2742 * @param object $course
2743 * @return string the text you want to post
2745 function feedback_send_email_text($info, $course) {
2746 $coursecontext = context_course::instance($course->id);
2747 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2748 $posttext = $courseshortname.' -> '.get_string('modulenameplural', 'feedback').' -> '.
2749 $info->feedback."\n";
2750 $posttext .= '---------------------------------------------------------------------'."\n";
2751 $posttext .= get_string("emailteachermail", "feedback", $info)."\n";
2752 $posttext .= '---------------------------------------------------------------------'."\n";
2753 return $posttext;
2758 * send the html-part of the email
2760 * @global object
2761 * @param object $info includes some infos about the feedback you want to send
2762 * @param object $course
2763 * @return string the text you want to post
2765 function feedback_send_email_html($info, $course, $cm) {
2766 global $CFG;
2767 $coursecontext = context_course::instance($course->id);
2768 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2769 $course_url = $CFG->wwwroot.'/course/view.php?id='.$course->id;
2770 $feedback_all_url = $CFG->wwwroot.'/mod/feedback/index.php?id='.$course->id;
2771 $feedback_url = $CFG->wwwroot.'/mod/feedback/view.php?id='.$cm->id;
2773 $posthtml = '<p><font face="sans-serif">'.
2774 '<a href="'.$course_url.'">'.$courseshortname.'</a> ->'.
2775 '<a href="'.$feedback_all_url.'">'.get_string('modulenameplural', 'feedback').'</a> ->'.
2776 '<a href="'.$feedback_url.'">'.$info->feedback.'</a></font></p>';
2777 $posthtml .= '<hr /><font face="sans-serif">';
2778 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'feedback', $info).'</p>';
2779 $posthtml .= '</font><hr />';
2780 return $posthtml;
2784 * @param string $url
2785 * @return string
2787 function feedback_encode_target_url($url) {
2788 if (strpos($url, '?')) {
2789 list($part1, $part2) = explode('?', $url, 2); //maximal 2 parts
2790 return $part1 . '?' . htmlentities($part2, ENT_COMPAT);
2791 } else {
2792 return $url;
2797 * Adds module specific settings to the settings block
2799 * @param settings_navigation $settings The settings navigation object
2800 * @param navigation_node $feedbacknode The node to add module settings to
2802 function feedback_extend_settings_navigation(settings_navigation $settings, navigation_node $feedbacknode) {
2803 $hassecondary = $settings->get_page()->has_secondary_navigation();
2804 if (!$context = context_module::instance($settings->get_page()->cm->id, IGNORE_MISSING)) {
2805 throw new \moodle_exception('badcontext');
2808 if (has_capability('mod/feedback:edititems', $context)) {
2809 $questionnode = $feedbacknode->add(get_string('questions', 'feedback'), null,
2810 navigation_node::TYPE_CUSTOM, null, 'questionnode');
2811 $questionnode->add(get_string('edit_items', 'feedback'),
2812 new moodle_url('/mod/feedback/edit.php', ['id' => $settings->get_page()->cm->id]));
2814 $questionnode->add(get_string('export_questions', 'feedback'),
2815 new moodle_url('/mod/feedback/export.php', ['id' => $settings->get_page()->cm->id, 'action' => 'exportfile']));
2817 $questionnode->add(get_string('import_questions', 'feedback'),
2818 new moodle_url('/mod/feedback/import.php', ['id' => $settings->get_page()->cm->id]));
2820 $feedbacknode->add(get_string('templates', 'feedback'),
2821 new moodle_url('/mod/feedback/manage_templates.php', ['id' => $settings->get_page()->cm->id, 'mode' => 'manage']),
2822 navigation_node::TYPE_CUSTOM, null, 'templatenode');
2825 if (has_capability('mod/feedback:mapcourse', $context) && $settings->get_page()->course->id == SITEID) {
2826 $feedbacknode->add(get_string('mappedcourses', 'feedback'),
2827 new moodle_url('/mod/feedback/mapcourse.php', ['id' => $settings->get_page()->cm->id]),
2828 navigation_node::TYPE_CUSTOM, null, 'mapcourse');
2831 $feedback = $settings->get_page()->activityrecord;
2832 if ($feedback->course == SITEID) {
2833 $analysisnode = navigation_node::create(get_string('analysis', 'feedback'),
2834 new moodle_url('/mod/feedback/analysis_course.php', ['id' => $settings->get_page()->cm->id]),
2835 navigation_node::TYPE_CUSTOM, null, 'feedbackanalysis');
2836 } else {
2837 $analysisnode = navigation_node::create(get_string('analysis', 'feedback'),
2838 new moodle_url('/mod/feedback/analysis.php', ['id' => $settings->get_page()->cm->id]),
2839 navigation_node::TYPE_CUSTOM, null, 'feedbackanalysis');
2842 if (has_capability('mod/feedback:viewreports', $context)) {
2843 $feedbacknode->add_node($analysisnode);
2844 $feedbacknode->add(get_string(($hassecondary ? 'responses' : 'show_entries'), 'feedback'),
2845 new moodle_url('/mod/feedback/show_entries.php', ['id' => $settings->get_page()->cm->id]),
2846 navigation_node::TYPE_CUSTOM, null, 'responses');
2847 } else {
2848 $feedbackcompletion = new mod_feedback_completion($feedback, $context, $settings->get_page()->course->id);
2849 if ($feedbackcompletion->can_view_analysis()) {
2850 $feedbacknode->add_node($analysisnode);
2855 function feedback_init_feedback_session() {
2856 //initialize the feedback-Session - not nice at all!!
2857 global $SESSION;
2858 if (!empty($SESSION)) {
2859 if (!isset($SESSION->feedback) OR !is_object($SESSION->feedback)) {
2860 $SESSION->feedback = new stdClass();
2866 * Return a list of page types
2867 * @param string $pagetype current page type
2868 * @param stdClass $parentcontext Block's parent context
2869 * @param stdClass $currentcontext Current context of block
2871 function feedback_page_type_list($pagetype, $parentcontext, $currentcontext) {
2872 $module_pagetype = array('mod-feedback-*'=>get_string('page-mod-feedback-x', 'feedback'));
2873 return $module_pagetype;
2877 * Move save the items of the given $feedback in the order of $itemlist.
2878 * @param string $itemlist a comma separated list with item ids
2879 * @param stdClass $feedback
2880 * @return bool true if success
2882 function feedback_ajax_saveitemorder($itemlist, $feedback) {
2883 global $DB;
2885 $result = true;
2886 $position = 0;
2887 foreach ($itemlist as $itemid) {
2888 $position++;
2889 $result = $result && $DB->set_field('feedback_item',
2890 'position',
2891 $position,
2892 array('id'=>$itemid, 'feedback'=>$feedback->id));
2894 return $result;
2898 * Checks if current user is able to view feedback on this course.
2900 * @param stdClass $feedback
2901 * @param context_module $context
2902 * @param int $courseid
2903 * @return bool
2905 function feedback_can_view_analysis($feedback, $context, $courseid = false) {
2906 if (has_capability('mod/feedback:viewreports', $context)) {
2907 return true;
2910 if (intval($feedback->publish_stats) != 1 ||
2911 !has_capability('mod/feedback:viewanalysepage', $context)) {
2912 return false;
2915 if (!isloggedin() || isguestuser()) {
2916 // There is no tracking for the guests, assume that they can view analysis if condition above is satisfied.
2917 return $feedback->course == SITEID;
2920 return feedback_is_already_submitted($feedback->id, $courseid);
2924 * Get icon mapping for font-awesome.
2926 function mod_feedback_get_fontawesome_icon_map() {
2927 return [
2928 'mod_feedback:required' => 'fa-exclamation-circle',
2929 'mod_feedback:notrequired' => 'fa-question-circle-o',
2934 * Check if the module has any update that affects the current user since a given time.
2936 * @param cm_info $cm course module data
2937 * @param int $from the time to check updates from
2938 * @param array $filter if we need to check only specific updates
2939 * @return stdClass an object with the different type of areas indicating if they were updated or not
2940 * @since Moodle 3.3
2942 function feedback_check_updates_since(cm_info $cm, $from, $filter = array()) {
2943 global $DB, $USER, $CFG;
2945 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2947 // Check for new attempts.
2948 $updates->attemptsfinished = (object) array('updated' => false);
2949 $updates->attemptsunfinished = (object) array('updated' => false);
2950 $select = 'feedback = ? AND userid = ? AND timemodified > ?';
2951 $params = array($cm->instance, $USER->id, $from);
2953 $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
2954 if (!empty($attemptsfinished)) {
2955 $updates->attemptsfinished->updated = true;
2956 $updates->attemptsfinished->itemids = array_keys($attemptsfinished);
2958 $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
2959 if (!empty($attemptsunfinished)) {
2960 $updates->attemptsunfinished->updated = true;
2961 $updates->attemptsunfinished->itemids = array_keys($attemptsunfinished);
2964 // Now, teachers should see other students updates.
2965 if (has_capability('mod/feedback:viewreports', $cm->context)) {
2966 $select = 'feedback = ? AND timemodified > ?';
2967 $params = array($cm->instance, $from);
2969 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
2970 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
2971 if (empty($groupusers)) {
2972 return $updates;
2974 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
2975 $select .= ' AND userid ' . $insql;
2976 $params = array_merge($params, $inparams);
2979 $updates->userattemptsfinished = (object) array('updated' => false);
2980 $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
2981 if (!empty($attemptsfinished)) {
2982 $updates->userattemptsfinished->updated = true;
2983 $updates->userattemptsfinished->itemids = array_keys($attemptsfinished);
2986 $updates->userattemptsunfinished = (object) array('updated' => false);
2987 $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
2988 if (!empty($attemptsunfinished)) {
2989 $updates->userattemptsunfinished->updated = true;
2990 $updates->userattemptsunfinished->itemids = array_keys($attemptsunfinished);
2994 return $updates;
2998 * This function receives a calendar event and returns the action associated with it, or null if there is none.
3000 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
3001 * is not displayed on the block.
3003 * @param calendar_event $event
3004 * @param \core_calendar\action_factory $factory
3005 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
3006 * @return \core_calendar\local\event\entities\action_interface|null
3008 function mod_feedback_core_calendar_provide_event_action(calendar_event $event,
3009 \core_calendar\action_factory $factory,
3010 int $userid = 0) {
3012 global $USER;
3014 if (empty($userid)) {
3015 $userid = $USER->id;
3018 $cm = get_fast_modinfo($event->courseid, $userid)->instances['feedback'][$event->instance];
3020 if (!$cm->uservisible) {
3021 // The module is not visible to the user for any reason.
3022 return null;
3025 $completion = new \completion_info($cm->get_course());
3027 $completiondata = $completion->get_data($cm, false, $userid);
3029 if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
3030 return null;
3033 $feedbackcompletion = new mod_feedback_completion(null, $cm, 0, false, null, null, $userid);
3035 if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
3036 // Feedback is already closed, do not display it even if it was never submitted.
3037 return null;
3040 if (!$feedbackcompletion->can_complete()) {
3041 // The user can't complete the feedback so there is no action for them.
3042 return null;
3045 // The feedback is actionable if it does not have timeopen or timeopen is in the past.
3046 $actionable = $feedbackcompletion->is_open();
3048 if ($actionable && $feedbackcompletion->is_already_submitted(false)) {
3049 // There is no need to display anything if the user has already submitted the feedback.
3050 return null;
3053 return $factory->create_instance(
3054 get_string('answerquestions', 'feedback'),
3055 new \moodle_url('/mod/feedback/view.php', ['id' => $cm->id]),
3057 $actionable
3062 * Add a get_coursemodule_info function in case any feedback type wants to add 'extra' information
3063 * for the course (see resource).
3065 * Given a course_module object, this function returns any "extra" information that may be needed
3066 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
3068 * @param stdClass $coursemodule The coursemodule object (record).
3069 * @return cached_cm_info An object on information that the courses
3070 * will know about (most noticeably, an icon).
3072 function feedback_get_coursemodule_info($coursemodule) {
3073 global $DB;
3075 $dbparams = ['id' => $coursemodule->instance];
3076 $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose, anonymous';
3077 if (!$feedback = $DB->get_record('feedback', $dbparams, $fields)) {
3078 return false;
3081 $result = new cached_cm_info();
3082 $result->name = $feedback->name;
3084 if ($coursemodule->showdescription) {
3085 // Convert intro to html. Do not filter cached version, filters run at display time.
3086 $result->content = format_module_intro('feedback', $feedback, $coursemodule->id, false);
3089 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
3090 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
3091 $result->customdata['customcompletionrules']['completionsubmit'] = $feedback->completionsubmit;
3093 // Populate some other values that can be used in calendar or on dashboard.
3094 if ($feedback->timeopen) {
3095 $result->customdata['timeopen'] = $feedback->timeopen;
3097 if ($feedback->timeclose) {
3098 $result->customdata['timeclose'] = $feedback->timeclose;
3100 if ($feedback->anonymous) {
3101 $result->customdata['anonymous'] = $feedback->anonymous;
3104 return $result;
3108 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
3110 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
3111 * @return array $descriptions the array of descriptions for the custom rules.
3113 function mod_feedback_get_completion_active_rule_descriptions($cm) {
3114 // Values will be present in cm_info, and we assume these are up to date.
3115 if (empty($cm->customdata['customcompletionrules'])
3116 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
3117 return [];
3120 $descriptions = [];
3121 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
3122 switch ($key) {
3123 case 'completionsubmit':
3124 if (!empty($val)) {
3125 $descriptions[] = get_string('completionsubmit', 'feedback');
3127 break;
3128 default:
3129 break;
3132 return $descriptions;
3136 * This function calculates the minimum and maximum cutoff values for the timestart of
3137 * the given event.
3139 * It will return an array with two values, the first being the minimum cutoff value and
3140 * the second being the maximum cutoff value. Either or both values can be null, which
3141 * indicates there is no minimum or maximum, respectively.
3143 * If a cutoff is required then the function must return an array containing the cutoff
3144 * timestamp and error string to display to the user if the cutoff value is violated.
3146 * A minimum and maximum cutoff return value will look like:
3148 * [1505704373, 'The due date must be after the sbumission start date'],
3149 * [1506741172, 'The due date must be before the cutoff date']
3152 * @param calendar_event $event The calendar event to get the time range for
3153 * @param stdClass $instance The module instance to get the range from
3154 * @return array
3156 function mod_feedback_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
3157 $mindate = null;
3158 $maxdate = null;
3160 if ($event->eventtype == FEEDBACK_EVENT_TYPE_OPEN) {
3161 // The start time of the open event can't be equal to or after the
3162 // close time of the choice activity.
3163 if (!empty($instance->timeclose)) {
3164 $maxdate = [
3165 $instance->timeclose,
3166 get_string('openafterclose', 'feedback')
3169 } else if ($event->eventtype == FEEDBACK_EVENT_TYPE_CLOSE) {
3170 // The start time of the close event can't be equal to or earlier than the
3171 // open time of the choice activity.
3172 if (!empty($instance->timeopen)) {
3173 $mindate = [
3174 $instance->timeopen,
3175 get_string('closebeforeopen', 'feedback')
3180 return [$mindate, $maxdate];
3184 * This function will update the feedback module according to the
3185 * event that has been modified.
3187 * It will set the timeopen or timeclose value of the feedback instance
3188 * according to the type of event provided.
3190 * @throws \moodle_exception
3191 * @param \calendar_event $event
3192 * @param stdClass $feedback The module instance to get the range from
3194 function mod_feedback_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $feedback) {
3195 global $CFG, $DB;
3197 if (empty($event->instance) || $event->modulename != 'feedback') {
3198 return;
3201 if ($event->instance != $feedback->id) {
3202 return;
3205 if (!in_array($event->eventtype, [FEEDBACK_EVENT_TYPE_OPEN, FEEDBACK_EVENT_TYPE_CLOSE])) {
3206 return;
3209 $courseid = $event->courseid;
3210 $modulename = $event->modulename;
3211 $instanceid = $event->instance;
3212 $modified = false;
3214 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
3215 $context = context_module::instance($coursemodule->id);
3217 // The user does not have the capability to modify this activity.
3218 if (!has_capability('moodle/course:manageactivities', $context)) {
3219 return;
3222 if ($event->eventtype == FEEDBACK_EVENT_TYPE_OPEN) {
3223 // If the event is for the feedback activity opening then we should
3224 // set the start time of the feedback activity to be the new start
3225 // time of the event.
3226 if ($feedback->timeopen != $event->timestart) {
3227 $feedback->timeopen = $event->timestart;
3228 $feedback->timemodified = time();
3229 $modified = true;
3231 } else if ($event->eventtype == FEEDBACK_EVENT_TYPE_CLOSE) {
3232 // If the event is for the feedback activity closing then we should
3233 // set the end time of the feedback activity to be the new start
3234 // time of the event.
3235 if ($feedback->timeclose != $event->timestart) {
3236 $feedback->timeclose = $event->timestart;
3237 $modified = true;
3241 if ($modified) {
3242 $feedback->timemodified = time();
3243 $DB->update_record('feedback', $feedback);
3244 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
3245 $event->trigger();
3250 * Callback to fetch the activity event type lang string.
3252 * @param string $eventtype The event type.
3253 * @return lang_string The event type lang string.
3255 function mod_feedback_core_calendar_get_event_action_string(string $eventtype): string {
3256 $modulename = get_string('modulename', 'feedback');
3258 switch ($eventtype) {
3259 case FEEDBACK_EVENT_TYPE_OPEN:
3260 $identifier = 'calendarstart';
3261 break;
3262 case FEEDBACK_EVENT_TYPE_CLOSE:
3263 $identifier = 'calendarend';
3264 break;
3265 default:
3266 return get_string('requiresaction', 'calendar', $modulename);
3269 return get_string($identifier, 'feedback', $modulename);