MDL-58453 mod_feedback: Refactor get_non_respondents WS
[moodle.git] / mod / feedback / lib.php
blob3fe661a8ef38f002d57f230df2e4887247d647c1
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 eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 // Include forms lib.
31 require_once($CFG->libdir.'/formslib.php');
33 define('FEEDBACK_ANONYMOUS_YES', 1);
34 define('FEEDBACK_ANONYMOUS_NO', 2);
35 define('FEEDBACK_MIN_ANONYMOUS_COUNT_IN_GROUP', 2);
36 define('FEEDBACK_DECIMAL', '.');
37 define('FEEDBACK_THOUSAND', ',');
38 define('FEEDBACK_RESETFORM_RESET', 'feedback_reset_data_');
39 define('FEEDBACK_RESETFORM_DROP', 'feedback_drop_feedback_');
40 define('FEEDBACK_MAX_PIX_LENGTH', '400'); //max. Breite des grafischen Balkens in der Auswertung
41 define('FEEDBACK_DEFAULT_PAGE_COUNT', 20);
43 // Event types.
44 define('FEEDBACK_EVENT_TYPE_OPEN', 'open');
45 define('FEEDBACK_EVENT_TYPE_CLOSE', 'close');
47 /**
48 * Returns all other caps used in module.
50 * @return array
52 function feedback_get_extra_capabilities() {
53 return array('moodle/site:accessallgroups');
56 /**
57 * @uses FEATURE_GROUPS
58 * @uses FEATURE_GROUPINGS
59 * @uses FEATURE_MOD_INTRO
60 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
61 * @uses FEATURE_GRADE_HAS_GRADE
62 * @uses FEATURE_GRADE_OUTCOMES
63 * @param string $feature FEATURE_xx constant for requested feature
64 * @return mixed True if module supports feature, null if doesn't know
66 function feedback_supports($feature) {
67 switch($feature) {
68 case FEATURE_GROUPS: return true;
69 case FEATURE_GROUPINGS: return true;
70 case FEATURE_MOD_INTRO: return true;
71 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
72 case FEATURE_COMPLETION_HAS_RULES: return true;
73 case FEATURE_GRADE_HAS_GRADE: return false;
74 case FEATURE_GRADE_OUTCOMES: return false;
75 case FEATURE_BACKUP_MOODLE2: return true;
76 case FEATURE_SHOW_DESCRIPTION: return true;
78 default: return null;
82 /**
83 * this will create a new instance and return the id number
84 * of the new instance.
86 * @global object
87 * @param object $feedback the object given by mod_feedback_mod_form
88 * @return int
90 function feedback_add_instance($feedback) {
91 global $DB;
93 $feedback->timemodified = time();
94 $feedback->id = '';
96 if (empty($feedback->site_after_submit)) {
97 $feedback->site_after_submit = '';
100 //saving the feedback in db
101 $feedbackid = $DB->insert_record("feedback", $feedback);
103 $feedback->id = $feedbackid;
105 feedback_set_events($feedback);
107 if (!isset($feedback->coursemodule)) {
108 $cm = get_coursemodule_from_id('feedback', $feedback->id);
109 $feedback->coursemodule = $cm->id;
111 $context = context_module::instance($feedback->coursemodule);
113 $editoroptions = feedback_get_editor_options();
115 // process the custom wysiwyg editor in page_after_submit
116 if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
117 $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
118 'mod_feedback', 'page_after_submit',
119 0, $editoroptions,
120 $feedback->page_after_submit_editor['text']);
122 $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
124 $DB->update_record('feedback', $feedback);
126 return $feedbackid;
130 * this will update a given instance
132 * @global object
133 * @param object $feedback the object given by mod_feedback_mod_form
134 * @return boolean
136 function feedback_update_instance($feedback) {
137 global $DB;
139 $feedback->timemodified = time();
140 $feedback->id = $feedback->instance;
142 if (empty($feedback->site_after_submit)) {
143 $feedback->site_after_submit = '';
146 //save the feedback into the db
147 $DB->update_record("feedback", $feedback);
149 //create or update the new events
150 feedback_set_events($feedback);
152 $context = context_module::instance($feedback->coursemodule);
154 $editoroptions = feedback_get_editor_options();
156 // process the custom wysiwyg editor in page_after_submit
157 if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
158 $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
159 'mod_feedback', 'page_after_submit',
160 0, $editoroptions,
161 $feedback->page_after_submit_editor['text']);
163 $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
165 $DB->update_record('feedback', $feedback);
167 return true;
171 * Serves the files included in feedback items like label. Implements needed access control ;-)
173 * There are two situations in general where the files will be sent.
174 * 1) filearea = item, 2) filearea = template
176 * @package mod_feedback
177 * @category files
178 * @param stdClass $course course object
179 * @param stdClass $cm course module object
180 * @param stdClass $context context object
181 * @param string $filearea file area
182 * @param array $args extra arguments
183 * @param bool $forcedownload whether or not force download
184 * @param array $options additional options affecting the file serving
185 * @return bool false if file not found, does not return if found - justsend the file
187 function feedback_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
188 global $CFG, $DB;
190 if ($filearea === 'item' or $filearea === 'template') {
191 $itemid = (int)array_shift($args);
192 //get the item what includes the file
193 if (!$item = $DB->get_record('feedback_item', array('id'=>$itemid))) {
194 return false;
196 $feedbackid = $item->feedback;
197 $templateid = $item->template;
200 if ($filearea === 'page_after_submit' or $filearea === 'item') {
201 if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) {
202 return false;
205 $feedbackid = $feedback->id;
207 //if the filearea is "item" so we check the permissions like view/complete the feedback
208 $canload = false;
209 //first check whether the user has the complete capability
210 if (has_capability('mod/feedback:complete', $context)) {
211 $canload = true;
214 //now we check whether the user has the view capability
215 if (has_capability('mod/feedback:view', $context)) {
216 $canload = true;
219 //if the feedback is on frontpage and anonymous and the fullanonymous is allowed
220 //so the file can be loaded too.
221 if (isset($CFG->feedback_allowfullanonymous)
222 AND $CFG->feedback_allowfullanonymous
223 AND $course->id == SITEID
224 AND $feedback->anonymous == FEEDBACK_ANONYMOUS_YES ) {
225 $canload = true;
228 if (!$canload) {
229 return false;
231 } else if ($filearea === 'template') { //now we check files in templates
232 if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
233 return false;
236 //if the file is not public so the capability edititems has to be there
237 if (!$template->ispublic) {
238 if (!has_capability('mod/feedback:edititems', $context)) {
239 return false;
241 } else { //on public templates, at least the user has to be logged in
242 if (!isloggedin()) {
243 return false;
246 } else {
247 return false;
250 if ($context->contextlevel == CONTEXT_MODULE) {
251 if ($filearea !== 'item' and $filearea !== 'page_after_submit') {
252 return false;
256 if ($context->contextlevel == CONTEXT_COURSE || $context->contextlevel == CONTEXT_SYSTEM) {
257 if ($filearea !== 'template') {
258 return false;
262 $relativepath = implode('/', $args);
263 if ($filearea === 'page_after_submit') {
264 $fullpath = "/{$context->id}/mod_feedback/$filearea/$relativepath";
265 } else {
266 $fullpath = "/{$context->id}/mod_feedback/$filearea/{$item->id}/$relativepath";
269 $fs = get_file_storage();
271 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
272 return false;
275 // finally send the file
276 send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
278 return false;
282 * this will delete a given instance.
283 * all referenced data also will be deleted
285 * @global object
286 * @param int $id the instanceid of feedback
287 * @return boolean
289 function feedback_delete_instance($id) {
290 global $DB;
292 //get all referenced items
293 $feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$id));
295 //deleting all referenced items and values
296 if (is_array($feedbackitems)) {
297 foreach ($feedbackitems as $feedbackitem) {
298 $DB->delete_records("feedback_value", array("item"=>$feedbackitem->id));
299 $DB->delete_records("feedback_valuetmp", array("item"=>$feedbackitem->id));
301 if ($delitems = $DB->get_records("feedback_item", array("feedback"=>$id))) {
302 foreach ($delitems as $delitem) {
303 feedback_delete_item($delitem->id, false);
308 //deleting the completeds
309 $DB->delete_records("feedback_completed", array("feedback"=>$id));
311 //deleting the unfinished completeds
312 $DB->delete_records("feedback_completedtmp", array("feedback"=>$id));
314 //deleting old events
315 $DB->delete_records('event', array('modulename'=>'feedback', 'instance'=>$id));
316 return $DB->delete_records("feedback", array("id"=>$id));
320 * Return a small object with summary information about what a
321 * user has done with a given particular instance of this module
322 * Used for user activity reports.
323 * $return->time = the time they did it
324 * $return->info = a short text description
326 * @param stdClass $course
327 * @param stdClass $user
328 * @param cm_info|stdClass $mod
329 * @param stdClass $feedback
330 * @return stdClass
332 function feedback_user_outline($course, $user, $mod, $feedback) {
333 global $DB;
334 $outline = (object)['info' => '', 'time' => 0];
335 if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
336 // Do not disclose any user info if feedback is anonymous.
337 return $outline;
339 $params = array('userid' => $user->id, 'feedback' => $feedback->id,
340 'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
341 $status = null;
342 $context = context_module::instance($mod->id);
343 if ($completed = $DB->get_record('feedback_completed', $params)) {
344 // User has completed feedback.
345 $outline->info = get_string('completed', 'feedback');
346 $outline->time = $completed->timemodified;
347 } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
348 // User has started but not completed feedback.
349 $outline->info = get_string('started', 'feedback');
350 $outline->time = $completedtmp->timemodified;
351 } else if (has_capability('mod/feedback:complete', $context, $user)) {
352 // User has not started feedback but has capability to do so.
353 $outline->info = get_string('not_started', 'feedback');
356 return $outline;
360 * Returns all users who has completed a specified feedback since a given time
361 * many thanks to Manolescu Dorel, who contributed these two functions
363 * @global object
364 * @global object
365 * @global object
366 * @global object
367 * @uses CONTEXT_MODULE
368 * @param array $activities Passed by reference
369 * @param int $index Passed by reference
370 * @param int $timemodified Timestamp
371 * @param int $courseid
372 * @param int $cmid
373 * @param int $userid
374 * @param int $groupid
375 * @return void
377 function feedback_get_recent_mod_activity(&$activities, &$index,
378 $timemodified, $courseid,
379 $cmid, $userid="", $groupid="") {
381 global $CFG, $COURSE, $USER, $DB;
383 if ($COURSE->id == $courseid) {
384 $course = $COURSE;
385 } else {
386 $course = $DB->get_record('course', array('id'=>$courseid));
389 $modinfo = get_fast_modinfo($course);
391 $cm = $modinfo->cms[$cmid];
393 $sqlargs = array();
395 $userfields = user_picture::fields('u', null, 'useridagain');
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\" valign=\"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('icon', $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 * Obtains the automatic completion state for this feedback based on the condition
519 * in feedback settings.
521 * @param object $course Course
522 * @param object $cm Course-module
523 * @param int $userid User ID
524 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
525 * @return bool True if completed, false if not, $type if conditions not set.
527 function feedback_get_completion_state($course, $cm, $userid, $type) {
528 global $CFG, $DB;
530 // Get feedback details
531 $feedback = $DB->get_record('feedback', array('id'=>$cm->instance), '*', MUST_EXIST);
533 // If completion option is enabled, evaluate it and return true/false
534 if ($feedback->completionsubmit) {
535 $params = array('userid'=>$userid, 'feedback'=>$feedback->id);
536 return $DB->record_exists('feedback_completed', $params);
537 } else {
538 // Completion option is not enabled so just return $type
539 return $type;
544 * Print a detailed representation of what a user has done with
545 * a given particular instance of this module, for user activity reports.
547 * @param stdClass $course
548 * @param stdClass $user
549 * @param cm_info|stdClass $mod
550 * @param stdClass $feedback
552 function feedback_user_complete($course, $user, $mod, $feedback) {
553 global $DB;
554 if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
555 // Do not disclose any user info if feedback is anonymous.
556 return;
558 $params = array('userid' => $user->id, 'feedback' => $feedback->id,
559 'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
560 $url = $status = null;
561 $context = context_module::instance($mod->id);
562 if ($completed = $DB->get_record('feedback_completed', $params)) {
563 // User has completed feedback.
564 if (has_capability('mod/feedback:viewreports', $context)) {
565 $url = new moodle_url('/mod/feedback/show_entries.php',
566 ['id' => $mod->id, 'userid' => $user->id,
567 'showcompleted' => $completed->id]);
569 $status = get_string('completedon', 'feedback', userdate($completed->timemodified));
570 } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
571 // User has started but not completed feedback.
572 $status = get_string('startedon', 'feedback', userdate($completedtmp->timemodified));
573 } else if (has_capability('mod/feedback:complete', $context, $user)) {
574 // User has not started feedback but has capability to do so.
575 $status = get_string('not_started', 'feedback');
578 if ($url && $status) {
579 echo html_writer::link($url, $status);
580 } else if ($status) {
581 echo html_writer::div($status);
586 * @return bool true
588 function feedback_cron () {
589 return true;
593 * @return bool false
595 function feedback_scale_used ($feedbackid, $scaleid) {
596 return false;
600 * Checks if scale is being used by any instance of feedback
602 * This is used to find out if scale used anywhere
603 * @param $scaleid int
604 * @return boolean True if the scale is used by any assignment
606 function feedback_scale_used_anywhere($scaleid) {
607 return false;
611 * List the actions that correspond to a view of this module.
612 * This is used by the participation report.
614 * Note: This is not used by new logging system. Event with
615 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
616 * be considered as view action.
618 * @return array
620 function feedback_get_view_actions() {
621 return array('view', 'view all');
625 * List the actions that correspond to a post of this module.
626 * This is used by the participation report.
628 * Note: This is not used by new logging system. Event with
629 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
630 * will be considered as post action.
632 * @return array
634 function feedback_get_post_actions() {
635 return array('submit');
639 * This function is used by the reset_course_userdata function in moodlelib.
640 * This function will remove all responses from the specified feedback
641 * and clean up any related data.
643 * @global object
644 * @global object
645 * @uses FEEDBACK_RESETFORM_RESET
646 * @uses FEEDBACK_RESETFORM_DROP
647 * @param object $data the data submitted from the reset course.
648 * @return array status array
650 function feedback_reset_userdata($data) {
651 global $CFG, $DB;
653 $resetfeedbacks = array();
654 $dropfeedbacks = array();
655 $status = array();
656 $componentstr = get_string('modulenameplural', 'feedback');
658 //get the relevant entries from $data
659 foreach ($data as $key => $value) {
660 switch(true) {
661 case substr($key, 0, strlen(FEEDBACK_RESETFORM_RESET)) == FEEDBACK_RESETFORM_RESET:
662 if ($value == 1) {
663 $templist = explode('_', $key);
664 if (isset($templist[3])) {
665 $resetfeedbacks[] = intval($templist[3]);
668 break;
669 case substr($key, 0, strlen(FEEDBACK_RESETFORM_DROP)) == FEEDBACK_RESETFORM_DROP:
670 if ($value == 1) {
671 $templist = explode('_', $key);
672 if (isset($templist[3])) {
673 $dropfeedbacks[] = intval($templist[3]);
676 break;
680 //reset the selected feedbacks
681 foreach ($resetfeedbacks as $id) {
682 $feedback = $DB->get_record('feedback', array('id'=>$id));
683 feedback_delete_all_completeds($feedback);
684 $status[] = array('component'=>$componentstr.':'.$feedback->name,
685 'item'=>get_string('resetting_data', 'feedback'),
686 'error'=>false);
689 // Updating dates - shift may be negative too.
690 if ($data->timeshift) {
691 $shifterror = !shift_course_mod_dates('feedback', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
692 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => $shifterror);
695 return $status;
699 * Called by course/reset.php
701 * @global object
702 * @uses FEEDBACK_RESETFORM_RESET
703 * @param object $mform form passed by reference
705 function feedback_reset_course_form_definition(&$mform) {
706 global $COURSE, $DB;
708 $mform->addElement('header', 'feedbackheader', get_string('modulenameplural', 'feedback'));
710 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$COURSE->id), 'name')) {
711 return;
714 $mform->addElement('static', 'hint', get_string('resetting_data', 'feedback'));
715 foreach ($feedbacks as $feedback) {
716 $mform->addElement('checkbox', FEEDBACK_RESETFORM_RESET.$feedback->id, $feedback->name);
721 * Course reset form defaults.
723 * @global object
724 * @uses FEEDBACK_RESETFORM_RESET
725 * @param object $course
727 function feedback_reset_course_form_defaults($course) {
728 global $DB;
730 $return = array();
731 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
732 return;
734 foreach ($feedbacks as $feedback) {
735 $return[FEEDBACK_RESETFORM_RESET.$feedback->id] = true;
737 return $return;
741 * Called by course/reset.php and shows the formdata by coursereset.
742 * it prints checkboxes for each feedback available at the given course
743 * there are two checkboxes:
744 * 1) delete userdata and keep the feedback
745 * 2) delete userdata and drop the feedback
747 * @global object
748 * @uses FEEDBACK_RESETFORM_RESET
749 * @uses FEEDBACK_RESETFORM_DROP
750 * @param object $course
751 * @return void
753 function feedback_reset_course_form($course) {
754 global $DB, $OUTPUT;
756 echo get_string('resetting_feedbacks', 'feedback'); echo ':<br />';
757 if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
758 return;
761 foreach ($feedbacks as $feedback) {
762 echo '<p>';
763 echo get_string('name', 'feedback').': '.$feedback->name.'<br />';
764 echo html_writer::checkbox(FEEDBACK_RESETFORM_RESET.$feedback->id,
765 1, true,
766 get_string('resetting_data', 'feedback'));
767 echo '<br />';
768 echo html_writer::checkbox(FEEDBACK_RESETFORM_DROP.$feedback->id,
769 1, false,
770 get_string('drop_feedback', 'feedback'));
771 echo '</p>';
776 * This gets an array with default options for the editor
778 * @return array the options
780 function feedback_get_editor_options() {
781 return array('maxfiles' => EDITOR_UNLIMITED_FILES,
782 'trusttext'=>true);
786 * This creates new events given as timeopen and closeopen by $feedback.
788 * @global object
789 * @param object $feedback
790 * @return void
792 function feedback_set_events($feedback) {
793 global $DB, $CFG;
795 // Include calendar/lib.php.
796 require_once($CFG->dirroot.'/calendar/lib.php');
798 // Get CMID if not sent as part of $feedback.
799 if (!isset($feedback->coursemodule)) {
800 $cm = get_coursemodule_from_instance('feedback', $feedback->id, $feedback->course);
801 $feedback->coursemodule = $cm->id;
804 // Feedback start calendar events.
805 $eventid = $DB->get_field('event', 'id',
806 array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_OPEN));
808 if (isset($feedback->timeopen) && $feedback->timeopen > 0) {
809 $event = new stdClass();
810 $event->eventtype = FEEDBACK_EVENT_TYPE_OPEN;
811 $event->type = empty($feedback->timeclose) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
812 $event->name = get_string('calendarstart', 'feedback', $feedback->name);
813 $event->description = format_module_intro('feedback', $feedback, $feedback->coursemodule);
814 $event->timestart = $feedback->timeopen;
815 $event->timesort = $feedback->timeopen;
816 $event->visible = instance_is_visible('feedback', $feedback);
817 $event->timeduration = 0;
818 if ($eventid) {
819 // Calendar event exists so update it.
820 $event->id = $eventid;
821 $calendarevent = calendar_event::load($event->id);
822 $calendarevent->update($event);
823 } else {
824 // Event doesn't exist so create one.
825 $event->courseid = $feedback->course;
826 $event->groupid = 0;
827 $event->userid = 0;
828 $event->modulename = 'feedback';
829 $event->instance = $feedback->id;
830 $event->eventtype = FEEDBACK_EVENT_TYPE_OPEN;
831 calendar_event::create($event);
833 } else if ($eventid) {
834 // Calendar event is on longer needed.
835 $calendarevent = calendar_event::load($eventid);
836 $calendarevent->delete();
839 // Feedback close calendar events.
840 $eventid = $DB->get_field('event', 'id',
841 array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_CLOSE));
843 if (isset($feedback->timeclose) && $feedback->timeclose > 0) {
844 $event = new stdClass();
845 $event->type = CALENDAR_EVENT_TYPE_ACTION;
846 $event->eventtype = FEEDBACK_EVENT_TYPE_CLOSE;
847 $event->name = get_string('calendarend', 'feedback', $feedback->name);
848 $event->description = format_module_intro('feedback', $feedback, $feedback->coursemodule);
849 $event->timestart = $feedback->timeclose;
850 $event->timesort = $feedback->timeclose;
851 $event->visible = instance_is_visible('feedback', $feedback);
852 $event->timeduration = 0;
853 if ($eventid) {
854 // Calendar event exists so update it.
855 $event->id = $eventid;
856 $calendarevent = calendar_event::load($event->id);
857 $calendarevent->update($event);
858 } else {
859 // Event doesn't exist so create one.
860 $event->courseid = $feedback->course;
861 $event->groupid = 0;
862 $event->userid = 0;
863 $event->modulename = 'feedback';
864 $event->instance = $feedback->id;
865 calendar_event::create($event);
867 } else if ($eventid) {
868 // Calendar event is on longer needed.
869 $calendarevent = calendar_event::load($eventid);
870 $calendarevent->delete();
875 * This standard function will check all instances of this module
876 * and make sure there are up-to-date events created for each of them.
877 * If courseid = 0, then every feedback event in the site is checked, else
878 * only feedback events belonging to the course specified are checked.
879 * This function is used, in its new format, by restore_refresh_events()
881 * @param int $courseid
882 * @return bool
884 function feedback_refresh_events($courseid = 0) {
885 global $DB;
887 if ($courseid) {
888 if (! $feedbacks = $DB->get_records("feedback", array("course" => $courseid))) {
889 return true;
891 } else {
892 if (! $feedbacks = $DB->get_records("feedback")) {
893 return true;
897 foreach ($feedbacks as $feedback) {
898 feedback_set_events($feedback);
900 return true;
904 * this function is called by {@link feedback_delete_userdata()}
905 * it drops the feedback-instance from the course_module table
907 * @global object
908 * @param int $id the id from the coursemodule
909 * @return boolean
911 function feedback_delete_course_module($id) {
912 global $DB;
914 if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
915 return true;
917 return $DB->delete_records('course_modules', array('id'=>$cm->id));
922 ////////////////////////////////////////////////
923 //functions to handle capabilities
924 ////////////////////////////////////////////////
927 * returns the context-id related to the given coursemodule-id
929 * @deprecated since 3.1
930 * @staticvar object $context
931 * @param int $cmid the coursemodule-id
932 * @return object $context
934 function feedback_get_context($cmid) {
935 debugging('Function feedback_get_context() is deprecated because it was not used.',
936 DEBUG_DEVELOPER);
937 static $context;
939 if (isset($context)) {
940 return $context;
943 $context = context_module::instance($cmid);
944 return $context;
948 * returns true if the current role is faked by switching role feature
950 * @global object
951 * @return boolean
953 function feedback_check_is_switchrole() {
954 global $USER;
955 if (isset($USER->switchrole) AND
956 is_array($USER->switchrole) AND
957 count($USER->switchrole) > 0) {
959 return true;
961 return false;
965 * count users which have not completed the feedback
967 * @global object
968 * @uses CONTEXT_MODULE
969 * @param cm_info $cm Course-module object
970 * @param int $group single groupid
971 * @param string $sort
972 * @param int $startpage
973 * @param int $pagecount
974 * @param bool $includestatus to return if the user started or not the feedback among the complete user record
975 * @return array array of user ids or user objects when $includestatus set to true
977 function feedback_get_incomplete_users(cm_info $cm,
978 $group = false,
979 $sort = '',
980 $startpage = false,
981 $pagecount = false,
982 $includestatus = false) {
984 global $DB;
986 $context = context_module::instance($cm->id);
988 //first get all user who can complete this feedback
989 $cap = 'mod/feedback:complete';
990 $allnames = get_all_user_name_fields(true, 'u');
991 $fields = 'u.id, ' . $allnames . ', u.picture, u.email, u.imagealt';
992 if (!$allusers = get_users_by_capability($context,
993 $cap,
994 $fields,
995 $sort,
998 $group,
1000 true)) {
1001 return false;
1003 // Filter users that are not in the correct group/grouping.
1004 $info = new \core_availability\info_module($cm);
1005 $allusersrecords = $info->filter_user_list($allusers);
1007 $allusers = array_keys($allusersrecords);
1009 //now get all completeds
1010 $params = array('feedback'=>$cm->instance);
1011 if ($completedusers = $DB->get_records_menu('feedback_completed', $params, '', 'id, userid')) {
1012 // Now strike all completedusers from allusers.
1013 $allusers = array_diff($allusers, $completedusers);
1016 //for paging I use array_slice()
1017 if ($startpage !== false AND $pagecount !== false) {
1018 $allusers = array_slice($allusers, $startpage, $pagecount);
1021 // Check if we should return the full users objects.
1022 if ($includestatus) {
1023 $userrecords = [];
1024 $startedusers = $DB->get_records_menu('feedback_completedtmp', ['feedback' => $cm->instance], '', 'id, userid');
1025 $startedusers = array_flip($startedusers);
1026 foreach ($allusers as $userid) {
1027 $allusersrecords[$userid]->feedbackstarted = isset($startedusers[$userid]);
1028 $userrecords[] = $allusersrecords[$userid];
1030 return $userrecords;
1031 } else { // Return just user ids.
1032 return $allusers;
1037 * count users which have not completed the feedback
1039 * @global object
1040 * @param object $cm
1041 * @param int $group single groupid
1042 * @return int count of userrecords
1044 function feedback_count_incomplete_users($cm, $group = false) {
1045 if ($allusers = feedback_get_incomplete_users($cm, $group)) {
1046 return count($allusers);
1048 return 0;
1052 * count users which have completed a feedback
1054 * @global object
1055 * @uses FEEDBACK_ANONYMOUS_NO
1056 * @param object $cm
1057 * @param int $group single groupid
1058 * @return int count of userrecords
1060 function feedback_count_complete_users($cm, $group = false) {
1061 global $DB;
1063 $params = array(FEEDBACK_ANONYMOUS_NO, $cm->instance);
1065 $fromgroup = '';
1066 $wheregroup = '';
1067 if ($group) {
1068 $fromgroup = ', {groups_members} g';
1069 $wheregroup = ' AND g.groupid = ? AND g.userid = c.userid';
1070 $params[] = $group;
1073 $sql = 'SELECT COUNT(u.id) FROM {user} u, {feedback_completed} c'.$fromgroup.'
1074 WHERE anonymous_response = ? AND u.id = c.userid AND c.feedback = ?
1075 '.$wheregroup;
1077 return $DB->count_records_sql($sql, $params);
1082 * get users which have completed a feedback
1084 * @global object
1085 * @uses CONTEXT_MODULE
1086 * @uses FEEDBACK_ANONYMOUS_NO
1087 * @param object $cm
1088 * @param int $group single groupid
1089 * @param string $where a sql where condition (must end with " AND ")
1090 * @param array parameters used in $where
1091 * @param string $sort a table field
1092 * @param int $startpage
1093 * @param int $pagecount
1094 * @return object the userrecords
1096 function feedback_get_complete_users($cm,
1097 $group = false,
1098 $where = '',
1099 array $params = null,
1100 $sort = '',
1101 $startpage = false,
1102 $pagecount = false) {
1104 global $DB;
1106 $context = context_module::instance($cm->id);
1108 $params = (array)$params;
1110 $params['anon'] = FEEDBACK_ANONYMOUS_NO;
1111 $params['instance'] = $cm->instance;
1113 $fromgroup = '';
1114 $wheregroup = '';
1115 if ($group) {
1116 $fromgroup = ', {groups_members} g';
1117 $wheregroup = ' AND g.groupid = :group AND g.userid = c.userid';
1118 $params['group'] = $group;
1121 if ($sort) {
1122 $sortsql = ' ORDER BY '.$sort;
1123 } else {
1124 $sortsql = '';
1127 $ufields = user_picture::fields('u');
1128 $sql = 'SELECT DISTINCT '.$ufields.', c.timemodified as completed_timemodified
1129 FROM {user} u, {feedback_completed} c '.$fromgroup.'
1130 WHERE '.$where.' anonymous_response = :anon
1131 AND u.id = c.userid
1132 AND c.feedback = :instance
1133 '.$wheregroup.$sortsql;
1135 if ($startpage === false OR $pagecount === false) {
1136 $startpage = false;
1137 $pagecount = false;
1139 return $DB->get_records_sql($sql, $params, $startpage, $pagecount);
1143 * get users which have the viewreports-capability
1145 * @uses CONTEXT_MODULE
1146 * @param int $cmid
1147 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1148 * @return object the userrecords
1150 function feedback_get_viewreports_users($cmid, $groups = false) {
1152 $context = context_module::instance($cmid);
1154 //description of the call below:
1155 //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1156 // $limitnum='', $groups='', $exceptions='', $doanything=true)
1157 return get_users_by_capability($context,
1158 'mod/feedback:viewreports',
1160 'lastname',
1163 $groups,
1165 false);
1169 * get users which have the receivemail-capability
1171 * @uses CONTEXT_MODULE
1172 * @param int $cmid
1173 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1174 * @return object the userrecords
1176 function feedback_get_receivemail_users($cmid, $groups = false) {
1178 $context = context_module::instance($cmid);
1180 //description of the call below:
1181 //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1182 // $limitnum='', $groups='', $exceptions='', $doanything=true)
1183 return get_users_by_capability($context,
1184 'mod/feedback:receivemail',
1186 'lastname',
1189 $groups,
1191 false);
1194 ////////////////////////////////////////////////
1195 //functions to handle the templates
1196 ////////////////////////////////////////////////
1197 ////////////////////////////////////////////////
1200 * creates a new template-record.
1202 * @global object
1203 * @param int $courseid
1204 * @param string $name the name of template shown in the templatelist
1205 * @param int $ispublic 0:privat 1:public
1206 * @return int the new templateid
1208 function feedback_create_template($courseid, $name, $ispublic = 0) {
1209 global $DB;
1211 $templ = new stdClass();
1212 $templ->course = ($ispublic ? 0 : $courseid);
1213 $templ->name = $name;
1214 $templ->ispublic = $ispublic;
1216 $templid = $DB->insert_record('feedback_template', $templ);
1217 return $DB->get_record('feedback_template', array('id'=>$templid));
1221 * creates new template items.
1222 * all items will be copied and the attribute feedback will be set to 0
1223 * and the attribute template will be set to the new templateid
1225 * @global object
1226 * @uses CONTEXT_MODULE
1227 * @uses CONTEXT_COURSE
1228 * @param object $feedback
1229 * @param string $name the name of template shown in the templatelist
1230 * @param int $ispublic 0:privat 1:public
1231 * @return boolean
1233 function feedback_save_as_template($feedback, $name, $ispublic = 0) {
1234 global $DB;
1235 $fs = get_file_storage();
1237 if (!$feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1238 return false;
1241 if (!$newtempl = feedback_create_template($feedback->course, $name, $ispublic)) {
1242 return false;
1245 //files in the template_item are in the context of the current course or
1246 //if the template is public the files are in the system context
1247 //files in the feedback_item are in the feedback_context of the feedback
1248 if ($ispublic) {
1249 $s_context = context_system::instance();
1250 } else {
1251 $s_context = context_course::instance($newtempl->course);
1253 $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1254 $f_context = context_module::instance($cm->id);
1256 //create items of this new template
1257 //depend items we are storing temporary in an mapping list array(new id => dependitem)
1258 //we also store a mapping of all items array(oldid => newid)
1259 $dependitemsmap = array();
1260 $itembackup = array();
1261 foreach ($feedbackitems as $item) {
1263 $t_item = clone($item);
1265 unset($t_item->id);
1266 $t_item->feedback = 0;
1267 $t_item->template = $newtempl->id;
1268 $t_item->id = $DB->insert_record('feedback_item', $t_item);
1269 //copy all included files to the feedback_template filearea
1270 $itemfiles = $fs->get_area_files($f_context->id,
1271 'mod_feedback',
1272 'item',
1273 $item->id,
1274 "id",
1275 false);
1276 if ($itemfiles) {
1277 foreach ($itemfiles as $ifile) {
1278 $file_record = new stdClass();
1279 $file_record->contextid = $s_context->id;
1280 $file_record->component = 'mod_feedback';
1281 $file_record->filearea = 'template';
1282 $file_record->itemid = $t_item->id;
1283 $fs->create_file_from_storedfile($file_record, $ifile);
1287 $itembackup[$item->id] = $t_item->id;
1288 if ($t_item->dependitem) {
1289 $dependitemsmap[$t_item->id] = $t_item->dependitem;
1294 //remapping the dependency
1295 foreach ($dependitemsmap as $key => $dependitem) {
1296 $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1297 $newitem->dependitem = $itembackup[$newitem->dependitem];
1298 $DB->update_record('feedback_item', $newitem);
1301 return true;
1305 * deletes all feedback_items related to the given template id
1307 * @global object
1308 * @uses CONTEXT_COURSE
1309 * @param object $template the template
1310 * @return void
1312 function feedback_delete_template($template) {
1313 global $DB;
1315 //deleting the files from the item is done by feedback_delete_item
1316 if ($t_items = $DB->get_records("feedback_item", array("template"=>$template->id))) {
1317 foreach ($t_items as $t_item) {
1318 feedback_delete_item($t_item->id, false, $template);
1321 $DB->delete_records("feedback_template", array("id"=>$template->id));
1325 * creates new feedback_item-records from template.
1326 * if $deleteold is set true so the existing items of the given feedback will be deleted
1327 * if $deleteold is set false so the new items will be appanded to the old items
1329 * @global object
1330 * @uses CONTEXT_COURSE
1331 * @uses CONTEXT_MODULE
1332 * @param object $feedback
1333 * @param int $templateid
1334 * @param boolean $deleteold
1336 function feedback_items_from_template($feedback, $templateid, $deleteold = false) {
1337 global $DB, $CFG;
1339 require_once($CFG->libdir.'/completionlib.php');
1341 $fs = get_file_storage();
1343 if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
1344 return false;
1346 //get all templateitems
1347 if (!$templitems = $DB->get_records('feedback_item', array('template'=>$templateid))) {
1348 return false;
1351 //files in the template_item are in the context of the current course
1352 //files in the feedback_item are in the feedback_context of the feedback
1353 if ($template->ispublic) {
1354 $s_context = context_system::instance();
1355 } else {
1356 $s_context = context_course::instance($feedback->course);
1358 $course = $DB->get_record('course', array('id'=>$feedback->course));
1359 $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1360 $f_context = context_module::instance($cm->id);
1362 //if deleteold then delete all old items before
1363 //get all items
1364 if ($deleteold) {
1365 if ($feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1366 //delete all items of this feedback
1367 foreach ($feedbackitems as $item) {
1368 feedback_delete_item($item->id, false);
1371 $params = array('feedback'=>$feedback->id);
1372 if ($completeds = $DB->get_records('feedback_completed', $params)) {
1373 $completion = new completion_info($course);
1374 foreach ($completeds as $completed) {
1375 // Update completion state
1376 if ($completion->is_enabled($cm) && $feedback->completionsubmit) {
1377 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1379 $DB->delete_records('feedback_completed', array('id'=>$completed->id));
1382 $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedback->id));
1384 $positionoffset = 0;
1385 } else {
1386 //if the old items are kept the new items will be appended
1387 //therefor the new position has an offset
1388 $positionoffset = $DB->count_records('feedback_item', array('feedback'=>$feedback->id));
1391 //create items of this new template
1392 //depend items we are storing temporary in an mapping list array(new id => dependitem)
1393 //we also store a mapping of all items array(oldid => newid)
1394 $dependitemsmap = array();
1395 $itembackup = array();
1396 foreach ($templitems as $t_item) {
1397 $item = clone($t_item);
1398 unset($item->id);
1399 $item->feedback = $feedback->id;
1400 $item->template = 0;
1401 $item->position = $item->position + $positionoffset;
1403 $item->id = $DB->insert_record('feedback_item', $item);
1405 //moving the files to the new item
1406 $templatefiles = $fs->get_area_files($s_context->id,
1407 'mod_feedback',
1408 'template',
1409 $t_item->id,
1410 "id",
1411 false);
1412 if ($templatefiles) {
1413 foreach ($templatefiles as $tfile) {
1414 $file_record = new stdClass();
1415 $file_record->contextid = $f_context->id;
1416 $file_record->component = 'mod_feedback';
1417 $file_record->filearea = 'item';
1418 $file_record->itemid = $item->id;
1419 $fs->create_file_from_storedfile($file_record, $tfile);
1423 $itembackup[$t_item->id] = $item->id;
1424 if ($item->dependitem) {
1425 $dependitemsmap[$item->id] = $item->dependitem;
1429 //remapping the dependency
1430 foreach ($dependitemsmap as $key => $dependitem) {
1431 $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1432 $newitem->dependitem = $itembackup[$newitem->dependitem];
1433 $DB->update_record('feedback_item', $newitem);
1438 * get the list of available templates.
1439 * if the $onlyown param is set true so only templates from own course will be served
1440 * this is important for droping templates
1442 * @global object
1443 * @param object $course
1444 * @param string $onlyownorpublic
1445 * @return array the template recordsets
1447 function feedback_get_template_list($course, $onlyownorpublic = '') {
1448 global $DB, $CFG;
1450 switch($onlyownorpublic) {
1451 case '':
1452 $templates = $DB->get_records_select('feedback_template',
1453 'course = ? OR ispublic = 1',
1454 array($course->id),
1455 'name');
1456 break;
1457 case 'own':
1458 $templates = $DB->get_records('feedback_template',
1459 array('course'=>$course->id),
1460 'name');
1461 break;
1462 case 'public':
1463 $templates = $DB->get_records('feedback_template', array('ispublic'=>1), 'name');
1464 break;
1466 return $templates;
1469 ////////////////////////////////////////////////
1470 //Handling der Items
1471 ////////////////////////////////////////////////
1472 ////////////////////////////////////////////////
1475 * load the lib.php from item-plugin-dir and returns the instance of the itemclass
1477 * @param string $typ
1478 * @return feedback_item_base the instance of itemclass
1480 function feedback_get_item_class($typ) {
1481 global $CFG;
1483 //get the class of item-typ
1484 $itemclass = 'feedback_item_'.$typ;
1485 //get the instance of item-class
1486 if (!class_exists($itemclass)) {
1487 require_once($CFG->dirroot.'/mod/feedback/item/'.$typ.'/lib.php');
1489 return new $itemclass();
1493 * load the available item plugins from given subdirectory of $CFG->dirroot
1494 * the default is "mod/feedback/item"
1496 * @global object
1497 * @param string $dir the subdir
1498 * @return array pluginnames as string
1500 function feedback_load_feedback_items($dir = 'mod/feedback/item') {
1501 global $CFG;
1502 $names = get_list_of_plugins($dir);
1503 $ret_names = array();
1505 foreach ($names as $name) {
1506 require_once($CFG->dirroot.'/'.$dir.'/'.$name.'/lib.php');
1507 if (class_exists('feedback_item_'.$name)) {
1508 $ret_names[] = $name;
1511 return $ret_names;
1515 * load the available item plugins to use as dropdown-options
1517 * @global object
1518 * @return array pluginnames as string
1520 function feedback_load_feedback_items_options() {
1521 global $CFG;
1523 $feedback_options = array("pagebreak" => get_string('add_pagebreak', 'feedback'));
1525 if (!$feedback_names = feedback_load_feedback_items('mod/feedback/item')) {
1526 return array();
1529 foreach ($feedback_names as $fn) {
1530 $feedback_options[$fn] = get_string($fn, 'feedback');
1532 asort($feedback_options);
1533 return $feedback_options;
1537 * load the available items for the depend item dropdown list shown in the edit_item form
1539 * @global object
1540 * @param object $feedback
1541 * @param object $item the item of the edit_item form
1542 * @return array all items except the item $item, labels and pagebreaks
1544 function feedback_get_depend_candidates_for_item($feedback, $item) {
1545 global $DB;
1546 //all items for dependitem
1547 $where = "feedback = ? AND typ != 'pagebreak' AND hasvalue = 1";
1548 $params = array($feedback->id);
1549 if (isset($item->id) AND $item->id) {
1550 $where .= ' AND id != ?';
1551 $params[] = $item->id;
1553 $dependitems = array(0 => get_string('choose'));
1554 $feedbackitems = $DB->get_records_select_menu('feedback_item',
1555 $where,
1556 $params,
1557 'position',
1558 'id, label');
1560 if (!$feedbackitems) {
1561 return $dependitems;
1563 //adding the choose-option
1564 foreach ($feedbackitems as $key => $val) {
1565 if (trim(strval($val)) !== '') {
1566 $dependitems[$key] = format_string($val);
1569 return $dependitems;
1573 * creates a new item-record
1575 * @deprecated since 3.1
1576 * @param object $data the data from edit_item_form
1577 * @return int the new itemid
1579 function feedback_create_item($data) {
1580 debugging('Function feedback_create_item() is deprecated because it was not used.',
1581 DEBUG_DEVELOPER);
1582 global $DB;
1584 $item = new stdClass();
1585 $item->feedback = $data->feedbackid;
1587 $item->template=0;
1588 if (isset($data->templateid)) {
1589 $item->template = intval($data->templateid);
1592 $itemname = trim($data->itemname);
1593 $item->name = ($itemname ? $data->itemname : get_string('no_itemname', 'feedback'));
1595 if (!empty($data->itemlabel)) {
1596 $item->label = trim($data->itemlabel);
1597 } else {
1598 $item->label = get_string('no_itemlabel', 'feedback');
1601 $itemobj = feedback_get_item_class($data->typ);
1602 $item->presentation = ''; //the date comes from postupdate() of the itemobj
1604 $item->hasvalue = $itemobj->get_hasvalue();
1606 $item->typ = $data->typ;
1607 $item->position = $data->position;
1609 $item->required=0;
1610 if (!empty($data->required)) {
1611 $item->required = $data->required;
1614 $item->id = $DB->insert_record('feedback_item', $item);
1616 //move all itemdata to the data
1617 $data->id = $item->id;
1618 $data->feedback = $item->feedback;
1619 $data->name = $item->name;
1620 $data->label = $item->label;
1621 $data->required = $item->required;
1622 return $itemobj->postupdate($data);
1626 * save the changes of a given item.
1628 * @global object
1629 * @param object $item
1630 * @return boolean
1632 function feedback_update_item($item) {
1633 global $DB;
1634 return $DB->update_record("feedback_item", $item);
1638 * deletes an item and also deletes all related values
1640 * @global object
1641 * @uses CONTEXT_MODULE
1642 * @param int $itemid
1643 * @param boolean $renumber should the kept items renumbered Yes/No
1644 * @param object $template if the template is given so the items are bound to it
1645 * @return void
1647 function feedback_delete_item($itemid, $renumber = true, $template = false) {
1648 global $DB;
1650 $item = $DB->get_record('feedback_item', array('id'=>$itemid));
1652 //deleting the files from the item
1653 $fs = get_file_storage();
1655 if ($template) {
1656 if ($template->ispublic) {
1657 $context = context_system::instance();
1658 } else {
1659 $context = context_course::instance($template->course);
1661 $templatefiles = $fs->get_area_files($context->id,
1662 'mod_feedback',
1663 'template',
1664 $item->id,
1665 "id",
1666 false);
1668 if ($templatefiles) {
1669 $fs->delete_area_files($context->id, 'mod_feedback', 'template', $item->id);
1671 } else {
1672 if (!$cm = get_coursemodule_from_instance('feedback', $item->feedback)) {
1673 return false;
1675 $context = context_module::instance($cm->id);
1677 $itemfiles = $fs->get_area_files($context->id,
1678 'mod_feedback',
1679 'item',
1680 $item->id,
1681 "id", false);
1683 if ($itemfiles) {
1684 $fs->delete_area_files($context->id, 'mod_feedback', 'item', $item->id);
1688 $DB->delete_records("feedback_value", array("item"=>$itemid));
1689 $DB->delete_records("feedback_valuetmp", array("item"=>$itemid));
1691 //remove all depends
1692 $DB->set_field('feedback_item', 'dependvalue', '', array('dependitem'=>$itemid));
1693 $DB->set_field('feedback_item', 'dependitem', 0, array('dependitem'=>$itemid));
1695 $DB->delete_records("feedback_item", array("id"=>$itemid));
1696 if ($renumber) {
1697 feedback_renumber_items($item->feedback);
1702 * deletes all items of the given feedbackid
1704 * @global object
1705 * @param int $feedbackid
1706 * @return void
1708 function feedback_delete_all_items($feedbackid) {
1709 global $DB, $CFG;
1710 require_once($CFG->libdir.'/completionlib.php');
1712 if (!$feedback = $DB->get_record('feedback', array('id'=>$feedbackid))) {
1713 return false;
1716 if (!$cm = get_coursemodule_from_instance('feedback', $feedback->id)) {
1717 return false;
1720 if (!$course = $DB->get_record('course', array('id'=>$feedback->course))) {
1721 return false;
1724 if (!$items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid))) {
1725 return;
1727 foreach ($items as $item) {
1728 feedback_delete_item($item->id, false);
1730 if ($completeds = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
1731 $completion = new completion_info($course);
1732 foreach ($completeds as $completed) {
1733 // Update completion state
1734 if ($completion->is_enabled($cm) && $feedback->completionsubmit) {
1735 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1737 $DB->delete_records('feedback_completed', array('id'=>$completed->id));
1741 $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedbackid));
1746 * this function toggled the item-attribute required (yes/no)
1748 * @global object
1749 * @param object $item
1750 * @return boolean
1752 function feedback_switch_item_required($item) {
1753 global $DB, $CFG;
1755 $itemobj = feedback_get_item_class($item->typ);
1757 if ($itemobj->can_switch_require()) {
1758 $new_require_val = (int)!(bool)$item->required;
1759 $params = array('id'=>$item->id);
1760 $DB->set_field('feedback_item', 'required', $new_require_val, $params);
1762 return true;
1766 * renumbers all items of the given feedbackid
1768 * @global object
1769 * @param int $feedbackid
1770 * @return void
1772 function feedback_renumber_items($feedbackid) {
1773 global $DB;
1775 $items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid), 'position');
1776 $pos = 1;
1777 if ($items) {
1778 foreach ($items as $item) {
1779 $DB->set_field('feedback_item', 'position', $pos, array('id'=>$item->id));
1780 $pos++;
1786 * this decreases the position of the given item
1788 * @global object
1789 * @param object $item
1790 * @return bool
1792 function feedback_moveup_item($item) {
1793 global $DB;
1795 if ($item->position == 1) {
1796 return true;
1799 $params = array('feedback'=>$item->feedback);
1800 if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1801 return false;
1804 $itembefore = null;
1805 foreach ($items as $i) {
1806 if ($i->id == $item->id) {
1807 if (is_null($itembefore)) {
1808 return true;
1810 $itembefore->position = $item->position;
1811 $item->position--;
1812 feedback_update_item($itembefore);
1813 feedback_update_item($item);
1814 feedback_renumber_items($item->feedback);
1815 return true;
1817 $itembefore = $i;
1819 return false;
1823 * this increased the position of the given item
1825 * @global object
1826 * @param object $item
1827 * @return bool
1829 function feedback_movedown_item($item) {
1830 global $DB;
1832 $params = array('feedback'=>$item->feedback);
1833 if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1834 return false;
1837 $movedownitem = null;
1838 foreach ($items as $i) {
1839 if (!is_null($movedownitem) AND $movedownitem->id == $item->id) {
1840 $movedownitem->position = $i->position;
1841 $i->position--;
1842 feedback_update_item($movedownitem);
1843 feedback_update_item($i);
1844 feedback_renumber_items($item->feedback);
1845 return true;
1847 $movedownitem = $i;
1849 return false;
1853 * here the position of the given item will be set to the value in $pos
1855 * @global object
1856 * @param object $moveitem
1857 * @param int $pos
1858 * @return boolean
1860 function feedback_move_item($moveitem, $pos) {
1861 global $DB;
1863 $params = array('feedback'=>$moveitem->feedback);
1864 if (!$allitems = $DB->get_records('feedback_item', $params, 'position')) {
1865 return false;
1867 if (is_array($allitems)) {
1868 $index = 1;
1869 foreach ($allitems as $item) {
1870 if ($index == $pos) {
1871 $index++;
1873 if ($item->id == $moveitem->id) {
1874 $moveitem->position = $pos;
1875 feedback_update_item($moveitem);
1876 continue;
1878 $item->position = $index;
1879 feedback_update_item($item);
1880 $index++;
1882 return true;
1884 return false;
1888 * prints the given item as a preview.
1889 * each item-class has an own print_item_preview function implemented.
1891 * @deprecated since Moodle 3.1
1892 * @global object
1893 * @param object $item the item what we want to print out
1894 * @return void
1896 function feedback_print_item_preview($item) {
1897 debugging('Function feedback_print_item_preview() is deprecated and does nothing. '
1898 . 'Items must implement complete_form_element()', DEBUG_DEVELOPER);
1902 * prints the given item in the completion form.
1903 * each item-class has an own print_item_complete function implemented.
1905 * @deprecated since Moodle 3.1
1906 * @param object $item the item what we want to print out
1907 * @param mixed $value the value
1908 * @param boolean $highlightrequire if this set true and the value are false on completing so the item will be highlighted
1909 * @return void
1911 function feedback_print_item_complete($item, $value = false, $highlightrequire = false) {
1912 debugging('Function feedback_print_item_complete() is deprecated and does nothing. '
1913 . 'Items must implement complete_form_element()', DEBUG_DEVELOPER);
1917 * prints the given item in the show entries page.
1918 * each item-class has an own print_item_show_value function implemented.
1920 * @deprecated since Moodle 3.1
1921 * @param object $item the item what we want to print out
1922 * @param mixed $value
1923 * @return void
1925 function feedback_print_item_show_value($item, $value = false) {
1926 debugging('Function feedback_print_item_show_value() is deprecated and does nothing. '
1927 . 'Items must implement complete_form_element()', DEBUG_DEVELOPER);
1931 * if the user completes a feedback and there is a pagebreak so the values are saved temporary.
1932 * the values are not saved permanently until the user click on save button
1934 * @global object
1935 * @param object $feedbackcompleted
1936 * @return object temporary saved completed-record
1938 function feedback_set_tmp_values($feedbackcompleted) {
1939 global $DB;
1940 debugging('Function feedback_set_tmp_values() is deprecated and since it is '
1941 . 'no longer used in mod_feedback', DEBUG_DEVELOPER);
1943 //first we create a completedtmp
1944 $tmpcpl = new stdClass();
1945 foreach ($feedbackcompleted as $key => $value) {
1946 $tmpcpl->{$key} = $value;
1948 unset($tmpcpl->id);
1949 $tmpcpl->timemodified = time();
1950 $tmpcpl->id = $DB->insert_record('feedback_completedtmp', $tmpcpl);
1951 //get all values of original-completed
1952 if (!$values = $DB->get_records('feedback_value', array('completed'=>$feedbackcompleted->id))) {
1953 return;
1955 foreach ($values as $value) {
1956 unset($value->id);
1957 $value->completed = $tmpcpl->id;
1958 $DB->insert_record('feedback_valuetmp', $value);
1960 return $tmpcpl;
1964 * this saves the temporary saved values permanently
1966 * @global object
1967 * @param object $feedbackcompletedtmp the temporary completed
1968 * @param object $feedbackcompleted the target completed
1969 * @return int the id of the completed
1971 function feedback_save_tmp_values($feedbackcompletedtmp, $feedbackcompleted) {
1972 global $DB;
1974 $tmpcplid = $feedbackcompletedtmp->id;
1975 if ($feedbackcompleted) {
1976 //first drop all existing values
1977 $DB->delete_records('feedback_value', array('completed'=>$feedbackcompleted->id));
1978 //update the current completed
1979 $feedbackcompleted->timemodified = time();
1980 $DB->update_record('feedback_completed', $feedbackcompleted);
1981 } else {
1982 $feedbackcompleted = clone($feedbackcompletedtmp);
1983 $feedbackcompleted->id = '';
1984 $feedbackcompleted->timemodified = time();
1985 $feedbackcompleted->id = $DB->insert_record('feedback_completed', $feedbackcompleted);
1988 $allitems = $DB->get_records('feedback_item', array('feedback' => $feedbackcompleted->feedback));
1990 //save all the new values from feedback_valuetmp
1991 //get all values of tmp-completed
1992 $params = array('completed'=>$feedbackcompletedtmp->id);
1993 $values = $DB->get_records('feedback_valuetmp', $params);
1994 foreach ($values as $value) {
1995 //check if there are depend items
1996 $item = $DB->get_record('feedback_item', array('id'=>$value->item));
1997 if ($item->dependitem > 0 && isset($allitems[$item->dependitem])) {
1998 $check = feedback_compare_item_value($tmpcplid,
1999 $allitems[$item->dependitem],
2000 $item->dependvalue,
2001 true);
2002 } else {
2003 $check = true;
2005 if ($check) {
2006 unset($value->id);
2007 $value->completed = $feedbackcompleted->id;
2008 $DB->insert_record('feedback_value', $value);
2011 //drop all the tmpvalues
2012 $DB->delete_records('feedback_valuetmp', array('completed'=>$tmpcplid));
2013 $DB->delete_records('feedback_completedtmp', array('id'=>$tmpcplid));
2015 // Trigger event for the delete action we performed.
2016 $cm = get_coursemodule_from_instance('feedback', $feedbackcompleted->feedback);
2017 $event = \mod_feedback\event\response_submitted::create_from_record($feedbackcompleted, $cm);
2018 $event->trigger();
2019 return $feedbackcompleted->id;
2024 * deletes the given temporary completed and all related temporary values
2026 * @deprecated since Moodle 3.1
2028 * @param int $tmpcplid
2029 * @return void
2031 function feedback_delete_completedtmp($tmpcplid) {
2032 global $DB;
2034 debugging('Function feedback_delete_completedtmp() is deprecated because it is no longer used',
2035 DEBUG_DEVELOPER);
2037 $DB->delete_records('feedback_valuetmp', array('completed'=>$tmpcplid));
2038 $DB->delete_records('feedback_completedtmp', array('id'=>$tmpcplid));
2041 ////////////////////////////////////////////////
2042 ////////////////////////////////////////////////
2043 ////////////////////////////////////////////////
2044 //functions to handle the pagebreaks
2045 ////////////////////////////////////////////////
2048 * this creates a pagebreak.
2049 * a pagebreak is a special kind of item
2051 * @global object
2052 * @param int $feedbackid
2053 * @return mixed false if there already is a pagebreak on last position or the id of the pagebreak-item
2055 function feedback_create_pagebreak($feedbackid) {
2056 global $DB;
2058 //check if there already is a pagebreak on the last position
2059 $lastposition = $DB->count_records('feedback_item', array('feedback'=>$feedbackid));
2060 if ($lastposition == feedback_get_last_break_position($feedbackid)) {
2061 return false;
2064 $item = new stdClass();
2065 $item->feedback = $feedbackid;
2067 $item->template=0;
2069 $item->name = '';
2071 $item->presentation = '';
2072 $item->hasvalue = 0;
2074 $item->typ = 'pagebreak';
2075 $item->position = $lastposition + 1;
2077 $item->required=0;
2079 return $DB->insert_record('feedback_item', $item);
2083 * get all positions of pagebreaks in the given feedback
2085 * @global object
2086 * @param int $feedbackid
2087 * @return array all ordered pagebreak positions
2089 function feedback_get_all_break_positions($feedbackid) {
2090 global $DB;
2092 $params = array('typ'=>'pagebreak', 'feedback'=>$feedbackid);
2093 $allbreaks = $DB->get_records_menu('feedback_item', $params, 'position', 'id, position');
2094 if (!$allbreaks) {
2095 return false;
2097 return array_values($allbreaks);
2101 * get the position of the last pagebreak
2103 * @param int $feedbackid
2104 * @return int the position of the last pagebreak
2106 function feedback_get_last_break_position($feedbackid) {
2107 if (!$allbreaks = feedback_get_all_break_positions($feedbackid)) {
2108 return false;
2110 return $allbreaks[count($allbreaks) - 1];
2114 * this returns the position where the user can continue the completing.
2116 * @deprecated since Moodle 3.1
2117 * @global object
2118 * @global object
2119 * @global object
2120 * @param int $feedbackid
2121 * @param int $courseid
2122 * @param string $guestid this id will be saved temporary and is unique
2123 * @return int the position to continue
2125 function feedback_get_page_to_continue($feedbackid, $courseid = false, $guestid = false) {
2126 global $CFG, $USER, $DB;
2128 debugging('Function feedback_get_page_to_continue() is deprecated and since it is '
2129 . 'no longer used in mod_feedback', DEBUG_DEVELOPER);
2131 //is there any break?
2133 if (!$allbreaks = feedback_get_all_break_positions($feedbackid)) {
2134 return false;
2137 $params = array();
2138 if ($courseid) {
2139 $courseselect = "AND fv.course_id = :courseid";
2140 $params['courseid'] = $courseid;
2141 } else {
2142 $courseselect = '';
2145 if ($guestid) {
2146 $userselect = "AND fc.guestid = :guestid";
2147 $usergroup = "GROUP BY fc.guestid";
2148 $params['guestid'] = $guestid;
2149 } else {
2150 $userselect = "AND fc.userid = :userid";
2151 $usergroup = "GROUP BY fc.userid";
2152 $params['userid'] = $USER->id;
2155 $sql = "SELECT MAX(fi.position)
2156 FROM {feedback_completedtmp} fc, {feedback_valuetmp} fv, {feedback_item} fi
2157 WHERE fc.id = fv.completed
2158 $userselect
2159 AND fc.feedback = :feedbackid
2160 $courseselect
2161 AND fi.id = fv.item
2162 $usergroup";
2163 $params['feedbackid'] = $feedbackid;
2165 $lastpos = $DB->get_field_sql($sql, $params);
2167 //the index of found pagebreak is the searched pagenumber
2168 foreach ($allbreaks as $pagenr => $br) {
2169 if ($lastpos < $br) {
2170 return $pagenr;
2173 return count($allbreaks);
2176 ////////////////////////////////////////////////
2177 ////////////////////////////////////////////////
2178 ////////////////////////////////////////////////
2179 //functions to handle the values
2180 ////////////////////////////////////////////////
2183 * cleans the userinput while submitting the form.
2185 * @deprecated since Moodle 3.1
2186 * @param mixed $value
2187 * @return mixed
2189 function feedback_clean_input_value($item, $value) {
2190 debugging('Function feedback_clean_input_value() is deprecated and does nothing. '
2191 . 'Items must implement complete_form_element()', DEBUG_DEVELOPER);
2195 * this saves the values of an completed.
2196 * if the param $tmp is set true so the values are saved temporary in table feedback_valuetmp.
2197 * if there is already a completed and the userid is set so the values are updated.
2198 * on all other things new value records will be created.
2200 * @deprecated since Moodle 3.1
2202 * @param int $usrid
2203 * @param boolean $tmp
2204 * @return mixed false on error or the completeid
2206 function feedback_save_values($usrid, $tmp = false) {
2207 global $DB;
2209 debugging('Function feedback_save_values() was deprecated because it did not have '.
2210 'enough arguments, was not suitable for non-temporary table and was taking '.
2211 'data directly from input', DEBUG_DEVELOPER);
2213 $completedid = optional_param('completedid', 0, PARAM_INT);
2214 $tmpstr = $tmp ? 'tmp' : '';
2215 $time = time();
2216 $timemodified = mktime(0, 0, 0, date('m', $time), date('d', $time), date('Y', $time));
2218 if ($usrid == 0) {
2219 return feedback_create_values($usrid, $timemodified, $tmp);
2221 $completed = $DB->get_record('feedback_completed'.$tmpstr, array('id'=>$completedid));
2222 if (!$completed) {
2223 return feedback_create_values($usrid, $timemodified, $tmp);
2224 } else {
2225 $completed->timemodified = $timemodified;
2226 return feedback_update_values($completed, $tmp);
2231 * this saves the values from anonymous user such as guest on the main-site
2233 * @deprecated since Moodle 3.1
2235 * @param string $guestid the unique guestidentifier
2236 * @return mixed false on error or the completeid
2238 function feedback_save_guest_values($guestid) {
2239 global $DB;
2241 debugging('Function feedback_save_guest_values() was deprecated because it did not have '.
2242 'enough arguments, was not suitable for non-temporary table and was taking '.
2243 'data directly from input', DEBUG_DEVELOPER);
2245 $completedid = optional_param('completedid', false, PARAM_INT);
2247 $timemodified = time();
2248 if (!$completed = $DB->get_record('feedback_completedtmp', array('id'=>$completedid))) {
2249 return feedback_create_values(0, $timemodified, true, $guestid);
2250 } else {
2251 $completed->timemodified = $timemodified;
2252 return feedback_update_values($completed, true);
2257 * get the value from the given item related to the given completed.
2258 * the value can come as temporary or as permanently value. the deciding is done by $tmp
2260 * @global object
2261 * @param int $completeid
2262 * @param int $itemid
2263 * @param boolean $tmp
2264 * @return mixed the value, the type depends on plugin-definition
2266 function feedback_get_item_value($completedid, $itemid, $tmp = false) {
2267 global $DB;
2269 $tmpstr = $tmp ? 'tmp' : '';
2270 $params = array('completed'=>$completedid, 'item'=>$itemid);
2271 return $DB->get_field('feedback_value'.$tmpstr, 'value', $params);
2275 * compares the value of the itemid related to the completedid with the dependvalue.
2276 * this is used if a depend item is set.
2277 * the value can come as temporary or as permanently value. the deciding is done by $tmp.
2279 * @param int $completedid
2280 * @param stdClass|int $item
2281 * @param mixed $dependvalue
2282 * @param bool $tmp
2283 * @return bool
2285 function feedback_compare_item_value($completedid, $item, $dependvalue, $tmp = false) {
2286 global $DB;
2288 if (is_int($item)) {
2289 $item = $DB->get_record('feedback_item', array('id' => $item));
2292 $dbvalue = feedback_get_item_value($completedid, $item->id, $tmp);
2294 $itemobj = feedback_get_item_class($item->typ);
2295 return $itemobj->compare_value($item, $dbvalue, $dependvalue); //true or false
2299 * this function checks the correctness of values.
2300 * the rules for this are implemented in the class of each item.
2301 * it can be the required attribute or the value self e.g. numeric.
2302 * the params first/lastitem are given to determine the visible range between pagebreaks.
2304 * @global object
2305 * @param int $firstitem the position of firstitem for checking
2306 * @param int $lastitem the position of lastitem for checking
2307 * @return boolean
2309 function feedback_check_values($firstitem, $lastitem) {
2310 debugging('Function feedback_check_values() is deprecated and does nothing. '
2311 . 'Items must implement complete_form_element()', DEBUG_DEVELOPER);
2312 return true;
2316 * this function create a complete-record and the related value-records.
2317 * depending on the $tmp (true/false) the values are saved temporary or permanently
2319 * @deprecated since Moodle 3.1
2321 * @param int $userid
2322 * @param int $timemodified
2323 * @param boolean $tmp
2324 * @param string $guestid a unique identifier to save temporary data
2325 * @return mixed false on error or the completedid
2327 function feedback_create_values($usrid, $timemodified, $tmp = false, $guestid = false) {
2328 global $DB;
2330 debugging('Function feedback_create_values() was deprecated because it did not have '.
2331 'enough arguments, was not suitable for non-temporary table and was taking '.
2332 'data directly from input', DEBUG_DEVELOPER);
2334 $tmpstr = $tmp ? 'tmp' : '';
2335 //first we create a new completed record
2336 $completed = new stdClass();
2337 $completed->feedback = $feedbackid;
2338 $completed->userid = $usrid;
2339 $completed->guestid = $guestid;
2340 $completed->timemodified = $timemodified;
2341 $completed->anonymous_response = $anonymous_response;
2343 $completedid = $DB->insert_record('feedback_completed'.$tmpstr, $completed);
2345 $completed = $DB->get_record('feedback_completed'.$tmpstr, array('id'=>$completedid));
2347 //the keys are in the form like abc_xxx
2348 //with explode we make an array with(abc, xxx) and (abc=typ und xxx=itemnr)
2350 //get the items of the feedback
2351 if (!$allitems = $DB->get_records('feedback_item', array('feedback'=>$completed->feedback))) {
2352 return false;
2354 foreach ($allitems as $item) {
2355 if (!$item->hasvalue) {
2356 continue;
2358 //get the class of item-typ
2359 $itemobj = feedback_get_item_class($item->typ);
2361 $keyname = $item->typ.'_'.$item->id;
2363 if ($item->typ === 'multichoice') {
2364 $itemvalue = optional_param_array($keyname, null, PARAM_INT);
2365 } else {
2366 $itemvalue = optional_param($keyname, null, PARAM_NOTAGS);
2369 if (is_null($itemvalue)) {
2370 continue;
2373 $value = new stdClass();
2374 $value->item = $item->id;
2375 $value->completed = $completed->id;
2376 $value->course_id = $courseid;
2378 //the kind of values can be absolutely different
2379 //so we run create_value directly by the item-class
2380 $value->value = $itemobj->create_value($itemvalue);
2381 $DB->insert_record('feedback_value'.$tmpstr, $value);
2383 return $completed->id;
2387 * this function updates a complete-record and the related value-records.
2388 * depending on the $tmp (true/false) the values are saved temporary or permanently
2390 * @global object
2391 * @param object $completed
2392 * @param boolean $tmp
2393 * @return int the completedid
2395 function feedback_update_values($completed, $tmp = false) {
2396 global $DB;
2398 debugging('Function feedback_update_values() was deprecated because it did not have '.
2399 'enough arguments, was not suitable for non-temporary table and was taking '.
2400 'data directly from input', DEBUG_DEVELOPER);
2402 $courseid = optional_param('courseid', false, PARAM_INT);
2403 $tmpstr = $tmp ? 'tmp' : '';
2405 $DB->update_record('feedback_completed'.$tmpstr, $completed);
2406 //get the values of this completed
2407 $values = $DB->get_records('feedback_value'.$tmpstr, array('completed'=>$completed->id));
2409 //get the items of the feedback
2410 if (!$allitems = $DB->get_records('feedback_item', array('feedback'=>$completed->feedback))) {
2411 return false;
2413 foreach ($allitems as $item) {
2414 if (!$item->hasvalue) {
2415 continue;
2417 //get the class of item-typ
2418 $itemobj = feedback_get_item_class($item->typ);
2420 $keyname = $item->typ.'_'.$item->id;
2422 if ($item->typ === 'multichoice') {
2423 $itemvalue = optional_param_array($keyname, null, PARAM_INT);
2424 } else {
2425 $itemvalue = optional_param($keyname, null, PARAM_NOTAGS);
2428 //is the itemvalue set (could be a subset of items because pagebreak)?
2429 if (is_null($itemvalue)) {
2430 continue;
2433 $newvalue = new stdClass();
2434 $newvalue->item = $item->id;
2435 $newvalue->completed = $completed->id;
2436 $newvalue->course_id = $courseid;
2438 //the kind of values can be absolutely different
2439 //so we run create_value directly by the item-class
2440 $newvalue->value = $itemobj->create_value($itemvalue);
2442 //check, if we have to create or update the value
2443 $exist = false;
2444 foreach ($values as $value) {
2445 if ($value->item == $newvalue->item) {
2446 $newvalue->id = $value->id;
2447 $exist = true;
2448 break;
2451 if ($exist) {
2452 $DB->update_record('feedback_value'.$tmpstr, $newvalue);
2453 } else {
2454 $DB->insert_record('feedback_value'.$tmpstr, $newvalue);
2458 return $completed->id;
2462 * get the values of an item depending on the given groupid.
2463 * if the feedback is anonymous so the values are shuffled
2465 * @global object
2466 * @global object
2467 * @param object $item
2468 * @param int $groupid
2469 * @param int $courseid
2470 * @param bool $ignore_empty if this is set true so empty values are not delivered
2471 * @return array the value-records
2473 function feedback_get_group_values($item,
2474 $groupid = false,
2475 $courseid = false,
2476 $ignore_empty = false) {
2478 global $CFG, $DB;
2480 //if the groupid is given?
2481 if (intval($groupid) > 0) {
2482 $params = array();
2483 if ($ignore_empty) {
2484 $value = $DB->sql_compare_text('fbv.value');
2485 $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2486 $params += array('emptyvalue' => '', 'zerovalue' => '0');
2487 } else {
2488 $ignore_empty_select = "";
2491 $query = 'SELECT fbv . *
2492 FROM {feedback_value} fbv, {feedback_completed} fbc, {groups_members} gm
2493 WHERE fbv.item = :itemid
2494 AND fbv.completed = fbc.id
2495 AND fbc.userid = gm.userid
2496 '.$ignore_empty_select.'
2497 AND gm.groupid = :groupid
2498 ORDER BY fbc.timemodified';
2499 $params += array('itemid' => $item->id, 'groupid' => $groupid);
2500 $values = $DB->get_records_sql($query, $params);
2502 } else {
2503 $params = array();
2504 if ($ignore_empty) {
2505 $value = $DB->sql_compare_text('value');
2506 $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2507 $params += array('emptyvalue' => '', 'zerovalue' => '0');
2508 } else {
2509 $ignore_empty_select = "";
2512 if ($courseid) {
2513 $select = "item = :itemid AND course_id = :courseid ".$ignore_empty_select;
2514 $params += array('itemid' => $item->id, 'courseid' => $courseid);
2515 $values = $DB->get_records_select('feedback_value', $select, $params);
2516 } else {
2517 $select = "item = :itemid ".$ignore_empty_select;
2518 $params += array('itemid' => $item->id);
2519 $values = $DB->get_records_select('feedback_value', $select, $params);
2522 $params = array('id'=>$item->feedback);
2523 if ($DB->get_field('feedback', 'anonymous', $params) == FEEDBACK_ANONYMOUS_YES) {
2524 if (is_array($values)) {
2525 shuffle($values);
2528 return $values;
2532 * check for multiple_submit = false.
2533 * if the feedback is global so the courseid must be given
2535 * @global object
2536 * @global object
2537 * @param int $feedbackid
2538 * @param int $courseid
2539 * @return boolean true if the feedback already is submitted otherwise false
2541 function feedback_is_already_submitted($feedbackid, $courseid = false) {
2542 global $USER, $DB;
2544 if (!isloggedin() || isguestuser()) {
2545 return false;
2548 $params = array('userid' => $USER->id, 'feedback' => $feedbackid);
2549 if ($courseid) {
2550 $params['courseid'] = $courseid;
2552 return $DB->record_exists('feedback_completed', $params);
2556 * if the completion of a feedback will be continued eg.
2557 * by pagebreak or by multiple submit so the complete must be found.
2558 * if the param $tmp is set true so all things are related to temporary completeds
2560 * @deprecated since Moodle 3.1
2561 * @param int $feedbackid
2562 * @param boolean $tmp
2563 * @param int $courseid
2564 * @param string $guestid
2565 * @return int the id of the found completed
2567 function feedback_get_current_completed($feedbackid,
2568 $tmp = false,
2569 $courseid = false,
2570 $guestid = false) {
2572 debugging('Function feedback_get_current_completed() is deprecated. Please use either '.
2573 'feedback_get_current_completed_tmp() or feedback_get_last_completed()',
2574 DEBUG_DEVELOPER);
2576 global $USER, $CFG, $DB;
2578 $tmpstr = $tmp ? 'tmp' : '';
2580 if (!$courseid) {
2581 if ($guestid) {
2582 $params = array('feedback'=>$feedbackid, 'guestid'=>$guestid);
2583 return $DB->get_record('feedback_completed'.$tmpstr, $params);
2584 } else {
2585 $params = array('feedback'=>$feedbackid, 'userid'=>$USER->id);
2586 return $DB->get_record('feedback_completed'.$tmpstr, $params);
2590 $params = array();
2592 if ($guestid) {
2593 $userselect = "AND fc.guestid = :guestid";
2594 $params['guestid'] = $guestid;
2595 } else {
2596 $userselect = "AND fc.userid = :userid";
2597 $params['userid'] = $USER->id;
2599 //if courseid is set the feedback is global.
2600 //there can be more than one completed on one feedback
2601 $sql = "SELECT DISTINCT fc.*
2602 FROM {feedback_value{$tmpstr}} fv, {feedback_completed{$tmpstr}} fc
2603 WHERE fv.course_id = :courseid
2604 AND fv.completed = fc.id
2605 $userselect
2606 AND fc.feedback = :feedbackid";
2607 $params['courseid'] = intval($courseid);
2608 $params['feedbackid'] = $feedbackid;
2610 if (!$sqlresult = $DB->get_records_sql($sql, $params)) {
2611 return false;
2613 foreach ($sqlresult as $r) {
2614 return $DB->get_record('feedback_completed'.$tmpstr, array('id'=>$r->id));
2619 * get the completeds depending on the given groupid.
2621 * @global object
2622 * @global object
2623 * @param object $feedback
2624 * @param int $groupid
2625 * @param int $courseid
2626 * @return mixed array of found completeds otherwise false
2628 function feedback_get_completeds_group($feedback, $groupid = false, $courseid = false) {
2629 global $CFG, $DB;
2631 if (intval($groupid) > 0) {
2632 $query = "SELECT fbc.*
2633 FROM {feedback_completed} fbc, {groups_members} gm
2634 WHERE fbc.feedback = ?
2635 AND gm.groupid = ?
2636 AND fbc.userid = gm.userid";
2637 if ($values = $DB->get_records_sql($query, array($feedback->id, $groupid))) {
2638 return $values;
2639 } else {
2640 return false;
2642 } else {
2643 if ($courseid) {
2644 $query = "SELECT DISTINCT fbc.*
2645 FROM {feedback_completed} fbc, {feedback_value} fbv
2646 WHERE fbc.id = fbv.completed
2647 AND fbc.feedback = ?
2648 AND fbv.course_id = ?
2649 ORDER BY random_response";
2650 if ($values = $DB->get_records_sql($query, array($feedback->id, $courseid))) {
2651 return $values;
2652 } else {
2653 return false;
2655 } else {
2656 if ($values = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
2657 return $values;
2658 } else {
2659 return false;
2666 * get the count of completeds depending on the given groupid.
2668 * @global object
2669 * @global object
2670 * @param object $feedback
2671 * @param int $groupid
2672 * @param int $courseid
2673 * @return mixed count of completeds or false
2675 function feedback_get_completeds_group_count($feedback, $groupid = false, $courseid = false) {
2676 global $CFG, $DB;
2678 if ($courseid > 0 AND !$groupid <= 0) {
2679 $sql = "SELECT id, COUNT(item) AS ci
2680 FROM {feedback_value}
2681 WHERE course_id = ?
2682 GROUP BY item ORDER BY ci DESC";
2683 if ($foundrecs = $DB->get_records_sql($sql, array($courseid))) {
2684 $foundrecs = array_values($foundrecs);
2685 return $foundrecs[0]->ci;
2687 return false;
2689 if ($values = feedback_get_completeds_group($feedback, $groupid)) {
2690 return count($values);
2691 } else {
2692 return false;
2697 * deletes all completed-recordsets from a feedback.
2698 * all related data such as values also will be deleted
2700 * @param stdClass|int $feedback
2701 * @param stdClass|cm_info $cm
2702 * @param stdClass $course
2703 * @return void
2705 function feedback_delete_all_completeds($feedback, $cm = null, $course = null) {
2706 global $DB;
2708 if (is_int($feedback)) {
2709 $feedback = $DB->get_record('feedback', array('id' => $feedback));
2712 if (!$completeds = $DB->get_records('feedback_completed', array('feedback' => $feedback->id))) {
2713 return;
2716 if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2717 return false;
2720 if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2721 return false;
2724 foreach ($completeds as $completed) {
2725 feedback_delete_completed($completed, $feedback, $cm, $course);
2730 * deletes a completed given by completedid.
2731 * all related data such values or tracking data also will be deleted
2733 * @param int|stdClass $completed
2734 * @param stdClass $feedback
2735 * @param stdClass|cm_info $cm
2736 * @param stdClass $course
2737 * @return boolean
2739 function feedback_delete_completed($completed, $feedback = null, $cm = null, $course = null) {
2740 global $DB, $CFG;
2741 require_once($CFG->libdir.'/completionlib.php');
2743 if (!isset($completed->id)) {
2744 if (!$completed = $DB->get_record('feedback_completed', array('id' => $completed))) {
2745 return false;
2749 if (!$feedback && !($feedback = $DB->get_record('feedback', array('id' => $completed->feedback)))) {
2750 return false;
2753 if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2754 return false;
2757 if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2758 return false;
2761 //first we delete all related values
2762 $DB->delete_records('feedback_value', array('completed' => $completed->id));
2764 // Update completion state
2765 $completion = new completion_info($course);
2766 if ($completion->is_enabled($cm) && $feedback->completionsubmit) {
2767 $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
2769 // Last we delete the completed-record.
2770 $return = $DB->delete_records('feedback_completed', array('id' => $completed->id));
2772 // Trigger event for the delete action we performed.
2773 $event = \mod_feedback\event\response_deleted::create_from_record($completed, $cm, $feedback);
2774 $event->trigger();
2776 return $return;
2779 ////////////////////////////////////////////////
2780 ////////////////////////////////////////////////
2781 ////////////////////////////////////////////////
2782 //functions to handle sitecourse mapping
2783 ////////////////////////////////////////////////
2786 * checks if the course and the feedback is in the table feedback_sitecourse_map.
2788 * @deprecated since 3.1
2789 * @param int $feedbackid
2790 * @param int $courseid
2791 * @return int the count of records
2793 function feedback_is_course_in_sitecourse_map($feedbackid, $courseid) {
2794 debugging('Function feedback_is_course_in_sitecourse_map() is deprecated because it was not used.',
2795 DEBUG_DEVELOPER);
2796 global $DB;
2797 $params = array('feedbackid'=>$feedbackid, 'courseid'=>$courseid);
2798 return $DB->count_records('feedback_sitecourse_map', $params);
2802 * checks if the feedback is in the table feedback_sitecourse_map.
2804 * @deprecated since 3.1
2805 * @param int $feedbackid
2806 * @return boolean
2808 function feedback_is_feedback_in_sitecourse_map($feedbackid) {
2809 debugging('Function feedback_is_feedback_in_sitecourse_map() is deprecated because it was not used.',
2810 DEBUG_DEVELOPER);
2811 global $DB;
2812 return $DB->record_exists('feedback_sitecourse_map', array('feedbackid'=>$feedbackid));
2816 * gets the feedbacks from table feedback_sitecourse_map.
2817 * this is used to show the global feedbacks on the feedback block
2818 * all feedbacks with the following criteria will be selected:<br />
2820 * 1) all feedbacks which id are listed together with the courseid in sitecoursemap and<br />
2821 * 2) all feedbacks which not are listed in sitecoursemap
2823 * @global object
2824 * @param int $courseid
2825 * @return array the feedback-records
2827 function feedback_get_feedbacks_from_sitecourse_map($courseid) {
2828 global $DB;
2830 //first get all feedbacks listed in sitecourse_map with named courseid
2831 $sql = "SELECT f.id AS id,
2832 cm.id AS cmid,
2833 f.name AS name,
2834 f.timeopen AS timeopen,
2835 f.timeclose AS timeclose
2836 FROM {feedback} f, {course_modules} cm, {feedback_sitecourse_map} sm, {modules} m
2837 WHERE f.id = cm.instance
2838 AND f.course = '".SITEID."'
2839 AND m.id = cm.module
2840 AND m.name = 'feedback'
2841 AND sm.courseid = ?
2842 AND sm.feedbackid = f.id";
2844 if (!$feedbacks1 = $DB->get_records_sql($sql, array($courseid))) {
2845 $feedbacks1 = array();
2848 //second get all feedbacks not listed in sitecourse_map
2849 $feedbacks2 = array();
2850 $sql = "SELECT f.id AS id,
2851 cm.id AS cmid,
2852 f.name AS name,
2853 f.timeopen AS timeopen,
2854 f.timeclose AS timeclose
2855 FROM {feedback} f, {course_modules} cm, {modules} m
2856 WHERE f.id = cm.instance
2857 AND f.course = '".SITEID."'
2858 AND m.id = cm.module
2859 AND m.name = 'feedback'";
2860 if (!$allfeedbacks = $DB->get_records_sql($sql)) {
2861 $allfeedbacks = array();
2863 foreach ($allfeedbacks as $a) {
2864 if (!$DB->record_exists('feedback_sitecourse_map', array('feedbackid'=>$a->id))) {
2865 $feedbacks2[] = $a;
2869 $feedbacks = array_merge($feedbacks1, $feedbacks2);
2870 $modinfo = get_fast_modinfo(SITEID);
2871 return array_filter($feedbacks, function($f) use ($modinfo) {
2872 return ($cm = $modinfo->get_cm($f->cmid)) && $cm->uservisible;
2878 * Gets the courses from table feedback_sitecourse_map
2880 * @param int $feedbackid
2881 * @return array the course-records
2883 function feedback_get_courses_from_sitecourse_map($feedbackid) {
2884 global $DB;
2886 $sql = "SELECT c.id, c.fullname, c.shortname
2887 FROM {feedback_sitecourse_map} f, {course} c
2888 WHERE c.id = f.courseid
2889 AND f.feedbackid = ?
2890 ORDER BY c.fullname";
2892 return $DB->get_records_sql($sql, array($feedbackid));
2897 * Updates the course mapping for the feedback
2899 * @param stdClass $feedback
2900 * @param array $courses array of course ids
2902 function feedback_update_sitecourse_map($feedback, $courses) {
2903 global $DB;
2904 if (empty($courses)) {
2905 $courses = array();
2907 $currentmapping = $DB->get_fieldset_select('feedback_sitecourse_map', 'courseid', 'feedbackid=?', array($feedback->id));
2908 foreach (array_diff($courses, $currentmapping) as $courseid) {
2909 $DB->insert_record('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2911 foreach (array_diff($currentmapping, $courses) as $courseid) {
2912 $DB->delete_records('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2914 // TODO MDL-53574 add events.
2918 * removes non existing courses or feedbacks from sitecourse_map.
2919 * it shouldn't be called all too often
2920 * a good place for it could be the mapcourse.php or unmapcourse.php
2922 * @deprecated since 3.1
2923 * @global object
2924 * @return void
2926 function feedback_clean_up_sitecourse_map() {
2927 global $DB;
2928 debugging('Function feedback_clean_up_sitecourse_map() is deprecated because it was not used.',
2929 DEBUG_DEVELOPER);
2931 $maps = $DB->get_records('feedback_sitecourse_map');
2932 foreach ($maps as $map) {
2933 if (!$DB->get_record('course', array('id'=>$map->courseid))) {
2934 $params = array('courseid'=>$map->courseid, 'feedbackid'=>$map->feedbackid);
2935 $DB->delete_records('feedback_sitecourse_map', $params);
2936 continue;
2938 if (!$DB->get_record('feedback', array('id'=>$map->feedbackid))) {
2939 $params = array('courseid'=>$map->courseid, 'feedbackid'=>$map->feedbackid);
2940 $DB->delete_records('feedback_sitecourse_map', $params);
2941 continue;
2947 ////////////////////////////////////////////////
2948 ////////////////////////////////////////////////
2949 ////////////////////////////////////////////////
2950 //not relatable functions
2951 ////////////////////////////////////////////////
2954 * prints the option items of a selection-input item (dropdownlist).
2955 * @deprecated since 3.1
2956 * @param int $startval the first value of the list
2957 * @param int $endval the last value of the list
2958 * @param int $selectval which item should be selected
2959 * @param int $interval the stepsize from the first to the last value
2960 * @return void
2962 function feedback_print_numeric_option_list($startval, $endval, $selectval = '', $interval = 1) {
2963 debugging('Function feedback_print_numeric_option_list() is deprecated because it was not used.',
2964 DEBUG_DEVELOPER);
2965 for ($i = $startval; $i <= $endval; $i += $interval) {
2966 if ($selectval == ($i)) {
2967 $selected = 'selected="selected"';
2968 } else {
2969 $selected = '';
2971 echo '<option '.$selected.'>'.$i.'</option>';
2976 * sends an email to the teachers of the course where the given feedback is placed.
2978 * @global object
2979 * @global object
2980 * @uses FEEDBACK_ANONYMOUS_NO
2981 * @uses FORMAT_PLAIN
2982 * @param object $cm the coursemodule-record
2983 * @param object $feedback
2984 * @param object $course
2985 * @param stdClass|int $user
2986 * @return void
2988 function feedback_send_email($cm, $feedback, $course, $user) {
2989 global $CFG, $DB;
2991 if ($feedback->email_notification == 0) { // No need to do anything
2992 return;
2995 if (is_int($user)) {
2996 $user = $DB->get_record('user', array('id' => $user));
2999 if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
3000 $groupmode = $cm->groupmode;
3001 } else {
3002 $groupmode = $course->groupmode;
3005 if ($groupmode == SEPARATEGROUPS) {
3006 $groups = $DB->get_records_sql_menu("SELECT g.name, g.id
3007 FROM {groups} g, {groups_members} m
3008 WHERE g.courseid = ?
3009 AND g.id = m.groupid
3010 AND m.userid = ?
3011 ORDER BY name ASC", array($course->id, $user->id));
3012 $groups = array_values($groups);
3014 $teachers = feedback_get_receivemail_users($cm->id, $groups);
3015 } else {
3016 $teachers = feedback_get_receivemail_users($cm->id);
3019 if ($teachers) {
3021 $strfeedbacks = get_string('modulenameplural', 'feedback');
3022 $strfeedback = get_string('modulename', 'feedback');
3024 if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
3025 $printusername = fullname($user);
3026 } else {
3027 $printusername = get_string('anonymous_user', 'feedback');
3030 foreach ($teachers as $teacher) {
3031 $info = new stdClass();
3032 $info->username = $printusername;
3033 $info->feedback = format_string($feedback->name, true);
3034 $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?'.
3035 'id='.$cm->id.'&'.
3036 'userid=' . $user->id;
3038 $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
3040 $postsubject = get_string('feedbackcompleted', 'feedback', $a);
3041 $posttext = feedback_send_email_text($info, $course);
3043 if ($teacher->mailformat == 1) {
3044 $posthtml = feedback_send_email_html($info, $course, $cm);
3045 } else {
3046 $posthtml = '';
3049 if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
3050 $eventdata = new \core\message\message();
3051 $eventdata->courseid = $course->id;
3052 $eventdata->name = 'submission';
3053 $eventdata->component = 'mod_feedback';
3054 $eventdata->userfrom = $user;
3055 $eventdata->userto = $teacher;
3056 $eventdata->subject = $postsubject;
3057 $eventdata->fullmessage = $posttext;
3058 $eventdata->fullmessageformat = FORMAT_PLAIN;
3059 $eventdata->fullmessagehtml = $posthtml;
3060 $eventdata->smallmessage = '';
3061 $eventdata->courseid = $course->id;
3062 $eventdata->contexturl = $info->url;
3063 $eventdata->contexturlname = $info->feedback;
3064 message_send($eventdata);
3065 } else {
3066 $eventdata = new \core\message\message();
3067 $eventdata->courseid = $course->id;
3068 $eventdata->name = 'submission';
3069 $eventdata->component = 'mod_feedback';
3070 $eventdata->userfrom = $teacher;
3071 $eventdata->userto = $teacher;
3072 $eventdata->subject = $postsubject;
3073 $eventdata->fullmessage = $posttext;
3074 $eventdata->fullmessageformat = FORMAT_PLAIN;
3075 $eventdata->fullmessagehtml = $posthtml;
3076 $eventdata->smallmessage = '';
3077 $eventdata->courseid = $course->id;
3078 $eventdata->contexturl = $info->url;
3079 $eventdata->contexturlname = $info->feedback;
3080 message_send($eventdata);
3087 * sends an email to the teachers of the course where the given feedback is placed.
3089 * @global object
3090 * @uses FORMAT_PLAIN
3091 * @param object $cm the coursemodule-record
3092 * @param object $feedback
3093 * @param object $course
3094 * @return void
3096 function feedback_send_email_anonym($cm, $feedback, $course) {
3097 global $CFG;
3099 if ($feedback->email_notification == 0) { // No need to do anything
3100 return;
3103 $teachers = feedback_get_receivemail_users($cm->id);
3105 if ($teachers) {
3107 $strfeedbacks = get_string('modulenameplural', 'feedback');
3108 $strfeedback = get_string('modulename', 'feedback');
3109 $printusername = get_string('anonymous_user', 'feedback');
3111 foreach ($teachers as $teacher) {
3112 $info = new stdClass();
3113 $info->username = $printusername;
3114 $info->feedback = format_string($feedback->name, true);
3115 $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?id=' . $cm->id;
3117 $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
3119 $postsubject = get_string('feedbackcompleted', 'feedback', $a);
3120 $posttext = feedback_send_email_text($info, $course);
3122 if ($teacher->mailformat == 1) {
3123 $posthtml = feedback_send_email_html($info, $course, $cm);
3124 } else {
3125 $posthtml = '';
3128 $eventdata = new \core\message\message();
3129 $eventdata->courseid = $course->id;
3130 $eventdata->name = 'submission';
3131 $eventdata->component = 'mod_feedback';
3132 $eventdata->userfrom = $teacher;
3133 $eventdata->userto = $teacher;
3134 $eventdata->subject = $postsubject;
3135 $eventdata->fullmessage = $posttext;
3136 $eventdata->fullmessageformat = FORMAT_PLAIN;
3137 $eventdata->fullmessagehtml = $posthtml;
3138 $eventdata->smallmessage = '';
3139 $eventdata->courseid = $course->id;
3140 $eventdata->contexturl = $info->url;
3141 $eventdata->contexturlname = $info->feedback;
3142 message_send($eventdata);
3148 * send the text-part of the email
3150 * @param object $info includes some infos about the feedback you want to send
3151 * @param object $course
3152 * @return string the text you want to post
3154 function feedback_send_email_text($info, $course) {
3155 $coursecontext = context_course::instance($course->id);
3156 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
3157 $posttext = $courseshortname.' -> '.get_string('modulenameplural', 'feedback').' -> '.
3158 $info->feedback."\n";
3159 $posttext .= '---------------------------------------------------------------------'."\n";
3160 $posttext .= get_string("emailteachermail", "feedback", $info)."\n";
3161 $posttext .= '---------------------------------------------------------------------'."\n";
3162 return $posttext;
3167 * send the html-part of the email
3169 * @global object
3170 * @param object $info includes some infos about the feedback you want to send
3171 * @param object $course
3172 * @return string the text you want to post
3174 function feedback_send_email_html($info, $course, $cm) {
3175 global $CFG;
3176 $coursecontext = context_course::instance($course->id);
3177 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
3178 $course_url = $CFG->wwwroot.'/course/view.php?id='.$course->id;
3179 $feedback_all_url = $CFG->wwwroot.'/mod/feedback/index.php?id='.$course->id;
3180 $feedback_url = $CFG->wwwroot.'/mod/feedback/view.php?id='.$cm->id;
3182 $posthtml = '<p><font face="sans-serif">'.
3183 '<a href="'.$course_url.'">'.$courseshortname.'</a> ->'.
3184 '<a href="'.$feedback_all_url.'">'.get_string('modulenameplural', 'feedback').'</a> ->'.
3185 '<a href="'.$feedback_url.'">'.$info->feedback.'</a></font></p>';
3186 $posthtml .= '<hr /><font face="sans-serif">';
3187 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'feedback', $info).'</p>';
3188 $posthtml .= '</font><hr />';
3189 return $posthtml;
3193 * @param string $url
3194 * @return string
3196 function feedback_encode_target_url($url) {
3197 if (strpos($url, '?')) {
3198 list($part1, $part2) = explode('?', $url, 2); //maximal 2 parts
3199 return $part1 . '?' . htmlentities($part2);
3200 } else {
3201 return $url;
3206 * Adds module specific settings to the settings block
3208 * @param settings_navigation $settings The settings navigation object
3209 * @param navigation_node $feedbacknode The node to add module settings to
3211 function feedback_extend_settings_navigation(settings_navigation $settings,
3212 navigation_node $feedbacknode) {
3214 global $PAGE;
3216 if (!$context = context_module::instance($PAGE->cm->id, IGNORE_MISSING)) {
3217 print_error('badcontext');
3220 if (has_capability('mod/feedback:edititems', $context)) {
3221 $questionnode = $feedbacknode->add(get_string('questions', 'feedback'));
3223 $questionnode->add(get_string('edit_items', 'feedback'),
3224 new moodle_url('/mod/feedback/edit.php',
3225 array('id' => $PAGE->cm->id,
3226 'do_show' => 'edit')));
3228 $questionnode->add(get_string('export_questions', 'feedback'),
3229 new moodle_url('/mod/feedback/export.php',
3230 array('id' => $PAGE->cm->id,
3231 'action' => 'exportfile')));
3233 $questionnode->add(get_string('import_questions', 'feedback'),
3234 new moodle_url('/mod/feedback/import.php',
3235 array('id' => $PAGE->cm->id)));
3237 $questionnode->add(get_string('templates', 'feedback'),
3238 new moodle_url('/mod/feedback/edit.php',
3239 array('id' => $PAGE->cm->id,
3240 'do_show' => 'templates')));
3243 if (has_capability('mod/feedback:mapcourse', $context) && $PAGE->course->id == SITEID) {
3244 $feedbacknode->add(get_string('mappedcourses', 'feedback'),
3245 new moodle_url('/mod/feedback/mapcourse.php',
3246 array('id' => $PAGE->cm->id)));
3249 if (has_capability('mod/feedback:viewreports', $context)) {
3250 $feedback = $PAGE->activityrecord;
3251 if ($feedback->course == SITEID) {
3252 $feedbacknode->add(get_string('analysis', 'feedback'),
3253 new moodle_url('/mod/feedback/analysis_course.php',
3254 array('id' => $PAGE->cm->id)));
3255 } else {
3256 $feedbacknode->add(get_string('analysis', 'feedback'),
3257 new moodle_url('/mod/feedback/analysis.php',
3258 array('id' => $PAGE->cm->id)));
3261 $feedbacknode->add(get_string('show_entries', 'feedback'),
3262 new moodle_url('/mod/feedback/show_entries.php',
3263 array('id' => $PAGE->cm->id)));
3265 if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO AND $feedback->course != SITEID) {
3266 $feedbacknode->add(get_string('show_nonrespondents', 'feedback'),
3267 new moodle_url('/mod/feedback/show_nonrespondents.php',
3268 array('id' => $PAGE->cm->id)));
3273 function feedback_init_feedback_session() {
3274 //initialize the feedback-Session - not nice at all!!
3275 global $SESSION;
3276 if (!empty($SESSION)) {
3277 if (!isset($SESSION->feedback) OR !is_object($SESSION->feedback)) {
3278 $SESSION->feedback = new stdClass();
3284 * Return a list of page types
3285 * @param string $pagetype current page type
3286 * @param stdClass $parentcontext Block's parent context
3287 * @param stdClass $currentcontext Current context of block
3289 function feedback_page_type_list($pagetype, $parentcontext, $currentcontext) {
3290 $module_pagetype = array('mod-feedback-*'=>get_string('page-mod-feedback-x', 'feedback'));
3291 return $module_pagetype;
3295 * Move save the items of the given $feedback in the order of $itemlist.
3296 * @param string $itemlist a comma separated list with item ids
3297 * @param stdClass $feedback
3298 * @return bool true if success
3300 function feedback_ajax_saveitemorder($itemlist, $feedback) {
3301 global $DB;
3303 $result = true;
3304 $position = 0;
3305 foreach ($itemlist as $itemid) {
3306 $position++;
3307 $result = $result && $DB->set_field('feedback_item',
3308 'position',
3309 $position,
3310 array('id'=>$itemid, 'feedback'=>$feedback->id));
3312 return $result;
3316 * Checks if current user is able to view feedback on this course.
3318 * @param stdClass $feedback
3319 * @param context_module $context
3320 * @param int $courseid
3321 * @return bool
3323 function feedback_can_view_analysis($feedback, $context, $courseid = false) {
3324 if (has_capability('mod/feedback:viewreports', $context)) {
3325 return true;
3328 if (intval($feedback->publish_stats) != 1 ||
3329 !has_capability('mod/feedback:viewanalysepage', $context)) {
3330 return false;
3333 if (!isloggedin() || isguestuser()) {
3334 // There is no tracking for the guests, assume that they can view analysis if condition above is satisfied.
3335 return $feedback->course == SITEID;
3338 return feedback_is_already_submitted($feedback->id, $courseid);
3342 * Get icon mapping for font-awesome.
3344 function mod_feedback_get_fontawesome_icon_map() {
3345 return [
3346 'mod_feedback:required' => 'fa-exclamation-circle',
3347 'mod_feedback:notrequired' => 'fa-question-circle-o',
3352 * Check if the module has any update that affects the current user since a given time.
3354 * @param cm_info $cm course module data
3355 * @param int $from the time to check updates from
3356 * @param array $filter if we need to check only specific updates
3357 * @return stdClass an object with the different type of areas indicating if they were updated or not
3358 * @since Moodle 3.3
3360 function feedback_check_updates_since(cm_info $cm, $from, $filter = array()) {
3361 global $DB, $USER, $CFG;
3363 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
3365 // Check for new attempts.
3366 $updates->attemptsfinished = (object) array('updated' => false);
3367 $updates->attemptsunfinished = (object) array('updated' => false);
3368 $select = 'feedback = ? AND userid = ? AND timemodified > ?';
3369 $params = array($cm->instance, $USER->id, $from);
3371 $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
3372 if (!empty($attemptsfinished)) {
3373 $updates->attemptsfinished->updated = true;
3374 $updates->attemptsfinished->itemids = array_keys($attemptsfinished);
3376 $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
3377 if (!empty($attemptsunfinished)) {
3378 $updates->attemptsunfinished->updated = true;
3379 $updates->attemptsunfinished->itemids = array_keys($attemptsunfinished);
3382 // Now, teachers should see other students updates.
3383 if (has_capability('mod/feedback:viewreports', $cm->context)) {
3384 $select = 'feedback = ? AND timemodified > ?';
3385 $params = array($cm->instance, $from);
3387 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
3388 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
3389 if (empty($groupusers)) {
3390 return $updates;
3392 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
3393 $select .= ' AND userid ' . $insql;
3394 $params = array_merge($params, $inparams);
3397 $updates->userattemptsfinished = (object) array('updated' => false);
3398 $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
3399 if (!empty($attemptsfinished)) {
3400 $updates->userattemptsfinished->updated = true;
3401 $updates->userattemptsfinished->itemids = array_keys($attemptsfinished);
3404 $updates->userattemptsunfinished = (object) array('updated' => false);
3405 $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
3406 if (!empty($attemptsunfinished)) {
3407 $updates->userattemptsunfinished->updated = true;
3408 $updates->userattemptsunfinished->itemids = array_keys($attemptsunfinished);
3412 return $updates;
3416 * Handles creating actions for events.
3418 * @param calendar_event $event
3419 * @param \core_calendar\action_factory $factory
3420 * @return \core_calendar\local\event\value_objects\action|\core_calendar\local\interfaces\action_interface|null
3422 function mod_feedback_core_calendar_provide_event_action(calendar_event $event,
3423 \core_calendar\action_factory $factory) {
3424 global $DB;
3426 $cm = get_fast_modinfo($event->courseid)->instances['feedback'][$event->instance];
3427 $feedback = $DB->get_record('feedback', ['id' => $event->instance], 'id, timeopen, timeclose');
3429 $now = time();
3430 if ($feedback->timeopen && $feedback->timeclose) {
3431 $actionable = ($now >= $feedback->timeopen) && ($now <= $feedback->timeclose);
3432 } else if ($feedback->timeclose) {
3433 $actionable = $now < $feedback->timeclose;
3434 } else if ($feedback->timeopen) {
3435 $actionable = $now >= $feedback->timeopen;
3436 } else {
3437 $actionable = true;
3440 return $factory->create_instance(
3441 get_string('answerquestions', 'feedback'),
3442 new \moodle_url('/mod/feedback/view.php', ['id' => $cm->id]),
3444 $actionable